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

Generated by: LCOV version 1.13