LLVM API Documentation

AsmWriter.cpp
Go to the documentation of this file.
00001 //===-- AsmWriter.cpp - Printing LLVM as an assembly file -----------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This library implements the functionality defined in llvm/IR/Writer.h
00011 //
00012 // Note that these routines must be extremely tolerant of various errors in the
00013 // LLVM code, because it can be used for debugging transformations.
00014 //
00015 //===----------------------------------------------------------------------===//
00016 
00017 #include "AsmWriter.h"
00018 #include "llvm/ADT/DenseMap.h"
00019 #include "llvm/ADT/STLExtras.h"
00020 #include "llvm/ADT/SmallString.h"
00021 #include "llvm/ADT/StringExtras.h"
00022 #include "llvm/IR/AssemblyAnnotationWriter.h"
00023 #include "llvm/IR/CFG.h"
00024 #include "llvm/IR/CallingConv.h"
00025 #include "llvm/IR/Constants.h"
00026 #include "llvm/IR/DebugInfo.h"
00027 #include "llvm/IR/DerivedTypes.h"
00028 #include "llvm/IR/IRPrintingPasses.h"
00029 #include "llvm/IR/InlineAsm.h"
00030 #include "llvm/IR/IntrinsicInst.h"
00031 #include "llvm/IR/LLVMContext.h"
00032 #include "llvm/IR/Module.h"
00033 #include "llvm/IR/Operator.h"
00034 #include "llvm/IR/TypeFinder.h"
00035 #include "llvm/IR/ValueSymbolTable.h"
00036 #include "llvm/Support/Debug.h"
00037 #include "llvm/Support/Dwarf.h"
00038 #include "llvm/Support/ErrorHandling.h"
00039 #include "llvm/Support/FormattedStream.h"
00040 #include "llvm/Support/MathExtras.h"
00041 #include <algorithm>
00042 #include <cctype>
00043 using namespace llvm;
00044 
00045 // Make virtual table appear in this compilation unit.
00046 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
00047 
00048 //===----------------------------------------------------------------------===//
00049 // Helper Functions
00050 //===----------------------------------------------------------------------===//
00051 
00052 namespace {
00053 struct OrderMap {
00054   DenseMap<const Value *, std::pair<unsigned, bool>> IDs;
00055 
00056   unsigned size() const { return IDs.size(); }
00057   std::pair<unsigned, bool> &operator[](const Value *V) { return IDs[V]; }
00058   std::pair<unsigned, bool> lookup(const Value *V) const {
00059     return IDs.lookup(V);
00060   }
00061   void index(const Value *V) {
00062     // Explicitly sequence get-size and insert-value operations to avoid UB.
00063     unsigned ID = IDs.size() + 1;
00064     IDs[V].first = ID;
00065   }
00066 };
00067 }
00068 
00069 static void orderValue(const Value *V, OrderMap &OM) {
00070   if (OM.lookup(V).first)
00071     return;
00072 
00073   if (const Constant *C = dyn_cast<Constant>(V))
00074     if (C->getNumOperands() && !isa<GlobalValue>(C))
00075       for (const Value *Op : C->operands())
00076         if (!isa<BasicBlock>(Op) && !isa<GlobalValue>(Op))
00077           orderValue(Op, OM);
00078 
00079   // Note: we cannot cache this lookup above, since inserting into the map
00080   // changes the map's size, and thus affects the other IDs.
00081   OM.index(V);
00082 }
00083 
00084 static OrderMap orderModule(const Module *M) {
00085   // This needs to match the order used by ValueEnumerator::ValueEnumerator()
00086   // and ValueEnumerator::incorporateFunction().
00087   OrderMap OM;
00088 
00089   for (const GlobalVariable &G : M->globals()) {
00090     if (G.hasInitializer())
00091       if (!isa<GlobalValue>(G.getInitializer()))
00092         orderValue(G.getInitializer(), OM);
00093     orderValue(&G, OM);
00094   }
00095   for (const GlobalAlias &A : M->aliases()) {
00096     if (!isa<GlobalValue>(A.getAliasee()))
00097       orderValue(A.getAliasee(), OM);
00098     orderValue(&A, OM);
00099   }
00100   for (const Function &F : *M) {
00101     if (F.hasPrefixData())
00102       if (!isa<GlobalValue>(F.getPrefixData()))
00103         orderValue(F.getPrefixData(), OM);
00104 
00105     if (F.hasPrologueData())
00106       if (!isa<GlobalValue>(F.getPrologueData()))
00107         orderValue(F.getPrologueData(), OM);
00108 
00109     orderValue(&F, OM);
00110 
00111     if (F.isDeclaration())
00112       continue;
00113 
00114     for (const Argument &A : F.args())
00115       orderValue(&A, OM);
00116     for (const BasicBlock &BB : F) {
00117       orderValue(&BB, OM);
00118       for (const Instruction &I : BB) {
00119         for (const Value *Op : I.operands())
00120           if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) ||
00121               isa<InlineAsm>(*Op))
00122             orderValue(Op, OM);
00123         orderValue(&I, OM);
00124       }
00125     }
00126   }
00127   return OM;
00128 }
00129 
00130 static void predictValueUseListOrderImpl(const Value *V, const Function *F,
00131                                          unsigned ID, const OrderMap &OM,
00132                                          UseListOrderStack &Stack) {
00133   // Predict use-list order for this one.
00134   typedef std::pair<const Use *, unsigned> Entry;
00135   SmallVector<Entry, 64> List;
00136   for (const Use &U : V->uses())
00137     // Check if this user will be serialized.
00138     if (OM.lookup(U.getUser()).first)
00139       List.push_back(std::make_pair(&U, List.size()));
00140 
00141   if (List.size() < 2)
00142     // We may have lost some users.
00143     return;
00144 
00145   bool GetsReversed =
00146       !isa<GlobalVariable>(V) && !isa<Function>(V) && !isa<BasicBlock>(V);
00147   if (auto *BA = dyn_cast<BlockAddress>(V))
00148     ID = OM.lookup(BA->getBasicBlock()).first;
00149   std::sort(List.begin(), List.end(), [&](const Entry &L, const Entry &R) {
00150     const Use *LU = L.first;
00151     const Use *RU = R.first;
00152     if (LU == RU)
00153       return false;
00154 
00155     auto LID = OM.lookup(LU->getUser()).first;
00156     auto RID = OM.lookup(RU->getUser()).first;
00157 
00158     // If ID is 4, then expect: 7 6 5 1 2 3.
00159     if (LID < RID) {
00160       if (GetsReversed)
00161         if (RID <= ID)
00162           return true;
00163       return false;
00164     }
00165     if (RID < LID) {
00166       if (GetsReversed)
00167         if (LID <= ID)
00168           return false;
00169       return true;
00170     }
00171 
00172     // LID and RID are equal, so we have different operands of the same user.
00173     // Assume operands are added in order for all instructions.
00174     if (GetsReversed)
00175       if (LID <= ID)
00176         return LU->getOperandNo() < RU->getOperandNo();
00177     return LU->getOperandNo() > RU->getOperandNo();
00178   });
00179 
00180   if (std::is_sorted(
00181           List.begin(), List.end(),
00182           [](const Entry &L, const Entry &R) { return L.second < R.second; }))
00183     // Order is already correct.
00184     return;
00185 
00186   // Store the shuffle.
00187   Stack.emplace_back(V, F, List.size());
00188   assert(List.size() == Stack.back().Shuffle.size() && "Wrong size");
00189   for (size_t I = 0, E = List.size(); I != E; ++I)
00190     Stack.back().Shuffle[I] = List[I].second;
00191 }
00192 
00193 static void predictValueUseListOrder(const Value *V, const Function *F,
00194                                      OrderMap &OM, UseListOrderStack &Stack) {
00195   auto &IDPair = OM[V];
00196   assert(IDPair.first && "Unmapped value");
00197   if (IDPair.second)
00198     // Already predicted.
00199     return;
00200 
00201   // Do the actual prediction.
00202   IDPair.second = true;
00203   if (!V->use_empty() && std::next(V->use_begin()) != V->use_end())
00204     predictValueUseListOrderImpl(V, F, IDPair.first, OM, Stack);
00205 
00206   // Recursive descent into constants.
00207   if (const Constant *C = dyn_cast<Constant>(V))
00208     if (C->getNumOperands()) // Visit GlobalValues.
00209       for (const Value *Op : C->operands())
00210         if (isa<Constant>(Op)) // Visit GlobalValues.
00211           predictValueUseListOrder(Op, F, OM, Stack);
00212 }
00213 
00214 static UseListOrderStack predictUseListOrder(const Module *M) {
00215   OrderMap OM = orderModule(M);
00216 
00217   // Use-list orders need to be serialized after all the users have been added
00218   // to a value, or else the shuffles will be incomplete.  Store them per
00219   // function in a stack.
00220   //
00221   // Aside from function order, the order of values doesn't matter much here.
00222   UseListOrderStack Stack;
00223 
00224   // We want to visit the functions backward now so we can list function-local
00225   // constants in the last Function they're used in.  Module-level constants
00226   // have already been visited above.
00227   for (auto I = M->rbegin(), E = M->rend(); I != E; ++I) {
00228     const Function &F = *I;
00229     if (F.isDeclaration())
00230       continue;
00231     for (const BasicBlock &BB : F)
00232       predictValueUseListOrder(&BB, &F, OM, Stack);
00233     for (const Argument &A : F.args())
00234       predictValueUseListOrder(&A, &F, OM, Stack);
00235     for (const BasicBlock &BB : F)
00236       for (const Instruction &I : BB)
00237         for (const Value *Op : I.operands())
00238           if (isa<Constant>(*Op) || isa<InlineAsm>(*Op)) // Visit GlobalValues.
00239             predictValueUseListOrder(Op, &F, OM, Stack);
00240     for (const BasicBlock &BB : F)
00241       for (const Instruction &I : BB)
00242         predictValueUseListOrder(&I, &F, OM, Stack);
00243   }
00244 
00245   // Visit globals last.
00246   for (const GlobalVariable &G : M->globals())
00247     predictValueUseListOrder(&G, nullptr, OM, Stack);
00248   for (const Function &F : *M)
00249     predictValueUseListOrder(&F, nullptr, OM, Stack);
00250   for (const GlobalAlias &A : M->aliases())
00251     predictValueUseListOrder(&A, nullptr, OM, Stack);
00252   for (const GlobalVariable &G : M->globals())
00253     if (G.hasInitializer())
00254       predictValueUseListOrder(G.getInitializer(), nullptr, OM, Stack);
00255   for (const GlobalAlias &A : M->aliases())
00256     predictValueUseListOrder(A.getAliasee(), nullptr, OM, Stack);
00257   for (const Function &F : *M)
00258     if (F.hasPrefixData())
00259       predictValueUseListOrder(F.getPrefixData(), nullptr, OM, Stack);
00260 
00261   return Stack;
00262 }
00263 
00264 static const Module *getModuleFromVal(const Value *V) {
00265   if (const Argument *MA = dyn_cast<Argument>(V))
00266     return MA->getParent() ? MA->getParent()->getParent() : nullptr;
00267 
00268   if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
00269     return BB->getParent() ? BB->getParent()->getParent() : nullptr;
00270 
00271   if (const Instruction *I = dyn_cast<Instruction>(V)) {
00272     const Function *M = I->getParent() ? I->getParent()->getParent() : nullptr;
00273     return M ? M->getParent() : nullptr;
00274   }
00275 
00276   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
00277     return GV->getParent();
00278   return nullptr;
00279 }
00280 
00281 static void PrintCallingConv(unsigned cc, raw_ostream &Out) {
00282   switch (cc) {
00283   default:                         Out << "cc" << cc; break;
00284   case CallingConv::Fast:          Out << "fastcc"; break;
00285   case CallingConv::Cold:          Out << "coldcc"; break;
00286   case CallingConv::WebKit_JS:     Out << "webkit_jscc"; break;
00287   case CallingConv::AnyReg:        Out << "anyregcc"; break;
00288   case CallingConv::PreserveMost:  Out << "preserve_mostcc"; break;
00289   case CallingConv::PreserveAll:   Out << "preserve_allcc"; break;
00290   case CallingConv::GHC:           Out << "ghccc"; break;
00291   case CallingConv::X86_StdCall:   Out << "x86_stdcallcc"; break;
00292   case CallingConv::X86_FastCall:  Out << "x86_fastcallcc"; break;
00293   case CallingConv::X86_ThisCall:  Out << "x86_thiscallcc"; break;
00294   case CallingConv::X86_VectorCall:Out << "x86_vectorcallcc"; break;
00295   case CallingConv::Intel_OCL_BI:  Out << "intel_ocl_bicc"; break;
00296   case CallingConv::ARM_APCS:      Out << "arm_apcscc"; break;
00297   case CallingConv::ARM_AAPCS:     Out << "arm_aapcscc"; break;
00298   case CallingConv::ARM_AAPCS_VFP: Out << "arm_aapcs_vfpcc"; break;
00299   case CallingConv::MSP430_INTR:   Out << "msp430_intrcc"; break;
00300   case CallingConv::PTX_Kernel:    Out << "ptx_kernel"; break;
00301   case CallingConv::PTX_Device:    Out << "ptx_device"; break;
00302   case CallingConv::X86_64_SysV:   Out << "x86_64_sysvcc"; break;
00303   case CallingConv::X86_64_Win64:  Out << "x86_64_win64cc"; break;
00304   case CallingConv::SPIR_FUNC:     Out << "spir_func"; break;
00305   case CallingConv::SPIR_KERNEL:   Out << "spir_kernel"; break;
00306   }
00307 }
00308 
00309 // PrintEscapedString - Print each character of the specified string, escaping
00310 // it if it is not printable or if it is an escape char.
00311 static void PrintEscapedString(StringRef Name, raw_ostream &Out) {
00312   for (unsigned i = 0, e = Name.size(); i != e; ++i) {
00313     unsigned char C = Name[i];
00314     if (isprint(C) && C != '\\' && C != '"')
00315       Out << C;
00316     else
00317       Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
00318   }
00319 }
00320 
00321 enum PrefixType {
00322   GlobalPrefix,
00323   ComdatPrefix,
00324   LabelPrefix,
00325   LocalPrefix,
00326   NoPrefix
00327 };
00328 
00329 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
00330 /// prefixed with % (if the string only contains simple characters) or is
00331 /// surrounded with ""'s (if it has special chars in it).  Print it out.
00332 static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) {
00333   assert(!Name.empty() && "Cannot get empty name!");
00334   switch (Prefix) {
00335   case NoPrefix: break;
00336   case GlobalPrefix: OS << '@'; break;
00337   case ComdatPrefix: OS << '$'; break;
00338   case LabelPrefix:  break;
00339   case LocalPrefix:  OS << '%'; break;
00340   }
00341 
00342   // Scan the name to see if it needs quotes first.
00343   bool NeedsQuotes = isdigit(static_cast<unsigned char>(Name[0]));
00344   if (!NeedsQuotes) {
00345     for (unsigned i = 0, e = Name.size(); i != e; ++i) {
00346       // By making this unsigned, the value passed in to isalnum will always be
00347       // in the range 0-255.  This is important when building with MSVC because
00348       // its implementation will assert.  This situation can arise when dealing
00349       // with UTF-8 multibyte characters.
00350       unsigned char C = Name[i];
00351       if (!isalnum(static_cast<unsigned char>(C)) && C != '-' && C != '.' &&
00352           C != '_') {
00353         NeedsQuotes = true;
00354         break;
00355       }
00356     }
00357   }
00358 
00359   // If we didn't need any quotes, just write out the name in one blast.
00360   if (!NeedsQuotes) {
00361     OS << Name;
00362     return;
00363   }
00364 
00365   // Okay, we need quotes.  Output the quotes and escape any scary characters as
00366   // needed.
00367   OS << '"';
00368   PrintEscapedString(Name, OS);
00369   OS << '"';
00370 }
00371 
00372 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
00373 /// prefixed with % (if the string only contains simple characters) or is
00374 /// surrounded with ""'s (if it has special chars in it).  Print it out.
00375 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
00376   PrintLLVMName(OS, V->getName(),
00377                 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
00378 }
00379 
00380 
00381 namespace llvm {
00382 
00383 void TypePrinting::incorporateTypes(const Module &M) {
00384   NamedTypes.run(M, false);
00385 
00386   // The list of struct types we got back includes all the struct types, split
00387   // the unnamed ones out to a numbering and remove the anonymous structs.
00388   unsigned NextNumber = 0;
00389 
00390   std::vector<StructType*>::iterator NextToUse = NamedTypes.begin(), I, E;
00391   for (I = NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I) {
00392     StructType *STy = *I;
00393 
00394     // Ignore anonymous types.
00395     if (STy->isLiteral())
00396       continue;
00397 
00398     if (STy->getName().empty())
00399       NumberedTypes[STy] = NextNumber++;
00400     else
00401       *NextToUse++ = STy;
00402   }
00403 
00404   NamedTypes.erase(NextToUse, NamedTypes.end());
00405 }
00406 
00407 
00408 /// CalcTypeName - Write the specified type to the specified raw_ostream, making
00409 /// use of type names or up references to shorten the type name where possible.
00410 void TypePrinting::print(Type *Ty, raw_ostream &OS) {
00411   switch (Ty->getTypeID()) {
00412   case Type::VoidTyID:      OS << "void"; return;
00413   case Type::HalfTyID:      OS << "half"; return;
00414   case Type::FloatTyID:     OS << "float"; return;
00415   case Type::DoubleTyID:    OS << "double"; return;
00416   case Type::X86_FP80TyID:  OS << "x86_fp80"; return;
00417   case Type::FP128TyID:     OS << "fp128"; return;
00418   case Type::PPC_FP128TyID: OS << "ppc_fp128"; return;
00419   case Type::LabelTyID:     OS << "label"; return;
00420   case Type::MetadataTyID:  OS << "metadata"; return;
00421   case Type::X86_MMXTyID:   OS << "x86_mmx"; return;
00422   case Type::IntegerTyID:
00423     OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
00424     return;
00425 
00426   case Type::FunctionTyID: {
00427     FunctionType *FTy = cast<FunctionType>(Ty);
00428     print(FTy->getReturnType(), OS);
00429     OS << " (";
00430     for (FunctionType::param_iterator I = FTy->param_begin(),
00431          E = FTy->param_end(); I != E; ++I) {
00432       if (I != FTy->param_begin())
00433         OS << ", ";
00434       print(*I, OS);
00435     }
00436     if (FTy->isVarArg()) {
00437       if (FTy->getNumParams()) OS << ", ";
00438       OS << "...";
00439     }
00440     OS << ')';
00441     return;
00442   }
00443   case Type::StructTyID: {
00444     StructType *STy = cast<StructType>(Ty);
00445 
00446     if (STy->isLiteral())
00447       return printStructBody(STy, OS);
00448 
00449     if (!STy->getName().empty())
00450       return PrintLLVMName(OS, STy->getName(), LocalPrefix);
00451 
00452     DenseMap<StructType*, unsigned>::iterator I = NumberedTypes.find(STy);
00453     if (I != NumberedTypes.end())
00454       OS << '%' << I->second;
00455     else  // Not enumerated, print the hex address.
00456       OS << "%\"type " << STy << '\"';
00457     return;
00458   }
00459   case Type::PointerTyID: {
00460     PointerType *PTy = cast<PointerType>(Ty);
00461     print(PTy->getElementType(), OS);
00462     if (unsigned AddressSpace = PTy->getAddressSpace())
00463       OS << " addrspace(" << AddressSpace << ')';
00464     OS << '*';
00465     return;
00466   }
00467   case Type::ArrayTyID: {
00468     ArrayType *ATy = cast<ArrayType>(Ty);
00469     OS << '[' << ATy->getNumElements() << " x ";
00470     print(ATy->getElementType(), OS);
00471     OS << ']';
00472     return;
00473   }
00474   case Type::VectorTyID: {
00475     VectorType *PTy = cast<VectorType>(Ty);
00476     OS << "<" << PTy->getNumElements() << " x ";
00477     print(PTy->getElementType(), OS);
00478     OS << '>';
00479     return;
00480   }
00481   }
00482   llvm_unreachable("Invalid TypeID");
00483 }
00484 
00485 void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
00486   if (STy->isOpaque()) {
00487     OS << "opaque";
00488     return;
00489   }
00490 
00491   if (STy->isPacked())
00492     OS << '<';
00493 
00494   if (STy->getNumElements() == 0) {
00495     OS << "{}";
00496   } else {
00497     StructType::element_iterator I = STy->element_begin();
00498     OS << "{ ";
00499     print(*I++, OS);
00500     for (StructType::element_iterator E = STy->element_end(); I != E; ++I) {
00501       OS << ", ";
00502       print(*I, OS);
00503     }
00504 
00505     OS << " }";
00506   }
00507   if (STy->isPacked())
00508     OS << '>';
00509 }
00510 
00511 //===----------------------------------------------------------------------===//
00512 // SlotTracker Class: Enumerate slot numbers for unnamed values
00513 //===----------------------------------------------------------------------===//
00514 /// This class provides computation of slot numbers for LLVM Assembly writing.
00515 ///
00516 class SlotTracker {
00517 public:
00518   /// ValueMap - A mapping of Values to slot numbers.
00519   typedef DenseMap<const Value*, unsigned> ValueMap;
00520 
00521 private:
00522   /// TheModule - The module for which we are holding slot numbers.
00523   const Module* TheModule;
00524 
00525   /// TheFunction - The function for which we are holding slot numbers.
00526   const Function* TheFunction;
00527   bool FunctionProcessed;
00528 
00529   /// mMap - The slot map for the module level data.
00530   ValueMap mMap;
00531   unsigned mNext;
00532 
00533   /// fMap - The slot map for the function level data.
00534   ValueMap fMap;
00535   unsigned fNext;
00536 
00537   /// mdnMap - Map for MDNodes.
00538   DenseMap<const MDNode*, unsigned> mdnMap;
00539   unsigned mdnNext;
00540 
00541   /// asMap - The slot map for attribute sets.
00542   DenseMap<AttributeSet, unsigned> asMap;
00543   unsigned asNext;
00544 public:
00545   /// Construct from a module
00546   explicit SlotTracker(const Module *M);
00547   /// Construct from a function, starting out in incorp state.
00548   explicit SlotTracker(const Function *F);
00549 
00550   /// Return the slot number of the specified value in it's type
00551   /// plane.  If something is not in the SlotTracker, return -1.
00552   int getLocalSlot(const Value *V);
00553   int getGlobalSlot(const GlobalValue *V);
00554   int getMetadataSlot(const MDNode *N);
00555   int getAttributeGroupSlot(AttributeSet AS);
00556 
00557   /// If you'd like to deal with a function instead of just a module, use
00558   /// this method to get its data into the SlotTracker.
00559   void incorporateFunction(const Function *F) {
00560     TheFunction = F;
00561     FunctionProcessed = false;
00562   }
00563 
00564   const Function *getFunction() const { return TheFunction; }
00565 
00566   /// After calling incorporateFunction, use this method to remove the
00567   /// most recently incorporated function from the SlotTracker. This
00568   /// will reset the state of the machine back to just the module contents.
00569   void purgeFunction();
00570 
00571   /// MDNode map iterators.
00572   typedef DenseMap<const MDNode*, unsigned>::iterator mdn_iterator;
00573   mdn_iterator mdn_begin() { return mdnMap.begin(); }
00574   mdn_iterator mdn_end() { return mdnMap.end(); }
00575   unsigned mdn_size() const { return mdnMap.size(); }
00576   bool mdn_empty() const { return mdnMap.empty(); }
00577 
00578   /// AttributeSet map iterators.
00579   typedef DenseMap<AttributeSet, unsigned>::iterator as_iterator;
00580   as_iterator as_begin()   { return asMap.begin(); }
00581   as_iterator as_end()     { return asMap.end(); }
00582   unsigned as_size() const { return asMap.size(); }
00583   bool as_empty() const    { return asMap.empty(); }
00584 
00585   /// This function does the actual initialization.
00586   inline void initialize();
00587 
00588   // Implementation Details
00589 private:
00590   /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
00591   void CreateModuleSlot(const GlobalValue *V);
00592 
00593   /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
00594   void CreateMetadataSlot(const MDNode *N);
00595 
00596   /// CreateFunctionSlot - Insert the specified Value* into the slot table.
00597   void CreateFunctionSlot(const Value *V);
00598 
00599   /// \brief Insert the specified AttributeSet into the slot table.
00600   void CreateAttributeSetSlot(AttributeSet AS);
00601 
00602   /// Add all of the module level global variables (and their initializers)
00603   /// and function declarations, but not the contents of those functions.
00604   void processModule();
00605 
00606   /// Add all of the functions arguments, basic blocks, and instructions.
00607   void processFunction();
00608 
00609   SlotTracker(const SlotTracker &) = delete;
00610   void operator=(const SlotTracker &) = delete;
00611 };
00612 
00613 SlotTracker *createSlotTracker(const Module *M) {
00614   return new SlotTracker(M);
00615 }
00616 
00617 static SlotTracker *createSlotTracker(const Value *V) {
00618   if (const Argument *FA = dyn_cast<Argument>(V))
00619     return new SlotTracker(FA->getParent());
00620 
00621   if (const Instruction *I = dyn_cast<Instruction>(V))
00622     if (I->getParent())
00623       return new SlotTracker(I->getParent()->getParent());
00624 
00625   if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
00626     return new SlotTracker(BB->getParent());
00627 
00628   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
00629     return new SlotTracker(GV->getParent());
00630 
00631   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
00632     return new SlotTracker(GA->getParent());
00633 
00634   if (const Function *Func = dyn_cast<Function>(V))
00635     return new SlotTracker(Func);
00636 
00637   return nullptr;
00638 }
00639 
00640 #if 0
00641 #define ST_DEBUG(X) dbgs() << X
00642 #else
00643 #define ST_DEBUG(X)
00644 #endif
00645 
00646 // Module level constructor. Causes the contents of the Module (sans functions)
00647 // to be added to the slot table.
00648 SlotTracker::SlotTracker(const Module *M)
00649     : TheModule(M), TheFunction(nullptr), FunctionProcessed(false), mNext(0),
00650       fNext(0), mdnNext(0), asNext(0) {}
00651 
00652 // Function level constructor. Causes the contents of the Module and the one
00653 // function provided to be added to the slot table.
00654 SlotTracker::SlotTracker(const Function *F)
00655     : TheModule(F ? F->getParent() : nullptr), TheFunction(F),
00656       FunctionProcessed(false), mNext(0), fNext(0), mdnNext(0), asNext(0) {}
00657 
00658 inline void SlotTracker::initialize() {
00659   if (TheModule) {
00660     processModule();
00661     TheModule = nullptr; ///< Prevent re-processing next time we're called.
00662   }
00663 
00664   if (TheFunction && !FunctionProcessed)
00665     processFunction();
00666 }
00667 
00668 // Iterate through all the global variables, functions, and global
00669 // variable initializers and create slots for them.
00670 void SlotTracker::processModule() {
00671   ST_DEBUG("begin processModule!\n");
00672 
00673   // Add all of the unnamed global variables to the value table.
00674   for (Module::const_global_iterator I = TheModule->global_begin(),
00675          E = TheModule->global_end(); I != E; ++I) {
00676     if (!I->hasName())
00677       CreateModuleSlot(I);
00678   }
00679 
00680   // Add metadata used by named metadata.
00681   for (Module::const_named_metadata_iterator
00682          I = TheModule->named_metadata_begin(),
00683          E = TheModule->named_metadata_end(); I != E; ++I) {
00684     const NamedMDNode *NMD = I;
00685     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
00686       CreateMetadataSlot(NMD->getOperand(i));
00687   }
00688 
00689   for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
00690        I != E; ++I) {
00691     if (!I->hasName())
00692       // Add all the unnamed functions to the table.
00693       CreateModuleSlot(I);
00694 
00695     // Add all the function attributes to the table.
00696     // FIXME: Add attributes of other objects?
00697     AttributeSet FnAttrs = I->getAttributes().getFnAttributes();
00698     if (FnAttrs.hasAttributes(AttributeSet::FunctionIndex))
00699       CreateAttributeSetSlot(FnAttrs);
00700   }
00701 
00702   ST_DEBUG("end processModule!\n");
00703 }
00704 
00705 // Process the arguments, basic blocks, and instructions  of a function.
00706 void SlotTracker::processFunction() {
00707   ST_DEBUG("begin processFunction!\n");
00708   fNext = 0;
00709 
00710   // Add all the function arguments with no names.
00711   for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
00712       AE = TheFunction->arg_end(); AI != AE; ++AI)
00713     if (!AI->hasName())
00714       CreateFunctionSlot(AI);
00715 
00716   ST_DEBUG("Inserting Instructions:\n");
00717 
00718   SmallVector<std::pair<unsigned, MDNode *>, 4> MDForInst;
00719 
00720   // Add all of the basic blocks and instructions with no names.
00721   for (Function::const_iterator BB = TheFunction->begin(),
00722        E = TheFunction->end(); BB != E; ++BB) {
00723     if (!BB->hasName())
00724       CreateFunctionSlot(BB);
00725 
00726     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E;
00727          ++I) {
00728       if (!I->getType()->isVoidTy() && !I->hasName())
00729         CreateFunctionSlot(I);
00730 
00731       // Intrinsics can directly use metadata.  We allow direct calls to any
00732       // llvm.foo function here, because the target may not be linked into the
00733       // optimizer.
00734       if (const CallInst *CI = dyn_cast<CallInst>(I)) {
00735         if (Function *F = CI->getCalledFunction())
00736           if (F->isIntrinsic())
00737             for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
00738               if (auto *V = dyn_cast_or_null<MetadataAsValue>(I->getOperand(i)))
00739                 if (MDNode *N = dyn_cast<MDNode>(V->getMetadata()))
00740                   CreateMetadataSlot(N);
00741 
00742         // Add all the call attributes to the table.
00743         AttributeSet Attrs = CI->getAttributes().getFnAttributes();
00744         if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
00745           CreateAttributeSetSlot(Attrs);
00746       } else if (const InvokeInst *II = dyn_cast<InvokeInst>(I)) {
00747         // Add all the call attributes to the table.
00748         AttributeSet Attrs = II->getAttributes().getFnAttributes();
00749         if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
00750           CreateAttributeSetSlot(Attrs);
00751       }
00752 
00753       // Process metadata attached with this instruction.
00754       I->getAllMetadata(MDForInst);
00755       for (unsigned i = 0, e = MDForInst.size(); i != e; ++i)
00756         CreateMetadataSlot(MDForInst[i].second);
00757       MDForInst.clear();
00758     }
00759   }
00760 
00761   FunctionProcessed = true;
00762 
00763   ST_DEBUG("end processFunction!\n");
00764 }
00765 
00766 /// Clean up after incorporating a function. This is the only way to get out of
00767 /// the function incorporation state that affects get*Slot/Create*Slot. Function
00768 /// incorporation state is indicated by TheFunction != 0.
00769 void SlotTracker::purgeFunction() {
00770   ST_DEBUG("begin purgeFunction!\n");
00771   fMap.clear(); // Simply discard the function level map
00772   TheFunction = nullptr;
00773   FunctionProcessed = false;
00774   ST_DEBUG("end purgeFunction!\n");
00775 }
00776 
00777 /// getGlobalSlot - Get the slot number of a global value.
00778 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
00779   // Check for uninitialized state and do lazy initialization.
00780   initialize();
00781 
00782   // Find the value in the module map
00783   ValueMap::iterator MI = mMap.find(V);
00784   return MI == mMap.end() ? -1 : (int)MI->second;
00785 }
00786 
00787 /// getMetadataSlot - Get the slot number of a MDNode.
00788 int SlotTracker::getMetadataSlot(const MDNode *N) {
00789   // Check for uninitialized state and do lazy initialization.
00790   initialize();
00791 
00792   // Find the MDNode in the module map
00793   mdn_iterator MI = mdnMap.find(N);
00794   return MI == mdnMap.end() ? -1 : (int)MI->second;
00795 }
00796 
00797 
00798 /// getLocalSlot - Get the slot number for a value that is local to a function.
00799 int SlotTracker::getLocalSlot(const Value *V) {
00800   assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
00801 
00802   // Check for uninitialized state and do lazy initialization.
00803   initialize();
00804 
00805   ValueMap::iterator FI = fMap.find(V);
00806   return FI == fMap.end() ? -1 : (int)FI->second;
00807 }
00808 
00809 int SlotTracker::getAttributeGroupSlot(AttributeSet AS) {
00810   // Check for uninitialized state and do lazy initialization.
00811   initialize();
00812 
00813   // Find the AttributeSet in the module map.
00814   as_iterator AI = asMap.find(AS);
00815   return AI == asMap.end() ? -1 : (int)AI->second;
00816 }
00817 
00818 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
00819 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
00820   assert(V && "Can't insert a null Value into SlotTracker!");
00821   assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
00822   assert(!V->hasName() && "Doesn't need a slot!");
00823 
00824   unsigned DestSlot = mNext++;
00825   mMap[V] = DestSlot;
00826 
00827   ST_DEBUG("  Inserting value [" << V->getType() << "] = " << V << " slot=" <<
00828            DestSlot << " [");
00829   // G = Global, F = Function, A = Alias, o = other
00830   ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
00831             (isa<Function>(V) ? 'F' :
00832              (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
00833 }
00834 
00835 /// CreateSlot - Create a new slot for the specified value if it has no name.
00836 void SlotTracker::CreateFunctionSlot(const Value *V) {
00837   assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
00838 
00839   unsigned DestSlot = fNext++;
00840   fMap[V] = DestSlot;
00841 
00842   // G = Global, F = Function, o = other
00843   ST_DEBUG("  Inserting value [" << V->getType() << "] = " << V << " slot=" <<
00844            DestSlot << " [o]\n");
00845 }
00846 
00847 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
00848 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
00849   assert(N && "Can't insert a null Value into SlotTracker!");
00850 
00851   unsigned DestSlot = mdnNext;
00852   if (!mdnMap.insert(std::make_pair(N, DestSlot)).second)
00853     return;
00854   ++mdnNext;
00855 
00856   // Recursively add any MDNodes referenced by operands.
00857   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
00858     if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
00859       CreateMetadataSlot(Op);
00860 }
00861 
00862 void SlotTracker::CreateAttributeSetSlot(AttributeSet AS) {
00863   assert(AS.hasAttributes(AttributeSet::FunctionIndex) &&
00864          "Doesn't need a slot!");
00865 
00866   as_iterator I = asMap.find(AS);
00867   if (I != asMap.end())
00868     return;
00869 
00870   unsigned DestSlot = asNext++;
00871   asMap[AS] = DestSlot;
00872 }
00873 
00874 //===----------------------------------------------------------------------===//
00875 // AsmWriter Implementation
00876 //===----------------------------------------------------------------------===//
00877 
00878 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
00879                                    TypePrinting *TypePrinter,
00880                                    SlotTracker *Machine,
00881                                    const Module *Context);
00882 
00883 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
00884                                    TypePrinting *TypePrinter,
00885                                    SlotTracker *Machine, const Module *Context,
00886                                    bool FromValue = false);
00887 
00888 static const char *getPredicateText(unsigned predicate) {
00889   const char * pred = "unknown";
00890   switch (predicate) {
00891   case FCmpInst::FCMP_FALSE: pred = "false"; break;
00892   case FCmpInst::FCMP_OEQ:   pred = "oeq"; break;
00893   case FCmpInst::FCMP_OGT:   pred = "ogt"; break;
00894   case FCmpInst::FCMP_OGE:   pred = "oge"; break;
00895   case FCmpInst::FCMP_OLT:   pred = "olt"; break;
00896   case FCmpInst::FCMP_OLE:   pred = "ole"; break;
00897   case FCmpInst::FCMP_ONE:   pred = "one"; break;
00898   case FCmpInst::FCMP_ORD:   pred = "ord"; break;
00899   case FCmpInst::FCMP_UNO:   pred = "uno"; break;
00900   case FCmpInst::FCMP_UEQ:   pred = "ueq"; break;
00901   case FCmpInst::FCMP_UGT:   pred = "ugt"; break;
00902   case FCmpInst::FCMP_UGE:   pred = "uge"; break;
00903   case FCmpInst::FCMP_ULT:   pred = "ult"; break;
00904   case FCmpInst::FCMP_ULE:   pred = "ule"; break;
00905   case FCmpInst::FCMP_UNE:   pred = "une"; break;
00906   case FCmpInst::FCMP_TRUE:  pred = "true"; break;
00907   case ICmpInst::ICMP_EQ:    pred = "eq"; break;
00908   case ICmpInst::ICMP_NE:    pred = "ne"; break;
00909   case ICmpInst::ICMP_SGT:   pred = "sgt"; break;
00910   case ICmpInst::ICMP_SGE:   pred = "sge"; break;
00911   case ICmpInst::ICMP_SLT:   pred = "slt"; break;
00912   case ICmpInst::ICMP_SLE:   pred = "sle"; break;
00913   case ICmpInst::ICMP_UGT:   pred = "ugt"; break;
00914   case ICmpInst::ICMP_UGE:   pred = "uge"; break;
00915   case ICmpInst::ICMP_ULT:   pred = "ult"; break;
00916   case ICmpInst::ICMP_ULE:   pred = "ule"; break;
00917   }
00918   return pred;
00919 }
00920 
00921 static void writeAtomicRMWOperation(raw_ostream &Out,
00922                                     AtomicRMWInst::BinOp Op) {
00923   switch (Op) {
00924   default: Out << " <unknown operation " << Op << ">"; break;
00925   case AtomicRMWInst::Xchg: Out << " xchg"; break;
00926   case AtomicRMWInst::Add:  Out << " add"; break;
00927   case AtomicRMWInst::Sub:  Out << " sub"; break;
00928   case AtomicRMWInst::And:  Out << " and"; break;
00929   case AtomicRMWInst::Nand: Out << " nand"; break;
00930   case AtomicRMWInst::Or:   Out << " or"; break;
00931   case AtomicRMWInst::Xor:  Out << " xor"; break;
00932   case AtomicRMWInst::Max:  Out << " max"; break;
00933   case AtomicRMWInst::Min:  Out << " min"; break;
00934   case AtomicRMWInst::UMax: Out << " umax"; break;
00935   case AtomicRMWInst::UMin: Out << " umin"; break;
00936   }
00937 }
00938 
00939 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
00940   if (const FPMathOperator *FPO = dyn_cast<const FPMathOperator>(U)) {
00941     // Unsafe algebra implies all the others, no need to write them all out
00942     if (FPO->hasUnsafeAlgebra())
00943       Out << " fast";
00944     else {
00945       if (FPO->hasNoNaNs())
00946         Out << " nnan";
00947       if (FPO->hasNoInfs())
00948         Out << " ninf";
00949       if (FPO->hasNoSignedZeros())
00950         Out << " nsz";
00951       if (FPO->hasAllowReciprocal())
00952         Out << " arcp";
00953     }
00954   }
00955 
00956   if (const OverflowingBinaryOperator *OBO =
00957         dyn_cast<OverflowingBinaryOperator>(U)) {
00958     if (OBO->hasNoUnsignedWrap())
00959       Out << " nuw";
00960     if (OBO->hasNoSignedWrap())
00961       Out << " nsw";
00962   } else if (const PossiblyExactOperator *Div =
00963                dyn_cast<PossiblyExactOperator>(U)) {
00964     if (Div->isExact())
00965       Out << " exact";
00966   } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
00967     if (GEP->isInBounds())
00968       Out << " inbounds";
00969   }
00970 }
00971 
00972 static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
00973                                   TypePrinting &TypePrinter,
00974                                   SlotTracker *Machine,
00975                                   const Module *Context) {
00976   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
00977     if (CI->getType()->isIntegerTy(1)) {
00978       Out << (CI->getZExtValue() ? "true" : "false");
00979       return;
00980     }
00981     Out << CI->getValue();
00982     return;
00983   }
00984 
00985   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
00986     if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle ||
00987         &CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble) {
00988       // We would like to output the FP constant value in exponential notation,
00989       // but we cannot do this if doing so will lose precision.  Check here to
00990       // make sure that we only output it in exponential format if we can parse
00991       // the value back and get the same value.
00992       //
00993       bool ignored;
00994       bool isHalf = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEhalf;
00995       bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
00996       bool isInf = CFP->getValueAPF().isInfinity();
00997       bool isNaN = CFP->getValueAPF().isNaN();
00998       if (!isHalf && !isInf && !isNaN) {
00999         double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
01000                                 CFP->getValueAPF().convertToFloat();
01001         SmallString<128> StrVal;
01002         raw_svector_ostream(StrVal) << Val;
01003 
01004         // Check to make sure that the stringized number is not some string like
01005         // "Inf" or NaN, that atof will accept, but the lexer will not.  Check
01006         // that the string matches the "[-+]?[0-9]" regex.
01007         //
01008         if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
01009             ((StrVal[0] == '-' || StrVal[0] == '+') &&
01010              (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
01011           // Reparse stringized version!
01012           if (APFloat(APFloat::IEEEdouble, StrVal).convertToDouble() == Val) {
01013             Out << StrVal.str();
01014             return;
01015           }
01016         }
01017       }
01018       // Otherwise we could not reparse it to exactly the same value, so we must
01019       // output the string in hexadecimal format!  Note that loading and storing
01020       // floating point types changes the bits of NaNs on some hosts, notably
01021       // x86, so we must not use these types.
01022       static_assert(sizeof(double) == sizeof(uint64_t),
01023                     "assuming that double is 64 bits!");
01024       char Buffer[40];
01025       APFloat apf = CFP->getValueAPF();
01026       // Halves and floats are represented in ASCII IR as double, convert.
01027       if (!isDouble)
01028         apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
01029                           &ignored);
01030       Out << "0x" <<
01031               utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()),
01032                             Buffer+40);
01033       return;
01034     }
01035 
01036     // Either half, or some form of long double.
01037     // These appear as a magic letter identifying the type, then a
01038     // fixed number of hex digits.
01039     Out << "0x";
01040     // Bit position, in the current word, of the next nibble to print.
01041     int shiftcount;
01042 
01043     if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
01044       Out << 'K';
01045       // api needed to prevent premature destruction
01046       APInt api = CFP->getValueAPF().bitcastToAPInt();
01047       const uint64_t* p = api.getRawData();
01048       uint64_t word = p[1];
01049       shiftcount = 12;
01050       int width = api.getBitWidth();
01051       for (int j=0; j<width; j+=4, shiftcount-=4) {
01052         unsigned int nibble = (word>>shiftcount) & 15;
01053         if (nibble < 10)
01054           Out << (unsigned char)(nibble + '0');
01055         else
01056           Out << (unsigned char)(nibble - 10 + 'A');
01057         if (shiftcount == 0 && j+4 < width) {
01058           word = *p;
01059           shiftcount = 64;
01060           if (width-j-4 < 64)
01061             shiftcount = width-j-4;
01062         }
01063       }
01064       return;
01065     } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad) {
01066       shiftcount = 60;
01067       Out << 'L';
01068     } else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble) {
01069       shiftcount = 60;
01070       Out << 'M';
01071     } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEhalf) {
01072       shiftcount = 12;
01073       Out << 'H';
01074     } else
01075       llvm_unreachable("Unsupported floating point type");
01076     // api needed to prevent premature destruction
01077     APInt api = CFP->getValueAPF().bitcastToAPInt();
01078     const uint64_t* p = api.getRawData();
01079     uint64_t word = *p;
01080     int width = api.getBitWidth();
01081     for (int j=0; j<width; j+=4, shiftcount-=4) {
01082       unsigned int nibble = (word>>shiftcount) & 15;
01083       if (nibble < 10)
01084         Out << (unsigned char)(nibble + '0');
01085       else
01086         Out << (unsigned char)(nibble - 10 + 'A');
01087       if (shiftcount == 0 && j+4 < width) {
01088         word = *(++p);
01089         shiftcount = 64;
01090         if (width-j-4 < 64)
01091           shiftcount = width-j-4;
01092       }
01093     }
01094     return;
01095   }
01096 
01097   if (isa<ConstantAggregateZero>(CV)) {
01098     Out << "zeroinitializer";
01099     return;
01100   }
01101 
01102   if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
01103     Out << "blockaddress(";
01104     WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine,
01105                            Context);
01106     Out << ", ";
01107     WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine,
01108                            Context);
01109     Out << ")";
01110     return;
01111   }
01112 
01113   if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
01114     Type *ETy = CA->getType()->getElementType();
01115     Out << '[';
01116     TypePrinter.print(ETy, Out);
01117     Out << ' ';
01118     WriteAsOperandInternal(Out, CA->getOperand(0),
01119                            &TypePrinter, Machine,
01120                            Context);
01121     for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
01122       Out << ", ";
01123       TypePrinter.print(ETy, Out);
01124       Out << ' ';
01125       WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine,
01126                              Context);
01127     }
01128     Out << ']';
01129     return;
01130   }
01131 
01132   if (const ConstantDataArray *CA = dyn_cast<ConstantDataArray>(CV)) {
01133     // As a special case, print the array as a string if it is an array of
01134     // i8 with ConstantInt values.
01135     if (CA->isString()) {
01136       Out << "c\"";
01137       PrintEscapedString(CA->getAsString(), Out);
01138       Out << '"';
01139       return;
01140     }
01141 
01142     Type *ETy = CA->getType()->getElementType();
01143     Out << '[';
01144     TypePrinter.print(ETy, Out);
01145     Out << ' ';
01146     WriteAsOperandInternal(Out, CA->getElementAsConstant(0),
01147                            &TypePrinter, Machine,
01148                            Context);
01149     for (unsigned i = 1, e = CA->getNumElements(); i != e; ++i) {
01150       Out << ", ";
01151       TypePrinter.print(ETy, Out);
01152       Out << ' ';
01153       WriteAsOperandInternal(Out, CA->getElementAsConstant(i), &TypePrinter,
01154                              Machine, Context);
01155     }
01156     Out << ']';
01157     return;
01158   }
01159 
01160 
01161   if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
01162     if (CS->getType()->isPacked())
01163       Out << '<';
01164     Out << '{';
01165     unsigned N = CS->getNumOperands();
01166     if (N) {
01167       Out << ' ';
01168       TypePrinter.print(CS->getOperand(0)->getType(), Out);
01169       Out << ' ';
01170 
01171       WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine,
01172                              Context);
01173 
01174       for (unsigned i = 1; i < N; i++) {
01175         Out << ", ";
01176         TypePrinter.print(CS->getOperand(i)->getType(), Out);
01177         Out << ' ';
01178 
01179         WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine,
01180                                Context);
01181       }
01182       Out << ' ';
01183     }
01184 
01185     Out << '}';
01186     if (CS->getType()->isPacked())
01187       Out << '>';
01188     return;
01189   }
01190 
01191   if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) {
01192     Type *ETy = CV->getType()->getVectorElementType();
01193     Out << '<';
01194     TypePrinter.print(ETy, Out);
01195     Out << ' ';
01196     WriteAsOperandInternal(Out, CV->getAggregateElement(0U), &TypePrinter,
01197                            Machine, Context);
01198     for (unsigned i = 1, e = CV->getType()->getVectorNumElements(); i != e;++i){
01199       Out << ", ";
01200       TypePrinter.print(ETy, Out);
01201       Out << ' ';
01202       WriteAsOperandInternal(Out, CV->getAggregateElement(i), &TypePrinter,
01203                              Machine, Context);
01204     }
01205     Out << '>';
01206     return;
01207   }
01208 
01209   if (isa<ConstantPointerNull>(CV)) {
01210     Out << "null";
01211     return;
01212   }
01213 
01214   if (isa<UndefValue>(CV)) {
01215     Out << "undef";
01216     return;
01217   }
01218 
01219   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
01220     Out << CE->getOpcodeName();
01221     WriteOptimizationInfo(Out, CE);
01222     if (CE->isCompare())
01223       Out << ' ' << getPredicateText(CE->getPredicate());
01224     Out << " (";
01225 
01226     for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
01227       TypePrinter.print((*OI)->getType(), Out);
01228       Out << ' ';
01229       WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context);
01230       if (OI+1 != CE->op_end())
01231         Out << ", ";
01232     }
01233 
01234     if (CE->hasIndices()) {
01235       ArrayRef<unsigned> Indices = CE->getIndices();
01236       for (unsigned i = 0, e = Indices.size(); i != e; ++i)
01237         Out << ", " << Indices[i];
01238     }
01239 
01240     if (CE->isCast()) {
01241       Out << " to ";
01242       TypePrinter.print(CE->getType(), Out);
01243     }
01244 
01245     Out << ')';
01246     return;
01247   }
01248 
01249   Out << "<placeholder or erroneous Constant>";
01250 }
01251 
01252 static void writeMDTuple(raw_ostream &Out, const MDTuple *Node,
01253                          TypePrinting *TypePrinter, SlotTracker *Machine,
01254                          const Module *Context) {
01255   Out << "!{";
01256   for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
01257     const Metadata *MD = Node->getOperand(mi);
01258     if (!MD)
01259       Out << "null";
01260     else if (auto *MDV = dyn_cast<ValueAsMetadata>(MD)) {
01261       Value *V = MDV->getValue();
01262       TypePrinter->print(V->getType(), Out);
01263       Out << ' ';
01264       WriteAsOperandInternal(Out, V, TypePrinter, Machine, Context);
01265     } else {
01266       WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
01267     }
01268     if (mi + 1 != me)
01269       Out << ", ";
01270   }
01271 
01272   Out << "}";
01273 }
01274 
01275 namespace {
01276 struct FieldSeparator {
01277   bool Skip;
01278   const char *Sep;
01279   FieldSeparator(const char *Sep = ", ") : Skip(true), Sep(Sep) {}
01280 };
01281 raw_ostream &operator<<(raw_ostream &OS, FieldSeparator &FS) {
01282   if (FS.Skip) {
01283     FS.Skip = false;
01284     return OS;
01285   }
01286   return OS << FS.Sep;
01287 }
01288 } // end namespace
01289 
01290 static void writeMetadataAsOperand(raw_ostream &Out, const Metadata *MD,
01291                                    TypePrinting *TypePrinter,
01292                                    SlotTracker *Machine,
01293                                    const Module *Context) {
01294   if (!MD) {
01295     Out << "null";
01296     return;
01297   }
01298   WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
01299 }
01300 
01301 static void writeTag(raw_ostream &Out, FieldSeparator &FS, const DebugNode *N) {
01302   Out << FS << "tag: ";
01303   if (const char *Tag = dwarf::TagString(N->getTag()))
01304     Out << Tag;
01305   else
01306     Out << N->getTag();
01307 }
01308 
01309 static void writeStringField(raw_ostream &Out, FieldSeparator &FS,
01310                              StringRef Name, StringRef Value,
01311                              bool ShouldSkipEmpty = true) {
01312   if (ShouldSkipEmpty && Value.empty())
01313     return;
01314 
01315   Out << FS << Name << ": \"";
01316   PrintEscapedString(Value, Out);
01317   Out << "\"";
01318 }
01319 
01320 static void writeGenericDebugNode(raw_ostream &Out, const GenericDebugNode *N,
01321                                   TypePrinting *TypePrinter,
01322                                   SlotTracker *Machine, const Module *Context) {
01323   Out << "!GenericDebugNode(";
01324   FieldSeparator FS;
01325   writeTag(Out, FS, N);
01326   writeStringField(Out, FS, "header", N->getHeader());
01327   if (N->getNumDwarfOperands()) {
01328     Out << FS << "operands: {";
01329     FieldSeparator IFS;
01330     for (auto &I : N->dwarf_operands()) {
01331       Out << IFS;
01332       writeMetadataAsOperand(Out, I, TypePrinter, Machine, Context);
01333     }
01334     Out << "}";
01335   }
01336   Out << ")";
01337 }
01338 
01339 static void writeMDLocation(raw_ostream &Out, const MDLocation *DL,
01340                             TypePrinting *TypePrinter, SlotTracker *Machine,
01341                             const Module *Context) {
01342   Out << "!MDLocation(";
01343   FieldSeparator FS;
01344   // Always output the line, since 0 is a relevant and important value for it.
01345   Out << FS << "line: " << DL->getLine();
01346   if (DL->getColumn())
01347     Out << FS << "column: " << DL->getColumn();
01348   Out << FS << "scope: ";
01349   WriteAsOperandInternal(Out, DL->getScope(), TypePrinter, Machine, Context);
01350   if (DL->getInlinedAt()) {
01351     Out << FS << "inlinedAt: ";
01352     WriteAsOperandInternal(Out, DL->getInlinedAt(), TypePrinter, Machine,
01353                            Context);
01354   }
01355   Out << ")";
01356 }
01357 
01358 static void writeMDSubrange(raw_ostream &Out, const MDSubrange *N,
01359                             TypePrinting *, SlotTracker *, const Module *) {
01360   Out << "!MDSubrange(";
01361   FieldSeparator FS;
01362   Out << FS << "count: " << N->getCount();
01363   if (N->getLo())
01364     Out << FS << "lowerBound: " << N->getLo();
01365   Out << ")";
01366 }
01367 
01368 static void writeMDEnumerator(raw_ostream &Out, const MDEnumerator *N,
01369                               TypePrinting *, SlotTracker *, const Module *) {
01370   Out << "!MDEnumerator(";
01371   FieldSeparator FS;
01372   writeStringField(Out, FS, "name", N->getName(), /* ShouldSkipEmpty */ false);
01373   Out << FS << "value: " << N->getValue();
01374   Out << ")";
01375 }
01376 
01377 static void writeMDBasicType(raw_ostream &Out, const MDBasicType *N,
01378                              TypePrinting *, SlotTracker *, const Module *) {
01379   Out << "!MDBasicType(";
01380   FieldSeparator FS;
01381   if (N->getTag() != dwarf::DW_TAG_base_type)
01382     writeTag(Out, FS, N);
01383   writeStringField(Out, FS, "name", N->getName());
01384   if (N->getSizeInBits())
01385     Out << FS << "size: " << N->getSizeInBits();
01386   if (N->getAlignInBits())
01387     Out << FS << "align: " << N->getAlignInBits();
01388   if (unsigned Encoding = N->getEncoding()) {
01389     Out << FS << "encoding: ";
01390     if (const char *S = dwarf::AttributeEncodingString(Encoding))
01391       Out << S;
01392     else
01393       Out << Encoding;
01394   }
01395   Out << ")";
01396 }
01397 
01398 static void writeDIFlags(raw_ostream &Out, unsigned Flags) {
01399   SmallVector<unsigned, 8> SplitFlags;
01400   unsigned Extra = DIDescriptor::splitFlags(Flags, SplitFlags);
01401 
01402   FieldSeparator FS(" | ");
01403   for (unsigned F : SplitFlags) {
01404     const char *StringF = DIDescriptor::getFlagString(F);
01405     assert(StringF && "Expected valid flag");
01406     Out << FS << StringF;
01407   }
01408   if (Extra || SplitFlags.empty())
01409     Out << FS << Extra;
01410 }
01411 
01412 static void writeMDDerivedType(raw_ostream &Out, const MDDerivedType *N,
01413                                TypePrinting *TypePrinter, SlotTracker *Machine,
01414                                const Module *Context) {
01415   Out << "!MDDerivedType(";
01416   FieldSeparator FS;
01417   writeTag(Out, FS, N);
01418   writeStringField(Out, FS, "name", N->getName());
01419   if (N->getScope()) {
01420     Out << FS << "scope: ";
01421     writeMetadataAsOperand(Out, N->getScope(), TypePrinter, Machine, Context);
01422   }
01423   if (N->getFile()) {
01424     Out << FS << "file: ";
01425     writeMetadataAsOperand(Out, N->getFile(), TypePrinter, Machine,
01426                            Context);
01427   }
01428   if (N->getLine())
01429     Out << FS << "line: " << N->getLine();
01430   Out << FS << "baseType: ";
01431   writeMetadataAsOperand(Out, N->getBaseType(), TypePrinter, Machine, Context);
01432   if (N->getSizeInBits())
01433     Out << FS << "size: " << N->getSizeInBits();
01434   if (N->getAlignInBits())
01435     Out << FS << "align: " << N->getAlignInBits();
01436   if (N->getOffsetInBits())
01437     Out << FS << "offset: " << N->getOffsetInBits();
01438   if (auto Flags = N->getFlags()) {
01439     Out << FS << "flags: ";
01440     writeDIFlags(Out, Flags);
01441   }
01442   if (N->getExtraData()) {
01443     Out << FS << "extraData: ";
01444     writeMetadataAsOperand(Out, N->getExtraData(), TypePrinter, Machine,
01445                            Context);
01446   }
01447   Out << ")";
01448 }
01449 
01450 static void writeMDCompositeType(raw_ostream &Out, const MDCompositeType *N,
01451                                  TypePrinting *TypePrinter,
01452                                  SlotTracker *Machine, const Module *Context) {
01453   Out << "!MDCompositeType(";
01454   FieldSeparator FS;
01455   writeTag(Out, FS, N);
01456   writeStringField(Out, FS, "name", N->getName());
01457   if (N->getScope()) {
01458     Out << FS << "scope: ";
01459     writeMetadataAsOperand(Out, N->getScope(), TypePrinter, Machine, Context);
01460   }
01461   if (N->getFile()) {
01462     Out << FS << "file: ";
01463     writeMetadataAsOperand(Out, N->getFile(), TypePrinter, Machine,
01464                            Context);
01465   }
01466   if (N->getLine())
01467     Out << FS << "line: " << N->getLine();
01468   if (N->getBaseType()) {
01469     Out << FS << "baseType: ";
01470     writeMetadataAsOperand(Out, N->getBaseType(), TypePrinter, Machine,
01471                            Context);
01472   }
01473   if (N->getSizeInBits())
01474     Out << FS << "size: " << N->getSizeInBits();
01475   if (N->getAlignInBits())
01476     Out << FS << "align: " << N->getAlignInBits();
01477   if (N->getOffsetInBits())
01478     Out << FS << "offset: " << N->getOffsetInBits();
01479   if (auto Flags = N->getFlags()) {
01480     Out << FS << "flags: ";
01481     writeDIFlags(Out, Flags);
01482   }
01483   if (N->getElements()) {
01484     Out << FS << "elements: ";
01485     writeMetadataAsOperand(Out, N->getElements(), TypePrinter, Machine,
01486                            Context);
01487   }
01488   if (unsigned Lang = N->getRuntimeLang()) {
01489     Out << FS << "runtimeLang: ";
01490     if (const char *S = dwarf::LanguageString(Lang))
01491       Out << S;
01492     else
01493       Out << Lang;
01494   }
01495 
01496   if (N->getVTableHolder()) {
01497     Out << FS << "vtableHolder: ";
01498     writeMetadataAsOperand(Out, N->getVTableHolder(), TypePrinter, Machine,
01499                            Context);
01500   }
01501   if (N->getTemplateParams()) {
01502     Out << FS << "templateParams: ";
01503     writeMetadataAsOperand(Out, N->getTemplateParams(), TypePrinter, Machine,
01504                            Context);
01505   }
01506   writeStringField(Out, FS, "identifier", N->getIdentifier());
01507   Out << ")";
01508 }
01509 
01510 static void writeMDSubroutineType(raw_ostream &Out, const MDSubroutineType *N,
01511                                   TypePrinting *TypePrinter,
01512                                   SlotTracker *Machine, const Module *Context) {
01513   Out << "!MDSubroutineType(";
01514   FieldSeparator FS;
01515   if (auto Flags = N->getFlags()) {
01516     Out << FS << "flags: ";
01517     writeDIFlags(Out, Flags);
01518   }
01519   Out << FS << "types: ";
01520   writeMetadataAsOperand(Out, N->getTypeArray(), TypePrinter, Machine, Context);
01521   Out << ")";
01522 }
01523 
01524 static void writeMDFile(raw_ostream &Out, const MDFile *N, TypePrinting *,
01525                         SlotTracker *, const Module *) {
01526   Out << "!MDFile(";
01527   FieldSeparator FS;
01528   writeStringField(Out, FS, "filename", N->getFilename(),
01529                    /* ShouldSkipEmpty */ false);
01530   writeStringField(Out, FS, "directory", N->getDirectory(),
01531                    /* ShouldSkipEmpty */ false);
01532   Out << ")";
01533 }
01534 
01535 static void writeMDCompileUnit(raw_ostream &Out, const MDCompileUnit *N,
01536                                TypePrinting *TypePrinter, SlotTracker *Machine,
01537                                const Module *Context) {
01538   Out << "!MDCompileUnit(";
01539   FieldSeparator FS;
01540   Out << FS << "language: ";
01541   if (const char *Lang = dwarf::LanguageString(N->getSourceLanguage()))
01542     Out << Lang;
01543   else
01544     Out << N->getSourceLanguage();
01545   Out << FS << "file: ";
01546   writeMetadataAsOperand(Out, N->getFile(), TypePrinter, Machine, Context);
01547   writeStringField(Out, FS, "producer", N->getProducer());
01548   Out << FS << "isOptimized: " << (N->isOptimized() ? "true" : "false");
01549   writeStringField(Out, FS, "flags", N->getFlags());
01550   Out << FS << "runtimeVersion: " << N->getRuntimeVersion();
01551   writeStringField(Out, FS, "splitDebugFilename", N->getSplitDebugFilename());
01552   Out << FS << "emissionKind: " << N->getEmissionKind();
01553   if (N->getEnumTypes()) {
01554     Out << FS << "enums: ";
01555     writeMetadataAsOperand(Out, N->getEnumTypes(), TypePrinter, Machine,
01556                            Context);
01557   }
01558   if (N->getRetainedTypes()) {
01559     Out << FS << "retainedTypes: ";
01560     writeMetadataAsOperand(Out, N->getRetainedTypes(), TypePrinter, Machine,
01561                            Context);
01562   }
01563   if (N->getSubprograms()) {
01564     Out << FS << "subprograms: ";
01565     writeMetadataAsOperand(Out, N->getSubprograms(), TypePrinter, Machine,
01566                            Context);
01567   }
01568   if (N->getGlobalVariables()) {
01569     Out << FS << "globals: ";
01570     writeMetadataAsOperand(Out, N->getGlobalVariables(), TypePrinter, Machine,
01571                            Context);
01572   }
01573   if (N->getImportedEntities()) {
01574     Out << FS << "imports: ";
01575     writeMetadataAsOperand(Out, N->getImportedEntities(), TypePrinter, Machine,
01576                            Context);
01577   }
01578   Out << ")";
01579 }
01580 
01581 static void writeMDSubprogram(raw_ostream &Out, const MDSubprogram *N,
01582                               TypePrinting *TypePrinter, SlotTracker *Machine,
01583                               const Module *Context) {
01584   Out << "!MDSubprogram(";
01585   FieldSeparator FS;
01586   writeStringField(Out, FS, "name", N->getName());
01587   writeStringField(Out, FS, "linkageName", N->getLinkageName());
01588   Out << FS << "scope: ";
01589   writeMetadataAsOperand(Out, N->getScope(), TypePrinter, Machine, Context);
01590   if (N->getFile()) {
01591     Out << FS << "file: ";
01592     writeMetadataAsOperand(Out, N->getFile(), TypePrinter, Machine,
01593                            Context);
01594   }
01595   if (N->getLine())
01596     Out << FS << "line: " << N->getLine();
01597   if (N->getType()) {
01598     Out << FS << "type: ";
01599     writeMetadataAsOperand(Out, N->getType(), TypePrinter, Machine,
01600                            Context);
01601   }
01602   Out << FS << "isLocal: " << (N->isLocalToUnit() ? "true" : "false");
01603   Out << FS << "isDefinition: " << (N->isDefinition() ? "true" : "false");
01604   if (N->getScopeLine())
01605     Out << FS << "scopeLine: " << N->getScopeLine();
01606   if (N->getContainingType()) {
01607     Out << FS << "containingType: ";
01608     writeMetadataAsOperand(Out, N->getContainingType(), TypePrinter, Machine,
01609                            Context);
01610   }
01611   if (unsigned V = N->getVirtuality()) {
01612     Out << FS << "virtuality: ";
01613     if (const char *S = dwarf::VirtualityString(V))
01614       Out << S;
01615     else
01616       Out << V;
01617   }
01618   if (N->getVirtualIndex())
01619     Out << FS << "virtualIndex: " << N->getVirtualIndex();
01620   if (auto Flags = N->getFlags()) {
01621     Out << FS << "flags: ";
01622     writeDIFlags(Out, Flags);
01623   }
01624   Out << FS << "isOptimized: " << (N->isOptimized() ? "true" : "false");
01625   if (N->getFunction()) {
01626     Out << FS << "function: ";
01627     writeMetadataAsOperand(Out, N->getFunction(), TypePrinter, Machine,
01628                            Context);
01629   }
01630   if (N->getTemplateParams()) {
01631     Out << FS << "templateParams: ";
01632     writeMetadataAsOperand(Out, N->getTemplateParams(), TypePrinter, Machine,
01633                            Context);
01634   }
01635   if (N->getDeclaration()) {
01636     Out << FS << "declaration: ";
01637     writeMetadataAsOperand(Out, N->getDeclaration(), TypePrinter, Machine,
01638                            Context);
01639   }
01640   if (N->getVariables()) {
01641     Out << FS << "variables: ";
01642     writeMetadataAsOperand(Out, N->getVariables(), TypePrinter, Machine,
01643                            Context);
01644   }
01645   Out << ")";
01646 }
01647 
01648 static void writeMDLexicalBlock(raw_ostream &Out, const MDLexicalBlock *N,
01649                               TypePrinting *TypePrinter, SlotTracker *Machine,
01650                               const Module *Context) {
01651   Out << "!MDLexicalBlock(";
01652   FieldSeparator FS;
01653   Out << FS << "scope: ";
01654   writeMetadataAsOperand(Out, N->getScope(), TypePrinter, Machine, Context);
01655   if (N->getFile()) {
01656     Out << FS << "file: ";
01657     writeMetadataAsOperand(Out, N->getFile(), TypePrinter, Machine,
01658                            Context);
01659   }
01660   if (N->getLine())
01661     Out << FS << "line: " << N->getLine();
01662   if (N->getColumn())
01663     Out << FS << "column: " << N->getColumn();
01664   Out << ")";
01665 }
01666 
01667 static void writeMDLexicalBlockFile(raw_ostream &Out,
01668                                     const MDLexicalBlockFile *N,
01669                                     TypePrinting *TypePrinter,
01670                                     SlotTracker *Machine,
01671                                     const Module *Context) {
01672   Out << "!MDLexicalBlockFile(";
01673   FieldSeparator FS;
01674   Out << FS << "scope: ";
01675   writeMetadataAsOperand(Out, N->getScope(), TypePrinter, Machine, Context);
01676   if (N->getFile()) {
01677     Out << FS << "file: ";
01678     writeMetadataAsOperand(Out, N->getFile(), TypePrinter, Machine,
01679                            Context);
01680   }
01681   Out << FS << "discriminator: " << N->getDiscriminator();
01682   Out << ")";
01683 }
01684 
01685 static void writeMDNamespace(raw_ostream &Out, const MDNamespace *N,
01686                              TypePrinting *TypePrinter, SlotTracker *Machine,
01687                              const Module *Context) {
01688   Out << "!MDNamespace(";
01689   FieldSeparator FS;
01690   writeStringField(Out, FS, "name", N->getName());
01691   Out << FS << "scope: ";
01692   writeMetadataAsOperand(Out, N->getScope(), TypePrinter, Machine, Context);
01693   if (N->getFile()) {
01694     Out << FS << "file: ";
01695     writeMetadataAsOperand(Out, N->getFile(), TypePrinter, Machine, Context);
01696   }
01697   if (N->getLine())
01698     Out << FS << "line: " << N->getLine();
01699   Out << ")";
01700 }
01701 
01702 static void writeMDTemplateTypeParameter(raw_ostream &Out,
01703                                          const MDTemplateTypeParameter *N,
01704                                          TypePrinting *TypePrinter,
01705                                          SlotTracker *Machine,
01706                                          const Module *Context) {
01707   Out << "!MDTemplateTypeParameter(";
01708   FieldSeparator FS;
01709   writeStringField(Out, FS, "name", N->getName());
01710   Out << FS << "type: ";
01711   writeMetadataAsOperand(Out, N->getType(), TypePrinter, Machine, Context);
01712   Out << ")";
01713 }
01714 
01715 static void writeMDTemplateValueParameter(raw_ostream &Out,
01716                                           const MDTemplateValueParameter *N,
01717                                           TypePrinting *TypePrinter,
01718                                           SlotTracker *Machine,
01719                                           const Module *Context) {
01720   Out << "!MDTemplateValueParameter(";
01721   FieldSeparator FS;
01722   if (N->getTag() != dwarf::DW_TAG_template_value_parameter)
01723     writeTag(Out, FS, N);
01724   writeStringField(Out, FS, "name", N->getName());
01725   if (auto *Type = N->getType()) {
01726     Out << FS << "type: ";
01727     writeMetadataAsOperand(Out, Type, TypePrinter, Machine, Context);
01728   }
01729   Out << FS << "value: ";
01730   writeMetadataAsOperand(Out, N->getValue(), TypePrinter, Machine, Context);
01731   Out << ")";
01732 }
01733 
01734 static void writeMDGlobalVariable(raw_ostream &Out, const MDGlobalVariable *N,
01735                                   TypePrinting *TypePrinter,
01736                                   SlotTracker *Machine, const Module *Context) {
01737   Out << "!MDGlobalVariable(";
01738   FieldSeparator FS;
01739   writeStringField(Out, FS, "name", N->getName());
01740   writeStringField(Out, FS, "linkageName", N->getLinkageName());
01741   Out << FS << "scope: ";
01742   writeMetadataAsOperand(Out, N->getScope(), TypePrinter, Machine, Context);
01743   if (N->getFile()) {
01744     Out << FS << "file: ";
01745     writeMetadataAsOperand(Out, N->getFile(), TypePrinter, Machine,
01746                            Context);
01747   }
01748   if (N->getLine())
01749     Out << FS << "line: " << N->getLine();
01750   if (N->getType()) {
01751     Out << FS << "type: ";
01752     writeMetadataAsOperand(Out, N->getType(), TypePrinter, Machine,
01753                            Context);
01754   }
01755   Out << FS << "isLocal: " << (N->isLocalToUnit() ? "true" : "false");
01756   Out << FS << "isDefinition: " << (N->isDefinition() ? "true" : "false");
01757   if (N->getVariable()) {
01758     Out << FS << "variable: ";
01759     writeMetadataAsOperand(Out, N->getVariable(), TypePrinter, Machine,
01760                            Context);
01761   }
01762   if (N->getStaticDataMemberDeclaration()) {
01763     Out << FS << "declaration: ";
01764     writeMetadataAsOperand(Out, N->getStaticDataMemberDeclaration(),
01765                            TypePrinter, Machine, Context);
01766   }
01767   Out << ")";
01768 }
01769 
01770 static void writeMDLocalVariable(raw_ostream &Out, const MDLocalVariable *N,
01771                                  TypePrinting *TypePrinter,
01772                                  SlotTracker *Machine, const Module *Context) {
01773   Out << "!MDLocalVariable(";
01774   FieldSeparator FS;
01775   writeTag(Out, FS, N);
01776   writeStringField(Out, FS, "name", N->getName());
01777   if (N->getTag() == dwarf::DW_TAG_arg_variable || N->getArg())
01778     Out << FS << "arg: " << N->getArg();
01779   Out << FS << "scope: ";
01780   writeMetadataAsOperand(Out, N->getScope(), TypePrinter, Machine, Context);
01781   if (N->getFile()) {
01782     Out << FS << "file: ";
01783     writeMetadataAsOperand(Out, N->getFile(), TypePrinter, Machine,
01784                            Context);
01785   }
01786   if (N->getLine())
01787     Out << FS << "line: " << N->getLine();
01788   if (N->getType()) {
01789     Out << FS << "type: ";
01790     writeMetadataAsOperand(Out, N->getType(), TypePrinter, Machine,
01791                            Context);
01792   }
01793   if (auto Flags = N->getFlags()) {
01794     Out << FS << "flags: ";
01795     writeDIFlags(Out, Flags);
01796   }
01797   if (N->getInlinedAt()) {
01798     Out << FS << "inlinedAt: ";
01799     writeMetadataAsOperand(Out, N->getInlinedAt(), TypePrinter, Machine,
01800                            Context);
01801   }
01802   Out << ")";
01803 }
01804 
01805 static void writeMDExpression(raw_ostream &Out, const MDExpression *N,
01806                               TypePrinting *TypePrinter, SlotTracker *Machine,
01807                               const Module *Context) {
01808   Out << "!MDExpression(";
01809   FieldSeparator FS;
01810   if (N->isValid()) {
01811     for (auto I = N->expr_op_begin(), E = N->expr_op_end(); I != E; ++I) {
01812       const char *OpStr = dwarf::OperationEncodingString(I->getOp());
01813       assert(OpStr && "Expected valid opcode");
01814 
01815       Out << FS << OpStr;
01816       for (unsigned A = 0, AE = I->getNumArgs(); A != AE; ++A)
01817         Out << FS << I->getArg(A);
01818     }
01819   } else {
01820     for (const auto &I : N->getElements())
01821       Out << FS << I;
01822   }
01823   Out << ")";
01824 }
01825 
01826 static void writeMDObjCProperty(raw_ostream &Out, const MDObjCProperty *N,
01827                                 TypePrinting *TypePrinter, SlotTracker *Machine,
01828                                 const Module *Context) {
01829   Out << "!MDObjCProperty(";
01830   FieldSeparator FS;
01831   writeStringField(Out, FS, "name", N->getName());
01832   if (N->getFile()) {
01833     Out << FS << "file: ";
01834     writeMetadataAsOperand(Out, N->getFile(), TypePrinter, Machine, Context);
01835   }
01836   if (N->getLine())
01837     Out << FS << "line: " << N->getLine();
01838   writeStringField(Out, FS, "setter", N->getSetterName());
01839   writeStringField(Out, FS, "getter", N->getGetterName());
01840   if (N->getAttributes())
01841     Out << FS << "attributes: " << N->getAttributes();
01842   if (N->getType()) {
01843     Out << FS << "type: ";
01844     writeMetadataAsOperand(Out, N->getType(), TypePrinter, Machine, Context);
01845   }
01846   Out << ")";
01847 }
01848 
01849 static void writeMDImportedEntity(raw_ostream &Out, const MDImportedEntity *N,
01850                                   TypePrinting *TypePrinter,
01851                                   SlotTracker *Machine, const Module *Context) {
01852   Out << "!MDImportedEntity(";
01853   FieldSeparator FS;
01854   writeTag(Out, FS, N);
01855   writeStringField(Out, FS, "name", N->getName());
01856   Out << FS << "scope: ";
01857   writeMetadataAsOperand(Out, N->getScope(), TypePrinter, Machine, Context);
01858   if (N->getEntity()) {
01859     Out << FS << "entity: ";
01860     writeMetadataAsOperand(Out, N->getEntity(), TypePrinter, Machine, Context);
01861   }
01862   if (N->getLine())
01863     Out << FS << "line: " << N->getLine();
01864   Out << ")";
01865 }
01866 
01867 
01868 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
01869                                     TypePrinting *TypePrinter,
01870                                     SlotTracker *Machine,
01871                                     const Module *Context) {
01872   assert(!Node->isTemporary() && "Unexpected forward declaration");
01873 
01874   if (Node->isDistinct())
01875     Out << "distinct ";
01876 
01877   switch (Node->getMetadataID()) {
01878   default:
01879     llvm_unreachable("Expected uniquable MDNode");
01880 #define HANDLE_MDNODE_LEAF(CLASS)                                              \
01881   case Metadata::CLASS##Kind:                                                  \
01882     write##CLASS(Out, cast<CLASS>(Node), TypePrinter, Machine, Context);       \
01883     break;
01884 #include "llvm/IR/Metadata.def"
01885   }
01886 }
01887 
01888 // Full implementation of printing a Value as an operand with support for
01889 // TypePrinting, etc.
01890 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
01891                                    TypePrinting *TypePrinter,
01892                                    SlotTracker *Machine,
01893                                    const Module *Context) {
01894   if (V->hasName()) {
01895     PrintLLVMName(Out, V);
01896     return;
01897   }
01898 
01899   const Constant *CV = dyn_cast<Constant>(V);
01900   if (CV && !isa<GlobalValue>(CV)) {
01901     assert(TypePrinter && "Constants require TypePrinting!");
01902     WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context);
01903     return;
01904   }
01905 
01906   if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
01907     Out << "asm ";
01908     if (IA->hasSideEffects())
01909       Out << "sideeffect ";
01910     if (IA->isAlignStack())
01911       Out << "alignstack ";
01912     // We don't emit the AD_ATT dialect as it's the assumed default.
01913     if (IA->getDialect() == InlineAsm::AD_Intel)
01914       Out << "inteldialect ";
01915     Out << '"';
01916     PrintEscapedString(IA->getAsmString(), Out);
01917     Out << "\", \"";
01918     PrintEscapedString(IA->getConstraintString(), Out);
01919     Out << '"';
01920     return;
01921   }
01922 
01923   if (auto *MD = dyn_cast<MetadataAsValue>(V)) {
01924     WriteAsOperandInternal(Out, MD->getMetadata(), TypePrinter, Machine,
01925                            Context, /* FromValue */ true);
01926     return;
01927   }
01928 
01929   char Prefix = '%';
01930   int Slot;
01931   // If we have a SlotTracker, use it.
01932   if (Machine) {
01933     if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
01934       Slot = Machine->getGlobalSlot(GV);
01935       Prefix = '@';
01936     } else {
01937       Slot = Machine->getLocalSlot(V);
01938 
01939       // If the local value didn't succeed, then we may be referring to a value
01940       // from a different function.  Translate it, as this can happen when using
01941       // address of blocks.
01942       if (Slot == -1)
01943         if ((Machine = createSlotTracker(V))) {
01944           Slot = Machine->getLocalSlot(V);
01945           delete Machine;
01946         }
01947     }
01948   } else if ((Machine = createSlotTracker(V))) {
01949     // Otherwise, create one to get the # and then destroy it.
01950     if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
01951       Slot = Machine->getGlobalSlot(GV);
01952       Prefix = '@';
01953     } else {
01954       Slot = Machine->getLocalSlot(V);
01955     }
01956     delete Machine;
01957     Machine = nullptr;
01958   } else {
01959     Slot = -1;
01960   }
01961 
01962   if (Slot != -1)
01963     Out << Prefix << Slot;
01964   else
01965     Out << "<badref>";
01966 }
01967 
01968 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
01969                                    TypePrinting *TypePrinter,
01970                                    SlotTracker *Machine, const Module *Context,
01971                                    bool FromValue) {
01972   if (const MDNode *N = dyn_cast<MDNode>(MD)) {
01973     if (!Machine)
01974       Machine = new SlotTracker(Context);
01975     int Slot = Machine->getMetadataSlot(N);
01976     if (Slot == -1)
01977       // Give the pointer value instead of "badref", since this comes up all
01978       // the time when debugging.
01979       Out << "<" << N << ">";
01980     else
01981       Out << '!' << Slot;
01982     return;
01983   }
01984 
01985   if (const MDString *MDS = dyn_cast<MDString>(MD)) {
01986     Out << "!\"";
01987     PrintEscapedString(MDS->getString(), Out);
01988     Out << '"';
01989     return;
01990   }
01991 
01992   auto *V = cast<ValueAsMetadata>(MD);
01993   assert(TypePrinter && "TypePrinter required for metadata values");
01994   assert((FromValue || !isa<LocalAsMetadata>(V)) &&
01995          "Unexpected function-local metadata outside of value argument");
01996 
01997   TypePrinter->print(V->getValue()->getType(), Out);
01998   Out << ' ';
01999   WriteAsOperandInternal(Out, V->getValue(), TypePrinter, Machine, Context);
02000 }
02001 
02002 void AssemblyWriter::init() {
02003   if (!TheModule)
02004     return;
02005   TypePrinter.incorporateTypes(*TheModule);
02006   for (const Function &F : *TheModule)
02007     if (const Comdat *C = F.getComdat())
02008       Comdats.insert(C);
02009   for (const GlobalVariable &GV : TheModule->globals())
02010     if (const Comdat *C = GV.getComdat())
02011       Comdats.insert(C);
02012 }
02013 
02014 
02015 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
02016                                const Module *M,
02017                                AssemblyAnnotationWriter *AAW)
02018   : Out(o), TheModule(M), Machine(Mac), AnnotationWriter(AAW) {
02019   init();
02020 }
02021 
02022 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, const Module *M,
02023                                AssemblyAnnotationWriter *AAW)
02024   : Out(o), TheModule(M), ModuleSlotTracker(createSlotTracker(M)),
02025     Machine(*ModuleSlotTracker), AnnotationWriter(AAW) {
02026   init();
02027 }
02028 
02029 AssemblyWriter::~AssemblyWriter() { }
02030 
02031 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
02032   if (!Operand) {
02033     Out << "<null operand!>";
02034     return;
02035   }
02036   if (PrintType) {
02037     TypePrinter.print(Operand->getType(), Out);
02038     Out << ' ';
02039   }
02040   WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
02041 }
02042 
02043 void AssemblyWriter::writeAtomic(AtomicOrdering Ordering,
02044                                  SynchronizationScope SynchScope) {
02045   if (Ordering == NotAtomic)
02046     return;
02047 
02048   switch (SynchScope) {
02049   case SingleThread: Out << " singlethread"; break;
02050   case CrossThread: break;
02051   }
02052 
02053   switch (Ordering) {
02054   default: Out << " <bad ordering " << int(Ordering) << ">"; break;
02055   case Unordered: Out << " unordered"; break;
02056   case Monotonic: Out << " monotonic"; break;
02057   case Acquire: Out << " acquire"; break;
02058   case Release: Out << " release"; break;
02059   case AcquireRelease: Out << " acq_rel"; break;
02060   case SequentiallyConsistent: Out << " seq_cst"; break;
02061   }
02062 }
02063 
02064 void AssemblyWriter::writeAtomicCmpXchg(AtomicOrdering SuccessOrdering,
02065                                         AtomicOrdering FailureOrdering,
02066                                         SynchronizationScope SynchScope) {
02067   assert(SuccessOrdering != NotAtomic && FailureOrdering != NotAtomic);
02068 
02069   switch (SynchScope) {
02070   case SingleThread: Out << " singlethread"; break;
02071   case CrossThread: break;
02072   }
02073 
02074   switch (SuccessOrdering) {
02075   default: Out << " <bad ordering " << int(SuccessOrdering) << ">"; break;
02076   case Unordered: Out << " unordered"; break;
02077   case Monotonic: Out << " monotonic"; break;
02078   case Acquire: Out << " acquire"; break;
02079   case Release: Out << " release"; break;
02080   case AcquireRelease: Out << " acq_rel"; break;
02081   case SequentiallyConsistent: Out << " seq_cst"; break;
02082   }
02083 
02084   switch (FailureOrdering) {
02085   default: Out << " <bad ordering " << int(FailureOrdering) << ">"; break;
02086   case Unordered: Out << " unordered"; break;
02087   case Monotonic: Out << " monotonic"; break;
02088   case Acquire: Out << " acquire"; break;
02089   case Release: Out << " release"; break;
02090   case AcquireRelease: Out << " acq_rel"; break;
02091   case SequentiallyConsistent: Out << " seq_cst"; break;
02092   }
02093 }
02094 
02095 void AssemblyWriter::writeParamOperand(const Value *Operand,
02096                                        AttributeSet Attrs, unsigned Idx) {
02097   if (!Operand) {
02098     Out << "<null operand!>";
02099     return;
02100   }
02101 
02102   // Print the type
02103   TypePrinter.print(Operand->getType(), Out);
02104   // Print parameter attributes list
02105   if (Attrs.hasAttributes(Idx))
02106     Out << ' ' << Attrs.getAsString(Idx);
02107   Out << ' ';
02108   // Print the operand
02109   WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
02110 }
02111 
02112 void AssemblyWriter::printModule(const Module *M) {
02113   Machine.initialize();
02114 
02115   if (shouldPreserveAssemblyUseListOrder())
02116     UseListOrders = predictUseListOrder(M);
02117 
02118   if (!M->getModuleIdentifier().empty() &&
02119       // Don't print the ID if it will start a new line (which would
02120       // require a comment char before it).
02121       M->getModuleIdentifier().find('\n') == std::string::npos)
02122     Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
02123 
02124   const std::string &DL = M->getDataLayoutStr();
02125   if (!DL.empty())
02126     Out << "target datalayout = \"" << DL << "\"\n";
02127   if (!M->getTargetTriple().empty())
02128     Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
02129 
02130   if (!M->getModuleInlineAsm().empty()) {
02131     // Split the string into lines, to make it easier to read the .ll file.
02132     std::string Asm = M->getModuleInlineAsm();
02133     size_t CurPos = 0;
02134     size_t NewLine = Asm.find_first_of('\n', CurPos);
02135     Out << '\n';
02136     while (NewLine != std::string::npos) {
02137       // We found a newline, print the portion of the asm string from the
02138       // last newline up to this newline.
02139       Out << "module asm \"";
02140       PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
02141                          Out);
02142       Out << "\"\n";
02143       CurPos = NewLine+1;
02144       NewLine = Asm.find_first_of('\n', CurPos);
02145     }
02146     std::string rest(Asm.begin()+CurPos, Asm.end());
02147     if (!rest.empty()) {
02148       Out << "module asm \"";
02149       PrintEscapedString(rest, Out);
02150       Out << "\"\n";
02151     }
02152   }
02153 
02154   printTypeIdentities();
02155 
02156   // Output all comdats.
02157   if (!Comdats.empty())
02158     Out << '\n';
02159   for (const Comdat *C : Comdats) {
02160     printComdat(C);
02161     if (C != Comdats.back())
02162       Out << '\n';
02163   }
02164 
02165   // Output all globals.
02166   if (!M->global_empty()) Out << '\n';
02167   for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
02168        I != E; ++I) {
02169     printGlobal(I); Out << '\n';
02170   }
02171 
02172   // Output all aliases.
02173   if (!M->alias_empty()) Out << "\n";
02174   for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
02175        I != E; ++I)
02176     printAlias(I);
02177 
02178   // Output global use-lists.
02179   printUseLists(nullptr);
02180 
02181   // Output all of the functions.
02182   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
02183     printFunction(I);
02184   assert(UseListOrders.empty() && "All use-lists should have been consumed");
02185 
02186   // Output all attribute groups.
02187   if (!Machine.as_empty()) {
02188     Out << '\n';
02189     writeAllAttributeGroups();
02190   }
02191 
02192   // Output named metadata.
02193   if (!M->named_metadata_empty()) Out << '\n';
02194 
02195   for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
02196        E = M->named_metadata_end(); I != E; ++I)
02197     printNamedMDNode(I);
02198 
02199   // Output metadata.
02200   if (!Machine.mdn_empty()) {
02201     Out << '\n';
02202     writeAllMDNodes();
02203   }
02204 }
02205 
02206 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
02207   Out << '!';
02208   StringRef Name = NMD->getName();
02209   if (Name.empty()) {
02210     Out << "<empty name> ";
02211   } else {
02212     if (isalpha(static_cast<unsigned char>(Name[0])) ||
02213         Name[0] == '-' || Name[0] == '$' ||
02214         Name[0] == '.' || Name[0] == '_')
02215       Out << Name[0];
02216     else
02217       Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F);
02218     for (unsigned i = 1, e = Name.size(); i != e; ++i) {
02219       unsigned char C = Name[i];
02220       if (isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' ||
02221           C == '.' || C == '_')
02222         Out << C;
02223       else
02224         Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
02225     }
02226   }
02227   Out << " = !{";
02228   for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
02229     if (i) Out << ", ";
02230     int Slot = Machine.getMetadataSlot(NMD->getOperand(i));
02231     if (Slot == -1)
02232       Out << "<badref>";
02233     else
02234       Out << '!' << Slot;
02235   }
02236   Out << "}\n";
02237 }
02238 
02239 
02240 static void PrintLinkage(GlobalValue::LinkageTypes LT,
02241                          formatted_raw_ostream &Out) {
02242   switch (LT) {
02243   case GlobalValue::ExternalLinkage: break;
02244   case GlobalValue::PrivateLinkage:       Out << "private ";        break;
02245   case GlobalValue::InternalLinkage:      Out << "internal ";       break;
02246   case GlobalValue::LinkOnceAnyLinkage:   Out << "linkonce ";       break;
02247   case GlobalValue::LinkOnceODRLinkage:   Out << "linkonce_odr ";   break;
02248   case GlobalValue::WeakAnyLinkage:       Out << "weak ";           break;
02249   case GlobalValue::WeakODRLinkage:       Out << "weak_odr ";       break;
02250   case GlobalValue::CommonLinkage:        Out << "common ";         break;
02251   case GlobalValue::AppendingLinkage:     Out << "appending ";      break;
02252   case GlobalValue::ExternalWeakLinkage:  Out << "extern_weak ";    break;
02253   case GlobalValue::AvailableExternallyLinkage:
02254     Out << "available_externally ";
02255     break;
02256   }
02257 }
02258 
02259 
02260 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
02261                             formatted_raw_ostream &Out) {
02262   switch (Vis) {
02263   case GlobalValue::DefaultVisibility: break;
02264   case GlobalValue::HiddenVisibility:    Out << "hidden "; break;
02265   case GlobalValue::ProtectedVisibility: Out << "protected "; break;
02266   }
02267 }
02268 
02269 static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT,
02270                                  formatted_raw_ostream &Out) {
02271   switch (SCT) {
02272   case GlobalValue::DefaultStorageClass: break;
02273   case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break;
02274   case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break;
02275   }
02276 }
02277 
02278 static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM,
02279                                   formatted_raw_ostream &Out) {
02280   switch (TLM) {
02281     case GlobalVariable::NotThreadLocal:
02282       break;
02283     case GlobalVariable::GeneralDynamicTLSModel:
02284       Out << "thread_local ";
02285       break;
02286     case GlobalVariable::LocalDynamicTLSModel:
02287       Out << "thread_local(localdynamic) ";
02288       break;
02289     case GlobalVariable::InitialExecTLSModel:
02290       Out << "thread_local(initialexec) ";
02291       break;
02292     case GlobalVariable::LocalExecTLSModel:
02293       Out << "thread_local(localexec) ";
02294       break;
02295   }
02296 }
02297 
02298 static void maybePrintComdat(formatted_raw_ostream &Out,
02299                              const GlobalObject &GO) {
02300   const Comdat *C = GO.getComdat();
02301   if (!C)
02302     return;
02303 
02304   if (isa<GlobalVariable>(GO))
02305     Out << ',';
02306   Out << " comdat";
02307 
02308   if (GO.getName() == C->getName())
02309     return;
02310 
02311   Out << '(';
02312   PrintLLVMName(Out, C->getName(), ComdatPrefix);
02313   Out << ')';
02314 }
02315 
02316 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
02317   if (GV->isMaterializable())
02318     Out << "; Materializable\n";
02319 
02320   WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent());
02321   Out << " = ";
02322 
02323   if (!GV->hasInitializer() && GV->hasExternalLinkage())
02324     Out << "external ";
02325 
02326   PrintLinkage(GV->getLinkage(), Out);
02327   PrintVisibility(GV->getVisibility(), Out);
02328   PrintDLLStorageClass(GV->getDLLStorageClass(), Out);
02329   PrintThreadLocalModel(GV->getThreadLocalMode(), Out);
02330   if (GV->hasUnnamedAddr())
02331     Out << "unnamed_addr ";
02332 
02333   if (unsigned AddressSpace = GV->getType()->getAddressSpace())
02334     Out << "addrspace(" << AddressSpace << ") ";
02335   if (GV->isExternallyInitialized()) Out << "externally_initialized ";
02336   Out << (GV->isConstant() ? "constant " : "global ");
02337   TypePrinter.print(GV->getType()->getElementType(), Out);
02338 
02339   if (GV->hasInitializer()) {
02340     Out << ' ';
02341     writeOperand(GV->getInitializer(), false);
02342   }
02343 
02344   if (GV->hasSection()) {
02345     Out << ", section \"";
02346     PrintEscapedString(GV->getSection(), Out);
02347     Out << '"';
02348   }
02349   maybePrintComdat(Out, *GV);
02350   if (GV->getAlignment())
02351     Out << ", align " << GV->getAlignment();
02352 
02353   printInfoComment(*GV);
02354 }
02355 
02356 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
02357   if (GA->isMaterializable())
02358     Out << "; Materializable\n";
02359 
02360   // Don't crash when dumping partially built GA
02361   if (!GA->hasName())
02362     Out << "<<nameless>> = ";
02363   else {
02364     PrintLLVMName(Out, GA);
02365     Out << " = ";
02366   }
02367   PrintLinkage(GA->getLinkage(), Out);
02368   PrintVisibility(GA->getVisibility(), Out);
02369   PrintDLLStorageClass(GA->getDLLStorageClass(), Out);
02370   PrintThreadLocalModel(GA->getThreadLocalMode(), Out);
02371   if (GA->hasUnnamedAddr())
02372     Out << "unnamed_addr ";
02373 
02374   Out << "alias ";
02375 
02376   const Constant *Aliasee = GA->getAliasee();
02377 
02378   if (!Aliasee) {
02379     TypePrinter.print(GA->getType(), Out);
02380     Out << " <<NULL ALIASEE>>";
02381   } else {
02382     writeOperand(Aliasee, !isa<ConstantExpr>(Aliasee));
02383   }
02384 
02385   printInfoComment(*GA);
02386   Out << '\n';
02387 }
02388 
02389 void AssemblyWriter::printComdat(const Comdat *C) {
02390   C->print(Out);
02391 }
02392 
02393 void AssemblyWriter::printTypeIdentities() {
02394   if (TypePrinter.NumberedTypes.empty() &&
02395       TypePrinter.NamedTypes.empty())
02396     return;
02397 
02398   Out << '\n';
02399 
02400   // We know all the numbers that each type is used and we know that it is a
02401   // dense assignment.  Convert the map to an index table.
02402   std::vector<StructType*> NumberedTypes(TypePrinter.NumberedTypes.size());
02403   for (DenseMap<StructType*, unsigned>::iterator I =
02404        TypePrinter.NumberedTypes.begin(), E = TypePrinter.NumberedTypes.end();
02405        I != E; ++I) {
02406     assert(I->second < NumberedTypes.size() && "Didn't get a dense numbering?");
02407     NumberedTypes[I->second] = I->first;
02408   }
02409 
02410   // Emit all numbered types.
02411   for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
02412     Out << '%' << i << " = type ";
02413 
02414     // Make sure we print out at least one level of the type structure, so
02415     // that we do not get %2 = type %2
02416     TypePrinter.printStructBody(NumberedTypes[i], Out);
02417     Out << '\n';
02418   }
02419 
02420   for (unsigned i = 0, e = TypePrinter.NamedTypes.size(); i != e; ++i) {
02421     PrintLLVMName(Out, TypePrinter.NamedTypes[i]->getName(), LocalPrefix);
02422     Out << " = type ";
02423 
02424     // Make sure we print out at least one level of the type structure, so
02425     // that we do not get %FILE = type %FILE
02426     TypePrinter.printStructBody(TypePrinter.NamedTypes[i], Out);
02427     Out << '\n';
02428   }
02429 }
02430 
02431 /// printFunction - Print all aspects of a function.
02432 ///
02433 void AssemblyWriter::printFunction(const Function *F) {
02434   // Print out the return type and name.
02435   Out << '\n';
02436 
02437   if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
02438 
02439   if (F->isMaterializable())
02440     Out << "; Materializable\n";
02441 
02442   const AttributeSet &Attrs = F->getAttributes();
02443   if (Attrs.hasAttributes(AttributeSet::FunctionIndex)) {
02444     AttributeSet AS = Attrs.getFnAttributes();
02445     std::string AttrStr;
02446 
02447     unsigned Idx = 0;
02448     for (unsigned E = AS.getNumSlots(); Idx != E; ++Idx)
02449       if (AS.getSlotIndex(Idx) == AttributeSet::FunctionIndex)
02450         break;
02451 
02452     for (AttributeSet::iterator I = AS.begin(Idx), E = AS.end(Idx);
02453          I != E; ++I) {
02454       Attribute Attr = *I;
02455       if (!Attr.isStringAttribute()) {
02456         if (!AttrStr.empty()) AttrStr += ' ';
02457         AttrStr += Attr.getAsString();
02458       }
02459     }
02460 
02461     if (!AttrStr.empty())
02462       Out << "; Function Attrs: " << AttrStr << '\n';
02463   }
02464 
02465   if (F->isDeclaration())
02466     Out << "declare ";
02467   else
02468     Out << "define ";
02469 
02470   PrintLinkage(F->getLinkage(), Out);
02471   PrintVisibility(F->getVisibility(), Out);
02472   PrintDLLStorageClass(F->getDLLStorageClass(), Out);
02473 
02474   // Print the calling convention.
02475   if (F->getCallingConv() != CallingConv::C) {
02476     PrintCallingConv(F->getCallingConv(), Out);
02477     Out << " ";
02478   }
02479 
02480   FunctionType *FT = F->getFunctionType();
02481   if (Attrs.hasAttributes(AttributeSet::ReturnIndex))
02482     Out <<  Attrs.getAsString(AttributeSet::ReturnIndex) << ' ';
02483   TypePrinter.print(F->getReturnType(), Out);
02484   Out << ' ';
02485   WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
02486   Out << '(';
02487   Machine.incorporateFunction(F);
02488 
02489   // Loop over the arguments, printing them...
02490 
02491   unsigned Idx = 1;
02492   if (!F->isDeclaration()) {
02493     // If this isn't a declaration, print the argument names as well.
02494     for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
02495          I != E; ++I) {
02496       // Insert commas as we go... the first arg doesn't get a comma
02497       if (I != F->arg_begin()) Out << ", ";
02498       printArgument(I, Attrs, Idx);
02499       Idx++;
02500     }
02501   } else {
02502     // Otherwise, print the types from the function type.
02503     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
02504       // Insert commas as we go... the first arg doesn't get a comma
02505       if (i) Out << ", ";
02506 
02507       // Output type...
02508       TypePrinter.print(FT->getParamType(i), Out);
02509 
02510       if (Attrs.hasAttributes(i+1))
02511         Out << ' ' << Attrs.getAsString(i+1);
02512     }
02513   }
02514 
02515   // Finish printing arguments...
02516   if (FT->isVarArg()) {
02517     if (FT->getNumParams()) Out << ", ";
02518     Out << "...";  // Output varargs portion of signature!
02519   }
02520   Out << ')';
02521   if (F->hasUnnamedAddr())
02522     Out << " unnamed_addr";
02523   if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
02524     Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttributes());
02525   if (F->hasSection()) {
02526     Out << " section \"";
02527     PrintEscapedString(F->getSection(), Out);
02528     Out << '"';
02529   }
02530   maybePrintComdat(Out, *F);
02531   if (F->getAlignment())
02532     Out << " align " << F->getAlignment();
02533   if (F->hasGC())
02534     Out << " gc \"" << F->getGC() << '"';
02535   if (F->hasPrefixData()) {
02536     Out << " prefix ";
02537     writeOperand(F->getPrefixData(), true);
02538   }
02539   if (F->hasPrologueData()) {
02540     Out << " prologue ";
02541     writeOperand(F->getPrologueData(), true);
02542   }
02543 
02544   if (F->isDeclaration()) {
02545     Out << '\n';
02546   } else {
02547     Out << " {";
02548     // Output all of the function's basic blocks.
02549     for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
02550       printBasicBlock(I);
02551 
02552     // Output the function's use-lists.
02553     printUseLists(F);
02554 
02555     Out << "}\n";
02556   }
02557 
02558   Machine.purgeFunction();
02559 }
02560 
02561 /// printArgument - This member is called for every argument that is passed into
02562 /// the function.  Simply print it out
02563 ///
02564 void AssemblyWriter::printArgument(const Argument *Arg,
02565                                    AttributeSet Attrs, unsigned Idx) {
02566   // Output type...
02567   TypePrinter.print(Arg->getType(), Out);
02568 
02569   // Output parameter attributes list
02570   if (Attrs.hasAttributes(Idx))
02571     Out << ' ' << Attrs.getAsString(Idx);
02572 
02573   // Output name, if available...
02574   if (Arg->hasName()) {
02575     Out << ' ';
02576     PrintLLVMName(Out, Arg);
02577   }
02578 }
02579 
02580 /// printBasicBlock - This member is called for each basic block in a method.
02581 ///
02582 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
02583   if (BB->hasName()) {              // Print out the label if it exists...
02584     Out << "\n";
02585     PrintLLVMName(Out, BB->getName(), LabelPrefix);
02586     Out << ':';
02587   } else if (!BB->use_empty()) {      // Don't print block # of no uses...
02588     Out << "\n; <label>:";
02589     int Slot = Machine.getLocalSlot(BB);
02590     if (Slot != -1)
02591       Out << Slot;
02592     else
02593       Out << "<badref>";
02594   }
02595 
02596   if (!BB->getParent()) {
02597     Out.PadToColumn(50);
02598     Out << "; Error: Block without parent!";
02599   } else if (BB != &BB->getParent()->getEntryBlock()) {  // Not the entry block?
02600     // Output predecessors for the block.
02601     Out.PadToColumn(50);
02602     Out << ";";
02603     const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
02604 
02605     if (PI == PE) {
02606       Out << " No predecessors!";
02607     } else {
02608       Out << " preds = ";
02609       writeOperand(*PI, false);
02610       for (++PI; PI != PE; ++PI) {
02611         Out << ", ";
02612         writeOperand(*PI, false);
02613       }
02614     }
02615   }
02616 
02617   Out << "\n";
02618 
02619   if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
02620 
02621   // Output all of the instructions in the basic block...
02622   for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
02623     printInstructionLine(*I);
02624   }
02625 
02626   if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
02627 }
02628 
02629 /// printInstructionLine - Print an instruction and a newline character.
02630 void AssemblyWriter::printInstructionLine(const Instruction &I) {
02631   printInstruction(I);
02632   Out << '\n';
02633 }
02634 
02635 /// printInfoComment - Print a little comment after the instruction indicating
02636 /// which slot it occupies.
02637 ///
02638 void AssemblyWriter::printInfoComment(const Value &V) {
02639   if (AnnotationWriter)
02640     AnnotationWriter->printInfoComment(V, Out);
02641 }
02642 
02643 // This member is called for each Instruction in a function..
02644 void AssemblyWriter::printInstruction(const Instruction &I) {
02645   if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
02646 
02647   // Print out indentation for an instruction.
02648   Out << "  ";
02649 
02650   // Print out name if it exists...
02651   if (I.hasName()) {
02652     PrintLLVMName(Out, &I);
02653     Out << " = ";
02654   } else if (!I.getType()->isVoidTy()) {
02655     // Print out the def slot taken.
02656     int SlotNum = Machine.getLocalSlot(&I);
02657     if (SlotNum == -1)
02658       Out << "<badref> = ";
02659     else
02660       Out << '%' << SlotNum << " = ";
02661   }
02662 
02663   if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
02664     if (CI->isMustTailCall())
02665       Out << "musttail ";
02666     else if (CI->isTailCall())
02667       Out << "tail ";
02668   }
02669 
02670   // Print out the opcode...
02671   Out << I.getOpcodeName();
02672 
02673   // If this is an atomic load or store, print out the atomic marker.
02674   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isAtomic()) ||
02675       (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
02676     Out << " atomic";
02677 
02678   if (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isWeak())
02679     Out << " weak";
02680 
02681   // If this is a volatile operation, print out the volatile marker.
02682   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isVolatile()) ||
02683       (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
02684       (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
02685       (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
02686     Out << " volatile";
02687 
02688   // Print out optimization information.
02689   WriteOptimizationInfo(Out, &I);
02690 
02691   // Print out the compare instruction predicates
02692   if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
02693     Out << ' ' << getPredicateText(CI->getPredicate());
02694 
02695   // Print out the atomicrmw operation
02696   if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
02697     writeAtomicRMWOperation(Out, RMWI->getOperation());
02698 
02699   // Print out the type of the operands...
02700   const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr;
02701 
02702   // Special case conditional branches to swizzle the condition out to the front
02703   if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
02704     const BranchInst &BI(cast<BranchInst>(I));
02705     Out << ' ';
02706     writeOperand(BI.getCondition(), true);
02707     Out << ", ";
02708     writeOperand(BI.getSuccessor(0), true);
02709     Out << ", ";
02710     writeOperand(BI.getSuccessor(1), true);
02711 
02712   } else if (isa<SwitchInst>(I)) {
02713     const SwitchInst& SI(cast<SwitchInst>(I));
02714     // Special case switch instruction to get formatting nice and correct.
02715     Out << ' ';
02716     writeOperand(SI.getCondition(), true);
02717     Out << ", ";
02718     writeOperand(SI.getDefaultDest(), true);
02719     Out << " [";
02720     for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
02721          i != e; ++i) {
02722       Out << "\n    ";
02723       writeOperand(i.getCaseValue(), true);
02724       Out << ", ";
02725       writeOperand(i.getCaseSuccessor(), true);
02726     }
02727     Out << "\n  ]";
02728   } else if (isa<IndirectBrInst>(I)) {
02729     // Special case indirectbr instruction to get formatting nice and correct.
02730     Out << ' ';
02731     writeOperand(Operand, true);
02732     Out << ", [";
02733 
02734     for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
02735       if (i != 1)
02736         Out << ", ";
02737       writeOperand(I.getOperand(i), true);
02738     }
02739     Out << ']';
02740   } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
02741     Out << ' ';
02742     TypePrinter.print(I.getType(), Out);
02743     Out << ' ';
02744 
02745     for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
02746       if (op) Out << ", ";
02747       Out << "[ ";
02748       writeOperand(PN->getIncomingValue(op), false); Out << ", ";
02749       writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
02750     }
02751   } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
02752     Out << ' ';
02753     writeOperand(I.getOperand(0), true);
02754     for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
02755       Out << ", " << *i;
02756   } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
02757     Out << ' ';
02758     writeOperand(I.getOperand(0), true); Out << ", ";
02759     writeOperand(I.getOperand(1), true);
02760     for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
02761       Out << ", " << *i;
02762   } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
02763     Out << ' ';
02764     TypePrinter.print(I.getType(), Out);
02765     Out << " personality ";
02766     writeOperand(I.getOperand(0), true); Out << '\n';
02767 
02768     if (LPI->isCleanup())
02769       Out << "          cleanup";
02770 
02771     for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
02772       if (i != 0 || LPI->isCleanup()) Out << "\n";
02773       if (LPI->isCatch(i))
02774         Out << "          catch ";
02775       else
02776         Out << "          filter ";
02777 
02778       writeOperand(LPI->getClause(i), true);
02779     }
02780   } else if (isa<ReturnInst>(I) && !Operand) {
02781     Out << " void";
02782   } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
02783     // Print the calling convention being used.
02784     if (CI->getCallingConv() != CallingConv::C) {
02785       Out << " ";
02786       PrintCallingConv(CI->getCallingConv(), Out);
02787     }
02788 
02789     Operand = CI->getCalledValue();
02790     PointerType *PTy = cast<PointerType>(Operand->getType());
02791     FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
02792     Type *RetTy = FTy->getReturnType();
02793     const AttributeSet &PAL = CI->getAttributes();
02794 
02795     if (PAL.hasAttributes(AttributeSet::ReturnIndex))
02796       Out << ' ' << PAL.getAsString(AttributeSet::ReturnIndex);
02797 
02798     // If possible, print out the short form of the call instruction.  We can
02799     // only do this if the first argument is a pointer to a nonvararg function,
02800     // and if the return type is not a pointer to a function.
02801     //
02802     Out << ' ';
02803     if (!FTy->isVarArg() &&
02804         (!RetTy->isPointerTy() ||
02805          !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
02806       TypePrinter.print(RetTy, Out);
02807       Out << ' ';
02808       writeOperand(Operand, false);
02809     } else {
02810       writeOperand(Operand, true);
02811     }
02812     Out << '(';
02813     for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
02814       if (op > 0)
02815         Out << ", ";
02816       writeParamOperand(CI->getArgOperand(op), PAL, op + 1);
02817     }
02818 
02819     // Emit an ellipsis if this is a musttail call in a vararg function.  This
02820     // is only to aid readability, musttail calls forward varargs by default.
02821     if (CI->isMustTailCall() && CI->getParent() &&
02822         CI->getParent()->getParent() &&
02823         CI->getParent()->getParent()->isVarArg())
02824       Out << ", ...";
02825 
02826     Out << ')';
02827     if (PAL.hasAttributes(AttributeSet::FunctionIndex))
02828       Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
02829   } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
02830     Operand = II->getCalledValue();
02831     PointerType *PTy = cast<PointerType>(Operand->getType());
02832     FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
02833     Type *RetTy = FTy->getReturnType();
02834     const AttributeSet &PAL = II->getAttributes();
02835 
02836     // Print the calling convention being used.
02837     if (II->getCallingConv() != CallingConv::C) {
02838       Out << " ";
02839       PrintCallingConv(II->getCallingConv(), Out);
02840     }
02841 
02842     if (PAL.hasAttributes(AttributeSet::ReturnIndex))
02843       Out << ' ' << PAL.getAsString(AttributeSet::ReturnIndex);
02844 
02845     // If possible, print out the short form of the invoke instruction. We can
02846     // only do this if the first argument is a pointer to a nonvararg function,
02847     // and if the return type is not a pointer to a function.
02848     //
02849     Out << ' ';
02850     if (!FTy->isVarArg() &&
02851         (!RetTy->isPointerTy() ||
02852          !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
02853       TypePrinter.print(RetTy, Out);
02854       Out << ' ';
02855       writeOperand(Operand, false);
02856     } else {
02857       writeOperand(Operand, true);
02858     }
02859     Out << '(';
02860     for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
02861       if (op)
02862         Out << ", ";
02863       writeParamOperand(II->getArgOperand(op), PAL, op + 1);
02864     }
02865 
02866     Out << ')';
02867     if (PAL.hasAttributes(AttributeSet::FunctionIndex))
02868       Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
02869 
02870     Out << "\n          to ";
02871     writeOperand(II->getNormalDest(), true);
02872     Out << " unwind ";
02873     writeOperand(II->getUnwindDest(), true);
02874 
02875   } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
02876     Out << ' ';
02877     if (AI->isUsedWithInAlloca())
02878       Out << "inalloca ";
02879     TypePrinter.print(AI->getAllocatedType(), Out);
02880     if (!AI->getArraySize() || AI->isArrayAllocation()) {
02881       Out << ", ";
02882       writeOperand(AI->getArraySize(), true);
02883     }
02884     if (AI->getAlignment()) {
02885       Out << ", align " << AI->getAlignment();
02886     }
02887   } else if (isa<CastInst>(I)) {
02888     if (Operand) {
02889       Out << ' ';
02890       writeOperand(Operand, true);   // Work with broken code
02891     }
02892     Out << " to ";
02893     TypePrinter.print(I.getType(), Out);
02894   } else if (isa<VAArgInst>(I)) {
02895     if (Operand) {
02896       Out << ' ';
02897       writeOperand(Operand, true);   // Work with broken code
02898     }
02899     Out << ", ";
02900     TypePrinter.print(I.getType(), Out);
02901   } else if (Operand) {   // Print the normal way.
02902     if (const auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
02903       Out << ' ';
02904       TypePrinter.print(GEP->getSourceElementType(), Out);
02905       Out << ',';
02906     } else if (const auto *LI = dyn_cast<LoadInst>(&I)) {
02907       Out << ' ';
02908       TypePrinter.print(LI->getType(), Out);
02909       Out << ',';
02910     }
02911 
02912     // PrintAllTypes - Instructions who have operands of all the same type
02913     // omit the type from all but the first operand.  If the instruction has
02914     // different type operands (for example br), then they are all printed.
02915     bool PrintAllTypes = false;
02916     Type *TheType = Operand->getType();
02917 
02918     // Select, Store and ShuffleVector always print all types.
02919     if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
02920         || isa<ReturnInst>(I)) {
02921       PrintAllTypes = true;
02922     } else {
02923       for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
02924         Operand = I.getOperand(i);
02925         // note that Operand shouldn't be null, but the test helps make dump()
02926         // more tolerant of malformed IR
02927         if (Operand && Operand->getType() != TheType) {
02928           PrintAllTypes = true;    // We have differing types!  Print them all!
02929           break;
02930         }
02931       }
02932     }
02933 
02934     if (!PrintAllTypes) {
02935       Out << ' ';
02936       TypePrinter.print(TheType, Out);
02937     }
02938 
02939     Out << ' ';
02940     for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
02941       if (i) Out << ", ";
02942       writeOperand(I.getOperand(i), PrintAllTypes);
02943     }
02944   }
02945 
02946   // Print atomic ordering/alignment for memory operations
02947   if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
02948     if (LI->isAtomic())
02949       writeAtomic(LI->getOrdering(), LI->getSynchScope());
02950     if (LI->getAlignment())
02951       Out << ", align " << LI->getAlignment();
02952   } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
02953     if (SI->isAtomic())
02954       writeAtomic(SI->getOrdering(), SI->getSynchScope());
02955     if (SI->getAlignment())
02956       Out << ", align " << SI->getAlignment();
02957   } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
02958     writeAtomicCmpXchg(CXI->getSuccessOrdering(), CXI->getFailureOrdering(),
02959                        CXI->getSynchScope());
02960   } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
02961     writeAtomic(RMWI->getOrdering(), RMWI->getSynchScope());
02962   } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
02963     writeAtomic(FI->getOrdering(), FI->getSynchScope());
02964   }
02965 
02966   // Print Metadata info.
02967   SmallVector<std::pair<unsigned, MDNode *>, 4> InstMD;
02968   I.getAllMetadata(InstMD);
02969   if (!InstMD.empty()) {
02970     SmallVector<StringRef, 8> MDNames;
02971     I.getType()->getContext().getMDKindNames(MDNames);
02972     for (unsigned i = 0, e = InstMD.size(); i != e; ++i) {
02973       unsigned Kind = InstMD[i].first;
02974        if (Kind < MDNames.size()) {
02975          Out << ", !" << MDNames[Kind];
02976        } else {
02977          Out << ", !<unknown kind #" << Kind << ">";
02978        }
02979       Out << ' ';
02980       WriteAsOperandInternal(Out, InstMD[i].second, &TypePrinter, &Machine,
02981                              TheModule);
02982     }
02983   }
02984   printInfoComment(I);
02985 }
02986 
02987 void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) {
02988   Out << '!' << Slot << " = ";
02989   printMDNodeBody(Node);
02990   Out << "\n";
02991 }
02992 
02993 void AssemblyWriter::writeAllMDNodes() {
02994   SmallVector<const MDNode *, 16> Nodes;
02995   Nodes.resize(Machine.mdn_size());
02996   for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
02997        I != E; ++I)
02998     Nodes[I->second] = cast<MDNode>(I->first);
02999 
03000   for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
03001     writeMDNode(i, Nodes[i]);
03002   }
03003 }
03004 
03005 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
03006   WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
03007 }
03008 
03009 void AssemblyWriter::writeAllAttributeGroups() {
03010   std::vector<std::pair<AttributeSet, unsigned> > asVec;
03011   asVec.resize(Machine.as_size());
03012 
03013   for (SlotTracker::as_iterator I = Machine.as_begin(), E = Machine.as_end();
03014        I != E; ++I)
03015     asVec[I->second] = *I;
03016 
03017   for (std::vector<std::pair<AttributeSet, unsigned> >::iterator
03018          I = asVec.begin(), E = asVec.end(); I != E; ++I)
03019     Out << "attributes #" << I->second << " = { "
03020         << I->first.getAsString(AttributeSet::FunctionIndex, true) << " }\n";
03021 }
03022 
03023 } // namespace llvm
03024 
03025 void AssemblyWriter::printUseListOrder(const UseListOrder &Order) {
03026   bool IsInFunction = Machine.getFunction();
03027   if (IsInFunction)
03028     Out << "  ";
03029 
03030   Out << "uselistorder";
03031   if (const BasicBlock *BB =
03032           IsInFunction ? nullptr : dyn_cast<BasicBlock>(Order.V)) {
03033     Out << "_bb ";
03034     writeOperand(BB->getParent(), false);
03035     Out << ", ";
03036     writeOperand(BB, false);
03037   } else {
03038     Out << " ";
03039     writeOperand(Order.V, true);
03040   }
03041   Out << ", { ";
03042 
03043   assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
03044   Out << Order.Shuffle[0];
03045   for (unsigned I = 1, E = Order.Shuffle.size(); I != E; ++I)
03046     Out << ", " << Order.Shuffle[I];
03047   Out << " }\n";
03048 }
03049 
03050 void AssemblyWriter::printUseLists(const Function *F) {
03051   auto hasMore =
03052       [&]() { return !UseListOrders.empty() && UseListOrders.back().F == F; };
03053   if (!hasMore())
03054     // Nothing to do.
03055     return;
03056 
03057   Out << "\n; uselistorder directives\n";
03058   while (hasMore()) {
03059     printUseListOrder(UseListOrders.back());
03060     UseListOrders.pop_back();
03061   }
03062 }
03063 
03064 //===----------------------------------------------------------------------===//
03065 //                       External Interface declarations
03066 //===----------------------------------------------------------------------===//
03067 
03068 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
03069   SlotTracker SlotTable(this);
03070   formatted_raw_ostream OS(ROS);
03071   AssemblyWriter W(OS, SlotTable, this, AAW);
03072   W.printModule(this);
03073 }
03074 
03075 void NamedMDNode::print(raw_ostream &ROS) const {
03076   SlotTracker SlotTable(getParent());
03077   formatted_raw_ostream OS(ROS);
03078   AssemblyWriter W(OS, SlotTable, getParent(), nullptr);
03079   W.printNamedMDNode(this);
03080 }
03081 
03082 void Comdat::print(raw_ostream &ROS) const {
03083   PrintLLVMName(ROS, getName(), ComdatPrefix);
03084   ROS << " = comdat ";
03085 
03086   switch (getSelectionKind()) {
03087   case Comdat::Any:
03088     ROS << "any";
03089     break;
03090   case Comdat::ExactMatch:
03091     ROS << "exactmatch";
03092     break;
03093   case Comdat::Largest:
03094     ROS << "largest";
03095     break;
03096   case Comdat::NoDuplicates:
03097     ROS << "noduplicates";
03098     break;
03099   case Comdat::SameSize:
03100     ROS << "samesize";
03101     break;
03102   }
03103 
03104   ROS << '\n';
03105 }
03106 
03107 void Type::print(raw_ostream &OS) const {
03108   TypePrinting TP;
03109   TP.print(const_cast<Type*>(this), OS);
03110 
03111   // If the type is a named struct type, print the body as well.
03112   if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
03113     if (!STy->isLiteral()) {
03114       OS << " = type ";
03115       TP.printStructBody(STy, OS);
03116     }
03117 }
03118 
03119 void Value::print(raw_ostream &ROS) const {
03120   formatted_raw_ostream OS(ROS);
03121   if (const Instruction *I = dyn_cast<Instruction>(this)) {
03122     const Function *F = I->getParent() ? I->getParent()->getParent() : nullptr;
03123     SlotTracker SlotTable(F);
03124     AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr);
03125     W.printInstruction(*I);
03126   } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
03127     SlotTracker SlotTable(BB->getParent());
03128     AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr);
03129     W.printBasicBlock(BB);
03130   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
03131     SlotTracker SlotTable(GV->getParent());
03132     AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr);
03133     if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
03134       W.printGlobal(V);
03135     else if (const Function *F = dyn_cast<Function>(GV))
03136       W.printFunction(F);
03137     else
03138       W.printAlias(cast<GlobalAlias>(GV));
03139   } else if (const MetadataAsValue *V = dyn_cast<MetadataAsValue>(this)) {
03140     V->getMetadata()->print(ROS);
03141   } else if (const Constant *C = dyn_cast<Constant>(this)) {
03142     TypePrinting TypePrinter;
03143     TypePrinter.print(C->getType(), OS);
03144     OS << ' ';
03145     WriteConstantInternal(OS, C, TypePrinter, nullptr, nullptr);
03146   } else if (isa<InlineAsm>(this) || isa<Argument>(this)) {
03147     this->printAsOperand(OS);
03148   } else {
03149     llvm_unreachable("Unknown value to print out!");
03150   }
03151 }
03152 
03153 void Value::printAsOperand(raw_ostream &O, bool PrintType, const Module *M) const {
03154   // Fast path: Don't construct and populate a TypePrinting object if we
03155   // won't be needing any types printed.
03156   if (!PrintType && ((!isa<Constant>(this) && !isa<MetadataAsValue>(this)) ||
03157                      hasName() || isa<GlobalValue>(this))) {
03158     WriteAsOperandInternal(O, this, nullptr, nullptr, M);
03159     return;
03160   }
03161 
03162   if (!M)
03163     M = getModuleFromVal(this);
03164 
03165   TypePrinting TypePrinter;
03166   if (M)
03167     TypePrinter.incorporateTypes(*M);
03168   if (PrintType) {
03169     TypePrinter.print(getType(), O);
03170     O << ' ';
03171   }
03172 
03173   WriteAsOperandInternal(O, this, &TypePrinter, nullptr, M);
03174 }
03175 
03176 void Metadata::print(raw_ostream &ROS) const {
03177   formatted_raw_ostream OS(ROS);
03178   if (auto *N = dyn_cast<MDNode>(this)) {
03179     SlotTracker SlotTable(static_cast<Function *>(nullptr));
03180     AssemblyWriter W(OS, SlotTable, nullptr, nullptr);
03181     W.printMDNodeBody(N);
03182 
03183     return;
03184   }
03185   printAsOperand(OS);
03186 }
03187 
03188 void Metadata::printAsOperand(raw_ostream &ROS, bool PrintType,
03189                               const Module *M) const {
03190   formatted_raw_ostream OS(ROS);
03191 
03192   std::unique_ptr<TypePrinting> TypePrinter;
03193   if (PrintType) {
03194     TypePrinter.reset(new TypePrinting);
03195     if (M)
03196       TypePrinter->incorporateTypes(*M);
03197   }
03198   WriteAsOperandInternal(OS, this, TypePrinter.get(), nullptr, M,
03199                          /* FromValue */ true);
03200 }
03201 
03202 // Value::dump - allow easy printing of Values from the debugger.
03203 LLVM_DUMP_METHOD
03204 void Value::dump() const { print(dbgs()); dbgs() << '\n'; }
03205 
03206 // Type::dump - allow easy printing of Types from the debugger.
03207 LLVM_DUMP_METHOD
03208 void Type::dump() const { print(dbgs()); dbgs() << '\n'; }
03209 
03210 // Module::dump() - Allow printing of Modules from the debugger.
03211 LLVM_DUMP_METHOD
03212 void Module::dump() const { print(dbgs(), nullptr); }
03213 
03214 // \brief Allow printing of Comdats from the debugger.
03215 LLVM_DUMP_METHOD
03216 void Comdat::dump() const { print(dbgs()); }
03217 
03218 // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
03219 LLVM_DUMP_METHOD
03220 void NamedMDNode::dump() const { print(dbgs()); }
03221 
03222 LLVM_DUMP_METHOD
03223 void Metadata::dump() const {
03224   print(dbgs());
03225   dbgs() << '\n';
03226 }