LCOV - code coverage report
Current view: top level - lib/IR - AsmWriter.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 1743 1779 98.0 %
Date: 2018-02-18 16:14:26 Functions: 136 136 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : //===- AsmWriter.cpp - Printing LLVM as an assembly file ------------------===//
       2             : //
       3             : //                     The LLVM Compiler Infrastructure
       4             : //
       5             : // This file is distributed under the University of Illinois Open Source
       6             : // License. See LICENSE.TXT for details.
       7             : //
       8             : //===----------------------------------------------------------------------===//
       9             : //
      10             : // This library implements the functionality defined in llvm/IR/Writer.h
      11             : //
      12             : // Note that these routines must be extremely tolerant of various errors in the
      13             : // LLVM code, because it can be used for debugging transformations.
      14             : //
      15             : //===----------------------------------------------------------------------===//
      16             : 
      17             : #include "llvm/ADT/APFloat.h"
      18             : #include "llvm/ADT/APInt.h"
      19             : #include "llvm/ADT/ArrayRef.h"
      20             : #include "llvm/ADT/DenseMap.h"
      21             : #include "llvm/ADT/None.h"
      22             : #include "llvm/ADT/Optional.h"
      23             : #include "llvm/ADT/STLExtras.h"
      24             : #include "llvm/ADT/SetVector.h"
      25             : #include "llvm/ADT/SmallString.h"
      26             : #include "llvm/ADT/SmallVector.h"
      27             : #include "llvm/ADT/StringExtras.h"
      28             : #include "llvm/ADT/StringRef.h"
      29             : #include "llvm/ADT/iterator_range.h"
      30             : #include "llvm/BinaryFormat/Dwarf.h"
      31             : #include "llvm/IR/Argument.h"
      32             : #include "llvm/IR/AssemblyAnnotationWriter.h"
      33             : #include "llvm/IR/Attributes.h"
      34             : #include "llvm/IR/BasicBlock.h"
      35             : #include "llvm/IR/CFG.h"
      36             : #include "llvm/IR/CallSite.h"
      37             : #include "llvm/IR/CallingConv.h"
      38             : #include "llvm/IR/Comdat.h"
      39             : #include "llvm/IR/Constant.h"
      40             : #include "llvm/IR/Constants.h"
      41             : #include "llvm/IR/DebugInfoMetadata.h"
      42             : #include "llvm/IR/DerivedTypes.h"
      43             : #include "llvm/IR/Function.h"
      44             : #include "llvm/IR/GlobalAlias.h"
      45             : #include "llvm/IR/GlobalIFunc.h"
      46             : #include "llvm/IR/GlobalIndirectSymbol.h"
      47             : #include "llvm/IR/GlobalObject.h"
      48             : #include "llvm/IR/GlobalValue.h"
      49             : #include "llvm/IR/GlobalVariable.h"
      50             : #include "llvm/IR/IRPrintingPasses.h"
      51             : #include "llvm/IR/InlineAsm.h"
      52             : #include "llvm/IR/InstrTypes.h"
      53             : #include "llvm/IR/Instruction.h"
      54             : #include "llvm/IR/Instructions.h"
      55             : #include "llvm/IR/LLVMContext.h"
      56             : #include "llvm/IR/Metadata.h"
      57             : #include "llvm/IR/Module.h"
      58             : #include "llvm/IR/ModuleSlotTracker.h"
      59             : #include "llvm/IR/Operator.h"
      60             : #include "llvm/IR/Statepoint.h"
      61             : #include "llvm/IR/Type.h"
      62             : #include "llvm/IR/TypeFinder.h"
      63             : #include "llvm/IR/Use.h"
      64             : #include "llvm/IR/UseListOrder.h"
      65             : #include "llvm/IR/User.h"
      66             : #include "llvm/IR/Value.h"
      67             : #include "llvm/Support/AtomicOrdering.h"
      68             : #include "llvm/Support/Casting.h"
      69             : #include "llvm/Support/Compiler.h"
      70             : #include "llvm/Support/Debug.h"
      71             : #include "llvm/Support/ErrorHandling.h"
      72             : #include "llvm/Support/Format.h"
      73             : #include "llvm/Support/FormattedStream.h"
      74             : #include "llvm/Support/raw_ostream.h"
      75             : #include <algorithm>
      76             : #include <cassert>
      77             : #include <cctype>
      78             : #include <cstddef>
      79             : #include <cstdint>
      80             : #include <iterator>
      81             : #include <memory>
      82             : #include <string>
      83             : #include <tuple>
      84             : #include <utility>
      85             : #include <vector>
      86             : 
      87             : using namespace llvm;
      88             : 
      89             : // Make virtual table appear in this compilation unit.
      90             : AssemblyAnnotationWriter::~AssemblyAnnotationWriter() = default;
      91             : 
      92             : //===----------------------------------------------------------------------===//
      93             : // Helper Functions
      94             : //===----------------------------------------------------------------------===//
      95             : 
      96             : namespace {
      97             : 
      98         746 : struct OrderMap {
      99             :   DenseMap<const Value *, std::pair<unsigned, bool>> IDs;
     100             : 
     101             :   unsigned size() const { return IDs.size(); }
     102       16614 :   std::pair<unsigned, bool> &operator[](const Value *V) { return IDs[V]; }
     103             : 
     104             :   std::pair<unsigned, bool> lookup(const Value *V) const {
     105       35472 :     return IDs.lookup(V);
     106             :   }
     107             : 
     108             :   void index(const Value *V) {
     109             :     // Explicitly sequence get-size and insert-value operations to avoid UB.
     110       13342 :     unsigned ID = IDs.size() + 1;
     111       13342 :     IDs[V].first = ID;
     112             :   }
     113             : };
     114             : 
     115             : } // end anonymous namespace
     116             : 
     117       14720 : static void orderValue(const Value *V, OrderMap &OM) {
     118       14720 :   if (OM.lookup(V).first)
     119             :     return;
     120             : 
     121             :   if (const Constant *C = dyn_cast<Constant>(V))
     122        5124 :     if (C->getNumOperands() && !isa<GlobalValue>(C))
     123        3632 :       for (const Value *Op : C->operands())
     124        1248 :         if (!isa<BasicBlock>(Op) && !isa<GlobalValue>(Op))
     125         928 :           orderValue(Op, OM);
     126             : 
     127             :   // Note: we cannot cache this lookup above, since inserting into the map
     128             :   // changes the map's size, and thus affects the other IDs.
     129             :   OM.index(V);
     130             : }
     131             : 
     132         746 : static OrderMap orderModule(const Module *M) {
     133             :   // This needs to match the order used by ValueEnumerator::ValueEnumerator()
     134             :   // and ValueEnumerator::incorporateFunction().
     135             :   OrderMap OM;
     136             : 
     137        1640 :   for (const GlobalVariable &G : M->globals()) {
     138         894 :     if (G.hasInitializer())
     139             :       if (!isa<GlobalValue>(G.getInitializer()))
     140         670 :         orderValue(G.getInitializer(), OM);
     141         894 :     orderValue(&G, OM);
     142             :   }
     143         890 :   for (const GlobalAlias &A : M->aliases()) {
     144             :     if (!isa<GlobalValue>(A.getAliasee()))
     145          60 :       orderValue(A.getAliasee(), OM);
     146         144 :     orderValue(&A, OM);
     147             :   }
     148         758 :   for (const GlobalIFunc &I : M->ifuncs()) {
     149             :     if (!isa<GlobalValue>(I.getResolver()))
     150           0 :       orderValue(I.getResolver(), OM);
     151          12 :     orderValue(&I, OM);
     152             :   }
     153        2808 :   for (const Function &F : *M) {
     154        4196 :     for (const Use &U : F.operands())
     155             :       if (!isa<GlobalValue>(U.get()))
     156          36 :         orderValue(U.get(), OM);
     157             : 
     158        2062 :     orderValue(&F, OM);
     159             : 
     160        2062 :     if (F.isDeclaration())
     161         338 :       continue;
     162             : 
     163        3038 :     for (const Argument &A : F.args())
     164        1314 :       orderValue(&A, OM);
     165        3696 :     for (const BasicBlock &BB : F) {
     166        1972 :       orderValue(&BB, OM);
     167        6888 :       for (const Instruction &I : BB) {
     168       23016 :         for (const Value *Op : I.operands())
     169       11488 :           if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) ||
     170             :               isa<InlineAsm>(*Op))
     171        1712 :             orderValue(Op, OM);
     172        4916 :         orderValue(&I, OM);
     173             :       }
     174             :     }
     175             :   }
     176         746 :   return OM;
     177             : }
     178             : 
     179        1492 : static void predictValueUseListOrderImpl(const Value *V, const Function *F,
     180             :                                          unsigned ID, const OrderMap &OM,
     181             :                                          UseListOrderStack &Stack) {
     182             :   // Predict use-list order for this one.
     183             :   using Entry = std::pair<const Use *, unsigned>;
     184             :   SmallVector<Entry, 64> List;
     185        1492 :   for (const Use &U : V->uses())
     186             :     // Check if this user will be serialized.
     187        9996 :     if (OM.lookup(U.getUser()).first)
     188        4874 :       List.push_back(std::make_pair(&U, List.size()));
     189             : 
     190        1492 :   if (List.size() < 2)
     191             :     // We may have lost some users.
     192             :     return;
     193             : 
     194             :   bool GetsReversed =
     195        1424 :       !isa<GlobalVariable>(V) && !isa<Function>(V) && !isa<BasicBlock>(V);
     196             :   if (auto *BA = dyn_cast<BlockAddress>(V))
     197          32 :     ID = OM.lookup(BA->getBasicBlock()).first;
     198        7861 :   std::sort(List.begin(), List.end(), [&](const Entry &L, const Entry &R) {
     199        7861 :     const Use *LU = L.first;
     200        7861 :     const Use *RU = R.first;
     201        7861 :     if (LU == RU)
     202             :       return false;
     203             : 
     204       15722 :     auto LID = OM.lookup(LU->getUser()).first;
     205        7861 :     auto RID = OM.lookup(RU->getUser()).first;
     206             : 
     207             :     // If ID is 4, then expect: 7 6 5 1 2 3.
     208        7861 :     if (LID < RID) {
     209        7861 :       if (GetsReversed)
     210        7297 :         if (RID <= ID)
     211             :           return true;
     212             :       return false;
     213             :     }
     214        3956 :     if (RID < LID) {
     215        3114 :       if (GetsReversed)
     216        2925 :         if (LID <= ID)
     217             :           return false;
     218             :       return true;
     219             :     }
     220             : 
     221             :     // LID and RID are equal, so we have different operands of the same user.
     222             :     // Assume operands are added in order for all instructions.
     223         842 :     if (GetsReversed)
     224         803 :       if (LID <= ID)
     225          12 :         return LU->getOperandNo() < RU->getOperandNo();
     226         830 :     return LU->getOperandNo() > RU->getOperandNo();
     227             :   });
     228             : 
     229        1424 :   if (std::is_sorted(
     230             :           List.begin(), List.end(),
     231             :           [](const Entry &L, const Entry &R) { return L.second < R.second; }))
     232             :     // Order is already correct.
     233             :     return;
     234             : 
     235             :   // Store the shuffle.
     236         836 :   Stack.emplace_back(V, F, List.size());
     237             :   assert(List.size() == Stack.back().Shuffle.size() && "Wrong size");
     238        7112 :   for (size_t I = 0, E = List.size(); I != E; ++I)
     239        3138 :     Stack.back().Shuffle[I] = List[I].second;
     240             : }
     241             : 
     242       16614 : static void predictValueUseListOrder(const Value *V, const Function *F,
     243             :                                      OrderMap &OM, UseListOrderStack &Stack) {
     244             :   auto &IDPair = OM[V];
     245             :   assert(IDPair.first && "Unmapped value");
     246       16614 :   if (IDPair.second)
     247             :     // Already predicted.
     248             :     return;
     249             : 
     250             :   // Do the actual prediction.
     251       13342 :   IDPair.second = true;
     252       18710 :   if (!V->use_empty() && std::next(V->use_begin()) != V->use_end())
     253        1492 :     predictValueUseListOrderImpl(V, F, IDPair.first, OM, Stack);
     254             : 
     255             :   // Recursive descent into constants.
     256             :   if (const Constant *C = dyn_cast<Constant>(V))
     257        5124 :     if (C->getNumOperands()) // Visit GlobalValues.
     258        7336 :       for (const Value *Op : C->operands())
     259        2186 :         if (isa<Constant>(Op)) // Visit GlobalValues.
     260        2154 :           predictValueUseListOrder(Op, F, OM, Stack);
     261             : }
     262             : 
     263         746 : static UseListOrderStack predictUseListOrder(const Module *M) {
     264         746 :   OrderMap OM = orderModule(M);
     265             : 
     266             :   // Use-list orders need to be serialized after all the users have been added
     267             :   // to a value, or else the shuffles will be incomplete.  Store them per
     268             :   // function in a stack.
     269             :   //
     270             :   // Aside from function order, the order of values doesn't matter much here.
     271             :   UseListOrderStack Stack;
     272             : 
     273             :   // We want to visit the functions backward now so we can list function-local
     274             :   // constants in the last Function they're used in.  Module-level constants
     275             :   // have already been visited above.
     276        2808 :   for (const Function &F : make_range(M->rbegin(), M->rend())) {
     277        2062 :     if (F.isDeclaration())
     278         338 :       continue;
     279        3696 :     for (const BasicBlock &BB : F)
     280        1972 :       predictValueUseListOrder(&BB, &F, OM, Stack);
     281        3038 :     for (const Argument &A : F.args())
     282        1314 :       predictValueUseListOrder(&A, &F, OM, Stack);
     283        3696 :     for (const BasicBlock &BB : F)
     284        6888 :       for (const Instruction &I : BB)
     285       23016 :         for (const Value *Op : I.operands())
     286        6592 :           if (isa<Constant>(*Op) || isa<InlineAsm>(*Op)) // Visit GlobalValues.
     287        2208 :             predictValueUseListOrder(Op, &F, OM, Stack);
     288        3696 :     for (const BasicBlock &BB : F)
     289        6888 :       for (const Instruction &I : BB)
     290        4916 :         predictValueUseListOrder(&I, &F, OM, Stack);
     291             :   }
     292             : 
     293             :   // Visit globals last.
     294        1640 :   for (const GlobalVariable &G : M->globals())
     295         894 :     predictValueUseListOrder(&G, nullptr, OM, Stack);
     296        2808 :   for (const Function &F : *M)
     297        2062 :     predictValueUseListOrder(&F, nullptr, OM, Stack);
     298         890 :   for (const GlobalAlias &A : M->aliases())
     299         144 :     predictValueUseListOrder(&A, nullptr, OM, Stack);
     300         758 :   for (const GlobalIFunc &I : M->ifuncs())
     301          12 :     predictValueUseListOrder(&I, nullptr, OM, Stack);
     302        1640 :   for (const GlobalVariable &G : M->globals())
     303         894 :     if (G.hasInitializer())
     304         746 :       predictValueUseListOrder(G.getInitializer(), nullptr, OM, Stack);
     305         890 :   for (const GlobalAlias &A : M->aliases())
     306         144 :     predictValueUseListOrder(A.getAliasee(), nullptr, OM, Stack);
     307         758 :   for (const GlobalIFunc &I : M->ifuncs())
     308          12 :     predictValueUseListOrder(I.getResolver(), nullptr, OM, Stack);
     309        2808 :   for (const Function &F : *M)
     310        4196 :     for (const Use &U : F.operands())
     311          36 :       predictValueUseListOrder(U.get(), nullptr, OM, Stack);
     312             : 
     313         746 :   return Stack;
     314             : }
     315             : 
     316       76108 : static const Module *getModuleFromVal(const Value *V) {
     317             :   if (const Argument *MA = dyn_cast<Argument>(V))
     318        4401 :     return MA->getParent() ? MA->getParent()->getParent() : nullptr;
     319             : 
     320             :   if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
     321       10216 :     return BB->getParent() ? BB->getParent()->getParent() : nullptr;
     322             : 
     323             :   if (const Instruction *I = dyn_cast<Instruction>(V)) {
     324       51536 :     const Function *M = I->getParent() ? I->getParent()->getParent() : nullptr;
     325       51460 :     return M ? M->getParent() : nullptr;
     326             :   }
     327             : 
     328             :   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
     329        1042 :     return GV->getParent();
     330             : 
     331             :   if (const auto *MAV = dyn_cast<MetadataAsValue>(V)) {
     332          10 :     for (const User *U : MAV->users())
     333          10 :       if (isa<Instruction>(U))
     334          10 :         if (const Module *M = getModuleFromVal(U))
     335             :           return M;
     336             :     return nullptr;
     337             :   }
     338             : 
     339             :   return nullptr;
     340             : }
     341             : 
     342       13316 : static void PrintCallingConv(unsigned cc, raw_ostream &Out) {
     343       13316 :   switch (cc) {
     344          63 :   default:                         Out << "cc" << cc; break;
     345         390 :   case CallingConv::Fast:          Out << "fastcc"; break;
     346         496 :   case CallingConv::Cold:          Out << "coldcc"; break;
     347           8 :   case CallingConv::WebKit_JS:     Out << "webkit_jscc"; break;
     348           8 :   case CallingConv::AnyReg:        Out << "anyregcc"; break;
     349          12 :   case CallingConv::PreserveMost:  Out << "preserve_mostcc"; break;
     350          12 :   case CallingConv::PreserveAll:   Out << "preserve_allcc"; break;
     351          50 :   case CallingConv::CXX_FAST_TLS:  Out << "cxx_fast_tlscc"; break;
     352          43 :   case CallingConv::GHC:           Out << "ghccc"; break;
     353         140 :   case CallingConv::X86_StdCall:   Out << "x86_stdcallcc"; break;
     354         125 :   case CallingConv::X86_FastCall:  Out << "x86_fastcallcc"; break;
     355        5777 :   case CallingConv::X86_ThisCall:  Out << "x86_thiscallcc"; break;
     356         156 :   case CallingConv::X86_RegCall:   Out << "x86_regcallcc"; break;
     357         120 :   case CallingConv::X86_VectorCall:Out << "x86_vectorcallcc"; break;
     358          30 :   case CallingConv::Intel_OCL_BI:  Out << "intel_ocl_bicc"; break;
     359          32 :   case CallingConv::ARM_APCS:      Out << "arm_apcscc"; break;
     360         594 :   case CallingConv::ARM_AAPCS:     Out << "arm_aapcscc"; break;
     361         707 :   case CallingConv::ARM_AAPCS_VFP: Out << "arm_aapcs_vfpcc"; break;
     362          26 :   case CallingConv::MSP430_INTR:   Out << "msp430_intrcc"; break;
     363          11 :   case CallingConv::AVR_INTR:      Out << "avr_intrcc "; break;
     364          11 :   case CallingConv::AVR_SIGNAL:    Out << "avr_signalcc "; break;
     365          26 :   case CallingConv::PTX_Kernel:    Out << "ptx_kernel"; break;
     366          98 :   case CallingConv::PTX_Device:    Out << "ptx_device"; break;
     367          19 :   case CallingConv::X86_64_SysV:   Out << "x86_64_sysvcc"; break;
     368          32 :   case CallingConv::Win64:         Out << "win64cc"; break;
     369         273 :   case CallingConv::SPIR_FUNC:     Out << "spir_func"; break;
     370         199 :   case CallingConv::SPIR_KERNEL:   Out << "spir_kernel"; break;
     371        2188 :   case CallingConv::Swift:         Out << "swiftcc"; break;
     372          35 :   case CallingConv::X86_INTR:      Out << "x86_intrcc"; break;
     373          12 :   case CallingConv::HHVM:          Out << "hhvmcc"; break;
     374          14 :   case CallingConv::HHVM_C:        Out << "hhvm_ccc"; break;
     375          23 :   case CallingConv::AMDGPU_VS:     Out << "amdgpu_vs"; break;
     376           4 :   case CallingConv::AMDGPU_LS:     Out << "amdgpu_ls"; break;
     377           6 :   case CallingConv::AMDGPU_HS:     Out << "amdgpu_hs"; break;
     378           4 :   case CallingConv::AMDGPU_ES:     Out << "amdgpu_es"; break;
     379          10 :   case CallingConv::AMDGPU_GS:     Out << "amdgpu_gs"; break;
     380         136 :   case CallingConv::AMDGPU_PS:     Out << "amdgpu_ps"; break;
     381          10 :   case CallingConv::AMDGPU_CS:     Out << "amdgpu_cs"; break;
     382        1416 :   case CallingConv::AMDGPU_KERNEL: Out << "amdgpu_kernel"; break;
     383             :   }
     384       13316 : }
     385             : 
     386             : enum PrefixType {
     387             :   GlobalPrefix,
     388             :   ComdatPrefix,
     389             :   LabelPrefix,
     390             :   LocalPrefix,
     391             :   NoPrefix
     392             : };
     393             : 
     394     4438260 : void llvm::printLLVMNameWithoutPrefix(raw_ostream &OS, StringRef Name) {
     395             :   assert(!Name.empty() && "Cannot get empty name!");
     396             : 
     397             :   // Scan the name to see if it needs quotes first.
     398     4438260 :   bool NeedsQuotes = isdigit(static_cast<unsigned char>(Name[0]));
     399             :   if (!NeedsQuotes) {
     400    50567593 :     for (unsigned i = 0, e = Name.size(); i != e; ++i) {
     401             :       // By making this unsigned, the value passed in to isalnum will always be
     402             :       // in the range 0-255.  This is important when building with MSVC because
     403             :       // its implementation will assert.  This situation can arise when dealing
     404             :       // with UTF-8 multibyte characters.
     405    92465230 :       unsigned char C = Name[i];
     406    46232615 :       if (!isalnum(static_cast<unsigned char>(C)) && C != '-' && C != '.' &&
     407             :           C != '_') {
     408             :         NeedsQuotes = true;
     409             :         break;
     410             :       }
     411             :     }
     412             :   }
     413             : 
     414             :   // If we didn't need any quotes, just write out the name in one blast.
     415     4438260 :   if (!NeedsQuotes) {
     416     4334978 :     OS << Name;
     417     4334978 :     return;
     418             :   }
     419             : 
     420             :   // Okay, we need quotes.  Output the quotes and escape any scary characters as
     421             :   // needed.
     422             :   OS << '"';
     423      103282 :   PrintEscapedString(Name, OS);
     424             :   OS << '"';
     425             : }
     426             : 
     427             : /// Turn the specified name into an 'LLVM name', which is either prefixed with %
     428             : /// (if the string only contains simple characters) or is surrounded with ""'s
     429             : /// (if it has special chars in it). Print it out.
     430     4184245 : static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) {
     431     4184245 :   switch (Prefix) {
     432             :   case NoPrefix:
     433             :     break;
     434             :   case GlobalPrefix:
     435             :     OS << '@';
     436             :     break;
     437             :   case ComdatPrefix:
     438             :     OS << '$';
     439             :     break;
     440             :   case LabelPrefix:
     441             :     break;
     442             :   case LocalPrefix:
     443             :     OS << '%';
     444             :     break;
     445             :   }
     446     4437409 :   printLLVMNameWithoutPrefix(OS, Name);
     447     4184245 : }
     448             : 
     449             : /// Turn the specified name into an 'LLVM name', which is either prefixed with %
     450             : /// (if the string only contains simple characters) or is surrounded with ""'s
     451             : /// (if it has special chars in it). Print it out.
     452     3552821 : static void PrintLLVMName(raw_ostream &OS, const Value *V) {
     453     3552821 :   PrintLLVMName(OS, V->getName(),
     454             :                 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
     455     3552821 : }
     456             : 
     457             : namespace {
     458             : 
     459       85880 : class TypePrinting {
     460             : public:
     461             :   /// NamedTypes - The named types that are used by the current module.
     462             :   TypeFinder NamedTypes;
     463             : 
     464             :   /// NumberedTypes - The numbered types, along with their value.
     465             :   DenseMap<StructType*, unsigned> NumberedTypes;
     466             : 
     467       85880 :   TypePrinting() = default;
     468             :   TypePrinting(const TypePrinting &) = delete;
     469             :   TypePrinting &operator=(const TypePrinting &) = delete;
     470             : 
     471             :   void incorporateTypes(const Module &M);
     472             : 
     473             :   void print(Type *Ty, raw_ostream &OS);
     474             : 
     475             :   void printStructBody(StructType *Ty, raw_ostream &OS);
     476             : };
     477             : 
     478             : } // end anonymous namespace
     479             : 
     480       52718 : void TypePrinting::incorporateTypes(const Module &M) {
     481       52718 :   NamedTypes.run(M, false);
     482             : 
     483             :   // The list of struct types we got back includes all the struct types, split
     484             :   // the unnamed ones out to a numbering and remove the anonymous structs.
     485             :   unsigned NextNumber = 0;
     486             : 
     487             :   std::vector<StructType*>::iterator NextToUse = NamedTypes.begin(), I, E;
     488      113483 :   for (I = NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I) {
     489       60765 :     StructType *STy = *I;
     490             : 
     491             :     // Ignore anonymous types.
     492       60765 :     if (STy->isLiteral())
     493       10173 :       continue;
     494             : 
     495      101184 :     if (STy->getName().empty())
     496        1838 :       NumberedTypes[STy] = NextNumber++;
     497             :     else
     498       49673 :       *NextToUse++ = STy;
     499             :   }
     500             : 
     501             :   NamedTypes.erase(NextToUse, NamedTypes.end());
     502       52718 : }
     503             : 
     504             : 
     505             : /// CalcTypeName - Write the specified type to the specified raw_ostream, making
     506             : /// use of type names or up references to shorten the type name where possible.
     507     9651664 : void TypePrinting::print(Type *Ty, raw_ostream &OS) {
     508     9651664 :   switch (Ty->getTypeID()) {
     509      265719 :   case Type::VoidTyID:      OS << "void"; return;
     510       26342 :   case Type::HalfTyID:      OS << "half"; return;
     511      242058 :   case Type::FloatTyID:     OS << "float"; return;
     512      191468 :   case Type::DoubleTyID:    OS << "double"; return;
     513       11608 :   case Type::X86_FP80TyID:  OS << "x86_fp80"; return;
     514        3019 :   case Type::FP128TyID:     OS << "fp128"; return;
     515        1019 :   case Type::PPC_FP128TyID: OS << "ppc_fp128"; return;
     516      209224 :   case Type::LabelTyID:     OS << "label"; return;
     517       15189 :   case Type::MetadataTyID:  OS << "metadata"; return;
     518        2847 :   case Type::X86_MMXTyID:   OS << "x86_mmx"; return;
     519        2245 :   case Type::TokenTyID:     OS << "token"; return;
     520             :   case Type::IntegerTyID:
     521             :     OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
     522             :     return;
     523             : 
     524             :   case Type::FunctionTyID: {
     525             :     FunctionType *FTy = cast<FunctionType>(Ty);
     526       95675 :     print(FTy->getReturnType(), OS);
     527       95675 :     OS << " (";
     528      135421 :     for (FunctionType::param_iterator I = FTy->param_begin(),
     529      231096 :          E = FTy->param_end(); I != E; ++I) {
     530      135421 :       if (I != FTy->param_begin())
     531       67063 :         OS << ", ";
     532      135421 :       print(*I, OS);
     533             :     }
     534       95675 :     if (FTy->isVarArg()) {
     535       40262 :       if (FTy->getNumParams()) OS << ", ";
     536       40262 :       OS << "...";
     537             :     }
     538             :     OS << ')';
     539             :     return;
     540             :   }
     541             :   case Type::StructTyID: {
     542             :     StructType *STy = cast<StructType>(Ty);
     543             : 
     544      687855 :     if (STy->isLiteral())
     545       93075 :       return printStructBody(STy, OS);
     546             : 
     547     1189560 :     if (!STy->getName().empty())
     548      575175 :       return PrintLLVMName(OS, STy->getName(), LocalPrefix);
     549             : 
     550       19605 :     DenseMap<StructType*, unsigned>::iterator I = NumberedTypes.find(STy);
     551       19605 :     if (I != NumberedTypes.end())
     552       19595 :       OS << '%' << I->second;
     553             :     else  // Not enumerated, print the hex address.
     554          10 :       OS << "%\"type " << STy << '\"';
     555             :     return;
     556             :   }
     557             :   case Type::PointerTyID: {
     558             :     PointerType *PTy = cast<PointerType>(Ty);
     559     2620235 :     print(PTy->getElementType(), OS);
     560     2620235 :     if (unsigned AddressSpace = PTy->getAddressSpace())
     561       26548 :       OS << " addrspace(" << AddressSpace << ')';
     562             :     OS << '*';
     563             :     return;
     564             :   }
     565             :   case Type::ArrayTyID: {
     566             :     ArrayType *ATy = cast<ArrayType>(Ty);
     567      301239 :     OS << '[' << ATy->getNumElements() << " x ";
     568      301239 :     print(ATy->getElementType(), OS);
     569             :     OS << ']';
     570             :     return;
     571             :   }
     572             :   case Type::VectorTyID: {
     573             :     VectorType *PTy = cast<VectorType>(Ty);
     574      874594 :     OS << "<" << PTy->getNumElements() << " x ";
     575      874594 :     print(PTy->getElementType(), OS);
     576             :     OS << '>';
     577             :     return;
     578             :   }
     579             :   }
     580           0 :   llvm_unreachable("Invalid TypeID");
     581             : }
     582             : 
     583      122635 : void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
     584      122635 :   if (STy->isOpaque()) {
     585        1629 :     OS << "opaque";
     586        1629 :     return;
     587             :   }
     588             : 
     589      121006 :   if (STy->isPacked())
     590             :     OS << '<';
     591             : 
     592      121006 :   if (STy->getNumElements() == 0) {
     593         452 :     OS << "{}";
     594             :   } else {
     595             :     StructType::element_iterator I = STy->element_begin();
     596      120554 :     OS << "{ ";
     597      120554 :     print(*I++, OS);
     598      736494 :     for (StructType::element_iterator E = STy->element_end(); I != E; ++I) {
     599      307970 :       OS << ", ";
     600      307970 :       print(*I, OS);
     601             :     }
     602             : 
     603      120554 :     OS << " }";
     604             :   }
     605      121006 :   if (STy->isPacked())
     606             :     OS << '>';
     607             : }
     608             : 
     609             : namespace llvm {
     610             : 
     611             : //===----------------------------------------------------------------------===//
     612             : // SlotTracker Class: Enumerate slot numbers for unnamed values
     613             : //===----------------------------------------------------------------------===//
     614             : /// This class provides computation of slot numbers for LLVM Assembly writing.
     615             : ///
     616      184624 : class SlotTracker {
     617             : public:
     618             :   /// ValueMap - A mapping of Values to slot numbers.
     619             :   using ValueMap = DenseMap<const Value *, unsigned>;
     620             : 
     621             : private:
     622             :   /// TheModule - The module for which we are holding slot numbers.
     623             :   const Module* TheModule;
     624             : 
     625             :   /// TheFunction - The function for which we are holding slot numbers.
     626             :   const Function* TheFunction = nullptr;
     627             :   bool FunctionProcessed = false;
     628             :   bool ShouldInitializeAllMetadata;
     629             : 
     630             :   /// mMap - The slot map for the module level data.
     631             :   ValueMap mMap;
     632             :   unsigned mNext = 0;
     633             : 
     634             :   /// fMap - The slot map for the function level data.
     635             :   ValueMap fMap;
     636             :   unsigned fNext = 0;
     637             : 
     638             :   /// mdnMap - Map for MDNodes.
     639             :   DenseMap<const MDNode*, unsigned> mdnMap;
     640             :   unsigned mdnNext = 0;
     641             : 
     642             :   /// asMap - The slot map for attribute sets.
     643             :   DenseMap<AttributeSet, unsigned> asMap;
     644             :   unsigned asNext = 0;
     645             : 
     646             : public:
     647             :   /// Construct from a module.
     648             :   ///
     649             :   /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
     650             :   /// functions, giving correct numbering for metadata referenced only from
     651             :   /// within a function (even if no functions have been initialized).
     652             :   explicit SlotTracker(const Module *M,
     653             :                        bool ShouldInitializeAllMetadata = false);
     654             : 
     655             :   /// Construct from a function, starting out in incorp state.
     656             :   ///
     657             :   /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
     658             :   /// functions, giving correct numbering for metadata referenced only from
     659             :   /// within a function (even if no functions have been initialized).
     660             :   explicit SlotTracker(const Function *F,
     661             :                        bool ShouldInitializeAllMetadata = false);
     662             : 
     663             :   SlotTracker(const SlotTracker &) = delete;
     664             :   SlotTracker &operator=(const SlotTracker &) = delete;
     665             : 
     666             :   /// Return the slot number of the specified value in it's type
     667             :   /// plane.  If something is not in the SlotTracker, return -1.
     668             :   int getLocalSlot(const Value *V);
     669             :   int getGlobalSlot(const GlobalValue *V);
     670             :   int getMetadataSlot(const MDNode *N);
     671             :   int getAttributeGroupSlot(AttributeSet AS);
     672             : 
     673             :   /// If you'd like to deal with a function instead of just a module, use
     674             :   /// this method to get its data into the SlotTracker.
     675             :   void incorporateFunction(const Function *F) {
     676      218707 :     TheFunction = F;
     677      218707 :     FunctionProcessed = false;
     678             :   }
     679             : 
     680             :   const Function *getFunction() const { return TheFunction; }
     681             : 
     682             :   /// After calling incorporateFunction, use this method to remove the
     683             :   /// most recently incorporated function from the SlotTracker. This
     684             :   /// will reset the state of the machine back to just the module contents.
     685             :   void purgeFunction();
     686             : 
     687             :   /// MDNode map iterators.
     688             :   using mdn_iterator = DenseMap<const MDNode*, unsigned>::iterator;
     689             : 
     690        9597 :   mdn_iterator mdn_begin() { return mdnMap.begin(); }
     691             :   mdn_iterator mdn_end() { return mdnMap.end(); }
     692             :   unsigned mdn_size() const { return mdnMap.size(); }
     693             :   bool mdn_empty() const { return mdnMap.empty(); }
     694             : 
     695             :   /// AttributeSet map iterators.
     696             :   using as_iterator = DenseMap<AttributeSet, unsigned>::iterator;
     697             : 
     698       10989 :   as_iterator as_begin()   { return asMap.begin(); }
     699             :   as_iterator as_end()     { return asMap.end(); }
     700             :   unsigned as_size() const { return asMap.size(); }
     701             :   bool as_empty() const    { return asMap.empty(); }
     702             : 
     703             :   /// This function does the actual initialization.
     704             :   inline void initialize();
     705             : 
     706             :   // Implementation Details
     707             : private:
     708             :   /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
     709             :   void CreateModuleSlot(const GlobalValue *V);
     710             : 
     711             :   /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
     712             :   void CreateMetadataSlot(const MDNode *N);
     713             : 
     714             :   /// CreateFunctionSlot - Insert the specified Value* into the slot table.
     715             :   void CreateFunctionSlot(const Value *V);
     716             : 
     717             :   /// \brief Insert the specified AttributeSet into the slot table.
     718             :   void CreateAttributeSetSlot(AttributeSet AS);
     719             : 
     720             :   /// Add all of the module level global variables (and their initializers)
     721             :   /// and function declarations, but not the contents of those functions.
     722             :   void processModule();
     723             : 
     724             :   /// Add all of the functions arguments, basic blocks, and instructions.
     725             :   void processFunction();
     726             : 
     727             :   /// Add the metadata directly attached to a GlobalObject.
     728             :   void processGlobalObjectMetadata(const GlobalObject &GO);
     729             : 
     730             :   /// Add all of the metadata from a function.
     731             :   void processFunctionMetadata(const Function &F);
     732             : 
     733             :   /// Add all of the metadata from an instruction.
     734             :   void processInstructionMetadata(const Instruction &I);
     735             : };
     736             : 
     737             : } // end namespace llvm
     738             : 
     739       19540 : ModuleSlotTracker::ModuleSlotTracker(SlotTracker &Machine, const Module *M,
     740       19540 :                                      const Function *F)
     741       19540 :     : M(M), F(F), Machine(&Machine) {}
     742             : 
     743      119040 : ModuleSlotTracker::ModuleSlotTracker(const Module *M,
     744      119040 :                                      bool ShouldInitializeAllMetadata)
     745             :     : ShouldCreateStorage(M),
     746      119040 :       ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), M(M) {}
     747             : 
     748             : ModuleSlotTracker::~ModuleSlotTracker() = default;
     749             : 
     750      111257 : SlotTracker *ModuleSlotTracker::getMachine() {
     751      111257 :   if (!ShouldCreateStorage)
     752       80673 :     return Machine;
     753             : 
     754       30584 :   ShouldCreateStorage = false;
     755       30584 :   MachineStorage =
     756       61168 :       llvm::make_unique<SlotTracker>(M, ShouldInitializeAllMetadata);
     757       30584 :   Machine = MachineStorage.get();
     758       30584 :   return Machine;
     759             : }
     760             : 
     761       30275 : void ModuleSlotTracker::incorporateFunction(const Function &F) {
     762             :   // Using getMachine() may lazily create the slot tracker.
     763       30275 :   if (!getMachine())
     764             :     return;
     765             : 
     766             :   // Nothing to do if this is the right function already.
     767       30275 :   if (this->F == &F)
     768             :     return;
     769       30163 :   if (this->F)
     770          54 :     Machine->purgeFunction();
     771       30163 :   Machine->incorporateFunction(&F);
     772       30163 :   this->F = &F;
     773             : }
     774             : 
     775        2699 : int ModuleSlotTracker::getLocalSlot(const Value *V) {
     776             :   assert(F && "No function incorporated");
     777        2699 :   return Machine->getLocalSlot(V);
     778             : }
     779             : 
     780        1401 : static SlotTracker *createSlotTracker(const Value *V) {
     781             :   if (const Argument *FA = dyn_cast<Argument>(V))
     782          16 :     return new SlotTracker(FA->getParent());
     783             : 
     784             :   if (const Instruction *I = dyn_cast<Instruction>(V))
     785        1162 :     if (I->getParent())
     786        1162 :       return new SlotTracker(I->getParent()->getParent());
     787             : 
     788             :   if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
     789         201 :     return new SlotTracker(BB->getParent());
     790             : 
     791             :   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
     792          16 :     return new SlotTracker(GV->getParent());
     793             : 
     794             :   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
     795           0 :     return new SlotTracker(GA->getParent());
     796             : 
     797             :   if (const GlobalIFunc *GIF = dyn_cast<GlobalIFunc>(V))
     798           0 :     return new SlotTracker(GIF->getParent());
     799             : 
     800             :   if (const Function *Func = dyn_cast<Function>(V))
     801           6 :     return new SlotTracker(Func);
     802             : 
     803             :   return nullptr;
     804             : }
     805             : 
     806             : #if 0
     807             : #define ST_DEBUG(X) dbgs() << X
     808             : #else
     809             : #define ST_DEBUG(X)
     810             : #endif
     811             : 
     812             : // Module level constructor. Causes the contents of the Module (sans functions)
     813             : // to be added to the slot table.
     814       90927 : SlotTracker::SlotTracker(const Module *M, bool ShouldInitializeAllMetadata)
     815      454635 :     : TheModule(M), ShouldInitializeAllMetadata(ShouldInitializeAllMetadata) {}
     816             : 
     817             : // Function level constructor. Causes the contents of the Module and the one
     818             : // function provided to be added to the slot table.
     819        1385 : SlotTracker::SlotTracker(const Function *F, bool ShouldInitializeAllMetadata)
     820        1385 :     : TheModule(F ? F->getParent() : nullptr), TheFunction(F),
     821        6925 :       ShouldInitializeAllMetadata(ShouldInitializeAllMetadata) {}
     822             : 
     823     1822264 : inline void SlotTracker::initialize() {
     824     1822264 :   if (TheModule) {
     825       23610 :     processModule();
     826       23610 :     TheModule = nullptr; ///< Prevent re-processing next time we're called.
     827             :   }
     828             : 
     829     1822264 :   if (TheFunction && !FunctionProcessed)
     830      149967 :     processFunction();
     831     1822264 : }
     832             : 
     833             : // Iterate through all the global variables, functions, and global
     834             : // variable initializers and create slots for them.
     835       23610 : void SlotTracker::processModule() {
     836             :   ST_DEBUG("begin processModule!\n");
     837             : 
     838             :   // Add all of the unnamed global variables to the value table.
     839      129260 :   for (const GlobalVariable &Var : TheModule->globals()) {
     840       82040 :     if (!Var.hasName())
     841        5341 :       CreateModuleSlot(&Var);
     842       82040 :     processGlobalObjectMetadata(Var);
     843             :     auto Attrs = Var.getAttributes();
     844       82040 :     if (Attrs.hasAttributes())
     845          33 :       CreateAttributeSetSlot(Attrs);
     846             :   }
     847             : 
     848       48317 :   for (const GlobalAlias &A : TheModule->aliases()) {
     849        1097 :     if (!A.hasName())
     850           4 :       CreateModuleSlot(&A);
     851             :   }
     852             : 
     853       47291 :   for (const GlobalIFunc &I : TheModule->ifuncs()) {
     854          71 :     if (!I.hasName())
     855           0 :       CreateModuleSlot(&I);
     856             :   }
     857             : 
     858             :   // Add metadata used by named metadata.
     859       66695 :   for (const NamedMDNode &NMD : TheModule->named_metadata()) {
     860       50451 :     for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i)
     861       30976 :       CreateMetadataSlot(NMD.getOperand(i));
     862             :   }
     863             : 
     864      341310 :   for (const Function &F : *TheModule) {
     865      294090 :     if (!F.hasName())
     866             :       // Add all the unnamed functions to the table.
     867          35 :       CreateModuleSlot(&F);
     868             : 
     869      294090 :     if (ShouldInitializeAllMetadata)
     870       32742 :       processFunctionMetadata(F);
     871             : 
     872             :     // Add all the function attributes to the table.
     873             :     // FIXME: Add attributes of other objects?
     874      294090 :     AttributeSet FnAttrs = F.getAttributes().getFnAttributes();
     875      294090 :     if (FnAttrs.hasAttributes())
     876      206807 :       CreateAttributeSetSlot(FnAttrs);
     877             :   }
     878             : 
     879             :   ST_DEBUG("end processModule!\n");
     880       23610 : }
     881             : 
     882             : // Process the arguments, basic blocks, and instructions  of a function.
     883      149967 : void SlotTracker::processFunction() {
     884             :   ST_DEBUG("begin processFunction!\n");
     885      149967 :   fNext = 0;
     886             : 
     887             :   // Process function metadata if it wasn't hit at the module-level.
     888      149967 :   if (!ShouldInitializeAllMetadata)
     889      148218 :     processFunctionMetadata(*TheFunction);
     890             : 
     891             :   // Add all the function arguments with no names.
     892      383667 :   for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
     893      533634 :       AE = TheFunction->arg_end(); AI != AE; ++AI)
     894      233700 :     if (!AI->hasName())
     895       78309 :       CreateFunctionSlot(&*AI);
     896             : 
     897             :   ST_DEBUG("Inserting Instructions:\n");
     898             : 
     899             :   // Add all of the basic blocks and instructions with no names.
     900      580471 :   for (auto &BB : *TheFunction) {
     901      280537 :     if (!BB.hasName())
     902       18864 :       CreateFunctionSlot(&BB);
     903             : 
     904     2438717 :     for (auto &I : BB) {
     905     3545657 :       if (!I.getType()->isVoidTy() && !I.hasName())
     906      688575 :         CreateFunctionSlot(&I);
     907             : 
     908             :       // We allow direct calls to any llvm.foo function here, because the
     909             :       // target may not be linked into the optimizer.
     910     2158180 :       if (auto CS = ImmutableCallSite(&I)) {
     911             :         // Add all the call attributes to the table.
     912      159355 :         AttributeSet Attrs = CS.getAttributes().getFnAttributes();
     913      159355 :         if (Attrs.hasAttributes())
     914       52350 :           CreateAttributeSetSlot(Attrs);
     915             :       }
     916             :     }
     917             :   }
     918             : 
     919      149967 :   FunctionProcessed = true;
     920             : 
     921             :   ST_DEBUG("end processFunction!\n");
     922      149967 : }
     923             : 
     924      263000 : void SlotTracker::processGlobalObjectMetadata(const GlobalObject &GO) {
     925             :   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
     926      263000 :   GO.getAllMetadata(MDs);
     927      274510 :   for (auto &MD : MDs)
     928        5755 :     CreateMetadataSlot(MD.second);
     929      263000 : }
     930             : 
     931      180960 : void SlotTracker::processFunctionMetadata(const Function &F) {
     932      180960 :   processGlobalObjectMetadata(F);
     933      492474 :   for (auto &BB : F) {
     934     2547924 :     for (auto &I : BB)
     935     2236410 :       processInstructionMetadata(I);
     936             :   }
     937      180960 : }
     938             : 
     939     2236410 : void SlotTracker::processInstructionMetadata(const Instruction &I) {
     940             :   // Process metadata used directly by intrinsics.
     941             :   if (const CallInst *CI = dyn_cast<CallInst>(&I))
     942             :     if (Function *F = CI->getCalledFunction())
     943      155958 :       if (F->isIntrinsic())
     944      511324 :         for (auto &Op : I.operands())
     945             :           if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
     946             :             if (MDNode *N = dyn_cast<MDNode>(V->getMetadata()))
     947        9257 :               CreateMetadataSlot(N);
     948             : 
     949             :   // Process metadata attached to this instruction.
     950             :   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
     951             :   I.getAllMetadata(MDs);
     952     2525162 :   for (auto &MD : MDs)
     953      144376 :     CreateMetadataSlot(MD.second);
     954     2236410 : }
     955             : 
     956             : /// Clean up after incorporating a function. This is the only way to get out of
     957             : /// the function incorporation state that affects get*Slot/Create*Slot. Function
     958             : /// incorporation state is indicated by TheFunction != 0.
     959      188598 : void SlotTracker::purgeFunction() {
     960             :   ST_DEBUG("begin purgeFunction!\n");
     961      188598 :   fMap.clear(); // Simply discard the function level map
     962      188598 :   TheFunction = nullptr;
     963      188598 :   FunctionProcessed = false;
     964             :   ST_DEBUG("end purgeFunction!\n");
     965      188598 : }
     966             : 
     967             : /// getGlobalSlot - Get the slot number of a global value.
     968       26815 : int SlotTracker::getGlobalSlot(const GlobalValue *V) {
     969             :   // Check for uninitialized state and do lazy initialization.
     970       26815 :   initialize();
     971             : 
     972             :   // Find the value in the module map
     973       26815 :   ValueMap::iterator MI = mMap.find(V);
     974       26815 :   return MI == mMap.end() ? -1 : (int)MI->second;
     975             : }
     976             : 
     977             : /// getMetadataSlot - Get the slot number of a MDNode.
     978      245900 : int SlotTracker::getMetadataSlot(const MDNode *N) {
     979             :   // Check for uninitialized state and do lazy initialization.
     980      245900 :   initialize();
     981             : 
     982             :   // Find the MDNode in the module map
     983      245900 :   mdn_iterator MI = mdnMap.find(N);
     984      245900 :   return MI == mdnMap.end() ? -1 : (int)MI->second;
     985             : }
     986             : 
     987             : /// getLocalSlot - Get the slot number for a value that is local to a function.
     988     1346556 : int SlotTracker::getLocalSlot(const Value *V) {
     989             :   assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
     990             : 
     991             :   // Check for uninitialized state and do lazy initialization.
     992     1346556 :   initialize();
     993             : 
     994     1346556 :   ValueMap::iterator FI = fMap.find(V);
     995     1346556 :   return FI == fMap.end() ? -1 : (int)FI->second;
     996             : }
     997             : 
     998      187548 : int SlotTracker::getAttributeGroupSlot(AttributeSet AS) {
     999             :   // Check for uninitialized state and do lazy initialization.
    1000      187548 :   initialize();
    1001             : 
    1002             :   // Find the AttributeSet in the module map.
    1003      187548 :   as_iterator AI = asMap.find(AS);
    1004      187548 :   return AI == asMap.end() ? -1 : (int)AI->second;
    1005             : }
    1006             : 
    1007             : /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
    1008        5380 : void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
    1009             :   assert(V && "Can't insert a null Value into SlotTracker!");
    1010             :   assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
    1011             :   assert(!V->hasName() && "Doesn't need a slot!");
    1012             : 
    1013        5380 :   unsigned DestSlot = mNext++;
    1014       10760 :   mMap[V] = DestSlot;
    1015             : 
    1016             :   ST_DEBUG("  Inserting value [" << V->getType() << "] = " << V << " slot=" <<
    1017             :            DestSlot << " [");
    1018             :   // G = Global, F = Function, A = Alias, I = IFunc, o = other
    1019             :   ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
    1020             :             (isa<Function>(V) ? 'F' :
    1021             :              (isa<GlobalAlias>(V) ? 'A' :
    1022             :               (isa<GlobalIFunc>(V) ? 'I' : 'o')))) << "]\n");
    1023        5380 : }
    1024             : 
    1025             : /// CreateSlot - Create a new slot for the specified value if it has no name.
    1026      785748 : void SlotTracker::CreateFunctionSlot(const Value *V) {
    1027             :   assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
    1028             : 
    1029      785748 :   unsigned DestSlot = fNext++;
    1030     1571496 :   fMap[V] = DestSlot;
    1031             : 
    1032             :   // G = Global, F = Function, o = other
    1033             :   ST_DEBUG("  Inserting value [" << V->getType() << "] = " << V << " slot=" <<
    1034             :            DestSlot << " [o]\n");
    1035      785748 : }
    1036             : 
    1037             : /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
    1038      323470 : void SlotTracker::CreateMetadataSlot(const MDNode *N) {
    1039             :   assert(N && "Can't insert a null Value into SlotTracker!");
    1040             : 
    1041             :   // Don't make slots for DIExpressions. We just print them inline everywhere.
    1042      323470 :   if (isa<DIExpression>(N))
    1043             :     return;
    1044             : 
    1045      318264 :   unsigned DestSlot = mdnNext;
    1046      636528 :   if (!mdnMap.insert(std::make_pair(N, DestSlot)).second)
    1047             :     return;
    1048      114666 :   ++mdnNext;
    1049             : 
    1050             :   // Recursively add any MDNodes referenced by operands.
    1051      812534 :   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
    1052             :     if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
    1053      133106 :       CreateMetadataSlot(Op);
    1054             : }
    1055             : 
    1056      259190 : void SlotTracker::CreateAttributeSetSlot(AttributeSet AS) {
    1057             :   assert(AS.hasAttributes() && "Doesn't need a slot!");
    1058             : 
    1059      259190 :   as_iterator I = asMap.find(AS);
    1060      259190 :   if (I != asMap.end())
    1061      222925 :     return;
    1062             : 
    1063       36265 :   unsigned DestSlot = asNext++;
    1064       36265 :   asMap[AS] = DestSlot;
    1065             : }
    1066             : 
    1067             : //===----------------------------------------------------------------------===//
    1068             : // AsmWriter Implementation
    1069             : //===----------------------------------------------------------------------===//
    1070             : 
    1071             : static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
    1072             :                                    TypePrinting *TypePrinter,
    1073             :                                    SlotTracker *Machine,
    1074             :                                    const Module *Context);
    1075             : 
    1076             : static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
    1077             :                                    TypePrinting *TypePrinter,
    1078             :                                    SlotTracker *Machine, const Module *Context,
    1079             :                                    bool FromValue = false);
    1080             : 
    1081         919 : static void writeAtomicRMWOperation(raw_ostream &Out,
    1082             :                                     AtomicRMWInst::BinOp Op) {
    1083         919 :   switch (Op) {
    1084           0 :   default: Out << " <unknown operation " << Op << ">"; break;
    1085          97 :   case AtomicRMWInst::Xchg: Out << " xchg"; break;
    1086         376 :   case AtomicRMWInst::Add:  Out << " add"; break;
    1087          97 :   case AtomicRMWInst::Sub:  Out << " sub"; break;
    1088          80 :   case AtomicRMWInst::And:  Out << " and"; break;
    1089          42 :   case AtomicRMWInst::Nand: Out << " nand"; break;
    1090          76 :   case AtomicRMWInst::Or:   Out << " or"; break;
    1091          65 :   case AtomicRMWInst::Xor:  Out << " xor"; break;
    1092          23 :   case AtomicRMWInst::Max:  Out << " max"; break;
    1093          25 :   case AtomicRMWInst::Min:  Out << " min"; break;
    1094          19 :   case AtomicRMWInst::UMax: Out << " umax"; break;
    1095          19 :   case AtomicRMWInst::UMin: Out << " umin"; break;
    1096             :   }
    1097         919 : }
    1098             : 
    1099     2210682 : static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
    1100       83369 :   if (const FPMathOperator *FPO = dyn_cast<const FPMathOperator>(U)) {
    1101             :     // 'Fast' is an abbreviation for all fast-math-flags.
    1102             :     if (FPO->isFast())
    1103        2454 :       Out << " fast";
    1104             :     else {
    1105       80915 :       if (FPO->hasAllowReassoc())
    1106         171 :         Out << " reassoc";
    1107       80915 :       if (FPO->hasNoNaNs())
    1108         215 :         Out << " nnan";
    1109       80915 :       if (FPO->hasNoInfs())
    1110          66 :         Out << " ninf";
    1111       80915 :       if (FPO->hasNoSignedZeros())
    1112          55 :         Out << " nsz";
    1113       80915 :       if (FPO->hasAllowReciprocal())
    1114          54 :         Out << " arcp";
    1115       80915 :       if (FPO->hasAllowContract())
    1116          43 :         Out << " contract";
    1117       80915 :       if (FPO->hasApproxFunc())
    1118          28 :         Out << " afn";
    1119             :     }
    1120             :   }
    1121             : 
    1122       89041 :   if (const OverflowingBinaryOperator *OBO =
    1123             :         dyn_cast<OverflowingBinaryOperator>(U)) {
    1124       89041 :     if (OBO->hasNoUnsignedWrap())
    1125        6055 :       Out << " nuw";
    1126       89041 :     if (OBO->hasNoSignedWrap())
    1127       61079 :       Out << " nsw";
    1128        9765 :   } else if (const PossiblyExactOperator *Div =
    1129             :                dyn_cast<PossiblyExactOperator>(U)) {
    1130        9765 :     if (Div->isExact())
    1131         406 :       Out << " exact";
    1132             :   } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
    1133      179441 :     if (GEP->isInBounds())
    1134      164083 :       Out << " inbounds";
    1135             :   }
    1136     2210682 : }
    1137             : 
    1138     1137967 : static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
    1139             :                                   TypePrinting &TypePrinter,
    1140             :                                   SlotTracker *Machine,
    1141             :                                   const Module *Context) {
    1142             :   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
    1143      877204 :     if (CI->getType()->isIntegerTy(1)) {
    1144       23647 :       Out << (CI->getZExtValue() ? "true" : "false");
    1145       23647 :       return;
    1146             :     }
    1147             :     Out << CI->getValue();
    1148             :     return;
    1149             :   }
    1150             : 
    1151             :   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
    1152             :     const APFloat &APF = CFP->getValueAPF();
    1153       23940 :     if (&APF.getSemantics() == &APFloat::IEEEsingle() ||
    1154        7380 :         &APF.getSemantics() == &APFloat::IEEEdouble()) {
    1155             :       // We would like to output the FP constant value in exponential notation,
    1156             :       // but we cannot do this if doing so will lose precision.  Check here to
    1157             :       // make sure that we only output it in exponential format if we can parse
    1158             :       // the value back and get the same value.
    1159             :       //
    1160             :       bool ignored;
    1161       15613 :       bool isDouble = &APF.getSemantics() == &APFloat::IEEEdouble();
    1162             :       bool isInf = APF.isInfinity();
    1163             :       bool isNaN = APF.isNaN();
    1164       15613 :       if (!isInf && !isNaN) {
    1165       15221 :         double Val = isDouble ? APF.convertToDouble() : APF.convertToFloat();
    1166             :         SmallString<128> StrVal;
    1167       15221 :         APF.toString(StrVal, 6, 0, false);
    1168             :         // Check to make sure that the stringized number is not some string like
    1169             :         // "Inf" or NaN, that atof will accept, but the lexer will not.  Check
    1170             :         // that the string matches the "[-+]?[0-9]" regex.
    1171             :         //
    1172             :         assert(((StrVal[0] >= '0' && StrVal[0] <= '9') ||
    1173             :                 ((StrVal[0] == '-' || StrVal[0] == '+') &&
    1174             :                  (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
    1175             :                "[-+]?[0-9] regex does not match!");
    1176             :         // Reparse stringized version!
    1177       30442 :         if (APFloat(APFloat::IEEEdouble(), StrVal).convertToDouble() == Val) {
    1178             :           Out << StrVal;
    1179             :           return;
    1180             :         }
    1181             :       }
    1182             :       // Otherwise we could not reparse it to exactly the same value, so we must
    1183             :       // output the string in hexadecimal format!  Note that loading and storing
    1184             :       // floating point types changes the bits of NaNs on some hosts, notably
    1185             :       // x86, so we must not use these types.
    1186             :       static_assert(sizeof(double) == sizeof(uint64_t),
    1187             :                     "assuming that double is 64 bits!");
    1188             :       APFloat apf = APF;
    1189             :       // Floats are represented in ASCII IR as double, convert.
    1190         813 :       if (!isDouble)
    1191         505 :         apf.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven,
    1192             :                           &ignored);
    1193        2439 :       Out << format_hex(apf.bitcastToAPInt().getZExtValue(), 0, /*Upper=*/true);
    1194             :       return;
    1195             :     }
    1196             : 
    1197             :     // Either half, or some form of long double.
    1198             :     // These appear as a magic letter identifying the type, then a
    1199             :     // fixed number of hex digits.
    1200         947 :     Out << "0x";
    1201         947 :     APInt API = APF.bitcastToAPInt();
    1202         947 :     if (&APF.getSemantics() == &APFloat::x87DoubleExtended()) {
    1203             :       Out << 'K';
    1204         930 :       Out << format_hex_no_prefix(API.getHiBits(16).getZExtValue(), 4,
    1205             :                                   /*Upper=*/true);
    1206         930 :       Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
    1207             :                                   /*Upper=*/true);
    1208         310 :       return;
    1209         637 :     } else if (&APF.getSemantics() == &APFloat::IEEEquad()) {
    1210             :       Out << 'L';
    1211         504 :       Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
    1212             :                                   /*Upper=*/true);
    1213         504 :       Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16,
    1214             :                                   /*Upper=*/true);
    1215         469 :     } else if (&APF.getSemantics() == &APFloat::PPCDoubleDouble()) {
    1216             :       Out << 'M';
    1217          78 :       Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
    1218             :                                   /*Upper=*/true);
    1219          78 :       Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16,
    1220             :                                   /*Upper=*/true);
    1221         443 :     } else if (&APF.getSemantics() == &APFloat::IEEEhalf()) {
    1222             :       Out << 'H';
    1223         443 :       Out << format_hex_no_prefix(API.getZExtValue(), 4,
    1224             :                                   /*Upper=*/true);
    1225             :     } else
    1226           0 :       llvm_unreachable("Unsupported floating point type");
    1227             :     return;
    1228             :   }
    1229             : 
    1230      244203 :   if (isa<ConstantAggregateZero>(CV)) {
    1231       14912 :     Out << "zeroinitializer";
    1232       14912 :     return;
    1233             :   }
    1234             : 
    1235             :   if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
    1236         303 :     Out << "blockaddress(";
    1237         303 :     WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine,
    1238             :                            Context);
    1239         303 :     Out << ", ";
    1240         303 :     WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine,
    1241             :                            Context);
    1242         303 :     Out << ")";
    1243         303 :     return;
    1244             :   }
    1245             : 
    1246             :   if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
    1247             :     Type *ETy = CA->getType()->getElementType();
    1248             :     Out << '[';
    1249        7293 :     TypePrinter.print(ETy, Out);
    1250             :     Out << ' ';
    1251       14586 :     WriteAsOperandInternal(Out, CA->getOperand(0),
    1252             :                            &TypePrinter, Machine,
    1253             :                            Context);
    1254       39649 :     for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
    1255       16178 :       Out << ", ";
    1256       16178 :       TypePrinter.print(ETy, Out);
    1257             :       Out << ' ';
    1258       16178 :       WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine,
    1259             :                              Context);
    1260             :     }
    1261             :     Out << ']';
    1262             :     return;
    1263             :   }
    1264             : 
    1265             :   if (const ConstantDataArray *CA = dyn_cast<ConstantDataArray>(CV)) {
    1266             :     // As a special case, print the array as a string if it is an array of
    1267             :     // i8 with ConstantInt values.
    1268       23445 :     if (CA->isString()) {
    1269       15584 :       Out << "c\"";
    1270       15584 :       PrintEscapedString(CA->getAsString(), Out);
    1271             :       Out << '"';
    1272             :       return;
    1273             :     }
    1274             : 
    1275             :     Type *ETy = CA->getType()->getElementType();
    1276             :     Out << '[';
    1277        7861 :     TypePrinter.print(ETy, Out);
    1278             :     Out << ' ';
    1279        7861 :     WriteAsOperandInternal(Out, CA->getElementAsConstant(0),
    1280             :                            &TypePrinter, Machine,
    1281             :                            Context);
    1282       19513 :     for (unsigned i = 1, e = CA->getNumElements(); i != e; ++i) {
    1283       11652 :       Out << ", ";
    1284       11652 :       TypePrinter.print(ETy, Out);
    1285             :       Out << ' ';
    1286       11652 :       WriteAsOperandInternal(Out, CA->getElementAsConstant(i), &TypePrinter,
    1287             :                              Machine, Context);
    1288             :     }
    1289             :     Out << ']';
    1290             :     return;
    1291             :   }
    1292             : 
    1293             :   if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
    1294       25758 :     if (CS->getType()->isPacked())
    1295             :       Out << '<';
    1296             :     Out << '{';
    1297             :     unsigned N = CS->getNumOperands();
    1298       25758 :     if (N) {
    1299             :       Out << ' ';
    1300       51516 :       TypePrinter.print(CS->getOperand(0)->getType(), Out);
    1301             :       Out << ' ';
    1302             : 
    1303       25758 :       WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine,
    1304             :                              Context);
    1305             : 
    1306      186880 :       for (unsigned i = 1; i < N; i++) {
    1307       80561 :         Out << ", ";
    1308       80561 :         TypePrinter.print(CS->getOperand(i)->getType(), Out);
    1309             :         Out << ' ';
    1310             : 
    1311       80561 :         WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine,
    1312             :                                Context);
    1313             :       }
    1314             :       Out << ' ';
    1315             :     }
    1316             : 
    1317             :     Out << '}';
    1318       25758 :     if (CS->getType()->isPacked())
    1319             :       Out << '>';
    1320             :     return;
    1321             :   }
    1322             : 
    1323      172492 :   if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) {
    1324             :     Type *ETy = CV->getType()->getVectorElementType();
    1325             :     Out << '<';
    1326       17099 :     TypePrinter.print(ETy, Out);
    1327             :     Out << ' ';
    1328       17099 :     WriteAsOperandInternal(Out, CV->getAggregateElement(0U), &TypePrinter,
    1329             :                            Machine, Context);
    1330      280239 :     for (unsigned i = 1, e = CV->getType()->getVectorNumElements(); i != e;++i){
    1331      131570 :       Out << ", ";
    1332      131570 :       TypePrinter.print(ETy, Out);
    1333             :       Out << ' ';
    1334      131570 :       WriteAsOperandInternal(Out, CV->getAggregateElement(i), &TypePrinter,
    1335             :                              Machine, Context);
    1336             :     }
    1337             :     Out << '>';
    1338             :     return;
    1339             :   }
    1340             : 
    1341      155393 :   if (isa<ConstantPointerNull>(CV)) {
    1342       21360 :     Out << "null";
    1343       21360 :     return;
    1344             :   }
    1345             : 
    1346      134033 :   if (isa<ConstantTokenNone>(CV)) {
    1347         494 :     Out << "none";
    1348         494 :     return;
    1349             :   }
    1350             : 
    1351      133539 :   if (isa<UndefValue>(CV)) {
    1352       34627 :     Out << "undef";
    1353       34627 :     return;
    1354             :   }
    1355             : 
    1356             :   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
    1357       98912 :     Out << CE->getOpcodeName();
    1358       98912 :     WriteOptimizationInfo(Out, CE);
    1359       98912 :     if (CE->isCompare())
    1360         202 :       Out << ' ' << CmpInst::getPredicateName(
    1361         202 :                         static_cast<CmpInst::Predicate>(CE->getPredicate()));
    1362       98912 :     Out << " (";
    1363             : 
    1364             :     Optional<unsigned> InRangeOp;
    1365             :     if (const GEPOperator *GEP = dyn_cast<GEPOperator>(CE)) {
    1366       47039 :       TypePrinter.print(GEP->getSourceElementType(), Out);
    1367       47039 :       Out << ", ";
    1368             :       InRangeOp = GEP->getInRangeIndex();
    1369       47039 :       if (InRangeOp)
    1370        1211 :         ++*InRangeOp;
    1371             :     }
    1372             : 
    1373      294140 :     for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
    1374      200071 :       if (InRangeOp && unsigned(OI - CE->op_begin()) == *InRangeOp)
    1375        1211 :         Out << "inrange ";
    1376      195228 :       TypePrinter.print((*OI)->getType(), Out);
    1377             :       Out << ' ';
    1378      195228 :       WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context);
    1379      195228 :       if (OI+1 != CE->op_end())
    1380       96316 :         Out << ", ";
    1381             :     }
    1382             : 
    1383       98912 :     if (CE->hasIndices()) {
    1384           3 :       ArrayRef<unsigned> Indices = CE->getIndices();
    1385           6 :       for (unsigned i = 0, e = Indices.size(); i != e; ++i)
    1386           6 :         Out << ", " << Indices[i];
    1387             :     }
    1388             : 
    1389       98912 :     if (CE->isCast()) {
    1390       49988 :       Out << " to ";
    1391       49988 :       TypePrinter.print(CE->getType(), Out);
    1392             :     }
    1393             : 
    1394             :     Out << ')';
    1395             :     return;
    1396             :   }
    1397             : 
    1398           0 :   Out << "<placeholder or erroneous Constant>";
    1399             : }
    1400             : 
    1401       55069 : static void writeMDTuple(raw_ostream &Out, const MDTuple *Node,
    1402             :                          TypePrinting *TypePrinter, SlotTracker *Machine,
    1403             :                          const Module *Context) {
    1404       55069 :   Out << "!{";
    1405      199866 :   for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
    1406      144797 :     const Metadata *MD = Node->getOperand(mi);
    1407      144797 :     if (!MD)
    1408         981 :       Out << "null";
    1409             :     else if (auto *MDV = dyn_cast<ValueAsMetadata>(MD)) {
    1410             :       Value *V = MDV->getValue();
    1411       68234 :       TypePrinter->print(V->getType(), Out);
    1412             :       Out << ' ';
    1413       68234 :       WriteAsOperandInternal(Out, V, TypePrinter, Machine, Context);
    1414             :     } else {
    1415       75582 :       WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
    1416             :     }
    1417      144797 :     if (mi + 1 != me)
    1418       91513 :       Out << ", ";
    1419             :   }
    1420             : 
    1421       55069 :   Out << "}";
    1422       55069 : }
    1423             : 
    1424             : namespace {
    1425             : 
    1426             : struct FieldSeparator {
    1427             :   bool Skip = true;
    1428             :   const char *Sep;
    1429             : 
    1430       31616 :   FieldSeparator(const char *Sep = ", ") : Sep(Sep) {}
    1431             : };
    1432             : 
    1433             : raw_ostream &operator<<(raw_ostream &OS, FieldSeparator &FS) {
    1434      149059 :   if (FS.Skip) {
    1435       31604 :     FS.Skip = false;
    1436             :     return OS;
    1437             :   }
    1438      110519 :   return OS << FS.Sep;
    1439             : }
    1440             : 
    1441             : struct MDFieldPrinter {
    1442             :   raw_ostream &Out;
    1443             :   FieldSeparator FS;
    1444             :   TypePrinting *TypePrinter = nullptr;
    1445             :   SlotTracker *Machine = nullptr;
    1446             :   const Module *Context = nullptr;
    1447             : 
    1448        5040 :   explicit MDFieldPrinter(raw_ostream &Out) : Out(Out) {}
    1449             :   MDFieldPrinter(raw_ostream &Out, TypePrinting *TypePrinter,
    1450             :                  SlotTracker *Machine, const Module *Context)
    1451       58192 :       : Out(Out), TypePrinter(TypePrinter), Machine(Machine), Context(Context) {
    1452             :   }
    1453             : 
    1454             :   void printTag(const DINode *N);
    1455             :   void printMacinfoType(const DIMacroNode *N);
    1456             :   void printChecksum(const DIFile::ChecksumInfo<StringRef> &N);
    1457             :   void printString(StringRef Name, StringRef Value,
    1458             :                    bool ShouldSkipEmpty = true);
    1459             :   void printMetadata(StringRef Name, const Metadata *MD,
    1460             :                      bool ShouldSkipNull = true);
    1461             :   template <class IntTy>
    1462             :   void printInt(StringRef Name, IntTy Int, bool ShouldSkipZero = true);
    1463             :   void printBool(StringRef Name, bool Value, Optional<bool> Default = None);
    1464             :   void printDIFlags(StringRef Name, DINode::DIFlags Flags);
    1465             :   template <class IntTy, class Stringifier>
    1466             :   void printDwarfEnum(StringRef Name, IntTy Value, Stringifier toString,
    1467             :                       bool ShouldSkipZero = true);
    1468             :   void printEmissionKind(StringRef Name, DICompileUnit::DebugEmissionKind EK);
    1469             : };
    1470             : 
    1471             : } // end anonymous namespace
    1472             : 
    1473        4751 : void MDFieldPrinter::printTag(const DINode *N) {
    1474        9502 :   Out << FS << "tag: ";
    1475        4751 :   auto Tag = dwarf::TagString(N->getTag());
    1476        4751 :   if (!Tag.empty())
    1477        4746 :     Out << Tag;
    1478             :   else
    1479           5 :     Out << N->getTag();
    1480        4751 : }
    1481             : 
    1482        1073 : void MDFieldPrinter::printMacinfoType(const DIMacroNode *N) {
    1483        2146 :   Out << FS << "type: ";
    1484        1073 :   auto Type = dwarf::MacinfoString(N->getMacinfoType());
    1485        1073 :   if (!Type.empty())
    1486        1073 :     Out << Type;
    1487             :   else
    1488           0 :     Out << N->getMacinfoType();
    1489        1073 : }
    1490             : 
    1491          51 : void MDFieldPrinter::printChecksum(
    1492             :     const DIFile::ChecksumInfo<StringRef> &Checksum) {
    1493         153 :   Out << FS << "checksumkind: " << Checksum.getKindAsString();
    1494          51 :   printString("checksum", Checksum.Value, /* ShouldSkipEmpty */ false);
    1495          51 : }
    1496             : 
    1497       28538 : void MDFieldPrinter::printString(StringRef Name, StringRef Value,
    1498             :                                  bool ShouldSkipEmpty) {
    1499       53976 :   if (ShouldSkipEmpty && Value.empty())
    1500             :     return;
    1501             : 
    1502       40350 :   Out << FS << Name << ": \"";
    1503       20175 :   PrintEscapedString(Value, Out);
    1504       20175 :   Out << "\"";
    1505             : }
    1506             : 
    1507       56263 : static void writeMetadataAsOperand(raw_ostream &Out, const Metadata *MD,
    1508             :                                    TypePrinting *TypePrinter,
    1509             :                                    SlotTracker *Machine,
    1510             :                                    const Module *Context) {
    1511       56263 :   if (!MD) {
    1512         365 :     Out << "null";
    1513         365 :     return;
    1514             :   }
    1515       55898 :   WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
    1516             : }
    1517             : 
    1518      100841 : void MDFieldPrinter::printMetadata(StringRef Name, const Metadata *MD,
    1519             :                                    bool ShouldSkipNull) {
    1520      100841 :   if (ShouldSkipNull && !MD)
    1521             :     return;
    1522             : 
    1523      112496 :   Out << FS << Name << ": ";
    1524       56248 :   writeMetadataAsOperand(Out, MD, TypePrinter, Machine, Context);
    1525             : }
    1526             : 
    1527             : template <class IntTy>
    1528       70013 : void MDFieldPrinter::printInt(StringRef Name, IntTy Int, bool ShouldSkipZero) {
    1529       70013 :   if (ShouldSkipZero && !Int)
    1530             :     return;
    1531             : 
    1532       69968 :   Out << FS << Name << ": " << Int;
    1533             : }
    1534             : 
    1535       15793 : void MDFieldPrinter::printBool(StringRef Name, bool Value,
    1536             :                                Optional<bool> Default) {
    1537       15793 :   if (Default && Value == *Default)
    1538             :     return;
    1539       25342 :   Out << FS << Name << ": " << (Value ? "true" : "false");
    1540             : }
    1541             : 
    1542       13956 : void MDFieldPrinter::printDIFlags(StringRef Name, DINode::DIFlags Flags) {
    1543       13956 :   if (!Flags)
    1544        7407 :     return;
    1545             : 
    1546       13098 :   Out << FS << Name << ": ";
    1547             : 
    1548             :   SmallVector<DINode::DIFlags, 8> SplitFlags;
    1549        6549 :   auto Extra = DINode::splitFlags(Flags, SplitFlags);
    1550             : 
    1551             :   FieldSeparator FlagsFS(" | ");
    1552       22721 :   for (auto F : SplitFlags) {
    1553        8086 :     auto StringF = DINode::getFlagString(F);
    1554             :     assert(!StringF.empty() && "Expected valid flag");
    1555       16172 :     Out << FlagsFS << StringF;
    1556             :   }
    1557        6549 :   if (Extra || SplitFlags.empty())
    1558           0 :     Out << FlagsFS << Extra;
    1559             : }
    1560             : 
    1561        1013 : void MDFieldPrinter::printEmissionKind(StringRef Name,
    1562             :                                        DICompileUnit::DebugEmissionKind EK) {
    1563        2026 :   Out << FS << Name << ": " << DICompileUnit::EmissionKindString(EK);
    1564        1013 : }
    1565             : 
    1566             : template <class IntTy, class Stringifier>
    1567        8635 : void MDFieldPrinter::printDwarfEnum(StringRef Name, IntTy Value,
    1568             :                                     Stringifier toString, bool ShouldSkipZero) {
    1569        8635 :   if (!Value)
    1570        6464 :     return;
    1571             : 
    1572        4342 :   Out << FS << Name << ": ";
    1573        2171 :   auto S = toString(Value);
    1574        2171 :   if (!S.empty())
    1575        2171 :     Out << S;
    1576             :   else
    1577           0 :     Out << Value;
    1578             : }
    1579             : 
    1580          20 : static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N,
    1581             :                                TypePrinting *TypePrinter, SlotTracker *Machine,
    1582             :                                const Module *Context) {
    1583          20 :   Out << "!GenericDINode(";
    1584             :   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
    1585          20 :   Printer.printTag(N);
    1586          20 :   Printer.printString("header", N->getHeader());
    1587          20 :   if (N->getNumDwarfOperands()) {
    1588           5 :     Out << Printer.FS << "operands: {";
    1589             :     FieldSeparator IFS;
    1590          35 :     for (auto &I : N->dwarf_operands()) {
    1591             :       Out << IFS;
    1592          15 :       writeMetadataAsOperand(Out, I, TypePrinter, Machine, Context);
    1593             :     }
    1594           5 :     Out << "}";
    1595             :   }
    1596          20 :   Out << ")";
    1597          20 : }
    1598             : 
    1599        9834 : static void writeDILocation(raw_ostream &Out, const DILocation *DL,
    1600             :                             TypePrinting *TypePrinter, SlotTracker *Machine,
    1601             :                             const Module *Context) {
    1602        9834 :   Out << "!DILocation(";
    1603             :   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
    1604             :   // Always output the line, since 0 is a relevant and important value for it.
    1605        9834 :   Printer.printInt("line", DL->getLine(), /* ShouldSkipZero */ false);
    1606        9834 :   Printer.printInt("column", DL->getColumn());
    1607        9834 :   Printer.printMetadata("scope", DL->getRawScope(), /* ShouldSkipNull */ false);
    1608        9834 :   Printer.printMetadata("inlinedAt", DL->getRawInlinedAt());
    1609        9834 :   Out << ")";
    1610        9834 : }
    1611             : 
    1612         273 : static void writeDISubrange(raw_ostream &Out, const DISubrange *N,
    1613             :                             TypePrinting *TypePrinter, SlotTracker *Machine,
    1614             :                             const Module *Context) {
    1615         273 :   Out << "!DISubrange(";
    1616             :   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
    1617         546 :   if (auto *CE = N->getCount().dyn_cast<ConstantInt*>())
    1618         256 :     Printer.printInt("count", CE->getSExtValue(), /* ShouldSkipZero */ false);
    1619             :   else
    1620          34 :     Printer.printMetadata("count", N->getCount().dyn_cast<DIVariable*>(),
    1621             :                           /*ShouldSkipNull */ false);
    1622         273 :   Printer.printInt("lowerBound", N->getLowerBound());
    1623         273 :   Out << ")";
    1624         273 : }
    1625             : 
    1626          87 : static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N,
    1627             :                               TypePrinting *, SlotTracker *, const Module *) {
    1628          87 :   Out << "!DIEnumerator(";
    1629             :   MDFieldPrinter Printer(Out);
    1630          87 :   Printer.printString("name", N->getName(), /* ShouldSkipEmpty */ false);
    1631          87 :   if (N->isUnsigned()) {
    1632          31 :     auto Value = static_cast<uint64_t>(N->getValue());
    1633          31 :     Printer.printInt("value", Value, /* ShouldSkipZero */ false);
    1634          31 :     Printer.printBool("isUnsigned", true);
    1635             :   } else {
    1636          56 :     Printer.printInt("value", N->getValue(), /* ShouldSkipZero */ false);
    1637             :   }
    1638          87 :   Out << ")";
    1639          87 : }
    1640             : 
    1641         952 : static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N,
    1642             :                              TypePrinting *, SlotTracker *, const Module *) {
    1643         952 :   Out << "!DIBasicType(";
    1644             :   MDFieldPrinter Printer(Out);
    1645         952 :   if (N->getTag() != dwarf::DW_TAG_base_type)
    1646           7 :     Printer.printTag(N);
    1647         952 :   Printer.printString("name", N->getName());
    1648         952 :   Printer.printInt("size", N->getSizeInBits());
    1649         952 :   Printer.printInt("align", N->getAlignInBits());
    1650         952 :   Printer.printDwarfEnum("encoding", N->getEncoding(),
    1651             :                          dwarf::AttributeEncodingString);
    1652         952 :   Out << ")";
    1653         952 : }
    1654             : 
    1655        3164 : static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N,
    1656             :                                TypePrinting *TypePrinter, SlotTracker *Machine,
    1657             :                                const Module *Context) {
    1658        3164 :   Out << "!DIDerivedType(";
    1659             :   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
    1660        3164 :   Printer.printTag(N);
    1661        3164 :   Printer.printString("name", N->getName());
    1662        3164 :   Printer.printMetadata("scope", N->getRawScope());
    1663        3164 :   Printer.printMetadata("file", N->getRawFile());
    1664        3164 :   Printer.printInt("line", N->getLine());
    1665        3164 :   Printer.printMetadata("baseType", N->getRawBaseType(),
    1666             :                         /* ShouldSkipNull */ false);
    1667        3164 :   Printer.printInt("size", N->getSizeInBits());
    1668        3164 :   Printer.printInt("align", N->getAlignInBits());
    1669        3164 :   Printer.printInt("offset", N->getOffsetInBits());
    1670        3164 :   Printer.printDIFlags("flags", N->getFlags());
    1671        3164 :   Printer.printMetadata("extraData", N->getRawExtraData());
    1672        3164 :   if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
    1673          24 :     Printer.printInt("dwarfAddressSpace", *DWARFAddressSpace,
    1674             :                      /* ShouldSkipZero */ false);
    1675        3164 :   Out << ")";
    1676        3164 : }
    1677             : 
    1678        1475 : static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N,
    1679             :                                  TypePrinting *TypePrinter,
    1680             :                                  SlotTracker *Machine, const Module *Context) {
    1681        1475 :   Out << "!DICompositeType(";
    1682             :   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
    1683        1475 :   Printer.printTag(N);
    1684        1475 :   Printer.printString("name", N->getName());
    1685        1475 :   Printer.printMetadata("scope", N->getRawScope());
    1686        1475 :   Printer.printMetadata("file", N->getRawFile());
    1687        1475 :   Printer.printInt("line", N->getLine());
    1688        1475 :   Printer.printMetadata("baseType", N->getRawBaseType());
    1689        1475 :   Printer.printInt("size", N->getSizeInBits());
    1690        1475 :   Printer.printInt("align", N->getAlignInBits());
    1691        1475 :   Printer.printInt("offset", N->getOffsetInBits());
    1692        1475 :   Printer.printDIFlags("flags", N->getFlags());
    1693        1475 :   Printer.printMetadata("elements", N->getRawElements());
    1694        1475 :   Printer.printDwarfEnum("runtimeLang", N->getRuntimeLang(),
    1695             :                          dwarf::LanguageString);
    1696        1475 :   Printer.printMetadata("vtableHolder", N->getRawVTableHolder());
    1697        1475 :   Printer.printMetadata("templateParams", N->getRawTemplateParams());
    1698        1475 :   Printer.printString("identifier", N->getIdentifier());
    1699        1475 :   Printer.printMetadata("discriminator", N->getRawDiscriminator());
    1700        1475 :   Out << ")";
    1701        1475 : }
    1702             : 
    1703        1737 : static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N,
    1704             :                                   TypePrinting *TypePrinter,
    1705             :                                   SlotTracker *Machine, const Module *Context) {
    1706        1737 :   Out << "!DISubroutineType(";
    1707             :   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
    1708        1737 :   Printer.printDIFlags("flags", N->getFlags());
    1709        3474 :   Printer.printDwarfEnum("cc", N->getCC(), dwarf::ConventionString);
    1710        1737 :   Printer.printMetadata("types", N->getRawTypeArray(),
    1711             :                         /* ShouldSkipNull */ false);
    1712        1737 :   Out << ")";
    1713        1737 : }
    1714             : 
    1715        1481 : static void writeDIFile(raw_ostream &Out, const DIFile *N, TypePrinting *,
    1716             :                         SlotTracker *, const Module *) {
    1717        1481 :   Out << "!DIFile(";
    1718             :   MDFieldPrinter Printer(Out);
    1719        1481 :   Printer.printString("filename", N->getFilename(),
    1720             :                       /* ShouldSkipEmpty */ false);
    1721        1481 :   Printer.printString("directory", N->getDirectory(),
    1722             :                       /* ShouldSkipEmpty */ false);
    1723             :   // Print all values for checksum together, or not at all.
    1724        1481 :   if (N->getChecksum())
    1725          51 :     Printer.printChecksum(*N->getChecksum());
    1726        1481 :   Out << ")";
    1727        1481 : }
    1728             : 
    1729        1013 : static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N,
    1730             :                                TypePrinting *TypePrinter, SlotTracker *Machine,
    1731             :                                const Module *Context) {
    1732        1013 :   Out << "!DICompileUnit(";
    1733             :   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
    1734        1013 :   Printer.printDwarfEnum("language", N->getSourceLanguage(),
    1735             :                          dwarf::LanguageString, /* ShouldSkipZero */ false);
    1736        1013 :   Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
    1737        1013 :   Printer.printString("producer", N->getProducer());
    1738        2026 :   Printer.printBool("isOptimized", N->isOptimized());
    1739        1013 :   Printer.printString("flags", N->getFlags());
    1740        1013 :   Printer.printInt("runtimeVersion", N->getRuntimeVersion(),
    1741             :                    /* ShouldSkipZero */ false);
    1742        1013 :   Printer.printString("splitDebugFilename", N->getSplitDebugFilename());
    1743        1013 :   Printer.printEmissionKind("emissionKind", N->getEmissionKind());
    1744        1013 :   Printer.printMetadata("enums", N->getRawEnumTypes());
    1745        1013 :   Printer.printMetadata("retainedTypes", N->getRawRetainedTypes());
    1746        1013 :   Printer.printMetadata("globals", N->getRawGlobalVariables());
    1747        1013 :   Printer.printMetadata("imports", N->getRawImportedEntities());
    1748        1013 :   Printer.printMetadata("macros", N->getRawMacros());
    1749        1013 :   Printer.printInt("dwoId", N->getDWOId());
    1750        2026 :   Printer.printBool("splitDebugInlining", N->getSplitDebugInlining(), true);
    1751        2026 :   Printer.printBool("debugInfoForProfiling", N->getDebugInfoForProfiling(),
    1752             :                     false);
    1753        2026 :   Printer.printBool("gnuPubnames", N->getGnuPubnames(), false);
    1754        1013 :   Out << ")";
    1755        1013 : }
    1756             : 
    1757        3458 : static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N,
    1758             :                               TypePrinting *TypePrinter, SlotTracker *Machine,
    1759             :                               const Module *Context) {
    1760        3458 :   Out << "!DISubprogram(";
    1761             :   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
    1762        3458 :   Printer.printString("name", N->getName());
    1763        3458 :   Printer.printString("linkageName", N->getLinkageName());
    1764        3458 :   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
    1765        3458 :   Printer.printMetadata("file", N->getRawFile());
    1766        3458 :   Printer.printInt("line", N->getLine());
    1767        3458 :   Printer.printMetadata("type", N->getRawType());
    1768        6916 :   Printer.printBool("isLocal", N->isLocalToUnit());
    1769        6916 :   Printer.printBool("isDefinition", N->isDefinition());
    1770        3458 :   Printer.printInt("scopeLine", N->getScopeLine());
    1771        3458 :   Printer.printMetadata("containingType", N->getRawContainingType());
    1772        3458 :   Printer.printDwarfEnum("virtuality", N->getVirtuality(),
    1773             :                          dwarf::VirtualityString);
    1774        3458 :   if (N->getVirtuality() != dwarf::DW_VIRTUALITY_none ||
    1775             :       N->getVirtualIndex() != 0)
    1776         202 :     Printer.printInt("virtualIndex", N->getVirtualIndex(), false);
    1777        3458 :   Printer.printInt("thisAdjustment", N->getThisAdjustment());
    1778        3458 :   Printer.printDIFlags("flags", N->getFlags());
    1779        6916 :   Printer.printBool("isOptimized", N->isOptimized());
    1780        3458 :   Printer.printMetadata("unit", N->getRawUnit());
    1781        3458 :   Printer.printMetadata("templateParams", N->getRawTemplateParams());
    1782        3458 :   Printer.printMetadata("declaration", N->getRawDeclaration());
    1783        3458 :   Printer.printMetadata("variables", N->getRawVariables());
    1784        3458 :   Printer.printMetadata("thrownTypes", N->getRawThrownTypes());
    1785        3458 :   Out << ")";
    1786        3458 : }
    1787             : 
    1788         769 : static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N,
    1789             :                                 TypePrinting *TypePrinter, SlotTracker *Machine,
    1790             :                                 const Module *Context) {
    1791         769 :   Out << "!DILexicalBlock(";
    1792             :   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
    1793         769 :   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
    1794         769 :   Printer.printMetadata("file", N->getRawFile());
    1795         769 :   Printer.printInt("line", N->getLine());
    1796         769 :   Printer.printInt("column", N->getColumn());
    1797         769 :   Out << ")";
    1798         769 : }
    1799             : 
    1800         221 : static void writeDILexicalBlockFile(raw_ostream &Out,
    1801             :                                     const DILexicalBlockFile *N,
    1802             :                                     TypePrinting *TypePrinter,
    1803             :                                     SlotTracker *Machine,
    1804             :                                     const Module *Context) {
    1805         221 :   Out << "!DILexicalBlockFile(";
    1806             :   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
    1807         221 :   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
    1808         221 :   Printer.printMetadata("file", N->getRawFile());
    1809         221 :   Printer.printInt("discriminator", N->getDiscriminator(),
    1810             :                    /* ShouldSkipZero */ false);
    1811         221 :   Out << ")";
    1812         221 : }
    1813             : 
    1814         104 : static void writeDINamespace(raw_ostream &Out, const DINamespace *N,
    1815             :                              TypePrinting *TypePrinter, SlotTracker *Machine,
    1816             :                              const Module *Context) {
    1817         104 :   Out << "!DINamespace(";
    1818             :   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
    1819         104 :   Printer.printString("name", N->getName());
    1820         104 :   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
    1821         208 :   Printer.printBool("exportSymbols", N->getExportSymbols(), false);
    1822         104 :   Out << ")";
    1823         104 : }
    1824             : 
    1825        1073 : static void writeDIMacro(raw_ostream &Out, const DIMacro *N,
    1826             :                          TypePrinting *TypePrinter, SlotTracker *Machine,
    1827             :                          const Module *Context) {
    1828        1073 :   Out << "!DIMacro(";
    1829             :   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
    1830        1073 :   Printer.printMacinfoType(N);
    1831        1073 :   Printer.printInt("line", N->getLine());
    1832        1073 :   Printer.printString("name", N->getName());
    1833        1073 :   Printer.printString("value", N->getValue());
    1834        1073 :   Out << ")";
    1835        1073 : }
    1836             : 
    1837          35 : static void writeDIMacroFile(raw_ostream &Out, const DIMacroFile *N,
    1838             :                              TypePrinting *TypePrinter, SlotTracker *Machine,
    1839             :                              const Module *Context) {
    1840          35 :   Out << "!DIMacroFile(";
    1841             :   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
    1842          35 :   Printer.printInt("line", N->getLine());
    1843          35 :   Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
    1844          35 :   Printer.printMetadata("nodes", N->getRawElements());
    1845          35 :   Out << ")";
    1846          35 : }
    1847             : 
    1848          37 : static void writeDIModule(raw_ostream &Out, const DIModule *N,
    1849             :                           TypePrinting *TypePrinter, SlotTracker *Machine,
    1850             :                           const Module *Context) {
    1851          37 :   Out << "!DIModule(";
    1852             :   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
    1853          37 :   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
    1854          37 :   Printer.printString("name", N->getName());
    1855          37 :   Printer.printString("configMacros", N->getConfigurationMacros());
    1856          37 :   Printer.printString("includePath", N->getIncludePath());
    1857          37 :   Printer.printString("isysroot", N->getISysRoot());
    1858          37 :   Out << ")";
    1859          37 : }
    1860             : 
    1861             : 
    1862         147 : static void writeDITemplateTypeParameter(raw_ostream &Out,
    1863             :                                          const DITemplateTypeParameter *N,
    1864             :                                          TypePrinting *TypePrinter,
    1865             :                                          SlotTracker *Machine,
    1866             :                                          const Module *Context) {
    1867         147 :   Out << "!DITemplateTypeParameter(";
    1868             :   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
    1869         147 :   Printer.printString("name", N->getName());
    1870         147 :   Printer.printMetadata("type", N->getRawType(), /* ShouldSkipNull */ false);
    1871         147 :   Out << ")";
    1872         147 : }
    1873             : 
    1874         268 : static void writeDITemplateValueParameter(raw_ostream &Out,
    1875             :                                           const DITemplateValueParameter *N,
    1876             :                                           TypePrinting *TypePrinter,
    1877             :                                           SlotTracker *Machine,
    1878             :                                           const Module *Context) {
    1879         268 :   Out << "!DITemplateValueParameter(";
    1880             :   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
    1881         268 :   if (N->getTag() != dwarf::DW_TAG_template_value_parameter)
    1882          11 :     Printer.printTag(N);
    1883         268 :   Printer.printString("name", N->getName());
    1884         268 :   Printer.printMetadata("type", N->getRawType());
    1885         268 :   Printer.printMetadata("value", N->getValue(), /* ShouldSkipNull */ false);
    1886         268 :   Out << ")";
    1887         268 : }
    1888             : 
    1889         616 : static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N,
    1890             :                                   TypePrinting *TypePrinter,
    1891             :                                   SlotTracker *Machine, const Module *Context) {
    1892         616 :   Out << "!DIGlobalVariable(";
    1893             :   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
    1894         616 :   Printer.printString("name", N->getName());
    1895         616 :   Printer.printString("linkageName", N->getLinkageName());
    1896         616 :   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
    1897         616 :   Printer.printMetadata("file", N->getRawFile());
    1898         616 :   Printer.printInt("line", N->getLine());
    1899         616 :   Printer.printMetadata("type", N->getRawType());
    1900        1232 :   Printer.printBool("isLocal", N->isLocalToUnit());
    1901        1232 :   Printer.printBool("isDefinition", N->isDefinition());
    1902         616 :   Printer.printMetadata("declaration", N->getRawStaticDataMemberDeclaration());
    1903         616 :   Printer.printInt("align", N->getAlignInBits());
    1904         616 :   Out << ")";
    1905         616 : }
    1906             : 
    1907        4122 : static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N,
    1908             :                                  TypePrinting *TypePrinter,
    1909             :                                  SlotTracker *Machine, const Module *Context) {
    1910        4122 :   Out << "!DILocalVariable(";
    1911             :   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
    1912        4122 :   Printer.printString("name", N->getName());
    1913        4122 :   Printer.printInt("arg", N->getArg());
    1914        4122 :   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
    1915        4122 :   Printer.printMetadata("file", N->getRawFile());
    1916        4122 :   Printer.printInt("line", N->getLine());
    1917        4122 :   Printer.printMetadata("type", N->getRawType());
    1918        4122 :   Printer.printDIFlags("flags", N->getFlags());
    1919        4122 :   Printer.printInt("align", N->getAlignInBits());
    1920        4122 :   Out << ")";
    1921        4122 : }
    1922             : 
    1923        5408 : static void writeDIExpression(raw_ostream &Out, const DIExpression *N,
    1924             :                               TypePrinting *TypePrinter, SlotTracker *Machine,
    1925             :                               const Module *Context) {
    1926        5408 :   Out << "!DIExpression(";
    1927             :   FieldSeparator FS;
    1928        5408 :   if (N->isValid()) {
    1929       11578 :     for (auto I = N->expr_op_begin(), E = N->expr_op_end(); I != E; ++I) {
    1930         770 :       auto OpStr = dwarf::OperationEncodingString(I->getOp());
    1931             :       assert(!OpStr.empty() && "Expected valid opcode");
    1932             : 
    1933         770 :       Out << FS << OpStr;
    1934        1252 :       for (unsigned A = 0, AE = I->getNumArgs(); A != AE; ++A)
    1935         482 :         Out << FS << I->getArg(A);
    1936             :     }
    1937             :   } else {
    1938          34 :     for (const auto &I : N->getElements())
    1939          15 :       Out << FS << I;
    1940             :   }
    1941        5408 :   Out << ")";
    1942        5408 : }
    1943             : 
    1944         604 : static void writeDIGlobalVariableExpression(raw_ostream &Out,
    1945             :                                             const DIGlobalVariableExpression *N,
    1946             :                                             TypePrinting *TypePrinter,
    1947             :                                             SlotTracker *Machine,
    1948             :                                             const Module *Context) {
    1949         604 :   Out << "!DIGlobalVariableExpression(";
    1950             :   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
    1951         604 :   Printer.printMetadata("var", N->getVariable());
    1952         604 :   Printer.printMetadata("expr", N->getExpression());
    1953         604 :   Out << ")";
    1954         604 : }
    1955             : 
    1956          52 : static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N,
    1957             :                                 TypePrinting *TypePrinter, SlotTracker *Machine,
    1958             :                                 const Module *Context) {
    1959          52 :   Out << "!DIObjCProperty(";
    1960             :   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
    1961          52 :   Printer.printString("name", N->getName());
    1962          52 :   Printer.printMetadata("file", N->getRawFile());
    1963          52 :   Printer.printInt("line", N->getLine());
    1964          52 :   Printer.printString("setter", N->getSetterName());
    1965          52 :   Printer.printString("getter", N->getGetterName());
    1966          52 :   Printer.printInt("attributes", N->getAttributes());
    1967          52 :   Printer.printMetadata("type", N->getRawType());
    1968          52 :   Out << ")";
    1969          52 : }
    1970             : 
    1971          74 : static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N,
    1972             :                                   TypePrinting *TypePrinter,
    1973             :                                   SlotTracker *Machine, const Module *Context) {
    1974          74 :   Out << "!DIImportedEntity(";
    1975             :   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
    1976          74 :   Printer.printTag(N);
    1977          74 :   Printer.printString("name", N->getName());
    1978          74 :   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
    1979          74 :   Printer.printMetadata("entity", N->getRawEntity());
    1980          74 :   Printer.printMetadata("file", N->getRawFile());
    1981          74 :   Printer.printInt("line", N->getLine());
    1982          74 :   Out << ")";
    1983          74 : }
    1984             : 
    1985       86685 : static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
    1986             :                                     TypePrinting *TypePrinter,
    1987             :                                     SlotTracker *Machine,
    1988             :                                     const Module *Context) {
    1989       86685 :   if (Node->isDistinct())
    1990       15475 :     Out << "distinct ";
    1991       71210 :   else if (Node->isTemporary())
    1992           1 :     Out << "<temporary!> "; // Handle broken code.
    1993             : 
    1994       86685 :   switch (Node->getMetadataID()) {
    1995           0 :   default:
    1996           0 :     llvm_unreachable("Expected uniquable MDNode");
    1997             : #define HANDLE_MDNODE_LEAF(CLASS)                                              \
    1998             :   case Metadata::CLASS##Kind:                                                  \
    1999             :     write##CLASS(Out, cast<CLASS>(Node), TypePrinter, Machine, Context);       \
    2000             :     break;
    2001             : #include "llvm/IR/Metadata.def"
    2002             :   }
    2003       86685 : }
    2004             : 
    2005             : // Full implementation of printing a Value as an operand with support for
    2006             : // TypePrinting, etc.
    2007     4566188 : static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
    2008             :                                    TypePrinting *TypePrinter,
    2009             :                                    SlotTracker *Machine,
    2010             :                                    const Module *Context) {
    2011     4566188 :   if (V->hasName()) {
    2012     2687445 :     PrintLLVMName(Out, V);
    2013     2687445 :     return;
    2014             :   }
    2015             : 
    2016             :   const Constant *CV = dyn_cast<Constant>(V);
    2017             :   if (CV && !isa<GlobalValue>(CV)) {
    2018             :     assert(TypePrinter && "Constants require TypePrinting!");
    2019     1137920 :     WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context);
    2020     1137920 :     return;
    2021             :   }
    2022             : 
    2023             :   if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
    2024        1812 :     Out << "asm ";
    2025        1812 :     if (IA->hasSideEffects())
    2026        1119 :       Out << "sideeffect ";
    2027        1812 :     if (IA->isAlignStack())
    2028          10 :       Out << "alignstack ";
    2029             :     // We don't emit the AD_ATT dialect as it's the assumed default.
    2030        1812 :     if (IA->getDialect() == InlineAsm::AD_Intel)
    2031         148 :       Out << "inteldialect ";
    2032             :     Out << '"';
    2033        1812 :     PrintEscapedString(IA->getAsmString(), Out);
    2034        1812 :     Out << "\", \"";
    2035        1812 :     PrintEscapedString(IA->getConstraintString(), Out);
    2036             :     Out << '"';
    2037             :     return;
    2038             :   }
    2039             : 
    2040             :   if (auto *MD = dyn_cast<MetadataAsValue>(V)) {
    2041       13357 :     WriteAsOperandInternal(Out, MD->getMetadata(), TypePrinter, Machine,
    2042             :                            Context, /* FromValue */ true);
    2043       13357 :     return;
    2044             :   }
    2045             : 
    2046             :   char Prefix = '%';
    2047             :   int Slot;
    2048             :   // If we have a SlotTracker, use it.
    2049      725654 :   if (Machine) {
    2050             :     if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
    2051       26793 :       Slot = Machine->getGlobalSlot(GV);
    2052             :       Prefix = '@';
    2053             :     } else {
    2054      698479 :       Slot = Machine->getLocalSlot(V);
    2055             : 
    2056             :       // If the local value didn't succeed, then we may be referring to a value
    2057             :       // from a different function.  Translate it, as this can happen when using
    2058             :       // address of blocks.
    2059      698479 :       if (Slot == -1)
    2060        1019 :         if ((Machine = createSlotTracker(V))) {
    2061        1019 :           Slot = Machine->getLocalSlot(V);
    2062        1019 :           delete Machine;
    2063             :         }
    2064             :     }
    2065         382 :   } else if ((Machine = createSlotTracker(V))) {
    2066             :     // Otherwise, create one to get the # and then destroy it.
    2067             :     if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
    2068          22 :       Slot = Machine->getGlobalSlot(GV);
    2069             :       Prefix = '@';
    2070             :     } else {
    2071         360 :       Slot = Machine->getLocalSlot(V);
    2072             :     }
    2073         382 :     delete Machine;
    2074             :     Machine = nullptr;
    2075             :   } else {
    2076             :     Slot = -1;
    2077             :   }
    2078             : 
    2079      725654 :   if (Slot != -1)
    2080             :     Out << Prefix << Slot;
    2081             :   else
    2082           2 :     Out << "<badref>";
    2083             : }
    2084             : 
    2085      264052 : static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
    2086             :                                    TypePrinting *TypePrinter,
    2087             :                                    SlotTracker *Machine, const Module *Context,
    2088             :                                    bool FromValue) {
    2089             :   // Write DIExpressions inline when used as a value. Improves readability of
    2090             :   // debug info intrinsics.
    2091             :   if (const DIExpression *Expr = dyn_cast<DIExpression>(MD)) {
    2092        5359 :     writeDIExpression(Out, Expr, TypePrinter, Machine, Context);
    2093        5359 :     return;
    2094             :   }
    2095             : 
    2096             :   if (const MDNode *N = dyn_cast<MDNode>(MD)) {
    2097      431882 :     std::unique_ptr<SlotTracker> MachineStorage;
    2098      215941 :     if (!Machine) {
    2099           5 :       MachineStorage = make_unique<SlotTracker>(Context);
    2100             :       Machine = MachineStorage.get();
    2101             :     }
    2102      215941 :     int Slot = Machine->getMetadataSlot(N);
    2103      215941 :     if (Slot == -1)
    2104             :       // Give the pointer value instead of "badref", since this comes up all
    2105             :       // the time when debugging.
    2106          10 :       Out << "<" << N << ">";
    2107             :     else
    2108             :       Out << '!' << Slot;
    2109             :     return;
    2110             :   }
    2111             : 
    2112             :   if (const MDString *MDS = dyn_cast<MDString>(MD)) {
    2113       38118 :     Out << "!\"";
    2114       38118 :     PrintEscapedString(MDS->getString(), Out);
    2115             :     Out << '"';
    2116             :     return;
    2117             :   }
    2118             : 
    2119             :   auto *V = cast<ValueAsMetadata>(MD);
    2120             :   assert(TypePrinter && "TypePrinter required for metadata values");
    2121             :   assert((FromValue || !isa<LocalAsMetadata>(V)) &&
    2122             :          "Unexpected function-local metadata outside of value argument");
    2123             : 
    2124        4634 :   TypePrinter->print(V->getValue()->getType(), Out);
    2125             :   Out << ' ';
    2126        4634 :   WriteAsOperandInternal(Out, V->getValue(), TypePrinter, Machine, Context);
    2127             : }
    2128             : 
    2129             : namespace {
    2130             : 
    2131      121797 : class AssemblyWriter {
    2132             :   formatted_raw_ostream &Out;
    2133             :   const Module *TheModule;
    2134             :   std::unique_ptr<SlotTracker> SlotTrackerStorage;
    2135             :   SlotTracker &Machine;
    2136             :   TypePrinting TypePrinter;
    2137             :   AssemblyAnnotationWriter *AnnotationWriter;
    2138             :   SetVector<const Comdat *> Comdats;
    2139             :   bool IsForDebug;
    2140             :   bool ShouldPreserveUseListOrder;
    2141             :   UseListOrderStack UseListOrders;
    2142             :   SmallVector<StringRef, 8> MDNames;
    2143             :   /// Synchronization scope names registered with LLVMContext.
    2144             :   SmallVector<StringRef, 8> SSNs;
    2145             : 
    2146             : public:
    2147             :   /// Construct an AssemblyWriter with an external SlotTracker
    2148             :   AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, const Module *M,
    2149             :                  AssemblyAnnotationWriter *AAW, bool IsForDebug,
    2150             :                  bool ShouldPreserveUseListOrder = false);
    2151             : 
    2152             :   void printMDNodeBody(const MDNode *MD);
    2153             :   void printNamedMDNode(const NamedMDNode *NMD);
    2154             : 
    2155             :   void printModule(const Module *M);
    2156             : 
    2157             :   void writeOperand(const Value *Op, bool PrintType);
    2158             :   void writeParamOperand(const Value *Operand, AttributeSet Attrs);
    2159             :   void writeOperandBundles(ImmutableCallSite CS);
    2160             :   void writeSyncScope(const LLVMContext &Context,
    2161             :                       SyncScope::ID SSID);
    2162             :   void writeAtomic(const LLVMContext &Context,
    2163             :                    AtomicOrdering Ordering,
    2164             :                    SyncScope::ID SSID);
    2165             :   void writeAtomicCmpXchg(const LLVMContext &Context,
    2166             :                           AtomicOrdering SuccessOrdering,
    2167             :                           AtomicOrdering FailureOrdering,
    2168             :                           SyncScope::ID SSID);
    2169             : 
    2170             :   void writeAllMDNodes();
    2171             :   void writeMDNode(unsigned Slot, const MDNode *Node);
    2172             :   void writeAllAttributeGroups();
    2173             : 
    2174             :   void printTypeIdentities();
    2175             :   void printGlobal(const GlobalVariable *GV);
    2176             :   void printIndirectSymbol(const GlobalIndirectSymbol *GIS);
    2177             :   void printComdat(const Comdat *C);
    2178             :   void printFunction(const Function *F);
    2179             :   void printArgument(const Argument *FA, AttributeSet Attrs);
    2180             :   void printBasicBlock(const BasicBlock *BB);
    2181             :   void printInstructionLine(const Instruction &I);
    2182             :   void printInstruction(const Instruction &I);
    2183             : 
    2184             :   void printUseListOrder(const UseListOrder &Order);
    2185             :   void printUseLists(const Function *F);
    2186             : 
    2187             : private:
    2188             :   /// \brief Print out metadata attachments.
    2189             :   void printMetadataAttachments(
    2190             :       const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
    2191             :       StringRef Separator);
    2192             : 
    2193             :   // printInfoComment - Print a little comment after the instruction indicating
    2194             :   // which slot it occupies.
    2195             :   void printInfoComment(const Value &V);
    2196             : 
    2197             :   // printGCRelocateComment - print comment after call to the gc.relocate
    2198             :   // intrinsic indicating base and derived pointer names.
    2199             :   void printGCRelocateComment(const GCRelocateInst &Relocate);
    2200             : };
    2201             : 
    2202             : } // end anonymous namespace
    2203             : 
    2204       40599 : AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
    2205             :                                const Module *M, AssemblyAnnotationWriter *AAW,
    2206       40599 :                                bool IsForDebug, bool ShouldPreserveUseListOrder)
    2207             :     : Out(o), TheModule(M), Machine(Mac), AnnotationWriter(AAW),
    2208             :       IsForDebug(IsForDebug),
    2209      162396 :       ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
    2210       40599 :   if (!TheModule)
    2211             :     return;
    2212       40561 :   TypePrinter.incorporateTypes(*TheModule);
    2213       40561 :   for (const GlobalObject &GO : TheModule->global_objects())
    2214     1110684 :     if (const Comdat *C = GO.getComdat())
    2215       27390 :       Comdats.insert(C);
    2216             : }
    2217             : 
    2218     3072406 : void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
    2219     3072406 :   if (!Operand) {
    2220           0 :     Out << "<null operand!>";
    2221           0 :     return;
    2222             :   }
    2223     3072406 :   if (PrintType) {
    2224     1655262 :     TypePrinter.print(Operand->getType(), Out);
    2225     1655262 :     Out << ' ';
    2226             :   }
    2227     3072406 :   WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
    2228             : }
    2229             : 
    2230        3487 : void AssemblyWriter::writeSyncScope(const LLVMContext &Context,
    2231             :                                     SyncScope::ID SSID) {
    2232        3487 :   switch (SSID) {
    2233             :   case SyncScope::System: {
    2234             :     break;
    2235             :   }
    2236         419 :   default: {
    2237         419 :     if (SSNs.empty())
    2238          38 :       Context.getSyncScopeNames(SSNs);
    2239             : 
    2240         419 :     Out << " syncscope(\"";
    2241         838 :     PrintEscapedString(SSNs[SSID], Out);
    2242         419 :     Out << "\")";
    2243         419 :     break;
    2244             :   }
    2245             :   }
    2246        3487 : }
    2247             : 
    2248        2811 : void AssemblyWriter::writeAtomic(const LLVMContext &Context,
    2249             :                                  AtomicOrdering Ordering,
    2250             :                                  SyncScope::ID SSID) {
    2251        2811 :   if (Ordering == AtomicOrdering::NotAtomic)
    2252             :     return;
    2253             : 
    2254        2811 :   writeSyncScope(Context, SSID);
    2255        5622 :   Out << " " << toIRString(Ordering);
    2256             : }
    2257             : 
    2258         676 : void AssemblyWriter::writeAtomicCmpXchg(const LLVMContext &Context,
    2259             :                                         AtomicOrdering SuccessOrdering,
    2260             :                                         AtomicOrdering FailureOrdering,
    2261             :                                         SyncScope::ID SSID) {
    2262             :   assert(SuccessOrdering != AtomicOrdering::NotAtomic &&
    2263             :          FailureOrdering != AtomicOrdering::NotAtomic);
    2264             : 
    2265         676 :   writeSyncScope(Context, SSID);
    2266        1352 :   Out << " " << toIRString(SuccessOrdering);
    2267        1352 :   Out << " " << toIRString(FailureOrdering);
    2268         676 : }
    2269             : 
    2270      374880 : void AssemblyWriter::writeParamOperand(const Value *Operand,
    2271             :                                        AttributeSet Attrs) {
    2272      374880 :   if (!Operand) {
    2273           0 :     Out << "<null operand!>";
    2274           0 :     return;
    2275             :   }
    2276             : 
    2277             :   // Print the type
    2278      374880 :   TypePrinter.print(Operand->getType(), Out);
    2279             :   // Print parameter attributes list
    2280      374880 :   if (Attrs.hasAttributes())
    2281       80742 :     Out << ' ' << Attrs.getAsString();
    2282      374880 :   Out << ' ';
    2283             :   // Print the operand
    2284      374880 :   WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
    2285             : }
    2286             : 
    2287      168037 : void AssemblyWriter::writeOperandBundles(ImmutableCallSite CS) {
    2288      168037 :   if (!CS.hasOperandBundles())
    2289             :     return;
    2290             : 
    2291         918 :   Out << " [ ";
    2292             : 
    2293             :   bool FirstBundle = true;
    2294        1915 :   for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
    2295         997 :     OperandBundleUse BU = CS.getOperandBundleAt(i);
    2296             : 
    2297         997 :     if (!FirstBundle)
    2298          79 :       Out << ", ";
    2299             :     FirstBundle = false;
    2300             : 
    2301         997 :     Out << '"';
    2302        1994 :     PrintEscapedString(BU.getTagName(), Out);
    2303         997 :     Out << '"';
    2304             : 
    2305         997 :     Out << '(';
    2306             : 
    2307             :     bool FirstInput = true;
    2308        2897 :     for (const auto &Input : BU.Inputs) {
    2309         950 :       if (!FirstInput)
    2310         301 :         Out << ", ";
    2311             :       FirstInput = false;
    2312             : 
    2313         950 :       TypePrinter.print(Input->getType(), Out);
    2314         950 :       Out << " ";
    2315         950 :       WriteAsOperandInternal(Out, Input, &TypePrinter, &Machine, TheModule);
    2316             :     }
    2317             : 
    2318         997 :     Out << ')';
    2319             :   }
    2320             : 
    2321         918 :   Out << " ]";
    2322             : }
    2323             : 
    2324       15445 : void AssemblyWriter::printModule(const Module *M) {
    2325       15445 :   Machine.initialize();
    2326             : 
    2327       15445 :   if (ShouldPreserveUseListOrder)
    2328        1492 :     UseListOrders = predictUseListOrder(M);
    2329             : 
    2330       30890 :   if (!M->getModuleIdentifier().empty() &&
    2331             :       // Don't print the ID if it will start a new line (which would
    2332             :       // require a comment char before it).
    2333       15445 :       M->getModuleIdentifier().find('\n') == std::string::npos)
    2334       30890 :     Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
    2335             : 
    2336       15445 :   if (!M->getSourceFileName().empty()) {
    2337       15445 :     Out << "source_filename = \"";
    2338       30890 :     PrintEscapedString(M->getSourceFileName(), Out);
    2339       15445 :     Out << "\"\n";
    2340             :   }
    2341             : 
    2342             :   const std::string &DL = M->getDataLayoutStr();
    2343       15445 :   if (!DL.empty())
    2344       22146 :     Out << "target datalayout = \"" << DL << "\"\n";
    2345       15445 :   if (!M->getTargetTriple().empty())
    2346       20568 :     Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
    2347             : 
    2348       15445 :   if (!M->getModuleInlineAsm().empty()) {
    2349         102 :     Out << '\n';
    2350             : 
    2351             :     // Split the string into lines, to make it easier to read the .ll file.
    2352             :     StringRef Asm = M->getModuleInlineAsm();
    2353             :     do {
    2354             :       StringRef Front;
    2355         650 :       std::tie(Front, Asm) = Asm.split('\n');
    2356             : 
    2357             :       // We found a newline, print the portion of the asm string from the
    2358             :       // last newline up to this newline.
    2359         325 :       Out << "module asm \"";
    2360         325 :       PrintEscapedString(Front, Out);
    2361         325 :       Out << "\"\n";
    2362         325 :     } while (!Asm.empty());
    2363             :   }
    2364             : 
    2365       15445 :   printTypeIdentities();
    2366             : 
    2367             :   // Output all comdats.
    2368       15445 :   if (!Comdats.empty())
    2369        2833 :     Out << '\n';
    2370       39748 :   for (const Comdat *C : Comdats) {
    2371             :     printComdat(C);
    2372       24303 :     if (C != Comdats.back())
    2373       21470 :       Out << '\n';
    2374             :   }
    2375             : 
    2376             :   // Output all globals.
    2377       15445 :   if (!M->global_empty()) Out << '\n';
    2378       94867 :   for (const GlobalVariable &GV : M->globals()) {
    2379       79422 :     printGlobal(&GV); Out << '\n';
    2380             :   }
    2381             : 
    2382             :   // Output all aliases.
    2383       15445 :   if (!M->alias_empty()) Out << "\n";
    2384       16535 :   for (const GlobalAlias &GA : M->aliases())
    2385        1090 :     printIndirectSymbol(&GA);
    2386             : 
    2387             :   // Output all ifuncs.
    2388       15445 :   if (!M->ifunc_empty()) Out << "\n";
    2389       15516 :   for (const GlobalIFunc &GI : M->ifuncs())
    2390          71 :     printIndirectSymbol(&GI);
    2391             : 
    2392             :   // Output global use-lists.
    2393       15445 :   printUseLists(nullptr);
    2394             : 
    2395             :   // Output all of the functions.
    2396      203643 :   for (const Function &F : *M)
    2397      188198 :     printFunction(&F);
    2398             :   assert(UseListOrders.empty() && "All use-lists should have been consumed");
    2399             : 
    2400             :   // Output all attribute groups.
    2401       15445 :   if (!Machine.as_empty()) {
    2402       10989 :     Out << '\n';
    2403       10989 :     writeAllAttributeGroups();
    2404             :   }
    2405             : 
    2406             :   // Output named metadata.
    2407       15445 :   if (!M->named_metadata_empty()) Out << '\n';
    2408             : 
    2409       34185 :   for (const NamedMDNode &Node : M->named_metadata())
    2410       18740 :     printNamedMDNode(&Node);
    2411             : 
    2412             :   // Output metadata.
    2413       15445 :   if (!Machine.mdn_empty()) {
    2414        9597 :     Out << '\n';
    2415        9597 :     writeAllMDNodes();
    2416             :   }
    2417       15445 : }
    2418             : 
    2419      135922 : static void printMetadataIdentifier(StringRef Name,
    2420             :                                     formatted_raw_ostream &Out) {
    2421      135922 :   if (Name.empty()) {
    2422           1 :     Out << "<empty name> ";
    2423             :   } else {
    2424      135949 :     if (isalpha(static_cast<unsigned char>(Name[0])) || Name[0] == '-' ||
    2425      135949 :         Name[0] == '$' || Name[0] == '.' || Name[0] == '_')
    2426      135895 :       Out << Name[0];
    2427             :     else
    2428          78 :       Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F);
    2429     1516104 :     for (unsigned i = 1, e = Name.size(); i != e; ++i) {
    2430     2760366 :       unsigned char C = Name[i];
    2431     1380183 :       if (isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' ||
    2432      151683 :           C == '.' || C == '_')
    2433     1380178 :         Out << C;
    2434             :       else
    2435          15 :         Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
    2436             :     }
    2437             :   }
    2438      135922 : }
    2439             : 
    2440       18747 : void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
    2441       18747 :   Out << '!';
    2442       18747 :   printMetadataIdentifier(NMD->getName(), Out);
    2443       18747 :   Out << " = !{";
    2444       48755 :   for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
    2445       30008 :     if (i)
    2446       11327 :       Out << ", ";
    2447             : 
    2448             :     // Write DIExpressions inline.
    2449             :     // FIXME: Ban DIExpressions in NamedMDNodes, they will serve no purpose.
    2450       30008 :     MDNode *Op = NMD->getOperand(i);
    2451          49 :     if (auto *Expr = dyn_cast<DIExpression>(Op)) {
    2452          49 :       writeDIExpression(Out, Expr, nullptr, nullptr, nullptr);
    2453             :       continue;
    2454             :     }
    2455             : 
    2456       29959 :     int Slot = Machine.getMetadataSlot(Op);
    2457       29959 :     if (Slot == -1)
    2458           0 :       Out << "<badref>";
    2459             :     else
    2460       29959 :       Out << '!' << Slot;
    2461             :   }
    2462       18747 :   Out << "}\n";
    2463       18747 : }
    2464             : 
    2465      269136 : static const char *getLinkagePrintName(GlobalValue::LinkageTypes LT) {
    2466      269136 :   switch (LT) {
    2467             :   case GlobalValue::ExternalLinkage:
    2468             :     return "";
    2469       27226 :   case GlobalValue::PrivateLinkage:
    2470       27226 :     return "private ";
    2471       32503 :   case GlobalValue::InternalLinkage:
    2472       32503 :     return "internal ";
    2473        1015 :   case GlobalValue::LinkOnceAnyLinkage:
    2474        1015 :     return "linkonce ";
    2475       25203 :   case GlobalValue::LinkOnceODRLinkage:
    2476       25203 :     return "linkonce_odr ";
    2477         635 :   case GlobalValue::WeakAnyLinkage:
    2478         635 :     return "weak ";
    2479        2599 :   case GlobalValue::WeakODRLinkage:
    2480        2599 :     return "weak_odr ";
    2481        4226 :   case GlobalValue::CommonLinkage:
    2482        4226 :     return "common ";
    2483        2736 :   case GlobalValue::AppendingLinkage:
    2484        2736 :     return "appending ";
    2485         504 :   case GlobalValue::ExternalWeakLinkage:
    2486         504 :     return "extern_weak ";
    2487         636 :   case GlobalValue::AvailableExternallyLinkage:
    2488         636 :     return "available_externally ";
    2489             :   }
    2490           0 :   llvm_unreachable("invalid linkage");
    2491             : }
    2492             : 
    2493      269136 : static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
    2494             :                             formatted_raw_ostream &Out) {
    2495      269136 :   switch (Vis) {
    2496             :   case GlobalValue::DefaultVisibility: break;
    2497        4424 :   case GlobalValue::HiddenVisibility:    Out << "hidden "; break;
    2498          62 :   case GlobalValue::ProtectedVisibility: Out << "protected "; break;
    2499             :   }
    2500      269136 : }
    2501             : 
    2502      269136 : static void PrintDSOLocation(const GlobalValue &GV,
    2503             :                              formatted_raw_ostream &Out) {
    2504             :   // GVs with local linkage or non default visibility are implicitly dso_local,
    2505             :   // so we don't print it.
    2506      209407 :   bool Implicit = GV.hasLocalLinkage() ||
    2507      208903 :                   (!GV.hasExternalWeakLinkage() && !GV.hasDefaultVisibility());
    2508      269136 :   if (GV.isDSOLocal() && !Implicit)
    2509         730 :     Out << "dso_local ";
    2510      269136 : }
    2511             : 
    2512      269136 : static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT,
    2513             :                                  formatted_raw_ostream &Out) {
    2514      269136 :   switch (SCT) {
    2515             :   case GlobalValue::DefaultStorageClass: break;
    2516        1673 :   case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break;
    2517        2586 :   case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break;
    2518             :   }
    2519      269136 : }
    2520             : 
    2521       80592 : static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM,
    2522             :                                   formatted_raw_ostream &Out) {
    2523       80592 :   switch (TLM) {
    2524             :     case GlobalVariable::NotThreadLocal:
    2525             :       break;
    2526         347 :     case GlobalVariable::GeneralDynamicTLSModel:
    2527         347 :       Out << "thread_local ";
    2528         347 :       break;
    2529          31 :     case GlobalVariable::LocalDynamicTLSModel:
    2530          31 :       Out << "thread_local(localdynamic) ";
    2531          31 :       break;
    2532         683 :     case GlobalVariable::InitialExecTLSModel:
    2533         683 :       Out << "thread_local(initialexec) ";
    2534         683 :       break;
    2535          30 :     case GlobalVariable::LocalExecTLSModel:
    2536          30 :       Out << "thread_local(localexec) ";
    2537          30 :       break;
    2538             :   }
    2539       80592 : }
    2540             : 
    2541             : static StringRef getUnnamedAddrEncoding(GlobalVariable::UnnamedAddr UA) {
    2542      269136 :   switch (UA) {
    2543             :   case GlobalVariable::UnnamedAddr::None:
    2544             :     return "";
    2545             :   case GlobalVariable::UnnamedAddr::Local:
    2546             :     return "local_unnamed_addr";
    2547             :   case GlobalVariable::UnnamedAddr::Global:
    2548             :     return "unnamed_addr";
    2549             :   }
    2550           0 :   llvm_unreachable("Unknown UnnamedAddr");
    2551             : }
    2552             : 
    2553      267975 : static void maybePrintComdat(formatted_raw_ostream &Out,
    2554             :                              const GlobalObject &GO) {
    2555             :   const Comdat *C = GO.getComdat();
    2556      267975 :   if (!C)
    2557             :     return;
    2558             : 
    2559       27390 :   if (isa<GlobalVariable>(GO))
    2560        7025 :     Out << ',';
    2561       27390 :   Out << " comdat";
    2562             : 
    2563       27390 :   if (GO.getName() == C->getName())
    2564             :     return;
    2565             : 
    2566             :   Out << '(';
    2567        3378 :   PrintLLVMName(Out, C->getName(), ComdatPrefix);
    2568             :   Out << ')';
    2569             : }
    2570             : 
    2571       79431 : void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
    2572       79431 :   if (GV->isMaterializable())
    2573           0 :     Out << "; Materializable\n";
    2574             : 
    2575       79431 :   WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent());
    2576       79431 :   Out << " = ";
    2577             : 
    2578       89588 :   if (!GV->hasInitializer() && GV->hasExternalLinkage())
    2579       10054 :     Out << "external ";
    2580             : 
    2581      158862 :   Out << getLinkagePrintName(GV->getLinkage());
    2582       79431 :   PrintDSOLocation(*GV, Out);
    2583      158862 :   PrintVisibility(GV->getVisibility(), Out);
    2584      158862 :   PrintDLLStorageClass(GV->getDLLStorageClass(), Out);
    2585      158862 :   PrintThreadLocalModel(GV->getThreadLocalMode(), Out);
    2586       79431 :   StringRef UA = getUnnamedAddrEncoding(GV->getUnnamedAddr());
    2587       79431 :   if (!UA.empty())
    2588       28283 :       Out << UA << ' ';
    2589             : 
    2590       79431 :   if (unsigned AddressSpace = GV->getType()->getAddressSpace())
    2591        1866 :     Out << "addrspace(" << AddressSpace << ") ";
    2592       79431 :   if (GV->isExternallyInitialized()) Out << "externally_initialized ";
    2593      158862 :   Out << (GV->isConstant() ? "constant " : "global ");
    2594       79431 :   TypePrinter.print(GV->getValueType(), Out);
    2595             : 
    2596       79431 :   if (GV->hasInitializer()) {
    2597       69274 :     Out << ' ';
    2598       69274 :     writeOperand(GV->getInitializer(), false);
    2599             :   }
    2600             : 
    2601       79431 :   if (GV->hasSection()) {
    2602       14011 :     Out << ", section \"";
    2603       28022 :     PrintEscapedString(GV->getSection(), Out);
    2604       14011 :     Out << '"';
    2605             :   }
    2606       79431 :   maybePrintComdat(Out, *GV);
    2607       79431 :   if (GV->getAlignment())
    2608       43663 :     Out << ", align " << GV->getAlignment();
    2609             : 
    2610             :   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
    2611       79431 :   GV->getAllMetadata(MDs);
    2612       79431 :   printMetadataAttachments(MDs, ", ");
    2613             : 
    2614             :   auto Attrs = GV->getAttributes();
    2615       79431 :   if (Attrs.hasAttributes())
    2616          33 :     Out << " #" << Machine.getAttributeGroupSlot(Attrs);
    2617             : 
    2618       79431 :   printInfoComment(*GV);
    2619       79431 : }
    2620             : 
    2621        1161 : void AssemblyWriter::printIndirectSymbol(const GlobalIndirectSymbol *GIS) {
    2622        1161 :   if (GIS->isMaterializable())
    2623           0 :     Out << "; Materializable\n";
    2624             : 
    2625        1161 :   WriteAsOperandInternal(Out, GIS, &TypePrinter, &Machine, GIS->getParent());
    2626        1161 :   Out << " = ";
    2627             : 
    2628        2322 :   Out << getLinkagePrintName(GIS->getLinkage());
    2629        1161 :   PrintDSOLocation(*GIS, Out);
    2630        2322 :   PrintVisibility(GIS->getVisibility(), Out);
    2631        2322 :   PrintDLLStorageClass(GIS->getDLLStorageClass(), Out);
    2632        2322 :   PrintThreadLocalModel(GIS->getThreadLocalMode(), Out);
    2633        1161 :   StringRef UA = getUnnamedAddrEncoding(GIS->getUnnamedAddr());
    2634        1161 :   if (!UA.empty())
    2635         192 :       Out << UA << ' ';
    2636             : 
    2637        1161 :   if (isa<GlobalAlias>(GIS))
    2638        1090 :     Out << "alias ";
    2639          71 :   else if (isa<GlobalIFunc>(GIS))
    2640          71 :     Out << "ifunc ";
    2641             :   else
    2642           0 :     llvm_unreachable("Not an alias or ifunc!");
    2643             : 
    2644        1161 :   TypePrinter.print(GIS->getValueType(), Out);
    2645             : 
    2646        1161 :   Out << ", ";
    2647             : 
    2648             :   const Constant *IS = GIS->getIndirectSymbol();
    2649             : 
    2650             :   if (!IS) {
    2651           0 :     TypePrinter.print(GIS->getType(), Out);
    2652           0 :     Out << " <<NULL ALIASEE>>";
    2653             :   } else {
    2654        1161 :     writeOperand(IS, !isa<ConstantExpr>(IS));
    2655             :   }
    2656             : 
    2657        1161 :   printInfoComment(*GIS);
    2658        1161 :   Out << '\n';
    2659        1161 : }
    2660             : 
    2661             : void AssemblyWriter::printComdat(const Comdat *C) {
    2662       24303 :   C->print(Out);
    2663             : }
    2664             : 
    2665       15445 : void AssemblyWriter::printTypeIdentities() {
    2666       15445 :   if (TypePrinter.NumberedTypes.empty() &&
    2667             :       TypePrinter.NamedTypes.empty())
    2668        9712 :     return;
    2669             : 
    2670        5733 :   Out << '\n';
    2671             : 
    2672             :   // We know all the numbers that each type is used and we know that it is a
    2673             :   // dense assignment.  Convert the map to an index table.
    2674        5733 :   std::vector<StructType*> NumberedTypes(TypePrinter.NumberedTypes.size());
    2675             :   for (DenseMap<StructType*, unsigned>::iterator I =
    2676        5733 :        TypePrinter.NumberedTypes.begin(), E = TypePrinter.NumberedTypes.end();
    2677        6648 :        I != E; ++I) {
    2678             :     assert(I->second < NumberedTypes.size() && "Didn't get a dense numbering?");
    2679        1830 :     NumberedTypes[I->second] = I->first;
    2680             :   }
    2681             : 
    2682             :   // Emit all numbered types.
    2683        6648 :   for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
    2684        1830 :     Out << '%' << i << " = type ";
    2685             : 
    2686             :     // Make sure we print out at least one level of the type structure, so
    2687             :     // that we do not get %2 = type %2
    2688        1830 :     TypePrinter.printStructBody(NumberedTypes[i], Out);
    2689         915 :     Out << '\n';
    2690             :   }
    2691             : 
    2692       34301 :   for (unsigned i = 0, e = TypePrinter.NamedTypes.size(); i != e; ++i) {
    2693       28568 :     PrintLLVMName(Out, TypePrinter.NamedTypes[i]->getName(), LocalPrefix);
    2694       28568 :     Out << " = type ";
    2695             : 
    2696             :     // Make sure we print out at least one level of the type structure, so
    2697             :     // that we do not get %FILE = type %FILE
    2698       57136 :     TypePrinter.printStructBody(TypePrinter.NamedTypes[i], Out);
    2699       28568 :     Out << '\n';
    2700             :   }
    2701             : }
    2702             : 
    2703             : /// printFunction - Print all aspects of a function.
    2704      188544 : void AssemblyWriter::printFunction(const Function *F) {
    2705             :   // Print out the return type and name.
    2706      188544 :   Out << '\n';
    2707             : 
    2708      188544 :   if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
    2709             : 
    2710      188544 :   if (F->isMaterializable())
    2711           6 :     Out << "; Materializable\n";
    2712             : 
    2713      188544 :   const AttributeList &Attrs = F->getAttributes();
    2714      188544 :   if (Attrs.hasAttributes(AttributeList::FunctionIndex)) {
    2715      135382 :     AttributeSet AS = Attrs.getFnAttributes();
    2716             :     std::string AttrStr;
    2717             : 
    2718     1720304 :     for (const Attribute &Attr : AS) {
    2719     1584922 :       if (!Attr.isStringAttribute()) {
    2720      305682 :         if (!AttrStr.empty()) AttrStr += ' ';
    2721      611364 :         AttrStr += Attr.getAsString();
    2722             :       }
    2723             :     }
    2724             : 
    2725      135382 :     if (!AttrStr.empty())
    2726      126391 :       Out << "; Function Attrs: " << AttrStr << '\n';
    2727             :   }
    2728             : 
    2729      188544 :   Machine.incorporateFunction(F);
    2730             : 
    2731      188544 :   if (F->isDeclaration()) {
    2732       65172 :     Out << "declare";
    2733             :     SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
    2734       65172 :     F->getAllMetadata(MDs);
    2735       65172 :     printMetadataAttachments(MDs, " ");
    2736       65172 :     Out << ' ';
    2737             :   } else
    2738      123372 :     Out << "define ";
    2739             : 
    2740      377088 :   Out << getLinkagePrintName(F->getLinkage());
    2741      188544 :   PrintDSOLocation(*F, Out);
    2742      377088 :   PrintVisibility(F->getVisibility(), Out);
    2743      377088 :   PrintDLLStorageClass(F->getDLLStorageClass(), Out);
    2744             : 
    2745             :   // Print the calling convention.
    2746      188544 :   if (F->getCallingConv() != CallingConv::C) {
    2747        8176 :     PrintCallingConv(F->getCallingConv(), Out);
    2748        8176 :     Out << " ";
    2749             :   }
    2750             : 
    2751             :   FunctionType *FT = F->getFunctionType();
    2752      188544 :   if (Attrs.hasAttributes(AttributeList::ReturnIndex))
    2753       10582 :     Out << Attrs.getAsString(AttributeList::ReturnIndex) << ' ';
    2754      377088 :   TypePrinter.print(F->getReturnType(), Out);
    2755      188544 :   Out << ' ';
    2756      188544 :   WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
    2757      188544 :   Out << '(';
    2758             : 
    2759             :   // Loop over the arguments, printing them...
    2760      188544 :   if (F->isDeclaration() && !IsForDebug) {
    2761             :     // We're only interested in the type here - don't print argument names.
    2762      324292 :     for (unsigned I = 0, E = FT->getNumParams(); I != E; ++I) {
    2763             :       // Insert commas as we go... the first arg doesn't get a comma
    2764      129560 :       if (I)
    2765       73198 :         Out << ", ";
    2766             :       // Output type...
    2767      259120 :       TypePrinter.print(FT->getParamType(I), Out);
    2768             : 
    2769      129560 :       AttributeSet ArgAttrs = Attrs.getParamAttributes(I);
    2770      129560 :       if (ArgAttrs.hasAttributes())
    2771       23253 :         Out << ' ' << ArgAttrs.getAsString();
    2772             :     }
    2773             :   } else {
    2774             :     // The arguments are meaningful here, print them in detail.
    2775      591004 :     for (const Argument &Arg : F->args()) {
    2776             :       // Insert commas as we go... the first arg doesn't get a comma
    2777      172130 :       if (Arg.getArgNo() != 0)
    2778       79081 :         Out << ", ";
    2779      172130 :       printArgument(&Arg, Attrs.getParamAttributes(Arg.getArgNo()));
    2780             :     }
    2781             :   }
    2782             : 
    2783             :   // Finish printing arguments...
    2784      188544 :   if (FT->isVarArg()) {
    2785        4429 :     if (FT->getNumParams()) Out << ", ";
    2786        4429 :     Out << "...";  // Output varargs portion of signature!
    2787             :   }
    2788      188544 :   Out << ')';
    2789      188544 :   StringRef UA = getUnnamedAddrEncoding(F->getUnnamedAddr());
    2790      188544 :   if (!UA.empty())
    2791       49680 :     Out << ' ' << UA;
    2792      188544 :   if (Attrs.hasAttributes(AttributeList::FunctionIndex))
    2793      135382 :     Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttributes());
    2794      188544 :   if (F->hasSection()) {
    2795        1259 :     Out << " section \"";
    2796        2518 :     PrintEscapedString(F->getSection(), Out);
    2797        1259 :     Out << '"';
    2798             :   }
    2799      188544 :   maybePrintComdat(Out, *F);
    2800      188544 :   if (F->getAlignment())
    2801       22474 :     Out << " align " << F->getAlignment();
    2802      188544 :   if (F->hasGC())
    2803         408 :     Out << " gc \"" << F->getGC() << '"';
    2804      188544 :   if (F->hasPrefixData()) {
    2805          28 :     Out << " prefix ";
    2806          28 :     writeOperand(F->getPrefixData(), true);
    2807             :   }
    2808      188544 :   if (F->hasPrologueData()) {
    2809         143 :     Out << " prologue ";
    2810         143 :     writeOperand(F->getPrologueData(), true);
    2811             :   }
    2812      188544 :   if (F->hasPersonalityFn()) {
    2813        1448 :     Out << " personality ";
    2814        1448 :     writeOperand(F->getPersonalityFn(), /*PrintType=*/true);
    2815             :   }
    2816             : 
    2817      188544 :   if (F->isDeclaration()) {
    2818       65172 :     Out << '\n';
    2819             :   } else {
    2820             :     SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
    2821      123372 :     F->getAllMetadata(MDs);
    2822      123372 :     printMetadataAttachments(MDs, " ");
    2823             : 
    2824      123372 :     Out << " {";
    2825             :     // Output all of the function's basic blocks.
    2826      401332 :     for (const BasicBlock &BB : *F)
    2827      277960 :       printBasicBlock(&BB);
    2828             : 
    2829             :     // Output the function's use-lists.
    2830      123372 :     printUseLists(F);
    2831             : 
    2832      123372 :     Out << "}\n";
    2833             :   }
    2834             : 
    2835      188544 :   Machine.purgeFunction();
    2836      188544 : }
    2837             : 
    2838             : /// printArgument - This member is called for every argument that is passed into
    2839             : /// the function.  Simply print it out
    2840      172130 : void AssemblyWriter::printArgument(const Argument *Arg, AttributeSet Attrs) {
    2841             :   // Output type...
    2842      172130 :   TypePrinter.print(Arg->getType(), Out);
    2843             : 
    2844             :   // Output parameter attributes list
    2845      172130 :   if (Attrs.hasAttributes())
    2846      114642 :     Out << ' ' << Attrs.getAsString();
    2847             : 
    2848             :   // Output name, if available...
    2849      172130 :   if (Arg->hasName()) {
    2850      161050 :     Out << ' ';
    2851      161050 :     PrintLLVMName(Out, Arg);
    2852             :   }
    2853      172130 : }
    2854             : 
    2855             : /// printBasicBlock - This member is called for each basic block in a method.
    2856      277988 : void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
    2857      277988 :   if (BB->hasName()) {              // Print out the label if it exists...
    2858      253164 :     Out << "\n";
    2859      253164 :     PrintLLVMName(Out, BB->getName(), LabelPrefix);
    2860      253164 :     Out << ':';
    2861       24824 :   } else if (!BB->use_empty()) {      // Don't print block # of no uses...
    2862        2466 :     Out << "\n; <label>:";
    2863        2466 :     int Slot = Machine.getLocalSlot(BB);
    2864        2466 :     if (Slot != -1)
    2865        4932 :       Out << Slot << ":";
    2866             :     else
    2867           0 :       Out << "<badref>";
    2868             :   }
    2869             : 
    2870      277988 :   if (!BB->getParent()) {
    2871           0 :     Out.PadToColumn(50);
    2872           0 :     Out << "; Error: Block without parent!";
    2873      277988 :   } else if (BB != &BB->getParent()->getEntryBlock()) {  // Not the entry block?
    2874             :     // Output predecessors for the block.
    2875      154617 :     Out.PadToColumn(50);
    2876      154617 :     Out << ";";
    2877      154617 :     const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
    2878             : 
    2879      154617 :     if (PI == PE) {
    2880         823 :       Out << " No predecessors!";
    2881             :     } else {
    2882      153794 :       Out << " preds = ";
    2883      153794 :       writeOperand(*PI, false);
    2884      208733 :       for (++PI; PI != PE; ++PI) {
    2885       54939 :         Out << ", ";
    2886       54939 :         writeOperand(*PI, false);
    2887             :       }
    2888             :     }
    2889             :   }
    2890             : 
    2891      277988 :   Out << "\n";
    2892             : 
    2893      277988 :   if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
    2894             : 
    2895             :   // Output all of the instructions in the basic block...
    2896     2364994 :   for (const Instruction &I : *BB) {
    2897     2087006 :     printInstructionLine(I);
    2898             :   }
    2899             : 
    2900      277988 :   if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
    2901      277988 : }
    2902             : 
    2903             : /// printInstructionLine - Print an instruction and a newline character.
    2904     2087006 : void AssemblyWriter::printInstructionLine(const Instruction &I) {
    2905     2087006 :   printInstruction(I);
    2906     2087006 :   Out << '\n';
    2907     2087006 : }
    2908             : 
    2909             : /// printGCRelocateComment - print comment after call to the gc.relocate
    2910             : /// intrinsic indicating base and derived pointer names.
    2911         482 : void AssemblyWriter::printGCRelocateComment(const GCRelocateInst &Relocate) {
    2912         482 :   Out << " ; (";
    2913         482 :   writeOperand(Relocate.getBasePtr(), false);
    2914         482 :   Out << ", ";
    2915         482 :   writeOperand(Relocate.getDerivedPtr(), false);
    2916         482 :   Out << ")";
    2917         482 : }
    2918             : 
    2919             : /// printInfoComment - Print a little comment after the instruction indicating
    2920             : /// which slot it occupies.
    2921     2192362 : void AssemblyWriter::printInfoComment(const Value &V) {
    2922             :   if (const auto *Relocate = dyn_cast<GCRelocateInst>(&V))
    2923         482 :     printGCRelocateComment(*Relocate);
    2924             : 
    2925     2192362 :   if (AnnotationWriter)
    2926        1136 :     AnnotationWriter->printInfoComment(V, Out);
    2927     2192362 : }
    2928             : 
    2929             : // This member is called for each Instruction in a function..
    2930     2111770 : void AssemblyWriter::printInstruction(const Instruction &I) {
    2931     2111770 :   if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
    2932             : 
    2933             :   // Print out indentation for an instruction.
    2934     2111770 :   Out << "  ";
    2935             : 
    2936             :   // Print out name if it exists...
    2937     2111770 :   if (I.hasName()) {
    2938      704326 :     PrintLLVMName(Out, &I);
    2939      704326 :     Out << " = ";
    2940     1407444 :   } else if (!I.getType()->isVoidTy()) {
    2941             :     // Print out the def slot taken.
    2942      641533 :     int SlotNum = Machine.getLocalSlot(&I);
    2943      641533 :     if (SlotNum == -1)
    2944          38 :       Out << "<badref> = ";
    2945             :     else
    2946     1282990 :       Out << '%' << SlotNum << " = ";
    2947             :   }
    2948             : 
    2949             :   if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
    2950      165213 :     if (CI->isMustTailCall())
    2951         105 :       Out << "musttail ";
    2952      165108 :     else if (CI->isTailCall())
    2953        7577 :       Out << "tail ";
    2954      157531 :     else if (CI->isNoTailCall())
    2955          52 :       Out << "notail ";
    2956             :   }
    2957             : 
    2958             :   // Print out the opcode...
    2959     4223540 :   Out << I.getOpcodeName();
    2960             : 
    2961             :   // If this is an atomic load or store, print out the atomic marker.
    2962     2111770 :   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isAtomic()) ||
    2963      382774 :       (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
    2964        1666 :     Out << " atomic";
    2965             : 
    2966     2111770 :   if (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isWeak())
    2967          65 :     Out << " weak";
    2968             : 
    2969             :   // If this is a volatile operation, print out the volatile marker.
    2970      401622 :   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isVolatile()) ||
    2971      382774 :       (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
    2972     2112446 :       (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
    2973         919 :       (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
    2974       16979 :     Out << " volatile";
    2975             : 
    2976             :   // Print out optimization information.
    2977     2111770 :   WriteOptimizationInfo(Out, &I);
    2978             : 
    2979             :   // Print out the compare instruction predicates
    2980             :   if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
    2981      121170 :     Out << ' ' << CmpInst::getPredicateName(CI->getPredicate());
    2982             : 
    2983             :   // Print out the atomicrmw operation
    2984             :   if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
    2985         919 :     writeAtomicRMWOperation(Out, RMWI->getOperation());
    2986             : 
    2987             :   // Print out the type of the operands...
    2988     2111770 :   const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr;
    2989             : 
    2990             :   // Special case conditional branches to swizzle the condition out to the front
    2991     2111770 :   if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
    2992             :     const BranchInst &BI(cast<BranchInst>(I));
    2993       52943 :     Out << ' ';
    2994       52943 :     writeOperand(BI.getCondition(), true);
    2995       52943 :     Out << ", ";
    2996       52943 :     writeOperand(BI.getSuccessor(0), true);
    2997       52943 :     Out << ", ";
    2998       52943 :     writeOperand(BI.getSuccessor(1), true);
    2999             : 
    3000     2058827 :   } else if (isa<SwitchInst>(I)) {
    3001             :     const SwitchInst& SI(cast<SwitchInst>(I));
    3002             :     // Special case switch instruction to get formatting nice and correct.
    3003        1106 :     Out << ' ';
    3004        1106 :     writeOperand(SI.getCondition(), true);
    3005        1106 :     Out << ", ";
    3006        1106 :     writeOperand(SI.getDefaultDest(), true);
    3007        1106 :     Out << " [";
    3008        3789 :     for (auto Case : SI.cases()) {
    3009        2683 :       Out << "\n    ";
    3010        2683 :       writeOperand(Case.getCaseValue(), true);
    3011        2683 :       Out << ", ";
    3012        2683 :       writeOperand(Case.getCaseSuccessor(), true);
    3013             :     }
    3014        1106 :     Out << "\n  ]";
    3015     2057721 :   } else if (isa<IndirectBrInst>(I)) {
    3016             :     // Special case indirectbr instruction to get formatting nice and correct.
    3017         215 :     Out << ' ';
    3018         215 :     writeOperand(Operand, true);
    3019         215 :     Out << ", [";
    3020             : 
    3021        1387 :     for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
    3022         586 :       if (i != 1)
    3023         375 :         Out << ", ";
    3024         586 :       writeOperand(I.getOperand(i), true);
    3025             :     }
    3026         215 :     Out << ']';
    3027             :   } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
    3028       24046 :     Out << ' ';
    3029       24046 :     TypePrinter.print(I.getType(), Out);
    3030       24046 :     Out << ' ';
    3031             : 
    3032      120204 :     for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
    3033       48079 :       if (op) Out << ", ";
    3034       48079 :       Out << "[ ";
    3035       48079 :       writeOperand(PN->getIncomingValue(op), false); Out << ", ";
    3036       48079 :       writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
    3037             :     }
    3038             :   } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
    3039        8152 :     Out << ' ';
    3040        8152 :     writeOperand(I.getOperand(0), true);
    3041       24564 :     for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
    3042        8206 :       Out << ", " << *i;
    3043             :   } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
    3044        2551 :     Out << ' ';
    3045        2551 :     writeOperand(I.getOperand(0), true); Out << ", ";
    3046        2551 :     writeOperand(I.getOperand(1), true);
    3047        7729 :     for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
    3048        2589 :       Out << ", " << *i;
    3049             :   } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
    3050        1610 :     Out << ' ';
    3051        1610 :     TypePrinter.print(I.getType(), Out);
    3052        2423 :     if (LPI->isCleanup() || LPI->getNumClauses() != 0)
    3053        1610 :       Out << '\n';
    3054             : 
    3055        1610 :     if (LPI->isCleanup())
    3056         797 :       Out << "          cleanup";
    3057             : 
    3058        3478 :     for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
    3059         934 :       if (i != 0 || LPI->isCleanup()) Out << "\n";
    3060         934 :       if (LPI->isCatch(i))
    3061         877 :         Out << "          catch ";
    3062             :       else
    3063          57 :         Out << "          filter ";
    3064             : 
    3065         934 :       writeOperand(LPI->getClause(i), true);
    3066             :     }
    3067             :   } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(&I)) {
    3068         233 :     Out << " within ";
    3069         233 :     writeOperand(CatchSwitch->getParentPad(), /*PrintType=*/false);
    3070         233 :     Out << " [";
    3071             :     unsigned Op = 0;
    3072         477 :     for (const BasicBlock *PadBB : CatchSwitch->handlers()) {
    3073         244 :       if (Op > 0)
    3074          11 :         Out << ", ";
    3075         244 :       writeOperand(PadBB, /*PrintType=*/true);
    3076         244 :       ++Op;
    3077             :     }
    3078         233 :     Out << "] unwind ";
    3079             :     if (const BasicBlock *UnwindDest = CatchSwitch->getUnwindDest())
    3080          63 :       writeOperand(UnwindDest, /*PrintType=*/true);
    3081             :     else
    3082         170 :       Out << "to caller";
    3083             :   } else if (const auto *FPI = dyn_cast<FuncletPadInst>(&I)) {
    3084         607 :     Out << " within ";
    3085         607 :     writeOperand(FPI->getParentPad(), /*PrintType=*/false);
    3086         607 :     Out << " [";
    3087        1237 :     for (unsigned Op = 0, NumOps = FPI->getNumArgOperands(); Op < NumOps;
    3088             :          ++Op) {
    3089         315 :       if (Op > 0)
    3090         156 :         Out << ", ";
    3091         315 :       writeOperand(FPI->getArgOperand(Op), /*PrintType=*/true);
    3092             :     }
    3093         607 :     Out << ']';
    3094     2020307 :   } else if (isa<ReturnInst>(I) && !Operand) {
    3095       69377 :     Out << " void";
    3096             :   } else if (const auto *CRI = dyn_cast<CatchReturnInst>(&I)) {
    3097         157 :     Out << " from ";
    3098         157 :     writeOperand(CRI->getOperand(0), /*PrintType=*/false);
    3099             : 
    3100         157 :     Out << " to ";
    3101         157 :     writeOperand(CRI->getOperand(1), /*PrintType=*/true);
    3102             :   } else if (const auto *CRI = dyn_cast<CleanupReturnInst>(&I)) {
    3103         250 :     Out << " from ";
    3104         250 :     writeOperand(CRI->getOperand(0), /*PrintType=*/false);
    3105             : 
    3106         250 :     Out << " unwind ";
    3107         250 :     if (CRI->hasUnwindDest())
    3108          88 :       writeOperand(CRI->getOperand(1), /*PrintType=*/true);
    3109             :     else
    3110         162 :       Out << "to caller";
    3111             :   } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
    3112             :     // Print the calling convention being used.
    3113      165213 :     if (CI->getCallingConv() != CallingConv::C) {
    3114        5098 :       Out << " ";
    3115       10196 :       PrintCallingConv(CI->getCallingConv(), Out);
    3116             :     }
    3117             : 
    3118             :     Operand = CI->getCalledValue();
    3119             :     FunctionType *FTy = CI->getFunctionType();
    3120             :     Type *RetTy = FTy->getReturnType();
    3121      165213 :     const AttributeList &PAL = CI->getAttributes();
    3122             : 
    3123      165213 :     if (PAL.hasAttributes(AttributeList::ReturnIndex))
    3124        6870 :       Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
    3125             : 
    3126             :     // If possible, print out the short form of the call instruction.  We can
    3127             :     // only do this if the first argument is a pointer to a nonvararg function,
    3128             :     // and if the return type is not a pointer to a function.
    3129             :     //
    3130      165213 :     Out << ' ';
    3131      330426 :     TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
    3132      165213 :     Out << ' ';
    3133      165213 :     writeOperand(Operand, false);
    3134      165213 :     Out << '(';
    3135      909513 :     for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
    3136      372150 :       if (op > 0)
    3137      228738 :         Out << ", ";
    3138      744300 :       writeParamOperand(CI->getArgOperand(op), PAL.getParamAttributes(op));
    3139             :     }
    3140             : 
    3141             :     // Emit an ellipsis if this is a musttail call in a vararg function.  This
    3142             :     // is only to aid readability, musttail calls forward varargs by default.
    3143         105 :     if (CI->isMustTailCall() && CI->getParent() &&
    3144      165318 :         CI->getParent()->getParent() &&
    3145             :         CI->getParent()->getParent()->isVarArg())
    3146          54 :       Out << ", ...";
    3147             : 
    3148      165213 :     Out << ')';
    3149      165213 :     if (PAL.hasAttributes(AttributeList::FunctionIndex))
    3150       51949 :       Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
    3151             : 
    3152      165213 :     writeOperandBundles(CI);
    3153             :   } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
    3154             :     Operand = II->getCalledValue();
    3155             :     FunctionType *FTy = II->getFunctionType();
    3156             :     Type *RetTy = FTy->getReturnType();
    3157        2824 :     const AttributeList &PAL = II->getAttributes();
    3158             : 
    3159             :     // Print the calling convention being used.
    3160        2824 :     if (II->getCallingConv() != CallingConv::C) {
    3161          42 :       Out << " ";
    3162          84 :       PrintCallingConv(II->getCallingConv(), Out);
    3163             :     }
    3164             : 
    3165        2824 :     if (PAL.hasAttributes(AttributeList::ReturnIndex))
    3166         819 :       Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
    3167             : 
    3168             :     // If possible, print out the short form of the invoke instruction. We can
    3169             :     // only do this if the first argument is a pointer to a nonvararg function,
    3170             :     // and if the return type is not a pointer to a function.
    3171             :     //
    3172        2824 :     Out << ' ';
    3173        5648 :     TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
    3174        2824 :     Out << ' ';
    3175        2824 :     writeOperand(Operand, false);
    3176        2824 :     Out << '(';
    3177        8284 :     for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
    3178        2730 :       if (op)
    3179        1165 :         Out << ", ";
    3180        5460 :       writeParamOperand(II->getArgOperand(op), PAL.getParamAttributes(op));
    3181             :     }
    3182             : 
    3183        2824 :     Out << ')';
    3184        2824 :     if (PAL.hasAttributes(AttributeList::FunctionIndex))
    3185         184 :       Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
    3186             : 
    3187        2824 :     writeOperandBundles(II);
    3188             : 
    3189        2824 :     Out << "\n          to ";
    3190        2824 :     writeOperand(II->getNormalDest(), true);
    3191        2824 :     Out << " unwind ";
    3192        2824 :     writeOperand(II->getUnwindDest(), true);
    3193             :   } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
    3194      301477 :     Out << ' ';
    3195      301477 :     if (AI->isUsedWithInAlloca())
    3196         115 :       Out << "inalloca ";
    3197      301477 :     if (AI->isSwiftError())
    3198          24 :       Out << "swifterror ";
    3199      301477 :     TypePrinter.print(AI->getAllocatedType(), Out);
    3200             : 
    3201             :     // Explicitly write the array size if the code is broken, if it's an array
    3202             :     // allocation, or if the type is not canonical for scalar allocations.  The
    3203             :     // latter case prevents the type from mutating when round-tripping through
    3204             :     // assembly.
    3205      601509 :     if (!AI->getArraySize() || AI->isArrayAllocation() ||
    3206      300032 :         !AI->getArraySize()->getType()->isIntegerTy(32)) {
    3207        1453 :       Out << ", ";
    3208        1453 :       writeOperand(AI->getArraySize(), true);
    3209             :     }
    3210      301477 :     if (AI->getAlignment()) {
    3211      298760 :       Out << ", align " << AI->getAlignment();
    3212             :     }
    3213             : 
    3214             :     unsigned AddrSpace = AI->getType()->getAddressSpace();
    3215      301477 :     if (AddrSpace != 0) {
    3216        1012 :       Out << ", addrspace(" << AddrSpace << ')';
    3217             :     }
    3218     1481009 :   } else if (isa<CastInst>(I)) {
    3219      183863 :     if (Operand) {
    3220      183863 :       Out << ' ';
    3221      183863 :       writeOperand(Operand, true);   // Work with broken code
    3222             :     }
    3223      183863 :     Out << " to ";
    3224      183863 :     TypePrinter.print(I.getType(), Out);
    3225     1297146 :   } else if (isa<VAArgInst>(I)) {
    3226          49 :     if (Operand) {
    3227          49 :       Out << ' ';
    3228          49 :       writeOperand(Operand, true);   // Work with broken code
    3229             :     }
    3230          49 :     Out << ", ";
    3231          49 :     TypePrinter.print(I.getType(), Out);
    3232     1297097 :   } else if (Operand) {   // Print the normal way.
    3233             :     if (const auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
    3234      132402 :       Out << ' ';
    3235      132402 :       TypePrinter.print(GEP->getSourceElementType(), Out);
    3236      132402 :       Out << ',';
    3237             :     } else if (const auto *LI = dyn_cast<LoadInst>(&I)) {
    3238      401622 :       Out << ' ';
    3239      401622 :       TypePrinter.print(LI->getType(), Out);
    3240      401622 :       Out << ',';
    3241             :     }
    3242             : 
    3243             :     // PrintAllTypes - Instructions who have operands of all the same type
    3244             :     // omit the type from all but the first operand.  If the instruction has
    3245             :     // different type operands (for example br), then they are all printed.
    3246             :     bool PrintAllTypes = false;
    3247             :     Type *TheType = Operand->getType();
    3248             : 
    3249             :     // Select, Store and ShuffleVector always print all types.
    3250     1287227 :     if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
    3251     2187779 :         || isa<ReturnInst>(I)) {
    3252             :       PrintAllTypes = true;
    3253             :     } else {
    3254     1212726 :       for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
    3255             :         Operand = I.getOperand(i);
    3256             :         // note that Operand shouldn't be null, but the test helps make dump()
    3257             :         // more tolerant of malformed IR
    3258      340536 :         if (Operand && Operand->getType() != TheType) {
    3259             :           PrintAllTypes = true;    // We have differing types!  Print them all!
    3260             :           break;
    3261             :         }
    3262             :       }
    3263             :     }
    3264             : 
    3265      835238 :     if (!PrintAllTypes) {
    3266      683446 :       Out << ' ';
    3267      683446 :       TypePrinter.print(TheType, Out);
    3268             :     }
    3269             : 
    3270     1293083 :     Out << ' ';
    3271     5595285 :     for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
    3272     2151101 :       if (i) Out << ", ";
    3273     4302202 :       writeOperand(I.getOperand(i), PrintAllTypes);
    3274             :     }
    3275             :   }
    3276             : 
    3277             :   // Print atomic ordering/alignment for memory operations
    3278             :   if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
    3279      401622 :     if (LI->isAtomic())
    3280        2258 :       writeAtomic(LI->getContext(), LI->getOrdering(), LI->getSyncScopeID());
    3281      401622 :     if (LI->getAlignment())
    3282      394367 :       Out << ", align " << LI->getAlignment();
    3283             :   } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
    3284      382774 :     if (SI->isAtomic())
    3285        1074 :       writeAtomic(SI->getContext(), SI->getOrdering(), SI->getSyncScopeID());
    3286      382774 :     if (SI->getAlignment())
    3287      373392 :       Out << ", align " << SI->getAlignment();
    3288             :   } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
    3289        1352 :     writeAtomicCmpXchg(CXI->getContext(), CXI->getSuccessOrdering(),
    3290             :                        CXI->getFailureOrdering(), CXI->getSyncScopeID());
    3291             :   } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
    3292        1838 :     writeAtomic(RMWI->getContext(), RMWI->getOrdering(),
    3293             :                 RMWI->getSyncScopeID());
    3294             :   } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
    3295         452 :     writeAtomic(FI->getContext(), FI->getOrdering(), FI->getSyncScopeID());
    3296             :   }
    3297             : 
    3298             :   // Print Metadata info.
    3299             :   SmallVector<std::pair<unsigned, MDNode *>, 4> InstMD;
    3300             :   I.getAllMetadata(InstMD);
    3301     2111770 :   printMetadataAttachments(InstMD, ", ");
    3302             : 
    3303             :   // Print a nice comment.
    3304     2111770 :   printInfoComment(I);
    3305     2111770 : }
    3306             : 
    3307     2379745 : void AssemblyWriter::printMetadataAttachments(
    3308             :     const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
    3309             :     StringRef Separator) {
    3310     2379745 :   if (MDs.empty())
    3311             :     return;
    3312             : 
    3313      108987 :   if (MDNames.empty())
    3314       11480 :     MDs[0].second->getContext().getMDKindNames(MDNames);
    3315             : 
    3316      343337 :   for (const auto &I : MDs) {
    3317      117175 :     unsigned Kind = I.first;
    3318      117175 :     Out << Separator;
    3319      234350 :     if (Kind < MDNames.size()) {
    3320      117175 :       Out << "!";
    3321      234350 :       printMetadataIdentifier(MDNames[Kind], Out);
    3322             :     } else
    3323           0 :       Out << "!<unknown kind #" << Kind << ">";
    3324      117175 :     Out << ' ';
    3325      117175 :     WriteAsOperandInternal(Out, I.second, &TypePrinter, &Machine, TheModule);
    3326             :   }
    3327             : }
    3328             : 
    3329       86515 : void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) {
    3330      173030 :   Out << '!' << Slot << " = ";
    3331             :   printMDNodeBody(Node);
    3332       86515 :   Out << "\n";
    3333       86515 : }
    3334             : 
    3335        9597 : void AssemblyWriter::writeAllMDNodes() {
    3336             :   SmallVector<const MDNode *, 16> Nodes;
    3337        9597 :   Nodes.resize(Machine.mdn_size());
    3338       19194 :   for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
    3339       96112 :        I != E; ++I)
    3340      173030 :     Nodes[I->second] = cast<MDNode>(I->first);
    3341             : 
    3342       96112 :   for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
    3343      173030 :     writeMDNode(i, Nodes[i]);
    3344             :   }
    3345        9597 : }
    3346             : 
    3347             : void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
    3348       86515 :   WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
    3349             : }
    3350             : 
    3351       10989 : void AssemblyWriter::writeAllAttributeGroups() {
    3352             :   std::vector<std::pair<AttributeSet, unsigned>> asVec;
    3353       10989 :   asVec.resize(Machine.as_size());
    3354             : 
    3355       21978 :   for (SlotTracker::as_iterator I = Machine.as_begin(), E = Machine.as_end();
    3356       38665 :        I != E; ++I)
    3357       27676 :     asVec[I->second] = *I;
    3358             : 
    3359       38665 :   for (const auto &I : asVec)
    3360       55352 :     Out << "attributes #" << I.second << " = { "
    3361       83028 :         << I.first.getAsString(true) << " }\n";
    3362       10989 : }
    3363             : 
    3364         836 : void AssemblyWriter::printUseListOrder(const UseListOrder &Order) {
    3365         836 :   bool IsInFunction = Machine.getFunction();
    3366         836 :   if (IsInFunction)
    3367         729 :     Out << "  ";
    3368             : 
    3369         836 :   Out << "uselistorder";
    3370             :   if (const BasicBlock *BB =
    3371         836 :           IsInFunction ? nullptr : dyn_cast<BasicBlock>(Order.V)) {
    3372           0 :     Out << "_bb ";
    3373           0 :     writeOperand(BB->getParent(), false);
    3374           0 :     Out << ", ";
    3375           0 :     writeOperand(BB, false);
    3376             :   } else {
    3377         836 :     Out << " ";
    3378         836 :     writeOperand(Order.V, true);
    3379             :   }
    3380         836 :   Out << ", { ";
    3381             : 
    3382             :   assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
    3383         836 :   Out << Order.Shuffle[0];
    3384        3138 :   for (unsigned I = 1, E = Order.Shuffle.size(); I != E; ++I)
    3385        4604 :     Out << ", " << Order.Shuffle[I];
    3386         836 :   Out << " }\n";
    3387         836 : }
    3388             : 
    3389      138817 : void AssemblyWriter::printUseLists(const Function *F) {
    3390             :   auto hasMore =
    3391      140037 :       [&]() { return !UseListOrders.empty() && UseListOrders.back().F == F; };
    3392             :   if (!hasMore())
    3393             :     // Nothing to do.
    3394             :     return;
    3395             : 
    3396         384 :   Out << "\n; uselistorder directives\n";
    3397             :   while (hasMore()) {
    3398         836 :     printUseListOrder(UseListOrders.back());
    3399             :     UseListOrders.pop_back();
    3400             :   }
    3401             : }
    3402             : 
    3403             : //===----------------------------------------------------------------------===//
    3404             : //                       External Interface declarations
    3405             : //===----------------------------------------------------------------------===//
    3406             : 
    3407         124 : void Function::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
    3408             :                      bool ShouldPreserveUseListOrder,
    3409             :                      bool IsForDebug) const {
    3410         248 :   SlotTracker SlotTable(this->getParent());
    3411         124 :   formatted_raw_ostream OS(ROS);
    3412             :   AssemblyWriter W(OS, SlotTable, this->getParent(), AAW,
    3413             :                    IsForDebug,
    3414         248 :                    ShouldPreserveUseListOrder);
    3415         124 :   W.printFunction(this);
    3416         124 : }
    3417             : 
    3418       15445 : void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
    3419             :                    bool ShouldPreserveUseListOrder, bool IsForDebug) const {
    3420       30890 :   SlotTracker SlotTable(this);
    3421       15445 :   formatted_raw_ostream OS(ROS);
    3422             :   AssemblyWriter W(OS, SlotTable, this, AAW, IsForDebug,
    3423       30890 :                    ShouldPreserveUseListOrder);
    3424       15445 :   W.printModule(this);
    3425       15445 : }
    3426             : 
    3427           1 : void NamedMDNode::print(raw_ostream &ROS, bool IsForDebug) const {
    3428           2 :   SlotTracker SlotTable(getParent());
    3429           1 :   formatted_raw_ostream OS(ROS);
    3430           2 :   AssemblyWriter W(OS, SlotTable, getParent(), nullptr, IsForDebug);
    3431           1 :   W.printNamedMDNode(this);
    3432           1 : }
    3433             : 
    3434           6 : void NamedMDNode::print(raw_ostream &ROS, ModuleSlotTracker &MST,
    3435             :                         bool IsForDebug) const {
    3436             :   Optional<SlotTracker> LocalST;
    3437             :   SlotTracker *SlotTable;
    3438           6 :   if (auto *ST = MST.getMachine())
    3439             :     SlotTable = ST;
    3440             :   else {
    3441           0 :     LocalST.emplace(getParent());
    3442             :     SlotTable = &*LocalST;
    3443             :   }
    3444             : 
    3445           6 :   formatted_raw_ostream OS(ROS);
    3446          12 :   AssemblyWriter W(OS, *SlotTable, getParent(), nullptr, IsForDebug);
    3447           6 :   W.printNamedMDNode(this);
    3448           6 : }
    3449             : 
    3450       24303 : void Comdat::print(raw_ostream &ROS, bool /*IsForDebug*/) const {
    3451       24303 :   PrintLLVMName(ROS, getName(), ComdatPrefix);
    3452       24303 :   ROS << " = comdat ";
    3453             : 
    3454       24303 :   switch (getSelectionKind()) {
    3455       24100 :   case Comdat::Any:
    3456       24100 :     ROS << "any";
    3457       24100 :     break;
    3458          10 :   case Comdat::ExactMatch:
    3459          10 :     ROS << "exactmatch";
    3460          10 :     break;
    3461         170 :   case Comdat::Largest:
    3462         170 :     ROS << "largest";
    3463         170 :     break;
    3464          15 :   case Comdat::NoDuplicates:
    3465          15 :     ROS << "noduplicates";
    3466          15 :     break;
    3467           8 :   case Comdat::SameSize:
    3468           8 :     ROS << "samesize";
    3469           8 :     break;
    3470             :   }
    3471             : 
    3472             :   ROS << '\n';
    3473       24303 : }
    3474             : 
    3475       22370 : void Type::print(raw_ostream &OS, bool /*IsForDebug*/, bool NoDetails) const {
    3476             :   TypePrinting TP;
    3477       22370 :   TP.print(const_cast<Type*>(this), OS);
    3478             : 
    3479       22370 :   if (NoDetails)
    3480             :     return;
    3481             : 
    3482             :   // If the type is a named struct type, print the body as well.
    3483             :   if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
    3484          79 :     if (!STy->isLiteral()) {
    3485          77 :       OS << " = type ";
    3486          77 :       TP.printStructBody(STy, OS);
    3487             :     }
    3488             : }
    3489             : 
    3490       24497 : static bool isReferencingMDNode(const Instruction &I) {
    3491             :   if (const auto *CI = dyn_cast<CallInst>(&I))
    3492             :     if (Function *F = CI->getCalledFunction())
    3493        2688 :       if (F->isIntrinsic())
    3494       10672 :         for (auto &Op : I.operands())
    3495             :           if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
    3496             :             if (isa<MDNode>(V->getMetadata()))
    3497             :               return true;
    3498             :   return false;
    3499             : }
    3500             : 
    3501       24943 : void Value::print(raw_ostream &ROS, bool IsForDebug) const {
    3502             :   bool ShouldInitializeAllMetadata = false;
    3503             :   if (auto *I = dyn_cast<Instruction>(this))
    3504       24497 :     ShouldInitializeAllMetadata = isReferencingMDNode(*I);
    3505         446 :   else if (isa<Function>(this) || isa<MetadataAsValue>(this))
    3506             :     ShouldInitializeAllMetadata = true;
    3507             : 
    3508       49886 :   ModuleSlotTracker MST(getModuleFromVal(this), ShouldInitializeAllMetadata);
    3509       24943 :   print(ROS, MST, IsForDebug);
    3510       24943 : }
    3511             : 
    3512       25212 : void Value::print(raw_ostream &ROS, ModuleSlotTracker &MST,
    3513             :                   bool IsForDebug) const {
    3514       25212 :   formatted_raw_ostream OS(ROS);
    3515       50424 :   SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));
    3516             :   SlotTracker &SlotTable =
    3517       25212 :       MST.getMachine() ? *MST.getMachine() : EmptySlotTable;
    3518             :   auto incorporateFunction = [&](const Function *F) {
    3519       24754 :     if (F)
    3520       24754 :       MST.incorporateFunction(*F);
    3521             :   };
    3522             : 
    3523             :   if (const Instruction *I = dyn_cast<Instruction>(this)) {
    3524       24764 :     incorporateFunction(I->getParent() ? I->getParent()->getParent() : nullptr);
    3525       49528 :     AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr, IsForDebug);
    3526       24764 :     W.printInstruction(*I);
    3527             :   } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
    3528             :     incorporateFunction(BB->getParent());
    3529          56 :     AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr, IsForDebug);
    3530          28 :     W.printBasicBlock(BB);
    3531             :   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
    3532         462 :     AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr, IsForDebug);
    3533             :     if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
    3534           9 :       W.printGlobal(V);
    3535             :     else if (const Function *F = dyn_cast<Function>(GV))
    3536         222 :       W.printFunction(F);
    3537             :     else
    3538           0 :       W.printIndirectSymbol(cast<GlobalIndirectSymbol>(GV));
    3539             :   } else if (const MetadataAsValue *V = dyn_cast<MetadataAsValue>(this)) {
    3540           4 :     V->getMetadata()->print(ROS, MST, getModuleFromVal(V));
    3541             :   } else if (const Constant *C = dyn_cast<Constant>(this)) {
    3542             :     TypePrinting TypePrinter;
    3543          47 :     TypePrinter.print(C->getType(), OS);
    3544             :     OS << ' ';
    3545          47 :     WriteConstantInternal(OS, C, TypePrinter, MST.getMachine(), nullptr);
    3546         138 :   } else if (isa<InlineAsm>(this) || isa<Argument>(this)) {
    3547         138 :     this->printAsOperand(OS, /* PrintType */ true, MST);
    3548             :   } else {
    3549           0 :     llvm_unreachable("Unknown value to print out!");
    3550             :   }
    3551       25212 : }
    3552             : 
    3553             : /// Print without a type, skipping the TypePrinting object.
    3554             : ///
    3555             : /// \return \c true iff printing was successful.
    3556      270148 : static bool printWithoutType(const Value &V, raw_ostream &O,
    3557             :                              SlotTracker *Machine, const Module *M) {
    3558      279348 :   if (V.hasName() || isa<GlobalValue>(V) ||
    3559         374 :       (!isa<Constant>(V) && !isa<MetadataAsValue>(V))) {
    3560      261318 :     WriteAsOperandInternal(O, &V, nullptr, Machine, M);
    3561      261318 :     return true;
    3562             :   }
    3563             :   return false;
    3564             : }
    3565             : 
    3566       20824 : static void printAsOperandImpl(const Value &V, raw_ostream &O, bool PrintType,
    3567             :                                ModuleSlotTracker &MST) {
    3568             :   TypePrinting TypePrinter;
    3569       20824 :   if (const Module *M = MST.getModule())
    3570       11965 :     TypePrinter.incorporateTypes(*M);
    3571       20824 :   if (PrintType) {
    3572       11994 :     TypePrinter.print(V.getType(), O);
    3573             :     O << ' ';
    3574             :   }
    3575             : 
    3576       20824 :   WriteAsOperandInternal(O, &V, &TypePrinter, MST.getMachine(),
    3577             :                          MST.getModule());
    3578       20824 : }
    3579             : 
    3580      273317 : void Value::printAsOperand(raw_ostream &O, bool PrintType,
    3581             :                            const Module *M) const {
    3582      273317 :   if (!M)
    3583       26359 :     M = getModuleFromVal(this);
    3584             : 
    3585      273317 :   if (!PrintType)
    3586      262592 :     if (printWithoutType(*this, O, nullptr, M))
    3587      253777 :       return;
    3588             : 
    3589             :   SlotTracker Machine(
    3590       39080 :       M, /* ShouldInitializeAllMetadata */ isa<MetadataAsValue>(this));
    3591       39080 :   ModuleSlotTracker MST(Machine, M);
    3592       19540 :   printAsOperandImpl(*this, O, PrintType, MST);
    3593             : }
    3594             : 
    3595        8825 : void Value::printAsOperand(raw_ostream &O, bool PrintType,
    3596             :                            ModuleSlotTracker &MST) const {
    3597        8825 :   if (!PrintType)
    3598        7556 :     if (printWithoutType(*this, O, MST.getMachine(), MST.getModule()))
    3599             :       return;
    3600             : 
    3601        1284 :   printAsOperandImpl(*this, O, PrintType, MST);
    3602             : }
    3603             : 
    3604        2040 : static void printMetadataImpl(raw_ostream &ROS, const Metadata &MD,
    3605             :                               ModuleSlotTracker &MST, const Module *M,
    3606             :                               bool OnlyAsOperand) {
    3607         170 :   formatted_raw_ostream OS(ROS);
    3608             : 
    3609             :   TypePrinting TypePrinter;
    3610        2040 :   if (M)
    3611         192 :     TypePrinter.incorporateTypes(*M);
    3612             : 
    3613        2040 :   WriteAsOperandInternal(OS, &MD, &TypePrinter, MST.getMachine(), M,
    3614             :                          /* FromValue */ true);
    3615             : 
    3616             :   auto *N = dyn_cast<MDNode>(&MD);
    3617        2040 :   if (OnlyAsOperand || !N || isa<DIExpression>(MD))
    3618             :     return;
    3619             : 
    3620         170 :   OS << " = ";
    3621         170 :   WriteMDNodeBodyInternal(OS, N, &TypePrinter, MST.getMachine(), M);
    3622             : }
    3623             : 
    3624           2 : void Metadata::printAsOperand(raw_ostream &OS, const Module *M) const {
    3625           4 :   ModuleSlotTracker MST(M, isa<MDNode>(this));
    3626           2 :   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
    3627           2 : }
    3628             : 
    3629        1840 : void Metadata::printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST,
    3630             :                               const Module *M) const {
    3631        1840 :   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
    3632        1840 : }
    3633             : 
    3634          10 : void Metadata::print(raw_ostream &OS, const Module *M,
    3635             :                      bool /*IsForDebug*/) const {
    3636          20 :   ModuleSlotTracker MST(M, isa<MDNode>(this));
    3637          10 :   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
    3638          10 : }
    3639             : 
    3640         188 : void Metadata::print(raw_ostream &OS, ModuleSlotTracker &MST,
    3641             :                      const Module *M, bool /*IsForDebug*/) const {
    3642         188 :   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
    3643         188 : }
    3644             : 
    3645             : #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
    3646             : // Value::dump - allow easy printing of Values from the debugger.
    3647             : LLVM_DUMP_METHOD
    3648             : void Value::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
    3649             : 
    3650             : // Type::dump - allow easy printing of Types from the debugger.
    3651             : LLVM_DUMP_METHOD
    3652             : void Type::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
    3653             : 
    3654             : // Module::dump() - Allow printing of Modules from the debugger.
    3655             : LLVM_DUMP_METHOD
    3656             : void Module::dump() const {
    3657             :   print(dbgs(), nullptr,
    3658             :         /*ShouldPreserveUseListOrder=*/false, /*IsForDebug=*/true);
    3659             : }
    3660             : 
    3661             : // \brief Allow printing of Comdats from the debugger.
    3662             : LLVM_DUMP_METHOD
    3663             : void Comdat::dump() const { print(dbgs(), /*IsForDebug=*/true); }
    3664             : 
    3665             : // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
    3666             : LLVM_DUMP_METHOD
    3667             : void NamedMDNode::dump() const { print(dbgs(), /*IsForDebug=*/true); }
    3668             : 
    3669             : LLVM_DUMP_METHOD
    3670             : void Metadata::dump() const { dump(nullptr); }
    3671             : 
    3672             : LLVM_DUMP_METHOD
    3673             : void Metadata::dump(const Module *M) const {
    3674             :   print(dbgs(), M, /*IsForDebug=*/true);
    3675             :   dbgs() << '\n';
    3676             : }
    3677             : #endif

Generated by: LCOV version 1.13