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