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