LLVM API Documentation

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