xref: /freebsd/contrib/llvm-project/llvm/lib/IR/AsmWriter.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
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"
425f757f3fSDimitry 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.
skipMetadataWrapper(const Value * V)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 
orderValue(const Value * V,OrderMap & OM)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 
orderModule(const Module * M)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>
predictValueUseListOrder(const Value * V,unsigned ID,const OrderMap & OM)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 
predictUseListOrder(const Module * M)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 
getModuleFromVal(const Value * V)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 
getModuleFromDPI(const DbgMarker * Marker)289*0fca6ea1SDimitry Andric static const Module *getModuleFromDPI(const DbgMarker *Marker) {
2905f757f3fSDimitry Andric   const Function *M =
2915f757f3fSDimitry Andric       Marker->getParent() ? Marker->getParent()->getParent() : nullptr;
2925f757f3fSDimitry Andric   return M ? M->getParent() : nullptr;
2935f757f3fSDimitry Andric }
2945f757f3fSDimitry Andric 
getModuleFromDPI(const DbgRecord * DR)295*0fca6ea1SDimitry Andric static const Module *getModuleFromDPI(const DbgRecord *DR) {
296*0fca6ea1SDimitry Andric   return DR->getMarker() ? getModuleFromDPI(DR->getMarker()) : nullptr;
2975f757f3fSDimitry Andric }
2985f757f3fSDimitry Andric 
PrintCallingConv(unsigned cc,raw_ostream & Out)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;
307*0fca6ea1SDimitry Andric   case CallingConv::PreserveNone:  Out << "preserve_nonecc"; break;
3080b57cec5SDimitry Andric   case CallingConv::CXX_FAST_TLS:  Out << "cxx_fast_tlscc"; break;
3090b57cec5SDimitry Andric   case CallingConv::GHC:           Out << "ghccc"; break;
3108bcb0991SDimitry Andric   case CallingConv::Tail:          Out << "tailcc"; break;
3115f757f3fSDimitry Andric   case CallingConv::GRAAL:         Out << "graalcc"; break;
312480093f4SDimitry Andric   case CallingConv::CFGuard_Check: Out << "cfguard_checkcc"; break;
3130b57cec5SDimitry Andric   case CallingConv::X86_StdCall:   Out << "x86_stdcallcc"; break;
3140b57cec5SDimitry Andric   case CallingConv::X86_FastCall:  Out << "x86_fastcallcc"; break;
3150b57cec5SDimitry Andric   case CallingConv::X86_ThisCall:  Out << "x86_thiscallcc"; break;
3160b57cec5SDimitry Andric   case CallingConv::X86_RegCall:   Out << "x86_regcallcc"; break;
3170b57cec5SDimitry Andric   case CallingConv::X86_VectorCall:Out << "x86_vectorcallcc"; break;
3180b57cec5SDimitry Andric   case CallingConv::Intel_OCL_BI:  Out << "intel_ocl_bicc"; break;
3190b57cec5SDimitry Andric   case CallingConv::ARM_APCS:      Out << "arm_apcscc"; break;
3200b57cec5SDimitry Andric   case CallingConv::ARM_AAPCS:     Out << "arm_aapcscc"; break;
3210b57cec5SDimitry Andric   case CallingConv::ARM_AAPCS_VFP: Out << "arm_aapcs_vfpcc"; break;
3220b57cec5SDimitry Andric   case CallingConv::AArch64_VectorCall: Out << "aarch64_vector_pcs"; break;
323480093f4SDimitry Andric   case CallingConv::AArch64_SVE_VectorCall:
324480093f4SDimitry Andric     Out << "aarch64_sve_vector_pcs";
325480093f4SDimitry Andric     break;
326bdd1243dSDimitry Andric   case CallingConv::AArch64_SME_ABI_Support_Routines_PreserveMost_From_X0:
327bdd1243dSDimitry Andric     Out << "aarch64_sme_preservemost_from_x0";
328bdd1243dSDimitry Andric     break;
329*0fca6ea1SDimitry Andric   case CallingConv::AArch64_SME_ABI_Support_Routines_PreserveMost_From_X1:
330*0fca6ea1SDimitry Andric     Out << "aarch64_sme_preservemost_from_x1";
331*0fca6ea1SDimitry Andric     break;
332bdd1243dSDimitry Andric   case CallingConv::AArch64_SME_ABI_Support_Routines_PreserveMost_From_X2:
333bdd1243dSDimitry Andric     Out << "aarch64_sme_preservemost_from_x2";
334bdd1243dSDimitry Andric     break;
3350b57cec5SDimitry Andric   case CallingConv::MSP430_INTR:   Out << "msp430_intrcc"; break;
3360b57cec5SDimitry Andric   case CallingConv::AVR_INTR:      Out << "avr_intrcc "; break;
3370b57cec5SDimitry Andric   case CallingConv::AVR_SIGNAL:    Out << "avr_signalcc "; break;
3380b57cec5SDimitry Andric   case CallingConv::PTX_Kernel:    Out << "ptx_kernel"; break;
3390b57cec5SDimitry Andric   case CallingConv::PTX_Device:    Out << "ptx_device"; break;
3400b57cec5SDimitry Andric   case CallingConv::X86_64_SysV:   Out << "x86_64_sysvcc"; break;
3410b57cec5SDimitry Andric   case CallingConv::Win64:         Out << "win64cc"; break;
3420b57cec5SDimitry Andric   case CallingConv::SPIR_FUNC:     Out << "spir_func"; break;
3430b57cec5SDimitry Andric   case CallingConv::SPIR_KERNEL:   Out << "spir_kernel"; break;
3440b57cec5SDimitry Andric   case CallingConv::Swift:         Out << "swiftcc"; break;
345fe6060f1SDimitry Andric   case CallingConv::SwiftTail:     Out << "swifttailcc"; break;
3460b57cec5SDimitry Andric   case CallingConv::X86_INTR:      Out << "x86_intrcc"; break;
34706c3fb27SDimitry Andric   case CallingConv::DUMMY_HHVM:
34806c3fb27SDimitry Andric     Out << "hhvmcc";
34906c3fb27SDimitry Andric     break;
35006c3fb27SDimitry Andric   case CallingConv::DUMMY_HHVM_C:
35106c3fb27SDimitry Andric     Out << "hhvm_ccc";
35206c3fb27SDimitry Andric     break;
3530b57cec5SDimitry Andric   case CallingConv::AMDGPU_VS:     Out << "amdgpu_vs"; break;
3540b57cec5SDimitry Andric   case CallingConv::AMDGPU_LS:     Out << "amdgpu_ls"; break;
3550b57cec5SDimitry Andric   case CallingConv::AMDGPU_HS:     Out << "amdgpu_hs"; break;
3560b57cec5SDimitry Andric   case CallingConv::AMDGPU_ES:     Out << "amdgpu_es"; break;
3570b57cec5SDimitry Andric   case CallingConv::AMDGPU_GS:     Out << "amdgpu_gs"; break;
3580b57cec5SDimitry Andric   case CallingConv::AMDGPU_PS:     Out << "amdgpu_ps"; break;
3590b57cec5SDimitry Andric   case CallingConv::AMDGPU_CS:     Out << "amdgpu_cs"; break;
36006c3fb27SDimitry Andric   case CallingConv::AMDGPU_CS_Chain:
36106c3fb27SDimitry Andric     Out << "amdgpu_cs_chain";
36206c3fb27SDimitry Andric     break;
36306c3fb27SDimitry Andric   case CallingConv::AMDGPU_CS_ChainPreserve:
36406c3fb27SDimitry Andric     Out << "amdgpu_cs_chain_preserve";
36506c3fb27SDimitry Andric     break;
3660b57cec5SDimitry Andric   case CallingConv::AMDGPU_KERNEL: Out << "amdgpu_kernel"; break;
367e8d8bef9SDimitry Andric   case CallingConv::AMDGPU_Gfx:    Out << "amdgpu_gfx"; break;
3685f757f3fSDimitry Andric   case CallingConv::M68k_RTD:      Out << "m68k_rtdcc"; break;
369*0fca6ea1SDimitry Andric   case CallingConv::RISCV_VectorCall:
370*0fca6ea1SDimitry Andric     Out << "riscv_vector_cc";
371*0fca6ea1SDimitry Andric     break;
3720b57cec5SDimitry Andric   }
3730b57cec5SDimitry Andric }
3740b57cec5SDimitry Andric 
3750b57cec5SDimitry Andric enum PrefixType {
3760b57cec5SDimitry Andric   GlobalPrefix,
3770b57cec5SDimitry Andric   ComdatPrefix,
3780b57cec5SDimitry Andric   LabelPrefix,
3790b57cec5SDimitry Andric   LocalPrefix,
3800b57cec5SDimitry Andric   NoPrefix
3810b57cec5SDimitry Andric };
3820b57cec5SDimitry Andric 
printLLVMNameWithoutPrefix(raw_ostream & OS,StringRef Name)3830b57cec5SDimitry Andric void llvm::printLLVMNameWithoutPrefix(raw_ostream &OS, StringRef Name) {
3840b57cec5SDimitry Andric   assert(!Name.empty() && "Cannot get empty name!");
3850b57cec5SDimitry Andric 
3860b57cec5SDimitry Andric   // Scan the name to see if it needs quotes first.
3870b57cec5SDimitry Andric   bool NeedsQuotes = isdigit(static_cast<unsigned char>(Name[0]));
3880b57cec5SDimitry Andric   if (!NeedsQuotes) {
3894824e7fdSDimitry Andric     for (unsigned char C : Name) {
3900b57cec5SDimitry Andric       // By making this unsigned, the value passed in to isalnum will always be
3910b57cec5SDimitry Andric       // in the range 0-255.  This is important when building with MSVC because
3920b57cec5SDimitry Andric       // its implementation will assert.  This situation can arise when dealing
3930b57cec5SDimitry Andric       // with UTF-8 multibyte characters.
3940b57cec5SDimitry Andric       if (!isalnum(static_cast<unsigned char>(C)) && C != '-' && C != '.' &&
3950b57cec5SDimitry Andric           C != '_') {
3960b57cec5SDimitry Andric         NeedsQuotes = true;
3970b57cec5SDimitry Andric         break;
3980b57cec5SDimitry Andric       }
3990b57cec5SDimitry Andric     }
4000b57cec5SDimitry Andric   }
4010b57cec5SDimitry Andric 
4020b57cec5SDimitry Andric   // If we didn't need any quotes, just write out the name in one blast.
4030b57cec5SDimitry Andric   if (!NeedsQuotes) {
4040b57cec5SDimitry Andric     OS << Name;
4050b57cec5SDimitry Andric     return;
4060b57cec5SDimitry Andric   }
4070b57cec5SDimitry Andric 
4080b57cec5SDimitry Andric   // Okay, we need quotes.  Output the quotes and escape any scary characters as
4090b57cec5SDimitry Andric   // needed.
4100b57cec5SDimitry Andric   OS << '"';
4110b57cec5SDimitry Andric   printEscapedString(Name, OS);
4120b57cec5SDimitry Andric   OS << '"';
4130b57cec5SDimitry Andric }
4140b57cec5SDimitry Andric 
4150b57cec5SDimitry Andric /// Turn the specified name into an 'LLVM name', which is either prefixed with %
4160b57cec5SDimitry Andric /// (if the string only contains simple characters) or is surrounded with ""'s
4170b57cec5SDimitry Andric /// (if it has special chars in it). Print it out.
PrintLLVMName(raw_ostream & OS,StringRef Name,PrefixType Prefix)4180b57cec5SDimitry Andric static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) {
4190b57cec5SDimitry Andric   switch (Prefix) {
4200b57cec5SDimitry Andric   case NoPrefix:
4210b57cec5SDimitry Andric     break;
4220b57cec5SDimitry Andric   case GlobalPrefix:
4230b57cec5SDimitry Andric     OS << '@';
4240b57cec5SDimitry Andric     break;
4250b57cec5SDimitry Andric   case ComdatPrefix:
4260b57cec5SDimitry Andric     OS << '$';
4270b57cec5SDimitry Andric     break;
4280b57cec5SDimitry Andric   case LabelPrefix:
4290b57cec5SDimitry Andric     break;
4300b57cec5SDimitry Andric   case LocalPrefix:
4310b57cec5SDimitry Andric     OS << '%';
4320b57cec5SDimitry Andric     break;
4330b57cec5SDimitry Andric   }
4340b57cec5SDimitry Andric   printLLVMNameWithoutPrefix(OS, Name);
4350b57cec5SDimitry Andric }
4360b57cec5SDimitry Andric 
4370b57cec5SDimitry Andric /// Turn the specified name into an 'LLVM name', which is either prefixed with %
4380b57cec5SDimitry Andric /// (if the string only contains simple characters) or is surrounded with ""'s
4390b57cec5SDimitry Andric /// (if it has special chars in it). Print it out.
PrintLLVMName(raw_ostream & OS,const Value * V)4400b57cec5SDimitry Andric static void PrintLLVMName(raw_ostream &OS, const Value *V) {
4410b57cec5SDimitry Andric   PrintLLVMName(OS, V->getName(),
4420b57cec5SDimitry Andric                 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
4430b57cec5SDimitry Andric }
4440b57cec5SDimitry Andric 
PrintShuffleMask(raw_ostream & Out,Type * Ty,ArrayRef<int> Mask)4455ffd83dbSDimitry Andric static void PrintShuffleMask(raw_ostream &Out, Type *Ty, ArrayRef<int> Mask) {
4465ffd83dbSDimitry Andric   Out << ", <";
4475ffd83dbSDimitry Andric   if (isa<ScalableVectorType>(Ty))
4485ffd83dbSDimitry Andric     Out << "vscale x ";
4495ffd83dbSDimitry Andric   Out << Mask.size() << " x i32> ";
4505ffd83dbSDimitry Andric   bool FirstElt = true;
4515ffd83dbSDimitry Andric   if (all_of(Mask, [](int Elt) { return Elt == 0; })) {
4525ffd83dbSDimitry Andric     Out << "zeroinitializer";
45306c3fb27SDimitry Andric   } else if (all_of(Mask, [](int Elt) { return Elt == PoisonMaskElem; })) {
45406c3fb27SDimitry Andric     Out << "poison";
4555ffd83dbSDimitry Andric   } else {
4565ffd83dbSDimitry Andric     Out << "<";
4575ffd83dbSDimitry Andric     for (int Elt : Mask) {
4585ffd83dbSDimitry Andric       if (FirstElt)
4595ffd83dbSDimitry Andric         FirstElt = false;
4605ffd83dbSDimitry Andric       else
4615ffd83dbSDimitry Andric         Out << ", ";
4625ffd83dbSDimitry Andric       Out << "i32 ";
46306c3fb27SDimitry Andric       if (Elt == PoisonMaskElem)
46406c3fb27SDimitry Andric         Out << "poison";
4655ffd83dbSDimitry Andric       else
4665ffd83dbSDimitry Andric         Out << Elt;
4675ffd83dbSDimitry Andric     }
4685ffd83dbSDimitry Andric     Out << ">";
4695ffd83dbSDimitry Andric   }
4705ffd83dbSDimitry Andric }
4715ffd83dbSDimitry Andric 
4720b57cec5SDimitry Andric namespace {
4730b57cec5SDimitry Andric 
4740b57cec5SDimitry Andric class TypePrinting {
4750b57cec5SDimitry Andric public:
TypePrinting(const Module * M=nullptr)4760b57cec5SDimitry Andric   TypePrinting(const Module *M = nullptr) : DeferredM(M) {}
4770b57cec5SDimitry Andric 
4780b57cec5SDimitry Andric   TypePrinting(const TypePrinting &) = delete;
4790b57cec5SDimitry Andric   TypePrinting &operator=(const TypePrinting &) = delete;
4800b57cec5SDimitry Andric 
4810b57cec5SDimitry Andric   /// The named types that are used by the current module.
4820b57cec5SDimitry Andric   TypeFinder &getNamedTypes();
4830b57cec5SDimitry Andric 
4840b57cec5SDimitry Andric   /// The numbered types, number to type mapping.
4850b57cec5SDimitry Andric   std::vector<StructType *> &getNumberedTypes();
4860b57cec5SDimitry Andric 
4870b57cec5SDimitry Andric   bool empty();
4880b57cec5SDimitry Andric 
4890b57cec5SDimitry Andric   void print(Type *Ty, raw_ostream &OS);
4900b57cec5SDimitry Andric 
4910b57cec5SDimitry Andric   void printStructBody(StructType *Ty, raw_ostream &OS);
4920b57cec5SDimitry Andric 
4930b57cec5SDimitry Andric private:
4940b57cec5SDimitry Andric   void incorporateTypes();
4950b57cec5SDimitry Andric 
4960b57cec5SDimitry Andric   /// A module to process lazily when needed. Set to nullptr as soon as used.
4970b57cec5SDimitry Andric   const Module *DeferredM;
4980b57cec5SDimitry Andric 
4990b57cec5SDimitry Andric   TypeFinder NamedTypes;
5000b57cec5SDimitry Andric 
5010b57cec5SDimitry Andric   // The numbered types, along with their value.
5020b57cec5SDimitry Andric   DenseMap<StructType *, unsigned> Type2Number;
5030b57cec5SDimitry Andric 
5040b57cec5SDimitry Andric   std::vector<StructType *> NumberedTypes;
5050b57cec5SDimitry Andric };
5060b57cec5SDimitry Andric 
5070b57cec5SDimitry Andric } // end anonymous namespace
5080b57cec5SDimitry Andric 
getNamedTypes()5090b57cec5SDimitry Andric TypeFinder &TypePrinting::getNamedTypes() {
5100b57cec5SDimitry Andric   incorporateTypes();
5110b57cec5SDimitry Andric   return NamedTypes;
5120b57cec5SDimitry Andric }
5130b57cec5SDimitry Andric 
getNumberedTypes()5140b57cec5SDimitry Andric std::vector<StructType *> &TypePrinting::getNumberedTypes() {
5150b57cec5SDimitry Andric   incorporateTypes();
5160b57cec5SDimitry Andric 
5170b57cec5SDimitry Andric   // We know all the numbers that each type is used and we know that it is a
5180b57cec5SDimitry Andric   // dense assignment. Convert the map to an index table, if it's not done
5190b57cec5SDimitry Andric   // already (judging from the sizes):
5200b57cec5SDimitry Andric   if (NumberedTypes.size() == Type2Number.size())
5210b57cec5SDimitry Andric     return NumberedTypes;
5220b57cec5SDimitry Andric 
5230b57cec5SDimitry Andric   NumberedTypes.resize(Type2Number.size());
5240b57cec5SDimitry Andric   for (const auto &P : Type2Number) {
5250b57cec5SDimitry Andric     assert(P.second < NumberedTypes.size() && "Didn't get a dense numbering?");
5260b57cec5SDimitry Andric     assert(!NumberedTypes[P.second] && "Didn't get a unique numbering?");
5270b57cec5SDimitry Andric     NumberedTypes[P.second] = P.first;
5280b57cec5SDimitry Andric   }
5290b57cec5SDimitry Andric   return NumberedTypes;
5300b57cec5SDimitry Andric }
5310b57cec5SDimitry Andric 
empty()5320b57cec5SDimitry Andric bool TypePrinting::empty() {
5330b57cec5SDimitry Andric   incorporateTypes();
5340b57cec5SDimitry Andric   return NamedTypes.empty() && Type2Number.empty();
5350b57cec5SDimitry Andric }
5360b57cec5SDimitry Andric 
incorporateTypes()5370b57cec5SDimitry Andric void TypePrinting::incorporateTypes() {
5380b57cec5SDimitry Andric   if (!DeferredM)
5390b57cec5SDimitry Andric     return;
5400b57cec5SDimitry Andric 
5410b57cec5SDimitry Andric   NamedTypes.run(*DeferredM, false);
5420b57cec5SDimitry Andric   DeferredM = nullptr;
5430b57cec5SDimitry Andric 
5440b57cec5SDimitry Andric   // The list of struct types we got back includes all the struct types, split
5450b57cec5SDimitry Andric   // the unnamed ones out to a numbering and remove the anonymous structs.
5460b57cec5SDimitry Andric   unsigned NextNumber = 0;
5470b57cec5SDimitry Andric 
5480eae32dcSDimitry Andric   std::vector<StructType *>::iterator NextToUse = NamedTypes.begin();
5490eae32dcSDimitry Andric   for (StructType *STy : NamedTypes) {
5500b57cec5SDimitry Andric     // Ignore anonymous types.
5510b57cec5SDimitry Andric     if (STy->isLiteral())
5520b57cec5SDimitry Andric       continue;
5530b57cec5SDimitry Andric 
5540b57cec5SDimitry Andric     if (STy->getName().empty())
5550b57cec5SDimitry Andric       Type2Number[STy] = NextNumber++;
5560b57cec5SDimitry Andric     else
5570b57cec5SDimitry Andric       *NextToUse++ = STy;
5580b57cec5SDimitry Andric   }
5590b57cec5SDimitry Andric 
5600b57cec5SDimitry Andric   NamedTypes.erase(NextToUse, NamedTypes.end());
5610b57cec5SDimitry Andric }
5620b57cec5SDimitry Andric 
5630b57cec5SDimitry Andric /// Write the specified type to the specified raw_ostream, making use of type
5640b57cec5SDimitry Andric /// names or up references to shorten the type name where possible.
print(Type * Ty,raw_ostream & OS)5650b57cec5SDimitry Andric void TypePrinting::print(Type *Ty, raw_ostream &OS) {
5660b57cec5SDimitry Andric   switch (Ty->getTypeID()) {
5670b57cec5SDimitry Andric   case Type::VoidTyID:      OS << "void"; return;
5680b57cec5SDimitry Andric   case Type::HalfTyID:      OS << "half"; return;
5695ffd83dbSDimitry Andric   case Type::BFloatTyID:    OS << "bfloat"; return;
5700b57cec5SDimitry Andric   case Type::FloatTyID:     OS << "float"; return;
5710b57cec5SDimitry Andric   case Type::DoubleTyID:    OS << "double"; return;
5720b57cec5SDimitry Andric   case Type::X86_FP80TyID:  OS << "x86_fp80"; return;
5730b57cec5SDimitry Andric   case Type::FP128TyID:     OS << "fp128"; return;
5740b57cec5SDimitry Andric   case Type::PPC_FP128TyID: OS << "ppc_fp128"; return;
5750b57cec5SDimitry Andric   case Type::LabelTyID:     OS << "label"; return;
5760b57cec5SDimitry Andric   case Type::MetadataTyID:  OS << "metadata"; return;
5770b57cec5SDimitry Andric   case Type::X86_MMXTyID:   OS << "x86_mmx"; return;
578e8d8bef9SDimitry Andric   case Type::X86_AMXTyID:   OS << "x86_amx"; return;
5790b57cec5SDimitry Andric   case Type::TokenTyID:     OS << "token"; return;
5800b57cec5SDimitry Andric   case Type::IntegerTyID:
5810b57cec5SDimitry Andric     OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
5820b57cec5SDimitry Andric     return;
5830b57cec5SDimitry Andric 
5840b57cec5SDimitry Andric   case Type::FunctionTyID: {
5850b57cec5SDimitry Andric     FunctionType *FTy = cast<FunctionType>(Ty);
5860b57cec5SDimitry Andric     print(FTy->getReturnType(), OS);
5870b57cec5SDimitry Andric     OS << " (";
588349cc55cSDimitry Andric     ListSeparator LS;
589349cc55cSDimitry Andric     for (Type *Ty : FTy->params()) {
590349cc55cSDimitry Andric       OS << LS;
591349cc55cSDimitry Andric       print(Ty, OS);
5920b57cec5SDimitry Andric     }
593349cc55cSDimitry Andric     if (FTy->isVarArg())
594349cc55cSDimitry Andric       OS << LS << "...";
5950b57cec5SDimitry Andric     OS << ')';
5960b57cec5SDimitry Andric     return;
5970b57cec5SDimitry Andric   }
5980b57cec5SDimitry Andric   case Type::StructTyID: {
5990b57cec5SDimitry Andric     StructType *STy = cast<StructType>(Ty);
6000b57cec5SDimitry Andric 
6010b57cec5SDimitry Andric     if (STy->isLiteral())
6020b57cec5SDimitry Andric       return printStructBody(STy, OS);
6030b57cec5SDimitry Andric 
6040b57cec5SDimitry Andric     if (!STy->getName().empty())
6050b57cec5SDimitry Andric       return PrintLLVMName(OS, STy->getName(), LocalPrefix);
6060b57cec5SDimitry Andric 
6070b57cec5SDimitry Andric     incorporateTypes();
6080b57cec5SDimitry Andric     const auto I = Type2Number.find(STy);
6090b57cec5SDimitry Andric     if (I != Type2Number.end())
6100b57cec5SDimitry Andric       OS << '%' << I->second;
6110b57cec5SDimitry Andric     else  // Not enumerated, print the hex address.
6120b57cec5SDimitry Andric       OS << "%\"type " << STy << '\"';
6130b57cec5SDimitry Andric     return;
6140b57cec5SDimitry Andric   }
6150b57cec5SDimitry Andric   case Type::PointerTyID: {
6160b57cec5SDimitry Andric     PointerType *PTy = cast<PointerType>(Ty);
617fe6060f1SDimitry Andric     OS << "ptr";
618fe6060f1SDimitry Andric     if (unsigned AddressSpace = PTy->getAddressSpace())
619fe6060f1SDimitry Andric       OS << " addrspace(" << AddressSpace << ')';
620fe6060f1SDimitry Andric     return;
621fe6060f1SDimitry Andric   }
6220b57cec5SDimitry Andric   case Type::ArrayTyID: {
6230b57cec5SDimitry Andric     ArrayType *ATy = cast<ArrayType>(Ty);
6240b57cec5SDimitry Andric     OS << '[' << ATy->getNumElements() << " x ";
6250b57cec5SDimitry Andric     print(ATy->getElementType(), OS);
6260b57cec5SDimitry Andric     OS << ']';
6270b57cec5SDimitry Andric     return;
6280b57cec5SDimitry Andric   }
6295ffd83dbSDimitry Andric   case Type::FixedVectorTyID:
6305ffd83dbSDimitry Andric   case Type::ScalableVectorTyID: {
6310b57cec5SDimitry Andric     VectorType *PTy = cast<VectorType>(Ty);
6325ffd83dbSDimitry Andric     ElementCount EC = PTy->getElementCount();
6330b57cec5SDimitry Andric     OS << "<";
634e8d8bef9SDimitry Andric     if (EC.isScalable())
6350b57cec5SDimitry Andric       OS << "vscale x ";
636e8d8bef9SDimitry Andric     OS << EC.getKnownMinValue() << " x ";
6370b57cec5SDimitry Andric     print(PTy->getElementType(), OS);
6380b57cec5SDimitry Andric     OS << '>';
6390b57cec5SDimitry Andric     return;
6400b57cec5SDimitry Andric   }
641bdd1243dSDimitry Andric   case Type::TypedPointerTyID: {
642bdd1243dSDimitry Andric     TypedPointerType *TPTy = cast<TypedPointerType>(Ty);
643bdd1243dSDimitry Andric     OS << "typedptr(" << *TPTy->getElementType() << ", "
644bdd1243dSDimitry Andric        << TPTy->getAddressSpace() << ")";
645bdd1243dSDimitry Andric     return;
646bdd1243dSDimitry Andric   }
647bdd1243dSDimitry Andric   case Type::TargetExtTyID:
648bdd1243dSDimitry Andric     TargetExtType *TETy = cast<TargetExtType>(Ty);
649bdd1243dSDimitry Andric     OS << "target(\"";
650bdd1243dSDimitry Andric     printEscapedString(Ty->getTargetExtName(), OS);
651bdd1243dSDimitry Andric     OS << "\"";
652bdd1243dSDimitry Andric     for (Type *Inner : TETy->type_params())
653bdd1243dSDimitry Andric       OS << ", " << *Inner;
654bdd1243dSDimitry Andric     for (unsigned IntParam : TETy->int_params())
655bdd1243dSDimitry Andric       OS << ", " << IntParam;
656bdd1243dSDimitry Andric     OS << ")";
65781ad6265SDimitry Andric     return;
6580b57cec5SDimitry Andric   }
6590b57cec5SDimitry Andric   llvm_unreachable("Invalid TypeID");
6600b57cec5SDimitry Andric }
6610b57cec5SDimitry Andric 
printStructBody(StructType * STy,raw_ostream & OS)6620b57cec5SDimitry Andric void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
6630b57cec5SDimitry Andric   if (STy->isOpaque()) {
6640b57cec5SDimitry Andric     OS << "opaque";
6650b57cec5SDimitry Andric     return;
6660b57cec5SDimitry Andric   }
6670b57cec5SDimitry Andric 
6680b57cec5SDimitry Andric   if (STy->isPacked())
6690b57cec5SDimitry Andric     OS << '<';
6700b57cec5SDimitry Andric 
6710b57cec5SDimitry Andric   if (STy->getNumElements() == 0) {
6720b57cec5SDimitry Andric     OS << "{}";
6730b57cec5SDimitry Andric   } else {
6740b57cec5SDimitry Andric     OS << "{ ";
675349cc55cSDimitry Andric     ListSeparator LS;
676349cc55cSDimitry Andric     for (Type *Ty : STy->elements()) {
677349cc55cSDimitry Andric       OS << LS;
678349cc55cSDimitry Andric       print(Ty, OS);
6790b57cec5SDimitry Andric     }
6800b57cec5SDimitry Andric 
6810b57cec5SDimitry Andric     OS << " }";
6820b57cec5SDimitry Andric   }
6830b57cec5SDimitry Andric   if (STy->isPacked())
6840b57cec5SDimitry Andric     OS << '>';
6850b57cec5SDimitry Andric }
6860b57cec5SDimitry Andric 
68781ad6265SDimitry Andric AbstractSlotTrackerStorage::~AbstractSlotTrackerStorage() = default;
688fe6060f1SDimitry Andric 
6890b57cec5SDimitry Andric namespace llvm {
6900b57cec5SDimitry Andric 
6910b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
6920b57cec5SDimitry Andric // SlotTracker Class: Enumerate slot numbers for unnamed values
6930b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
6940b57cec5SDimitry Andric /// This class provides computation of slot numbers for LLVM Assembly writing.
6950b57cec5SDimitry Andric ///
696fe6060f1SDimitry Andric class SlotTracker : public AbstractSlotTrackerStorage {
6970b57cec5SDimitry Andric public:
6980b57cec5SDimitry Andric   /// ValueMap - A mapping of Values to slot numbers.
6990b57cec5SDimitry Andric   using ValueMap = DenseMap<const Value *, unsigned>;
7000b57cec5SDimitry Andric 
7010b57cec5SDimitry Andric private:
7020b57cec5SDimitry Andric   /// TheModule - The module for which we are holding slot numbers.
7030b57cec5SDimitry Andric   const Module* TheModule;
7040b57cec5SDimitry Andric 
7050b57cec5SDimitry Andric   /// TheFunction - The function for which we are holding slot numbers.
7060b57cec5SDimitry Andric   const Function* TheFunction = nullptr;
7070b57cec5SDimitry Andric   bool FunctionProcessed = false;
7080b57cec5SDimitry Andric   bool ShouldInitializeAllMetadata;
7090b57cec5SDimitry Andric 
710fe6060f1SDimitry Andric   std::function<void(AbstractSlotTrackerStorage *, const Module *, bool)>
711fe6060f1SDimitry Andric       ProcessModuleHookFn;
712fe6060f1SDimitry Andric   std::function<void(AbstractSlotTrackerStorage *, const Function *, bool)>
713fe6060f1SDimitry Andric       ProcessFunctionHookFn;
714fe6060f1SDimitry Andric 
7150b57cec5SDimitry Andric   /// The summary index for which we are holding slot numbers.
7160b57cec5SDimitry Andric   const ModuleSummaryIndex *TheIndex = nullptr;
7170b57cec5SDimitry Andric 
7180b57cec5SDimitry Andric   /// mMap - The slot map for the module level data.
7190b57cec5SDimitry Andric   ValueMap mMap;
7200b57cec5SDimitry Andric   unsigned mNext = 0;
7210b57cec5SDimitry Andric 
7220b57cec5SDimitry Andric   /// fMap - The slot map for the function level data.
7230b57cec5SDimitry Andric   ValueMap fMap;
7240b57cec5SDimitry Andric   unsigned fNext = 0;
7250b57cec5SDimitry Andric 
7260b57cec5SDimitry Andric   /// mdnMap - Map for MDNodes.
7270b57cec5SDimitry Andric   DenseMap<const MDNode*, unsigned> mdnMap;
7280b57cec5SDimitry Andric   unsigned mdnNext = 0;
7290b57cec5SDimitry Andric 
7300b57cec5SDimitry Andric   /// asMap - The slot map for attribute sets.
7310b57cec5SDimitry Andric   DenseMap<AttributeSet, unsigned> asMap;
7320b57cec5SDimitry Andric   unsigned asNext = 0;
7330b57cec5SDimitry Andric 
7340b57cec5SDimitry Andric   /// ModulePathMap - The slot map for Module paths used in the summary index.
7350b57cec5SDimitry Andric   StringMap<unsigned> ModulePathMap;
7360b57cec5SDimitry Andric   unsigned ModulePathNext = 0;
7370b57cec5SDimitry Andric 
7380b57cec5SDimitry Andric   /// GUIDMap - The slot map for GUIDs used in the summary index.
7390b57cec5SDimitry Andric   DenseMap<GlobalValue::GUID, unsigned> GUIDMap;
7400b57cec5SDimitry Andric   unsigned GUIDNext = 0;
7410b57cec5SDimitry Andric 
7420b57cec5SDimitry Andric   /// TypeIdMap - The slot map for type ids used in the summary index.
7430b57cec5SDimitry Andric   StringMap<unsigned> TypeIdMap;
7440b57cec5SDimitry Andric   unsigned TypeIdNext = 0;
7450b57cec5SDimitry Andric 
7465f757f3fSDimitry Andric   /// TypeIdCompatibleVtableMap - The slot map for type compatible vtable ids
7475f757f3fSDimitry Andric   /// used in the summary index.
7485f757f3fSDimitry Andric   StringMap<unsigned> TypeIdCompatibleVtableMap;
7495f757f3fSDimitry Andric   unsigned TypeIdCompatibleVtableNext = 0;
7505f757f3fSDimitry Andric 
7510b57cec5SDimitry Andric public:
7520b57cec5SDimitry Andric   /// Construct from a module.
7530b57cec5SDimitry Andric   ///
7540b57cec5SDimitry Andric   /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
7550b57cec5SDimitry Andric   /// functions, giving correct numbering for metadata referenced only from
7560b57cec5SDimitry Andric   /// within a function (even if no functions have been initialized).
7570b57cec5SDimitry Andric   explicit SlotTracker(const Module *M,
7580b57cec5SDimitry Andric                        bool ShouldInitializeAllMetadata = false);
7590b57cec5SDimitry Andric 
7600b57cec5SDimitry Andric   /// Construct from a function, starting out in incorp state.
7610b57cec5SDimitry Andric   ///
7620b57cec5SDimitry Andric   /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
7630b57cec5SDimitry Andric   /// functions, giving correct numbering for metadata referenced only from
7640b57cec5SDimitry Andric   /// within a function (even if no functions have been initialized).
7650b57cec5SDimitry Andric   explicit SlotTracker(const Function *F,
7660b57cec5SDimitry Andric                        bool ShouldInitializeAllMetadata = false);
7670b57cec5SDimitry Andric 
7680b57cec5SDimitry Andric   /// Construct from a module summary index.
7690b57cec5SDimitry Andric   explicit SlotTracker(const ModuleSummaryIndex *Index);
7700b57cec5SDimitry Andric 
7710b57cec5SDimitry Andric   SlotTracker(const SlotTracker &) = delete;
7720b57cec5SDimitry Andric   SlotTracker &operator=(const SlotTracker &) = delete;
7730b57cec5SDimitry Andric 
774fe6060f1SDimitry Andric   ~SlotTracker() = default;
775fe6060f1SDimitry Andric 
776fe6060f1SDimitry Andric   void setProcessHook(
777fe6060f1SDimitry Andric       std::function<void(AbstractSlotTrackerStorage *, const Module *, bool)>);
778fe6060f1SDimitry Andric   void setProcessHook(std::function<void(AbstractSlotTrackerStorage *,
779fe6060f1SDimitry Andric                                          const Function *, bool)>);
780fe6060f1SDimitry Andric 
getNextMetadataSlot()781fe6060f1SDimitry Andric   unsigned getNextMetadataSlot() override { return mdnNext; }
782fe6060f1SDimitry Andric 
783fe6060f1SDimitry Andric   void createMetadataSlot(const MDNode *N) override;
784fe6060f1SDimitry Andric 
7850b57cec5SDimitry Andric   /// Return the slot number of the specified value in it's type
7860b57cec5SDimitry Andric   /// plane.  If something is not in the SlotTracker, return -1.
7870b57cec5SDimitry Andric   int getLocalSlot(const Value *V);
7880b57cec5SDimitry Andric   int getGlobalSlot(const GlobalValue *V);
789fe6060f1SDimitry Andric   int getMetadataSlot(const MDNode *N) override;
7900b57cec5SDimitry Andric   int getAttributeGroupSlot(AttributeSet AS);
7910b57cec5SDimitry Andric   int getModulePathSlot(StringRef Path);
7920b57cec5SDimitry Andric   int getGUIDSlot(GlobalValue::GUID GUID);
7930b57cec5SDimitry Andric   int getTypeIdSlot(StringRef Id);
7945f757f3fSDimitry Andric   int getTypeIdCompatibleVtableSlot(StringRef Id);
7950b57cec5SDimitry Andric 
7960b57cec5SDimitry Andric   /// If you'd like to deal with a function instead of just a module, use
7970b57cec5SDimitry Andric   /// this method to get its data into the SlotTracker.
incorporateFunction(const Function * F)7980b57cec5SDimitry Andric   void incorporateFunction(const Function *F) {
7990b57cec5SDimitry Andric     TheFunction = F;
8000b57cec5SDimitry Andric     FunctionProcessed = false;
8010b57cec5SDimitry Andric   }
8020b57cec5SDimitry Andric 
getFunction() const8030b57cec5SDimitry Andric   const Function *getFunction() const { return TheFunction; }
8040b57cec5SDimitry Andric 
8050b57cec5SDimitry Andric   /// After calling incorporateFunction, use this method to remove the
8060b57cec5SDimitry Andric   /// most recently incorporated function from the SlotTracker. This
8070b57cec5SDimitry Andric   /// will reset the state of the machine back to just the module contents.
8080b57cec5SDimitry Andric   void purgeFunction();
8090b57cec5SDimitry Andric 
8100b57cec5SDimitry Andric   /// MDNode map iterators.
8110b57cec5SDimitry Andric   using mdn_iterator = DenseMap<const MDNode*, unsigned>::iterator;
8120b57cec5SDimitry Andric 
mdn_begin()8130b57cec5SDimitry Andric   mdn_iterator mdn_begin() { return mdnMap.begin(); }
mdn_end()8140b57cec5SDimitry Andric   mdn_iterator mdn_end() { return mdnMap.end(); }
mdn_size() const8150b57cec5SDimitry Andric   unsigned mdn_size() const { return mdnMap.size(); }
mdn_empty() const8160b57cec5SDimitry Andric   bool mdn_empty() const { return mdnMap.empty(); }
8170b57cec5SDimitry Andric 
8180b57cec5SDimitry Andric   /// AttributeSet map iterators.
8190b57cec5SDimitry Andric   using as_iterator = DenseMap<AttributeSet, unsigned>::iterator;
8200b57cec5SDimitry Andric 
as_begin()8210b57cec5SDimitry Andric   as_iterator as_begin()   { return asMap.begin(); }
as_end()8220b57cec5SDimitry Andric   as_iterator as_end()     { return asMap.end(); }
as_size() const8230b57cec5SDimitry Andric   unsigned as_size() const { return asMap.size(); }
as_empty() const8240b57cec5SDimitry Andric   bool as_empty() const    { return asMap.empty(); }
8250b57cec5SDimitry Andric 
8260b57cec5SDimitry Andric   /// GUID map iterators.
8270b57cec5SDimitry Andric   using guid_iterator = DenseMap<GlobalValue::GUID, unsigned>::iterator;
8280b57cec5SDimitry Andric 
8290b57cec5SDimitry Andric   /// These functions do the actual initialization.
8300b57cec5SDimitry Andric   inline void initializeIfNeeded();
8315ffd83dbSDimitry Andric   int initializeIndexIfNeeded();
8320b57cec5SDimitry Andric 
8330b57cec5SDimitry Andric   // Implementation Details
8340b57cec5SDimitry Andric private:
8350b57cec5SDimitry Andric   /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
8360b57cec5SDimitry Andric   void CreateModuleSlot(const GlobalValue *V);
8370b57cec5SDimitry Andric 
8380b57cec5SDimitry Andric   /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
8390b57cec5SDimitry Andric   void CreateMetadataSlot(const MDNode *N);
8400b57cec5SDimitry Andric 
8410b57cec5SDimitry Andric   /// CreateFunctionSlot - Insert the specified Value* into the slot table.
8420b57cec5SDimitry Andric   void CreateFunctionSlot(const Value *V);
8430b57cec5SDimitry Andric 
8440b57cec5SDimitry Andric   /// Insert the specified AttributeSet into the slot table.
8450b57cec5SDimitry Andric   void CreateAttributeSetSlot(AttributeSet AS);
8460b57cec5SDimitry Andric 
8470b57cec5SDimitry Andric   inline void CreateModulePathSlot(StringRef Path);
8480b57cec5SDimitry Andric   void CreateGUIDSlot(GlobalValue::GUID GUID);
8490b57cec5SDimitry Andric   void CreateTypeIdSlot(StringRef Id);
8505f757f3fSDimitry Andric   void CreateTypeIdCompatibleVtableSlot(StringRef Id);
8510b57cec5SDimitry Andric 
8520b57cec5SDimitry Andric   /// Add all of the module level global variables (and their initializers)
8530b57cec5SDimitry Andric   /// and function declarations, but not the contents of those functions.
8540b57cec5SDimitry Andric   void processModule();
8555ffd83dbSDimitry Andric   // Returns number of allocated slots
8565ffd83dbSDimitry Andric   int processIndex();
8570b57cec5SDimitry Andric 
8580b57cec5SDimitry Andric   /// Add all of the functions arguments, basic blocks, and instructions.
8590b57cec5SDimitry Andric   void processFunction();
8600b57cec5SDimitry Andric 
8610b57cec5SDimitry Andric   /// Add the metadata directly attached to a GlobalObject.
8620b57cec5SDimitry Andric   void processGlobalObjectMetadata(const GlobalObject &GO);
8630b57cec5SDimitry Andric 
8640b57cec5SDimitry Andric   /// Add all of the metadata from a function.
8650b57cec5SDimitry Andric   void processFunctionMetadata(const Function &F);
8660b57cec5SDimitry Andric 
8670b57cec5SDimitry Andric   /// Add all of the metadata from an instruction.
8680b57cec5SDimitry Andric   void processInstructionMetadata(const Instruction &I);
8691db9f3b2SDimitry Andric 
870*0fca6ea1SDimitry Andric   /// Add all of the metadata from a DbgRecord.
871*0fca6ea1SDimitry Andric   void processDbgRecordMetadata(const DbgRecord &DVR);
8720b57cec5SDimitry Andric };
8730b57cec5SDimitry Andric 
8740b57cec5SDimitry Andric } // end namespace llvm
8750b57cec5SDimitry Andric 
ModuleSlotTracker(SlotTracker & Machine,const Module * M,const Function * F)8760b57cec5SDimitry Andric ModuleSlotTracker::ModuleSlotTracker(SlotTracker &Machine, const Module *M,
8770b57cec5SDimitry Andric                                      const Function *F)
8780b57cec5SDimitry Andric     : M(M), F(F), Machine(&Machine) {}
8790b57cec5SDimitry Andric 
ModuleSlotTracker(const Module * M,bool ShouldInitializeAllMetadata)8800b57cec5SDimitry Andric ModuleSlotTracker::ModuleSlotTracker(const Module *M,
8810b57cec5SDimitry Andric                                      bool ShouldInitializeAllMetadata)
8820b57cec5SDimitry Andric     : ShouldCreateStorage(M),
8830b57cec5SDimitry Andric       ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), M(M) {}
8840b57cec5SDimitry Andric 
8850b57cec5SDimitry Andric ModuleSlotTracker::~ModuleSlotTracker() = default;
8860b57cec5SDimitry Andric 
getMachine()8870b57cec5SDimitry Andric SlotTracker *ModuleSlotTracker::getMachine() {
8880b57cec5SDimitry Andric   if (!ShouldCreateStorage)
8890b57cec5SDimitry Andric     return Machine;
8900b57cec5SDimitry Andric 
8910b57cec5SDimitry Andric   ShouldCreateStorage = false;
8920b57cec5SDimitry Andric   MachineStorage =
8938bcb0991SDimitry Andric       std::make_unique<SlotTracker>(M, ShouldInitializeAllMetadata);
8940b57cec5SDimitry Andric   Machine = MachineStorage.get();
895fe6060f1SDimitry Andric   if (ProcessModuleHookFn)
896fe6060f1SDimitry Andric     Machine->setProcessHook(ProcessModuleHookFn);
897fe6060f1SDimitry Andric   if (ProcessFunctionHookFn)
898fe6060f1SDimitry Andric     Machine->setProcessHook(ProcessFunctionHookFn);
8990b57cec5SDimitry Andric   return Machine;
9000b57cec5SDimitry Andric }
9010b57cec5SDimitry Andric 
incorporateFunction(const Function & F)9020b57cec5SDimitry Andric void ModuleSlotTracker::incorporateFunction(const Function &F) {
9030b57cec5SDimitry Andric   // Using getMachine() may lazily create the slot tracker.
9040b57cec5SDimitry Andric   if (!getMachine())
9050b57cec5SDimitry Andric     return;
9060b57cec5SDimitry Andric 
9070b57cec5SDimitry Andric   // Nothing to do if this is the right function already.
9080b57cec5SDimitry Andric   if (this->F == &F)
9090b57cec5SDimitry Andric     return;
9100b57cec5SDimitry Andric   if (this->F)
9110b57cec5SDimitry Andric     Machine->purgeFunction();
9120b57cec5SDimitry Andric   Machine->incorporateFunction(&F);
9130b57cec5SDimitry Andric   this->F = &F;
9140b57cec5SDimitry Andric }
9150b57cec5SDimitry Andric 
getLocalSlot(const Value * V)9160b57cec5SDimitry Andric int ModuleSlotTracker::getLocalSlot(const Value *V) {
9170b57cec5SDimitry Andric   assert(F && "No function incorporated");
9180b57cec5SDimitry Andric   return Machine->getLocalSlot(V);
9190b57cec5SDimitry Andric }
9200b57cec5SDimitry Andric 
setProcessHook(std::function<void (AbstractSlotTrackerStorage *,const Module *,bool)> Fn)921fe6060f1SDimitry Andric void ModuleSlotTracker::setProcessHook(
922fe6060f1SDimitry Andric     std::function<void(AbstractSlotTrackerStorage *, const Module *, bool)>
923fe6060f1SDimitry Andric         Fn) {
924fe6060f1SDimitry Andric   ProcessModuleHookFn = Fn;
925fe6060f1SDimitry Andric }
926fe6060f1SDimitry Andric 
setProcessHook(std::function<void (AbstractSlotTrackerStorage *,const Function *,bool)> Fn)927fe6060f1SDimitry Andric void ModuleSlotTracker::setProcessHook(
928fe6060f1SDimitry Andric     std::function<void(AbstractSlotTrackerStorage *, const Function *, bool)>
929fe6060f1SDimitry Andric         Fn) {
930fe6060f1SDimitry Andric   ProcessFunctionHookFn = Fn;
931fe6060f1SDimitry Andric }
932fe6060f1SDimitry Andric 
createSlotTracker(const Value * V)9330b57cec5SDimitry Andric static SlotTracker *createSlotTracker(const Value *V) {
9340b57cec5SDimitry Andric   if (const Argument *FA = dyn_cast<Argument>(V))
9350b57cec5SDimitry Andric     return new SlotTracker(FA->getParent());
9360b57cec5SDimitry Andric 
9370b57cec5SDimitry Andric   if (const Instruction *I = dyn_cast<Instruction>(V))
9380b57cec5SDimitry Andric     if (I->getParent())
9390b57cec5SDimitry Andric       return new SlotTracker(I->getParent()->getParent());
9400b57cec5SDimitry Andric 
9410b57cec5SDimitry Andric   if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
9420b57cec5SDimitry Andric     return new SlotTracker(BB->getParent());
9430b57cec5SDimitry Andric 
9440b57cec5SDimitry Andric   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
9450b57cec5SDimitry Andric     return new SlotTracker(GV->getParent());
9460b57cec5SDimitry Andric 
9470b57cec5SDimitry Andric   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
9480b57cec5SDimitry Andric     return new SlotTracker(GA->getParent());
9490b57cec5SDimitry Andric 
9500b57cec5SDimitry Andric   if (const GlobalIFunc *GIF = dyn_cast<GlobalIFunc>(V))
9510b57cec5SDimitry Andric     return new SlotTracker(GIF->getParent());
9520b57cec5SDimitry Andric 
9530b57cec5SDimitry Andric   if (const Function *Func = dyn_cast<Function>(V))
9540b57cec5SDimitry Andric     return new SlotTracker(Func);
9550b57cec5SDimitry Andric 
9560b57cec5SDimitry Andric   return nullptr;
9570b57cec5SDimitry Andric }
9580b57cec5SDimitry Andric 
9590b57cec5SDimitry Andric #if 0
9600b57cec5SDimitry Andric #define ST_DEBUG(X) dbgs() << X
9610b57cec5SDimitry Andric #else
9620b57cec5SDimitry Andric #define ST_DEBUG(X)
9630b57cec5SDimitry Andric #endif
9640b57cec5SDimitry Andric 
9650b57cec5SDimitry Andric // Module level constructor. Causes the contents of the Module (sans functions)
9660b57cec5SDimitry Andric // to be added to the slot table.
SlotTracker(const Module * M,bool ShouldInitializeAllMetadata)9670b57cec5SDimitry Andric SlotTracker::SlotTracker(const Module *M, bool ShouldInitializeAllMetadata)
9680b57cec5SDimitry Andric     : TheModule(M), ShouldInitializeAllMetadata(ShouldInitializeAllMetadata) {}
9690b57cec5SDimitry Andric 
9700b57cec5SDimitry Andric // Function level constructor. Causes the contents of the Module and the one
9710b57cec5SDimitry Andric // function provided to be added to the slot table.
SlotTracker(const Function * F,bool ShouldInitializeAllMetadata)9720b57cec5SDimitry Andric SlotTracker::SlotTracker(const Function *F, bool ShouldInitializeAllMetadata)
9730b57cec5SDimitry Andric     : TheModule(F ? F->getParent() : nullptr), TheFunction(F),
9740b57cec5SDimitry Andric       ShouldInitializeAllMetadata(ShouldInitializeAllMetadata) {}
9750b57cec5SDimitry Andric 
SlotTracker(const ModuleSummaryIndex * Index)9760b57cec5SDimitry Andric SlotTracker::SlotTracker(const ModuleSummaryIndex *Index)
9770b57cec5SDimitry Andric     : TheModule(nullptr), ShouldInitializeAllMetadata(false), TheIndex(Index) {}
9780b57cec5SDimitry Andric 
initializeIfNeeded()9790b57cec5SDimitry Andric inline void SlotTracker::initializeIfNeeded() {
9800b57cec5SDimitry Andric   if (TheModule) {
9810b57cec5SDimitry Andric     processModule();
9820b57cec5SDimitry Andric     TheModule = nullptr; ///< Prevent re-processing next time we're called.
9830b57cec5SDimitry Andric   }
9840b57cec5SDimitry Andric 
9850b57cec5SDimitry Andric   if (TheFunction && !FunctionProcessed)
9860b57cec5SDimitry Andric     processFunction();
9870b57cec5SDimitry Andric }
9880b57cec5SDimitry Andric 
initializeIndexIfNeeded()9895ffd83dbSDimitry Andric int SlotTracker::initializeIndexIfNeeded() {
9900b57cec5SDimitry Andric   if (!TheIndex)
9915ffd83dbSDimitry Andric     return 0;
9925ffd83dbSDimitry Andric   int NumSlots = processIndex();
9930b57cec5SDimitry Andric   TheIndex = nullptr; ///< Prevent re-processing next time we're called.
9945ffd83dbSDimitry Andric   return NumSlots;
9950b57cec5SDimitry Andric }
9960b57cec5SDimitry Andric 
9970b57cec5SDimitry Andric // Iterate through all the global variables, functions, and global
9980b57cec5SDimitry Andric // variable initializers and create slots for them.
processModule()9990b57cec5SDimitry Andric void SlotTracker::processModule() {
10000b57cec5SDimitry Andric   ST_DEBUG("begin processModule!\n");
10010b57cec5SDimitry Andric 
10020b57cec5SDimitry Andric   // Add all of the unnamed global variables to the value table.
10030b57cec5SDimitry Andric   for (const GlobalVariable &Var : TheModule->globals()) {
10040b57cec5SDimitry Andric     if (!Var.hasName())
10050b57cec5SDimitry Andric       CreateModuleSlot(&Var);
10060b57cec5SDimitry Andric     processGlobalObjectMetadata(Var);
10070b57cec5SDimitry Andric     auto Attrs = Var.getAttributes();
10080b57cec5SDimitry Andric     if (Attrs.hasAttributes())
10090b57cec5SDimitry Andric       CreateAttributeSetSlot(Attrs);
10100b57cec5SDimitry Andric   }
10110b57cec5SDimitry Andric 
10120b57cec5SDimitry Andric   for (const GlobalAlias &A : TheModule->aliases()) {
10130b57cec5SDimitry Andric     if (!A.hasName())
10140b57cec5SDimitry Andric       CreateModuleSlot(&A);
10150b57cec5SDimitry Andric   }
10160b57cec5SDimitry Andric 
10170b57cec5SDimitry Andric   for (const GlobalIFunc &I : TheModule->ifuncs()) {
10180b57cec5SDimitry Andric     if (!I.hasName())
10190b57cec5SDimitry Andric       CreateModuleSlot(&I);
10200b57cec5SDimitry Andric   }
10210b57cec5SDimitry Andric 
10220b57cec5SDimitry Andric   // Add metadata used by named metadata.
10230b57cec5SDimitry Andric   for (const NamedMDNode &NMD : TheModule->named_metadata()) {
1024*0fca6ea1SDimitry Andric     for (const MDNode *N : NMD.operands())
1025*0fca6ea1SDimitry Andric       CreateMetadataSlot(N);
10260b57cec5SDimitry Andric   }
10270b57cec5SDimitry Andric 
10280b57cec5SDimitry Andric   for (const Function &F : *TheModule) {
10290b57cec5SDimitry Andric     if (!F.hasName())
10300b57cec5SDimitry Andric       // Add all the unnamed functions to the table.
10310b57cec5SDimitry Andric       CreateModuleSlot(&F);
10320b57cec5SDimitry Andric 
10330b57cec5SDimitry Andric     if (ShouldInitializeAllMetadata)
10340b57cec5SDimitry Andric       processFunctionMetadata(F);
10350b57cec5SDimitry Andric 
10360b57cec5SDimitry Andric     // Add all the function attributes to the table.
10370b57cec5SDimitry Andric     // FIXME: Add attributes of other objects?
1038349cc55cSDimitry Andric     AttributeSet FnAttrs = F.getAttributes().getFnAttrs();
10390b57cec5SDimitry Andric     if (FnAttrs.hasAttributes())
10400b57cec5SDimitry Andric       CreateAttributeSetSlot(FnAttrs);
10410b57cec5SDimitry Andric   }
10420b57cec5SDimitry Andric 
1043fe6060f1SDimitry Andric   if (ProcessModuleHookFn)
1044fe6060f1SDimitry Andric     ProcessModuleHookFn(this, TheModule, ShouldInitializeAllMetadata);
1045fe6060f1SDimitry Andric 
10460b57cec5SDimitry Andric   ST_DEBUG("end processModule!\n");
10470b57cec5SDimitry Andric }
10480b57cec5SDimitry Andric 
10490b57cec5SDimitry Andric // Process the arguments, basic blocks, and instructions  of a function.
processFunction()10500b57cec5SDimitry Andric void SlotTracker::processFunction() {
10510b57cec5SDimitry Andric   ST_DEBUG("begin processFunction!\n");
10520b57cec5SDimitry Andric   fNext = 0;
10530b57cec5SDimitry Andric 
10540b57cec5SDimitry Andric   // Process function metadata if it wasn't hit at the module-level.
10550b57cec5SDimitry Andric   if (!ShouldInitializeAllMetadata)
10560b57cec5SDimitry Andric     processFunctionMetadata(*TheFunction);
10570b57cec5SDimitry Andric 
10580b57cec5SDimitry Andric   // Add all the function arguments with no names.
10590b57cec5SDimitry Andric   for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
10600b57cec5SDimitry Andric       AE = TheFunction->arg_end(); AI != AE; ++AI)
10610b57cec5SDimitry Andric     if (!AI->hasName())
10620b57cec5SDimitry Andric       CreateFunctionSlot(&*AI);
10630b57cec5SDimitry Andric 
10640b57cec5SDimitry Andric   ST_DEBUG("Inserting Instructions:\n");
10650b57cec5SDimitry Andric 
10660b57cec5SDimitry Andric   // Add all of the basic blocks and instructions with no names.
10670b57cec5SDimitry Andric   for (auto &BB : *TheFunction) {
10680b57cec5SDimitry Andric     if (!BB.hasName())
10690b57cec5SDimitry Andric       CreateFunctionSlot(&BB);
10700b57cec5SDimitry Andric 
10710b57cec5SDimitry Andric     for (auto &I : BB) {
10720b57cec5SDimitry Andric       if (!I.getType()->isVoidTy() && !I.hasName())
10730b57cec5SDimitry Andric         CreateFunctionSlot(&I);
10740b57cec5SDimitry Andric 
10750b57cec5SDimitry Andric       // We allow direct calls to any llvm.foo function here, because the
10760b57cec5SDimitry Andric       // target may not be linked into the optimizer.
10770b57cec5SDimitry Andric       if (const auto *Call = dyn_cast<CallBase>(&I)) {
10780b57cec5SDimitry Andric         // Add all the call attributes to the table.
1079349cc55cSDimitry Andric         AttributeSet Attrs = Call->getAttributes().getFnAttrs();
10800b57cec5SDimitry Andric         if (Attrs.hasAttributes())
10810b57cec5SDimitry Andric           CreateAttributeSetSlot(Attrs);
10820b57cec5SDimitry Andric       }
10830b57cec5SDimitry Andric     }
10840b57cec5SDimitry Andric   }
10850b57cec5SDimitry Andric 
1086fe6060f1SDimitry Andric   if (ProcessFunctionHookFn)
1087fe6060f1SDimitry Andric     ProcessFunctionHookFn(this, TheFunction, ShouldInitializeAllMetadata);
1088fe6060f1SDimitry Andric 
10890b57cec5SDimitry Andric   FunctionProcessed = true;
10900b57cec5SDimitry Andric 
10910b57cec5SDimitry Andric   ST_DEBUG("end processFunction!\n");
10920b57cec5SDimitry Andric }
10930b57cec5SDimitry Andric 
10940b57cec5SDimitry Andric // Iterate through all the GUID in the index and create slots for them.
processIndex()10955ffd83dbSDimitry Andric int SlotTracker::processIndex() {
10960b57cec5SDimitry Andric   ST_DEBUG("begin processIndex!\n");
10970b57cec5SDimitry Andric   assert(TheIndex);
10980b57cec5SDimitry Andric 
10990b57cec5SDimitry Andric   // The first block of slots are just the module ids, which start at 0 and are
11000b57cec5SDimitry Andric   // assigned consecutively. Since the StringMap iteration order isn't
11015f757f3fSDimitry Andric   // guaranteed, order by path string before assigning slots.
11025f757f3fSDimitry Andric   std::vector<StringRef> ModulePaths;
11035f757f3fSDimitry Andric   for (auto &[ModPath, _] : TheIndex->modulePaths())
11045f757f3fSDimitry Andric     ModulePaths.push_back(ModPath);
11055f757f3fSDimitry Andric   llvm::sort(ModulePaths.begin(), ModulePaths.end());
11065f757f3fSDimitry Andric   for (auto &ModPath : ModulePaths)
11075f757f3fSDimitry Andric     CreateModulePathSlot(ModPath);
11080b57cec5SDimitry Andric 
11090b57cec5SDimitry Andric   // Start numbering the GUIDs after the module ids.
11100b57cec5SDimitry Andric   GUIDNext = ModulePathNext;
11110b57cec5SDimitry Andric 
11120b57cec5SDimitry Andric   for (auto &GlobalList : *TheIndex)
11130b57cec5SDimitry Andric     CreateGUIDSlot(GlobalList.first);
11140b57cec5SDimitry Andric 
11155f757f3fSDimitry Andric   // Start numbering the TypeIdCompatibleVtables after the GUIDs.
11165f757f3fSDimitry Andric   TypeIdCompatibleVtableNext = GUIDNext;
11175ffd83dbSDimitry Andric   for (auto &TId : TheIndex->typeIdCompatibleVtableMap())
11185f757f3fSDimitry Andric     CreateTypeIdCompatibleVtableSlot(TId.first);
11195ffd83dbSDimitry Andric 
11205f757f3fSDimitry Andric   // Start numbering the TypeIds after the TypeIdCompatibleVtables.
11215f757f3fSDimitry Andric   TypeIdNext = TypeIdCompatibleVtableNext;
1122fe6060f1SDimitry Andric   for (const auto &TID : TheIndex->typeIds())
1123fe6060f1SDimitry Andric     CreateTypeIdSlot(TID.second.first);
11240b57cec5SDimitry Andric 
11250b57cec5SDimitry Andric   ST_DEBUG("end processIndex!\n");
11265ffd83dbSDimitry Andric   return TypeIdNext;
11270b57cec5SDimitry Andric }
11280b57cec5SDimitry Andric 
processGlobalObjectMetadata(const GlobalObject & GO)11290b57cec5SDimitry Andric void SlotTracker::processGlobalObjectMetadata(const GlobalObject &GO) {
11300b57cec5SDimitry Andric   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
11310b57cec5SDimitry Andric   GO.getAllMetadata(MDs);
11320b57cec5SDimitry Andric   for (auto &MD : MDs)
11330b57cec5SDimitry Andric     CreateMetadataSlot(MD.second);
11340b57cec5SDimitry Andric }
11350b57cec5SDimitry Andric 
processFunctionMetadata(const Function & F)11360b57cec5SDimitry Andric void SlotTracker::processFunctionMetadata(const Function &F) {
11370b57cec5SDimitry Andric   processGlobalObjectMetadata(F);
11380b57cec5SDimitry Andric   for (auto &BB : F) {
11391db9f3b2SDimitry Andric     for (auto &I : BB) {
1140*0fca6ea1SDimitry Andric       for (const DbgRecord &DR : I.getDbgRecordRange())
1141*0fca6ea1SDimitry Andric         processDbgRecordMetadata(DR);
11420b57cec5SDimitry Andric       processInstructionMetadata(I);
11430b57cec5SDimitry Andric     }
11440b57cec5SDimitry Andric   }
11451db9f3b2SDimitry Andric }
11461db9f3b2SDimitry Andric 
processDbgRecordMetadata(const DbgRecord & DR)1147*0fca6ea1SDimitry Andric void SlotTracker::processDbgRecordMetadata(const DbgRecord &DR) {
1148*0fca6ea1SDimitry Andric   if (const DbgVariableRecord *DVR = dyn_cast<const DbgVariableRecord>(&DR)) {
1149*0fca6ea1SDimitry Andric     // Process metadata used by DbgRecords; we only specifically care about the
1150*0fca6ea1SDimitry Andric     // DILocalVariable, DILocation, and DIAssignID fields, as the Value and
1151*0fca6ea1SDimitry Andric     // Expression fields should only be printed inline and so do not use a slot.
1152*0fca6ea1SDimitry Andric     // Note: The above doesn't apply for empty-metadata operands.
1153*0fca6ea1SDimitry Andric     if (auto *Empty = dyn_cast<MDNode>(DVR->getRawLocation()))
1154*0fca6ea1SDimitry Andric       CreateMetadataSlot(Empty);
1155*0fca6ea1SDimitry Andric     CreateMetadataSlot(DVR->getRawVariable());
1156*0fca6ea1SDimitry Andric     if (DVR->isDbgAssign()) {
1157*0fca6ea1SDimitry Andric       CreateMetadataSlot(cast<MDNode>(DVR->getRawAssignID()));
1158*0fca6ea1SDimitry Andric       if (auto *Empty = dyn_cast<MDNode>(DVR->getRawAddress()))
1159*0fca6ea1SDimitry Andric         CreateMetadataSlot(Empty);
11607a6dacacSDimitry Andric     }
1161*0fca6ea1SDimitry Andric   } else if (const DbgLabelRecord *DLR = dyn_cast<const DbgLabelRecord>(&DR)) {
1162*0fca6ea1SDimitry Andric     CreateMetadataSlot(DLR->getRawLabel());
1163*0fca6ea1SDimitry Andric   } else {
1164*0fca6ea1SDimitry Andric     llvm_unreachable("unsupported DbgRecord kind");
1165*0fca6ea1SDimitry Andric   }
1166*0fca6ea1SDimitry Andric   CreateMetadataSlot(DR.getDebugLoc().getAsMDNode());
11671db9f3b2SDimitry Andric }
11680b57cec5SDimitry Andric 
processInstructionMetadata(const Instruction & I)11690b57cec5SDimitry Andric void SlotTracker::processInstructionMetadata(const Instruction &I) {
11700b57cec5SDimitry Andric   // Process metadata used directly by intrinsics.
11710b57cec5SDimitry Andric   if (const CallInst *CI = dyn_cast<CallInst>(&I))
11720b57cec5SDimitry Andric     if (Function *F = CI->getCalledFunction())
11730b57cec5SDimitry Andric       if (F->isIntrinsic())
11740b57cec5SDimitry Andric         for (auto &Op : I.operands())
11750b57cec5SDimitry Andric           if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
11760b57cec5SDimitry Andric             if (MDNode *N = dyn_cast<MDNode>(V->getMetadata()))
11770b57cec5SDimitry Andric               CreateMetadataSlot(N);
11780b57cec5SDimitry Andric 
11790b57cec5SDimitry Andric   // Process metadata attached to this instruction.
11800b57cec5SDimitry Andric   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
11810b57cec5SDimitry Andric   I.getAllMetadata(MDs);
11820b57cec5SDimitry Andric   for (auto &MD : MDs)
11830b57cec5SDimitry Andric     CreateMetadataSlot(MD.second);
11840b57cec5SDimitry Andric }
11850b57cec5SDimitry Andric 
11860b57cec5SDimitry Andric /// Clean up after incorporating a function. This is the only way to get out of
11870b57cec5SDimitry Andric /// the function incorporation state that affects get*Slot/Create*Slot. Function
11880b57cec5SDimitry Andric /// incorporation state is indicated by TheFunction != 0.
purgeFunction()11890b57cec5SDimitry Andric void SlotTracker::purgeFunction() {
11900b57cec5SDimitry Andric   ST_DEBUG("begin purgeFunction!\n");
11910b57cec5SDimitry Andric   fMap.clear(); // Simply discard the function level map
11920b57cec5SDimitry Andric   TheFunction = nullptr;
11930b57cec5SDimitry Andric   FunctionProcessed = false;
11940b57cec5SDimitry Andric   ST_DEBUG("end purgeFunction!\n");
11950b57cec5SDimitry Andric }
11960b57cec5SDimitry Andric 
11970b57cec5SDimitry Andric /// getGlobalSlot - Get the slot number of a global value.
getGlobalSlot(const GlobalValue * V)11980b57cec5SDimitry Andric int SlotTracker::getGlobalSlot(const GlobalValue *V) {
11990b57cec5SDimitry Andric   // Check for uninitialized state and do lazy initialization.
12000b57cec5SDimitry Andric   initializeIfNeeded();
12010b57cec5SDimitry Andric 
12020b57cec5SDimitry Andric   // Find the value in the module map
12030b57cec5SDimitry Andric   ValueMap::iterator MI = mMap.find(V);
12040b57cec5SDimitry Andric   return MI == mMap.end() ? -1 : (int)MI->second;
12050b57cec5SDimitry Andric }
12060b57cec5SDimitry Andric 
setProcessHook(std::function<void (AbstractSlotTrackerStorage *,const Module *,bool)> Fn)1207fe6060f1SDimitry Andric void SlotTracker::setProcessHook(
1208fe6060f1SDimitry Andric     std::function<void(AbstractSlotTrackerStorage *, const Module *, bool)>
1209fe6060f1SDimitry Andric         Fn) {
1210fe6060f1SDimitry Andric   ProcessModuleHookFn = Fn;
1211fe6060f1SDimitry Andric }
1212fe6060f1SDimitry Andric 
setProcessHook(std::function<void (AbstractSlotTrackerStorage *,const Function *,bool)> Fn)1213fe6060f1SDimitry Andric void SlotTracker::setProcessHook(
1214fe6060f1SDimitry Andric     std::function<void(AbstractSlotTrackerStorage *, const Function *, bool)>
1215fe6060f1SDimitry Andric         Fn) {
1216fe6060f1SDimitry Andric   ProcessFunctionHookFn = Fn;
1217fe6060f1SDimitry Andric }
1218fe6060f1SDimitry Andric 
1219fe6060f1SDimitry Andric /// getMetadataSlot - Get the slot number of a MDNode.
createMetadataSlot(const MDNode * N)1220fe6060f1SDimitry Andric void SlotTracker::createMetadataSlot(const MDNode *N) { CreateMetadataSlot(N); }
1221fe6060f1SDimitry Andric 
12220b57cec5SDimitry Andric /// getMetadataSlot - Get the slot number of a MDNode.
getMetadataSlot(const MDNode * N)12230b57cec5SDimitry Andric int SlotTracker::getMetadataSlot(const MDNode *N) {
12240b57cec5SDimitry Andric   // Check for uninitialized state and do lazy initialization.
12250b57cec5SDimitry Andric   initializeIfNeeded();
12260b57cec5SDimitry Andric 
12270b57cec5SDimitry Andric   // Find the MDNode in the module map
12280b57cec5SDimitry Andric   mdn_iterator MI = mdnMap.find(N);
12290b57cec5SDimitry Andric   return MI == mdnMap.end() ? -1 : (int)MI->second;
12300b57cec5SDimitry Andric }
12310b57cec5SDimitry Andric 
12320b57cec5SDimitry Andric /// getLocalSlot - Get the slot number for a value that is local to a function.
getLocalSlot(const Value * V)12330b57cec5SDimitry Andric int SlotTracker::getLocalSlot(const Value *V) {
12340b57cec5SDimitry Andric   assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
12350b57cec5SDimitry Andric 
12360b57cec5SDimitry Andric   // Check for uninitialized state and do lazy initialization.
12370b57cec5SDimitry Andric   initializeIfNeeded();
12380b57cec5SDimitry Andric 
12390b57cec5SDimitry Andric   ValueMap::iterator FI = fMap.find(V);
12400b57cec5SDimitry Andric   return FI == fMap.end() ? -1 : (int)FI->second;
12410b57cec5SDimitry Andric }
12420b57cec5SDimitry Andric 
getAttributeGroupSlot(AttributeSet AS)12430b57cec5SDimitry Andric int SlotTracker::getAttributeGroupSlot(AttributeSet AS) {
12440b57cec5SDimitry Andric   // Check for uninitialized state and do lazy initialization.
12450b57cec5SDimitry Andric   initializeIfNeeded();
12460b57cec5SDimitry Andric 
12470b57cec5SDimitry Andric   // Find the AttributeSet in the module map.
12480b57cec5SDimitry Andric   as_iterator AI = asMap.find(AS);
12490b57cec5SDimitry Andric   return AI == asMap.end() ? -1 : (int)AI->second;
12500b57cec5SDimitry Andric }
12510b57cec5SDimitry Andric 
getModulePathSlot(StringRef Path)12520b57cec5SDimitry Andric int SlotTracker::getModulePathSlot(StringRef Path) {
12530b57cec5SDimitry Andric   // Check for uninitialized state and do lazy initialization.
12540b57cec5SDimitry Andric   initializeIndexIfNeeded();
12550b57cec5SDimitry Andric 
12560b57cec5SDimitry Andric   // Find the Module path in the map
12570b57cec5SDimitry Andric   auto I = ModulePathMap.find(Path);
12580b57cec5SDimitry Andric   return I == ModulePathMap.end() ? -1 : (int)I->second;
12590b57cec5SDimitry Andric }
12600b57cec5SDimitry Andric 
getGUIDSlot(GlobalValue::GUID GUID)12610b57cec5SDimitry Andric int SlotTracker::getGUIDSlot(GlobalValue::GUID GUID) {
12620b57cec5SDimitry Andric   // Check for uninitialized state and do lazy initialization.
12630b57cec5SDimitry Andric   initializeIndexIfNeeded();
12640b57cec5SDimitry Andric 
12650b57cec5SDimitry Andric   // Find the GUID in the map
12660b57cec5SDimitry Andric   guid_iterator I = GUIDMap.find(GUID);
12670b57cec5SDimitry Andric   return I == GUIDMap.end() ? -1 : (int)I->second;
12680b57cec5SDimitry Andric }
12690b57cec5SDimitry Andric 
getTypeIdSlot(StringRef Id)12700b57cec5SDimitry Andric int SlotTracker::getTypeIdSlot(StringRef Id) {
12710b57cec5SDimitry Andric   // Check for uninitialized state and do lazy initialization.
12720b57cec5SDimitry Andric   initializeIndexIfNeeded();
12730b57cec5SDimitry Andric 
12740b57cec5SDimitry Andric   // Find the TypeId string in the map
12750b57cec5SDimitry Andric   auto I = TypeIdMap.find(Id);
12760b57cec5SDimitry Andric   return I == TypeIdMap.end() ? -1 : (int)I->second;
12770b57cec5SDimitry Andric }
12780b57cec5SDimitry Andric 
getTypeIdCompatibleVtableSlot(StringRef Id)12795f757f3fSDimitry Andric int SlotTracker::getTypeIdCompatibleVtableSlot(StringRef Id) {
12805f757f3fSDimitry Andric   // Check for uninitialized state and do lazy initialization.
12815f757f3fSDimitry Andric   initializeIndexIfNeeded();
12825f757f3fSDimitry Andric 
12835f757f3fSDimitry Andric   // Find the TypeIdCompatibleVtable string in the map
12845f757f3fSDimitry Andric   auto I = TypeIdCompatibleVtableMap.find(Id);
12855f757f3fSDimitry Andric   return I == TypeIdCompatibleVtableMap.end() ? -1 : (int)I->second;
12865f757f3fSDimitry Andric }
12875f757f3fSDimitry Andric 
12880b57cec5SDimitry Andric /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
CreateModuleSlot(const GlobalValue * V)12890b57cec5SDimitry Andric void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
12900b57cec5SDimitry Andric   assert(V && "Can't insert a null Value into SlotTracker!");
12910b57cec5SDimitry Andric   assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
12920b57cec5SDimitry Andric   assert(!V->hasName() && "Doesn't need a slot!");
12930b57cec5SDimitry Andric 
12940b57cec5SDimitry Andric   unsigned DestSlot = mNext++;
12950b57cec5SDimitry Andric   mMap[V] = DestSlot;
12960b57cec5SDimitry Andric 
12970b57cec5SDimitry Andric   ST_DEBUG("  Inserting value [" << V->getType() << "] = " << V << " slot=" <<
12980b57cec5SDimitry Andric            DestSlot << " [");
12990b57cec5SDimitry Andric   // G = Global, F = Function, A = Alias, I = IFunc, o = other
13000b57cec5SDimitry Andric   ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
13010b57cec5SDimitry Andric             (isa<Function>(V) ? 'F' :
13020b57cec5SDimitry Andric              (isa<GlobalAlias>(V) ? 'A' :
13030b57cec5SDimitry Andric               (isa<GlobalIFunc>(V) ? 'I' : 'o')))) << "]\n");
13040b57cec5SDimitry Andric }
13050b57cec5SDimitry Andric 
13060b57cec5SDimitry Andric /// CreateSlot - Create a new slot for the specified value if it has no name.
CreateFunctionSlot(const Value * V)13070b57cec5SDimitry Andric void SlotTracker::CreateFunctionSlot(const Value *V) {
13080b57cec5SDimitry Andric   assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
13090b57cec5SDimitry Andric 
13100b57cec5SDimitry Andric   unsigned DestSlot = fNext++;
13110b57cec5SDimitry Andric   fMap[V] = DestSlot;
13120b57cec5SDimitry Andric 
13130b57cec5SDimitry Andric   // G = Global, F = Function, o = other
13140b57cec5SDimitry Andric   ST_DEBUG("  Inserting value [" << V->getType() << "] = " << V << " slot=" <<
13150b57cec5SDimitry Andric            DestSlot << " [o]\n");
13160b57cec5SDimitry Andric }
13170b57cec5SDimitry Andric 
13180b57cec5SDimitry Andric /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
CreateMetadataSlot(const MDNode * N)13190b57cec5SDimitry Andric void SlotTracker::CreateMetadataSlot(const MDNode *N) {
13200b57cec5SDimitry Andric   assert(N && "Can't insert a null Value into SlotTracker!");
13210b57cec5SDimitry Andric 
13225f757f3fSDimitry Andric   // Don't make slots for DIExpressions. We just print them inline everywhere.
13235f757f3fSDimitry Andric   if (isa<DIExpression>(N))
13240b57cec5SDimitry Andric     return;
13250b57cec5SDimitry Andric 
13260b57cec5SDimitry Andric   unsigned DestSlot = mdnNext;
13270b57cec5SDimitry Andric   if (!mdnMap.insert(std::make_pair(N, DestSlot)).second)
13280b57cec5SDimitry Andric     return;
13290b57cec5SDimitry Andric   ++mdnNext;
13300b57cec5SDimitry Andric 
13310b57cec5SDimitry Andric   // Recursively add any MDNodes referenced by operands.
13320b57cec5SDimitry Andric   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
13330b57cec5SDimitry Andric     if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
13340b57cec5SDimitry Andric       CreateMetadataSlot(Op);
13350b57cec5SDimitry Andric }
13360b57cec5SDimitry Andric 
CreateAttributeSetSlot(AttributeSet AS)13370b57cec5SDimitry Andric void SlotTracker::CreateAttributeSetSlot(AttributeSet AS) {
13380b57cec5SDimitry Andric   assert(AS.hasAttributes() && "Doesn't need a slot!");
13390b57cec5SDimitry Andric 
13400b57cec5SDimitry Andric   as_iterator I = asMap.find(AS);
13410b57cec5SDimitry Andric   if (I != asMap.end())
13420b57cec5SDimitry Andric     return;
13430b57cec5SDimitry Andric 
13440b57cec5SDimitry Andric   unsigned DestSlot = asNext++;
13450b57cec5SDimitry Andric   asMap[AS] = DestSlot;
13460b57cec5SDimitry Andric }
13470b57cec5SDimitry Andric 
13480b57cec5SDimitry Andric /// Create a new slot for the specified Module
CreateModulePathSlot(StringRef Path)13490b57cec5SDimitry Andric void SlotTracker::CreateModulePathSlot(StringRef Path) {
13500b57cec5SDimitry Andric   ModulePathMap[Path] = ModulePathNext++;
13510b57cec5SDimitry Andric }
13520b57cec5SDimitry Andric 
13530b57cec5SDimitry Andric /// Create a new slot for the specified GUID
CreateGUIDSlot(GlobalValue::GUID GUID)13540b57cec5SDimitry Andric void SlotTracker::CreateGUIDSlot(GlobalValue::GUID GUID) {
13550b57cec5SDimitry Andric   GUIDMap[GUID] = GUIDNext++;
13560b57cec5SDimitry Andric }
13570b57cec5SDimitry Andric 
13580b57cec5SDimitry Andric /// Create a new slot for the specified Id
CreateTypeIdSlot(StringRef Id)13590b57cec5SDimitry Andric void SlotTracker::CreateTypeIdSlot(StringRef Id) {
13600b57cec5SDimitry Andric   TypeIdMap[Id] = TypeIdNext++;
13610b57cec5SDimitry Andric }
13620b57cec5SDimitry Andric 
13635f757f3fSDimitry Andric /// Create a new slot for the specified Id
CreateTypeIdCompatibleVtableSlot(StringRef Id)13645f757f3fSDimitry Andric void SlotTracker::CreateTypeIdCompatibleVtableSlot(StringRef Id) {
13655f757f3fSDimitry Andric   TypeIdCompatibleVtableMap[Id] = TypeIdCompatibleVtableNext++;
13665f757f3fSDimitry Andric }
13675f757f3fSDimitry Andric 
1368349cc55cSDimitry Andric namespace {
1369349cc55cSDimitry Andric /// Common instances used by most of the printer functions.
1370349cc55cSDimitry Andric struct AsmWriterContext {
1371349cc55cSDimitry Andric   TypePrinting *TypePrinter = nullptr;
1372349cc55cSDimitry Andric   SlotTracker *Machine = nullptr;
1373349cc55cSDimitry Andric   const Module *Context = nullptr;
1374349cc55cSDimitry Andric 
AsmWriterContext__anon33b632580511::AsmWriterContext1375349cc55cSDimitry Andric   AsmWriterContext(TypePrinting *TP, SlotTracker *ST, const Module *M = nullptr)
1376349cc55cSDimitry Andric       : TypePrinter(TP), Machine(ST), Context(M) {}
1377349cc55cSDimitry Andric 
getEmpty__anon33b632580511::AsmWriterContext1378349cc55cSDimitry Andric   static AsmWriterContext &getEmpty() {
1379349cc55cSDimitry Andric     static AsmWriterContext EmptyCtx(nullptr, nullptr);
1380349cc55cSDimitry Andric     return EmptyCtx;
1381349cc55cSDimitry Andric   }
1382349cc55cSDimitry Andric 
1383349cc55cSDimitry Andric   /// A callback that will be triggered when the underlying printer
1384349cc55cSDimitry Andric   /// prints a Metadata as operand.
onWriteMetadataAsOperand__anon33b632580511::AsmWriterContext1385349cc55cSDimitry Andric   virtual void onWriteMetadataAsOperand(const Metadata *) {}
1386349cc55cSDimitry Andric 
138781ad6265SDimitry Andric   virtual ~AsmWriterContext() = default;
1388349cc55cSDimitry Andric };
1389349cc55cSDimitry Andric } // end anonymous namespace
1390349cc55cSDimitry Andric 
13910b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
13920b57cec5SDimitry Andric // AsmWriter Implementation
13930b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
13940b57cec5SDimitry Andric 
13950b57cec5SDimitry Andric static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1396349cc55cSDimitry Andric                                    AsmWriterContext &WriterCtx);
13970b57cec5SDimitry Andric 
13980b57cec5SDimitry Andric static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
1399349cc55cSDimitry Andric                                    AsmWriterContext &WriterCtx,
14000b57cec5SDimitry Andric                                    bool FromValue = false);
14010b57cec5SDimitry Andric 
WriteOptimizationInfo(raw_ostream & Out,const User * U)14020b57cec5SDimitry Andric static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
14034824e7fdSDimitry Andric   if (const FPMathOperator *FPO = dyn_cast<const FPMathOperator>(U))
14044824e7fdSDimitry Andric     Out << FPO->getFastMathFlags();
14050b57cec5SDimitry Andric 
14060b57cec5SDimitry Andric   if (const OverflowingBinaryOperator *OBO =
14070b57cec5SDimitry Andric         dyn_cast<OverflowingBinaryOperator>(U)) {
14080b57cec5SDimitry Andric     if (OBO->hasNoUnsignedWrap())
14090b57cec5SDimitry Andric       Out << " nuw";
14100b57cec5SDimitry Andric     if (OBO->hasNoSignedWrap())
14110b57cec5SDimitry Andric       Out << " nsw";
14120b57cec5SDimitry Andric   } else if (const PossiblyExactOperator *Div =
14130b57cec5SDimitry Andric                dyn_cast<PossiblyExactOperator>(U)) {
14140b57cec5SDimitry Andric     if (Div->isExact())
14150b57cec5SDimitry Andric       Out << " exact";
14165f757f3fSDimitry Andric   } else if (const PossiblyDisjointInst *PDI =
14175f757f3fSDimitry Andric                  dyn_cast<PossiblyDisjointInst>(U)) {
14185f757f3fSDimitry Andric     if (PDI->isDisjoint())
14195f757f3fSDimitry Andric       Out << " disjoint";
14200b57cec5SDimitry Andric   } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
14210b57cec5SDimitry Andric     if (GEP->isInBounds())
14220b57cec5SDimitry Andric       Out << " inbounds";
1423*0fca6ea1SDimitry Andric     else if (GEP->hasNoUnsignedSignedWrap())
1424*0fca6ea1SDimitry Andric       Out << " nusw";
1425*0fca6ea1SDimitry Andric     if (GEP->hasNoUnsignedWrap())
1426*0fca6ea1SDimitry Andric       Out << " nuw";
1427*0fca6ea1SDimitry Andric     if (auto InRange = GEP->getInRange()) {
1428*0fca6ea1SDimitry Andric       Out << " inrange(" << InRange->getLower() << ", " << InRange->getUpper()
1429*0fca6ea1SDimitry Andric           << ")";
1430*0fca6ea1SDimitry Andric     }
14315f757f3fSDimitry Andric   } else if (const auto *NNI = dyn_cast<PossiblyNonNegInst>(U)) {
14325f757f3fSDimitry Andric     if (NNI->hasNonNeg())
14335f757f3fSDimitry Andric       Out << " nneg";
1434*0fca6ea1SDimitry Andric   } else if (const auto *TI = dyn_cast<TruncInst>(U)) {
1435*0fca6ea1SDimitry Andric     if (TI->hasNoUnsignedWrap())
1436*0fca6ea1SDimitry Andric       Out << " nuw";
1437*0fca6ea1SDimitry Andric     if (TI->hasNoSignedWrap())
1438*0fca6ea1SDimitry Andric       Out << " nsw";
14390b57cec5SDimitry Andric   }
14400b57cec5SDimitry Andric }
14410b57cec5SDimitry Andric 
WriteAPFloatInternal(raw_ostream & Out,const APFloat & APF)1442*0fca6ea1SDimitry Andric static void WriteAPFloatInternal(raw_ostream &Out, const APFloat &APF) {
14430b57cec5SDimitry Andric   if (&APF.getSemantics() == &APFloat::IEEEsingle() ||
14440b57cec5SDimitry Andric       &APF.getSemantics() == &APFloat::IEEEdouble()) {
14450b57cec5SDimitry Andric     // We would like to output the FP constant value in exponential notation,
14460b57cec5SDimitry Andric     // but we cannot do this if doing so will lose precision.  Check here to
14470b57cec5SDimitry Andric     // make sure that we only output it in exponential format if we can parse
14480b57cec5SDimitry Andric     // the value back and get the same value.
14490b57cec5SDimitry Andric     //
14500b57cec5SDimitry Andric     bool ignored;
14510b57cec5SDimitry Andric     bool isDouble = &APF.getSemantics() == &APFloat::IEEEdouble();
14520b57cec5SDimitry Andric     bool isInf = APF.isInfinity();
14530b57cec5SDimitry Andric     bool isNaN = APF.isNaN();
1454*0fca6ea1SDimitry Andric 
14550b57cec5SDimitry Andric     if (!isInf && !isNaN) {
1456fe6060f1SDimitry Andric       double Val = APF.convertToDouble();
14570b57cec5SDimitry Andric       SmallString<128> StrVal;
14580b57cec5SDimitry Andric       APF.toString(StrVal, 6, 0, false);
14590b57cec5SDimitry Andric       // Check to make sure that the stringized number is not some string like
14600b57cec5SDimitry Andric       // "Inf" or NaN, that atof will accept, but the lexer will not.  Check
14610b57cec5SDimitry Andric       // that the string matches the "[-+]?[0-9]" regex.
14620b57cec5SDimitry Andric       //
1463*0fca6ea1SDimitry Andric       assert((isDigit(StrVal[0]) ||
1464*0fca6ea1SDimitry Andric               ((StrVal[0] == '-' || StrVal[0] == '+') && isDigit(StrVal[1]))) &&
14650b57cec5SDimitry Andric              "[-+]?[0-9] regex does not match!");
14660b57cec5SDimitry Andric       // Reparse stringized version!
14670b57cec5SDimitry Andric       if (APFloat(APFloat::IEEEdouble(), StrVal).convertToDouble() == Val) {
14680b57cec5SDimitry Andric         Out << StrVal;
14690b57cec5SDimitry Andric         return;
14700b57cec5SDimitry Andric       }
14710b57cec5SDimitry Andric     }
1472*0fca6ea1SDimitry Andric 
14730b57cec5SDimitry Andric     // Otherwise we could not reparse it to exactly the same value, so we must
14740b57cec5SDimitry Andric     // output the string in hexadecimal format!  Note that loading and storing
14750b57cec5SDimitry Andric     // floating point types changes the bits of NaNs on some hosts, notably
14760b57cec5SDimitry Andric     // x86, so we must not use these types.
14770b57cec5SDimitry Andric     static_assert(sizeof(double) == sizeof(uint64_t),
14780b57cec5SDimitry Andric                   "assuming that double is 64 bits!");
14790b57cec5SDimitry Andric     APFloat apf = APF;
1480*0fca6ea1SDimitry Andric 
14810b57cec5SDimitry Andric     // Floats are represented in ASCII IR as double, convert.
1482e8d8bef9SDimitry Andric     // FIXME: We should allow 32-bit hex float and remove this.
1483e8d8bef9SDimitry Andric     if (!isDouble) {
1484e8d8bef9SDimitry Andric       // A signaling NaN is quieted on conversion, so we need to recreate the
1485e8d8bef9SDimitry Andric       // expected value after convert (quiet bit of the payload is clear).
1486e8d8bef9SDimitry Andric       bool IsSNAN = apf.isSignaling();
14870b57cec5SDimitry Andric       apf.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven,
14880b57cec5SDimitry Andric                   &ignored);
1489e8d8bef9SDimitry Andric       if (IsSNAN) {
1490e8d8bef9SDimitry Andric         APInt Payload = apf.bitcastToAPInt();
1491*0fca6ea1SDimitry Andric         apf =
1492*0fca6ea1SDimitry Andric             APFloat::getSNaN(APFloat::IEEEdouble(), apf.isNegative(), &Payload);
1493e8d8bef9SDimitry Andric       }
1494e8d8bef9SDimitry Andric     }
1495*0fca6ea1SDimitry Andric 
14960b57cec5SDimitry Andric     Out << format_hex(apf.bitcastToAPInt().getZExtValue(), 0, /*Upper=*/true);
14970b57cec5SDimitry Andric     return;
14980b57cec5SDimitry Andric   }
14990b57cec5SDimitry Andric 
15005ffd83dbSDimitry Andric   // Either half, bfloat or some form of long double.
15010b57cec5SDimitry Andric   // These appear as a magic letter identifying the type, then a
15020b57cec5SDimitry Andric   // fixed number of hex digits.
15030b57cec5SDimitry Andric   Out << "0x";
15040b57cec5SDimitry Andric   APInt API = APF.bitcastToAPInt();
15050b57cec5SDimitry Andric   if (&APF.getSemantics() == &APFloat::x87DoubleExtended()) {
15060b57cec5SDimitry Andric     Out << 'K';
15070b57cec5SDimitry Andric     Out << format_hex_no_prefix(API.getHiBits(16).getZExtValue(), 4,
15080b57cec5SDimitry Andric                                 /*Upper=*/true);
15090b57cec5SDimitry Andric     Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
15100b57cec5SDimitry Andric                                 /*Upper=*/true);
15110b57cec5SDimitry Andric   } else if (&APF.getSemantics() == &APFloat::IEEEquad()) {
15120b57cec5SDimitry Andric     Out << 'L';
15130b57cec5SDimitry Andric     Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
15140b57cec5SDimitry Andric                                 /*Upper=*/true);
15150b57cec5SDimitry Andric     Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16,
15160b57cec5SDimitry Andric                                 /*Upper=*/true);
15170b57cec5SDimitry Andric   } else if (&APF.getSemantics() == &APFloat::PPCDoubleDouble()) {
15180b57cec5SDimitry Andric     Out << 'M';
15190b57cec5SDimitry Andric     Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
15200b57cec5SDimitry Andric                                 /*Upper=*/true);
15210b57cec5SDimitry Andric     Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16,
15220b57cec5SDimitry Andric                                 /*Upper=*/true);
15230b57cec5SDimitry Andric   } else if (&APF.getSemantics() == &APFloat::IEEEhalf()) {
15240b57cec5SDimitry Andric     Out << 'H';
15250b57cec5SDimitry Andric     Out << format_hex_no_prefix(API.getZExtValue(), 4,
15260b57cec5SDimitry Andric                                 /*Upper=*/true);
15275ffd83dbSDimitry Andric   } else if (&APF.getSemantics() == &APFloat::BFloat()) {
15285ffd83dbSDimitry Andric     Out << 'R';
15295ffd83dbSDimitry Andric     Out << format_hex_no_prefix(API.getZExtValue(), 4,
15305ffd83dbSDimitry Andric                                 /*Upper=*/true);
15310b57cec5SDimitry Andric   } else
15320b57cec5SDimitry Andric     llvm_unreachable("Unsupported floating point type");
1533*0fca6ea1SDimitry Andric }
1534*0fca6ea1SDimitry Andric 
WriteConstantInternal(raw_ostream & Out,const Constant * CV,AsmWriterContext & WriterCtx)1535*0fca6ea1SDimitry Andric static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
1536*0fca6ea1SDimitry Andric                                   AsmWriterContext &WriterCtx) {
1537*0fca6ea1SDimitry Andric   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1538*0fca6ea1SDimitry Andric     Type *Ty = CI->getType();
1539*0fca6ea1SDimitry Andric 
1540*0fca6ea1SDimitry Andric     if (Ty->isVectorTy()) {
1541*0fca6ea1SDimitry Andric       Out << "splat (";
1542*0fca6ea1SDimitry Andric       WriterCtx.TypePrinter->print(Ty->getScalarType(), Out);
1543*0fca6ea1SDimitry Andric       Out << " ";
1544*0fca6ea1SDimitry Andric     }
1545*0fca6ea1SDimitry Andric 
1546*0fca6ea1SDimitry Andric     if (Ty->getScalarType()->isIntegerTy(1))
1547*0fca6ea1SDimitry Andric       Out << (CI->getZExtValue() ? "true" : "false");
1548*0fca6ea1SDimitry Andric     else
1549*0fca6ea1SDimitry Andric       Out << CI->getValue();
1550*0fca6ea1SDimitry Andric 
1551*0fca6ea1SDimitry Andric     if (Ty->isVectorTy())
1552*0fca6ea1SDimitry Andric       Out << ")";
1553*0fca6ea1SDimitry Andric 
1554*0fca6ea1SDimitry Andric     return;
1555*0fca6ea1SDimitry Andric   }
1556*0fca6ea1SDimitry Andric 
1557*0fca6ea1SDimitry Andric   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
1558*0fca6ea1SDimitry Andric     Type *Ty = CFP->getType();
1559*0fca6ea1SDimitry Andric 
1560*0fca6ea1SDimitry Andric     if (Ty->isVectorTy()) {
1561*0fca6ea1SDimitry Andric       Out << "splat (";
1562*0fca6ea1SDimitry Andric       WriterCtx.TypePrinter->print(Ty->getScalarType(), Out);
1563*0fca6ea1SDimitry Andric       Out << " ";
1564*0fca6ea1SDimitry Andric     }
1565*0fca6ea1SDimitry Andric 
1566*0fca6ea1SDimitry Andric     WriteAPFloatInternal(Out, CFP->getValueAPF());
1567*0fca6ea1SDimitry Andric 
1568*0fca6ea1SDimitry Andric     if (Ty->isVectorTy())
1569*0fca6ea1SDimitry Andric       Out << ")";
1570*0fca6ea1SDimitry Andric 
15710b57cec5SDimitry Andric     return;
15720b57cec5SDimitry Andric   }
15730b57cec5SDimitry Andric 
1574bdd1243dSDimitry Andric   if (isa<ConstantAggregateZero>(CV) || isa<ConstantTargetNone>(CV)) {
15750b57cec5SDimitry Andric     Out << "zeroinitializer";
15760b57cec5SDimitry Andric     return;
15770b57cec5SDimitry Andric   }
15780b57cec5SDimitry Andric 
15790b57cec5SDimitry Andric   if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
15800b57cec5SDimitry Andric     Out << "blockaddress(";
1581349cc55cSDimitry Andric     WriteAsOperandInternal(Out, BA->getFunction(), WriterCtx);
15820b57cec5SDimitry Andric     Out << ", ";
1583349cc55cSDimitry Andric     WriteAsOperandInternal(Out, BA->getBasicBlock(), WriterCtx);
15840b57cec5SDimitry Andric     Out << ")";
15850b57cec5SDimitry Andric     return;
15860b57cec5SDimitry Andric   }
15870b57cec5SDimitry Andric 
1588e8d8bef9SDimitry Andric   if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(CV)) {
1589e8d8bef9SDimitry Andric     Out << "dso_local_equivalent ";
1590349cc55cSDimitry Andric     WriteAsOperandInternal(Out, Equiv->getGlobalValue(), WriterCtx);
1591e8d8bef9SDimitry Andric     return;
1592e8d8bef9SDimitry Andric   }
1593e8d8bef9SDimitry Andric 
15940eae32dcSDimitry Andric   if (const auto *NC = dyn_cast<NoCFIValue>(CV)) {
15950eae32dcSDimitry Andric     Out << "no_cfi ";
15960eae32dcSDimitry Andric     WriteAsOperandInternal(Out, NC->getGlobalValue(), WriterCtx);
15970eae32dcSDimitry Andric     return;
15980eae32dcSDimitry Andric   }
15990eae32dcSDimitry Andric 
1600*0fca6ea1SDimitry Andric   if (const ConstantPtrAuth *CPA = dyn_cast<ConstantPtrAuth>(CV)) {
1601*0fca6ea1SDimitry Andric     Out << "ptrauth (";
1602*0fca6ea1SDimitry Andric 
1603*0fca6ea1SDimitry Andric     // ptrauth (ptr CST, i32 KEY[, i64 DISC[, ptr ADDRDISC]?]?)
1604*0fca6ea1SDimitry Andric     unsigned NumOpsToWrite = 2;
1605*0fca6ea1SDimitry Andric     if (!CPA->getOperand(2)->isNullValue())
1606*0fca6ea1SDimitry Andric       NumOpsToWrite = 3;
1607*0fca6ea1SDimitry Andric     if (!CPA->getOperand(3)->isNullValue())
1608*0fca6ea1SDimitry Andric       NumOpsToWrite = 4;
1609*0fca6ea1SDimitry Andric 
1610*0fca6ea1SDimitry Andric     ListSeparator LS;
1611*0fca6ea1SDimitry Andric     for (unsigned i = 0, e = NumOpsToWrite; i != e; ++i) {
1612*0fca6ea1SDimitry Andric       Out << LS;
1613*0fca6ea1SDimitry Andric       WriterCtx.TypePrinter->print(CPA->getOperand(i)->getType(), Out);
1614*0fca6ea1SDimitry Andric       Out << ' ';
1615*0fca6ea1SDimitry Andric       WriteAsOperandInternal(Out, CPA->getOperand(i), WriterCtx);
1616*0fca6ea1SDimitry Andric     }
1617*0fca6ea1SDimitry Andric     Out << ')';
1618*0fca6ea1SDimitry Andric     return;
1619*0fca6ea1SDimitry Andric   }
1620*0fca6ea1SDimitry Andric 
16210b57cec5SDimitry Andric   if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
16220b57cec5SDimitry Andric     Type *ETy = CA->getType()->getElementType();
16230b57cec5SDimitry Andric     Out << '[';
1624349cc55cSDimitry Andric     WriterCtx.TypePrinter->print(ETy, Out);
16250b57cec5SDimitry Andric     Out << ' ';
1626349cc55cSDimitry Andric     WriteAsOperandInternal(Out, CA->getOperand(0), WriterCtx);
16270b57cec5SDimitry Andric     for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
16280b57cec5SDimitry Andric       Out << ", ";
1629349cc55cSDimitry Andric       WriterCtx.TypePrinter->print(ETy, Out);
16300b57cec5SDimitry Andric       Out << ' ';
1631349cc55cSDimitry Andric       WriteAsOperandInternal(Out, CA->getOperand(i), WriterCtx);
16320b57cec5SDimitry Andric     }
16330b57cec5SDimitry Andric     Out << ']';
16340b57cec5SDimitry Andric     return;
16350b57cec5SDimitry Andric   }
16360b57cec5SDimitry Andric 
16370b57cec5SDimitry Andric   if (const ConstantDataArray *CA = dyn_cast<ConstantDataArray>(CV)) {
16380b57cec5SDimitry Andric     // As a special case, print the array as a string if it is an array of
16390b57cec5SDimitry Andric     // i8 with ConstantInt values.
16400b57cec5SDimitry Andric     if (CA->isString()) {
16410b57cec5SDimitry Andric       Out << "c\"";
16420b57cec5SDimitry Andric       printEscapedString(CA->getAsString(), Out);
16430b57cec5SDimitry Andric       Out << '"';
16440b57cec5SDimitry Andric       return;
16450b57cec5SDimitry Andric     }
16460b57cec5SDimitry Andric 
16470b57cec5SDimitry Andric     Type *ETy = CA->getType()->getElementType();
16480b57cec5SDimitry Andric     Out << '[';
1649349cc55cSDimitry Andric     WriterCtx.TypePrinter->print(ETy, Out);
16500b57cec5SDimitry Andric     Out << ' ';
1651349cc55cSDimitry Andric     WriteAsOperandInternal(Out, CA->getElementAsConstant(0), WriterCtx);
16520b57cec5SDimitry Andric     for (unsigned i = 1, e = CA->getNumElements(); i != e; ++i) {
16530b57cec5SDimitry Andric       Out << ", ";
1654349cc55cSDimitry Andric       WriterCtx.TypePrinter->print(ETy, Out);
16550b57cec5SDimitry Andric       Out << ' ';
1656349cc55cSDimitry Andric       WriteAsOperandInternal(Out, CA->getElementAsConstant(i), WriterCtx);
16570b57cec5SDimitry Andric     }
16580b57cec5SDimitry Andric     Out << ']';
16590b57cec5SDimitry Andric     return;
16600b57cec5SDimitry Andric   }
16610b57cec5SDimitry Andric 
16620b57cec5SDimitry Andric   if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
16630b57cec5SDimitry Andric     if (CS->getType()->isPacked())
16640b57cec5SDimitry Andric       Out << '<';
16650b57cec5SDimitry Andric     Out << '{';
16660b57cec5SDimitry Andric     unsigned N = CS->getNumOperands();
16670b57cec5SDimitry Andric     if (N) {
16680b57cec5SDimitry Andric       Out << ' ';
1669349cc55cSDimitry Andric       WriterCtx.TypePrinter->print(CS->getOperand(0)->getType(), Out);
16700b57cec5SDimitry Andric       Out << ' ';
16710b57cec5SDimitry Andric 
1672349cc55cSDimitry Andric       WriteAsOperandInternal(Out, CS->getOperand(0), WriterCtx);
16730b57cec5SDimitry Andric 
16740b57cec5SDimitry Andric       for (unsigned i = 1; i < N; i++) {
16750b57cec5SDimitry Andric         Out << ", ";
1676349cc55cSDimitry Andric         WriterCtx.TypePrinter->print(CS->getOperand(i)->getType(), Out);
16770b57cec5SDimitry Andric         Out << ' ';
16780b57cec5SDimitry Andric 
1679349cc55cSDimitry Andric         WriteAsOperandInternal(Out, CS->getOperand(i), WriterCtx);
16800b57cec5SDimitry Andric       }
16810b57cec5SDimitry Andric       Out << ' ';
16820b57cec5SDimitry Andric     }
16830b57cec5SDimitry Andric 
16840b57cec5SDimitry Andric     Out << '}';
16850b57cec5SDimitry Andric     if (CS->getType()->isPacked())
16860b57cec5SDimitry Andric       Out << '>';
16870b57cec5SDimitry Andric     return;
16880b57cec5SDimitry Andric   }
16890b57cec5SDimitry Andric 
16900b57cec5SDimitry Andric   if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) {
1691e8d8bef9SDimitry Andric     auto *CVVTy = cast<FixedVectorType>(CV->getType());
16925ffd83dbSDimitry Andric     Type *ETy = CVVTy->getElementType();
16930b57cec5SDimitry Andric     Out << '<';
1694349cc55cSDimitry Andric     WriterCtx.TypePrinter->print(ETy, Out);
16950b57cec5SDimitry Andric     Out << ' ';
1696349cc55cSDimitry Andric     WriteAsOperandInternal(Out, CV->getAggregateElement(0U), WriterCtx);
16975ffd83dbSDimitry Andric     for (unsigned i = 1, e = CVVTy->getNumElements(); i != e; ++i) {
16980b57cec5SDimitry Andric       Out << ", ";
1699349cc55cSDimitry Andric       WriterCtx.TypePrinter->print(ETy, Out);
17000b57cec5SDimitry Andric       Out << ' ';
1701349cc55cSDimitry Andric       WriteAsOperandInternal(Out, CV->getAggregateElement(i), WriterCtx);
17020b57cec5SDimitry Andric     }
17030b57cec5SDimitry Andric     Out << '>';
17040b57cec5SDimitry Andric     return;
17050b57cec5SDimitry Andric   }
17060b57cec5SDimitry Andric 
17070b57cec5SDimitry Andric   if (isa<ConstantPointerNull>(CV)) {
17080b57cec5SDimitry Andric     Out << "null";
17090b57cec5SDimitry Andric     return;
17100b57cec5SDimitry Andric   }
17110b57cec5SDimitry Andric 
17120b57cec5SDimitry Andric   if (isa<ConstantTokenNone>(CV)) {
17130b57cec5SDimitry Andric     Out << "none";
17140b57cec5SDimitry Andric     return;
17150b57cec5SDimitry Andric   }
17160b57cec5SDimitry Andric 
1717e8d8bef9SDimitry Andric   if (isa<PoisonValue>(CV)) {
1718e8d8bef9SDimitry Andric     Out << "poison";
1719e8d8bef9SDimitry Andric     return;
1720e8d8bef9SDimitry Andric   }
1721e8d8bef9SDimitry Andric 
17220b57cec5SDimitry Andric   if (isa<UndefValue>(CV)) {
17230b57cec5SDimitry Andric     Out << "undef";
17240b57cec5SDimitry Andric     return;
17250b57cec5SDimitry Andric   }
17260b57cec5SDimitry Andric 
17270b57cec5SDimitry Andric   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
17280b57cec5SDimitry Andric     Out << CE->getOpcodeName();
17290b57cec5SDimitry Andric     WriteOptimizationInfo(Out, CE);
17300b57cec5SDimitry Andric     Out << " (";
17310b57cec5SDimitry Andric 
17320b57cec5SDimitry Andric     if (const GEPOperator *GEP = dyn_cast<GEPOperator>(CE)) {
1733349cc55cSDimitry Andric       WriterCtx.TypePrinter->print(GEP->getSourceElementType(), Out);
17340b57cec5SDimitry Andric       Out << ", ";
17350b57cec5SDimitry Andric     }
17360b57cec5SDimitry Andric 
1737*0fca6ea1SDimitry Andric     for (User::const_op_iterator OI = CE->op_begin(); OI != CE->op_end();
1738*0fca6ea1SDimitry Andric          ++OI) {
1739349cc55cSDimitry Andric       WriterCtx.TypePrinter->print((*OI)->getType(), Out);
17400b57cec5SDimitry Andric       Out << ' ';
1741349cc55cSDimitry Andric       WriteAsOperandInternal(Out, *OI, WriterCtx);
17420b57cec5SDimitry Andric       if (OI+1 != CE->op_end())
17430b57cec5SDimitry Andric         Out << ", ";
17440b57cec5SDimitry Andric     }
17450b57cec5SDimitry Andric 
17460b57cec5SDimitry Andric     if (CE->isCast()) {
17470b57cec5SDimitry Andric       Out << " to ";
1748349cc55cSDimitry Andric       WriterCtx.TypePrinter->print(CE->getType(), Out);
17490b57cec5SDimitry Andric     }
17500b57cec5SDimitry Andric 
17515ffd83dbSDimitry Andric     if (CE->getOpcode() == Instruction::ShuffleVector)
17525ffd83dbSDimitry Andric       PrintShuffleMask(Out, CE->getType(), CE->getShuffleMask());
17535ffd83dbSDimitry Andric 
17540b57cec5SDimitry Andric     Out << ')';
17550b57cec5SDimitry Andric     return;
17560b57cec5SDimitry Andric   }
17570b57cec5SDimitry Andric 
17580b57cec5SDimitry Andric   Out << "<placeholder or erroneous Constant>";
17590b57cec5SDimitry Andric }
17600b57cec5SDimitry Andric 
writeMDTuple(raw_ostream & Out,const MDTuple * Node,AsmWriterContext & WriterCtx)17610b57cec5SDimitry Andric static void writeMDTuple(raw_ostream &Out, const MDTuple *Node,
1762349cc55cSDimitry Andric                          AsmWriterContext &WriterCtx) {
17630b57cec5SDimitry Andric   Out << "!{";
17640b57cec5SDimitry Andric   for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
17650b57cec5SDimitry Andric     const Metadata *MD = Node->getOperand(mi);
17660b57cec5SDimitry Andric     if (!MD)
17670b57cec5SDimitry Andric       Out << "null";
17680b57cec5SDimitry Andric     else if (auto *MDV = dyn_cast<ValueAsMetadata>(MD)) {
17690b57cec5SDimitry Andric       Value *V = MDV->getValue();
1770349cc55cSDimitry Andric       WriterCtx.TypePrinter->print(V->getType(), Out);
17710b57cec5SDimitry Andric       Out << ' ';
1772349cc55cSDimitry Andric       WriteAsOperandInternal(Out, V, WriterCtx);
17730b57cec5SDimitry Andric     } else {
1774349cc55cSDimitry Andric       WriteAsOperandInternal(Out, MD, WriterCtx);
1775349cc55cSDimitry Andric       WriterCtx.onWriteMetadataAsOperand(MD);
17760b57cec5SDimitry Andric     }
17770b57cec5SDimitry Andric     if (mi + 1 != me)
17780b57cec5SDimitry Andric       Out << ", ";
17790b57cec5SDimitry Andric   }
17800b57cec5SDimitry Andric 
17810b57cec5SDimitry Andric   Out << "}";
17820b57cec5SDimitry Andric }
17830b57cec5SDimitry Andric 
17840b57cec5SDimitry Andric namespace {
17850b57cec5SDimitry Andric 
17860b57cec5SDimitry Andric struct FieldSeparator {
17870b57cec5SDimitry Andric   bool Skip = true;
17880b57cec5SDimitry Andric   const char *Sep;
17890b57cec5SDimitry Andric 
FieldSeparator__anon33b632580611::FieldSeparator17900b57cec5SDimitry Andric   FieldSeparator(const char *Sep = ", ") : Sep(Sep) {}
17910b57cec5SDimitry Andric };
17920b57cec5SDimitry Andric 
operator <<(raw_ostream & OS,FieldSeparator & FS)17930b57cec5SDimitry Andric raw_ostream &operator<<(raw_ostream &OS, FieldSeparator &FS) {
17940b57cec5SDimitry Andric   if (FS.Skip) {
17950b57cec5SDimitry Andric     FS.Skip = false;
17960b57cec5SDimitry Andric     return OS;
17970b57cec5SDimitry Andric   }
17980b57cec5SDimitry Andric   return OS << FS.Sep;
17990b57cec5SDimitry Andric }
18000b57cec5SDimitry Andric 
18010b57cec5SDimitry Andric struct MDFieldPrinter {
18020b57cec5SDimitry Andric   raw_ostream &Out;
18030b57cec5SDimitry Andric   FieldSeparator FS;
1804349cc55cSDimitry Andric   AsmWriterContext &WriterCtx;
18050b57cec5SDimitry Andric 
MDFieldPrinter__anon33b632580611::MDFieldPrinter1806349cc55cSDimitry Andric   explicit MDFieldPrinter(raw_ostream &Out)
1807349cc55cSDimitry Andric       : Out(Out), WriterCtx(AsmWriterContext::getEmpty()) {}
MDFieldPrinter__anon33b632580611::MDFieldPrinter1808349cc55cSDimitry Andric   MDFieldPrinter(raw_ostream &Out, AsmWriterContext &Ctx)
1809349cc55cSDimitry Andric       : Out(Out), WriterCtx(Ctx) {}
18100b57cec5SDimitry Andric 
18110b57cec5SDimitry Andric   void printTag(const DINode *N);
18120b57cec5SDimitry Andric   void printMacinfoType(const DIMacroNode *N);
18130b57cec5SDimitry Andric   void printChecksum(const DIFile::ChecksumInfo<StringRef> &N);
18140b57cec5SDimitry Andric   void printString(StringRef Name, StringRef Value,
18150b57cec5SDimitry Andric                    bool ShouldSkipEmpty = true);
18160b57cec5SDimitry Andric   void printMetadata(StringRef Name, const Metadata *MD,
18170b57cec5SDimitry Andric                      bool ShouldSkipNull = true);
18180b57cec5SDimitry Andric   template <class IntTy>
18190b57cec5SDimitry Andric   void printInt(StringRef Name, IntTy Int, bool ShouldSkipZero = true);
18205ffd83dbSDimitry Andric   void printAPInt(StringRef Name, const APInt &Int, bool IsUnsigned,
18215ffd83dbSDimitry Andric                   bool ShouldSkipZero);
1822bdd1243dSDimitry Andric   void printBool(StringRef Name, bool Value,
1823bdd1243dSDimitry Andric                  std::optional<bool> Default = std::nullopt);
18240b57cec5SDimitry Andric   void printDIFlags(StringRef Name, DINode::DIFlags Flags);
18250b57cec5SDimitry Andric   void printDISPFlags(StringRef Name, DISubprogram::DISPFlags Flags);
18260b57cec5SDimitry Andric   template <class IntTy, class Stringifier>
18270b57cec5SDimitry Andric   void printDwarfEnum(StringRef Name, IntTy Value, Stringifier toString,
18280b57cec5SDimitry Andric                       bool ShouldSkipZero = true);
18290b57cec5SDimitry Andric   void printEmissionKind(StringRef Name, DICompileUnit::DebugEmissionKind EK);
18300b57cec5SDimitry Andric   void printNameTableKind(StringRef Name,
18310b57cec5SDimitry Andric                           DICompileUnit::DebugNameTableKind NTK);
18320b57cec5SDimitry Andric };
18330b57cec5SDimitry Andric 
18340b57cec5SDimitry Andric } // end anonymous namespace
18350b57cec5SDimitry Andric 
printTag(const DINode * N)18360b57cec5SDimitry Andric void MDFieldPrinter::printTag(const DINode *N) {
18370b57cec5SDimitry Andric   Out << FS << "tag: ";
18380b57cec5SDimitry Andric   auto Tag = dwarf::TagString(N->getTag());
18390b57cec5SDimitry Andric   if (!Tag.empty())
18400b57cec5SDimitry Andric     Out << Tag;
18410b57cec5SDimitry Andric   else
18420b57cec5SDimitry Andric     Out << N->getTag();
18430b57cec5SDimitry Andric }
18440b57cec5SDimitry Andric 
printMacinfoType(const DIMacroNode * N)18450b57cec5SDimitry Andric void MDFieldPrinter::printMacinfoType(const DIMacroNode *N) {
18460b57cec5SDimitry Andric   Out << FS << "type: ";
18470b57cec5SDimitry Andric   auto Type = dwarf::MacinfoString(N->getMacinfoType());
18480b57cec5SDimitry Andric   if (!Type.empty())
18490b57cec5SDimitry Andric     Out << Type;
18500b57cec5SDimitry Andric   else
18510b57cec5SDimitry Andric     Out << N->getMacinfoType();
18520b57cec5SDimitry Andric }
18530b57cec5SDimitry Andric 
printChecksum(const DIFile::ChecksumInfo<StringRef> & Checksum)18540b57cec5SDimitry Andric void MDFieldPrinter::printChecksum(
18550b57cec5SDimitry Andric     const DIFile::ChecksumInfo<StringRef> &Checksum) {
18560b57cec5SDimitry Andric   Out << FS << "checksumkind: " << Checksum.getKindAsString();
18570b57cec5SDimitry Andric   printString("checksum", Checksum.Value, /* ShouldSkipEmpty */ false);
18580b57cec5SDimitry Andric }
18590b57cec5SDimitry Andric 
printString(StringRef Name,StringRef Value,bool ShouldSkipEmpty)18600b57cec5SDimitry Andric void MDFieldPrinter::printString(StringRef Name, StringRef Value,
18610b57cec5SDimitry Andric                                  bool ShouldSkipEmpty) {
18620b57cec5SDimitry Andric   if (ShouldSkipEmpty && Value.empty())
18630b57cec5SDimitry Andric     return;
18640b57cec5SDimitry Andric 
18650b57cec5SDimitry Andric   Out << FS << Name << ": \"";
18660b57cec5SDimitry Andric   printEscapedString(Value, Out);
18670b57cec5SDimitry Andric   Out << "\"";
18680b57cec5SDimitry Andric }
18690b57cec5SDimitry Andric 
writeMetadataAsOperand(raw_ostream & Out,const Metadata * MD,AsmWriterContext & WriterCtx)18700b57cec5SDimitry Andric static void writeMetadataAsOperand(raw_ostream &Out, const Metadata *MD,
1871349cc55cSDimitry Andric                                    AsmWriterContext &WriterCtx) {
18720b57cec5SDimitry Andric   if (!MD) {
18730b57cec5SDimitry Andric     Out << "null";
18740b57cec5SDimitry Andric     return;
18750b57cec5SDimitry Andric   }
1876349cc55cSDimitry Andric   WriteAsOperandInternal(Out, MD, WriterCtx);
1877349cc55cSDimitry Andric   WriterCtx.onWriteMetadataAsOperand(MD);
18780b57cec5SDimitry Andric }
18790b57cec5SDimitry Andric 
printMetadata(StringRef Name,const Metadata * MD,bool ShouldSkipNull)18800b57cec5SDimitry Andric void MDFieldPrinter::printMetadata(StringRef Name, const Metadata *MD,
18810b57cec5SDimitry Andric                                    bool ShouldSkipNull) {
18820b57cec5SDimitry Andric   if (ShouldSkipNull && !MD)
18830b57cec5SDimitry Andric     return;
18840b57cec5SDimitry Andric 
18850b57cec5SDimitry Andric   Out << FS << Name << ": ";
1886349cc55cSDimitry Andric   writeMetadataAsOperand(Out, MD, WriterCtx);
18870b57cec5SDimitry Andric }
18880b57cec5SDimitry Andric 
18890b57cec5SDimitry Andric template <class IntTy>
printInt(StringRef Name,IntTy Int,bool ShouldSkipZero)18900b57cec5SDimitry Andric void MDFieldPrinter::printInt(StringRef Name, IntTy Int, bool ShouldSkipZero) {
18910b57cec5SDimitry Andric   if (ShouldSkipZero && !Int)
18920b57cec5SDimitry Andric     return;
18930b57cec5SDimitry Andric 
18940b57cec5SDimitry Andric   Out << FS << Name << ": " << Int;
18950b57cec5SDimitry Andric }
18960b57cec5SDimitry Andric 
printAPInt(StringRef Name,const APInt & Int,bool IsUnsigned,bool ShouldSkipZero)18975ffd83dbSDimitry Andric void MDFieldPrinter::printAPInt(StringRef Name, const APInt &Int,
18985ffd83dbSDimitry Andric                                 bool IsUnsigned, bool ShouldSkipZero) {
1899349cc55cSDimitry Andric   if (ShouldSkipZero && Int.isZero())
19005ffd83dbSDimitry Andric     return;
19015ffd83dbSDimitry Andric 
19025ffd83dbSDimitry Andric   Out << FS << Name << ": ";
19035ffd83dbSDimitry Andric   Int.print(Out, !IsUnsigned);
19045ffd83dbSDimitry Andric }
19055ffd83dbSDimitry Andric 
printBool(StringRef Name,bool Value,std::optional<bool> Default)19060b57cec5SDimitry Andric void MDFieldPrinter::printBool(StringRef Name, bool Value,
1907bdd1243dSDimitry Andric                                std::optional<bool> Default) {
19080b57cec5SDimitry Andric   if (Default && Value == *Default)
19090b57cec5SDimitry Andric     return;
19100b57cec5SDimitry Andric   Out << FS << Name << ": " << (Value ? "true" : "false");
19110b57cec5SDimitry Andric }
19120b57cec5SDimitry Andric 
printDIFlags(StringRef Name,DINode::DIFlags Flags)19130b57cec5SDimitry Andric void MDFieldPrinter::printDIFlags(StringRef Name, DINode::DIFlags Flags) {
19140b57cec5SDimitry Andric   if (!Flags)
19150b57cec5SDimitry Andric     return;
19160b57cec5SDimitry Andric 
19170b57cec5SDimitry Andric   Out << FS << Name << ": ";
19180b57cec5SDimitry Andric 
19190b57cec5SDimitry Andric   SmallVector<DINode::DIFlags, 8> SplitFlags;
19200b57cec5SDimitry Andric   auto Extra = DINode::splitFlags(Flags, SplitFlags);
19210b57cec5SDimitry Andric 
19220b57cec5SDimitry Andric   FieldSeparator FlagsFS(" | ");
19230b57cec5SDimitry Andric   for (auto F : SplitFlags) {
19240b57cec5SDimitry Andric     auto StringF = DINode::getFlagString(F);
19250b57cec5SDimitry Andric     assert(!StringF.empty() && "Expected valid flag");
19260b57cec5SDimitry Andric     Out << FlagsFS << StringF;
19270b57cec5SDimitry Andric   }
19280b57cec5SDimitry Andric   if (Extra || SplitFlags.empty())
19290b57cec5SDimitry Andric     Out << FlagsFS << Extra;
19300b57cec5SDimitry Andric }
19310b57cec5SDimitry Andric 
printDISPFlags(StringRef Name,DISubprogram::DISPFlags Flags)19320b57cec5SDimitry Andric void MDFieldPrinter::printDISPFlags(StringRef Name,
19330b57cec5SDimitry Andric                                     DISubprogram::DISPFlags Flags) {
19340b57cec5SDimitry Andric   // Always print this field, because no flags in the IR at all will be
19350b57cec5SDimitry Andric   // interpreted as old-style isDefinition: true.
19360b57cec5SDimitry Andric   Out << FS << Name << ": ";
19370b57cec5SDimitry Andric 
19380b57cec5SDimitry Andric   if (!Flags) {
19390b57cec5SDimitry Andric     Out << 0;
19400b57cec5SDimitry Andric     return;
19410b57cec5SDimitry Andric   }
19420b57cec5SDimitry Andric 
19430b57cec5SDimitry Andric   SmallVector<DISubprogram::DISPFlags, 8> SplitFlags;
19440b57cec5SDimitry Andric   auto Extra = DISubprogram::splitFlags(Flags, SplitFlags);
19450b57cec5SDimitry Andric 
19460b57cec5SDimitry Andric   FieldSeparator FlagsFS(" | ");
19470b57cec5SDimitry Andric   for (auto F : SplitFlags) {
19480b57cec5SDimitry Andric     auto StringF = DISubprogram::getFlagString(F);
19490b57cec5SDimitry Andric     assert(!StringF.empty() && "Expected valid flag");
19500b57cec5SDimitry Andric     Out << FlagsFS << StringF;
19510b57cec5SDimitry Andric   }
19520b57cec5SDimitry Andric   if (Extra || SplitFlags.empty())
19530b57cec5SDimitry Andric     Out << FlagsFS << Extra;
19540b57cec5SDimitry Andric }
19550b57cec5SDimitry Andric 
printEmissionKind(StringRef Name,DICompileUnit::DebugEmissionKind EK)19560b57cec5SDimitry Andric void MDFieldPrinter::printEmissionKind(StringRef Name,
19570b57cec5SDimitry Andric                                        DICompileUnit::DebugEmissionKind EK) {
19580b57cec5SDimitry Andric   Out << FS << Name << ": " << DICompileUnit::emissionKindString(EK);
19590b57cec5SDimitry Andric }
19600b57cec5SDimitry Andric 
printNameTableKind(StringRef Name,DICompileUnit::DebugNameTableKind NTK)19610b57cec5SDimitry Andric void MDFieldPrinter::printNameTableKind(StringRef Name,
19620b57cec5SDimitry Andric                                         DICompileUnit::DebugNameTableKind NTK) {
19630b57cec5SDimitry Andric   if (NTK == DICompileUnit::DebugNameTableKind::Default)
19640b57cec5SDimitry Andric     return;
19650b57cec5SDimitry Andric   Out << FS << Name << ": " << DICompileUnit::nameTableKindString(NTK);
19660b57cec5SDimitry Andric }
19670b57cec5SDimitry Andric 
19680b57cec5SDimitry Andric template <class IntTy, class Stringifier>
printDwarfEnum(StringRef Name,IntTy Value,Stringifier toString,bool ShouldSkipZero)19690b57cec5SDimitry Andric void MDFieldPrinter::printDwarfEnum(StringRef Name, IntTy Value,
19700b57cec5SDimitry Andric                                     Stringifier toString, bool ShouldSkipZero) {
19710b57cec5SDimitry Andric   if (!Value)
19720b57cec5SDimitry Andric     return;
19730b57cec5SDimitry Andric 
19740b57cec5SDimitry Andric   Out << FS << Name << ": ";
19750b57cec5SDimitry Andric   auto S = toString(Value);
19760b57cec5SDimitry Andric   if (!S.empty())
19770b57cec5SDimitry Andric     Out << S;
19780b57cec5SDimitry Andric   else
19790b57cec5SDimitry Andric     Out << Value;
19800b57cec5SDimitry Andric }
19810b57cec5SDimitry Andric 
writeGenericDINode(raw_ostream & Out,const GenericDINode * N,AsmWriterContext & WriterCtx)19820b57cec5SDimitry Andric static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N,
1983349cc55cSDimitry Andric                                AsmWriterContext &WriterCtx) {
19840b57cec5SDimitry Andric   Out << "!GenericDINode(";
1985349cc55cSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
19860b57cec5SDimitry Andric   Printer.printTag(N);
19870b57cec5SDimitry Andric   Printer.printString("header", N->getHeader());
19880b57cec5SDimitry Andric   if (N->getNumDwarfOperands()) {
19890b57cec5SDimitry Andric     Out << Printer.FS << "operands: {";
19900b57cec5SDimitry Andric     FieldSeparator IFS;
19910b57cec5SDimitry Andric     for (auto &I : N->dwarf_operands()) {
19920b57cec5SDimitry Andric       Out << IFS;
1993349cc55cSDimitry Andric       writeMetadataAsOperand(Out, I, WriterCtx);
19940b57cec5SDimitry Andric     }
19950b57cec5SDimitry Andric     Out << "}";
19960b57cec5SDimitry Andric   }
19970b57cec5SDimitry Andric   Out << ")";
19980b57cec5SDimitry Andric }
19990b57cec5SDimitry Andric 
writeDILocation(raw_ostream & Out,const DILocation * DL,AsmWriterContext & WriterCtx)20000b57cec5SDimitry Andric static void writeDILocation(raw_ostream &Out, const DILocation *DL,
2001349cc55cSDimitry Andric                             AsmWriterContext &WriterCtx) {
20020b57cec5SDimitry Andric   Out << "!DILocation(";
2003349cc55cSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
20040b57cec5SDimitry Andric   // Always output the line, since 0 is a relevant and important value for it.
20050b57cec5SDimitry Andric   Printer.printInt("line", DL->getLine(), /* ShouldSkipZero */ false);
20060b57cec5SDimitry Andric   Printer.printInt("column", DL->getColumn());
20070b57cec5SDimitry Andric   Printer.printMetadata("scope", DL->getRawScope(), /* ShouldSkipNull */ false);
20080b57cec5SDimitry Andric   Printer.printMetadata("inlinedAt", DL->getRawInlinedAt());
20090b57cec5SDimitry Andric   Printer.printBool("isImplicitCode", DL->isImplicitCode(),
20100b57cec5SDimitry Andric                     /* Default */ false);
20110b57cec5SDimitry Andric   Out << ")";
20120b57cec5SDimitry Andric }
20130b57cec5SDimitry Andric 
writeDIAssignID(raw_ostream & Out,const DIAssignID * DL,AsmWriterContext & WriterCtx)2014bdd1243dSDimitry Andric static void writeDIAssignID(raw_ostream &Out, const DIAssignID *DL,
2015bdd1243dSDimitry Andric                             AsmWriterContext &WriterCtx) {
2016bdd1243dSDimitry Andric   Out << "!DIAssignID()";
2017bdd1243dSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
2018bdd1243dSDimitry Andric }
2019bdd1243dSDimitry Andric 
writeDISubrange(raw_ostream & Out,const DISubrange * N,AsmWriterContext & WriterCtx)20200b57cec5SDimitry Andric static void writeDISubrange(raw_ostream &Out, const DISubrange *N,
2021349cc55cSDimitry Andric                             AsmWriterContext &WriterCtx) {
20220b57cec5SDimitry Andric   Out << "!DISubrange(";
2023349cc55cSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
2024fe6060f1SDimitry Andric 
2025fe6060f1SDimitry Andric   auto *Count = N->getRawCountNode();
2026fe6060f1SDimitry Andric   if (auto *CE = dyn_cast_or_null<ConstantAsMetadata>(Count)) {
2027fe6060f1SDimitry Andric     auto *CV = cast<ConstantInt>(CE->getValue());
2028fe6060f1SDimitry Andric     Printer.printInt("count", CV->getSExtValue(),
2029fe6060f1SDimitry Andric                      /* ShouldSkipZero */ false);
2030fe6060f1SDimitry Andric   } else
2031fe6060f1SDimitry Andric     Printer.printMetadata("count", Count, /*ShouldSkipNull */ true);
20325ffd83dbSDimitry Andric 
20335ffd83dbSDimitry Andric   // A lowerBound of constant 0 should not be skipped, since it is different
20345ffd83dbSDimitry Andric   // from an unspecified lower bound (= nullptr).
20355ffd83dbSDimitry Andric   auto *LBound = N->getRawLowerBound();
20365ffd83dbSDimitry Andric   if (auto *LE = dyn_cast_or_null<ConstantAsMetadata>(LBound)) {
20375ffd83dbSDimitry Andric     auto *LV = cast<ConstantInt>(LE->getValue());
20385ffd83dbSDimitry Andric     Printer.printInt("lowerBound", LV->getSExtValue(),
20395ffd83dbSDimitry Andric                      /* ShouldSkipZero */ false);
20405ffd83dbSDimitry Andric   } else
20415ffd83dbSDimitry Andric     Printer.printMetadata("lowerBound", LBound, /*ShouldSkipNull */ true);
20425ffd83dbSDimitry Andric 
20435ffd83dbSDimitry Andric   auto *UBound = N->getRawUpperBound();
20445ffd83dbSDimitry Andric   if (auto *UE = dyn_cast_or_null<ConstantAsMetadata>(UBound)) {
20455ffd83dbSDimitry Andric     auto *UV = cast<ConstantInt>(UE->getValue());
20465ffd83dbSDimitry Andric     Printer.printInt("upperBound", UV->getSExtValue(),
20475ffd83dbSDimitry Andric                      /* ShouldSkipZero */ false);
20485ffd83dbSDimitry Andric   } else
20495ffd83dbSDimitry Andric     Printer.printMetadata("upperBound", UBound, /*ShouldSkipNull */ true);
20505ffd83dbSDimitry Andric 
20515ffd83dbSDimitry Andric   auto *Stride = N->getRawStride();
20525ffd83dbSDimitry Andric   if (auto *SE = dyn_cast_or_null<ConstantAsMetadata>(Stride)) {
20535ffd83dbSDimitry Andric     auto *SV = cast<ConstantInt>(SE->getValue());
20545ffd83dbSDimitry Andric     Printer.printInt("stride", SV->getSExtValue(), /* ShouldSkipZero */ false);
20555ffd83dbSDimitry Andric   } else
20565ffd83dbSDimitry Andric     Printer.printMetadata("stride", Stride, /*ShouldSkipNull */ true);
20575ffd83dbSDimitry Andric 
20580b57cec5SDimitry Andric   Out << ")";
20590b57cec5SDimitry Andric }
20600b57cec5SDimitry Andric 
writeDIGenericSubrange(raw_ostream & Out,const DIGenericSubrange * N,AsmWriterContext & WriterCtx)2061e8d8bef9SDimitry Andric static void writeDIGenericSubrange(raw_ostream &Out, const DIGenericSubrange *N,
2062349cc55cSDimitry Andric                                    AsmWriterContext &WriterCtx) {
2063e8d8bef9SDimitry Andric   Out << "!DIGenericSubrange(";
2064349cc55cSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
2065e8d8bef9SDimitry Andric 
2066e8d8bef9SDimitry Andric   auto IsConstant = [&](Metadata *Bound) -> bool {
2067e8d8bef9SDimitry Andric     if (auto *BE = dyn_cast_or_null<DIExpression>(Bound)) {
2068349cc55cSDimitry Andric       return BE->isConstant() &&
2069349cc55cSDimitry Andric              DIExpression::SignedOrUnsignedConstant::SignedConstant ==
2070349cc55cSDimitry Andric                  *BE->isConstant();
2071e8d8bef9SDimitry Andric     }
2072e8d8bef9SDimitry Andric     return false;
2073e8d8bef9SDimitry Andric   };
2074e8d8bef9SDimitry Andric 
2075e8d8bef9SDimitry Andric   auto GetConstant = [&](Metadata *Bound) -> int64_t {
2076e8d8bef9SDimitry Andric     assert(IsConstant(Bound) && "Expected constant");
2077e8d8bef9SDimitry Andric     auto *BE = dyn_cast_or_null<DIExpression>(Bound);
2078e8d8bef9SDimitry Andric     return static_cast<int64_t>(BE->getElement(1));
2079e8d8bef9SDimitry Andric   };
2080e8d8bef9SDimitry Andric 
2081e8d8bef9SDimitry Andric   auto *Count = N->getRawCountNode();
2082e8d8bef9SDimitry Andric   if (IsConstant(Count))
2083e8d8bef9SDimitry Andric     Printer.printInt("count", GetConstant(Count),
2084e8d8bef9SDimitry Andric                      /* ShouldSkipZero */ false);
2085e8d8bef9SDimitry Andric   else
2086e8d8bef9SDimitry Andric     Printer.printMetadata("count", Count, /*ShouldSkipNull */ true);
2087e8d8bef9SDimitry Andric 
2088e8d8bef9SDimitry Andric   auto *LBound = N->getRawLowerBound();
2089e8d8bef9SDimitry Andric   if (IsConstant(LBound))
2090e8d8bef9SDimitry Andric     Printer.printInt("lowerBound", GetConstant(LBound),
2091e8d8bef9SDimitry Andric                      /* ShouldSkipZero */ false);
2092e8d8bef9SDimitry Andric   else
2093e8d8bef9SDimitry Andric     Printer.printMetadata("lowerBound", LBound, /*ShouldSkipNull */ true);
2094e8d8bef9SDimitry Andric 
2095e8d8bef9SDimitry Andric   auto *UBound = N->getRawUpperBound();
2096e8d8bef9SDimitry Andric   if (IsConstant(UBound))
2097e8d8bef9SDimitry Andric     Printer.printInt("upperBound", GetConstant(UBound),
2098e8d8bef9SDimitry Andric                      /* ShouldSkipZero */ false);
2099e8d8bef9SDimitry Andric   else
2100e8d8bef9SDimitry Andric     Printer.printMetadata("upperBound", UBound, /*ShouldSkipNull */ true);
2101e8d8bef9SDimitry Andric 
2102e8d8bef9SDimitry Andric   auto *Stride = N->getRawStride();
2103e8d8bef9SDimitry Andric   if (IsConstant(Stride))
2104e8d8bef9SDimitry Andric     Printer.printInt("stride", GetConstant(Stride),
2105e8d8bef9SDimitry Andric                      /* ShouldSkipZero */ false);
2106e8d8bef9SDimitry Andric   else
2107e8d8bef9SDimitry Andric     Printer.printMetadata("stride", Stride, /*ShouldSkipNull */ true);
2108e8d8bef9SDimitry Andric 
2109e8d8bef9SDimitry Andric   Out << ")";
2110e8d8bef9SDimitry Andric }
2111e8d8bef9SDimitry Andric 
writeDIEnumerator(raw_ostream & Out,const DIEnumerator * N,AsmWriterContext &)21120b57cec5SDimitry Andric static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N,
2113349cc55cSDimitry Andric                               AsmWriterContext &) {
21140b57cec5SDimitry Andric   Out << "!DIEnumerator(";
21150b57cec5SDimitry Andric   MDFieldPrinter Printer(Out);
21160b57cec5SDimitry Andric   Printer.printString("name", N->getName(), /* ShouldSkipEmpty */ false);
21175ffd83dbSDimitry Andric   Printer.printAPInt("value", N->getValue(), N->isUnsigned(),
21185ffd83dbSDimitry Andric                      /*ShouldSkipZero=*/false);
21195ffd83dbSDimitry Andric   if (N->isUnsigned())
21200b57cec5SDimitry Andric     Printer.printBool("isUnsigned", true);
21210b57cec5SDimitry Andric   Out << ")";
21220b57cec5SDimitry Andric }
21230b57cec5SDimitry Andric 
writeDIBasicType(raw_ostream & Out,const DIBasicType * N,AsmWriterContext &)21240b57cec5SDimitry Andric static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N,
2125349cc55cSDimitry Andric                              AsmWriterContext &) {
21260b57cec5SDimitry Andric   Out << "!DIBasicType(";
21270b57cec5SDimitry Andric   MDFieldPrinter Printer(Out);
21280b57cec5SDimitry Andric   if (N->getTag() != dwarf::DW_TAG_base_type)
21290b57cec5SDimitry Andric     Printer.printTag(N);
21300b57cec5SDimitry Andric   Printer.printString("name", N->getName());
21310b57cec5SDimitry Andric   Printer.printInt("size", N->getSizeInBits());
21320b57cec5SDimitry Andric   Printer.printInt("align", N->getAlignInBits());
21330b57cec5SDimitry Andric   Printer.printDwarfEnum("encoding", N->getEncoding(),
21340b57cec5SDimitry Andric                          dwarf::AttributeEncodingString);
21350b57cec5SDimitry Andric   Printer.printDIFlags("flags", N->getFlags());
21360b57cec5SDimitry Andric   Out << ")";
21370b57cec5SDimitry Andric }
21380b57cec5SDimitry Andric 
writeDIStringType(raw_ostream & Out,const DIStringType * N,AsmWriterContext & WriterCtx)2139e8d8bef9SDimitry Andric static void writeDIStringType(raw_ostream &Out, const DIStringType *N,
2140349cc55cSDimitry Andric                               AsmWriterContext &WriterCtx) {
2141e8d8bef9SDimitry Andric   Out << "!DIStringType(";
2142349cc55cSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
2143e8d8bef9SDimitry Andric   if (N->getTag() != dwarf::DW_TAG_string_type)
2144e8d8bef9SDimitry Andric     Printer.printTag(N);
2145e8d8bef9SDimitry Andric   Printer.printString("name", N->getName());
2146e8d8bef9SDimitry Andric   Printer.printMetadata("stringLength", N->getRawStringLength());
2147e8d8bef9SDimitry Andric   Printer.printMetadata("stringLengthExpression", N->getRawStringLengthExp());
214804eeddc0SDimitry Andric   Printer.printMetadata("stringLocationExpression",
214904eeddc0SDimitry Andric                         N->getRawStringLocationExp());
2150e8d8bef9SDimitry Andric   Printer.printInt("size", N->getSizeInBits());
2151e8d8bef9SDimitry Andric   Printer.printInt("align", N->getAlignInBits());
2152e8d8bef9SDimitry Andric   Printer.printDwarfEnum("encoding", N->getEncoding(),
2153e8d8bef9SDimitry Andric                          dwarf::AttributeEncodingString);
2154e8d8bef9SDimitry Andric   Out << ")";
2155e8d8bef9SDimitry Andric }
2156e8d8bef9SDimitry Andric 
writeDIDerivedType(raw_ostream & Out,const DIDerivedType * N,AsmWriterContext & WriterCtx)21570b57cec5SDimitry Andric static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N,
2158349cc55cSDimitry Andric                                AsmWriterContext &WriterCtx) {
21590b57cec5SDimitry Andric   Out << "!DIDerivedType(";
2160349cc55cSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
21610b57cec5SDimitry Andric   Printer.printTag(N);
21620b57cec5SDimitry Andric   Printer.printString("name", N->getName());
21630b57cec5SDimitry Andric   Printer.printMetadata("scope", N->getRawScope());
21640b57cec5SDimitry Andric   Printer.printMetadata("file", N->getRawFile());
21650b57cec5SDimitry Andric   Printer.printInt("line", N->getLine());
21660b57cec5SDimitry Andric   Printer.printMetadata("baseType", N->getRawBaseType(),
21670b57cec5SDimitry Andric                         /* ShouldSkipNull */ false);
21680b57cec5SDimitry Andric   Printer.printInt("size", N->getSizeInBits());
21690b57cec5SDimitry Andric   Printer.printInt("align", N->getAlignInBits());
21700b57cec5SDimitry Andric   Printer.printInt("offset", N->getOffsetInBits());
21710b57cec5SDimitry Andric   Printer.printDIFlags("flags", N->getFlags());
21720b57cec5SDimitry Andric   Printer.printMetadata("extraData", N->getRawExtraData());
21730b57cec5SDimitry Andric   if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
21740b57cec5SDimitry Andric     Printer.printInt("dwarfAddressSpace", *DWARFAddressSpace,
21750b57cec5SDimitry Andric                      /* ShouldSkipZero */ false);
2176349cc55cSDimitry Andric   Printer.printMetadata("annotations", N->getRawAnnotations());
2177*0fca6ea1SDimitry Andric   if (auto PtrAuthData = N->getPtrAuthData()) {
2178*0fca6ea1SDimitry Andric     Printer.printInt("ptrAuthKey", PtrAuthData->key());
2179*0fca6ea1SDimitry Andric     Printer.printBool("ptrAuthIsAddressDiscriminated",
2180*0fca6ea1SDimitry Andric                       PtrAuthData->isAddressDiscriminated());
2181*0fca6ea1SDimitry Andric     Printer.printInt("ptrAuthExtraDiscriminator",
2182*0fca6ea1SDimitry Andric                      PtrAuthData->extraDiscriminator());
2183*0fca6ea1SDimitry Andric     Printer.printBool("ptrAuthIsaPointer", PtrAuthData->isaPointer());
2184*0fca6ea1SDimitry Andric     Printer.printBool("ptrAuthAuthenticatesNullValues",
2185*0fca6ea1SDimitry Andric                       PtrAuthData->authenticatesNullValues());
2186*0fca6ea1SDimitry Andric   }
21870b57cec5SDimitry Andric   Out << ")";
21880b57cec5SDimitry Andric }
21890b57cec5SDimitry Andric 
writeDICompositeType(raw_ostream & Out,const DICompositeType * N,AsmWriterContext & WriterCtx)21900b57cec5SDimitry Andric static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N,
2191349cc55cSDimitry Andric                                  AsmWriterContext &WriterCtx) {
21920b57cec5SDimitry Andric   Out << "!DICompositeType(";
2193349cc55cSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
21940b57cec5SDimitry Andric   Printer.printTag(N);
21950b57cec5SDimitry Andric   Printer.printString("name", N->getName());
21960b57cec5SDimitry Andric   Printer.printMetadata("scope", N->getRawScope());
21970b57cec5SDimitry Andric   Printer.printMetadata("file", N->getRawFile());
21980b57cec5SDimitry Andric   Printer.printInt("line", N->getLine());
21990b57cec5SDimitry Andric   Printer.printMetadata("baseType", N->getRawBaseType());
22000b57cec5SDimitry Andric   Printer.printInt("size", N->getSizeInBits());
22010b57cec5SDimitry Andric   Printer.printInt("align", N->getAlignInBits());
22020b57cec5SDimitry Andric   Printer.printInt("offset", N->getOffsetInBits());
22030b57cec5SDimitry Andric   Printer.printDIFlags("flags", N->getFlags());
22040b57cec5SDimitry Andric   Printer.printMetadata("elements", N->getRawElements());
22050b57cec5SDimitry Andric   Printer.printDwarfEnum("runtimeLang", N->getRuntimeLang(),
22060b57cec5SDimitry Andric                          dwarf::LanguageString);
22070b57cec5SDimitry Andric   Printer.printMetadata("vtableHolder", N->getRawVTableHolder());
22080b57cec5SDimitry Andric   Printer.printMetadata("templateParams", N->getRawTemplateParams());
22090b57cec5SDimitry Andric   Printer.printString("identifier", N->getIdentifier());
22100b57cec5SDimitry Andric   Printer.printMetadata("discriminator", N->getRawDiscriminator());
22115ffd83dbSDimitry Andric   Printer.printMetadata("dataLocation", N->getRawDataLocation());
2212e8d8bef9SDimitry Andric   Printer.printMetadata("associated", N->getRawAssociated());
2213e8d8bef9SDimitry Andric   Printer.printMetadata("allocated", N->getRawAllocated());
2214e8d8bef9SDimitry Andric   if (auto *RankConst = N->getRankConst())
2215e8d8bef9SDimitry Andric     Printer.printInt("rank", RankConst->getSExtValue(),
2216e8d8bef9SDimitry Andric                      /* ShouldSkipZero */ false);
2217e8d8bef9SDimitry Andric   else
2218e8d8bef9SDimitry Andric     Printer.printMetadata("rank", N->getRawRank(), /*ShouldSkipNull */ true);
2219349cc55cSDimitry Andric   Printer.printMetadata("annotations", N->getRawAnnotations());
22200b57cec5SDimitry Andric   Out << ")";
22210b57cec5SDimitry Andric }
22220b57cec5SDimitry Andric 
writeDISubroutineType(raw_ostream & Out,const DISubroutineType * N,AsmWriterContext & WriterCtx)22230b57cec5SDimitry Andric static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N,
2224349cc55cSDimitry Andric                                   AsmWriterContext &WriterCtx) {
22250b57cec5SDimitry Andric   Out << "!DISubroutineType(";
2226349cc55cSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
22270b57cec5SDimitry Andric   Printer.printDIFlags("flags", N->getFlags());
22280b57cec5SDimitry Andric   Printer.printDwarfEnum("cc", N->getCC(), dwarf::ConventionString);
22290b57cec5SDimitry Andric   Printer.printMetadata("types", N->getRawTypeArray(),
22300b57cec5SDimitry Andric                         /* ShouldSkipNull */ false);
22310b57cec5SDimitry Andric   Out << ")";
22320b57cec5SDimitry Andric }
22330b57cec5SDimitry Andric 
writeDIFile(raw_ostream & Out,const DIFile * N,AsmWriterContext &)2234349cc55cSDimitry Andric static void writeDIFile(raw_ostream &Out, const DIFile *N, AsmWriterContext &) {
22350b57cec5SDimitry Andric   Out << "!DIFile(";
22360b57cec5SDimitry Andric   MDFieldPrinter Printer(Out);
22370b57cec5SDimitry Andric   Printer.printString("filename", N->getFilename(),
22380b57cec5SDimitry Andric                       /* ShouldSkipEmpty */ false);
22390b57cec5SDimitry Andric   Printer.printString("directory", N->getDirectory(),
22400b57cec5SDimitry Andric                       /* ShouldSkipEmpty */ false);
22410b57cec5SDimitry Andric   // Print all values for checksum together, or not at all.
22420b57cec5SDimitry Andric   if (N->getChecksum())
22430b57cec5SDimitry Andric     Printer.printChecksum(*N->getChecksum());
224481ad6265SDimitry Andric   Printer.printString("source", N->getSource().value_or(StringRef()),
22450b57cec5SDimitry Andric                       /* ShouldSkipEmpty */ true);
22460b57cec5SDimitry Andric   Out << ")";
22470b57cec5SDimitry Andric }
22480b57cec5SDimitry Andric 
writeDICompileUnit(raw_ostream & Out,const DICompileUnit * N,AsmWriterContext & WriterCtx)22490b57cec5SDimitry Andric static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N,
2250349cc55cSDimitry Andric                                AsmWriterContext &WriterCtx) {
22510b57cec5SDimitry Andric   Out << "!DICompileUnit(";
2252349cc55cSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
22530b57cec5SDimitry Andric   Printer.printDwarfEnum("language", N->getSourceLanguage(),
22540b57cec5SDimitry Andric                          dwarf::LanguageString, /* ShouldSkipZero */ false);
22550b57cec5SDimitry Andric   Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
22560b57cec5SDimitry Andric   Printer.printString("producer", N->getProducer());
22570b57cec5SDimitry Andric   Printer.printBool("isOptimized", N->isOptimized());
22580b57cec5SDimitry Andric   Printer.printString("flags", N->getFlags());
22590b57cec5SDimitry Andric   Printer.printInt("runtimeVersion", N->getRuntimeVersion(),
22600b57cec5SDimitry Andric                    /* ShouldSkipZero */ false);
22610b57cec5SDimitry Andric   Printer.printString("splitDebugFilename", N->getSplitDebugFilename());
22620b57cec5SDimitry Andric   Printer.printEmissionKind("emissionKind", N->getEmissionKind());
22630b57cec5SDimitry Andric   Printer.printMetadata("enums", N->getRawEnumTypes());
22640b57cec5SDimitry Andric   Printer.printMetadata("retainedTypes", N->getRawRetainedTypes());
22650b57cec5SDimitry Andric   Printer.printMetadata("globals", N->getRawGlobalVariables());
22660b57cec5SDimitry Andric   Printer.printMetadata("imports", N->getRawImportedEntities());
22670b57cec5SDimitry Andric   Printer.printMetadata("macros", N->getRawMacros());
22680b57cec5SDimitry Andric   Printer.printInt("dwoId", N->getDWOId());
22690b57cec5SDimitry Andric   Printer.printBool("splitDebugInlining", N->getSplitDebugInlining(), true);
22700b57cec5SDimitry Andric   Printer.printBool("debugInfoForProfiling", N->getDebugInfoForProfiling(),
22710b57cec5SDimitry Andric                     false);
22720b57cec5SDimitry Andric   Printer.printNameTableKind("nameTableKind", N->getNameTableKind());
22730b57cec5SDimitry Andric   Printer.printBool("rangesBaseAddress", N->getRangesBaseAddress(), false);
22745ffd83dbSDimitry Andric   Printer.printString("sysroot", N->getSysRoot());
22755ffd83dbSDimitry Andric   Printer.printString("sdk", N->getSDK());
22760b57cec5SDimitry Andric   Out << ")";
22770b57cec5SDimitry Andric }
22780b57cec5SDimitry Andric 
writeDISubprogram(raw_ostream & Out,const DISubprogram * N,AsmWriterContext & WriterCtx)22790b57cec5SDimitry Andric static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N,
2280349cc55cSDimitry Andric                               AsmWriterContext &WriterCtx) {
22810b57cec5SDimitry Andric   Out << "!DISubprogram(";
2282349cc55cSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
22830b57cec5SDimitry Andric   Printer.printString("name", N->getName());
22840b57cec5SDimitry Andric   Printer.printString("linkageName", N->getLinkageName());
22850b57cec5SDimitry Andric   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
22860b57cec5SDimitry Andric   Printer.printMetadata("file", N->getRawFile());
22870b57cec5SDimitry Andric   Printer.printInt("line", N->getLine());
22880b57cec5SDimitry Andric   Printer.printMetadata("type", N->getRawType());
22890b57cec5SDimitry Andric   Printer.printInt("scopeLine", N->getScopeLine());
22900b57cec5SDimitry Andric   Printer.printMetadata("containingType", N->getRawContainingType());
22910b57cec5SDimitry Andric   if (N->getVirtuality() != dwarf::DW_VIRTUALITY_none ||
22920b57cec5SDimitry Andric       N->getVirtualIndex() != 0)
22930b57cec5SDimitry Andric     Printer.printInt("virtualIndex", N->getVirtualIndex(), false);
22940b57cec5SDimitry Andric   Printer.printInt("thisAdjustment", N->getThisAdjustment());
22950b57cec5SDimitry Andric   Printer.printDIFlags("flags", N->getFlags());
22960b57cec5SDimitry Andric   Printer.printDISPFlags("spFlags", N->getSPFlags());
22970b57cec5SDimitry Andric   Printer.printMetadata("unit", N->getRawUnit());
22980b57cec5SDimitry Andric   Printer.printMetadata("templateParams", N->getRawTemplateParams());
22990b57cec5SDimitry Andric   Printer.printMetadata("declaration", N->getRawDeclaration());
23000b57cec5SDimitry Andric   Printer.printMetadata("retainedNodes", N->getRawRetainedNodes());
23010b57cec5SDimitry Andric   Printer.printMetadata("thrownTypes", N->getRawThrownTypes());
2302349cc55cSDimitry Andric   Printer.printMetadata("annotations", N->getRawAnnotations());
230381ad6265SDimitry Andric   Printer.printString("targetFuncName", N->getTargetFuncName());
23040b57cec5SDimitry Andric   Out << ")";
23050b57cec5SDimitry Andric }
23060b57cec5SDimitry Andric 
writeDILexicalBlock(raw_ostream & Out,const DILexicalBlock * N,AsmWriterContext & WriterCtx)23070b57cec5SDimitry Andric static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N,
2308349cc55cSDimitry Andric                                 AsmWriterContext &WriterCtx) {
23090b57cec5SDimitry Andric   Out << "!DILexicalBlock(";
2310349cc55cSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
23110b57cec5SDimitry Andric   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
23120b57cec5SDimitry Andric   Printer.printMetadata("file", N->getRawFile());
23130b57cec5SDimitry Andric   Printer.printInt("line", N->getLine());
23140b57cec5SDimitry Andric   Printer.printInt("column", N->getColumn());
23150b57cec5SDimitry Andric   Out << ")";
23160b57cec5SDimitry Andric }
23170b57cec5SDimitry Andric 
writeDILexicalBlockFile(raw_ostream & Out,const DILexicalBlockFile * N,AsmWriterContext & WriterCtx)23180b57cec5SDimitry Andric static void writeDILexicalBlockFile(raw_ostream &Out,
23190b57cec5SDimitry Andric                                     const DILexicalBlockFile *N,
2320349cc55cSDimitry Andric                                     AsmWriterContext &WriterCtx) {
23210b57cec5SDimitry Andric   Out << "!DILexicalBlockFile(";
2322349cc55cSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
23230b57cec5SDimitry Andric   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
23240b57cec5SDimitry Andric   Printer.printMetadata("file", N->getRawFile());
23250b57cec5SDimitry Andric   Printer.printInt("discriminator", N->getDiscriminator(),
23260b57cec5SDimitry Andric                    /* ShouldSkipZero */ false);
23270b57cec5SDimitry Andric   Out << ")";
23280b57cec5SDimitry Andric }
23290b57cec5SDimitry Andric 
writeDINamespace(raw_ostream & Out,const DINamespace * N,AsmWriterContext & WriterCtx)23300b57cec5SDimitry Andric static void writeDINamespace(raw_ostream &Out, const DINamespace *N,
2331349cc55cSDimitry Andric                              AsmWriterContext &WriterCtx) {
23320b57cec5SDimitry Andric   Out << "!DINamespace(";
2333349cc55cSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
23340b57cec5SDimitry Andric   Printer.printString("name", N->getName());
23350b57cec5SDimitry Andric   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
23360b57cec5SDimitry Andric   Printer.printBool("exportSymbols", N->getExportSymbols(), false);
23370b57cec5SDimitry Andric   Out << ")";
23380b57cec5SDimitry Andric }
23390b57cec5SDimitry Andric 
writeDICommonBlock(raw_ostream & Out,const DICommonBlock * N,AsmWriterContext & WriterCtx)23400b57cec5SDimitry Andric static void writeDICommonBlock(raw_ostream &Out, const DICommonBlock *N,
2341349cc55cSDimitry Andric                                AsmWriterContext &WriterCtx) {
23420b57cec5SDimitry Andric   Out << "!DICommonBlock(";
2343349cc55cSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
23440b57cec5SDimitry Andric   Printer.printMetadata("scope", N->getRawScope(), false);
23450b57cec5SDimitry Andric   Printer.printMetadata("declaration", N->getRawDecl(), false);
23460b57cec5SDimitry Andric   Printer.printString("name", N->getName());
23470b57cec5SDimitry Andric   Printer.printMetadata("file", N->getRawFile());
23480b57cec5SDimitry Andric   Printer.printInt("line", N->getLineNo());
23490b57cec5SDimitry Andric   Out << ")";
23500b57cec5SDimitry Andric }
23510b57cec5SDimitry Andric 
writeDIMacro(raw_ostream & Out,const DIMacro * N,AsmWriterContext & WriterCtx)23520b57cec5SDimitry Andric static void writeDIMacro(raw_ostream &Out, const DIMacro *N,
2353349cc55cSDimitry Andric                          AsmWriterContext &WriterCtx) {
23540b57cec5SDimitry Andric   Out << "!DIMacro(";
2355349cc55cSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
23560b57cec5SDimitry Andric   Printer.printMacinfoType(N);
23570b57cec5SDimitry Andric   Printer.printInt("line", N->getLine());
23580b57cec5SDimitry Andric   Printer.printString("name", N->getName());
23590b57cec5SDimitry Andric   Printer.printString("value", N->getValue());
23600b57cec5SDimitry Andric   Out << ")";
23610b57cec5SDimitry Andric }
23620b57cec5SDimitry Andric 
writeDIMacroFile(raw_ostream & Out,const DIMacroFile * N,AsmWriterContext & WriterCtx)23630b57cec5SDimitry Andric static void writeDIMacroFile(raw_ostream &Out, const DIMacroFile *N,
2364349cc55cSDimitry Andric                              AsmWriterContext &WriterCtx) {
23650b57cec5SDimitry Andric   Out << "!DIMacroFile(";
2366349cc55cSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
23670b57cec5SDimitry Andric   Printer.printInt("line", N->getLine());
23680b57cec5SDimitry Andric   Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
23690b57cec5SDimitry Andric   Printer.printMetadata("nodes", N->getRawElements());
23700b57cec5SDimitry Andric   Out << ")";
23710b57cec5SDimitry Andric }
23720b57cec5SDimitry Andric 
writeDIModule(raw_ostream & Out,const DIModule * N,AsmWriterContext & WriterCtx)23730b57cec5SDimitry Andric static void writeDIModule(raw_ostream &Out, const DIModule *N,
2374349cc55cSDimitry Andric                           AsmWriterContext &WriterCtx) {
23750b57cec5SDimitry Andric   Out << "!DIModule(";
2376349cc55cSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
23770b57cec5SDimitry Andric   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
23780b57cec5SDimitry Andric   Printer.printString("name", N->getName());
23790b57cec5SDimitry Andric   Printer.printString("configMacros", N->getConfigurationMacros());
23800b57cec5SDimitry Andric   Printer.printString("includePath", N->getIncludePath());
23815ffd83dbSDimitry Andric   Printer.printString("apinotes", N->getAPINotesFile());
23825ffd83dbSDimitry Andric   Printer.printMetadata("file", N->getRawFile());
23835ffd83dbSDimitry Andric   Printer.printInt("line", N->getLineNo());
2384e8d8bef9SDimitry Andric   Printer.printBool("isDecl", N->getIsDecl(), /* Default */ false);
23850b57cec5SDimitry Andric   Out << ")";
23860b57cec5SDimitry Andric }
23870b57cec5SDimitry Andric 
writeDITemplateTypeParameter(raw_ostream & Out,const DITemplateTypeParameter * N,AsmWriterContext & WriterCtx)23880b57cec5SDimitry Andric static void writeDITemplateTypeParameter(raw_ostream &Out,
23890b57cec5SDimitry Andric                                          const DITemplateTypeParameter *N,
2390349cc55cSDimitry Andric                                          AsmWriterContext &WriterCtx) {
23910b57cec5SDimitry Andric   Out << "!DITemplateTypeParameter(";
2392349cc55cSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
23930b57cec5SDimitry Andric   Printer.printString("name", N->getName());
23940b57cec5SDimitry Andric   Printer.printMetadata("type", N->getRawType(), /* ShouldSkipNull */ false);
23955ffd83dbSDimitry Andric   Printer.printBool("defaulted", N->isDefault(), /* Default= */ false);
23960b57cec5SDimitry Andric   Out << ")";
23970b57cec5SDimitry Andric }
23980b57cec5SDimitry Andric 
writeDITemplateValueParameter(raw_ostream & Out,const DITemplateValueParameter * N,AsmWriterContext & WriterCtx)23990b57cec5SDimitry Andric static void writeDITemplateValueParameter(raw_ostream &Out,
24000b57cec5SDimitry Andric                                           const DITemplateValueParameter *N,
2401349cc55cSDimitry Andric                                           AsmWriterContext &WriterCtx) {
24020b57cec5SDimitry Andric   Out << "!DITemplateValueParameter(";
2403349cc55cSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
24040b57cec5SDimitry Andric   if (N->getTag() != dwarf::DW_TAG_template_value_parameter)
24050b57cec5SDimitry Andric     Printer.printTag(N);
24060b57cec5SDimitry Andric   Printer.printString("name", N->getName());
24070b57cec5SDimitry Andric   Printer.printMetadata("type", N->getRawType());
24085ffd83dbSDimitry Andric   Printer.printBool("defaulted", N->isDefault(), /* Default= */ false);
24090b57cec5SDimitry Andric   Printer.printMetadata("value", N->getValue(), /* ShouldSkipNull */ false);
24100b57cec5SDimitry Andric   Out << ")";
24110b57cec5SDimitry Andric }
24120b57cec5SDimitry Andric 
writeDIGlobalVariable(raw_ostream & Out,const DIGlobalVariable * N,AsmWriterContext & WriterCtx)24130b57cec5SDimitry Andric static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N,
2414349cc55cSDimitry Andric                                   AsmWriterContext &WriterCtx) {
24150b57cec5SDimitry Andric   Out << "!DIGlobalVariable(";
2416349cc55cSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
24170b57cec5SDimitry Andric   Printer.printString("name", N->getName());
24180b57cec5SDimitry Andric   Printer.printString("linkageName", N->getLinkageName());
24190b57cec5SDimitry Andric   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
24200b57cec5SDimitry Andric   Printer.printMetadata("file", N->getRawFile());
24210b57cec5SDimitry Andric   Printer.printInt("line", N->getLine());
24220b57cec5SDimitry Andric   Printer.printMetadata("type", N->getRawType());
24230b57cec5SDimitry Andric   Printer.printBool("isLocal", N->isLocalToUnit());
24240b57cec5SDimitry Andric   Printer.printBool("isDefinition", N->isDefinition());
24250b57cec5SDimitry Andric   Printer.printMetadata("declaration", N->getRawStaticDataMemberDeclaration());
24260b57cec5SDimitry Andric   Printer.printMetadata("templateParams", N->getRawTemplateParams());
24270b57cec5SDimitry Andric   Printer.printInt("align", N->getAlignInBits());
2428349cc55cSDimitry Andric   Printer.printMetadata("annotations", N->getRawAnnotations());
24290b57cec5SDimitry Andric   Out << ")";
24300b57cec5SDimitry Andric }
24310b57cec5SDimitry Andric 
writeDILocalVariable(raw_ostream & Out,const DILocalVariable * N,AsmWriterContext & WriterCtx)24320b57cec5SDimitry Andric static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N,
2433349cc55cSDimitry Andric                                  AsmWriterContext &WriterCtx) {
24340b57cec5SDimitry Andric   Out << "!DILocalVariable(";
2435349cc55cSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
24360b57cec5SDimitry Andric   Printer.printString("name", N->getName());
24370b57cec5SDimitry Andric   Printer.printInt("arg", N->getArg());
24380b57cec5SDimitry Andric   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
24390b57cec5SDimitry Andric   Printer.printMetadata("file", N->getRawFile());
24400b57cec5SDimitry Andric   Printer.printInt("line", N->getLine());
24410b57cec5SDimitry Andric   Printer.printMetadata("type", N->getRawType());
24420b57cec5SDimitry Andric   Printer.printDIFlags("flags", N->getFlags());
24430b57cec5SDimitry Andric   Printer.printInt("align", N->getAlignInBits());
2444349cc55cSDimitry Andric   Printer.printMetadata("annotations", N->getRawAnnotations());
24450b57cec5SDimitry Andric   Out << ")";
24460b57cec5SDimitry Andric }
24470b57cec5SDimitry Andric 
writeDILabel(raw_ostream & Out,const DILabel * N,AsmWriterContext & WriterCtx)24480b57cec5SDimitry Andric static void writeDILabel(raw_ostream &Out, const DILabel *N,
2449349cc55cSDimitry Andric                          AsmWriterContext &WriterCtx) {
24500b57cec5SDimitry Andric   Out << "!DILabel(";
2451349cc55cSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
24520b57cec5SDimitry Andric   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
24530b57cec5SDimitry Andric   Printer.printString("name", N->getName());
24540b57cec5SDimitry Andric   Printer.printMetadata("file", N->getRawFile());
24550b57cec5SDimitry Andric   Printer.printInt("line", N->getLine());
24560b57cec5SDimitry Andric   Out << ")";
24570b57cec5SDimitry Andric }
24580b57cec5SDimitry Andric 
writeDIExpression(raw_ostream & Out,const DIExpression * N,AsmWriterContext & WriterCtx)24590b57cec5SDimitry Andric static void writeDIExpression(raw_ostream &Out, const DIExpression *N,
2460349cc55cSDimitry Andric                               AsmWriterContext &WriterCtx) {
24610b57cec5SDimitry Andric   Out << "!DIExpression(";
24620b57cec5SDimitry Andric   FieldSeparator FS;
24630b57cec5SDimitry Andric   if (N->isValid()) {
2464fe6060f1SDimitry Andric     for (const DIExpression::ExprOperand &Op : N->expr_ops()) {
2465fe6060f1SDimitry Andric       auto OpStr = dwarf::OperationEncodingString(Op.getOp());
24660b57cec5SDimitry Andric       assert(!OpStr.empty() && "Expected valid opcode");
24670b57cec5SDimitry Andric 
24680b57cec5SDimitry Andric       Out << FS << OpStr;
2469fe6060f1SDimitry Andric       if (Op.getOp() == dwarf::DW_OP_LLVM_convert) {
2470fe6060f1SDimitry Andric         Out << FS << Op.getArg(0);
2471fe6060f1SDimitry Andric         Out << FS << dwarf::AttributeEncodingString(Op.getArg(1));
24720b57cec5SDimitry Andric       } else {
2473fe6060f1SDimitry Andric         for (unsigned A = 0, AE = Op.getNumArgs(); A != AE; ++A)
2474fe6060f1SDimitry Andric           Out << FS << Op.getArg(A);
24750b57cec5SDimitry Andric       }
24760b57cec5SDimitry Andric     }
24770b57cec5SDimitry Andric   } else {
24780b57cec5SDimitry Andric     for (const auto &I : N->getElements())
24790b57cec5SDimitry Andric       Out << FS << I;
24800b57cec5SDimitry Andric   }
24810b57cec5SDimitry Andric   Out << ")";
24820b57cec5SDimitry Andric }
24830b57cec5SDimitry Andric 
writeDIArgList(raw_ostream & Out,const DIArgList * N,AsmWriterContext & WriterCtx,bool FromValue=false)2484fe6060f1SDimitry Andric static void writeDIArgList(raw_ostream &Out, const DIArgList *N,
2485349cc55cSDimitry Andric                            AsmWriterContext &WriterCtx,
2486349cc55cSDimitry Andric                            bool FromValue = false) {
2487fe6060f1SDimitry Andric   assert(FromValue &&
2488fe6060f1SDimitry Andric          "Unexpected DIArgList metadata outside of value argument");
2489fe6060f1SDimitry Andric   Out << "!DIArgList(";
2490fe6060f1SDimitry Andric   FieldSeparator FS;
2491349cc55cSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
2492fe6060f1SDimitry Andric   for (Metadata *Arg : N->getArgs()) {
2493fe6060f1SDimitry Andric     Out << FS;
2494349cc55cSDimitry Andric     WriteAsOperandInternal(Out, Arg, WriterCtx, true);
2495fe6060f1SDimitry Andric   }
2496fe6060f1SDimitry Andric   Out << ")";
2497fe6060f1SDimitry Andric }
2498fe6060f1SDimitry Andric 
writeDIGlobalVariableExpression(raw_ostream & Out,const DIGlobalVariableExpression * N,AsmWriterContext & WriterCtx)24990b57cec5SDimitry Andric static void writeDIGlobalVariableExpression(raw_ostream &Out,
25000b57cec5SDimitry Andric                                             const DIGlobalVariableExpression *N,
2501349cc55cSDimitry Andric                                             AsmWriterContext &WriterCtx) {
25020b57cec5SDimitry Andric   Out << "!DIGlobalVariableExpression(";
2503349cc55cSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
25040b57cec5SDimitry Andric   Printer.printMetadata("var", N->getVariable());
25050b57cec5SDimitry Andric   Printer.printMetadata("expr", N->getExpression());
25060b57cec5SDimitry Andric   Out << ")";
25070b57cec5SDimitry Andric }
25080b57cec5SDimitry Andric 
writeDIObjCProperty(raw_ostream & Out,const DIObjCProperty * N,AsmWriterContext & WriterCtx)25090b57cec5SDimitry Andric static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N,
2510349cc55cSDimitry Andric                                 AsmWriterContext &WriterCtx) {
25110b57cec5SDimitry Andric   Out << "!DIObjCProperty(";
2512349cc55cSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
25130b57cec5SDimitry Andric   Printer.printString("name", N->getName());
25140b57cec5SDimitry Andric   Printer.printMetadata("file", N->getRawFile());
25150b57cec5SDimitry Andric   Printer.printInt("line", N->getLine());
25160b57cec5SDimitry Andric   Printer.printString("setter", N->getSetterName());
25170b57cec5SDimitry Andric   Printer.printString("getter", N->getGetterName());
25180b57cec5SDimitry Andric   Printer.printInt("attributes", N->getAttributes());
25190b57cec5SDimitry Andric   Printer.printMetadata("type", N->getRawType());
25200b57cec5SDimitry Andric   Out << ")";
25210b57cec5SDimitry Andric }
25220b57cec5SDimitry Andric 
writeDIImportedEntity(raw_ostream & Out,const DIImportedEntity * N,AsmWriterContext & WriterCtx)25230b57cec5SDimitry Andric static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N,
2524349cc55cSDimitry Andric                                   AsmWriterContext &WriterCtx) {
25250b57cec5SDimitry Andric   Out << "!DIImportedEntity(";
2526349cc55cSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
25270b57cec5SDimitry Andric   Printer.printTag(N);
25280b57cec5SDimitry Andric   Printer.printString("name", N->getName());
25290b57cec5SDimitry Andric   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
25300b57cec5SDimitry Andric   Printer.printMetadata("entity", N->getRawEntity());
25310b57cec5SDimitry Andric   Printer.printMetadata("file", N->getRawFile());
25320b57cec5SDimitry Andric   Printer.printInt("line", N->getLine());
2533349cc55cSDimitry Andric   Printer.printMetadata("elements", N->getRawElements());
25340b57cec5SDimitry Andric   Out << ")";
25350b57cec5SDimitry Andric }
25360b57cec5SDimitry Andric 
WriteMDNodeBodyInternal(raw_ostream & Out,const MDNode * Node,AsmWriterContext & Ctx)25370b57cec5SDimitry Andric static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
2538349cc55cSDimitry Andric                                     AsmWriterContext &Ctx) {
25390b57cec5SDimitry Andric   if (Node->isDistinct())
25400b57cec5SDimitry Andric     Out << "distinct ";
25410b57cec5SDimitry Andric   else if (Node->isTemporary())
25420b57cec5SDimitry Andric     Out << "<temporary!> "; // Handle broken code.
25430b57cec5SDimitry Andric 
25440b57cec5SDimitry Andric   switch (Node->getMetadataID()) {
25450b57cec5SDimitry Andric   default:
25460b57cec5SDimitry Andric     llvm_unreachable("Expected uniquable MDNode");
25470b57cec5SDimitry Andric #define HANDLE_MDNODE_LEAF(CLASS)                                              \
25480b57cec5SDimitry Andric   case Metadata::CLASS##Kind:                                                  \
2549349cc55cSDimitry Andric     write##CLASS(Out, cast<CLASS>(Node), Ctx);                                 \
25500b57cec5SDimitry Andric     break;
25510b57cec5SDimitry Andric #include "llvm/IR/Metadata.def"
25520b57cec5SDimitry Andric   }
25530b57cec5SDimitry Andric }
25540b57cec5SDimitry Andric 
25550b57cec5SDimitry Andric // Full implementation of printing a Value as an operand with support for
25560b57cec5SDimitry Andric // TypePrinting, etc.
WriteAsOperandInternal(raw_ostream & Out,const Value * V,AsmWriterContext & WriterCtx)25570b57cec5SDimitry Andric static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
2558349cc55cSDimitry Andric                                    AsmWriterContext &WriterCtx) {
25590b57cec5SDimitry Andric   if (V->hasName()) {
25600b57cec5SDimitry Andric     PrintLLVMName(Out, V);
25610b57cec5SDimitry Andric     return;
25620b57cec5SDimitry Andric   }
25630b57cec5SDimitry Andric 
25640b57cec5SDimitry Andric   const Constant *CV = dyn_cast<Constant>(V);
25650b57cec5SDimitry Andric   if (CV && !isa<GlobalValue>(CV)) {
2566349cc55cSDimitry Andric     assert(WriterCtx.TypePrinter && "Constants require TypePrinting!");
2567349cc55cSDimitry Andric     WriteConstantInternal(Out, CV, WriterCtx);
25680b57cec5SDimitry Andric     return;
25690b57cec5SDimitry Andric   }
25700b57cec5SDimitry Andric 
25710b57cec5SDimitry Andric   if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
25720b57cec5SDimitry Andric     Out << "asm ";
25730b57cec5SDimitry Andric     if (IA->hasSideEffects())
25740b57cec5SDimitry Andric       Out << "sideeffect ";
25750b57cec5SDimitry Andric     if (IA->isAlignStack())
25760b57cec5SDimitry Andric       Out << "alignstack ";
25770b57cec5SDimitry Andric     // We don't emit the AD_ATT dialect as it's the assumed default.
25780b57cec5SDimitry Andric     if (IA->getDialect() == InlineAsm::AD_Intel)
25790b57cec5SDimitry Andric       Out << "inteldialect ";
2580fe6060f1SDimitry Andric     if (IA->canThrow())
2581fe6060f1SDimitry Andric       Out << "unwind ";
25820b57cec5SDimitry Andric     Out << '"';
25830b57cec5SDimitry Andric     printEscapedString(IA->getAsmString(), Out);
25840b57cec5SDimitry Andric     Out << "\", \"";
25850b57cec5SDimitry Andric     printEscapedString(IA->getConstraintString(), Out);
25860b57cec5SDimitry Andric     Out << '"';
25870b57cec5SDimitry Andric     return;
25880b57cec5SDimitry Andric   }
25890b57cec5SDimitry Andric 
25900b57cec5SDimitry Andric   if (auto *MD = dyn_cast<MetadataAsValue>(V)) {
2591349cc55cSDimitry Andric     WriteAsOperandInternal(Out, MD->getMetadata(), WriterCtx,
2592349cc55cSDimitry Andric                            /* FromValue */ true);
25930b57cec5SDimitry Andric     return;
25940b57cec5SDimitry Andric   }
25950b57cec5SDimitry Andric 
25960b57cec5SDimitry Andric   char Prefix = '%';
25970b57cec5SDimitry Andric   int Slot;
2598349cc55cSDimitry Andric   auto *Machine = WriterCtx.Machine;
25990b57cec5SDimitry Andric   // If we have a SlotTracker, use it.
26000b57cec5SDimitry Andric   if (Machine) {
26010b57cec5SDimitry Andric     if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
26020b57cec5SDimitry Andric       Slot = Machine->getGlobalSlot(GV);
26030b57cec5SDimitry Andric       Prefix = '@';
26040b57cec5SDimitry Andric     } else {
26050b57cec5SDimitry Andric       Slot = Machine->getLocalSlot(V);
26060b57cec5SDimitry Andric 
26070b57cec5SDimitry Andric       // If the local value didn't succeed, then we may be referring to a value
26080b57cec5SDimitry Andric       // from a different function.  Translate it, as this can happen when using
26090b57cec5SDimitry Andric       // address of blocks.
26100b57cec5SDimitry Andric       if (Slot == -1)
26110b57cec5SDimitry Andric         if ((Machine = createSlotTracker(V))) {
26120b57cec5SDimitry Andric           Slot = Machine->getLocalSlot(V);
26130b57cec5SDimitry Andric           delete Machine;
26140b57cec5SDimitry Andric         }
26150b57cec5SDimitry Andric     }
26160b57cec5SDimitry Andric   } else if ((Machine = createSlotTracker(V))) {
26170b57cec5SDimitry Andric     // Otherwise, create one to get the # and then destroy it.
26180b57cec5SDimitry Andric     if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
26190b57cec5SDimitry Andric       Slot = Machine->getGlobalSlot(GV);
26200b57cec5SDimitry Andric       Prefix = '@';
26210b57cec5SDimitry Andric     } else {
26220b57cec5SDimitry Andric       Slot = Machine->getLocalSlot(V);
26230b57cec5SDimitry Andric     }
26240b57cec5SDimitry Andric     delete Machine;
26250b57cec5SDimitry Andric     Machine = nullptr;
26260b57cec5SDimitry Andric   } else {
26270b57cec5SDimitry Andric     Slot = -1;
26280b57cec5SDimitry Andric   }
26290b57cec5SDimitry Andric 
26300b57cec5SDimitry Andric   if (Slot != -1)
26310b57cec5SDimitry Andric     Out << Prefix << Slot;
26320b57cec5SDimitry Andric   else
26330b57cec5SDimitry Andric     Out << "<badref>";
26340b57cec5SDimitry Andric }
26350b57cec5SDimitry Andric 
WriteAsOperandInternal(raw_ostream & Out,const Metadata * MD,AsmWriterContext & WriterCtx,bool FromValue)26360b57cec5SDimitry Andric static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
2637349cc55cSDimitry Andric                                    AsmWriterContext &WriterCtx,
26380b57cec5SDimitry Andric                                    bool FromValue) {
2639fe6060f1SDimitry Andric   // Write DIExpressions and DIArgLists inline when used as a value. Improves
2640fe6060f1SDimitry Andric   // readability of debug info intrinsics.
26410b57cec5SDimitry Andric   if (const DIExpression *Expr = dyn_cast<DIExpression>(MD)) {
2642349cc55cSDimitry Andric     writeDIExpression(Out, Expr, WriterCtx);
26430b57cec5SDimitry Andric     return;
26440b57cec5SDimitry Andric   }
2645fe6060f1SDimitry Andric   if (const DIArgList *ArgList = dyn_cast<DIArgList>(MD)) {
2646349cc55cSDimitry Andric     writeDIArgList(Out, ArgList, WriterCtx, FromValue);
2647fe6060f1SDimitry Andric     return;
2648fe6060f1SDimitry Andric   }
26490b57cec5SDimitry Andric 
26500b57cec5SDimitry Andric   if (const MDNode *N = dyn_cast<MDNode>(MD)) {
26510b57cec5SDimitry Andric     std::unique_ptr<SlotTracker> MachineStorage;
2652bdd1243dSDimitry Andric     SaveAndRestore SARMachine(WriterCtx.Machine);
2653349cc55cSDimitry Andric     if (!WriterCtx.Machine) {
2654349cc55cSDimitry Andric       MachineStorage = std::make_unique<SlotTracker>(WriterCtx.Context);
2655349cc55cSDimitry Andric       WriterCtx.Machine = MachineStorage.get();
26560b57cec5SDimitry Andric     }
2657349cc55cSDimitry Andric     int Slot = WriterCtx.Machine->getMetadataSlot(N);
26580b57cec5SDimitry Andric     if (Slot == -1) {
26590b57cec5SDimitry Andric       if (const DILocation *Loc = dyn_cast<DILocation>(N)) {
2660349cc55cSDimitry Andric         writeDILocation(Out, Loc, WriterCtx);
26610b57cec5SDimitry Andric         return;
26620b57cec5SDimitry Andric       }
26630b57cec5SDimitry Andric       // Give the pointer value instead of "badref", since this comes up all
26640b57cec5SDimitry Andric       // the time when debugging.
26650b57cec5SDimitry Andric       Out << "<" << N << ">";
26660b57cec5SDimitry Andric     } else
26670b57cec5SDimitry Andric       Out << '!' << Slot;
26680b57cec5SDimitry Andric     return;
26690b57cec5SDimitry Andric   }
26700b57cec5SDimitry Andric 
26710b57cec5SDimitry Andric   if (const MDString *MDS = dyn_cast<MDString>(MD)) {
26720b57cec5SDimitry Andric     Out << "!\"";
26730b57cec5SDimitry Andric     printEscapedString(MDS->getString(), Out);
26740b57cec5SDimitry Andric     Out << '"';
26750b57cec5SDimitry Andric     return;
26760b57cec5SDimitry Andric   }
26770b57cec5SDimitry Andric 
26780b57cec5SDimitry Andric   auto *V = cast<ValueAsMetadata>(MD);
2679349cc55cSDimitry Andric   assert(WriterCtx.TypePrinter && "TypePrinter required for metadata values");
26800b57cec5SDimitry Andric   assert((FromValue || !isa<LocalAsMetadata>(V)) &&
26810b57cec5SDimitry Andric          "Unexpected function-local metadata outside of value argument");
26820b57cec5SDimitry Andric 
2683349cc55cSDimitry Andric   WriterCtx.TypePrinter->print(V->getValue()->getType(), Out);
26840b57cec5SDimitry Andric   Out << ' ';
2685349cc55cSDimitry Andric   WriteAsOperandInternal(Out, V->getValue(), WriterCtx);
26860b57cec5SDimitry Andric }
26870b57cec5SDimitry Andric 
26880b57cec5SDimitry Andric namespace {
26890b57cec5SDimitry Andric 
26900b57cec5SDimitry Andric class AssemblyWriter {
26910b57cec5SDimitry Andric   formatted_raw_ostream &Out;
26920b57cec5SDimitry Andric   const Module *TheModule = nullptr;
26930b57cec5SDimitry Andric   const ModuleSummaryIndex *TheIndex = nullptr;
26940b57cec5SDimitry Andric   std::unique_ptr<SlotTracker> SlotTrackerStorage;
26950b57cec5SDimitry Andric   SlotTracker &Machine;
26960b57cec5SDimitry Andric   TypePrinting TypePrinter;
26970b57cec5SDimitry Andric   AssemblyAnnotationWriter *AnnotationWriter = nullptr;
26980b57cec5SDimitry Andric   SetVector<const Comdat *> Comdats;
26990b57cec5SDimitry Andric   bool IsForDebug;
27000b57cec5SDimitry Andric   bool ShouldPreserveUseListOrder;
2701fe6060f1SDimitry Andric   UseListOrderMap UseListOrders;
27020b57cec5SDimitry Andric   SmallVector<StringRef, 8> MDNames;
27030b57cec5SDimitry Andric   /// Synchronization scope names registered with LLVMContext.
27040b57cec5SDimitry Andric   SmallVector<StringRef, 8> SSNs;
27050b57cec5SDimitry Andric   DenseMap<const GlobalValueSummary *, GlobalValue::GUID> SummaryToGUIDMap;
27060b57cec5SDimitry Andric 
27070b57cec5SDimitry Andric public:
27080b57cec5SDimitry Andric   /// Construct an AssemblyWriter with an external SlotTracker
27090b57cec5SDimitry Andric   AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, const Module *M,
27100b57cec5SDimitry Andric                  AssemblyAnnotationWriter *AAW, bool IsForDebug,
27110b57cec5SDimitry Andric                  bool ShouldPreserveUseListOrder = false);
27120b57cec5SDimitry Andric 
27130b57cec5SDimitry Andric   AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
27140b57cec5SDimitry Andric                  const ModuleSummaryIndex *Index, bool IsForDebug);
27150b57cec5SDimitry Andric 
getContext()2716349cc55cSDimitry Andric   AsmWriterContext getContext() {
2717349cc55cSDimitry Andric     return AsmWriterContext(&TypePrinter, &Machine, TheModule);
2718349cc55cSDimitry Andric   }
2719349cc55cSDimitry Andric 
27200b57cec5SDimitry Andric   void printMDNodeBody(const MDNode *MD);
27210b57cec5SDimitry Andric   void printNamedMDNode(const NamedMDNode *NMD);
27220b57cec5SDimitry Andric 
27230b57cec5SDimitry Andric   void printModule(const Module *M);
27240b57cec5SDimitry Andric 
27250b57cec5SDimitry Andric   void writeOperand(const Value *Op, bool PrintType);
27260b57cec5SDimitry Andric   void writeParamOperand(const Value *Operand, AttributeSet Attrs);
27270b57cec5SDimitry Andric   void writeOperandBundles(const CallBase *Call);
27280b57cec5SDimitry Andric   void writeSyncScope(const LLVMContext &Context,
27290b57cec5SDimitry Andric                       SyncScope::ID SSID);
27300b57cec5SDimitry Andric   void writeAtomic(const LLVMContext &Context,
27310b57cec5SDimitry Andric                    AtomicOrdering Ordering,
27320b57cec5SDimitry Andric                    SyncScope::ID SSID);
27330b57cec5SDimitry Andric   void writeAtomicCmpXchg(const LLVMContext &Context,
27340b57cec5SDimitry Andric                           AtomicOrdering SuccessOrdering,
27350b57cec5SDimitry Andric                           AtomicOrdering FailureOrdering,
27360b57cec5SDimitry Andric                           SyncScope::ID SSID);
27370b57cec5SDimitry Andric 
27380b57cec5SDimitry Andric   void writeAllMDNodes();
27390b57cec5SDimitry Andric   void writeMDNode(unsigned Slot, const MDNode *Node);
2740480093f4SDimitry Andric   void writeAttribute(const Attribute &Attr, bool InAttrGroup = false);
2741480093f4SDimitry Andric   void writeAttributeSet(const AttributeSet &AttrSet, bool InAttrGroup = false);
27420b57cec5SDimitry Andric   void writeAllAttributeGroups();
27430b57cec5SDimitry Andric 
27440b57cec5SDimitry Andric   void printTypeIdentities();
27450b57cec5SDimitry Andric   void printGlobal(const GlobalVariable *GV);
2746349cc55cSDimitry Andric   void printAlias(const GlobalAlias *GA);
2747349cc55cSDimitry Andric   void printIFunc(const GlobalIFunc *GI);
27480b57cec5SDimitry Andric   void printComdat(const Comdat *C);
27490b57cec5SDimitry Andric   void printFunction(const Function *F);
27500b57cec5SDimitry Andric   void printArgument(const Argument *FA, AttributeSet Attrs);
27510b57cec5SDimitry Andric   void printBasicBlock(const BasicBlock *BB);
27520b57cec5SDimitry Andric   void printInstructionLine(const Instruction &I);
27530b57cec5SDimitry Andric   void printInstruction(const Instruction &I);
2754*0fca6ea1SDimitry Andric   void printDbgMarker(const DbgMarker &DPI);
2755*0fca6ea1SDimitry Andric   void printDbgVariableRecord(const DbgVariableRecord &DVR);
2756*0fca6ea1SDimitry Andric   void printDbgLabelRecord(const DbgLabelRecord &DLR);
2757*0fca6ea1SDimitry Andric   void printDbgRecord(const DbgRecord &DR);
2758*0fca6ea1SDimitry Andric   void printDbgRecordLine(const DbgRecord &DR);
27590b57cec5SDimitry Andric 
2760fe6060f1SDimitry Andric   void printUseListOrder(const Value *V, const std::vector<unsigned> &Shuffle);
27610b57cec5SDimitry Andric   void printUseLists(const Function *F);
27620b57cec5SDimitry Andric 
27630b57cec5SDimitry Andric   void printModuleSummaryIndex();
27640b57cec5SDimitry Andric   void printSummaryInfo(unsigned Slot, const ValueInfo &VI);
27650b57cec5SDimitry Andric   void printSummary(const GlobalValueSummary &Summary);
27660b57cec5SDimitry Andric   void printAliasSummary(const AliasSummary *AS);
27670b57cec5SDimitry Andric   void printGlobalVarSummary(const GlobalVarSummary *GS);
27680b57cec5SDimitry Andric   void printFunctionSummary(const FunctionSummary *FS);
27690b57cec5SDimitry Andric   void printTypeIdSummary(const TypeIdSummary &TIS);
27700b57cec5SDimitry Andric   void printTypeIdCompatibleVtableSummary(const TypeIdCompatibleVtableInfo &TI);
27710b57cec5SDimitry Andric   void printTypeTestResolution(const TypeTestResolution &TTRes);
27720b57cec5SDimitry Andric   void printArgs(const std::vector<uint64_t> &Args);
27730b57cec5SDimitry Andric   void printWPDRes(const WholeProgramDevirtResolution &WPDRes);
27740b57cec5SDimitry Andric   void printTypeIdInfo(const FunctionSummary::TypeIdInfo &TIDInfo);
27750b57cec5SDimitry Andric   void printVFuncId(const FunctionSummary::VFuncId VFId);
27760b57cec5SDimitry Andric   void
27775ffd83dbSDimitry Andric   printNonConstVCalls(const std::vector<FunctionSummary::VFuncId> &VCallList,
27780b57cec5SDimitry Andric                       const char *Tag);
27790b57cec5SDimitry Andric   void
27805ffd83dbSDimitry Andric   printConstVCalls(const std::vector<FunctionSummary::ConstVCall> &VCallList,
27810b57cec5SDimitry Andric                    const char *Tag);
27820b57cec5SDimitry Andric 
27830b57cec5SDimitry Andric private:
27840b57cec5SDimitry Andric   /// Print out metadata attachments.
27850b57cec5SDimitry Andric   void printMetadataAttachments(
27860b57cec5SDimitry Andric       const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
27870b57cec5SDimitry Andric       StringRef Separator);
27880b57cec5SDimitry Andric 
27890b57cec5SDimitry Andric   // printInfoComment - Print a little comment after the instruction indicating
27900b57cec5SDimitry Andric   // which slot it occupies.
27910b57cec5SDimitry Andric   void printInfoComment(const Value &V);
27920b57cec5SDimitry Andric 
27930b57cec5SDimitry Andric   // printGCRelocateComment - print comment after call to the gc.relocate
27940b57cec5SDimitry Andric   // intrinsic indicating base and derived pointer names.
27950b57cec5SDimitry Andric   void printGCRelocateComment(const GCRelocateInst &Relocate);
27960b57cec5SDimitry Andric };
27970b57cec5SDimitry Andric 
27980b57cec5SDimitry Andric } // end anonymous namespace
27990b57cec5SDimitry Andric 
AssemblyWriter(formatted_raw_ostream & o,SlotTracker & Mac,const Module * M,AssemblyAnnotationWriter * AAW,bool IsForDebug,bool ShouldPreserveUseListOrder)28000b57cec5SDimitry Andric AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
28010b57cec5SDimitry Andric                                const Module *M, AssemblyAnnotationWriter *AAW,
28020b57cec5SDimitry Andric                                bool IsForDebug, bool ShouldPreserveUseListOrder)
28030b57cec5SDimitry Andric     : Out(o), TheModule(M), Machine(Mac), TypePrinter(M), AnnotationWriter(AAW),
28040b57cec5SDimitry Andric       IsForDebug(IsForDebug),
28050b57cec5SDimitry Andric       ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
28060b57cec5SDimitry Andric   if (!TheModule)
28070b57cec5SDimitry Andric     return;
28080b57cec5SDimitry Andric   for (const GlobalObject &GO : TheModule->global_objects())
28090b57cec5SDimitry Andric     if (const Comdat *C = GO.getComdat())
28100b57cec5SDimitry Andric       Comdats.insert(C);
28110b57cec5SDimitry Andric }
28120b57cec5SDimitry Andric 
AssemblyWriter(formatted_raw_ostream & o,SlotTracker & Mac,const ModuleSummaryIndex * Index,bool IsForDebug)28130b57cec5SDimitry Andric AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
28140b57cec5SDimitry Andric                                const ModuleSummaryIndex *Index, bool IsForDebug)
28150b57cec5SDimitry Andric     : Out(o), TheIndex(Index), Machine(Mac), TypePrinter(/*Module=*/nullptr),
28160b57cec5SDimitry Andric       IsForDebug(IsForDebug), ShouldPreserveUseListOrder(false) {}
28170b57cec5SDimitry Andric 
writeOperand(const Value * Operand,bool PrintType)28180b57cec5SDimitry Andric void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
28190b57cec5SDimitry Andric   if (!Operand) {
28200b57cec5SDimitry Andric     Out << "<null operand!>";
28210b57cec5SDimitry Andric     return;
28220b57cec5SDimitry Andric   }
28230b57cec5SDimitry Andric   if (PrintType) {
28240b57cec5SDimitry Andric     TypePrinter.print(Operand->getType(), Out);
28250b57cec5SDimitry Andric     Out << ' ';
28260b57cec5SDimitry Andric   }
2827349cc55cSDimitry Andric   auto WriterCtx = getContext();
2828349cc55cSDimitry Andric   WriteAsOperandInternal(Out, Operand, WriterCtx);
28290b57cec5SDimitry Andric }
28300b57cec5SDimitry Andric 
writeSyncScope(const LLVMContext & Context,SyncScope::ID SSID)28310b57cec5SDimitry Andric void AssemblyWriter::writeSyncScope(const LLVMContext &Context,
28320b57cec5SDimitry Andric                                     SyncScope::ID SSID) {
28330b57cec5SDimitry Andric   switch (SSID) {
28340b57cec5SDimitry Andric   case SyncScope::System: {
28350b57cec5SDimitry Andric     break;
28360b57cec5SDimitry Andric   }
28370b57cec5SDimitry Andric   default: {
28380b57cec5SDimitry Andric     if (SSNs.empty())
28390b57cec5SDimitry Andric       Context.getSyncScopeNames(SSNs);
28400b57cec5SDimitry Andric 
28410b57cec5SDimitry Andric     Out << " syncscope(\"";
28420b57cec5SDimitry Andric     printEscapedString(SSNs[SSID], Out);
28430b57cec5SDimitry Andric     Out << "\")";
28440b57cec5SDimitry Andric     break;
28450b57cec5SDimitry Andric   }
28460b57cec5SDimitry Andric   }
28470b57cec5SDimitry Andric }
28480b57cec5SDimitry Andric 
writeAtomic(const LLVMContext & Context,AtomicOrdering Ordering,SyncScope::ID SSID)28490b57cec5SDimitry Andric void AssemblyWriter::writeAtomic(const LLVMContext &Context,
28500b57cec5SDimitry Andric                                  AtomicOrdering Ordering,
28510b57cec5SDimitry Andric                                  SyncScope::ID SSID) {
28520b57cec5SDimitry Andric   if (Ordering == AtomicOrdering::NotAtomic)
28530b57cec5SDimitry Andric     return;
28540b57cec5SDimitry Andric 
28550b57cec5SDimitry Andric   writeSyncScope(Context, SSID);
28560b57cec5SDimitry Andric   Out << " " << toIRString(Ordering);
28570b57cec5SDimitry Andric }
28580b57cec5SDimitry Andric 
writeAtomicCmpXchg(const LLVMContext & Context,AtomicOrdering SuccessOrdering,AtomicOrdering FailureOrdering,SyncScope::ID SSID)28590b57cec5SDimitry Andric void AssemblyWriter::writeAtomicCmpXchg(const LLVMContext &Context,
28600b57cec5SDimitry Andric                                         AtomicOrdering SuccessOrdering,
28610b57cec5SDimitry Andric                                         AtomicOrdering FailureOrdering,
28620b57cec5SDimitry Andric                                         SyncScope::ID SSID) {
28630b57cec5SDimitry Andric   assert(SuccessOrdering != AtomicOrdering::NotAtomic &&
28640b57cec5SDimitry Andric          FailureOrdering != AtomicOrdering::NotAtomic);
28650b57cec5SDimitry Andric 
28660b57cec5SDimitry Andric   writeSyncScope(Context, SSID);
28670b57cec5SDimitry Andric   Out << " " << toIRString(SuccessOrdering);
28680b57cec5SDimitry Andric   Out << " " << toIRString(FailureOrdering);
28690b57cec5SDimitry Andric }
28700b57cec5SDimitry Andric 
writeParamOperand(const Value * Operand,AttributeSet Attrs)28710b57cec5SDimitry Andric void AssemblyWriter::writeParamOperand(const Value *Operand,
28720b57cec5SDimitry Andric                                        AttributeSet Attrs) {
28730b57cec5SDimitry Andric   if (!Operand) {
28740b57cec5SDimitry Andric     Out << "<null operand!>";
28750b57cec5SDimitry Andric     return;
28760b57cec5SDimitry Andric   }
28770b57cec5SDimitry Andric 
28780b57cec5SDimitry Andric   // Print the type
28790b57cec5SDimitry Andric   TypePrinter.print(Operand->getType(), Out);
28800b57cec5SDimitry Andric   // Print parameter attributes list
2881480093f4SDimitry Andric   if (Attrs.hasAttributes()) {
2882480093f4SDimitry Andric     Out << ' ';
2883480093f4SDimitry Andric     writeAttributeSet(Attrs);
2884480093f4SDimitry Andric   }
28850b57cec5SDimitry Andric   Out << ' ';
28860b57cec5SDimitry Andric   // Print the operand
2887349cc55cSDimitry Andric   auto WriterCtx = getContext();
2888349cc55cSDimitry Andric   WriteAsOperandInternal(Out, Operand, WriterCtx);
28890b57cec5SDimitry Andric }
28900b57cec5SDimitry Andric 
writeOperandBundles(const CallBase * Call)28910b57cec5SDimitry Andric void AssemblyWriter::writeOperandBundles(const CallBase *Call) {
28920b57cec5SDimitry Andric   if (!Call->hasOperandBundles())
28930b57cec5SDimitry Andric     return;
28940b57cec5SDimitry Andric 
28950b57cec5SDimitry Andric   Out << " [ ";
28960b57cec5SDimitry Andric 
28970b57cec5SDimitry Andric   bool FirstBundle = true;
28980b57cec5SDimitry Andric   for (unsigned i = 0, e = Call->getNumOperandBundles(); i != e; ++i) {
28990b57cec5SDimitry Andric     OperandBundleUse BU = Call->getOperandBundleAt(i);
29000b57cec5SDimitry Andric 
29010b57cec5SDimitry Andric     if (!FirstBundle)
29020b57cec5SDimitry Andric       Out << ", ";
29030b57cec5SDimitry Andric     FirstBundle = false;
29040b57cec5SDimitry Andric 
29050b57cec5SDimitry Andric     Out << '"';
29060b57cec5SDimitry Andric     printEscapedString(BU.getTagName(), Out);
29070b57cec5SDimitry Andric     Out << '"';
29080b57cec5SDimitry Andric 
29090b57cec5SDimitry Andric     Out << '(';
29100b57cec5SDimitry Andric 
29110b57cec5SDimitry Andric     bool FirstInput = true;
2912349cc55cSDimitry Andric     auto WriterCtx = getContext();
29130b57cec5SDimitry Andric     for (const auto &Input : BU.Inputs) {
29140b57cec5SDimitry Andric       if (!FirstInput)
29150b57cec5SDimitry Andric         Out << ", ";
29160b57cec5SDimitry Andric       FirstInput = false;
29170b57cec5SDimitry Andric 
2918bdd1243dSDimitry Andric       if (Input == nullptr)
2919bdd1243dSDimitry Andric         Out << "<null operand bundle!>";
2920bdd1243dSDimitry Andric       else {
29210b57cec5SDimitry Andric         TypePrinter.print(Input->getType(), Out);
29220b57cec5SDimitry Andric         Out << " ";
2923349cc55cSDimitry Andric         WriteAsOperandInternal(Out, Input, WriterCtx);
29240b57cec5SDimitry Andric       }
2925bdd1243dSDimitry Andric     }
29260b57cec5SDimitry Andric 
29270b57cec5SDimitry Andric     Out << ')';
29280b57cec5SDimitry Andric   }
29290b57cec5SDimitry Andric 
29300b57cec5SDimitry Andric   Out << " ]";
29310b57cec5SDimitry Andric }
29320b57cec5SDimitry Andric 
printModule(const Module * M)29330b57cec5SDimitry Andric void AssemblyWriter::printModule(const Module *M) {
29340b57cec5SDimitry Andric   Machine.initializeIfNeeded();
29350b57cec5SDimitry Andric 
29360b57cec5SDimitry Andric   if (ShouldPreserveUseListOrder)
29370b57cec5SDimitry Andric     UseListOrders = predictUseListOrder(M);
29380b57cec5SDimitry Andric 
29390b57cec5SDimitry Andric   if (!M->getModuleIdentifier().empty() &&
29400b57cec5SDimitry Andric       // Don't print the ID if it will start a new line (which would
29410b57cec5SDimitry Andric       // require a comment char before it).
29420b57cec5SDimitry Andric       M->getModuleIdentifier().find('\n') == std::string::npos)
29430b57cec5SDimitry Andric     Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
29440b57cec5SDimitry Andric 
29450b57cec5SDimitry Andric   if (!M->getSourceFileName().empty()) {
29460b57cec5SDimitry Andric     Out << "source_filename = \"";
29470b57cec5SDimitry Andric     printEscapedString(M->getSourceFileName(), Out);
29480b57cec5SDimitry Andric     Out << "\"\n";
29490b57cec5SDimitry Andric   }
29500b57cec5SDimitry Andric 
29510b57cec5SDimitry Andric   const std::string &DL = M->getDataLayoutStr();
29520b57cec5SDimitry Andric   if (!DL.empty())
29530b57cec5SDimitry Andric     Out << "target datalayout = \"" << DL << "\"\n";
29540b57cec5SDimitry Andric   if (!M->getTargetTriple().empty())
29550b57cec5SDimitry Andric     Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
29560b57cec5SDimitry Andric 
29570b57cec5SDimitry Andric   if (!M->getModuleInlineAsm().empty()) {
29580b57cec5SDimitry Andric     Out << '\n';
29590b57cec5SDimitry Andric 
29600b57cec5SDimitry Andric     // Split the string into lines, to make it easier to read the .ll file.
29610b57cec5SDimitry Andric     StringRef Asm = M->getModuleInlineAsm();
29620b57cec5SDimitry Andric     do {
29630b57cec5SDimitry Andric       StringRef Front;
29640b57cec5SDimitry Andric       std::tie(Front, Asm) = Asm.split('\n');
29650b57cec5SDimitry Andric 
29660b57cec5SDimitry Andric       // We found a newline, print the portion of the asm string from the
29670b57cec5SDimitry Andric       // last newline up to this newline.
29680b57cec5SDimitry Andric       Out << "module asm \"";
29690b57cec5SDimitry Andric       printEscapedString(Front, Out);
29700b57cec5SDimitry Andric       Out << "\"\n";
29710b57cec5SDimitry Andric     } while (!Asm.empty());
29720b57cec5SDimitry Andric   }
29730b57cec5SDimitry Andric 
29740b57cec5SDimitry Andric   printTypeIdentities();
29750b57cec5SDimitry Andric 
29760b57cec5SDimitry Andric   // Output all comdats.
29770b57cec5SDimitry Andric   if (!Comdats.empty())
29780b57cec5SDimitry Andric     Out << '\n';
29790b57cec5SDimitry Andric   for (const Comdat *C : Comdats) {
29800b57cec5SDimitry Andric     printComdat(C);
29810b57cec5SDimitry Andric     if (C != Comdats.back())
29820b57cec5SDimitry Andric       Out << '\n';
29830b57cec5SDimitry Andric   }
29840b57cec5SDimitry Andric 
29850b57cec5SDimitry Andric   // Output all globals.
29860b57cec5SDimitry Andric   if (!M->global_empty()) Out << '\n';
29870b57cec5SDimitry Andric   for (const GlobalVariable &GV : M->globals()) {
29880b57cec5SDimitry Andric     printGlobal(&GV); Out << '\n';
29890b57cec5SDimitry Andric   }
29900b57cec5SDimitry Andric 
29910b57cec5SDimitry Andric   // Output all aliases.
29920b57cec5SDimitry Andric   if (!M->alias_empty()) Out << "\n";
29930b57cec5SDimitry Andric   for (const GlobalAlias &GA : M->aliases())
2994349cc55cSDimitry Andric     printAlias(&GA);
29950b57cec5SDimitry Andric 
29960b57cec5SDimitry Andric   // Output all ifuncs.
29970b57cec5SDimitry Andric   if (!M->ifunc_empty()) Out << "\n";
29980b57cec5SDimitry Andric   for (const GlobalIFunc &GI : M->ifuncs())
2999349cc55cSDimitry Andric     printIFunc(&GI);
30000b57cec5SDimitry Andric 
30010b57cec5SDimitry Andric   // Output all of the functions.
300213138422SDimitry Andric   for (const Function &F : *M) {
300313138422SDimitry Andric     Out << '\n';
30040b57cec5SDimitry Andric     printFunction(&F);
300513138422SDimitry Andric   }
3006fe6060f1SDimitry Andric 
3007fe6060f1SDimitry Andric   // Output global use-lists.
3008fe6060f1SDimitry Andric   printUseLists(nullptr);
30090b57cec5SDimitry Andric 
30100b57cec5SDimitry Andric   // Output all attribute groups.
30110b57cec5SDimitry Andric   if (!Machine.as_empty()) {
30120b57cec5SDimitry Andric     Out << '\n';
30130b57cec5SDimitry Andric     writeAllAttributeGroups();
30140b57cec5SDimitry Andric   }
30150b57cec5SDimitry Andric 
30160b57cec5SDimitry Andric   // Output named metadata.
30170b57cec5SDimitry Andric   if (!M->named_metadata_empty()) Out << '\n';
30180b57cec5SDimitry Andric 
30190b57cec5SDimitry Andric   for (const NamedMDNode &Node : M->named_metadata())
30200b57cec5SDimitry Andric     printNamedMDNode(&Node);
30210b57cec5SDimitry Andric 
30220b57cec5SDimitry Andric   // Output metadata.
30230b57cec5SDimitry Andric   if (!Machine.mdn_empty()) {
30240b57cec5SDimitry Andric     Out << '\n';
30250b57cec5SDimitry Andric     writeAllMDNodes();
30260b57cec5SDimitry Andric   }
30270b57cec5SDimitry Andric }
30280b57cec5SDimitry Andric 
printModuleSummaryIndex()30290b57cec5SDimitry Andric void AssemblyWriter::printModuleSummaryIndex() {
30300b57cec5SDimitry Andric   assert(TheIndex);
30315ffd83dbSDimitry Andric   int NumSlots = Machine.initializeIndexIfNeeded();
30320b57cec5SDimitry Andric 
30330b57cec5SDimitry Andric   Out << "\n";
30340b57cec5SDimitry Andric 
30350b57cec5SDimitry Andric   // Print module path entries. To print in order, add paths to a vector
30360b57cec5SDimitry Andric   // indexed by module slot.
30370b57cec5SDimitry Andric   std::vector<std::pair<std::string, ModuleHash>> moduleVec;
30385ffd83dbSDimitry Andric   std::string RegularLTOModuleName =
30395ffd83dbSDimitry Andric       ModuleSummaryIndex::getRegularLTOModuleName();
30400b57cec5SDimitry Andric   moduleVec.resize(TheIndex->modulePaths().size());
30415f757f3fSDimitry Andric   for (auto &[ModPath, ModHash] : TheIndex->modulePaths())
3042bdd1243dSDimitry Andric     moduleVec[Machine.getModulePathSlot(ModPath)] = std::make_pair(
30435f757f3fSDimitry Andric         // An empty module path is a special entry for a regular LTO module
30445f757f3fSDimitry Andric         // created during the thin link.
30455f757f3fSDimitry Andric         ModPath.empty() ? RegularLTOModuleName : std::string(ModPath), ModHash);
30460b57cec5SDimitry Andric 
30470b57cec5SDimitry Andric   unsigned i = 0;
30480b57cec5SDimitry Andric   for (auto &ModPair : moduleVec) {
30490b57cec5SDimitry Andric     Out << "^" << i++ << " = module: (";
30500b57cec5SDimitry Andric     Out << "path: \"";
30510b57cec5SDimitry Andric     printEscapedString(ModPair.first, Out);
30520b57cec5SDimitry Andric     Out << "\", hash: (";
30530b57cec5SDimitry Andric     FieldSeparator FS;
30540b57cec5SDimitry Andric     for (auto Hash : ModPair.second)
30550b57cec5SDimitry Andric       Out << FS << Hash;
30560b57cec5SDimitry Andric     Out << "))\n";
30570b57cec5SDimitry Andric   }
30580b57cec5SDimitry Andric 
30590b57cec5SDimitry Andric   // FIXME: Change AliasSummary to hold a ValueInfo instead of summary pointer
30600b57cec5SDimitry Andric   // for aliasee (then update BitcodeWriter.cpp and remove get/setAliaseeGUID).
30610b57cec5SDimitry Andric   for (auto &GlobalList : *TheIndex) {
30620b57cec5SDimitry Andric     auto GUID = GlobalList.first;
30630b57cec5SDimitry Andric     for (auto &Summary : GlobalList.second.SummaryList)
30640b57cec5SDimitry Andric       SummaryToGUIDMap[Summary.get()] = GUID;
30650b57cec5SDimitry Andric   }
30660b57cec5SDimitry Andric 
30670b57cec5SDimitry Andric   // Print the global value summary entries.
30680b57cec5SDimitry Andric   for (auto &GlobalList : *TheIndex) {
30690b57cec5SDimitry Andric     auto GUID = GlobalList.first;
30700b57cec5SDimitry Andric     auto VI = TheIndex->getValueInfo(GlobalList);
30710b57cec5SDimitry Andric     printSummaryInfo(Machine.getGUIDSlot(GUID), VI);
30720b57cec5SDimitry Andric   }
30730b57cec5SDimitry Andric 
30740b57cec5SDimitry Andric   // Print the TypeIdMap entries.
3075fe6060f1SDimitry Andric   for (const auto &TID : TheIndex->typeIds()) {
3076fe6060f1SDimitry Andric     Out << "^" << Machine.getTypeIdSlot(TID.second.first)
3077fe6060f1SDimitry Andric         << " = typeid: (name: \"" << TID.second.first << "\"";
3078fe6060f1SDimitry Andric     printTypeIdSummary(TID.second.second);
3079fe6060f1SDimitry Andric     Out << ") ; guid = " << TID.first << "\n";
30800b57cec5SDimitry Andric   }
30810b57cec5SDimitry Andric 
30820b57cec5SDimitry Andric   // Print the TypeIdCompatibleVtableMap entries.
30830b57cec5SDimitry Andric   for (auto &TId : TheIndex->typeIdCompatibleVtableMap()) {
30840b57cec5SDimitry Andric     auto GUID = GlobalValue::getGUID(TId.first);
30855f757f3fSDimitry Andric     Out << "^" << Machine.getTypeIdCompatibleVtableSlot(TId.first)
30860b57cec5SDimitry Andric         << " = typeidCompatibleVTable: (name: \"" << TId.first << "\"";
30870b57cec5SDimitry Andric     printTypeIdCompatibleVtableSummary(TId.second);
30880b57cec5SDimitry Andric     Out << ") ; guid = " << GUID << "\n";
30890b57cec5SDimitry Andric   }
30905ffd83dbSDimitry Andric 
30915ffd83dbSDimitry Andric   // Don't emit flags when it's not really needed (value is zero by default).
30925ffd83dbSDimitry Andric   if (TheIndex->getFlags()) {
30935ffd83dbSDimitry Andric     Out << "^" << NumSlots << " = flags: " << TheIndex->getFlags() << "\n";
30945ffd83dbSDimitry Andric     ++NumSlots;
30955ffd83dbSDimitry Andric   }
30965ffd83dbSDimitry Andric 
30975ffd83dbSDimitry Andric   Out << "^" << NumSlots << " = blockcount: " << TheIndex->getBlockCount()
30985ffd83dbSDimitry Andric       << "\n";
30990b57cec5SDimitry Andric }
31000b57cec5SDimitry Andric 
31010b57cec5SDimitry Andric static const char *
getWholeProgDevirtResKindName(WholeProgramDevirtResolution::Kind K)31020b57cec5SDimitry Andric getWholeProgDevirtResKindName(WholeProgramDevirtResolution::Kind K) {
31030b57cec5SDimitry Andric   switch (K) {
31040b57cec5SDimitry Andric   case WholeProgramDevirtResolution::Indir:
31050b57cec5SDimitry Andric     return "indir";
31060b57cec5SDimitry Andric   case WholeProgramDevirtResolution::SingleImpl:
31070b57cec5SDimitry Andric     return "singleImpl";
31080b57cec5SDimitry Andric   case WholeProgramDevirtResolution::BranchFunnel:
31090b57cec5SDimitry Andric     return "branchFunnel";
31100b57cec5SDimitry Andric   }
31110b57cec5SDimitry Andric   llvm_unreachable("invalid WholeProgramDevirtResolution kind");
31120b57cec5SDimitry Andric }
31130b57cec5SDimitry Andric 
getWholeProgDevirtResByArgKindName(WholeProgramDevirtResolution::ByArg::Kind K)31140b57cec5SDimitry Andric static const char *getWholeProgDevirtResByArgKindName(
31150b57cec5SDimitry Andric     WholeProgramDevirtResolution::ByArg::Kind K) {
31160b57cec5SDimitry Andric   switch (K) {
31170b57cec5SDimitry Andric   case WholeProgramDevirtResolution::ByArg::Indir:
31180b57cec5SDimitry Andric     return "indir";
31190b57cec5SDimitry Andric   case WholeProgramDevirtResolution::ByArg::UniformRetVal:
31200b57cec5SDimitry Andric     return "uniformRetVal";
31210b57cec5SDimitry Andric   case WholeProgramDevirtResolution::ByArg::UniqueRetVal:
31220b57cec5SDimitry Andric     return "uniqueRetVal";
31230b57cec5SDimitry Andric   case WholeProgramDevirtResolution::ByArg::VirtualConstProp:
31240b57cec5SDimitry Andric     return "virtualConstProp";
31250b57cec5SDimitry Andric   }
31260b57cec5SDimitry Andric   llvm_unreachable("invalid WholeProgramDevirtResolution::ByArg kind");
31270b57cec5SDimitry Andric }
31280b57cec5SDimitry Andric 
getTTResKindName(TypeTestResolution::Kind K)31290b57cec5SDimitry Andric static const char *getTTResKindName(TypeTestResolution::Kind K) {
31300b57cec5SDimitry Andric   switch (K) {
31315ffd83dbSDimitry Andric   case TypeTestResolution::Unknown:
31325ffd83dbSDimitry Andric     return "unknown";
31330b57cec5SDimitry Andric   case TypeTestResolution::Unsat:
31340b57cec5SDimitry Andric     return "unsat";
31350b57cec5SDimitry Andric   case TypeTestResolution::ByteArray:
31360b57cec5SDimitry Andric     return "byteArray";
31370b57cec5SDimitry Andric   case TypeTestResolution::Inline:
31380b57cec5SDimitry Andric     return "inline";
31390b57cec5SDimitry Andric   case TypeTestResolution::Single:
31400b57cec5SDimitry Andric     return "single";
31410b57cec5SDimitry Andric   case TypeTestResolution::AllOnes:
31420b57cec5SDimitry Andric     return "allOnes";
31430b57cec5SDimitry Andric   }
31440b57cec5SDimitry Andric   llvm_unreachable("invalid TypeTestResolution kind");
31450b57cec5SDimitry Andric }
31460b57cec5SDimitry Andric 
printTypeTestResolution(const TypeTestResolution & TTRes)31470b57cec5SDimitry Andric void AssemblyWriter::printTypeTestResolution(const TypeTestResolution &TTRes) {
31480b57cec5SDimitry Andric   Out << "typeTestRes: (kind: " << getTTResKindName(TTRes.TheKind)
31490b57cec5SDimitry Andric       << ", sizeM1BitWidth: " << TTRes.SizeM1BitWidth;
31500b57cec5SDimitry Andric 
31510b57cec5SDimitry Andric   // The following fields are only used if the target does not support the use
31520b57cec5SDimitry Andric   // of absolute symbols to store constants. Print only if non-zero.
31530b57cec5SDimitry Andric   if (TTRes.AlignLog2)
31540b57cec5SDimitry Andric     Out << ", alignLog2: " << TTRes.AlignLog2;
31550b57cec5SDimitry Andric   if (TTRes.SizeM1)
31560b57cec5SDimitry Andric     Out << ", sizeM1: " << TTRes.SizeM1;
31570b57cec5SDimitry Andric   if (TTRes.BitMask)
31580b57cec5SDimitry Andric     // BitMask is uint8_t which causes it to print the corresponding char.
31590b57cec5SDimitry Andric     Out << ", bitMask: " << (unsigned)TTRes.BitMask;
31600b57cec5SDimitry Andric   if (TTRes.InlineBits)
31610b57cec5SDimitry Andric     Out << ", inlineBits: " << TTRes.InlineBits;
31620b57cec5SDimitry Andric 
31630b57cec5SDimitry Andric   Out << ")";
31640b57cec5SDimitry Andric }
31650b57cec5SDimitry Andric 
printTypeIdSummary(const TypeIdSummary & TIS)31660b57cec5SDimitry Andric void AssemblyWriter::printTypeIdSummary(const TypeIdSummary &TIS) {
31670b57cec5SDimitry Andric   Out << ", summary: (";
31680b57cec5SDimitry Andric   printTypeTestResolution(TIS.TTRes);
31690b57cec5SDimitry Andric   if (!TIS.WPDRes.empty()) {
31700b57cec5SDimitry Andric     Out << ", wpdResolutions: (";
31710b57cec5SDimitry Andric     FieldSeparator FS;
31720b57cec5SDimitry Andric     for (auto &WPDRes : TIS.WPDRes) {
31730b57cec5SDimitry Andric       Out << FS;
31740b57cec5SDimitry Andric       Out << "(offset: " << WPDRes.first << ", ";
31750b57cec5SDimitry Andric       printWPDRes(WPDRes.second);
31760b57cec5SDimitry Andric       Out << ")";
31770b57cec5SDimitry Andric     }
31780b57cec5SDimitry Andric     Out << ")";
31790b57cec5SDimitry Andric   }
31800b57cec5SDimitry Andric   Out << ")";
31810b57cec5SDimitry Andric }
31820b57cec5SDimitry Andric 
printTypeIdCompatibleVtableSummary(const TypeIdCompatibleVtableInfo & TI)31830b57cec5SDimitry Andric void AssemblyWriter::printTypeIdCompatibleVtableSummary(
31840b57cec5SDimitry Andric     const TypeIdCompatibleVtableInfo &TI) {
31850b57cec5SDimitry Andric   Out << ", summary: (";
31860b57cec5SDimitry Andric   FieldSeparator FS;
31870b57cec5SDimitry Andric   for (auto &P : TI) {
31880b57cec5SDimitry Andric     Out << FS;
31890b57cec5SDimitry Andric     Out << "(offset: " << P.AddressPointOffset << ", ";
31900b57cec5SDimitry Andric     Out << "^" << Machine.getGUIDSlot(P.VTableVI.getGUID());
31910b57cec5SDimitry Andric     Out << ")";
31920b57cec5SDimitry Andric   }
31930b57cec5SDimitry Andric   Out << ")";
31940b57cec5SDimitry Andric }
31950b57cec5SDimitry Andric 
printArgs(const std::vector<uint64_t> & Args)31960b57cec5SDimitry Andric void AssemblyWriter::printArgs(const std::vector<uint64_t> &Args) {
31970b57cec5SDimitry Andric   Out << "args: (";
31980b57cec5SDimitry Andric   FieldSeparator FS;
31990b57cec5SDimitry Andric   for (auto arg : Args) {
32000b57cec5SDimitry Andric     Out << FS;
32010b57cec5SDimitry Andric     Out << arg;
32020b57cec5SDimitry Andric   }
32030b57cec5SDimitry Andric   Out << ")";
32040b57cec5SDimitry Andric }
32050b57cec5SDimitry Andric 
printWPDRes(const WholeProgramDevirtResolution & WPDRes)32060b57cec5SDimitry Andric void AssemblyWriter::printWPDRes(const WholeProgramDevirtResolution &WPDRes) {
32070b57cec5SDimitry Andric   Out << "wpdRes: (kind: ";
32080b57cec5SDimitry Andric   Out << getWholeProgDevirtResKindName(WPDRes.TheKind);
32090b57cec5SDimitry Andric 
32100b57cec5SDimitry Andric   if (WPDRes.TheKind == WholeProgramDevirtResolution::SingleImpl)
32110b57cec5SDimitry Andric     Out << ", singleImplName: \"" << WPDRes.SingleImplName << "\"";
32120b57cec5SDimitry Andric 
32130b57cec5SDimitry Andric   if (!WPDRes.ResByArg.empty()) {
32140b57cec5SDimitry Andric     Out << ", resByArg: (";
32150b57cec5SDimitry Andric     FieldSeparator FS;
32160b57cec5SDimitry Andric     for (auto &ResByArg : WPDRes.ResByArg) {
32170b57cec5SDimitry Andric       Out << FS;
32180b57cec5SDimitry Andric       printArgs(ResByArg.first);
32190b57cec5SDimitry Andric       Out << ", byArg: (kind: ";
32200b57cec5SDimitry Andric       Out << getWholeProgDevirtResByArgKindName(ResByArg.second.TheKind);
32210b57cec5SDimitry Andric       if (ResByArg.second.TheKind ==
32220b57cec5SDimitry Andric               WholeProgramDevirtResolution::ByArg::UniformRetVal ||
32230b57cec5SDimitry Andric           ResByArg.second.TheKind ==
32240b57cec5SDimitry Andric               WholeProgramDevirtResolution::ByArg::UniqueRetVal)
32250b57cec5SDimitry Andric         Out << ", info: " << ResByArg.second.Info;
32260b57cec5SDimitry Andric 
32270b57cec5SDimitry Andric       // The following fields are only used if the target does not support the
32280b57cec5SDimitry Andric       // use of absolute symbols to store constants. Print only if non-zero.
32290b57cec5SDimitry Andric       if (ResByArg.second.Byte || ResByArg.second.Bit)
32300b57cec5SDimitry Andric         Out << ", byte: " << ResByArg.second.Byte
32310b57cec5SDimitry Andric             << ", bit: " << ResByArg.second.Bit;
32320b57cec5SDimitry Andric 
32330b57cec5SDimitry Andric       Out << ")";
32340b57cec5SDimitry Andric     }
32350b57cec5SDimitry Andric     Out << ")";
32360b57cec5SDimitry Andric   }
32370b57cec5SDimitry Andric   Out << ")";
32380b57cec5SDimitry Andric }
32390b57cec5SDimitry Andric 
getSummaryKindName(GlobalValueSummary::SummaryKind SK)32400b57cec5SDimitry Andric static const char *getSummaryKindName(GlobalValueSummary::SummaryKind SK) {
32410b57cec5SDimitry Andric   switch (SK) {
32420b57cec5SDimitry Andric   case GlobalValueSummary::AliasKind:
32430b57cec5SDimitry Andric     return "alias";
32440b57cec5SDimitry Andric   case GlobalValueSummary::FunctionKind:
32450b57cec5SDimitry Andric     return "function";
32460b57cec5SDimitry Andric   case GlobalValueSummary::GlobalVarKind:
32470b57cec5SDimitry Andric     return "variable";
32480b57cec5SDimitry Andric   }
32490b57cec5SDimitry Andric   llvm_unreachable("invalid summary kind");
32500b57cec5SDimitry Andric }
32510b57cec5SDimitry Andric 
printAliasSummary(const AliasSummary * AS)32520b57cec5SDimitry Andric void AssemblyWriter::printAliasSummary(const AliasSummary *AS) {
32530b57cec5SDimitry Andric   Out << ", aliasee: ";
32540b57cec5SDimitry Andric   // The indexes emitted for distributed backends may not include the
32550b57cec5SDimitry Andric   // aliasee summary (only if it is being imported directly). Handle
32560b57cec5SDimitry Andric   // that case by just emitting "null" as the aliasee.
32570b57cec5SDimitry Andric   if (AS->hasAliasee())
32580b57cec5SDimitry Andric     Out << "^" << Machine.getGUIDSlot(SummaryToGUIDMap[&AS->getAliasee()]);
32590b57cec5SDimitry Andric   else
32600b57cec5SDimitry Andric     Out << "null";
32610b57cec5SDimitry Andric }
32620b57cec5SDimitry Andric 
printGlobalVarSummary(const GlobalVarSummary * GS)32630b57cec5SDimitry Andric void AssemblyWriter::printGlobalVarSummary(const GlobalVarSummary *GS) {
32640b57cec5SDimitry Andric   auto VTableFuncs = GS->vTableFuncs();
32655ffd83dbSDimitry Andric   Out << ", varFlags: (readonly: " << GS->VarFlags.MaybeReadOnly << ", "
32665ffd83dbSDimitry Andric       << "writeonly: " << GS->VarFlags.MaybeWriteOnly << ", "
32675ffd83dbSDimitry Andric       << "constant: " << GS->VarFlags.Constant;
32685ffd83dbSDimitry Andric   if (!VTableFuncs.empty())
32695ffd83dbSDimitry Andric     Out << ", "
32705ffd83dbSDimitry Andric         << "vcall_visibility: " << GS->VarFlags.VCallVisibility;
32715ffd83dbSDimitry Andric   Out << ")";
32725ffd83dbSDimitry Andric 
32730b57cec5SDimitry Andric   if (!VTableFuncs.empty()) {
32740b57cec5SDimitry Andric     Out << ", vTableFuncs: (";
32750b57cec5SDimitry Andric     FieldSeparator FS;
32760b57cec5SDimitry Andric     for (auto &P : VTableFuncs) {
32770b57cec5SDimitry Andric       Out << FS;
32780b57cec5SDimitry Andric       Out << "(virtFunc: ^" << Machine.getGUIDSlot(P.FuncVI.getGUID())
32790b57cec5SDimitry Andric           << ", offset: " << P.VTableOffset;
32800b57cec5SDimitry Andric       Out << ")";
32810b57cec5SDimitry Andric     }
32820b57cec5SDimitry Andric     Out << ")";
32830b57cec5SDimitry Andric   }
32840b57cec5SDimitry Andric }
32850b57cec5SDimitry Andric 
getLinkageName(GlobalValue::LinkageTypes LT)32860b57cec5SDimitry Andric static std::string getLinkageName(GlobalValue::LinkageTypes LT) {
32870b57cec5SDimitry Andric   switch (LT) {
32880b57cec5SDimitry Andric   case GlobalValue::ExternalLinkage:
32890b57cec5SDimitry Andric     return "external";
32900b57cec5SDimitry Andric   case GlobalValue::PrivateLinkage:
32910b57cec5SDimitry Andric     return "private";
32920b57cec5SDimitry Andric   case GlobalValue::InternalLinkage:
32930b57cec5SDimitry Andric     return "internal";
32940b57cec5SDimitry Andric   case GlobalValue::LinkOnceAnyLinkage:
32950b57cec5SDimitry Andric     return "linkonce";
32960b57cec5SDimitry Andric   case GlobalValue::LinkOnceODRLinkage:
32970b57cec5SDimitry Andric     return "linkonce_odr";
32980b57cec5SDimitry Andric   case GlobalValue::WeakAnyLinkage:
32990b57cec5SDimitry Andric     return "weak";
33000b57cec5SDimitry Andric   case GlobalValue::WeakODRLinkage:
33010b57cec5SDimitry Andric     return "weak_odr";
33020b57cec5SDimitry Andric   case GlobalValue::CommonLinkage:
33030b57cec5SDimitry Andric     return "common";
33040b57cec5SDimitry Andric   case GlobalValue::AppendingLinkage:
33050b57cec5SDimitry Andric     return "appending";
33060b57cec5SDimitry Andric   case GlobalValue::ExternalWeakLinkage:
33070b57cec5SDimitry Andric     return "extern_weak";
33080b57cec5SDimitry Andric   case GlobalValue::AvailableExternallyLinkage:
33090b57cec5SDimitry Andric     return "available_externally";
33100b57cec5SDimitry Andric   }
33110b57cec5SDimitry Andric   llvm_unreachable("invalid linkage");
33120b57cec5SDimitry Andric }
33130b57cec5SDimitry Andric 
33140b57cec5SDimitry Andric // When printing the linkage types in IR where the ExternalLinkage is
33150b57cec5SDimitry Andric // not printed, and other linkage types are expected to be printed with
33160b57cec5SDimitry Andric // a space after the name.
getLinkageNameWithSpace(GlobalValue::LinkageTypes LT)33170b57cec5SDimitry Andric static std::string getLinkageNameWithSpace(GlobalValue::LinkageTypes LT) {
33180b57cec5SDimitry Andric   if (LT == GlobalValue::ExternalLinkage)
33190b57cec5SDimitry Andric     return "";
33200b57cec5SDimitry Andric   return getLinkageName(LT) + " ";
33210b57cec5SDimitry Andric }
33220b57cec5SDimitry Andric 
getVisibilityName(GlobalValue::VisibilityTypes Vis)3323fe6060f1SDimitry Andric static const char *getVisibilityName(GlobalValue::VisibilityTypes Vis) {
3324fe6060f1SDimitry Andric   switch (Vis) {
3325fe6060f1SDimitry Andric   case GlobalValue::DefaultVisibility:
3326fe6060f1SDimitry Andric     return "default";
3327fe6060f1SDimitry Andric   case GlobalValue::HiddenVisibility:
3328fe6060f1SDimitry Andric     return "hidden";
3329fe6060f1SDimitry Andric   case GlobalValue::ProtectedVisibility:
3330fe6060f1SDimitry Andric     return "protected";
3331fe6060f1SDimitry Andric   }
3332fe6060f1SDimitry Andric   llvm_unreachable("invalid visibility");
3333fe6060f1SDimitry Andric }
3334fe6060f1SDimitry Andric 
getImportTypeName(GlobalValueSummary::ImportKind IK)3335*0fca6ea1SDimitry Andric static const char *getImportTypeName(GlobalValueSummary::ImportKind IK) {
3336*0fca6ea1SDimitry Andric   switch (IK) {
3337*0fca6ea1SDimitry Andric   case GlobalValueSummary::Definition:
3338*0fca6ea1SDimitry Andric     return "definition";
3339*0fca6ea1SDimitry Andric   case GlobalValueSummary::Declaration:
3340*0fca6ea1SDimitry Andric     return "declaration";
3341*0fca6ea1SDimitry Andric   }
3342*0fca6ea1SDimitry Andric   llvm_unreachable("invalid import kind");
3343*0fca6ea1SDimitry Andric }
3344*0fca6ea1SDimitry Andric 
printFunctionSummary(const FunctionSummary * FS)33450b57cec5SDimitry Andric void AssemblyWriter::printFunctionSummary(const FunctionSummary *FS) {
33460b57cec5SDimitry Andric   Out << ", insts: " << FS->instCount();
3347349cc55cSDimitry Andric   if (FS->fflags().anyFlagSet())
3348349cc55cSDimitry Andric     Out << ", " << FS->fflags();
33490b57cec5SDimitry Andric 
33500b57cec5SDimitry Andric   if (!FS->calls().empty()) {
33510b57cec5SDimitry Andric     Out << ", calls: (";
33520b57cec5SDimitry Andric     FieldSeparator IFS;
33530b57cec5SDimitry Andric     for (auto &Call : FS->calls()) {
33540b57cec5SDimitry Andric       Out << IFS;
33550b57cec5SDimitry Andric       Out << "(callee: ^" << Machine.getGUIDSlot(Call.first.getGUID());
33560b57cec5SDimitry Andric       if (Call.second.getHotness() != CalleeInfo::HotnessType::Unknown)
33570b57cec5SDimitry Andric         Out << ", hotness: " << getHotnessName(Call.second.getHotness());
33580b57cec5SDimitry Andric       else if (Call.second.RelBlockFreq)
33590b57cec5SDimitry Andric         Out << ", relbf: " << Call.second.RelBlockFreq;
33605f757f3fSDimitry Andric       // Follow the convention of emitting flags as a boolean value, but only
33615f757f3fSDimitry Andric       // emit if true to avoid unnecessary verbosity and test churn.
33625f757f3fSDimitry Andric       if (Call.second.HasTailCall)
33635f757f3fSDimitry Andric         Out << ", tail: 1";
33640b57cec5SDimitry Andric       Out << ")";
33650b57cec5SDimitry Andric     }
33660b57cec5SDimitry Andric     Out << ")";
33670b57cec5SDimitry Andric   }
33680b57cec5SDimitry Andric 
33690b57cec5SDimitry Andric   if (const auto *TIdInfo = FS->getTypeIdInfo())
33700b57cec5SDimitry Andric     printTypeIdInfo(*TIdInfo);
33715ffd83dbSDimitry Andric 
3372bdd1243dSDimitry Andric   // The AllocationType identifiers capture the profiled context behavior
337306c3fb27SDimitry Andric   // reaching a specific static allocation site (possibly cloned).
3374bdd1243dSDimitry Andric   auto AllocTypeName = [](uint8_t Type) -> const char * {
3375bdd1243dSDimitry Andric     switch (Type) {
3376bdd1243dSDimitry Andric     case (uint8_t)AllocationType::None:
3377bdd1243dSDimitry Andric       return "none";
3378bdd1243dSDimitry Andric     case (uint8_t)AllocationType::NotCold:
3379bdd1243dSDimitry Andric       return "notcold";
3380bdd1243dSDimitry Andric     case (uint8_t)AllocationType::Cold:
3381bdd1243dSDimitry Andric       return "cold";
338206c3fb27SDimitry Andric     case (uint8_t)AllocationType::Hot:
338306c3fb27SDimitry Andric       return "hot";
3384bdd1243dSDimitry Andric     }
3385bdd1243dSDimitry Andric     llvm_unreachable("Unexpected alloc type");
3386bdd1243dSDimitry Andric   };
3387bdd1243dSDimitry Andric 
3388bdd1243dSDimitry Andric   if (!FS->allocs().empty()) {
3389bdd1243dSDimitry Andric     Out << ", allocs: (";
3390bdd1243dSDimitry Andric     FieldSeparator AFS;
3391bdd1243dSDimitry Andric     for (auto &AI : FS->allocs()) {
3392bdd1243dSDimitry Andric       Out << AFS;
3393bdd1243dSDimitry Andric       Out << "(versions: (";
3394bdd1243dSDimitry Andric       FieldSeparator VFS;
3395bdd1243dSDimitry Andric       for (auto V : AI.Versions) {
3396bdd1243dSDimitry Andric         Out << VFS;
3397bdd1243dSDimitry Andric         Out << AllocTypeName(V);
3398bdd1243dSDimitry Andric       }
3399bdd1243dSDimitry Andric       Out << "), memProf: (";
3400bdd1243dSDimitry Andric       FieldSeparator MIBFS;
3401bdd1243dSDimitry Andric       for (auto &MIB : AI.MIBs) {
3402bdd1243dSDimitry Andric         Out << MIBFS;
3403bdd1243dSDimitry Andric         Out << "(type: " << AllocTypeName((uint8_t)MIB.AllocType);
3404bdd1243dSDimitry Andric         Out << ", stackIds: (";
3405bdd1243dSDimitry Andric         FieldSeparator SIDFS;
3406bdd1243dSDimitry Andric         for (auto Id : MIB.StackIdIndices) {
3407bdd1243dSDimitry Andric           Out << SIDFS;
3408bdd1243dSDimitry Andric           Out << TheIndex->getStackIdAtIndex(Id);
3409bdd1243dSDimitry Andric         }
3410bdd1243dSDimitry Andric         Out << "))";
3411bdd1243dSDimitry Andric       }
3412bdd1243dSDimitry Andric       Out << "))";
3413bdd1243dSDimitry Andric     }
3414bdd1243dSDimitry Andric     Out << ")";
3415bdd1243dSDimitry Andric   }
3416bdd1243dSDimitry Andric 
3417bdd1243dSDimitry Andric   if (!FS->callsites().empty()) {
3418bdd1243dSDimitry Andric     Out << ", callsites: (";
3419bdd1243dSDimitry Andric     FieldSeparator SNFS;
3420bdd1243dSDimitry Andric     for (auto &CI : FS->callsites()) {
3421bdd1243dSDimitry Andric       Out << SNFS;
3422bdd1243dSDimitry Andric       if (CI.Callee)
3423bdd1243dSDimitry Andric         Out << "(callee: ^" << Machine.getGUIDSlot(CI.Callee.getGUID());
3424bdd1243dSDimitry Andric       else
3425bdd1243dSDimitry Andric         Out << "(callee: null";
3426bdd1243dSDimitry Andric       Out << ", clones: (";
3427bdd1243dSDimitry Andric       FieldSeparator VFS;
3428bdd1243dSDimitry Andric       for (auto V : CI.Clones) {
3429bdd1243dSDimitry Andric         Out << VFS;
3430bdd1243dSDimitry Andric         Out << V;
3431bdd1243dSDimitry Andric       }
3432bdd1243dSDimitry Andric       Out << "), stackIds: (";
3433bdd1243dSDimitry Andric       FieldSeparator SIDFS;
3434bdd1243dSDimitry Andric       for (auto Id : CI.StackIdIndices) {
3435bdd1243dSDimitry Andric         Out << SIDFS;
3436bdd1243dSDimitry Andric         Out << TheIndex->getStackIdAtIndex(Id);
3437bdd1243dSDimitry Andric       }
3438bdd1243dSDimitry Andric       Out << "))";
3439bdd1243dSDimitry Andric     }
3440bdd1243dSDimitry Andric     Out << ")";
3441bdd1243dSDimitry Andric   }
3442bdd1243dSDimitry Andric 
34435ffd83dbSDimitry Andric   auto PrintRange = [&](const ConstantRange &Range) {
3444e8d8bef9SDimitry Andric     Out << "[" << Range.getSignedMin() << ", " << Range.getSignedMax() << "]";
34455ffd83dbSDimitry Andric   };
34465ffd83dbSDimitry Andric 
34475ffd83dbSDimitry Andric   if (!FS->paramAccesses().empty()) {
34485ffd83dbSDimitry Andric     Out << ", params: (";
34495ffd83dbSDimitry Andric     FieldSeparator IFS;
34505ffd83dbSDimitry Andric     for (auto &PS : FS->paramAccesses()) {
34515ffd83dbSDimitry Andric       Out << IFS;
34525ffd83dbSDimitry Andric       Out << "(param: " << PS.ParamNo;
34535ffd83dbSDimitry Andric       Out << ", offset: ";
34545ffd83dbSDimitry Andric       PrintRange(PS.Use);
34555ffd83dbSDimitry Andric       if (!PS.Calls.empty()) {
34565ffd83dbSDimitry Andric         Out << ", calls: (";
34575ffd83dbSDimitry Andric         FieldSeparator IFS;
34585ffd83dbSDimitry Andric         for (auto &Call : PS.Calls) {
34595ffd83dbSDimitry Andric           Out << IFS;
3460e8d8bef9SDimitry Andric           Out << "(callee: ^" << Machine.getGUIDSlot(Call.Callee.getGUID());
34615ffd83dbSDimitry Andric           Out << ", param: " << Call.ParamNo;
34625ffd83dbSDimitry Andric           Out << ", offset: ";
34635ffd83dbSDimitry Andric           PrintRange(Call.Offsets);
34645ffd83dbSDimitry Andric           Out << ")";
34655ffd83dbSDimitry Andric         }
34665ffd83dbSDimitry Andric         Out << ")";
34675ffd83dbSDimitry Andric       }
34685ffd83dbSDimitry Andric       Out << ")";
34695ffd83dbSDimitry Andric     }
34705ffd83dbSDimitry Andric     Out << ")";
34715ffd83dbSDimitry Andric   }
34720b57cec5SDimitry Andric }
34730b57cec5SDimitry Andric 
printTypeIdInfo(const FunctionSummary::TypeIdInfo & TIDInfo)34740b57cec5SDimitry Andric void AssemblyWriter::printTypeIdInfo(
34750b57cec5SDimitry Andric     const FunctionSummary::TypeIdInfo &TIDInfo) {
34760b57cec5SDimitry Andric   Out << ", typeIdInfo: (";
34770b57cec5SDimitry Andric   FieldSeparator TIDFS;
34780b57cec5SDimitry Andric   if (!TIDInfo.TypeTests.empty()) {
34790b57cec5SDimitry Andric     Out << TIDFS;
34800b57cec5SDimitry Andric     Out << "typeTests: (";
34810b57cec5SDimitry Andric     FieldSeparator FS;
34820b57cec5SDimitry Andric     for (auto &GUID : TIDInfo.TypeTests) {
34830b57cec5SDimitry Andric       auto TidIter = TheIndex->typeIds().equal_range(GUID);
34840b57cec5SDimitry Andric       if (TidIter.first == TidIter.second) {
34850b57cec5SDimitry Andric         Out << FS;
34860b57cec5SDimitry Andric         Out << GUID;
34870b57cec5SDimitry Andric         continue;
34880b57cec5SDimitry Andric       }
34890b57cec5SDimitry Andric       // Print all type id that correspond to this GUID.
34900b57cec5SDimitry Andric       for (auto It = TidIter.first; It != TidIter.second; ++It) {
34910b57cec5SDimitry Andric         Out << FS;
34920b57cec5SDimitry Andric         auto Slot = Machine.getTypeIdSlot(It->second.first);
34930b57cec5SDimitry Andric         assert(Slot != -1);
34940b57cec5SDimitry Andric         Out << "^" << Slot;
34950b57cec5SDimitry Andric       }
34960b57cec5SDimitry Andric     }
34970b57cec5SDimitry Andric     Out << ")";
34980b57cec5SDimitry Andric   }
34990b57cec5SDimitry Andric   if (!TIDInfo.TypeTestAssumeVCalls.empty()) {
35000b57cec5SDimitry Andric     Out << TIDFS;
35010b57cec5SDimitry Andric     printNonConstVCalls(TIDInfo.TypeTestAssumeVCalls, "typeTestAssumeVCalls");
35020b57cec5SDimitry Andric   }
35030b57cec5SDimitry Andric   if (!TIDInfo.TypeCheckedLoadVCalls.empty()) {
35040b57cec5SDimitry Andric     Out << TIDFS;
35050b57cec5SDimitry Andric     printNonConstVCalls(TIDInfo.TypeCheckedLoadVCalls, "typeCheckedLoadVCalls");
35060b57cec5SDimitry Andric   }
35070b57cec5SDimitry Andric   if (!TIDInfo.TypeTestAssumeConstVCalls.empty()) {
35080b57cec5SDimitry Andric     Out << TIDFS;
35090b57cec5SDimitry Andric     printConstVCalls(TIDInfo.TypeTestAssumeConstVCalls,
35100b57cec5SDimitry Andric                      "typeTestAssumeConstVCalls");
35110b57cec5SDimitry Andric   }
35120b57cec5SDimitry Andric   if (!TIDInfo.TypeCheckedLoadConstVCalls.empty()) {
35130b57cec5SDimitry Andric     Out << TIDFS;
35140b57cec5SDimitry Andric     printConstVCalls(TIDInfo.TypeCheckedLoadConstVCalls,
35150b57cec5SDimitry Andric                      "typeCheckedLoadConstVCalls");
35160b57cec5SDimitry Andric   }
35170b57cec5SDimitry Andric   Out << ")";
35180b57cec5SDimitry Andric }
35190b57cec5SDimitry Andric 
printVFuncId(const FunctionSummary::VFuncId VFId)35200b57cec5SDimitry Andric void AssemblyWriter::printVFuncId(const FunctionSummary::VFuncId VFId) {
35210b57cec5SDimitry Andric   auto TidIter = TheIndex->typeIds().equal_range(VFId.GUID);
35220b57cec5SDimitry Andric   if (TidIter.first == TidIter.second) {
35230b57cec5SDimitry Andric     Out << "vFuncId: (";
35240b57cec5SDimitry Andric     Out << "guid: " << VFId.GUID;
35250b57cec5SDimitry Andric     Out << ", offset: " << VFId.Offset;
35260b57cec5SDimitry Andric     Out << ")";
35270b57cec5SDimitry Andric     return;
35280b57cec5SDimitry Andric   }
35290b57cec5SDimitry Andric   // Print all type id that correspond to this GUID.
35300b57cec5SDimitry Andric   FieldSeparator FS;
35310b57cec5SDimitry Andric   for (auto It = TidIter.first; It != TidIter.second; ++It) {
35320b57cec5SDimitry Andric     Out << FS;
35330b57cec5SDimitry Andric     Out << "vFuncId: (";
35340b57cec5SDimitry Andric     auto Slot = Machine.getTypeIdSlot(It->second.first);
35350b57cec5SDimitry Andric     assert(Slot != -1);
35360b57cec5SDimitry Andric     Out << "^" << Slot;
35370b57cec5SDimitry Andric     Out << ", offset: " << VFId.Offset;
35380b57cec5SDimitry Andric     Out << ")";
35390b57cec5SDimitry Andric   }
35400b57cec5SDimitry Andric }
35410b57cec5SDimitry Andric 
printNonConstVCalls(const std::vector<FunctionSummary::VFuncId> & VCallList,const char * Tag)35420b57cec5SDimitry Andric void AssemblyWriter::printNonConstVCalls(
35435ffd83dbSDimitry Andric     const std::vector<FunctionSummary::VFuncId> &VCallList, const char *Tag) {
35440b57cec5SDimitry Andric   Out << Tag << ": (";
35450b57cec5SDimitry Andric   FieldSeparator FS;
35460b57cec5SDimitry Andric   for (auto &VFuncId : VCallList) {
35470b57cec5SDimitry Andric     Out << FS;
35480b57cec5SDimitry Andric     printVFuncId(VFuncId);
35490b57cec5SDimitry Andric   }
35500b57cec5SDimitry Andric   Out << ")";
35510b57cec5SDimitry Andric }
35520b57cec5SDimitry Andric 
printConstVCalls(const std::vector<FunctionSummary::ConstVCall> & VCallList,const char * Tag)35530b57cec5SDimitry Andric void AssemblyWriter::printConstVCalls(
35545ffd83dbSDimitry Andric     const std::vector<FunctionSummary::ConstVCall> &VCallList,
35555ffd83dbSDimitry Andric     const char *Tag) {
35560b57cec5SDimitry Andric   Out << Tag << ": (";
35570b57cec5SDimitry Andric   FieldSeparator FS;
35580b57cec5SDimitry Andric   for (auto &ConstVCall : VCallList) {
35590b57cec5SDimitry Andric     Out << FS;
35600b57cec5SDimitry Andric     Out << "(";
35610b57cec5SDimitry Andric     printVFuncId(ConstVCall.VFunc);
35620b57cec5SDimitry Andric     if (!ConstVCall.Args.empty()) {
35630b57cec5SDimitry Andric       Out << ", ";
35640b57cec5SDimitry Andric       printArgs(ConstVCall.Args);
35650b57cec5SDimitry Andric     }
35660b57cec5SDimitry Andric     Out << ")";
35670b57cec5SDimitry Andric   }
35680b57cec5SDimitry Andric   Out << ")";
35690b57cec5SDimitry Andric }
35700b57cec5SDimitry Andric 
printSummary(const GlobalValueSummary & Summary)35710b57cec5SDimitry Andric void AssemblyWriter::printSummary(const GlobalValueSummary &Summary) {
35720b57cec5SDimitry Andric   GlobalValueSummary::GVFlags GVFlags = Summary.flags();
35730b57cec5SDimitry Andric   GlobalValue::LinkageTypes LT = (GlobalValue::LinkageTypes)GVFlags.Linkage;
35740b57cec5SDimitry Andric   Out << getSummaryKindName(Summary.getSummaryKind()) << ": ";
35750b57cec5SDimitry Andric   Out << "(module: ^" << Machine.getModulePathSlot(Summary.modulePath())
35760b57cec5SDimitry Andric       << ", flags: (";
35770b57cec5SDimitry Andric   Out << "linkage: " << getLinkageName(LT);
3578fe6060f1SDimitry Andric   Out << ", visibility: "
3579fe6060f1SDimitry Andric       << getVisibilityName((GlobalValue::VisibilityTypes)GVFlags.Visibility);
35800b57cec5SDimitry Andric   Out << ", notEligibleToImport: " << GVFlags.NotEligibleToImport;
35810b57cec5SDimitry Andric   Out << ", live: " << GVFlags.Live;
35820b57cec5SDimitry Andric   Out << ", dsoLocal: " << GVFlags.DSOLocal;
35830b57cec5SDimitry Andric   Out << ", canAutoHide: " << GVFlags.CanAutoHide;
3584*0fca6ea1SDimitry Andric   Out << ", importType: "
3585*0fca6ea1SDimitry Andric       << getImportTypeName(GlobalValueSummary::ImportKind(GVFlags.ImportType));
35860b57cec5SDimitry Andric   Out << ")";
35870b57cec5SDimitry Andric 
35880b57cec5SDimitry Andric   if (Summary.getSummaryKind() == GlobalValueSummary::AliasKind)
35890b57cec5SDimitry Andric     printAliasSummary(cast<AliasSummary>(&Summary));
35900b57cec5SDimitry Andric   else if (Summary.getSummaryKind() == GlobalValueSummary::FunctionKind)
35910b57cec5SDimitry Andric     printFunctionSummary(cast<FunctionSummary>(&Summary));
35920b57cec5SDimitry Andric   else
35930b57cec5SDimitry Andric     printGlobalVarSummary(cast<GlobalVarSummary>(&Summary));
35940b57cec5SDimitry Andric 
35950b57cec5SDimitry Andric   auto RefList = Summary.refs();
35960b57cec5SDimitry Andric   if (!RefList.empty()) {
35970b57cec5SDimitry Andric     Out << ", refs: (";
35980b57cec5SDimitry Andric     FieldSeparator FS;
35990b57cec5SDimitry Andric     for (auto &Ref : RefList) {
36000b57cec5SDimitry Andric       Out << FS;
36010b57cec5SDimitry Andric       if (Ref.isReadOnly())
36020b57cec5SDimitry Andric         Out << "readonly ";
36030b57cec5SDimitry Andric       else if (Ref.isWriteOnly())
36040b57cec5SDimitry Andric         Out << "writeonly ";
36050b57cec5SDimitry Andric       Out << "^" << Machine.getGUIDSlot(Ref.getGUID());
36060b57cec5SDimitry Andric     }
36070b57cec5SDimitry Andric     Out << ")";
36080b57cec5SDimitry Andric   }
36090b57cec5SDimitry Andric 
36100b57cec5SDimitry Andric   Out << ")";
36110b57cec5SDimitry Andric }
36120b57cec5SDimitry Andric 
printSummaryInfo(unsigned Slot,const ValueInfo & VI)36130b57cec5SDimitry Andric void AssemblyWriter::printSummaryInfo(unsigned Slot, const ValueInfo &VI) {
36140b57cec5SDimitry Andric   Out << "^" << Slot << " = gv: (";
36150b57cec5SDimitry Andric   if (!VI.name().empty())
36160b57cec5SDimitry Andric     Out << "name: \"" << VI.name() << "\"";
36170b57cec5SDimitry Andric   else
36180b57cec5SDimitry Andric     Out << "guid: " << VI.getGUID();
36190b57cec5SDimitry Andric   if (!VI.getSummaryList().empty()) {
36200b57cec5SDimitry Andric     Out << ", summaries: (";
36210b57cec5SDimitry Andric     FieldSeparator FS;
36220b57cec5SDimitry Andric     for (auto &Summary : VI.getSummaryList()) {
36230b57cec5SDimitry Andric       Out << FS;
36240b57cec5SDimitry Andric       printSummary(*Summary);
36250b57cec5SDimitry Andric     }
36260b57cec5SDimitry Andric     Out << ")";
36270b57cec5SDimitry Andric   }
36280b57cec5SDimitry Andric   Out << ")";
36290b57cec5SDimitry Andric   if (!VI.name().empty())
36300b57cec5SDimitry Andric     Out << " ; guid = " << VI.getGUID();
36310b57cec5SDimitry Andric   Out << "\n";
36320b57cec5SDimitry Andric }
36330b57cec5SDimitry Andric 
printMetadataIdentifier(StringRef Name,formatted_raw_ostream & Out)36340b57cec5SDimitry Andric static void printMetadataIdentifier(StringRef Name,
36350b57cec5SDimitry Andric                                     formatted_raw_ostream &Out) {
36360b57cec5SDimitry Andric   if (Name.empty()) {
36370b57cec5SDimitry Andric     Out << "<empty name> ";
36380b57cec5SDimitry Andric   } else {
36395f757f3fSDimitry Andric     unsigned char FirstC = static_cast<unsigned char>(Name[0]);
36405f757f3fSDimitry Andric     if (isalpha(FirstC) || FirstC == '-' || FirstC == '$' || FirstC == '.' ||
36415f757f3fSDimitry Andric         FirstC == '_')
36425f757f3fSDimitry Andric       Out << FirstC;
36430b57cec5SDimitry Andric     else
36445f757f3fSDimitry Andric       Out << '\\' << hexdigit(FirstC >> 4) << hexdigit(FirstC & 0x0F);
36450b57cec5SDimitry Andric     for (unsigned i = 1, e = Name.size(); i != e; ++i) {
36460b57cec5SDimitry Andric       unsigned char C = Name[i];
36475f757f3fSDimitry Andric       if (isalnum(C) || C == '-' || C == '$' || C == '.' || C == '_')
36480b57cec5SDimitry Andric         Out << C;
36490b57cec5SDimitry Andric       else
36500b57cec5SDimitry Andric         Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
36510b57cec5SDimitry Andric     }
36520b57cec5SDimitry Andric   }
36530b57cec5SDimitry Andric }
36540b57cec5SDimitry Andric 
printNamedMDNode(const NamedMDNode * NMD)36550b57cec5SDimitry Andric void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
36560b57cec5SDimitry Andric   Out << '!';
36570b57cec5SDimitry Andric   printMetadataIdentifier(NMD->getName(), Out);
36580b57cec5SDimitry Andric   Out << " = !{";
36590b57cec5SDimitry Andric   for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
36600b57cec5SDimitry Andric     if (i)
36610b57cec5SDimitry Andric       Out << ", ";
36620b57cec5SDimitry Andric 
36630b57cec5SDimitry Andric     // Write DIExpressions inline.
36640b57cec5SDimitry Andric     // FIXME: Ban DIExpressions in NamedMDNodes, they will serve no purpose.
36650b57cec5SDimitry Andric     MDNode *Op = NMD->getOperand(i);
36660b57cec5SDimitry Andric     if (auto *Expr = dyn_cast<DIExpression>(Op)) {
3667349cc55cSDimitry Andric       writeDIExpression(Out, Expr, AsmWriterContext::getEmpty());
36680b57cec5SDimitry Andric       continue;
36690b57cec5SDimitry Andric     }
36700b57cec5SDimitry Andric 
36710b57cec5SDimitry Andric     int Slot = Machine.getMetadataSlot(Op);
36720b57cec5SDimitry Andric     if (Slot == -1)
36730b57cec5SDimitry Andric       Out << "<badref>";
36740b57cec5SDimitry Andric     else
36750b57cec5SDimitry Andric       Out << '!' << Slot;
36760b57cec5SDimitry Andric   }
36770b57cec5SDimitry Andric   Out << "}\n";
36780b57cec5SDimitry Andric }
36790b57cec5SDimitry Andric 
PrintVisibility(GlobalValue::VisibilityTypes Vis,formatted_raw_ostream & Out)36800b57cec5SDimitry Andric static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
36810b57cec5SDimitry Andric                             formatted_raw_ostream &Out) {
36820b57cec5SDimitry Andric   switch (Vis) {
36830b57cec5SDimitry Andric   case GlobalValue::DefaultVisibility: break;
36840b57cec5SDimitry Andric   case GlobalValue::HiddenVisibility:    Out << "hidden "; break;
36850b57cec5SDimitry Andric   case GlobalValue::ProtectedVisibility: Out << "protected "; break;
36860b57cec5SDimitry Andric   }
36870b57cec5SDimitry Andric }
36880b57cec5SDimitry Andric 
PrintDSOLocation(const GlobalValue & GV,formatted_raw_ostream & Out)36890b57cec5SDimitry Andric static void PrintDSOLocation(const GlobalValue &GV,
36900b57cec5SDimitry Andric                              formatted_raw_ostream &Out) {
36915ffd83dbSDimitry Andric   if (GV.isDSOLocal() && !GV.isImplicitDSOLocal())
36920b57cec5SDimitry Andric     Out << "dso_local ";
36930b57cec5SDimitry Andric }
36940b57cec5SDimitry Andric 
PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT,formatted_raw_ostream & Out)36950b57cec5SDimitry Andric static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT,
36960b57cec5SDimitry Andric                                  formatted_raw_ostream &Out) {
36970b57cec5SDimitry Andric   switch (SCT) {
36980b57cec5SDimitry Andric   case GlobalValue::DefaultStorageClass: break;
36990b57cec5SDimitry Andric   case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break;
37000b57cec5SDimitry Andric   case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break;
37010b57cec5SDimitry Andric   }
37020b57cec5SDimitry Andric }
37030b57cec5SDimitry Andric 
PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM,formatted_raw_ostream & Out)37040b57cec5SDimitry Andric static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM,
37050b57cec5SDimitry Andric                                   formatted_raw_ostream &Out) {
37060b57cec5SDimitry Andric   switch (TLM) {
37070b57cec5SDimitry Andric     case GlobalVariable::NotThreadLocal:
37080b57cec5SDimitry Andric       break;
37090b57cec5SDimitry Andric     case GlobalVariable::GeneralDynamicTLSModel:
37100b57cec5SDimitry Andric       Out << "thread_local ";
37110b57cec5SDimitry Andric       break;
37120b57cec5SDimitry Andric     case GlobalVariable::LocalDynamicTLSModel:
37130b57cec5SDimitry Andric       Out << "thread_local(localdynamic) ";
37140b57cec5SDimitry Andric       break;
37150b57cec5SDimitry Andric     case GlobalVariable::InitialExecTLSModel:
37160b57cec5SDimitry Andric       Out << "thread_local(initialexec) ";
37170b57cec5SDimitry Andric       break;
37180b57cec5SDimitry Andric     case GlobalVariable::LocalExecTLSModel:
37190b57cec5SDimitry Andric       Out << "thread_local(localexec) ";
37200b57cec5SDimitry Andric       break;
37210b57cec5SDimitry Andric   }
37220b57cec5SDimitry Andric }
37230b57cec5SDimitry Andric 
getUnnamedAddrEncoding(GlobalVariable::UnnamedAddr UA)37240b57cec5SDimitry Andric static StringRef getUnnamedAddrEncoding(GlobalVariable::UnnamedAddr UA) {
37250b57cec5SDimitry Andric   switch (UA) {
37260b57cec5SDimitry Andric   case GlobalVariable::UnnamedAddr::None:
37270b57cec5SDimitry Andric     return "";
37280b57cec5SDimitry Andric   case GlobalVariable::UnnamedAddr::Local:
37290b57cec5SDimitry Andric     return "local_unnamed_addr";
37300b57cec5SDimitry Andric   case GlobalVariable::UnnamedAddr::Global:
37310b57cec5SDimitry Andric     return "unnamed_addr";
37320b57cec5SDimitry Andric   }
37330b57cec5SDimitry Andric   llvm_unreachable("Unknown UnnamedAddr");
37340b57cec5SDimitry Andric }
37350b57cec5SDimitry Andric 
maybePrintComdat(formatted_raw_ostream & Out,const GlobalObject & GO)37360b57cec5SDimitry Andric static void maybePrintComdat(formatted_raw_ostream &Out,
37370b57cec5SDimitry Andric                              const GlobalObject &GO) {
37380b57cec5SDimitry Andric   const Comdat *C = GO.getComdat();
37390b57cec5SDimitry Andric   if (!C)
37400b57cec5SDimitry Andric     return;
37410b57cec5SDimitry Andric 
37420b57cec5SDimitry Andric   if (isa<GlobalVariable>(GO))
37430b57cec5SDimitry Andric     Out << ',';
37440b57cec5SDimitry Andric   Out << " comdat";
37450b57cec5SDimitry Andric 
37460b57cec5SDimitry Andric   if (GO.getName() == C->getName())
37470b57cec5SDimitry Andric     return;
37480b57cec5SDimitry Andric 
37490b57cec5SDimitry Andric   Out << '(';
37500b57cec5SDimitry Andric   PrintLLVMName(Out, C->getName(), ComdatPrefix);
37510b57cec5SDimitry Andric   Out << ')';
37520b57cec5SDimitry Andric }
37530b57cec5SDimitry Andric 
printGlobal(const GlobalVariable * GV)37540b57cec5SDimitry Andric void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
37550b57cec5SDimitry Andric   if (GV->isMaterializable())
37560b57cec5SDimitry Andric     Out << "; Materializable\n";
37570b57cec5SDimitry Andric 
3758349cc55cSDimitry Andric   AsmWriterContext WriterCtx(&TypePrinter, &Machine, GV->getParent());
3759349cc55cSDimitry Andric   WriteAsOperandInternal(Out, GV, WriterCtx);
37600b57cec5SDimitry Andric   Out << " = ";
37610b57cec5SDimitry Andric 
37620b57cec5SDimitry Andric   if (!GV->hasInitializer() && GV->hasExternalLinkage())
37630b57cec5SDimitry Andric     Out << "external ";
37640b57cec5SDimitry Andric 
37650b57cec5SDimitry Andric   Out << getLinkageNameWithSpace(GV->getLinkage());
37660b57cec5SDimitry Andric   PrintDSOLocation(*GV, Out);
37670b57cec5SDimitry Andric   PrintVisibility(GV->getVisibility(), Out);
37680b57cec5SDimitry Andric   PrintDLLStorageClass(GV->getDLLStorageClass(), Out);
37690b57cec5SDimitry Andric   PrintThreadLocalModel(GV->getThreadLocalMode(), Out);
37700b57cec5SDimitry Andric   StringRef UA = getUnnamedAddrEncoding(GV->getUnnamedAddr());
37710b57cec5SDimitry Andric   if (!UA.empty())
37720b57cec5SDimitry Andric       Out << UA << ' ';
37730b57cec5SDimitry Andric 
37740b57cec5SDimitry Andric   if (unsigned AddressSpace = GV->getType()->getAddressSpace())
37750b57cec5SDimitry Andric     Out << "addrspace(" << AddressSpace << ") ";
37760b57cec5SDimitry Andric   if (GV->isExternallyInitialized()) Out << "externally_initialized ";
37770b57cec5SDimitry Andric   Out << (GV->isConstant() ? "constant " : "global ");
37780b57cec5SDimitry Andric   TypePrinter.print(GV->getValueType(), Out);
37790b57cec5SDimitry Andric 
37800b57cec5SDimitry Andric   if (GV->hasInitializer()) {
37810b57cec5SDimitry Andric     Out << ' ';
37820b57cec5SDimitry Andric     writeOperand(GV->getInitializer(), false);
37830b57cec5SDimitry Andric   }
37840b57cec5SDimitry Andric 
37850b57cec5SDimitry Andric   if (GV->hasSection()) {
37860b57cec5SDimitry Andric     Out << ", section \"";
37870b57cec5SDimitry Andric     printEscapedString(GV->getSection(), Out);
37880b57cec5SDimitry Andric     Out << '"';
37890b57cec5SDimitry Andric   }
37900b57cec5SDimitry Andric   if (GV->hasPartition()) {
37910b57cec5SDimitry Andric     Out << ", partition \"";
37920b57cec5SDimitry Andric     printEscapedString(GV->getPartition(), Out);
37930b57cec5SDimitry Andric     Out << '"';
37940b57cec5SDimitry Andric   }
37955f757f3fSDimitry Andric   if (auto CM = GV->getCodeModel()) {
37965f757f3fSDimitry Andric     Out << ", code_model \"";
37975f757f3fSDimitry Andric     switch (*CM) {
37985f757f3fSDimitry Andric     case CodeModel::Tiny:
37995f757f3fSDimitry Andric       Out << "tiny";
38005f757f3fSDimitry Andric       break;
38015f757f3fSDimitry Andric     case CodeModel::Small:
38025f757f3fSDimitry Andric       Out << "small";
38035f757f3fSDimitry Andric       break;
38045f757f3fSDimitry Andric     case CodeModel::Kernel:
38055f757f3fSDimitry Andric       Out << "kernel";
38065f757f3fSDimitry Andric       break;
38075f757f3fSDimitry Andric     case CodeModel::Medium:
38085f757f3fSDimitry Andric       Out << "medium";
38095f757f3fSDimitry Andric       break;
38105f757f3fSDimitry Andric     case CodeModel::Large:
38115f757f3fSDimitry Andric       Out << "large";
38125f757f3fSDimitry Andric       break;
38135f757f3fSDimitry Andric     }
38145f757f3fSDimitry Andric     Out << '"';
38155f757f3fSDimitry Andric   }
38160b57cec5SDimitry Andric 
381781ad6265SDimitry Andric   using SanitizerMetadata = llvm::GlobalValue::SanitizerMetadata;
381881ad6265SDimitry Andric   if (GV->hasSanitizerMetadata()) {
381981ad6265SDimitry Andric     SanitizerMetadata MD = GV->getSanitizerMetadata();
382081ad6265SDimitry Andric     if (MD.NoAddress)
382181ad6265SDimitry Andric       Out << ", no_sanitize_address";
382281ad6265SDimitry Andric     if (MD.NoHWAddress)
382381ad6265SDimitry Andric       Out << ", no_sanitize_hwaddress";
3824753f127fSDimitry Andric     if (MD.Memtag)
3825753f127fSDimitry Andric       Out << ", sanitize_memtag";
382681ad6265SDimitry Andric     if (MD.IsDynInit)
382781ad6265SDimitry Andric       Out << ", sanitize_address_dyninit";
382881ad6265SDimitry Andric   }
382981ad6265SDimitry Andric 
38300b57cec5SDimitry Andric   maybePrintComdat(Out, *GV);
38310eae32dcSDimitry Andric   if (MaybeAlign A = GV->getAlign())
38320eae32dcSDimitry Andric     Out << ", align " << A->value();
38330b57cec5SDimitry Andric 
38340b57cec5SDimitry Andric   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
38350b57cec5SDimitry Andric   GV->getAllMetadata(MDs);
38360b57cec5SDimitry Andric   printMetadataAttachments(MDs, ", ");
38370b57cec5SDimitry Andric 
38380b57cec5SDimitry Andric   auto Attrs = GV->getAttributes();
38390b57cec5SDimitry Andric   if (Attrs.hasAttributes())
38400b57cec5SDimitry Andric     Out << " #" << Machine.getAttributeGroupSlot(Attrs);
38410b57cec5SDimitry Andric 
38420b57cec5SDimitry Andric   printInfoComment(*GV);
38430b57cec5SDimitry Andric }
38440b57cec5SDimitry Andric 
printAlias(const GlobalAlias * GA)3845349cc55cSDimitry Andric void AssemblyWriter::printAlias(const GlobalAlias *GA) {
3846349cc55cSDimitry Andric   if (GA->isMaterializable())
38470b57cec5SDimitry Andric     Out << "; Materializable\n";
38480b57cec5SDimitry Andric 
3849349cc55cSDimitry Andric   AsmWriterContext WriterCtx(&TypePrinter, &Machine, GA->getParent());
3850349cc55cSDimitry Andric   WriteAsOperandInternal(Out, GA, WriterCtx);
38510b57cec5SDimitry Andric   Out << " = ";
38520b57cec5SDimitry Andric 
3853349cc55cSDimitry Andric   Out << getLinkageNameWithSpace(GA->getLinkage());
3854349cc55cSDimitry Andric   PrintDSOLocation(*GA, Out);
3855349cc55cSDimitry Andric   PrintVisibility(GA->getVisibility(), Out);
3856349cc55cSDimitry Andric   PrintDLLStorageClass(GA->getDLLStorageClass(), Out);
3857349cc55cSDimitry Andric   PrintThreadLocalModel(GA->getThreadLocalMode(), Out);
3858349cc55cSDimitry Andric   StringRef UA = getUnnamedAddrEncoding(GA->getUnnamedAddr());
38590b57cec5SDimitry Andric   if (!UA.empty())
38600b57cec5SDimitry Andric       Out << UA << ' ';
38610b57cec5SDimitry Andric 
38620b57cec5SDimitry Andric   Out << "alias ";
38630b57cec5SDimitry Andric 
3864349cc55cSDimitry Andric   TypePrinter.print(GA->getValueType(), Out);
38650b57cec5SDimitry Andric   Out << ", ";
38660b57cec5SDimitry Andric 
3867349cc55cSDimitry Andric   if (const Constant *Aliasee = GA->getAliasee()) {
3868349cc55cSDimitry Andric     writeOperand(Aliasee, !isa<ConstantExpr>(Aliasee));
38690b57cec5SDimitry Andric   } else {
3870349cc55cSDimitry Andric     TypePrinter.print(GA->getType(), Out);
3871349cc55cSDimitry Andric     Out << " <<NULL ALIASEE>>";
38720b57cec5SDimitry Andric   }
38730b57cec5SDimitry Andric 
3874349cc55cSDimitry Andric   if (GA->hasPartition()) {
38750b57cec5SDimitry Andric     Out << ", partition \"";
3876349cc55cSDimitry Andric     printEscapedString(GA->getPartition(), Out);
38770b57cec5SDimitry Andric     Out << '"';
38780b57cec5SDimitry Andric   }
38790b57cec5SDimitry Andric 
3880349cc55cSDimitry Andric   printInfoComment(*GA);
3881349cc55cSDimitry Andric   Out << '\n';
3882349cc55cSDimitry Andric }
3883349cc55cSDimitry Andric 
printIFunc(const GlobalIFunc * GI)3884349cc55cSDimitry Andric void AssemblyWriter::printIFunc(const GlobalIFunc *GI) {
3885349cc55cSDimitry Andric   if (GI->isMaterializable())
3886349cc55cSDimitry Andric     Out << "; Materializable\n";
3887349cc55cSDimitry Andric 
3888349cc55cSDimitry Andric   AsmWriterContext WriterCtx(&TypePrinter, &Machine, GI->getParent());
3889349cc55cSDimitry Andric   WriteAsOperandInternal(Out, GI, WriterCtx);
3890349cc55cSDimitry Andric   Out << " = ";
3891349cc55cSDimitry Andric 
3892349cc55cSDimitry Andric   Out << getLinkageNameWithSpace(GI->getLinkage());
3893349cc55cSDimitry Andric   PrintDSOLocation(*GI, Out);
3894349cc55cSDimitry Andric   PrintVisibility(GI->getVisibility(), Out);
3895349cc55cSDimitry Andric 
3896349cc55cSDimitry Andric   Out << "ifunc ";
3897349cc55cSDimitry Andric 
3898349cc55cSDimitry Andric   TypePrinter.print(GI->getValueType(), Out);
3899349cc55cSDimitry Andric   Out << ", ";
3900349cc55cSDimitry Andric 
3901349cc55cSDimitry Andric   if (const Constant *Resolver = GI->getResolver()) {
3902349cc55cSDimitry Andric     writeOperand(Resolver, !isa<ConstantExpr>(Resolver));
3903349cc55cSDimitry Andric   } else {
3904349cc55cSDimitry Andric     TypePrinter.print(GI->getType(), Out);
3905349cc55cSDimitry Andric     Out << " <<NULL RESOLVER>>";
3906349cc55cSDimitry Andric   }
3907349cc55cSDimitry Andric 
3908349cc55cSDimitry Andric   if (GI->hasPartition()) {
3909349cc55cSDimitry Andric     Out << ", partition \"";
3910349cc55cSDimitry Andric     printEscapedString(GI->getPartition(), Out);
3911349cc55cSDimitry Andric     Out << '"';
3912349cc55cSDimitry Andric   }
3913349cc55cSDimitry Andric 
3914349cc55cSDimitry Andric   printInfoComment(*GI);
39150b57cec5SDimitry Andric   Out << '\n';
39160b57cec5SDimitry Andric }
39170b57cec5SDimitry Andric 
printComdat(const Comdat * C)39180b57cec5SDimitry Andric void AssemblyWriter::printComdat(const Comdat *C) {
39190b57cec5SDimitry Andric   C->print(Out);
39200b57cec5SDimitry Andric }
39210b57cec5SDimitry Andric 
printTypeIdentities()39220b57cec5SDimitry Andric void AssemblyWriter::printTypeIdentities() {
39230b57cec5SDimitry Andric   if (TypePrinter.empty())
39240b57cec5SDimitry Andric     return;
39250b57cec5SDimitry Andric 
39260b57cec5SDimitry Andric   Out << '\n';
39270b57cec5SDimitry Andric 
39280b57cec5SDimitry Andric   // Emit all numbered types.
39290b57cec5SDimitry Andric   auto &NumberedTypes = TypePrinter.getNumberedTypes();
39300b57cec5SDimitry Andric   for (unsigned I = 0, E = NumberedTypes.size(); I != E; ++I) {
39310b57cec5SDimitry Andric     Out << '%' << I << " = type ";
39320b57cec5SDimitry Andric 
39330b57cec5SDimitry Andric     // Make sure we print out at least one level of the type structure, so
39340b57cec5SDimitry Andric     // that we do not get %2 = type %2
39350b57cec5SDimitry Andric     TypePrinter.printStructBody(NumberedTypes[I], Out);
39360b57cec5SDimitry Andric     Out << '\n';
39370b57cec5SDimitry Andric   }
39380b57cec5SDimitry Andric 
39390b57cec5SDimitry Andric   auto &NamedTypes = TypePrinter.getNamedTypes();
39400eae32dcSDimitry Andric   for (StructType *NamedType : NamedTypes) {
39410eae32dcSDimitry Andric     PrintLLVMName(Out, NamedType->getName(), LocalPrefix);
39420b57cec5SDimitry Andric     Out << " = type ";
39430b57cec5SDimitry Andric 
39440b57cec5SDimitry Andric     // Make sure we print out at least one level of the type structure, so
39450b57cec5SDimitry Andric     // that we do not get %FILE = type %FILE
39460eae32dcSDimitry Andric     TypePrinter.printStructBody(NamedType, Out);
39470b57cec5SDimitry Andric     Out << '\n';
39480b57cec5SDimitry Andric   }
39490b57cec5SDimitry Andric }
39500b57cec5SDimitry Andric 
39510b57cec5SDimitry Andric /// printFunction - Print all aspects of a function.
printFunction(const Function * F)39520b57cec5SDimitry Andric void AssemblyWriter::printFunction(const Function *F) {
39530b57cec5SDimitry Andric   if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
39540b57cec5SDimitry Andric 
39550b57cec5SDimitry Andric   if (F->isMaterializable())
39560b57cec5SDimitry Andric     Out << "; Materializable\n";
39570b57cec5SDimitry Andric 
39580b57cec5SDimitry Andric   const AttributeList &Attrs = F->getAttributes();
3959349cc55cSDimitry Andric   if (Attrs.hasFnAttrs()) {
3960349cc55cSDimitry Andric     AttributeSet AS = Attrs.getFnAttrs();
39610b57cec5SDimitry Andric     std::string AttrStr;
39620b57cec5SDimitry Andric 
39630b57cec5SDimitry Andric     for (const Attribute &Attr : AS) {
39640b57cec5SDimitry Andric       if (!Attr.isStringAttribute()) {
39650b57cec5SDimitry Andric         if (!AttrStr.empty()) AttrStr += ' ';
39660b57cec5SDimitry Andric         AttrStr += Attr.getAsString();
39670b57cec5SDimitry Andric       }
39680b57cec5SDimitry Andric     }
39690b57cec5SDimitry Andric 
39700b57cec5SDimitry Andric     if (!AttrStr.empty())
39710b57cec5SDimitry Andric       Out << "; Function Attrs: " << AttrStr << '\n';
39720b57cec5SDimitry Andric   }
39730b57cec5SDimitry Andric 
39740b57cec5SDimitry Andric   Machine.incorporateFunction(F);
39750b57cec5SDimitry Andric 
39760b57cec5SDimitry Andric   if (F->isDeclaration()) {
39770b57cec5SDimitry Andric     Out << "declare";
39780b57cec5SDimitry Andric     SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
39790b57cec5SDimitry Andric     F->getAllMetadata(MDs);
39800b57cec5SDimitry Andric     printMetadataAttachments(MDs, " ");
39810b57cec5SDimitry Andric     Out << ' ';
39820b57cec5SDimitry Andric   } else
39830b57cec5SDimitry Andric     Out << "define ";
39840b57cec5SDimitry Andric 
39850b57cec5SDimitry Andric   Out << getLinkageNameWithSpace(F->getLinkage());
39860b57cec5SDimitry Andric   PrintDSOLocation(*F, Out);
39870b57cec5SDimitry Andric   PrintVisibility(F->getVisibility(), Out);
39880b57cec5SDimitry Andric   PrintDLLStorageClass(F->getDLLStorageClass(), Out);
39890b57cec5SDimitry Andric 
39900b57cec5SDimitry Andric   // Print the calling convention.
39910b57cec5SDimitry Andric   if (F->getCallingConv() != CallingConv::C) {
39920b57cec5SDimitry Andric     PrintCallingConv(F->getCallingConv(), Out);
39930b57cec5SDimitry Andric     Out << " ";
39940b57cec5SDimitry Andric   }
39950b57cec5SDimitry Andric 
39960b57cec5SDimitry Andric   FunctionType *FT = F->getFunctionType();
3997349cc55cSDimitry Andric   if (Attrs.hasRetAttrs())
39980b57cec5SDimitry Andric     Out << Attrs.getAsString(AttributeList::ReturnIndex) << ' ';
39990b57cec5SDimitry Andric   TypePrinter.print(F->getReturnType(), Out);
4000349cc55cSDimitry Andric   AsmWriterContext WriterCtx(&TypePrinter, &Machine, F->getParent());
40010b57cec5SDimitry Andric   Out << ' ';
4002349cc55cSDimitry Andric   WriteAsOperandInternal(Out, F, WriterCtx);
40030b57cec5SDimitry Andric   Out << '(';
40040b57cec5SDimitry Andric 
40050b57cec5SDimitry Andric   // Loop over the arguments, printing them...
40060b57cec5SDimitry Andric   if (F->isDeclaration() && !IsForDebug) {
40070b57cec5SDimitry Andric     // We're only interested in the type here - don't print argument names.
40080b57cec5SDimitry Andric     for (unsigned I = 0, E = FT->getNumParams(); I != E; ++I) {
40090b57cec5SDimitry Andric       // Insert commas as we go... the first arg doesn't get a comma
40100b57cec5SDimitry Andric       if (I)
40110b57cec5SDimitry Andric         Out << ", ";
40120b57cec5SDimitry Andric       // Output type...
40130b57cec5SDimitry Andric       TypePrinter.print(FT->getParamType(I), Out);
40140b57cec5SDimitry Andric 
4015349cc55cSDimitry Andric       AttributeSet ArgAttrs = Attrs.getParamAttrs(I);
4016480093f4SDimitry Andric       if (ArgAttrs.hasAttributes()) {
4017480093f4SDimitry Andric         Out << ' ';
4018480093f4SDimitry Andric         writeAttributeSet(ArgAttrs);
4019480093f4SDimitry Andric       }
40200b57cec5SDimitry Andric     }
40210b57cec5SDimitry Andric   } else {
40220b57cec5SDimitry Andric     // The arguments are meaningful here, print them in detail.
40230b57cec5SDimitry Andric     for (const Argument &Arg : F->args()) {
40240b57cec5SDimitry Andric       // Insert commas as we go... the first arg doesn't get a comma
40250b57cec5SDimitry Andric       if (Arg.getArgNo() != 0)
40260b57cec5SDimitry Andric         Out << ", ";
4027349cc55cSDimitry Andric       printArgument(&Arg, Attrs.getParamAttrs(Arg.getArgNo()));
40280b57cec5SDimitry Andric     }
40290b57cec5SDimitry Andric   }
40300b57cec5SDimitry Andric 
40310b57cec5SDimitry Andric   // Finish printing arguments...
40320b57cec5SDimitry Andric   if (FT->isVarArg()) {
40330b57cec5SDimitry Andric     if (FT->getNumParams()) Out << ", ";
40340b57cec5SDimitry Andric     Out << "...";  // Output varargs portion of signature!
40350b57cec5SDimitry Andric   }
40360b57cec5SDimitry Andric   Out << ')';
40370b57cec5SDimitry Andric   StringRef UA = getUnnamedAddrEncoding(F->getUnnamedAddr());
40380b57cec5SDimitry Andric   if (!UA.empty())
40390b57cec5SDimitry Andric     Out << ' ' << UA;
40400b57cec5SDimitry Andric   // We print the function address space if it is non-zero or if we are writing
40410b57cec5SDimitry Andric   // a module with a non-zero program address space or if there is no valid
40420b57cec5SDimitry Andric   // Module* so that the file can be parsed without the datalayout string.
40430b57cec5SDimitry Andric   const Module *Mod = F->getParent();
40440b57cec5SDimitry Andric   if (F->getAddressSpace() != 0 || !Mod ||
40450b57cec5SDimitry Andric       Mod->getDataLayout().getProgramAddressSpace() != 0)
40460b57cec5SDimitry Andric     Out << " addrspace(" << F->getAddressSpace() << ")";
4047349cc55cSDimitry Andric   if (Attrs.hasFnAttrs())
4048349cc55cSDimitry Andric     Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttrs());
40490b57cec5SDimitry Andric   if (F->hasSection()) {
40500b57cec5SDimitry Andric     Out << " section \"";
40510b57cec5SDimitry Andric     printEscapedString(F->getSection(), Out);
40520b57cec5SDimitry Andric     Out << '"';
40530b57cec5SDimitry Andric   }
40540b57cec5SDimitry Andric   if (F->hasPartition()) {
40550b57cec5SDimitry Andric     Out << " partition \"";
40560b57cec5SDimitry Andric     printEscapedString(F->getPartition(), Out);
40570b57cec5SDimitry Andric     Out << '"';
40580b57cec5SDimitry Andric   }
40590b57cec5SDimitry Andric   maybePrintComdat(Out, *F);
40600eae32dcSDimitry Andric   if (MaybeAlign A = F->getAlign())
40610eae32dcSDimitry Andric     Out << " align " << A->value();
40620b57cec5SDimitry Andric   if (F->hasGC())
40630b57cec5SDimitry Andric     Out << " gc \"" << F->getGC() << '"';
40640b57cec5SDimitry Andric   if (F->hasPrefixData()) {
40650b57cec5SDimitry Andric     Out << " prefix ";
40660b57cec5SDimitry Andric     writeOperand(F->getPrefixData(), true);
40670b57cec5SDimitry Andric   }
40680b57cec5SDimitry Andric   if (F->hasPrologueData()) {
40690b57cec5SDimitry Andric     Out << " prologue ";
40700b57cec5SDimitry Andric     writeOperand(F->getPrologueData(), true);
40710b57cec5SDimitry Andric   }
40720b57cec5SDimitry Andric   if (F->hasPersonalityFn()) {
40730b57cec5SDimitry Andric     Out << " personality ";
40740b57cec5SDimitry Andric     writeOperand(F->getPersonalityFn(), /*PrintType=*/true);
40750b57cec5SDimitry Andric   }
40760b57cec5SDimitry Andric 
40770b57cec5SDimitry Andric   if (F->isDeclaration()) {
40780b57cec5SDimitry Andric     Out << '\n';
40790b57cec5SDimitry Andric   } else {
40800b57cec5SDimitry Andric     SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
40810b57cec5SDimitry Andric     F->getAllMetadata(MDs);
40820b57cec5SDimitry Andric     printMetadataAttachments(MDs, " ");
40830b57cec5SDimitry Andric 
40840b57cec5SDimitry Andric     Out << " {";
40850b57cec5SDimitry Andric     // Output all of the function's basic blocks.
40860b57cec5SDimitry Andric     for (const BasicBlock &BB : *F)
40870b57cec5SDimitry Andric       printBasicBlock(&BB);
40880b57cec5SDimitry Andric 
40890b57cec5SDimitry Andric     // Output the function's use-lists.
40900b57cec5SDimitry Andric     printUseLists(F);
40910b57cec5SDimitry Andric 
40920b57cec5SDimitry Andric     Out << "}\n";
40930b57cec5SDimitry Andric   }
40940b57cec5SDimitry Andric 
40950b57cec5SDimitry Andric   Machine.purgeFunction();
40960b57cec5SDimitry Andric }
40970b57cec5SDimitry Andric 
40980b57cec5SDimitry Andric /// printArgument - This member is called for every argument that is passed into
40990b57cec5SDimitry Andric /// the function.  Simply print it out
printArgument(const Argument * Arg,AttributeSet Attrs)41000b57cec5SDimitry Andric void AssemblyWriter::printArgument(const Argument *Arg, AttributeSet Attrs) {
41010b57cec5SDimitry Andric   // Output type...
41020b57cec5SDimitry Andric   TypePrinter.print(Arg->getType(), Out);
41030b57cec5SDimitry Andric 
41040b57cec5SDimitry Andric   // Output parameter attributes list
4105480093f4SDimitry Andric   if (Attrs.hasAttributes()) {
4106480093f4SDimitry Andric     Out << ' ';
4107480093f4SDimitry Andric     writeAttributeSet(Attrs);
4108480093f4SDimitry Andric   }
41090b57cec5SDimitry Andric 
41100b57cec5SDimitry Andric   // Output name, if available...
41110b57cec5SDimitry Andric   if (Arg->hasName()) {
41120b57cec5SDimitry Andric     Out << ' ';
41130b57cec5SDimitry Andric     PrintLLVMName(Out, Arg);
41148bcb0991SDimitry Andric   } else {
41158bcb0991SDimitry Andric     int Slot = Machine.getLocalSlot(Arg);
41168bcb0991SDimitry Andric     assert(Slot != -1 && "expect argument in function here");
41178bcb0991SDimitry Andric     Out << " %" << Slot;
41180b57cec5SDimitry Andric   }
41190b57cec5SDimitry Andric }
41200b57cec5SDimitry Andric 
41210b57cec5SDimitry Andric /// printBasicBlock - This member is called for each basic block in a method.
printBasicBlock(const BasicBlock * BB)41220b57cec5SDimitry Andric void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
4123fe6060f1SDimitry Andric   bool IsEntryBlock = BB->getParent() && BB->isEntryBlock();
41240b57cec5SDimitry Andric   if (BB->hasName()) {              // Print out the label if it exists...
41250b57cec5SDimitry Andric     Out << "\n";
41260b57cec5SDimitry Andric     PrintLLVMName(Out, BB->getName(), LabelPrefix);
41270b57cec5SDimitry Andric     Out << ':';
41280b57cec5SDimitry Andric   } else if (!IsEntryBlock) {
41290b57cec5SDimitry Andric     Out << "\n";
41300b57cec5SDimitry Andric     int Slot = Machine.getLocalSlot(BB);
41310b57cec5SDimitry Andric     if (Slot != -1)
41320b57cec5SDimitry Andric       Out << Slot << ":";
41330b57cec5SDimitry Andric     else
41340b57cec5SDimitry Andric       Out << "<badref>:";
41350b57cec5SDimitry Andric   }
41360b57cec5SDimitry Andric 
4137480093f4SDimitry Andric   if (!IsEntryBlock) {
41380b57cec5SDimitry Andric     // Output predecessors for the block.
41390b57cec5SDimitry Andric     Out.PadToColumn(50);
41400b57cec5SDimitry Andric     Out << ";";
41410b57cec5SDimitry Andric     const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
41420b57cec5SDimitry Andric 
41430b57cec5SDimitry Andric     if (PI == PE) {
41440b57cec5SDimitry Andric       Out << " No predecessors!";
41450b57cec5SDimitry Andric     } else {
41460b57cec5SDimitry Andric       Out << " preds = ";
41470b57cec5SDimitry Andric       writeOperand(*PI, false);
41480b57cec5SDimitry Andric       for (++PI; PI != PE; ++PI) {
41490b57cec5SDimitry Andric         Out << ", ";
41500b57cec5SDimitry Andric         writeOperand(*PI, false);
41510b57cec5SDimitry Andric       }
41520b57cec5SDimitry Andric     }
41530b57cec5SDimitry Andric   }
41540b57cec5SDimitry Andric 
41550b57cec5SDimitry Andric   Out << "\n";
41560b57cec5SDimitry Andric 
41570b57cec5SDimitry Andric   if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
41580b57cec5SDimitry Andric 
41590b57cec5SDimitry Andric   // Output all of the instructions in the basic block...
41600b57cec5SDimitry Andric   for (const Instruction &I : *BB) {
4161*0fca6ea1SDimitry Andric     for (const DbgRecord &DR : I.getDbgRecordRange())
4162*0fca6ea1SDimitry Andric       printDbgRecordLine(DR);
41630b57cec5SDimitry Andric     printInstructionLine(I);
41640b57cec5SDimitry Andric   }
41650b57cec5SDimitry Andric 
41660b57cec5SDimitry Andric   if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
41670b57cec5SDimitry Andric }
41680b57cec5SDimitry Andric 
41690b57cec5SDimitry Andric /// printInstructionLine - Print an instruction and a newline character.
printInstructionLine(const Instruction & I)41700b57cec5SDimitry Andric void AssemblyWriter::printInstructionLine(const Instruction &I) {
41710b57cec5SDimitry Andric   printInstruction(I);
41720b57cec5SDimitry Andric   Out << '\n';
41730b57cec5SDimitry Andric }
41740b57cec5SDimitry Andric 
41750b57cec5SDimitry Andric /// printGCRelocateComment - print comment after call to the gc.relocate
41760b57cec5SDimitry Andric /// intrinsic indicating base and derived pointer names.
printGCRelocateComment(const GCRelocateInst & Relocate)41770b57cec5SDimitry Andric void AssemblyWriter::printGCRelocateComment(const GCRelocateInst &Relocate) {
41780b57cec5SDimitry Andric   Out << " ; (";
41790b57cec5SDimitry Andric   writeOperand(Relocate.getBasePtr(), false);
41800b57cec5SDimitry Andric   Out << ", ";
41810b57cec5SDimitry Andric   writeOperand(Relocate.getDerivedPtr(), false);
41820b57cec5SDimitry Andric   Out << ")";
41830b57cec5SDimitry Andric }
41840b57cec5SDimitry Andric 
41850b57cec5SDimitry Andric /// printInfoComment - Print a little comment after the instruction indicating
41860b57cec5SDimitry Andric /// which slot it occupies.
printInfoComment(const Value & V)41870b57cec5SDimitry Andric void AssemblyWriter::printInfoComment(const Value &V) {
41880b57cec5SDimitry Andric   if (const auto *Relocate = dyn_cast<GCRelocateInst>(&V))
41890b57cec5SDimitry Andric     printGCRelocateComment(*Relocate);
41900b57cec5SDimitry Andric 
41915f757f3fSDimitry Andric   if (AnnotationWriter) {
41920b57cec5SDimitry Andric     AnnotationWriter->printInfoComment(V, Out);
41935f757f3fSDimitry Andric   }
41940b57cec5SDimitry Andric }
41950b57cec5SDimitry Andric 
maybePrintCallAddrSpace(const Value * Operand,const Instruction * I,raw_ostream & Out)41960b57cec5SDimitry Andric static void maybePrintCallAddrSpace(const Value *Operand, const Instruction *I,
41970b57cec5SDimitry Andric                                     raw_ostream &Out) {
41980b57cec5SDimitry Andric   // We print the address space of the call if it is non-zero.
4199bdd1243dSDimitry Andric   if (Operand == nullptr) {
4200bdd1243dSDimitry Andric     Out << " <cannot get addrspace!>";
4201bdd1243dSDimitry Andric     return;
4202bdd1243dSDimitry Andric   }
42030b57cec5SDimitry Andric   unsigned CallAddrSpace = Operand->getType()->getPointerAddressSpace();
42040b57cec5SDimitry Andric   bool PrintAddrSpace = CallAddrSpace != 0;
42050b57cec5SDimitry Andric   if (!PrintAddrSpace) {
42060b57cec5SDimitry Andric     const Module *Mod = getModuleFromVal(I);
42070b57cec5SDimitry Andric     // We also print it if it is zero but not equal to the program address space
42080b57cec5SDimitry Andric     // or if we can't find a valid Module* to make it possible to parse
42090b57cec5SDimitry Andric     // the resulting file even without a datalayout string.
42100b57cec5SDimitry Andric     if (!Mod || Mod->getDataLayout().getProgramAddressSpace() != 0)
42110b57cec5SDimitry Andric       PrintAddrSpace = true;
42120b57cec5SDimitry Andric   }
42130b57cec5SDimitry Andric   if (PrintAddrSpace)
42140b57cec5SDimitry Andric     Out << " addrspace(" << CallAddrSpace << ")";
42150b57cec5SDimitry Andric }
42160b57cec5SDimitry Andric 
42170b57cec5SDimitry Andric // This member is called for each Instruction in a function..
printInstruction(const Instruction & I)42180b57cec5SDimitry Andric void AssemblyWriter::printInstruction(const Instruction &I) {
42190b57cec5SDimitry Andric   if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
42200b57cec5SDimitry Andric 
42210b57cec5SDimitry Andric   // Print out indentation for an instruction.
42220b57cec5SDimitry Andric   Out << "  ";
42230b57cec5SDimitry Andric 
42240b57cec5SDimitry Andric   // Print out name if it exists...
42250b57cec5SDimitry Andric   if (I.hasName()) {
42260b57cec5SDimitry Andric     PrintLLVMName(Out, &I);
42270b57cec5SDimitry Andric     Out << " = ";
42280b57cec5SDimitry Andric   } else if (!I.getType()->isVoidTy()) {
42290b57cec5SDimitry Andric     // Print out the def slot taken.
42300b57cec5SDimitry Andric     int SlotNum = Machine.getLocalSlot(&I);
42310b57cec5SDimitry Andric     if (SlotNum == -1)
42320b57cec5SDimitry Andric       Out << "<badref> = ";
42330b57cec5SDimitry Andric     else
42340b57cec5SDimitry Andric       Out << '%' << SlotNum << " = ";
42350b57cec5SDimitry Andric   }
42360b57cec5SDimitry Andric 
42370b57cec5SDimitry Andric   if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
42380b57cec5SDimitry Andric     if (CI->isMustTailCall())
42390b57cec5SDimitry Andric       Out << "musttail ";
42400b57cec5SDimitry Andric     else if (CI->isTailCall())
42410b57cec5SDimitry Andric       Out << "tail ";
42420b57cec5SDimitry Andric     else if (CI->isNoTailCall())
42430b57cec5SDimitry Andric       Out << "notail ";
42440b57cec5SDimitry Andric   }
42450b57cec5SDimitry Andric 
42460b57cec5SDimitry Andric   // Print out the opcode...
42470b57cec5SDimitry Andric   Out << I.getOpcodeName();
42480b57cec5SDimitry Andric 
42490b57cec5SDimitry Andric   // If this is an atomic load or store, print out the atomic marker.
42500b57cec5SDimitry Andric   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isAtomic()) ||
42510b57cec5SDimitry Andric       (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
42520b57cec5SDimitry Andric     Out << " atomic";
42530b57cec5SDimitry Andric 
42540b57cec5SDimitry Andric   if (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isWeak())
42550b57cec5SDimitry Andric     Out << " weak";
42560b57cec5SDimitry Andric 
42570b57cec5SDimitry Andric   // If this is a volatile operation, print out the volatile marker.
42580b57cec5SDimitry Andric   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isVolatile()) ||
42590b57cec5SDimitry Andric       (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
42600b57cec5SDimitry Andric       (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
42610b57cec5SDimitry Andric       (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
42620b57cec5SDimitry Andric     Out << " volatile";
42630b57cec5SDimitry Andric 
42640b57cec5SDimitry Andric   // Print out optimization information.
42650b57cec5SDimitry Andric   WriteOptimizationInfo(Out, &I);
42660b57cec5SDimitry Andric 
42670b57cec5SDimitry Andric   // Print out the compare instruction predicates
42680b57cec5SDimitry Andric   if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
426906c3fb27SDimitry Andric     Out << ' ' << CI->getPredicate();
42700b57cec5SDimitry Andric 
42710b57cec5SDimitry Andric   // Print out the atomicrmw operation
42720b57cec5SDimitry Andric   if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
42730b57cec5SDimitry Andric     Out << ' ' << AtomicRMWInst::getOperationName(RMWI->getOperation());
42740b57cec5SDimitry Andric 
42750b57cec5SDimitry Andric   // Print out the type of the operands...
42760b57cec5SDimitry Andric   const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr;
42770b57cec5SDimitry Andric 
42780b57cec5SDimitry Andric   // Special case conditional branches to swizzle the condition out to the front
42790b57cec5SDimitry Andric   if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
42800b57cec5SDimitry Andric     const BranchInst &BI(cast<BranchInst>(I));
42810b57cec5SDimitry Andric     Out << ' ';
42820b57cec5SDimitry Andric     writeOperand(BI.getCondition(), true);
42830b57cec5SDimitry Andric     Out << ", ";
42840b57cec5SDimitry Andric     writeOperand(BI.getSuccessor(0), true);
42850b57cec5SDimitry Andric     Out << ", ";
42860b57cec5SDimitry Andric     writeOperand(BI.getSuccessor(1), true);
42870b57cec5SDimitry Andric 
42880b57cec5SDimitry Andric   } else if (isa<SwitchInst>(I)) {
42890b57cec5SDimitry Andric     const SwitchInst& SI(cast<SwitchInst>(I));
42900b57cec5SDimitry Andric     // Special case switch instruction to get formatting nice and correct.
42910b57cec5SDimitry Andric     Out << ' ';
42920b57cec5SDimitry Andric     writeOperand(SI.getCondition(), true);
42930b57cec5SDimitry Andric     Out << ", ";
42940b57cec5SDimitry Andric     writeOperand(SI.getDefaultDest(), true);
42950b57cec5SDimitry Andric     Out << " [";
42960b57cec5SDimitry Andric     for (auto Case : SI.cases()) {
42970b57cec5SDimitry Andric       Out << "\n    ";
42980b57cec5SDimitry Andric       writeOperand(Case.getCaseValue(), true);
42990b57cec5SDimitry Andric       Out << ", ";
43000b57cec5SDimitry Andric       writeOperand(Case.getCaseSuccessor(), true);
43010b57cec5SDimitry Andric     }
43020b57cec5SDimitry Andric     Out << "\n  ]";
43030b57cec5SDimitry Andric   } else if (isa<IndirectBrInst>(I)) {
43040b57cec5SDimitry Andric     // Special case indirectbr instruction to get formatting nice and correct.
43050b57cec5SDimitry Andric     Out << ' ';
43060b57cec5SDimitry Andric     writeOperand(Operand, true);
43070b57cec5SDimitry Andric     Out << ", [";
43080b57cec5SDimitry Andric 
43090b57cec5SDimitry Andric     for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
43100b57cec5SDimitry Andric       if (i != 1)
43110b57cec5SDimitry Andric         Out << ", ";
43120b57cec5SDimitry Andric       writeOperand(I.getOperand(i), true);
43130b57cec5SDimitry Andric     }
43140b57cec5SDimitry Andric     Out << ']';
43150b57cec5SDimitry Andric   } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
43160b57cec5SDimitry Andric     Out << ' ';
43170b57cec5SDimitry Andric     TypePrinter.print(I.getType(), Out);
43180b57cec5SDimitry Andric     Out << ' ';
43190b57cec5SDimitry Andric 
43200b57cec5SDimitry Andric     for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
43210b57cec5SDimitry Andric       if (op) Out << ", ";
43220b57cec5SDimitry Andric       Out << "[ ";
43230b57cec5SDimitry Andric       writeOperand(PN->getIncomingValue(op), false); Out << ", ";
43240b57cec5SDimitry Andric       writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
43250b57cec5SDimitry Andric     }
43260b57cec5SDimitry Andric   } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
43270b57cec5SDimitry Andric     Out << ' ';
43280b57cec5SDimitry Andric     writeOperand(I.getOperand(0), true);
4329fe6060f1SDimitry Andric     for (unsigned i : EVI->indices())
4330fe6060f1SDimitry Andric       Out << ", " << i;
43310b57cec5SDimitry Andric   } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
43320b57cec5SDimitry Andric     Out << ' ';
43330b57cec5SDimitry Andric     writeOperand(I.getOperand(0), true); Out << ", ";
43340b57cec5SDimitry Andric     writeOperand(I.getOperand(1), true);
4335fe6060f1SDimitry Andric     for (unsigned i : IVI->indices())
4336fe6060f1SDimitry Andric       Out << ", " << i;
43370b57cec5SDimitry Andric   } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
43380b57cec5SDimitry Andric     Out << ' ';
43390b57cec5SDimitry Andric     TypePrinter.print(I.getType(), Out);
43400b57cec5SDimitry Andric     if (LPI->isCleanup() || LPI->getNumClauses() != 0)
43410b57cec5SDimitry Andric       Out << '\n';
43420b57cec5SDimitry Andric 
43430b57cec5SDimitry Andric     if (LPI->isCleanup())
43440b57cec5SDimitry Andric       Out << "          cleanup";
43450b57cec5SDimitry Andric 
43460b57cec5SDimitry Andric     for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
43470b57cec5SDimitry Andric       if (i != 0 || LPI->isCleanup()) Out << "\n";
43480b57cec5SDimitry Andric       if (LPI->isCatch(i))
43490b57cec5SDimitry Andric         Out << "          catch ";
43500b57cec5SDimitry Andric       else
43510b57cec5SDimitry Andric         Out << "          filter ";
43520b57cec5SDimitry Andric 
43530b57cec5SDimitry Andric       writeOperand(LPI->getClause(i), true);
43540b57cec5SDimitry Andric     }
43550b57cec5SDimitry Andric   } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(&I)) {
43560b57cec5SDimitry Andric     Out << " within ";
43570b57cec5SDimitry Andric     writeOperand(CatchSwitch->getParentPad(), /*PrintType=*/false);
43580b57cec5SDimitry Andric     Out << " [";
43590b57cec5SDimitry Andric     unsigned Op = 0;
43600b57cec5SDimitry Andric     for (const BasicBlock *PadBB : CatchSwitch->handlers()) {
43610b57cec5SDimitry Andric       if (Op > 0)
43620b57cec5SDimitry Andric         Out << ", ";
43630b57cec5SDimitry Andric       writeOperand(PadBB, /*PrintType=*/true);
43640b57cec5SDimitry Andric       ++Op;
43650b57cec5SDimitry Andric     }
43660b57cec5SDimitry Andric     Out << "] unwind ";
43670b57cec5SDimitry Andric     if (const BasicBlock *UnwindDest = CatchSwitch->getUnwindDest())
43680b57cec5SDimitry Andric       writeOperand(UnwindDest, /*PrintType=*/true);
43690b57cec5SDimitry Andric     else
43700b57cec5SDimitry Andric       Out << "to caller";
43710b57cec5SDimitry Andric   } else if (const auto *FPI = dyn_cast<FuncletPadInst>(&I)) {
43720b57cec5SDimitry Andric     Out << " within ";
43730b57cec5SDimitry Andric     writeOperand(FPI->getParentPad(), /*PrintType=*/false);
43740b57cec5SDimitry Andric     Out << " [";
4375bdd1243dSDimitry Andric     for (unsigned Op = 0, NumOps = FPI->arg_size(); Op < NumOps; ++Op) {
43760b57cec5SDimitry Andric       if (Op > 0)
43770b57cec5SDimitry Andric         Out << ", ";
43780b57cec5SDimitry Andric       writeOperand(FPI->getArgOperand(Op), /*PrintType=*/true);
43790b57cec5SDimitry Andric     }
43800b57cec5SDimitry Andric     Out << ']';
43810b57cec5SDimitry Andric   } else if (isa<ReturnInst>(I) && !Operand) {
43820b57cec5SDimitry Andric     Out << " void";
43830b57cec5SDimitry Andric   } else if (const auto *CRI = dyn_cast<CatchReturnInst>(&I)) {
43840b57cec5SDimitry Andric     Out << " from ";
43850b57cec5SDimitry Andric     writeOperand(CRI->getOperand(0), /*PrintType=*/false);
43860b57cec5SDimitry Andric 
43870b57cec5SDimitry Andric     Out << " to ";
43880b57cec5SDimitry Andric     writeOperand(CRI->getOperand(1), /*PrintType=*/true);
43890b57cec5SDimitry Andric   } else if (const auto *CRI = dyn_cast<CleanupReturnInst>(&I)) {
43900b57cec5SDimitry Andric     Out << " from ";
43910b57cec5SDimitry Andric     writeOperand(CRI->getOperand(0), /*PrintType=*/false);
43920b57cec5SDimitry Andric 
43930b57cec5SDimitry Andric     Out << " unwind ";
43940b57cec5SDimitry Andric     if (CRI->hasUnwindDest())
43950b57cec5SDimitry Andric       writeOperand(CRI->getOperand(1), /*PrintType=*/true);
43960b57cec5SDimitry Andric     else
43970b57cec5SDimitry Andric       Out << "to caller";
43980b57cec5SDimitry Andric   } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
43990b57cec5SDimitry Andric     // Print the calling convention being used.
44000b57cec5SDimitry Andric     if (CI->getCallingConv() != CallingConv::C) {
44010b57cec5SDimitry Andric       Out << " ";
44020b57cec5SDimitry Andric       PrintCallingConv(CI->getCallingConv(), Out);
44030b57cec5SDimitry Andric     }
44040b57cec5SDimitry Andric 
44055ffd83dbSDimitry Andric     Operand = CI->getCalledOperand();
44060b57cec5SDimitry Andric     FunctionType *FTy = CI->getFunctionType();
44070b57cec5SDimitry Andric     Type *RetTy = FTy->getReturnType();
44080b57cec5SDimitry Andric     const AttributeList &PAL = CI->getAttributes();
44090b57cec5SDimitry Andric 
4410349cc55cSDimitry Andric     if (PAL.hasRetAttrs())
44110b57cec5SDimitry Andric       Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
44120b57cec5SDimitry Andric 
44130b57cec5SDimitry Andric     // Only print addrspace(N) if necessary:
44140b57cec5SDimitry Andric     maybePrintCallAddrSpace(Operand, &I, Out);
44150b57cec5SDimitry Andric 
44160b57cec5SDimitry Andric     // If possible, print out the short form of the call instruction.  We can
44170b57cec5SDimitry Andric     // only do this if the first argument is a pointer to a nonvararg function,
44180b57cec5SDimitry Andric     // and if the return type is not a pointer to a function.
44190b57cec5SDimitry Andric     Out << ' ';
44200b57cec5SDimitry Andric     TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
44210b57cec5SDimitry Andric     Out << ' ';
44220b57cec5SDimitry Andric     writeOperand(Operand, false);
44230b57cec5SDimitry Andric     Out << '(';
4424349cc55cSDimitry Andric     for (unsigned op = 0, Eop = CI->arg_size(); op < Eop; ++op) {
44250b57cec5SDimitry Andric       if (op > 0)
44260b57cec5SDimitry Andric         Out << ", ";
4427349cc55cSDimitry Andric       writeParamOperand(CI->getArgOperand(op), PAL.getParamAttrs(op));
44280b57cec5SDimitry Andric     }
44290b57cec5SDimitry Andric 
44300b57cec5SDimitry Andric     // Emit an ellipsis if this is a musttail call in a vararg function.  This
44310b57cec5SDimitry Andric     // is only to aid readability, musttail calls forward varargs by default.
44320b57cec5SDimitry Andric     if (CI->isMustTailCall() && CI->getParent() &&
44330b57cec5SDimitry Andric         CI->getParent()->getParent() &&
4434bdd1243dSDimitry Andric         CI->getParent()->getParent()->isVarArg()) {
4435bdd1243dSDimitry Andric       if (CI->arg_size() > 0)
4436bdd1243dSDimitry Andric         Out << ", ";
4437bdd1243dSDimitry Andric       Out << "...";
4438bdd1243dSDimitry Andric     }
44390b57cec5SDimitry Andric 
44400b57cec5SDimitry Andric     Out << ')';
4441349cc55cSDimitry Andric     if (PAL.hasFnAttrs())
4442349cc55cSDimitry Andric       Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttrs());
44430b57cec5SDimitry Andric 
44440b57cec5SDimitry Andric     writeOperandBundles(CI);
44450b57cec5SDimitry Andric   } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
44465ffd83dbSDimitry Andric     Operand = II->getCalledOperand();
44470b57cec5SDimitry Andric     FunctionType *FTy = II->getFunctionType();
44480b57cec5SDimitry Andric     Type *RetTy = FTy->getReturnType();
44490b57cec5SDimitry Andric     const AttributeList &PAL = II->getAttributes();
44500b57cec5SDimitry Andric 
44510b57cec5SDimitry Andric     // Print the calling convention being used.
44520b57cec5SDimitry Andric     if (II->getCallingConv() != CallingConv::C) {
44530b57cec5SDimitry Andric       Out << " ";
44540b57cec5SDimitry Andric       PrintCallingConv(II->getCallingConv(), Out);
44550b57cec5SDimitry Andric     }
44560b57cec5SDimitry Andric 
4457349cc55cSDimitry Andric     if (PAL.hasRetAttrs())
44580b57cec5SDimitry Andric       Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
44590b57cec5SDimitry Andric 
44600b57cec5SDimitry Andric     // Only print addrspace(N) if necessary:
44610b57cec5SDimitry Andric     maybePrintCallAddrSpace(Operand, &I, Out);
44620b57cec5SDimitry Andric 
44630b57cec5SDimitry Andric     // If possible, print out the short form of the invoke instruction. We can
44640b57cec5SDimitry Andric     // only do this if the first argument is a pointer to a nonvararg function,
44650b57cec5SDimitry Andric     // and if the return type is not a pointer to a function.
44660b57cec5SDimitry Andric     //
44670b57cec5SDimitry Andric     Out << ' ';
44680b57cec5SDimitry Andric     TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
44690b57cec5SDimitry Andric     Out << ' ';
44700b57cec5SDimitry Andric     writeOperand(Operand, false);
44710b57cec5SDimitry Andric     Out << '(';
4472349cc55cSDimitry Andric     for (unsigned op = 0, Eop = II->arg_size(); op < Eop; ++op) {
44730b57cec5SDimitry Andric       if (op)
44740b57cec5SDimitry Andric         Out << ", ";
4475349cc55cSDimitry Andric       writeParamOperand(II->getArgOperand(op), PAL.getParamAttrs(op));
44760b57cec5SDimitry Andric     }
44770b57cec5SDimitry Andric 
44780b57cec5SDimitry Andric     Out << ')';
4479349cc55cSDimitry Andric     if (PAL.hasFnAttrs())
4480349cc55cSDimitry Andric       Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttrs());
44810b57cec5SDimitry Andric 
44820b57cec5SDimitry Andric     writeOperandBundles(II);
44830b57cec5SDimitry Andric 
44840b57cec5SDimitry Andric     Out << "\n          to ";
44850b57cec5SDimitry Andric     writeOperand(II->getNormalDest(), true);
44860b57cec5SDimitry Andric     Out << " unwind ";
44870b57cec5SDimitry Andric     writeOperand(II->getUnwindDest(), true);
44880b57cec5SDimitry Andric   } else if (const CallBrInst *CBI = dyn_cast<CallBrInst>(&I)) {
44895ffd83dbSDimitry Andric     Operand = CBI->getCalledOperand();
44900b57cec5SDimitry Andric     FunctionType *FTy = CBI->getFunctionType();
44910b57cec5SDimitry Andric     Type *RetTy = FTy->getReturnType();
44920b57cec5SDimitry Andric     const AttributeList &PAL = CBI->getAttributes();
44930b57cec5SDimitry Andric 
44940b57cec5SDimitry Andric     // Print the calling convention being used.
44950b57cec5SDimitry Andric     if (CBI->getCallingConv() != CallingConv::C) {
44960b57cec5SDimitry Andric       Out << " ";
44970b57cec5SDimitry Andric       PrintCallingConv(CBI->getCallingConv(), Out);
44980b57cec5SDimitry Andric     }
44990b57cec5SDimitry Andric 
4500349cc55cSDimitry Andric     if (PAL.hasRetAttrs())
45010b57cec5SDimitry Andric       Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
45020b57cec5SDimitry Andric 
45030b57cec5SDimitry Andric     // If possible, print out the short form of the callbr instruction. We can
45040b57cec5SDimitry Andric     // only do this if the first argument is a pointer to a nonvararg function,
45050b57cec5SDimitry Andric     // and if the return type is not a pointer to a function.
45060b57cec5SDimitry Andric     //
45070b57cec5SDimitry Andric     Out << ' ';
45080b57cec5SDimitry Andric     TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
45090b57cec5SDimitry Andric     Out << ' ';
45100b57cec5SDimitry Andric     writeOperand(Operand, false);
45110b57cec5SDimitry Andric     Out << '(';
4512349cc55cSDimitry Andric     for (unsigned op = 0, Eop = CBI->arg_size(); op < Eop; ++op) {
45130b57cec5SDimitry Andric       if (op)
45140b57cec5SDimitry Andric         Out << ", ";
4515349cc55cSDimitry Andric       writeParamOperand(CBI->getArgOperand(op), PAL.getParamAttrs(op));
45160b57cec5SDimitry Andric     }
45170b57cec5SDimitry Andric 
45180b57cec5SDimitry Andric     Out << ')';
4519349cc55cSDimitry Andric     if (PAL.hasFnAttrs())
4520349cc55cSDimitry Andric       Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttrs());
45210b57cec5SDimitry Andric 
45220b57cec5SDimitry Andric     writeOperandBundles(CBI);
45230b57cec5SDimitry Andric 
45240b57cec5SDimitry Andric     Out << "\n          to ";
45250b57cec5SDimitry Andric     writeOperand(CBI->getDefaultDest(), true);
45260b57cec5SDimitry Andric     Out << " [";
45270b57cec5SDimitry Andric     for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i) {
45280b57cec5SDimitry Andric       if (i != 0)
45290b57cec5SDimitry Andric         Out << ", ";
45300b57cec5SDimitry Andric       writeOperand(CBI->getIndirectDest(i), true);
45310b57cec5SDimitry Andric     }
45320b57cec5SDimitry Andric     Out << ']';
45330b57cec5SDimitry Andric   } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
45340b57cec5SDimitry Andric     Out << ' ';
45350b57cec5SDimitry Andric     if (AI->isUsedWithInAlloca())
45360b57cec5SDimitry Andric       Out << "inalloca ";
45370b57cec5SDimitry Andric     if (AI->isSwiftError())
45380b57cec5SDimitry Andric       Out << "swifterror ";
45390b57cec5SDimitry Andric     TypePrinter.print(AI->getAllocatedType(), Out);
45400b57cec5SDimitry Andric 
45410b57cec5SDimitry Andric     // Explicitly write the array size if the code is broken, if it's an array
45420b57cec5SDimitry Andric     // allocation, or if the type is not canonical for scalar allocations.  The
45430b57cec5SDimitry Andric     // latter case prevents the type from mutating when round-tripping through
45440b57cec5SDimitry Andric     // assembly.
45450b57cec5SDimitry Andric     if (!AI->getArraySize() || AI->isArrayAllocation() ||
45460b57cec5SDimitry Andric         !AI->getArraySize()->getType()->isIntegerTy(32)) {
45470b57cec5SDimitry Andric       Out << ", ";
45480b57cec5SDimitry Andric       writeOperand(AI->getArraySize(), true);
45490b57cec5SDimitry Andric     }
45500eae32dcSDimitry Andric     if (MaybeAlign A = AI->getAlign()) {
45510eae32dcSDimitry Andric       Out << ", align " << A->value();
45520b57cec5SDimitry Andric     }
45530b57cec5SDimitry Andric 
4554bdd1243dSDimitry Andric     unsigned AddrSpace = AI->getAddressSpace();
45550b57cec5SDimitry Andric     if (AddrSpace != 0) {
45560b57cec5SDimitry Andric       Out << ", addrspace(" << AddrSpace << ')';
45570b57cec5SDimitry Andric     }
45580b57cec5SDimitry Andric   } else if (isa<CastInst>(I)) {
45590b57cec5SDimitry Andric     if (Operand) {
45600b57cec5SDimitry Andric       Out << ' ';
45610b57cec5SDimitry Andric       writeOperand(Operand, true);   // Work with broken code
45620b57cec5SDimitry Andric     }
45630b57cec5SDimitry Andric     Out << " to ";
45640b57cec5SDimitry Andric     TypePrinter.print(I.getType(), Out);
45650b57cec5SDimitry Andric   } else if (isa<VAArgInst>(I)) {
45660b57cec5SDimitry Andric     if (Operand) {
45670b57cec5SDimitry Andric       Out << ' ';
45680b57cec5SDimitry Andric       writeOperand(Operand, true);   // Work with broken code
45690b57cec5SDimitry Andric     }
45700b57cec5SDimitry Andric     Out << ", ";
45710b57cec5SDimitry Andric     TypePrinter.print(I.getType(), Out);
45720b57cec5SDimitry Andric   } else if (Operand) {   // Print the normal way.
45730b57cec5SDimitry Andric     if (const auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
45740b57cec5SDimitry Andric       Out << ' ';
45750b57cec5SDimitry Andric       TypePrinter.print(GEP->getSourceElementType(), Out);
45760b57cec5SDimitry Andric       Out << ',';
45770b57cec5SDimitry Andric     } else if (const auto *LI = dyn_cast<LoadInst>(&I)) {
45780b57cec5SDimitry Andric       Out << ' ';
45790b57cec5SDimitry Andric       TypePrinter.print(LI->getType(), Out);
45800b57cec5SDimitry Andric       Out << ',';
45810b57cec5SDimitry Andric     }
45820b57cec5SDimitry Andric 
45830b57cec5SDimitry Andric     // PrintAllTypes - Instructions who have operands of all the same type
45840b57cec5SDimitry Andric     // omit the type from all but the first operand.  If the instruction has
45850b57cec5SDimitry Andric     // different type operands (for example br), then they are all printed.
45860b57cec5SDimitry Andric     bool PrintAllTypes = false;
45870b57cec5SDimitry Andric     Type *TheType = Operand->getType();
45880b57cec5SDimitry Andric 
4589bdd1243dSDimitry Andric     // Select, Store, ShuffleVector, CmpXchg and AtomicRMW always print all
4590bdd1243dSDimitry Andric     // types.
4591753f127fSDimitry Andric     if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I) ||
4592bdd1243dSDimitry Andric         isa<ReturnInst>(I) || isa<AtomicCmpXchgInst>(I) ||
4593bdd1243dSDimitry Andric         isa<AtomicRMWInst>(I)) {
45940b57cec5SDimitry Andric       PrintAllTypes = true;
45950b57cec5SDimitry Andric     } else {
45960b57cec5SDimitry Andric       for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
45970b57cec5SDimitry Andric         Operand = I.getOperand(i);
45980b57cec5SDimitry Andric         // note that Operand shouldn't be null, but the test helps make dump()
45990b57cec5SDimitry Andric         // more tolerant of malformed IR
46000b57cec5SDimitry Andric         if (Operand && Operand->getType() != TheType) {
46010b57cec5SDimitry Andric           PrintAllTypes = true;    // We have differing types!  Print them all!
46020b57cec5SDimitry Andric           break;
46030b57cec5SDimitry Andric         }
46040b57cec5SDimitry Andric       }
46050b57cec5SDimitry Andric     }
46060b57cec5SDimitry Andric 
46070b57cec5SDimitry Andric     if (!PrintAllTypes) {
46080b57cec5SDimitry Andric       Out << ' ';
46090b57cec5SDimitry Andric       TypePrinter.print(TheType, Out);
46100b57cec5SDimitry Andric     }
46110b57cec5SDimitry Andric 
46120b57cec5SDimitry Andric     Out << ' ';
46130b57cec5SDimitry Andric     for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
46140b57cec5SDimitry Andric       if (i) Out << ", ";
46150b57cec5SDimitry Andric       writeOperand(I.getOperand(i), PrintAllTypes);
46160b57cec5SDimitry Andric     }
46170b57cec5SDimitry Andric   }
46180b57cec5SDimitry Andric 
46190b57cec5SDimitry Andric   // Print atomic ordering/alignment for memory operations
46200b57cec5SDimitry Andric   if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
46210b57cec5SDimitry Andric     if (LI->isAtomic())
46220b57cec5SDimitry Andric       writeAtomic(LI->getContext(), LI->getOrdering(), LI->getSyncScopeID());
46230eae32dcSDimitry Andric     if (MaybeAlign A = LI->getAlign())
46240eae32dcSDimitry Andric       Out << ", align " << A->value();
46250b57cec5SDimitry Andric   } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
46260b57cec5SDimitry Andric     if (SI->isAtomic())
46270b57cec5SDimitry Andric       writeAtomic(SI->getContext(), SI->getOrdering(), SI->getSyncScopeID());
46280eae32dcSDimitry Andric     if (MaybeAlign A = SI->getAlign())
46290eae32dcSDimitry Andric       Out << ", align " << A->value();
46300b57cec5SDimitry Andric   } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
46310b57cec5SDimitry Andric     writeAtomicCmpXchg(CXI->getContext(), CXI->getSuccessOrdering(),
46320b57cec5SDimitry Andric                        CXI->getFailureOrdering(), CXI->getSyncScopeID());
4633fe6060f1SDimitry Andric     Out << ", align " << CXI->getAlign().value();
46340b57cec5SDimitry Andric   } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
46350b57cec5SDimitry Andric     writeAtomic(RMWI->getContext(), RMWI->getOrdering(),
46360b57cec5SDimitry Andric                 RMWI->getSyncScopeID());
4637fe6060f1SDimitry Andric     Out << ", align " << RMWI->getAlign().value();
46380b57cec5SDimitry Andric   } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
46390b57cec5SDimitry Andric     writeAtomic(FI->getContext(), FI->getOrdering(), FI->getSyncScopeID());
46405ffd83dbSDimitry Andric   } else if (const ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(&I)) {
46415ffd83dbSDimitry Andric     PrintShuffleMask(Out, SVI->getType(), SVI->getShuffleMask());
46420b57cec5SDimitry Andric   }
46430b57cec5SDimitry Andric 
46440b57cec5SDimitry Andric   // Print Metadata info.
46450b57cec5SDimitry Andric   SmallVector<std::pair<unsigned, MDNode *>, 4> InstMD;
46460b57cec5SDimitry Andric   I.getAllMetadata(InstMD);
46470b57cec5SDimitry Andric   printMetadataAttachments(InstMD, ", ");
46480b57cec5SDimitry Andric 
46490b57cec5SDimitry Andric   // Print a nice comment.
46500b57cec5SDimitry Andric   printInfoComment(I);
46510b57cec5SDimitry Andric }
46520b57cec5SDimitry Andric 
printDbgMarker(const DbgMarker & Marker)4653*0fca6ea1SDimitry Andric void AssemblyWriter::printDbgMarker(const DbgMarker &Marker) {
4654*0fca6ea1SDimitry Andric   // There's no formal representation of a DbgMarker -- print purely as a
46555f757f3fSDimitry Andric   // debugging aid.
4656*0fca6ea1SDimitry Andric   for (const DbgRecord &DPR : Marker.StoredDbgRecords) {
4657*0fca6ea1SDimitry Andric     printDbgRecord(DPR);
46585f757f3fSDimitry Andric     Out << "\n";
46595f757f3fSDimitry Andric   }
46605f757f3fSDimitry Andric 
4661*0fca6ea1SDimitry Andric   Out << "  DbgMarker -> { ";
46625f757f3fSDimitry Andric   printInstruction(*Marker.MarkedInstr);
46635f757f3fSDimitry Andric   Out << " }";
46645f757f3fSDimitry Andric   return;
46655f757f3fSDimitry Andric }
46665f757f3fSDimitry Andric 
printDbgRecord(const DbgRecord & DR)4667*0fca6ea1SDimitry Andric void AssemblyWriter::printDbgRecord(const DbgRecord &DR) {
4668*0fca6ea1SDimitry Andric   if (auto *DVR = dyn_cast<DbgVariableRecord>(&DR))
4669*0fca6ea1SDimitry Andric     printDbgVariableRecord(*DVR);
4670*0fca6ea1SDimitry Andric   else if (auto *DLR = dyn_cast<DbgLabelRecord>(&DR))
4671*0fca6ea1SDimitry Andric     printDbgLabelRecord(*DLR);
4672*0fca6ea1SDimitry Andric   else
4673*0fca6ea1SDimitry Andric     llvm_unreachable("Unexpected DbgRecord kind");
4674*0fca6ea1SDimitry Andric }
46757a6dacacSDimitry Andric 
printDbgVariableRecord(const DbgVariableRecord & DVR)4676*0fca6ea1SDimitry Andric void AssemblyWriter::printDbgVariableRecord(const DbgVariableRecord &DVR) {
4677*0fca6ea1SDimitry Andric   auto WriterCtx = getContext();
4678*0fca6ea1SDimitry Andric   Out << "#dbg_";
4679*0fca6ea1SDimitry Andric   switch (DVR.getType()) {
4680*0fca6ea1SDimitry Andric   case DbgVariableRecord::LocationType::Value:
46817a6dacacSDimitry Andric     Out << "value";
46827a6dacacSDimitry Andric     break;
4683*0fca6ea1SDimitry Andric   case DbgVariableRecord::LocationType::Declare:
46847a6dacacSDimitry Andric     Out << "declare";
46857a6dacacSDimitry Andric     break;
4686*0fca6ea1SDimitry Andric   case DbgVariableRecord::LocationType::Assign:
46877a6dacacSDimitry Andric     Out << "assign";
46887a6dacacSDimitry Andric     break;
46897a6dacacSDimitry Andric   default:
4690*0fca6ea1SDimitry Andric     llvm_unreachable(
4691*0fca6ea1SDimitry Andric         "Tried to print a DbgVariableRecord with an invalid LocationType!");
46927a6dacacSDimitry Andric   }
4693*0fca6ea1SDimitry Andric   Out << "(";
4694*0fca6ea1SDimitry Andric   WriteAsOperandInternal(Out, DVR.getRawLocation(), WriterCtx, true);
4695*0fca6ea1SDimitry Andric   Out << ", ";
4696*0fca6ea1SDimitry Andric   WriteAsOperandInternal(Out, DVR.getRawVariable(), WriterCtx, true);
4697*0fca6ea1SDimitry Andric   Out << ", ";
4698*0fca6ea1SDimitry Andric   WriteAsOperandInternal(Out, DVR.getRawExpression(), WriterCtx, true);
4699*0fca6ea1SDimitry Andric   Out << ", ";
4700*0fca6ea1SDimitry Andric   if (DVR.isDbgAssign()) {
4701*0fca6ea1SDimitry Andric     WriteAsOperandInternal(Out, DVR.getRawAssignID(), WriterCtx, true);
4702*0fca6ea1SDimitry Andric     Out << ", ";
4703*0fca6ea1SDimitry Andric     WriteAsOperandInternal(Out, DVR.getRawAddress(), WriterCtx, true);
4704*0fca6ea1SDimitry Andric     Out << ", ";
4705*0fca6ea1SDimitry Andric     WriteAsOperandInternal(Out, DVR.getRawAddressExpression(), WriterCtx, true);
4706*0fca6ea1SDimitry Andric     Out << ", ";
4707*0fca6ea1SDimitry Andric   }
4708*0fca6ea1SDimitry Andric   WriteAsOperandInternal(Out, DVR.getDebugLoc().getAsMDNode(), WriterCtx, true);
4709*0fca6ea1SDimitry Andric   Out << ")";
4710*0fca6ea1SDimitry Andric }
4711*0fca6ea1SDimitry Andric 
4712*0fca6ea1SDimitry Andric /// printDbgRecordLine - Print a DbgRecord with indentation and a newline
4713*0fca6ea1SDimitry Andric /// character.
printDbgRecordLine(const DbgRecord & DR)4714*0fca6ea1SDimitry Andric void AssemblyWriter::printDbgRecordLine(const DbgRecord &DR) {
4715*0fca6ea1SDimitry Andric   // Print lengthier indentation to bring out-of-line with instructions.
4716*0fca6ea1SDimitry Andric   Out << "    ";
4717*0fca6ea1SDimitry Andric   printDbgRecord(DR);
4718*0fca6ea1SDimitry Andric   Out << '\n';
4719*0fca6ea1SDimitry Andric }
4720*0fca6ea1SDimitry Andric 
printDbgLabelRecord(const DbgLabelRecord & Label)4721*0fca6ea1SDimitry Andric void AssemblyWriter::printDbgLabelRecord(const DbgLabelRecord &Label) {
47225f757f3fSDimitry Andric   auto WriterCtx = getContext();
4723*0fca6ea1SDimitry Andric   Out << "#dbg_label(";
4724*0fca6ea1SDimitry Andric   WriteAsOperandInternal(Out, Label.getRawLabel(), WriterCtx, true);
47255f757f3fSDimitry Andric   Out << ", ";
4726*0fca6ea1SDimitry Andric   WriteAsOperandInternal(Out, Label.getDebugLoc(), WriterCtx, true);
4727*0fca6ea1SDimitry Andric   Out << ")";
47285f757f3fSDimitry Andric }
47295f757f3fSDimitry Andric 
printMetadataAttachments(const SmallVectorImpl<std::pair<unsigned,MDNode * >> & MDs,StringRef Separator)47300b57cec5SDimitry Andric void AssemblyWriter::printMetadataAttachments(
47310b57cec5SDimitry Andric     const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
47320b57cec5SDimitry Andric     StringRef Separator) {
47330b57cec5SDimitry Andric   if (MDs.empty())
47340b57cec5SDimitry Andric     return;
47350b57cec5SDimitry Andric 
47360b57cec5SDimitry Andric   if (MDNames.empty())
47370b57cec5SDimitry Andric     MDs[0].second->getContext().getMDKindNames(MDNames);
47380b57cec5SDimitry Andric 
4739349cc55cSDimitry Andric   auto WriterCtx = getContext();
47400b57cec5SDimitry Andric   for (const auto &I : MDs) {
47410b57cec5SDimitry Andric     unsigned Kind = I.first;
47420b57cec5SDimitry Andric     Out << Separator;
47430b57cec5SDimitry Andric     if (Kind < MDNames.size()) {
47440b57cec5SDimitry Andric       Out << "!";
47450b57cec5SDimitry Andric       printMetadataIdentifier(MDNames[Kind], Out);
47460b57cec5SDimitry Andric     } else
47470b57cec5SDimitry Andric       Out << "!<unknown kind #" << Kind << ">";
47480b57cec5SDimitry Andric     Out << ' ';
4749349cc55cSDimitry Andric     WriteAsOperandInternal(Out, I.second, WriterCtx);
47500b57cec5SDimitry Andric   }
47510b57cec5SDimitry Andric }
47520b57cec5SDimitry Andric 
writeMDNode(unsigned Slot,const MDNode * Node)47530b57cec5SDimitry Andric void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) {
47540b57cec5SDimitry Andric   Out << '!' << Slot << " = ";
47550b57cec5SDimitry Andric   printMDNodeBody(Node);
47560b57cec5SDimitry Andric   Out << "\n";
47570b57cec5SDimitry Andric }
47580b57cec5SDimitry Andric 
writeAllMDNodes()47590b57cec5SDimitry Andric void AssemblyWriter::writeAllMDNodes() {
47600b57cec5SDimitry Andric   SmallVector<const MDNode *, 16> Nodes;
47610b57cec5SDimitry Andric   Nodes.resize(Machine.mdn_size());
4762fe6060f1SDimitry Andric   for (auto &I : llvm::make_range(Machine.mdn_begin(), Machine.mdn_end()))
4763fe6060f1SDimitry Andric     Nodes[I.second] = cast<MDNode>(I.first);
47640b57cec5SDimitry Andric 
47650b57cec5SDimitry Andric   for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
47660b57cec5SDimitry Andric     writeMDNode(i, Nodes[i]);
47670b57cec5SDimitry Andric   }
47680b57cec5SDimitry Andric }
47690b57cec5SDimitry Andric 
printMDNodeBody(const MDNode * Node)47700b57cec5SDimitry Andric void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
4771349cc55cSDimitry Andric   auto WriterCtx = getContext();
4772349cc55cSDimitry Andric   WriteMDNodeBodyInternal(Out, Node, WriterCtx);
47730b57cec5SDimitry Andric }
47740b57cec5SDimitry Andric 
writeAttribute(const Attribute & Attr,bool InAttrGroup)4775480093f4SDimitry Andric void AssemblyWriter::writeAttribute(const Attribute &Attr, bool InAttrGroup) {
4776480093f4SDimitry Andric   if (!Attr.isTypeAttribute()) {
4777480093f4SDimitry Andric     Out << Attr.getAsString(InAttrGroup);
4778480093f4SDimitry Andric     return;
4779480093f4SDimitry Andric   }
4780480093f4SDimitry Andric 
4781fe6060f1SDimitry Andric   Out << Attribute::getNameFromAttrKind(Attr.getKindAsEnum());
4782480093f4SDimitry Andric   if (Type *Ty = Attr.getValueAsType()) {
4783480093f4SDimitry Andric     Out << '(';
4784480093f4SDimitry Andric     TypePrinter.print(Ty, Out);
4785480093f4SDimitry Andric     Out << ')';
4786480093f4SDimitry Andric   }
4787480093f4SDimitry Andric }
4788480093f4SDimitry Andric 
writeAttributeSet(const AttributeSet & AttrSet,bool InAttrGroup)4789480093f4SDimitry Andric void AssemblyWriter::writeAttributeSet(const AttributeSet &AttrSet,
4790480093f4SDimitry Andric                                        bool InAttrGroup) {
4791480093f4SDimitry Andric   bool FirstAttr = true;
4792480093f4SDimitry Andric   for (const auto &Attr : AttrSet) {
4793480093f4SDimitry Andric     if (!FirstAttr)
4794480093f4SDimitry Andric       Out << ' ';
4795480093f4SDimitry Andric     writeAttribute(Attr, InAttrGroup);
4796480093f4SDimitry Andric     FirstAttr = false;
4797480093f4SDimitry Andric   }
4798480093f4SDimitry Andric }
4799480093f4SDimitry Andric 
writeAllAttributeGroups()48000b57cec5SDimitry Andric void AssemblyWriter::writeAllAttributeGroups() {
48010b57cec5SDimitry Andric   std::vector<std::pair<AttributeSet, unsigned>> asVec;
48020b57cec5SDimitry Andric   asVec.resize(Machine.as_size());
48030b57cec5SDimitry Andric 
4804fe6060f1SDimitry Andric   for (auto &I : llvm::make_range(Machine.as_begin(), Machine.as_end()))
4805fe6060f1SDimitry Andric     asVec[I.second] = I;
48060b57cec5SDimitry Andric 
48070b57cec5SDimitry Andric   for (const auto &I : asVec)
48080b57cec5SDimitry Andric     Out << "attributes #" << I.second << " = { "
48090b57cec5SDimitry Andric         << I.first.getAsString(true) << " }\n";
48100b57cec5SDimitry Andric }
48110b57cec5SDimitry Andric 
printUseListOrder(const Value * V,const std::vector<unsigned> & Shuffle)4812fe6060f1SDimitry Andric void AssemblyWriter::printUseListOrder(const Value *V,
4813fe6060f1SDimitry Andric                                        const std::vector<unsigned> &Shuffle) {
48140b57cec5SDimitry Andric   bool IsInFunction = Machine.getFunction();
48150b57cec5SDimitry Andric   if (IsInFunction)
48160b57cec5SDimitry Andric     Out << "  ";
48170b57cec5SDimitry Andric 
48180b57cec5SDimitry Andric   Out << "uselistorder";
4819fe6060f1SDimitry Andric   if (const BasicBlock *BB = IsInFunction ? nullptr : dyn_cast<BasicBlock>(V)) {
48200b57cec5SDimitry Andric     Out << "_bb ";
48210b57cec5SDimitry Andric     writeOperand(BB->getParent(), false);
48220b57cec5SDimitry Andric     Out << ", ";
48230b57cec5SDimitry Andric     writeOperand(BB, false);
48240b57cec5SDimitry Andric   } else {
48250b57cec5SDimitry Andric     Out << " ";
4826fe6060f1SDimitry Andric     writeOperand(V, true);
48270b57cec5SDimitry Andric   }
48280b57cec5SDimitry Andric   Out << ", { ";
48290b57cec5SDimitry Andric 
4830fe6060f1SDimitry Andric   assert(Shuffle.size() >= 2 && "Shuffle too small");
4831fe6060f1SDimitry Andric   Out << Shuffle[0];
4832fe6060f1SDimitry Andric   for (unsigned I = 1, E = Shuffle.size(); I != E; ++I)
4833fe6060f1SDimitry Andric     Out << ", " << Shuffle[I];
48340b57cec5SDimitry Andric   Out << " }\n";
48350b57cec5SDimitry Andric }
48360b57cec5SDimitry Andric 
printUseLists(const Function * F)48370b57cec5SDimitry Andric void AssemblyWriter::printUseLists(const Function *F) {
4838fe6060f1SDimitry Andric   auto It = UseListOrders.find(F);
4839fe6060f1SDimitry Andric   if (It == UseListOrders.end())
48400b57cec5SDimitry Andric     return;
48410b57cec5SDimitry Andric 
48420b57cec5SDimitry Andric   Out << "\n; uselistorder directives\n";
4843fe6060f1SDimitry Andric   for (const auto &Pair : It->second)
4844fe6060f1SDimitry Andric     printUseListOrder(Pair.first, Pair.second);
48450b57cec5SDimitry Andric }
48460b57cec5SDimitry Andric 
48470b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
48480b57cec5SDimitry Andric //                       External Interface declarations
48490b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
48500b57cec5SDimitry Andric 
print(raw_ostream & ROS,AssemblyAnnotationWriter * AAW,bool ShouldPreserveUseListOrder,bool IsForDebug) const48510b57cec5SDimitry Andric void Function::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
48520b57cec5SDimitry Andric                      bool ShouldPreserveUseListOrder,
48530b57cec5SDimitry Andric                      bool IsForDebug) const {
48540b57cec5SDimitry Andric   SlotTracker SlotTable(this->getParent());
48550b57cec5SDimitry Andric   formatted_raw_ostream OS(ROS);
48560b57cec5SDimitry Andric   AssemblyWriter W(OS, SlotTable, this->getParent(), AAW,
48570b57cec5SDimitry Andric                    IsForDebug,
48580b57cec5SDimitry Andric                    ShouldPreserveUseListOrder);
48590b57cec5SDimitry Andric   W.printFunction(this);
48600b57cec5SDimitry Andric }
48610b57cec5SDimitry Andric 
print(raw_ostream & ROS,AssemblyAnnotationWriter * AAW,bool ShouldPreserveUseListOrder,bool IsForDebug) const48625ffd83dbSDimitry Andric void BasicBlock::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
48635ffd83dbSDimitry Andric                      bool ShouldPreserveUseListOrder,
48645ffd83dbSDimitry Andric                      bool IsForDebug) const {
4865e8d8bef9SDimitry Andric   SlotTracker SlotTable(this->getParent());
48665ffd83dbSDimitry Andric   formatted_raw_ostream OS(ROS);
48675ffd83dbSDimitry Andric   AssemblyWriter W(OS, SlotTable, this->getModule(), AAW,
48685ffd83dbSDimitry Andric                    IsForDebug,
48695ffd83dbSDimitry Andric                    ShouldPreserveUseListOrder);
48705ffd83dbSDimitry Andric   W.printBasicBlock(this);
48715ffd83dbSDimitry Andric }
48725ffd83dbSDimitry Andric 
print(raw_ostream & ROS,AssemblyAnnotationWriter * AAW,bool ShouldPreserveUseListOrder,bool IsForDebug) const48730b57cec5SDimitry Andric void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
48740b57cec5SDimitry Andric                    bool ShouldPreserveUseListOrder, bool IsForDebug) const {
48750b57cec5SDimitry Andric   SlotTracker SlotTable(this);
48760b57cec5SDimitry Andric   formatted_raw_ostream OS(ROS);
48770b57cec5SDimitry Andric   AssemblyWriter W(OS, SlotTable, this, AAW, IsForDebug,
48780b57cec5SDimitry Andric                    ShouldPreserveUseListOrder);
48790b57cec5SDimitry Andric   W.printModule(this);
48800b57cec5SDimitry Andric }
48810b57cec5SDimitry Andric 
print(raw_ostream & ROS,bool IsForDebug) const48820b57cec5SDimitry Andric void NamedMDNode::print(raw_ostream &ROS, bool IsForDebug) const {
48830b57cec5SDimitry Andric   SlotTracker SlotTable(getParent());
48840b57cec5SDimitry Andric   formatted_raw_ostream OS(ROS);
48850b57cec5SDimitry Andric   AssemblyWriter W(OS, SlotTable, getParent(), nullptr, IsForDebug);
48860b57cec5SDimitry Andric   W.printNamedMDNode(this);
48870b57cec5SDimitry Andric }
48880b57cec5SDimitry Andric 
print(raw_ostream & ROS,ModuleSlotTracker & MST,bool IsForDebug) const48890b57cec5SDimitry Andric void NamedMDNode::print(raw_ostream &ROS, ModuleSlotTracker &MST,
48900b57cec5SDimitry Andric                         bool IsForDebug) const {
4891bdd1243dSDimitry Andric   std::optional<SlotTracker> LocalST;
48920b57cec5SDimitry Andric   SlotTracker *SlotTable;
48930b57cec5SDimitry Andric   if (auto *ST = MST.getMachine())
48940b57cec5SDimitry Andric     SlotTable = ST;
48950b57cec5SDimitry Andric   else {
48960b57cec5SDimitry Andric     LocalST.emplace(getParent());
48970b57cec5SDimitry Andric     SlotTable = &*LocalST;
48980b57cec5SDimitry Andric   }
48990b57cec5SDimitry Andric 
49000b57cec5SDimitry Andric   formatted_raw_ostream OS(ROS);
49010b57cec5SDimitry Andric   AssemblyWriter W(OS, *SlotTable, getParent(), nullptr, IsForDebug);
49020b57cec5SDimitry Andric   W.printNamedMDNode(this);
49030b57cec5SDimitry Andric }
49040b57cec5SDimitry Andric 
print(raw_ostream & ROS,bool) const49050b57cec5SDimitry Andric void Comdat::print(raw_ostream &ROS, bool /*IsForDebug*/) const {
49060b57cec5SDimitry Andric   PrintLLVMName(ROS, getName(), ComdatPrefix);
49070b57cec5SDimitry Andric   ROS << " = comdat ";
49080b57cec5SDimitry Andric 
49090b57cec5SDimitry Andric   switch (getSelectionKind()) {
49100b57cec5SDimitry Andric   case Comdat::Any:
49110b57cec5SDimitry Andric     ROS << "any";
49120b57cec5SDimitry Andric     break;
49130b57cec5SDimitry Andric   case Comdat::ExactMatch:
49140b57cec5SDimitry Andric     ROS << "exactmatch";
49150b57cec5SDimitry Andric     break;
49160b57cec5SDimitry Andric   case Comdat::Largest:
49170b57cec5SDimitry Andric     ROS << "largest";
49180b57cec5SDimitry Andric     break;
4919fe6060f1SDimitry Andric   case Comdat::NoDeduplicate:
4920fe6060f1SDimitry Andric     ROS << "nodeduplicate";
49210b57cec5SDimitry Andric     break;
49220b57cec5SDimitry Andric   case Comdat::SameSize:
49230b57cec5SDimitry Andric     ROS << "samesize";
49240b57cec5SDimitry Andric     break;
49250b57cec5SDimitry Andric   }
49260b57cec5SDimitry Andric 
49270b57cec5SDimitry Andric   ROS << '\n';
49280b57cec5SDimitry Andric }
49290b57cec5SDimitry Andric 
print(raw_ostream & OS,bool,bool NoDetails) const49300b57cec5SDimitry Andric void Type::print(raw_ostream &OS, bool /*IsForDebug*/, bool NoDetails) const {
49310b57cec5SDimitry Andric   TypePrinting TP;
49320b57cec5SDimitry Andric   TP.print(const_cast<Type*>(this), OS);
49330b57cec5SDimitry Andric 
49340b57cec5SDimitry Andric   if (NoDetails)
49350b57cec5SDimitry Andric     return;
49360b57cec5SDimitry Andric 
49370b57cec5SDimitry Andric   // If the type is a named struct type, print the body as well.
49380b57cec5SDimitry Andric   if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
49390b57cec5SDimitry Andric     if (!STy->isLiteral()) {
49400b57cec5SDimitry Andric       OS << " = type ";
49410b57cec5SDimitry Andric       TP.printStructBody(STy, OS);
49420b57cec5SDimitry Andric     }
49430b57cec5SDimitry Andric }
49440b57cec5SDimitry Andric 
isReferencingMDNode(const Instruction & I)49450b57cec5SDimitry Andric static bool isReferencingMDNode(const Instruction &I) {
49460b57cec5SDimitry Andric   if (const auto *CI = dyn_cast<CallInst>(&I))
49470b57cec5SDimitry Andric     if (Function *F = CI->getCalledFunction())
49480b57cec5SDimitry Andric       if (F->isIntrinsic())
49490b57cec5SDimitry Andric         for (auto &Op : I.operands())
49500b57cec5SDimitry Andric           if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
49510b57cec5SDimitry Andric             if (isa<MDNode>(V->getMetadata()))
49520b57cec5SDimitry Andric               return true;
49530b57cec5SDimitry Andric   return false;
49540b57cec5SDimitry Andric }
49550b57cec5SDimitry Andric 
print(raw_ostream & ROS,bool IsForDebug) const4956*0fca6ea1SDimitry Andric void DbgMarker::print(raw_ostream &ROS, bool IsForDebug) const {
49575f757f3fSDimitry Andric 
49585f757f3fSDimitry Andric   ModuleSlotTracker MST(getModuleFromDPI(this), true);
49595f757f3fSDimitry Andric   print(ROS, MST, IsForDebug);
49605f757f3fSDimitry Andric }
49615f757f3fSDimitry Andric 
print(raw_ostream & ROS,bool IsForDebug) const4962*0fca6ea1SDimitry Andric void DbgVariableRecord::print(raw_ostream &ROS, bool IsForDebug) const {
49635f757f3fSDimitry Andric 
49645f757f3fSDimitry Andric   ModuleSlotTracker MST(getModuleFromDPI(this), true);
49655f757f3fSDimitry Andric   print(ROS, MST, IsForDebug);
49665f757f3fSDimitry Andric }
49675f757f3fSDimitry Andric 
print(raw_ostream & ROS,ModuleSlotTracker & MST,bool IsForDebug) const4968*0fca6ea1SDimitry Andric void DbgMarker::print(raw_ostream &ROS, ModuleSlotTracker &MST,
49695f757f3fSDimitry Andric                       bool IsForDebug) const {
49705f757f3fSDimitry Andric   formatted_raw_ostream OS(ROS);
49715f757f3fSDimitry Andric   SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));
49725f757f3fSDimitry Andric   SlotTracker &SlotTable =
49735f757f3fSDimitry Andric       MST.getMachine() ? *MST.getMachine() : EmptySlotTable;
49745f757f3fSDimitry Andric   auto incorporateFunction = [&](const Function *F) {
49755f757f3fSDimitry Andric     if (F)
49765f757f3fSDimitry Andric       MST.incorporateFunction(*F);
49775f757f3fSDimitry Andric   };
49785f757f3fSDimitry Andric   incorporateFunction(getParent() ? getParent()->getParent() : nullptr);
49795f757f3fSDimitry Andric   AssemblyWriter W(OS, SlotTable, getModuleFromDPI(this), nullptr, IsForDebug);
4980*0fca6ea1SDimitry Andric   W.printDbgMarker(*this);
49815f757f3fSDimitry Andric }
49825f757f3fSDimitry Andric 
print(raw_ostream & ROS,bool IsForDebug) const4983*0fca6ea1SDimitry Andric void DbgLabelRecord::print(raw_ostream &ROS, bool IsForDebug) const {
4984*0fca6ea1SDimitry Andric 
4985*0fca6ea1SDimitry Andric   ModuleSlotTracker MST(getModuleFromDPI(this), true);
4986*0fca6ea1SDimitry Andric   print(ROS, MST, IsForDebug);
4987*0fca6ea1SDimitry Andric }
4988*0fca6ea1SDimitry Andric 
print(raw_ostream & ROS,ModuleSlotTracker & MST,bool IsForDebug) const4989*0fca6ea1SDimitry Andric void DbgVariableRecord::print(raw_ostream &ROS, ModuleSlotTracker &MST,
49905f757f3fSDimitry Andric                               bool IsForDebug) const {
4991*0fca6ea1SDimitry Andric   formatted_raw_ostream OS(ROS);
4992*0fca6ea1SDimitry Andric   SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));
4993*0fca6ea1SDimitry Andric   SlotTracker &SlotTable =
4994*0fca6ea1SDimitry Andric       MST.getMachine() ? *MST.getMachine() : EmptySlotTable;
4995*0fca6ea1SDimitry Andric   auto incorporateFunction = [&](const Function *F) {
4996*0fca6ea1SDimitry Andric     if (F)
4997*0fca6ea1SDimitry Andric       MST.incorporateFunction(*F);
4998*0fca6ea1SDimitry Andric   };
4999*0fca6ea1SDimitry Andric   incorporateFunction(Marker && Marker->getParent()
5000*0fca6ea1SDimitry Andric                           ? Marker->getParent()->getParent()
5001*0fca6ea1SDimitry Andric                           : nullptr);
5002*0fca6ea1SDimitry Andric   AssemblyWriter W(OS, SlotTable, getModuleFromDPI(this), nullptr, IsForDebug);
5003*0fca6ea1SDimitry Andric   W.printDbgVariableRecord(*this);
5004*0fca6ea1SDimitry Andric }
5005*0fca6ea1SDimitry Andric 
print(raw_ostream & ROS,ModuleSlotTracker & MST,bool IsForDebug) const5006*0fca6ea1SDimitry Andric void DbgLabelRecord::print(raw_ostream &ROS, ModuleSlotTracker &MST,
5007*0fca6ea1SDimitry Andric                            bool IsForDebug) const {
50085f757f3fSDimitry Andric   formatted_raw_ostream OS(ROS);
50095f757f3fSDimitry Andric   SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));
50105f757f3fSDimitry Andric   SlotTracker &SlotTable =
50115f757f3fSDimitry Andric       MST.getMachine() ? *MST.getMachine() : EmptySlotTable;
50125f757f3fSDimitry Andric   auto incorporateFunction = [&](const Function *F) {
50135f757f3fSDimitry Andric     if (F)
50145f757f3fSDimitry Andric       MST.incorporateFunction(*F);
50155f757f3fSDimitry Andric   };
50165f757f3fSDimitry Andric   incorporateFunction(Marker->getParent() ? Marker->getParent()->getParent()
50175f757f3fSDimitry Andric                                           : nullptr);
50185f757f3fSDimitry Andric   AssemblyWriter W(OS, SlotTable, getModuleFromDPI(this), nullptr, IsForDebug);
5019*0fca6ea1SDimitry Andric   W.printDbgLabelRecord(*this);
50205f757f3fSDimitry Andric }
50215f757f3fSDimitry Andric 
print(raw_ostream & ROS,bool IsForDebug) const50220b57cec5SDimitry Andric void Value::print(raw_ostream &ROS, bool IsForDebug) const {
50230b57cec5SDimitry Andric   bool ShouldInitializeAllMetadata = false;
50240b57cec5SDimitry Andric   if (auto *I = dyn_cast<Instruction>(this))
50250b57cec5SDimitry Andric     ShouldInitializeAllMetadata = isReferencingMDNode(*I);
50260b57cec5SDimitry Andric   else if (isa<Function>(this) || isa<MetadataAsValue>(this))
50270b57cec5SDimitry Andric     ShouldInitializeAllMetadata = true;
50280b57cec5SDimitry Andric 
50290b57cec5SDimitry Andric   ModuleSlotTracker MST(getModuleFromVal(this), ShouldInitializeAllMetadata);
50300b57cec5SDimitry Andric   print(ROS, MST, IsForDebug);
50310b57cec5SDimitry Andric }
50320b57cec5SDimitry Andric 
print(raw_ostream & ROS,ModuleSlotTracker & MST,bool IsForDebug) const50330b57cec5SDimitry Andric void Value::print(raw_ostream &ROS, ModuleSlotTracker &MST,
50340b57cec5SDimitry Andric                   bool IsForDebug) const {
50350b57cec5SDimitry Andric   formatted_raw_ostream OS(ROS);
50360b57cec5SDimitry Andric   SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));
50370b57cec5SDimitry Andric   SlotTracker &SlotTable =
50380b57cec5SDimitry Andric       MST.getMachine() ? *MST.getMachine() : EmptySlotTable;
50390b57cec5SDimitry Andric   auto incorporateFunction = [&](const Function *F) {
50400b57cec5SDimitry Andric     if (F)
50410b57cec5SDimitry Andric       MST.incorporateFunction(*F);
50420b57cec5SDimitry Andric   };
50430b57cec5SDimitry Andric 
50440b57cec5SDimitry Andric   if (const Instruction *I = dyn_cast<Instruction>(this)) {
50450b57cec5SDimitry Andric     incorporateFunction(I->getParent() ? I->getParent()->getParent() : nullptr);
50460b57cec5SDimitry Andric     AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr, IsForDebug);
50470b57cec5SDimitry Andric     W.printInstruction(*I);
50480b57cec5SDimitry Andric   } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
50490b57cec5SDimitry Andric     incorporateFunction(BB->getParent());
50500b57cec5SDimitry Andric     AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr, IsForDebug);
50510b57cec5SDimitry Andric     W.printBasicBlock(BB);
50520b57cec5SDimitry Andric   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
50530b57cec5SDimitry Andric     AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr, IsForDebug);
50540b57cec5SDimitry Andric     if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
50550b57cec5SDimitry Andric       W.printGlobal(V);
50560b57cec5SDimitry Andric     else if (const Function *F = dyn_cast<Function>(GV))
50570b57cec5SDimitry Andric       W.printFunction(F);
5058349cc55cSDimitry Andric     else if (const GlobalAlias *A = dyn_cast<GlobalAlias>(GV))
5059349cc55cSDimitry Andric       W.printAlias(A);
5060349cc55cSDimitry Andric     else if (const GlobalIFunc *I = dyn_cast<GlobalIFunc>(GV))
5061349cc55cSDimitry Andric       W.printIFunc(I);
50620b57cec5SDimitry Andric     else
5063349cc55cSDimitry Andric       llvm_unreachable("Unknown GlobalValue to print out!");
50640b57cec5SDimitry Andric   } else if (const MetadataAsValue *V = dyn_cast<MetadataAsValue>(this)) {
50650b57cec5SDimitry Andric     V->getMetadata()->print(ROS, MST, getModuleFromVal(V));
50660b57cec5SDimitry Andric   } else if (const Constant *C = dyn_cast<Constant>(this)) {
50670b57cec5SDimitry Andric     TypePrinting TypePrinter;
50680b57cec5SDimitry Andric     TypePrinter.print(C->getType(), OS);
50690b57cec5SDimitry Andric     OS << ' ';
5070349cc55cSDimitry Andric     AsmWriterContext WriterCtx(&TypePrinter, MST.getMachine());
5071349cc55cSDimitry Andric     WriteConstantInternal(OS, C, WriterCtx);
50720b57cec5SDimitry Andric   } else if (isa<InlineAsm>(this) || isa<Argument>(this)) {
50730b57cec5SDimitry Andric     this->printAsOperand(OS, /* PrintType */ true, MST);
50740b57cec5SDimitry Andric   } else {
50750b57cec5SDimitry Andric     llvm_unreachable("Unknown value to print out!");
50760b57cec5SDimitry Andric   }
50770b57cec5SDimitry Andric }
50780b57cec5SDimitry Andric 
50790b57cec5SDimitry Andric /// Print without a type, skipping the TypePrinting object.
50800b57cec5SDimitry Andric ///
50810b57cec5SDimitry Andric /// \return \c true iff printing was successful.
printWithoutType(const Value & V,raw_ostream & O,SlotTracker * Machine,const Module * M)50820b57cec5SDimitry Andric static bool printWithoutType(const Value &V, raw_ostream &O,
50830b57cec5SDimitry Andric                              SlotTracker *Machine, const Module *M) {
50840b57cec5SDimitry Andric   if (V.hasName() || isa<GlobalValue>(V) ||
50850b57cec5SDimitry Andric       (!isa<Constant>(V) && !isa<MetadataAsValue>(V))) {
5086349cc55cSDimitry Andric     AsmWriterContext WriterCtx(nullptr, Machine, M);
5087349cc55cSDimitry Andric     WriteAsOperandInternal(O, &V, WriterCtx);
50880b57cec5SDimitry Andric     return true;
50890b57cec5SDimitry Andric   }
50900b57cec5SDimitry Andric   return false;
50910b57cec5SDimitry Andric }
50920b57cec5SDimitry Andric 
printAsOperandImpl(const Value & V,raw_ostream & O,bool PrintType,ModuleSlotTracker & MST)50930b57cec5SDimitry Andric static void printAsOperandImpl(const Value &V, raw_ostream &O, bool PrintType,
50940b57cec5SDimitry Andric                                ModuleSlotTracker &MST) {
50950b57cec5SDimitry Andric   TypePrinting TypePrinter(MST.getModule());
50960b57cec5SDimitry Andric   if (PrintType) {
50970b57cec5SDimitry Andric     TypePrinter.print(V.getType(), O);
50980b57cec5SDimitry Andric     O << ' ';
50990b57cec5SDimitry Andric   }
51000b57cec5SDimitry Andric 
5101349cc55cSDimitry Andric   AsmWriterContext WriterCtx(&TypePrinter, MST.getMachine(), MST.getModule());
5102349cc55cSDimitry Andric   WriteAsOperandInternal(O, &V, WriterCtx);
51030b57cec5SDimitry Andric }
51040b57cec5SDimitry Andric 
printAsOperand(raw_ostream & O,bool PrintType,const Module * M) const51050b57cec5SDimitry Andric void Value::printAsOperand(raw_ostream &O, bool PrintType,
51060b57cec5SDimitry Andric                            const Module *M) const {
51070b57cec5SDimitry Andric   if (!M)
51080b57cec5SDimitry Andric     M = getModuleFromVal(this);
51090b57cec5SDimitry Andric 
51100b57cec5SDimitry Andric   if (!PrintType)
51110b57cec5SDimitry Andric     if (printWithoutType(*this, O, nullptr, M))
51120b57cec5SDimitry Andric       return;
51130b57cec5SDimitry Andric 
51140b57cec5SDimitry Andric   SlotTracker Machine(
51150b57cec5SDimitry Andric       M, /* ShouldInitializeAllMetadata */ isa<MetadataAsValue>(this));
51160b57cec5SDimitry Andric   ModuleSlotTracker MST(Machine, M);
51170b57cec5SDimitry Andric   printAsOperandImpl(*this, O, PrintType, MST);
51180b57cec5SDimitry Andric }
51190b57cec5SDimitry Andric 
printAsOperand(raw_ostream & O,bool PrintType,ModuleSlotTracker & MST) const51200b57cec5SDimitry Andric void Value::printAsOperand(raw_ostream &O, bool PrintType,
51210b57cec5SDimitry Andric                            ModuleSlotTracker &MST) const {
51220b57cec5SDimitry Andric   if (!PrintType)
51230b57cec5SDimitry Andric     if (printWithoutType(*this, O, MST.getMachine(), MST.getModule()))
51240b57cec5SDimitry Andric       return;
51250b57cec5SDimitry Andric 
51260b57cec5SDimitry Andric   printAsOperandImpl(*this, O, PrintType, MST);
51270b57cec5SDimitry Andric }
51280b57cec5SDimitry Andric 
5129349cc55cSDimitry Andric /// Recursive version of printMetadataImpl.
printMetadataImplRec(raw_ostream & ROS,const Metadata & MD,AsmWriterContext & WriterCtx)5130349cc55cSDimitry Andric static void printMetadataImplRec(raw_ostream &ROS, const Metadata &MD,
5131349cc55cSDimitry Andric                                  AsmWriterContext &WriterCtx) {
5132349cc55cSDimitry Andric   formatted_raw_ostream OS(ROS);
5133349cc55cSDimitry Andric   WriteAsOperandInternal(OS, &MD, WriterCtx, /* FromValue */ true);
5134349cc55cSDimitry Andric 
5135349cc55cSDimitry Andric   auto *N = dyn_cast<MDNode>(&MD);
51365f757f3fSDimitry Andric   if (!N || isa<DIExpression>(MD))
5137349cc55cSDimitry Andric     return;
5138349cc55cSDimitry Andric 
5139349cc55cSDimitry Andric   OS << " = ";
5140349cc55cSDimitry Andric   WriteMDNodeBodyInternal(OS, N, WriterCtx);
5141349cc55cSDimitry Andric }
5142349cc55cSDimitry Andric 
5143349cc55cSDimitry Andric namespace {
5144349cc55cSDimitry Andric struct MDTreeAsmWriterContext : public AsmWriterContext {
5145349cc55cSDimitry Andric   unsigned Level;
5146349cc55cSDimitry Andric   // {Level, Printed string}
5147349cc55cSDimitry Andric   using EntryTy = std::pair<unsigned, std::string>;
5148349cc55cSDimitry Andric   SmallVector<EntryTy, 4> Buffer;
5149349cc55cSDimitry Andric 
5150349cc55cSDimitry Andric   // Used to break the cycle in case there is any.
5151349cc55cSDimitry Andric   SmallPtrSet<const Metadata *, 4> Visited;
5152349cc55cSDimitry Andric 
5153349cc55cSDimitry Andric   raw_ostream &MainOS;
5154349cc55cSDimitry Andric 
MDTreeAsmWriterContext__anon33b632581011::MDTreeAsmWriterContext5155349cc55cSDimitry Andric   MDTreeAsmWriterContext(TypePrinting *TP, SlotTracker *ST, const Module *M,
5156349cc55cSDimitry Andric                          raw_ostream &OS, const Metadata *InitMD)
5157349cc55cSDimitry Andric       : AsmWriterContext(TP, ST, M), Level(0U), Visited({InitMD}), MainOS(OS) {}
5158349cc55cSDimitry Andric 
onWriteMetadataAsOperand__anon33b632581011::MDTreeAsmWriterContext5159349cc55cSDimitry Andric   void onWriteMetadataAsOperand(const Metadata *MD) override {
516081ad6265SDimitry Andric     if (!Visited.insert(MD).second)
5161349cc55cSDimitry Andric       return;
5162349cc55cSDimitry Andric 
5163349cc55cSDimitry Andric     std::string Str;
5164349cc55cSDimitry Andric     raw_string_ostream SS(Str);
5165349cc55cSDimitry Andric     ++Level;
5166349cc55cSDimitry Andric     // A placeholder entry to memorize the correct
5167349cc55cSDimitry Andric     // position in buffer.
5168349cc55cSDimitry Andric     Buffer.emplace_back(std::make_pair(Level, ""));
5169349cc55cSDimitry Andric     unsigned InsertIdx = Buffer.size() - 1;
5170349cc55cSDimitry Andric 
5171349cc55cSDimitry Andric     printMetadataImplRec(SS, *MD, *this);
5172349cc55cSDimitry Andric     Buffer[InsertIdx].second = std::move(SS.str());
5173349cc55cSDimitry Andric     --Level;
5174349cc55cSDimitry Andric   }
5175349cc55cSDimitry Andric 
~MDTreeAsmWriterContext__anon33b632581011::MDTreeAsmWriterContext5176349cc55cSDimitry Andric   ~MDTreeAsmWriterContext() {
5177349cc55cSDimitry Andric     for (const auto &Entry : Buffer) {
5178349cc55cSDimitry Andric       MainOS << "\n";
5179349cc55cSDimitry Andric       unsigned NumIndent = Entry.first * 2U;
5180349cc55cSDimitry Andric       MainOS.indent(NumIndent) << Entry.second;
5181349cc55cSDimitry Andric     }
5182349cc55cSDimitry Andric   }
5183349cc55cSDimitry Andric };
5184349cc55cSDimitry Andric } // end anonymous namespace
5185349cc55cSDimitry Andric 
printMetadataImpl(raw_ostream & ROS,const Metadata & MD,ModuleSlotTracker & MST,const Module * M,bool OnlyAsOperand,bool PrintAsTree=false)51860b57cec5SDimitry Andric static void printMetadataImpl(raw_ostream &ROS, const Metadata &MD,
51870b57cec5SDimitry Andric                               ModuleSlotTracker &MST, const Module *M,
5188349cc55cSDimitry Andric                               bool OnlyAsOperand, bool PrintAsTree = false) {
51890b57cec5SDimitry Andric   formatted_raw_ostream OS(ROS);
51900b57cec5SDimitry Andric 
51910b57cec5SDimitry Andric   TypePrinting TypePrinter(M);
51920b57cec5SDimitry Andric 
5193349cc55cSDimitry Andric   std::unique_ptr<AsmWriterContext> WriterCtx;
5194349cc55cSDimitry Andric   if (PrintAsTree && !OnlyAsOperand)
5195349cc55cSDimitry Andric     WriterCtx = std::make_unique<MDTreeAsmWriterContext>(
5196349cc55cSDimitry Andric         &TypePrinter, MST.getMachine(), M, OS, &MD);
5197349cc55cSDimitry Andric   else
5198349cc55cSDimitry Andric     WriterCtx =
5199349cc55cSDimitry Andric         std::make_unique<AsmWriterContext>(&TypePrinter, MST.getMachine(), M);
5200349cc55cSDimitry Andric 
5201349cc55cSDimitry Andric   WriteAsOperandInternal(OS, &MD, *WriterCtx, /* FromValue */ true);
52020b57cec5SDimitry Andric 
52030b57cec5SDimitry Andric   auto *N = dyn_cast<MDNode>(&MD);
52045f757f3fSDimitry Andric   if (OnlyAsOperand || !N || isa<DIExpression>(MD))
52050b57cec5SDimitry Andric     return;
52060b57cec5SDimitry Andric 
52070b57cec5SDimitry Andric   OS << " = ";
5208349cc55cSDimitry Andric   WriteMDNodeBodyInternal(OS, N, *WriterCtx);
52090b57cec5SDimitry Andric }
52100b57cec5SDimitry Andric 
printAsOperand(raw_ostream & OS,const Module * M) const52110b57cec5SDimitry Andric void Metadata::printAsOperand(raw_ostream &OS, const Module *M) const {
52120b57cec5SDimitry Andric   ModuleSlotTracker MST(M, isa<MDNode>(this));
52130b57cec5SDimitry Andric   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
52140b57cec5SDimitry Andric }
52150b57cec5SDimitry Andric 
printAsOperand(raw_ostream & OS,ModuleSlotTracker & MST,const Module * M) const52160b57cec5SDimitry Andric void Metadata::printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST,
52170b57cec5SDimitry Andric                               const Module *M) const {
52180b57cec5SDimitry Andric   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
52190b57cec5SDimitry Andric }
52200b57cec5SDimitry Andric 
print(raw_ostream & OS,const Module * M,bool) const52210b57cec5SDimitry Andric void Metadata::print(raw_ostream &OS, const Module *M,
52220b57cec5SDimitry Andric                      bool /*IsForDebug*/) const {
52230b57cec5SDimitry Andric   ModuleSlotTracker MST(M, isa<MDNode>(this));
52240b57cec5SDimitry Andric   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
52250b57cec5SDimitry Andric }
52260b57cec5SDimitry Andric 
print(raw_ostream & OS,ModuleSlotTracker & MST,const Module * M,bool) const52270b57cec5SDimitry Andric void Metadata::print(raw_ostream &OS, ModuleSlotTracker &MST,
52280b57cec5SDimitry Andric                      const Module *M, bool /*IsForDebug*/) const {
52290b57cec5SDimitry Andric   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
52300b57cec5SDimitry Andric }
52310b57cec5SDimitry Andric 
printTree(raw_ostream & OS,const Module * M) const5232349cc55cSDimitry Andric void MDNode::printTree(raw_ostream &OS, const Module *M) const {
5233349cc55cSDimitry Andric   ModuleSlotTracker MST(M, true);
5234349cc55cSDimitry Andric   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false,
5235349cc55cSDimitry Andric                     /*PrintAsTree=*/true);
5236349cc55cSDimitry Andric }
5237349cc55cSDimitry Andric 
printTree(raw_ostream & OS,ModuleSlotTracker & MST,const Module * M) const5238349cc55cSDimitry Andric void MDNode::printTree(raw_ostream &OS, ModuleSlotTracker &MST,
5239349cc55cSDimitry Andric                        const Module *M) const {
5240349cc55cSDimitry Andric   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false,
5241349cc55cSDimitry Andric                     /*PrintAsTree=*/true);
5242349cc55cSDimitry Andric }
5243349cc55cSDimitry Andric 
print(raw_ostream & ROS,bool IsForDebug) const52440b57cec5SDimitry Andric void ModuleSummaryIndex::print(raw_ostream &ROS, bool IsForDebug) const {
52450b57cec5SDimitry Andric   SlotTracker SlotTable(this);
52460b57cec5SDimitry Andric   formatted_raw_ostream OS(ROS);
52470b57cec5SDimitry Andric   AssemblyWriter W(OS, SlotTable, this, IsForDebug);
52480b57cec5SDimitry Andric   W.printModuleSummaryIndex();
52490b57cec5SDimitry Andric }
52500b57cec5SDimitry Andric 
collectMDNodes(MachineMDNodeListType & L,unsigned LB,unsigned UB) const5251fe6060f1SDimitry Andric void ModuleSlotTracker::collectMDNodes(MachineMDNodeListType &L, unsigned LB,
5252fe6060f1SDimitry Andric                                        unsigned UB) const {
5253fe6060f1SDimitry Andric   SlotTracker *ST = MachineStorage.get();
5254fe6060f1SDimitry Andric   if (!ST)
5255fe6060f1SDimitry Andric     return;
5256fe6060f1SDimitry Andric 
5257fe6060f1SDimitry Andric   for (auto &I : llvm::make_range(ST->mdn_begin(), ST->mdn_end()))
5258fe6060f1SDimitry Andric     if (I.second >= LB && I.second < UB)
5259fe6060f1SDimitry Andric       L.push_back(std::make_pair(I.second, I.first));
5260fe6060f1SDimitry Andric }
5261fe6060f1SDimitry Andric 
52620b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
52630b57cec5SDimitry Andric // Value::dump - allow easy printing of Values from the debugger.
52640b57cec5SDimitry Andric LLVM_DUMP_METHOD
dump() const52650b57cec5SDimitry Andric void Value::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
52660b57cec5SDimitry Andric 
52675f757f3fSDimitry Andric // Value::dump - allow easy printing of Values from the debugger.
52685f757f3fSDimitry Andric LLVM_DUMP_METHOD
dump() const5269*0fca6ea1SDimitry Andric void DbgMarker::dump() const {
5270*0fca6ea1SDimitry Andric   print(dbgs(), /*IsForDebug=*/true);
5271*0fca6ea1SDimitry Andric   dbgs() << '\n';
5272*0fca6ea1SDimitry Andric }
52735f757f3fSDimitry Andric 
52745f757f3fSDimitry Andric // Value::dump - allow easy printing of Values from the debugger.
52755f757f3fSDimitry Andric LLVM_DUMP_METHOD
dump() const5276*0fca6ea1SDimitry Andric void DbgRecord::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
52775f757f3fSDimitry Andric 
52780b57cec5SDimitry Andric // Type::dump - allow easy printing of Types from the debugger.
52790b57cec5SDimitry Andric LLVM_DUMP_METHOD
dump() const52800b57cec5SDimitry Andric void Type::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
52810b57cec5SDimitry Andric 
52820b57cec5SDimitry Andric // Module::dump() - Allow printing of Modules from the debugger.
52830b57cec5SDimitry Andric LLVM_DUMP_METHOD
dump() const52840b57cec5SDimitry Andric void Module::dump() const {
52850b57cec5SDimitry Andric   print(dbgs(), nullptr,
52860b57cec5SDimitry Andric         /*ShouldPreserveUseListOrder=*/false, /*IsForDebug=*/true);
52870b57cec5SDimitry Andric }
52880b57cec5SDimitry Andric 
52890b57cec5SDimitry Andric // Allow printing of Comdats from the debugger.
52900b57cec5SDimitry Andric LLVM_DUMP_METHOD
dump() const52910b57cec5SDimitry Andric void Comdat::dump() const { print(dbgs(), /*IsForDebug=*/true); }
52920b57cec5SDimitry Andric 
52930b57cec5SDimitry Andric // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
52940b57cec5SDimitry Andric LLVM_DUMP_METHOD
dump() const52950b57cec5SDimitry Andric void NamedMDNode::dump() const { print(dbgs(), /*IsForDebug=*/true); }
52960b57cec5SDimitry Andric 
52970b57cec5SDimitry Andric LLVM_DUMP_METHOD
dump() const52980b57cec5SDimitry Andric void Metadata::dump() const { dump(nullptr); }
52990b57cec5SDimitry Andric 
53000b57cec5SDimitry Andric LLVM_DUMP_METHOD
dump(const Module * M) const53010b57cec5SDimitry Andric void Metadata::dump(const Module *M) const {
53020b57cec5SDimitry Andric   print(dbgs(), M, /*IsForDebug=*/true);
53030b57cec5SDimitry Andric   dbgs() << '\n';
53040b57cec5SDimitry Andric }
53050b57cec5SDimitry Andric 
5306349cc55cSDimitry Andric LLVM_DUMP_METHOD
dumpTree() const5307349cc55cSDimitry Andric void MDNode::dumpTree() const { dumpTree(nullptr); }
5308349cc55cSDimitry Andric 
5309349cc55cSDimitry Andric LLVM_DUMP_METHOD
dumpTree(const Module * M) const5310349cc55cSDimitry Andric void MDNode::dumpTree(const Module *M) const {
5311349cc55cSDimitry Andric   printTree(dbgs(), M);
5312349cc55cSDimitry Andric   dbgs() << '\n';
5313349cc55cSDimitry Andric }
5314349cc55cSDimitry Andric 
53150b57cec5SDimitry Andric // Allow printing of ModuleSummaryIndex from the debugger.
53160b57cec5SDimitry Andric LLVM_DUMP_METHOD
dump() const53170b57cec5SDimitry Andric void ModuleSummaryIndex::dump() const { print(dbgs(), /*IsForDebug=*/true); }
53180b57cec5SDimitry Andric #endif
5319