0eb45c53f8505e5a7cce053a8f6db73618afd013
[oota-llvm.git] / lib / VMCore / AsmWriter.cpp
1 //===-- AsmWriter.cpp - Printing LLVM as an assembly file -----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This library implements the functionality defined in llvm/Assembly/Writer.h
11 //
12 // Note that these routines must be extremely tolerant of various errors in the
13 // LLVM code, because it can be used for debugging transformations.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "llvm/Assembly/Writer.h"
18 #include "llvm/Assembly/PrintModulePass.h"
19 #include "llvm/Assembly/AssemblyAnnotationWriter.h"
20 #include "llvm/LLVMContext.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/Constants.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/InlineAsm.h"
25 #include "llvm/IntrinsicInst.h"
26 #include "llvm/Operator.h"
27 #include "llvm/Module.h"
28 #include "llvm/ValueSymbolTable.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/SmallString.h"
31 #include "llvm/ADT/StringExtras.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/Support/CFG.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/Dwarf.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/FormattedStream.h"
39 #include <algorithm>
40 #include <cctype>
41 using namespace llvm;
42
43 // Make virtual table appear in this compilation unit.
44 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
45
46 //===----------------------------------------------------------------------===//
47 // Helper Functions
48 //===----------------------------------------------------------------------===//
49
50 static const Module *getModuleFromVal(const Value *V) {
51   if (const Argument *MA = dyn_cast<Argument>(V))
52     return MA->getParent() ? MA->getParent()->getParent() : 0;
53
54   if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
55     return BB->getParent() ? BB->getParent()->getParent() : 0;
56
57   if (const Instruction *I = dyn_cast<Instruction>(V)) {
58     const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
59     return M ? M->getParent() : 0;
60   }
61
62   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
63     return GV->getParent();
64   return 0;
65 }
66
67 // PrintEscapedString - Print each character of the specified string, escaping
68 // it if it is not printable or if it is an escape char.
69 static void PrintEscapedString(StringRef Name, raw_ostream &Out) {
70   for (unsigned i = 0, e = Name.size(); i != e; ++i) {
71     unsigned char C = Name[i];
72     if (isprint(C) && C != '\\' && C != '"')
73       Out << C;
74     else
75       Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
76   }
77 }
78
79 enum PrefixType {
80   GlobalPrefix,
81   LabelPrefix,
82   LocalPrefix,
83   NoPrefix
84 };
85
86 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
87 /// prefixed with % (if the string only contains simple characters) or is
88 /// surrounded with ""'s (if it has special chars in it).  Print it out.
89 static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) {
90   assert(!Name.empty() && "Cannot get empty name!");
91   switch (Prefix) {
92   case NoPrefix: break;
93   case GlobalPrefix: OS << '@'; break;
94   case LabelPrefix:  break;
95   case LocalPrefix:  OS << '%'; break;
96   }
97
98   // Scan the name to see if it needs quotes first.
99   bool NeedsQuotes = isdigit(Name[0]);
100   if (!NeedsQuotes) {
101     for (unsigned i = 0, e = Name.size(); i != e; ++i) {
102       char C = Name[i];
103       if (!isalnum(C) && C != '-' && C != '.' && C != '_') {
104         NeedsQuotes = true;
105         break;
106       }
107     }
108   }
109
110   // If we didn't need any quotes, just write out the name in one blast.
111   if (!NeedsQuotes) {
112     OS << Name;
113     return;
114   }
115
116   // Okay, we need quotes.  Output the quotes and escape any scary characters as
117   // needed.
118   OS << '"';
119   PrintEscapedString(Name, OS);
120   OS << '"';
121 }
122
123 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
124 /// prefixed with % (if the string only contains simple characters) or is
125 /// surrounded with ""'s (if it has special chars in it).  Print it out.
126 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
127   PrintLLVMName(OS, V->getName(),
128                 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
129 }
130
131 //===----------------------------------------------------------------------===//
132 // TypePrinting Class: Type printing machinery
133 //===----------------------------------------------------------------------===//
134
135 /// TypePrinting - Type printing machinery.
136 namespace {
137 class TypePrinting {
138   TypePrinting(const TypePrinting &);   // DO NOT IMPLEMENT
139   void operator=(const TypePrinting&);  // DO NOT IMPLEMENT
140 public:
141
142   /// NamedTypes - The named types that are used by the current module.
143   std::vector<StructType*> NamedTypes;
144
145   /// NumberedTypes - The numbered types, along with their value.
146   DenseMap<StructType*, unsigned> NumberedTypes;
147
148
149   TypePrinting() {}
150   ~TypePrinting() {}
151
152   void incorporateTypes(const Module &M);
153
154   void print(Type *Ty, raw_ostream &OS);
155
156   void printStructBody(StructType *Ty, raw_ostream &OS);
157 };
158 } // end anonymous namespace.
159
160
161 void TypePrinting::incorporateTypes(const Module &M) {
162   M.findUsedStructTypes(NamedTypes);
163
164   // The list of struct types we got back includes all the struct types, split
165   // the unnamed ones out to a numbering and remove the anonymous structs.
166   unsigned NextNumber = 0;
167
168   std::vector<StructType*>::iterator NextToUse = NamedTypes.begin(), I, E;
169   for (I = NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I) {
170     StructType *STy = *I;
171
172     // Ignore anonymous types.
173     if (STy->isLiteral())
174       continue;
175
176     if (STy->getName().empty())
177       NumberedTypes[STy] = NextNumber++;
178     else
179       *NextToUse++ = STy;
180   }
181
182   NamedTypes.erase(NextToUse, NamedTypes.end());
183 }
184
185
186 /// CalcTypeName - Write the specified type to the specified raw_ostream, making
187 /// use of type names or up references to shorten the type name where possible.
188 void TypePrinting::print(Type *Ty, raw_ostream &OS) {
189   switch (Ty->getTypeID()) {
190   case Type::VoidTyID:      OS << "void"; break;
191   case Type::HalfTyID:      OS << "half"; break;
192   case Type::FloatTyID:     OS << "float"; break;
193   case Type::DoubleTyID:    OS << "double"; break;
194   case Type::X86_FP80TyID:  OS << "x86_fp80"; break;
195   case Type::FP128TyID:     OS << "fp128"; break;
196   case Type::PPC_FP128TyID: OS << "ppc_fp128"; break;
197   case Type::LabelTyID:     OS << "label"; break;
198   case Type::MetadataTyID:  OS << "metadata"; break;
199   case Type::X86_MMXTyID:   OS << "x86_mmx"; break;
200   case Type::IntegerTyID:
201     OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
202     return;
203
204   case Type::FunctionTyID: {
205     FunctionType *FTy = cast<FunctionType>(Ty);
206     print(FTy->getReturnType(), OS);
207     OS << " (";
208     for (FunctionType::param_iterator I = FTy->param_begin(),
209          E = FTy->param_end(); I != E; ++I) {
210       if (I != FTy->param_begin())
211         OS << ", ";
212       print(*I, OS);
213     }
214     if (FTy->isVarArg()) {
215       if (FTy->getNumParams()) OS << ", ";
216       OS << "...";
217     }
218     OS << ')';
219     return;
220   }
221   case Type::StructTyID: {
222     StructType *STy = cast<StructType>(Ty);
223
224     if (STy->isLiteral())
225       return printStructBody(STy, OS);
226
227     if (!STy->getName().empty())
228       return PrintLLVMName(OS, STy->getName(), LocalPrefix);
229
230     DenseMap<StructType*, unsigned>::iterator I = NumberedTypes.find(STy);
231     if (I != NumberedTypes.end())
232       OS << '%' << I->second;
233     else  // Not enumerated, print the hex address.
234       OS << "%\"type " << STy << '\"';
235     return;
236   }
237   case Type::PointerTyID: {
238     PointerType *PTy = cast<PointerType>(Ty);
239     print(PTy->getElementType(), OS);
240     if (unsigned AddressSpace = PTy->getAddressSpace())
241       OS << " addrspace(" << AddressSpace << ')';
242     OS << '*';
243     return;
244   }
245   case Type::ArrayTyID: {
246     ArrayType *ATy = cast<ArrayType>(Ty);
247     OS << '[' << ATy->getNumElements() << " x ";
248     print(ATy->getElementType(), OS);
249     OS << ']';
250     return;
251   }
252   case Type::VectorTyID: {
253     VectorType *PTy = cast<VectorType>(Ty);
254     OS << "<" << PTy->getNumElements() << " x ";
255     print(PTy->getElementType(), OS);
256     OS << '>';
257     return;
258   }
259   default:
260     OS << "<unrecognized-type>";
261     return;
262   }
263 }
264
265 void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
266   if (STy->isOpaque()) {
267     OS << "opaque";
268     return;
269   }
270
271   if (STy->isPacked())
272     OS << '<';
273
274   if (STy->getNumElements() == 0) {
275     OS << "{}";
276   } else {
277     StructType::element_iterator I = STy->element_begin();
278     OS << "{ ";
279     print(*I++, OS);
280     for (StructType::element_iterator E = STy->element_end(); I != E; ++I) {
281       OS << ", ";
282       print(*I, OS);
283     }
284
285     OS << " }";
286   }
287   if (STy->isPacked())
288     OS << '>';
289 }
290
291
292
293 //===----------------------------------------------------------------------===//
294 // SlotTracker Class: Enumerate slot numbers for unnamed values
295 //===----------------------------------------------------------------------===//
296
297 namespace {
298
299 /// This class provides computation of slot numbers for LLVM Assembly writing.
300 ///
301 class SlotTracker {
302 public:
303   /// ValueMap - A mapping of Values to slot numbers.
304   typedef DenseMap<const Value*, unsigned> ValueMap;
305
306 private:
307   /// TheModule - The module for which we are holding slot numbers.
308   const Module* TheModule;
309
310   /// TheFunction - The function for which we are holding slot numbers.
311   const Function* TheFunction;
312   bool FunctionProcessed;
313
314   /// mMap - The slot map for the module level data.
315   ValueMap mMap;
316   unsigned mNext;
317
318   /// fMap - The slot map for the function level data.
319   ValueMap fMap;
320   unsigned fNext;
321
322   /// mdnMap - Map for MDNodes.
323   DenseMap<const MDNode*, unsigned> mdnMap;
324   unsigned mdnNext;
325 public:
326   /// Construct from a module
327   explicit SlotTracker(const Module *M);
328   /// Construct from a function, starting out in incorp state.
329   explicit SlotTracker(const Function *F);
330
331   /// Return the slot number of the specified value in it's type
332   /// plane.  If something is not in the SlotTracker, return -1.
333   int getLocalSlot(const Value *V);
334   int getGlobalSlot(const GlobalValue *V);
335   int getMetadataSlot(const MDNode *N);
336
337   /// If you'd like to deal with a function instead of just a module, use
338   /// this method to get its data into the SlotTracker.
339   void incorporateFunction(const Function *F) {
340     TheFunction = F;
341     FunctionProcessed = false;
342   }
343
344   /// After calling incorporateFunction, use this method to remove the
345   /// most recently incorporated function from the SlotTracker. This
346   /// will reset the state of the machine back to just the module contents.
347   void purgeFunction();
348
349   /// MDNode map iterators.
350   typedef DenseMap<const MDNode*, unsigned>::iterator mdn_iterator;
351   mdn_iterator mdn_begin() { return mdnMap.begin(); }
352   mdn_iterator mdn_end() { return mdnMap.end(); }
353   unsigned mdn_size() const { return mdnMap.size(); }
354   bool mdn_empty() const { return mdnMap.empty(); }
355
356   /// This function does the actual initialization.
357   inline void initialize();
358
359   // Implementation Details
360 private:
361   /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
362   void CreateModuleSlot(const GlobalValue *V);
363
364   /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
365   void CreateMetadataSlot(const MDNode *N);
366
367   /// CreateFunctionSlot - Insert the specified Value* into the slot table.
368   void CreateFunctionSlot(const Value *V);
369
370   /// Add all of the module level global variables (and their initializers)
371   /// and function declarations, but not the contents of those functions.
372   void processModule();
373
374   /// Add all of the functions arguments, basic blocks, and instructions.
375   void processFunction();
376
377   SlotTracker(const SlotTracker &);  // DO NOT IMPLEMENT
378   void operator=(const SlotTracker &);  // DO NOT IMPLEMENT
379 };
380
381 }  // end anonymous namespace
382
383
384 static SlotTracker *createSlotTracker(const Value *V) {
385   if (const Argument *FA = dyn_cast<Argument>(V))
386     return new SlotTracker(FA->getParent());
387
388   if (const Instruction *I = dyn_cast<Instruction>(V))
389     if (I->getParent())
390       return new SlotTracker(I->getParent()->getParent());
391
392   if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
393     return new SlotTracker(BB->getParent());
394
395   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
396     return new SlotTracker(GV->getParent());
397
398   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
399     return new SlotTracker(GA->getParent());
400
401   if (const Function *Func = dyn_cast<Function>(V))
402     return new SlotTracker(Func);
403
404   if (const MDNode *MD = dyn_cast<MDNode>(V)) {
405     if (!MD->isFunctionLocal())
406       return new SlotTracker(MD->getFunction());
407
408     return new SlotTracker((Function *)0);
409   }
410
411   return 0;
412 }
413
414 #if 0
415 #define ST_DEBUG(X) dbgs() << X
416 #else
417 #define ST_DEBUG(X)
418 #endif
419
420 // Module level constructor. Causes the contents of the Module (sans functions)
421 // to be added to the slot table.
422 SlotTracker::SlotTracker(const Module *M)
423   : TheModule(M), TheFunction(0), FunctionProcessed(false),
424     mNext(0), fNext(0),  mdnNext(0) {
425 }
426
427 // Function level constructor. Causes the contents of the Module and the one
428 // function provided to be added to the slot table.
429 SlotTracker::SlotTracker(const Function *F)
430   : TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false),
431     mNext(0), fNext(0), mdnNext(0) {
432 }
433
434 inline void SlotTracker::initialize() {
435   if (TheModule) {
436     processModule();
437     TheModule = 0; ///< Prevent re-processing next time we're called.
438   }
439
440   if (TheFunction && !FunctionProcessed)
441     processFunction();
442 }
443
444 // Iterate through all the global variables, functions, and global
445 // variable initializers and create slots for them.
446 void SlotTracker::processModule() {
447   ST_DEBUG("begin processModule!\n");
448
449   // Add all of the unnamed global variables to the value table.
450   for (Module::const_global_iterator I = TheModule->global_begin(),
451          E = TheModule->global_end(); I != E; ++I) {
452     if (!I->hasName())
453       CreateModuleSlot(I);
454   }
455
456   // Add metadata used by named metadata.
457   for (Module::const_named_metadata_iterator
458          I = TheModule->named_metadata_begin(),
459          E = TheModule->named_metadata_end(); I != E; ++I) {
460     const NamedMDNode *NMD = I;
461     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
462       CreateMetadataSlot(NMD->getOperand(i));
463   }
464
465   // Add all the unnamed functions to the table.
466   for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
467        I != E; ++I)
468     if (!I->hasName())
469       CreateModuleSlot(I);
470
471   ST_DEBUG("end processModule!\n");
472 }
473
474 // Process the arguments, basic blocks, and instructions  of a function.
475 void SlotTracker::processFunction() {
476   ST_DEBUG("begin processFunction!\n");
477   fNext = 0;
478
479   // Add all the function arguments with no names.
480   for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
481       AE = TheFunction->arg_end(); AI != AE; ++AI)
482     if (!AI->hasName())
483       CreateFunctionSlot(AI);
484
485   ST_DEBUG("Inserting Instructions:\n");
486
487   SmallVector<std::pair<unsigned, MDNode*>, 4> MDForInst;
488
489   // Add all of the basic blocks and instructions with no names.
490   for (Function::const_iterator BB = TheFunction->begin(),
491        E = TheFunction->end(); BB != E; ++BB) {
492     if (!BB->hasName())
493       CreateFunctionSlot(BB);
494
495     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E;
496          ++I) {
497       if (!I->getType()->isVoidTy() && !I->hasName())
498         CreateFunctionSlot(I);
499
500       // Intrinsics can directly use metadata.  We allow direct calls to any
501       // llvm.foo function here, because the target may not be linked into the
502       // optimizer.
503       if (const CallInst *CI = dyn_cast<CallInst>(I)) {
504         if (Function *F = CI->getCalledFunction())
505           if (F->getName().startswith("llvm."))
506             for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
507               if (MDNode *N = dyn_cast_or_null<MDNode>(I->getOperand(i)))
508                 CreateMetadataSlot(N);
509       }
510
511       // Process metadata attached with this instruction.
512       I->getAllMetadata(MDForInst);
513       for (unsigned i = 0, e = MDForInst.size(); i != e; ++i)
514         CreateMetadataSlot(MDForInst[i].second);
515       MDForInst.clear();
516     }
517   }
518
519   FunctionProcessed = true;
520
521   ST_DEBUG("end processFunction!\n");
522 }
523
524 /// Clean up after incorporating a function. This is the only way to get out of
525 /// the function incorporation state that affects get*Slot/Create*Slot. Function
526 /// incorporation state is indicated by TheFunction != 0.
527 void SlotTracker::purgeFunction() {
528   ST_DEBUG("begin purgeFunction!\n");
529   fMap.clear(); // Simply discard the function level map
530   TheFunction = 0;
531   FunctionProcessed = false;
532   ST_DEBUG("end purgeFunction!\n");
533 }
534
535 /// getGlobalSlot - Get the slot number of a global value.
536 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
537   // Check for uninitialized state and do lazy initialization.
538   initialize();
539
540   // Find the value in the module map
541   ValueMap::iterator MI = mMap.find(V);
542   return MI == mMap.end() ? -1 : (int)MI->second;
543 }
544
545 /// getMetadataSlot - Get the slot number of a MDNode.
546 int SlotTracker::getMetadataSlot(const MDNode *N) {
547   // Check for uninitialized state and do lazy initialization.
548   initialize();
549
550   // Find the MDNode in the module map
551   mdn_iterator MI = mdnMap.find(N);
552   return MI == mdnMap.end() ? -1 : (int)MI->second;
553 }
554
555
556 /// getLocalSlot - Get the slot number for a value that is local to a function.
557 int SlotTracker::getLocalSlot(const Value *V) {
558   assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
559
560   // Check for uninitialized state and do lazy initialization.
561   initialize();
562
563   ValueMap::iterator FI = fMap.find(V);
564   return FI == fMap.end() ? -1 : (int)FI->second;
565 }
566
567
568 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
569 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
570   assert(V && "Can't insert a null Value into SlotTracker!");
571   assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
572   assert(!V->hasName() && "Doesn't need a slot!");
573
574   unsigned DestSlot = mNext++;
575   mMap[V] = DestSlot;
576
577   ST_DEBUG("  Inserting value [" << V->getType() << "] = " << V << " slot=" <<
578            DestSlot << " [");
579   // G = Global, F = Function, A = Alias, o = other
580   ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
581             (isa<Function>(V) ? 'F' :
582              (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
583 }
584
585 /// CreateSlot - Create a new slot for the specified value if it has no name.
586 void SlotTracker::CreateFunctionSlot(const Value *V) {
587   assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
588
589   unsigned DestSlot = fNext++;
590   fMap[V] = DestSlot;
591
592   // G = Global, F = Function, o = other
593   ST_DEBUG("  Inserting value [" << V->getType() << "] = " << V << " slot=" <<
594            DestSlot << " [o]\n");
595 }
596
597 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
598 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
599   assert(N && "Can't insert a null Value into SlotTracker!");
600
601   // Don't insert if N is a function-local metadata, these are always printed
602   // inline.
603   if (!N->isFunctionLocal()) {
604     mdn_iterator I = mdnMap.find(N);
605     if (I != mdnMap.end())
606       return;
607
608     unsigned DestSlot = mdnNext++;
609     mdnMap[N] = DestSlot;
610   }
611
612   // Recursively add any MDNodes referenced by operands.
613   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
614     if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
615       CreateMetadataSlot(Op);
616 }
617
618 //===----------------------------------------------------------------------===//
619 // AsmWriter Implementation
620 //===----------------------------------------------------------------------===//
621
622 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
623                                    TypePrinting *TypePrinter,
624                                    SlotTracker *Machine,
625                                    const Module *Context);
626
627
628
629 static const char *getPredicateText(unsigned predicate) {
630   const char * pred = "unknown";
631   switch (predicate) {
632   case FCmpInst::FCMP_FALSE: pred = "false"; break;
633   case FCmpInst::FCMP_OEQ:   pred = "oeq"; break;
634   case FCmpInst::FCMP_OGT:   pred = "ogt"; break;
635   case FCmpInst::FCMP_OGE:   pred = "oge"; break;
636   case FCmpInst::FCMP_OLT:   pred = "olt"; break;
637   case FCmpInst::FCMP_OLE:   pred = "ole"; break;
638   case FCmpInst::FCMP_ONE:   pred = "one"; break;
639   case FCmpInst::FCMP_ORD:   pred = "ord"; break;
640   case FCmpInst::FCMP_UNO:   pred = "uno"; break;
641   case FCmpInst::FCMP_UEQ:   pred = "ueq"; break;
642   case FCmpInst::FCMP_UGT:   pred = "ugt"; break;
643   case FCmpInst::FCMP_UGE:   pred = "uge"; break;
644   case FCmpInst::FCMP_ULT:   pred = "ult"; break;
645   case FCmpInst::FCMP_ULE:   pred = "ule"; break;
646   case FCmpInst::FCMP_UNE:   pred = "une"; break;
647   case FCmpInst::FCMP_TRUE:  pred = "true"; break;
648   case ICmpInst::ICMP_EQ:    pred = "eq"; break;
649   case ICmpInst::ICMP_NE:    pred = "ne"; break;
650   case ICmpInst::ICMP_SGT:   pred = "sgt"; break;
651   case ICmpInst::ICMP_SGE:   pred = "sge"; break;
652   case ICmpInst::ICMP_SLT:   pred = "slt"; break;
653   case ICmpInst::ICMP_SLE:   pred = "sle"; break;
654   case ICmpInst::ICMP_UGT:   pred = "ugt"; break;
655   case ICmpInst::ICMP_UGE:   pred = "uge"; break;
656   case ICmpInst::ICMP_ULT:   pred = "ult"; break;
657   case ICmpInst::ICMP_ULE:   pred = "ule"; break;
658   }
659   return pred;
660 }
661
662 static void writeAtomicRMWOperation(raw_ostream &Out,
663                                     AtomicRMWInst::BinOp Op) {
664   switch (Op) {
665   default: Out << " <unknown operation " << Op << ">"; break;
666   case AtomicRMWInst::Xchg: Out << " xchg"; break;
667   case AtomicRMWInst::Add:  Out << " add"; break;
668   case AtomicRMWInst::Sub:  Out << " sub"; break;
669   case AtomicRMWInst::And:  Out << " and"; break;
670   case AtomicRMWInst::Nand: Out << " nand"; break;
671   case AtomicRMWInst::Or:   Out << " or"; break;
672   case AtomicRMWInst::Xor:  Out << " xor"; break;
673   case AtomicRMWInst::Max:  Out << " max"; break;
674   case AtomicRMWInst::Min:  Out << " min"; break;
675   case AtomicRMWInst::UMax: Out << " umax"; break;
676   case AtomicRMWInst::UMin: Out << " umin"; break;
677   }
678 }
679
680 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
681   if (const OverflowingBinaryOperator *OBO =
682         dyn_cast<OverflowingBinaryOperator>(U)) {
683     if (OBO->hasNoUnsignedWrap())
684       Out << " nuw";
685     if (OBO->hasNoSignedWrap())
686       Out << " nsw";
687   } else if (const PossiblyExactOperator *Div =
688                dyn_cast<PossiblyExactOperator>(U)) {
689     if (Div->isExact())
690       Out << " exact";
691   } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
692     if (GEP->isInBounds())
693       Out << " inbounds";
694   }
695 }
696
697 static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
698                                   TypePrinting &TypePrinter,
699                                   SlotTracker *Machine,
700                                   const Module *Context) {
701   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
702     if (CI->getType()->isIntegerTy(1)) {
703       Out << (CI->getZExtValue() ? "true" : "false");
704       return;
705     }
706     Out << CI->getValue();
707     return;
708   }
709
710   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
711     if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEhalf ||
712         &CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle ||
713         &CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble) {
714       // We would like to output the FP constant value in exponential notation,
715       // but we cannot do this if doing so will lose precision.  Check here to
716       // make sure that we only output it in exponential format if we can parse
717       // the value back and get the same value.
718       //
719       bool ignored;
720       bool isHalf = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEhalf;
721       bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
722       if (!isHalf) {
723         double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
724                                 CFP->getValueAPF().convertToFloat();
725         SmallString<128> StrVal;
726         raw_svector_ostream(StrVal) << Val;
727
728         // Check to make sure that the stringized number is not some string like
729         // "Inf" or NaN, that atof will accept, but the lexer will not.  Check
730         // that the string matches the "[-+]?[0-9]" regex.
731         //
732         if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
733             ((StrVal[0] == '-' || StrVal[0] == '+') &&
734              (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
735           // Reparse stringized version!
736           if (atof(StrVal.c_str()) == Val) {
737             Out << StrVal.str();
738             return;
739           }
740         }
741       }
742       // Otherwise we could not reparse it to exactly the same value, so we must
743       // output the string in hexadecimal format!  Note that loading and storing
744       // floating point types changes the bits of NaNs on some hosts, notably
745       // x86, so we must not use these types.
746       assert(sizeof(double) == sizeof(uint64_t) &&
747              "assuming that double is 64 bits!");
748       char Buffer[40];
749       APFloat apf = CFP->getValueAPF();
750       // Halves and floats are represented in ASCII IR as double, convert.
751       if (!isDouble)
752         apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
753                           &ignored);
754       Out << "0x" <<
755               utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()),
756                             Buffer+40);
757       return;
758     }
759
760     // Some form of long double.  These appear as a magic letter identifying
761     // the type, then a fixed number of hex digits.
762     Out << "0x";
763     if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
764       Out << 'K';
765       // api needed to prevent premature destruction
766       APInt api = CFP->getValueAPF().bitcastToAPInt();
767       const uint64_t* p = api.getRawData();
768       uint64_t word = p[1];
769       int shiftcount=12;
770       int width = api.getBitWidth();
771       for (int j=0; j<width; j+=4, shiftcount-=4) {
772         unsigned int nibble = (word>>shiftcount) & 15;
773         if (nibble < 10)
774           Out << (unsigned char)(nibble + '0');
775         else
776           Out << (unsigned char)(nibble - 10 + 'A');
777         if (shiftcount == 0 && j+4 < width) {
778           word = *p;
779           shiftcount = 64;
780           if (width-j-4 < 64)
781             shiftcount = width-j-4;
782         }
783       }
784       return;
785     } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad)
786       Out << 'L';
787     else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble)
788       Out << 'M';
789     else
790       llvm_unreachable("Unsupported floating point type");
791     // api needed to prevent premature destruction
792     APInt api = CFP->getValueAPF().bitcastToAPInt();
793     const uint64_t* p = api.getRawData();
794     uint64_t word = *p;
795     int shiftcount=60;
796     int width = api.getBitWidth();
797     for (int j=0; j<width; j+=4, shiftcount-=4) {
798       unsigned int nibble = (word>>shiftcount) & 15;
799       if (nibble < 10)
800         Out << (unsigned char)(nibble + '0');
801       else
802         Out << (unsigned char)(nibble - 10 + 'A');
803       if (shiftcount == 0 && j+4 < width) {
804         word = *(++p);
805         shiftcount = 64;
806         if (width-j-4 < 64)
807           shiftcount = width-j-4;
808       }
809     }
810     return;
811   }
812
813   if (isa<ConstantAggregateZero>(CV)) {
814     Out << "zeroinitializer";
815     return;
816   }
817
818   if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
819     Out << "blockaddress(";
820     WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine,
821                            Context);
822     Out << ", ";
823     WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine,
824                            Context);
825     Out << ")";
826     return;
827   }
828
829   if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
830     // As a special case, print the array as a string if it is an array of
831     // i8 with ConstantInt values.
832     //
833     Type *ETy = CA->getType()->getElementType();
834     if (CA->isString()) {
835       Out << "c\"";
836       PrintEscapedString(CA->getAsString(), Out);
837       Out << '"';
838     } else {                // Cannot output in string format...
839       Out << '[';
840       if (CA->getNumOperands()) {
841         TypePrinter.print(ETy, Out);
842         Out << ' ';
843         WriteAsOperandInternal(Out, CA->getOperand(0),
844                                &TypePrinter, Machine,
845                                Context);
846         for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
847           Out << ", ";
848           TypePrinter.print(ETy, Out);
849           Out << ' ';
850           WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine,
851                                  Context);
852         }
853       }
854       Out << ']';
855     }
856     return;
857   }
858
859   if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
860     if (CS->getType()->isPacked())
861       Out << '<';
862     Out << '{';
863     unsigned N = CS->getNumOperands();
864     if (N) {
865       Out << ' ';
866       TypePrinter.print(CS->getOperand(0)->getType(), Out);
867       Out << ' ';
868
869       WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine,
870                              Context);
871
872       for (unsigned i = 1; i < N; i++) {
873         Out << ", ";
874         TypePrinter.print(CS->getOperand(i)->getType(), Out);
875         Out << ' ';
876
877         WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine,
878                                Context);
879       }
880       Out << ' ';
881     }
882
883     Out << '}';
884     if (CS->getType()->isPacked())
885       Out << '>';
886     return;
887   }
888
889   if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
890     Type *ETy = CP->getType()->getElementType();
891     assert(CP->getNumOperands() > 0 &&
892            "Number of operands for a PackedConst must be > 0");
893     Out << '<';
894     TypePrinter.print(ETy, Out);
895     Out << ' ';
896     WriteAsOperandInternal(Out, CP->getOperand(0), &TypePrinter, Machine,
897                            Context);
898     for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
899       Out << ", ";
900       TypePrinter.print(ETy, Out);
901       Out << ' ';
902       WriteAsOperandInternal(Out, CP->getOperand(i), &TypePrinter, Machine,
903                              Context);
904     }
905     Out << '>';
906     return;
907   }
908
909   if (isa<ConstantPointerNull>(CV)) {
910     Out << "null";
911     return;
912   }
913
914   if (isa<UndefValue>(CV)) {
915     Out << "undef";
916     return;
917   }
918
919   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
920     Out << CE->getOpcodeName();
921     WriteOptimizationInfo(Out, CE);
922     if (CE->isCompare())
923       Out << ' ' << getPredicateText(CE->getPredicate());
924     Out << " (";
925
926     for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
927       TypePrinter.print((*OI)->getType(), Out);
928       Out << ' ';
929       WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context);
930       if (OI+1 != CE->op_end())
931         Out << ", ";
932     }
933
934     if (CE->hasIndices()) {
935       ArrayRef<unsigned> Indices = CE->getIndices();
936       for (unsigned i = 0, e = Indices.size(); i != e; ++i)
937         Out << ", " << Indices[i];
938     }
939
940     if (CE->isCast()) {
941       Out << " to ";
942       TypePrinter.print(CE->getType(), Out);
943     }
944
945     Out << ')';
946     return;
947   }
948
949   Out << "<placeholder or erroneous Constant>";
950 }
951
952 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
953                                     TypePrinting *TypePrinter,
954                                     SlotTracker *Machine,
955                                     const Module *Context) {
956   Out << "!{";
957   for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
958     const Value *V = Node->getOperand(mi);
959     if (V == 0)
960       Out << "null";
961     else {
962       TypePrinter->print(V->getType(), Out);
963       Out << ' ';
964       WriteAsOperandInternal(Out, Node->getOperand(mi),
965                              TypePrinter, Machine, Context);
966     }
967     if (mi + 1 != me)
968       Out << ", ";
969   }
970
971   Out << "}";
972 }
973
974
975 /// WriteAsOperand - Write the name of the specified value out to the specified
976 /// ostream.  This can be useful when you just want to print int %reg126, not
977 /// the whole instruction that generated it.
978 ///
979 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
980                                    TypePrinting *TypePrinter,
981                                    SlotTracker *Machine,
982                                    const Module *Context) {
983   if (V->hasName()) {
984     PrintLLVMName(Out, V);
985     return;
986   }
987
988   const Constant *CV = dyn_cast<Constant>(V);
989   if (CV && !isa<GlobalValue>(CV)) {
990     assert(TypePrinter && "Constants require TypePrinting!");
991     WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context);
992     return;
993   }
994
995   if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
996     Out << "asm ";
997     if (IA->hasSideEffects())
998       Out << "sideeffect ";
999     if (IA->isAlignStack())
1000       Out << "alignstack ";
1001     Out << '"';
1002     PrintEscapedString(IA->getAsmString(), Out);
1003     Out << "\", \"";
1004     PrintEscapedString(IA->getConstraintString(), Out);
1005     Out << '"';
1006     return;
1007   }
1008
1009   if (const MDNode *N = dyn_cast<MDNode>(V)) {
1010     if (N->isFunctionLocal()) {
1011       // Print metadata inline, not via slot reference number.
1012       WriteMDNodeBodyInternal(Out, N, TypePrinter, Machine, Context);
1013       return;
1014     }
1015
1016     if (!Machine) {
1017       if (N->isFunctionLocal())
1018         Machine = new SlotTracker(N->getFunction());
1019       else
1020         Machine = new SlotTracker(Context);
1021     }
1022     int Slot = Machine->getMetadataSlot(N);
1023     if (Slot == -1)
1024       Out << "<badref>";
1025     else
1026       Out << '!' << Slot;
1027     return;
1028   }
1029
1030   if (const MDString *MDS = dyn_cast<MDString>(V)) {
1031     Out << "!\"";
1032     PrintEscapedString(MDS->getString(), Out);
1033     Out << '"';
1034     return;
1035   }
1036
1037   if (V->getValueID() == Value::PseudoSourceValueVal ||
1038       V->getValueID() == Value::FixedStackPseudoSourceValueVal) {
1039     V->print(Out);
1040     return;
1041   }
1042
1043   char Prefix = '%';
1044   int Slot;
1045   // If we have a SlotTracker, use it.
1046   if (Machine) {
1047     if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1048       Slot = Machine->getGlobalSlot(GV);
1049       Prefix = '@';
1050     } else {
1051       Slot = Machine->getLocalSlot(V);
1052
1053       // If the local value didn't succeed, then we may be referring to a value
1054       // from a different function.  Translate it, as this can happen when using
1055       // address of blocks.
1056       if (Slot == -1)
1057         if ((Machine = createSlotTracker(V))) {
1058           Slot = Machine->getLocalSlot(V);
1059           delete Machine;
1060         }
1061     }
1062   } else if ((Machine = createSlotTracker(V))) {
1063     // Otherwise, create one to get the # and then destroy it.
1064     if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1065       Slot = Machine->getGlobalSlot(GV);
1066       Prefix = '@';
1067     } else {
1068       Slot = Machine->getLocalSlot(V);
1069     }
1070     delete Machine;
1071     Machine = 0;
1072   } else {
1073     Slot = -1;
1074   }
1075
1076   if (Slot != -1)
1077     Out << Prefix << Slot;
1078   else
1079     Out << "<badref>";
1080 }
1081
1082 void llvm::WriteAsOperand(raw_ostream &Out, const Value *V,
1083                           bool PrintType, const Module *Context) {
1084
1085   // Fast path: Don't construct and populate a TypePrinting object if we
1086   // won't be needing any types printed.
1087   if (!PrintType &&
1088       ((!isa<Constant>(V) && !isa<MDNode>(V)) ||
1089        V->hasName() || isa<GlobalValue>(V))) {
1090     WriteAsOperandInternal(Out, V, 0, 0, Context);
1091     return;
1092   }
1093
1094   if (Context == 0) Context = getModuleFromVal(V);
1095
1096   TypePrinting TypePrinter;
1097   if (Context)
1098     TypePrinter.incorporateTypes(*Context);
1099   if (PrintType) {
1100     TypePrinter.print(V->getType(), Out);
1101     Out << ' ';
1102   }
1103
1104   WriteAsOperandInternal(Out, V, &TypePrinter, 0, Context);
1105 }
1106
1107 namespace {
1108
1109 class AssemblyWriter {
1110   formatted_raw_ostream &Out;
1111   SlotTracker &Machine;
1112   const Module *TheModule;
1113   TypePrinting TypePrinter;
1114   AssemblyAnnotationWriter *AnnotationWriter;
1115
1116 public:
1117   inline AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
1118                         const Module *M,
1119                         AssemblyAnnotationWriter *AAW)
1120     : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
1121     if (M)
1122       TypePrinter.incorporateTypes(*M);
1123   }
1124
1125   void printMDNodeBody(const MDNode *MD);
1126   void printNamedMDNode(const NamedMDNode *NMD);
1127
1128   void printModule(const Module *M);
1129
1130   void writeOperand(const Value *Op, bool PrintType);
1131   void writeParamOperand(const Value *Operand, Attributes Attrs);
1132   void writeAtomic(AtomicOrdering Ordering, SynchronizationScope SynchScope);
1133
1134   void writeAllMDNodes();
1135
1136   void printTypeIdentities();
1137   void printGlobal(const GlobalVariable *GV);
1138   void printAlias(const GlobalAlias *GV);
1139   void printFunction(const Function *F);
1140   void printArgument(const Argument *FA, Attributes Attrs);
1141   void printBasicBlock(const BasicBlock *BB);
1142   void printInstruction(const Instruction &I);
1143
1144 private:
1145   // printInfoComment - Print a little comment after the instruction indicating
1146   // which slot it occupies.
1147   void printInfoComment(const Value &V);
1148 };
1149 }  // end of anonymous namespace
1150
1151 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
1152   if (Operand == 0) {
1153     Out << "<null operand!>";
1154     return;
1155   }
1156   if (PrintType) {
1157     TypePrinter.print(Operand->getType(), Out);
1158     Out << ' ';
1159   }
1160   WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
1161 }
1162
1163 void AssemblyWriter::writeAtomic(AtomicOrdering Ordering,
1164                                  SynchronizationScope SynchScope) {
1165   if (Ordering == NotAtomic)
1166     return;
1167
1168   switch (SynchScope) {
1169   case SingleThread: Out << " singlethread"; break;
1170   case CrossThread: break;
1171   }
1172
1173   switch (Ordering) {
1174   default: Out << " <bad ordering " << int(Ordering) << ">"; break;
1175   case Unordered: Out << " unordered"; break;
1176   case Monotonic: Out << " monotonic"; break;
1177   case Acquire: Out << " acquire"; break;
1178   case Release: Out << " release"; break;
1179   case AcquireRelease: Out << " acq_rel"; break;
1180   case SequentiallyConsistent: Out << " seq_cst"; break;
1181   }
1182 }
1183
1184 void AssemblyWriter::writeParamOperand(const Value *Operand,
1185                                        Attributes Attrs) {
1186   if (Operand == 0) {
1187     Out << "<null operand!>";
1188     return;
1189   }
1190
1191   // Print the type
1192   TypePrinter.print(Operand->getType(), Out);
1193   // Print parameter attributes list
1194   if (Attrs != Attribute::None)
1195     Out << ' ' << Attribute::getAsString(Attrs);
1196   Out << ' ';
1197   // Print the operand
1198   WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
1199 }
1200
1201 void AssemblyWriter::printModule(const Module *M) {
1202   if (!M->getModuleIdentifier().empty() &&
1203       // Don't print the ID if it will start a new line (which would
1204       // require a comment char before it).
1205       M->getModuleIdentifier().find('\n') == std::string::npos)
1206     Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1207
1208   if (!M->getDataLayout().empty())
1209     Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
1210   if (!M->getTargetTriple().empty())
1211     Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1212
1213   if (!M->getModuleInlineAsm().empty()) {
1214     // Split the string into lines, to make it easier to read the .ll file.
1215     std::string Asm = M->getModuleInlineAsm();
1216     size_t CurPos = 0;
1217     size_t NewLine = Asm.find_first_of('\n', CurPos);
1218     Out << '\n';
1219     while (NewLine != std::string::npos) {
1220       // We found a newline, print the portion of the asm string from the
1221       // last newline up to this newline.
1222       Out << "module asm \"";
1223       PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1224                          Out);
1225       Out << "\"\n";
1226       CurPos = NewLine+1;
1227       NewLine = Asm.find_first_of('\n', CurPos);
1228     }
1229     std::string rest(Asm.begin()+CurPos, Asm.end());
1230     if (!rest.empty()) {
1231       Out << "module asm \"";
1232       PrintEscapedString(rest, Out);
1233       Out << "\"\n";
1234     }
1235   }
1236
1237   // Loop over the dependent libraries and emit them.
1238   Module::lib_iterator LI = M->lib_begin();
1239   Module::lib_iterator LE = M->lib_end();
1240   if (LI != LE) {
1241     Out << '\n';
1242     Out << "deplibs = [ ";
1243     while (LI != LE) {
1244       Out << '"' << *LI << '"';
1245       ++LI;
1246       if (LI != LE)
1247         Out << ", ";
1248     }
1249     Out << " ]";
1250   }
1251
1252   printTypeIdentities();
1253
1254   // Output all globals.
1255   if (!M->global_empty()) Out << '\n';
1256   for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1257        I != E; ++I)
1258     printGlobal(I);
1259
1260   // Output all aliases.
1261   if (!M->alias_empty()) Out << "\n";
1262   for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1263        I != E; ++I)
1264     printAlias(I);
1265
1266   // Output all of the functions.
1267   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1268     printFunction(I);
1269
1270   // Output named metadata.
1271   if (!M->named_metadata_empty()) Out << '\n';
1272
1273   for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
1274        E = M->named_metadata_end(); I != E; ++I)
1275     printNamedMDNode(I);
1276
1277   // Output metadata.
1278   if (!Machine.mdn_empty()) {
1279     Out << '\n';
1280     writeAllMDNodes();
1281   }
1282 }
1283
1284 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
1285   Out << '!';
1286   StringRef Name = NMD->getName();
1287   if (Name.empty()) {
1288     Out << "<empty name> ";
1289   } else {
1290     if (isalpha(Name[0]) || Name[0] == '-' || Name[0] == '$' ||
1291         Name[0] == '.' || Name[0] == '_')
1292       Out << Name[0];
1293     else
1294       Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F);
1295     for (unsigned i = 1, e = Name.size(); i != e; ++i) {
1296       unsigned char C = Name[i];
1297       if (isalnum(C) || C == '-' || C == '$' || C == '.' || C == '_')
1298         Out << C;
1299       else
1300         Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
1301     }
1302   }
1303   Out << " = !{";
1304   for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1305     if (i) Out << ", ";
1306     int Slot = Machine.getMetadataSlot(NMD->getOperand(i));
1307     if (Slot == -1)
1308       Out << "<badref>";
1309     else
1310       Out << '!' << Slot;
1311   }
1312   Out << "}\n";
1313 }
1314
1315
1316 static void PrintLinkage(GlobalValue::LinkageTypes LT,
1317                          formatted_raw_ostream &Out) {
1318   switch (LT) {
1319   case GlobalValue::ExternalLinkage: break;
1320   case GlobalValue::PrivateLinkage:       Out << "private ";        break;
1321   case GlobalValue::LinkerPrivateLinkage: Out << "linker_private "; break;
1322   case GlobalValue::LinkerPrivateWeakLinkage:
1323     Out << "linker_private_weak ";
1324     break;
1325   case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
1326     Out << "linker_private_weak_def_auto ";
1327     break;
1328   case GlobalValue::InternalLinkage:      Out << "internal ";       break;
1329   case GlobalValue::LinkOnceAnyLinkage:   Out << "linkonce ";       break;
1330   case GlobalValue::LinkOnceODRLinkage:   Out << "linkonce_odr ";   break;
1331   case GlobalValue::WeakAnyLinkage:       Out << "weak ";           break;
1332   case GlobalValue::WeakODRLinkage:       Out << "weak_odr ";       break;
1333   case GlobalValue::CommonLinkage:        Out << "common ";         break;
1334   case GlobalValue::AppendingLinkage:     Out << "appending ";      break;
1335   case GlobalValue::DLLImportLinkage:     Out << "dllimport ";      break;
1336   case GlobalValue::DLLExportLinkage:     Out << "dllexport ";      break;
1337   case GlobalValue::ExternalWeakLinkage:  Out << "extern_weak ";    break;
1338   case GlobalValue::AvailableExternallyLinkage:
1339     Out << "available_externally ";
1340     break;
1341   }
1342 }
1343
1344
1345 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1346                             formatted_raw_ostream &Out) {
1347   switch (Vis) {
1348   case GlobalValue::DefaultVisibility: break;
1349   case GlobalValue::HiddenVisibility:    Out << "hidden "; break;
1350   case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1351   }
1352 }
1353
1354 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1355   if (GV->isMaterializable())
1356     Out << "; Materializable\n";
1357
1358   WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent());
1359   Out << " = ";
1360
1361   if (!GV->hasInitializer() && GV->hasExternalLinkage())
1362     Out << "external ";
1363
1364   PrintLinkage(GV->getLinkage(), Out);
1365   PrintVisibility(GV->getVisibility(), Out);
1366
1367   if (GV->isThreadLocal()) Out << "thread_local ";
1368   if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1369     Out << "addrspace(" << AddressSpace << ") ";
1370   if (GV->hasUnnamedAddr()) Out << "unnamed_addr ";
1371   Out << (GV->isConstant() ? "constant " : "global ");
1372   TypePrinter.print(GV->getType()->getElementType(), Out);
1373
1374   if (GV->hasInitializer()) {
1375     Out << ' ';
1376     writeOperand(GV->getInitializer(), false);
1377   }
1378
1379   if (GV->hasSection()) {
1380     Out << ", section \"";
1381     PrintEscapedString(GV->getSection(), Out);
1382     Out << '"';
1383   }
1384   if (GV->getAlignment())
1385     Out << ", align " << GV->getAlignment();
1386
1387   printInfoComment(*GV);
1388   Out << '\n';
1389 }
1390
1391 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1392   if (GA->isMaterializable())
1393     Out << "; Materializable\n";
1394
1395   // Don't crash when dumping partially built GA
1396   if (!GA->hasName())
1397     Out << "<<nameless>> = ";
1398   else {
1399     PrintLLVMName(Out, GA);
1400     Out << " = ";
1401   }
1402   PrintVisibility(GA->getVisibility(), Out);
1403
1404   Out << "alias ";
1405
1406   PrintLinkage(GA->getLinkage(), Out);
1407
1408   const Constant *Aliasee = GA->getAliasee();
1409
1410   if (Aliasee == 0) {
1411     TypePrinter.print(GA->getType(), Out);
1412     Out << " <<NULL ALIASEE>>";
1413   } else {
1414     writeOperand(Aliasee, !isa<ConstantExpr>(Aliasee));
1415   }
1416
1417   printInfoComment(*GA);
1418   Out << '\n';
1419 }
1420
1421 void AssemblyWriter::printTypeIdentities() {
1422   if (TypePrinter.NumberedTypes.empty() &&
1423       TypePrinter.NamedTypes.empty())
1424     return;
1425
1426   Out << '\n';
1427
1428   // We know all the numbers that each type is used and we know that it is a
1429   // dense assignment.  Convert the map to an index table.
1430   std::vector<StructType*> NumberedTypes(TypePrinter.NumberedTypes.size());
1431   for (DenseMap<StructType*, unsigned>::iterator I =
1432        TypePrinter.NumberedTypes.begin(), E = TypePrinter.NumberedTypes.end();
1433        I != E; ++I) {
1434     assert(I->second < NumberedTypes.size() && "Didn't get a dense numbering?");
1435     NumberedTypes[I->second] = I->first;
1436   }
1437
1438   // Emit all numbered types.
1439   for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
1440     Out << '%' << i << " = type ";
1441
1442     // Make sure we print out at least one level of the type structure, so
1443     // that we do not get %2 = type %2
1444     TypePrinter.printStructBody(NumberedTypes[i], Out);
1445     Out << '\n';
1446   }
1447
1448   for (unsigned i = 0, e = TypePrinter.NamedTypes.size(); i != e; ++i) {
1449     PrintLLVMName(Out, TypePrinter.NamedTypes[i]->getName(), LocalPrefix);
1450     Out << " = type ";
1451
1452     // Make sure we print out at least one level of the type structure, so
1453     // that we do not get %FILE = type %FILE
1454     TypePrinter.printStructBody(TypePrinter.NamedTypes[i], Out);
1455     Out << '\n';
1456   }
1457 }
1458
1459 /// printFunction - Print all aspects of a function.
1460 ///
1461 void AssemblyWriter::printFunction(const Function *F) {
1462   // Print out the return type and name.
1463   Out << '\n';
1464
1465   if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1466
1467   if (F->isMaterializable())
1468     Out << "; Materializable\n";
1469
1470   if (F->isDeclaration())
1471     Out << "declare ";
1472   else
1473     Out << "define ";
1474
1475   PrintLinkage(F->getLinkage(), Out);
1476   PrintVisibility(F->getVisibility(), Out);
1477
1478   // Print the calling convention.
1479   switch (F->getCallingConv()) {
1480   case CallingConv::C: break;   // default
1481   case CallingConv::Fast:         Out << "fastcc "; break;
1482   case CallingConv::Cold:         Out << "coldcc "; break;
1483   case CallingConv::X86_StdCall:  Out << "x86_stdcallcc "; break;
1484   case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1485   case CallingConv::X86_ThisCall: Out << "x86_thiscallcc "; break;
1486   case CallingConv::ARM_APCS:     Out << "arm_apcscc "; break;
1487   case CallingConv::ARM_AAPCS:    Out << "arm_aapcscc "; break;
1488   case CallingConv::ARM_AAPCS_VFP:Out << "arm_aapcs_vfpcc "; break;
1489   case CallingConv::MSP430_INTR:  Out << "msp430_intrcc "; break;
1490   case CallingConv::PTX_Kernel:   Out << "ptx_kernel "; break;
1491   case CallingConv::PTX_Device:   Out << "ptx_device "; break;
1492   default: Out << "cc" << F->getCallingConv() << " "; break;
1493   }
1494
1495   FunctionType *FT = F->getFunctionType();
1496   const AttrListPtr &Attrs = F->getAttributes();
1497   Attributes RetAttrs = Attrs.getRetAttributes();
1498   if (RetAttrs != Attribute::None)
1499     Out <<  Attribute::getAsString(Attrs.getRetAttributes()) << ' ';
1500   TypePrinter.print(F->getReturnType(), Out);
1501   Out << ' ';
1502   WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
1503   Out << '(';
1504   Machine.incorporateFunction(F);
1505
1506   // Loop over the arguments, printing them...
1507
1508   unsigned Idx = 1;
1509   if (!F->isDeclaration()) {
1510     // If this isn't a declaration, print the argument names as well.
1511     for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1512          I != E; ++I) {
1513       // Insert commas as we go... the first arg doesn't get a comma
1514       if (I != F->arg_begin()) Out << ", ";
1515       printArgument(I, Attrs.getParamAttributes(Idx));
1516       Idx++;
1517     }
1518   } else {
1519     // Otherwise, print the types from the function type.
1520     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1521       // Insert commas as we go... the first arg doesn't get a comma
1522       if (i) Out << ", ";
1523
1524       // Output type...
1525       TypePrinter.print(FT->getParamType(i), Out);
1526
1527       Attributes ArgAttrs = Attrs.getParamAttributes(i+1);
1528       if (ArgAttrs != Attribute::None)
1529         Out << ' ' << Attribute::getAsString(ArgAttrs);
1530     }
1531   }
1532
1533   // Finish printing arguments...
1534   if (FT->isVarArg()) {
1535     if (FT->getNumParams()) Out << ", ";
1536     Out << "...";  // Output varargs portion of signature!
1537   }
1538   Out << ')';
1539   if (F->hasUnnamedAddr())
1540     Out << " unnamed_addr";
1541   Attributes FnAttrs = Attrs.getFnAttributes();
1542   if (FnAttrs != Attribute::None)
1543     Out << ' ' << Attribute::getAsString(Attrs.getFnAttributes());
1544   if (F->hasSection()) {
1545     Out << " section \"";
1546     PrintEscapedString(F->getSection(), Out);
1547     Out << '"';
1548   }
1549   if (F->getAlignment())
1550     Out << " align " << F->getAlignment();
1551   if (F->hasGC())
1552     Out << " gc \"" << F->getGC() << '"';
1553   if (F->isDeclaration()) {
1554     Out << '\n';
1555   } else {
1556     Out << " {";
1557     // Output all of the function's basic blocks.
1558     for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1559       printBasicBlock(I);
1560
1561     Out << "}\n";
1562   }
1563
1564   Machine.purgeFunction();
1565 }
1566
1567 /// printArgument - This member is called for every argument that is passed into
1568 /// the function.  Simply print it out
1569 ///
1570 void AssemblyWriter::printArgument(const Argument *Arg,
1571                                    Attributes Attrs) {
1572   // Output type...
1573   TypePrinter.print(Arg->getType(), Out);
1574
1575   // Output parameter attributes list
1576   if (Attrs != Attribute::None)
1577     Out << ' ' << Attribute::getAsString(Attrs);
1578
1579   // Output name, if available...
1580   if (Arg->hasName()) {
1581     Out << ' ';
1582     PrintLLVMName(Out, Arg);
1583   }
1584 }
1585
1586 /// printBasicBlock - This member is called for each basic block in a method.
1587 ///
1588 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1589   if (BB->hasName()) {              // Print out the label if it exists...
1590     Out << "\n";
1591     PrintLLVMName(Out, BB->getName(), LabelPrefix);
1592     Out << ':';
1593   } else if (!BB->use_empty()) {      // Don't print block # of no uses...
1594     Out << "\n; <label>:";
1595     int Slot = Machine.getLocalSlot(BB);
1596     if (Slot != -1)
1597       Out << Slot;
1598     else
1599       Out << "<badref>";
1600   }
1601
1602   if (BB->getParent() == 0) {
1603     Out.PadToColumn(50);
1604     Out << "; Error: Block without parent!";
1605   } else if (BB != &BB->getParent()->getEntryBlock()) {  // Not the entry block?
1606     // Output predecessors for the block.
1607     Out.PadToColumn(50);
1608     Out << ";";
1609     const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1610
1611     if (PI == PE) {
1612       Out << " No predecessors!";
1613     } else {
1614       Out << " preds = ";
1615       writeOperand(*PI, false);
1616       for (++PI; PI != PE; ++PI) {
1617         Out << ", ";
1618         writeOperand(*PI, false);
1619       }
1620     }
1621   }
1622
1623   Out << "\n";
1624
1625   if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1626
1627   // Output all of the instructions in the basic block...
1628   for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1629     printInstruction(*I);
1630     Out << '\n';
1631   }
1632
1633   if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1634 }
1635
1636 /// printInfoComment - Print a little comment after the instruction indicating
1637 /// which slot it occupies.
1638 ///
1639 void AssemblyWriter::printInfoComment(const Value &V) {
1640   if (AnnotationWriter) {
1641     AnnotationWriter->printInfoComment(V, Out);
1642     return;
1643   }
1644 }
1645
1646 // This member is called for each Instruction in a function..
1647 void AssemblyWriter::printInstruction(const Instruction &I) {
1648   if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1649
1650   // Print out indentation for an instruction.
1651   Out << "  ";
1652
1653   // Print out name if it exists...
1654   if (I.hasName()) {
1655     PrintLLVMName(Out, &I);
1656     Out << " = ";
1657   } else if (!I.getType()->isVoidTy()) {
1658     // Print out the def slot taken.
1659     int SlotNum = Machine.getLocalSlot(&I);
1660     if (SlotNum == -1)
1661       Out << "<badref> = ";
1662     else
1663       Out << '%' << SlotNum << " = ";
1664   }
1665
1666   if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall())
1667     Out << "tail ";
1668
1669   // Print out the opcode...
1670   Out << I.getOpcodeName();
1671
1672   // If this is an atomic load or store, print out the atomic marker.
1673   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isAtomic()) ||
1674       (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
1675     Out << " atomic";
1676
1677   // If this is a volatile operation, print out the volatile marker.
1678   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isVolatile()) ||
1679       (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
1680       (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
1681       (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
1682     Out << " volatile";
1683
1684   // Print out optimization information.
1685   WriteOptimizationInfo(Out, &I);
1686
1687   // Print out the compare instruction predicates
1688   if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1689     Out << ' ' << getPredicateText(CI->getPredicate());
1690
1691   // Print out the atomicrmw operation
1692   if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
1693     writeAtomicRMWOperation(Out, RMWI->getOperation());
1694
1695   // Print out the type of the operands...
1696   const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1697
1698   // Special case conditional branches to swizzle the condition out to the front
1699   if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
1700     BranchInst &BI(cast<BranchInst>(I));
1701     Out << ' ';
1702     writeOperand(BI.getCondition(), true);
1703     Out << ", ";
1704     writeOperand(BI.getSuccessor(0), true);
1705     Out << ", ";
1706     writeOperand(BI.getSuccessor(1), true);
1707
1708   } else if (isa<SwitchInst>(I)) {
1709     SwitchInst& SI(cast<SwitchInst>(I));
1710     // Special case switch instruction to get formatting nice and correct.
1711     Out << ' ';
1712     writeOperand(SI.getCondition(), true);
1713     Out << ", ";
1714     writeOperand(SI.getDefaultDest(), true);
1715     Out << " [";
1716     // Skip the first item since that's the default case.
1717     unsigned NumCases = SI.getNumCases();
1718     for (unsigned i = 1; i < NumCases; ++i) {
1719       Out << "\n    ";
1720       writeOperand(SI.getCaseValue(i), true);
1721       Out << ", ";
1722       writeOperand(SI.getSuccessor(i), true);
1723     }
1724     Out << "\n  ]";
1725   } else if (isa<IndirectBrInst>(I)) {
1726     // Special case indirectbr instruction to get formatting nice and correct.
1727     Out << ' ';
1728     writeOperand(Operand, true);
1729     Out << ", [";
1730
1731     for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1732       if (i != 1)
1733         Out << ", ";
1734       writeOperand(I.getOperand(i), true);
1735     }
1736     Out << ']';
1737   } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
1738     Out << ' ';
1739     TypePrinter.print(I.getType(), Out);
1740     Out << ' ';
1741
1742     for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
1743       if (op) Out << ", ";
1744       Out << "[ ";
1745       writeOperand(PN->getIncomingValue(op), false); Out << ", ";
1746       writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
1747     }
1748   } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1749     Out << ' ';
1750     writeOperand(I.getOperand(0), true);
1751     for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1752       Out << ", " << *i;
1753   } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1754     Out << ' ';
1755     writeOperand(I.getOperand(0), true); Out << ", ";
1756     writeOperand(I.getOperand(1), true);
1757     for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1758       Out << ", " << *i;
1759   } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
1760     Out << ' ';
1761     TypePrinter.print(I.getType(), Out);
1762     Out << " personality ";
1763     writeOperand(I.getOperand(0), true); Out << '\n';
1764
1765     if (LPI->isCleanup())
1766       Out << "          cleanup";
1767
1768     for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
1769       if (i != 0 || LPI->isCleanup()) Out << "\n";
1770       if (LPI->isCatch(i))
1771         Out << "          catch ";
1772       else
1773         Out << "          filter ";
1774
1775       writeOperand(LPI->getClause(i), true);
1776     }
1777   } else if (isa<ReturnInst>(I) && !Operand) {
1778     Out << " void";
1779   } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1780     // Print the calling convention being used.
1781     switch (CI->getCallingConv()) {
1782     case CallingConv::C: break;   // default
1783     case CallingConv::Fast:  Out << " fastcc"; break;
1784     case CallingConv::Cold:  Out << " coldcc"; break;
1785     case CallingConv::X86_StdCall:  Out << " x86_stdcallcc"; break;
1786     case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1787     case CallingConv::X86_ThisCall: Out << " x86_thiscallcc"; break;
1788     case CallingConv::ARM_APCS:     Out << " arm_apcscc "; break;
1789     case CallingConv::ARM_AAPCS:    Out << " arm_aapcscc "; break;
1790     case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1791     case CallingConv::MSP430_INTR:  Out << " msp430_intrcc "; break;
1792     case CallingConv::PTX_Kernel:   Out << " ptx_kernel"; break;
1793     case CallingConv::PTX_Device:   Out << " ptx_device"; break;
1794     default: Out << " cc" << CI->getCallingConv(); break;
1795     }
1796
1797     Operand = CI->getCalledValue();
1798     PointerType *PTy = cast<PointerType>(Operand->getType());
1799     FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1800     Type *RetTy = FTy->getReturnType();
1801     const AttrListPtr &PAL = CI->getAttributes();
1802
1803     if (PAL.getRetAttributes() != Attribute::None)
1804       Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1805
1806     // If possible, print out the short form of the call instruction.  We can
1807     // only do this if the first argument is a pointer to a nonvararg function,
1808     // and if the return type is not a pointer to a function.
1809     //
1810     Out << ' ';
1811     if (!FTy->isVarArg() &&
1812         (!RetTy->isPointerTy() ||
1813          !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
1814       TypePrinter.print(RetTy, Out);
1815       Out << ' ';
1816       writeOperand(Operand, false);
1817     } else {
1818       writeOperand(Operand, true);
1819     }
1820     Out << '(';
1821     for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
1822       if (op > 0)
1823         Out << ", ";
1824       writeParamOperand(CI->getArgOperand(op), PAL.getParamAttributes(op + 1));
1825     }
1826     Out << ')';
1827     if (PAL.getFnAttributes() != Attribute::None)
1828       Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1829   } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1830     Operand = II->getCalledValue();
1831     PointerType *PTy = cast<PointerType>(Operand->getType());
1832     FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1833     Type *RetTy = FTy->getReturnType();
1834     const AttrListPtr &PAL = II->getAttributes();
1835
1836     // Print the calling convention being used.
1837     switch (II->getCallingConv()) {
1838     case CallingConv::C: break;   // default
1839     case CallingConv::Fast:  Out << " fastcc"; break;
1840     case CallingConv::Cold:  Out << " coldcc"; break;
1841     case CallingConv::X86_StdCall:  Out << " x86_stdcallcc"; break;
1842     case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1843     case CallingConv::X86_ThisCall: Out << " x86_thiscallcc"; break;
1844     case CallingConv::ARM_APCS:     Out << " arm_apcscc "; break;
1845     case CallingConv::ARM_AAPCS:    Out << " arm_aapcscc "; break;
1846     case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1847     case CallingConv::MSP430_INTR:  Out << " msp430_intrcc "; break;
1848     case CallingConv::PTX_Kernel:   Out << " ptx_kernel"; break;
1849     case CallingConv::PTX_Device:   Out << " ptx_device"; break;
1850     default: Out << " cc" << II->getCallingConv(); break;
1851     }
1852
1853     if (PAL.getRetAttributes() != Attribute::None)
1854       Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1855
1856     // If possible, print out the short form of the invoke instruction. We can
1857     // only do this if the first argument is a pointer to a nonvararg function,
1858     // and if the return type is not a pointer to a function.
1859     //
1860     Out << ' ';
1861     if (!FTy->isVarArg() &&
1862         (!RetTy->isPointerTy() ||
1863          !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
1864       TypePrinter.print(RetTy, Out);
1865       Out << ' ';
1866       writeOperand(Operand, false);
1867     } else {
1868       writeOperand(Operand, true);
1869     }
1870     Out << '(';
1871     for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
1872       if (op)
1873         Out << ", ";
1874       writeParamOperand(II->getArgOperand(op), PAL.getParamAttributes(op + 1));
1875     }
1876
1877     Out << ')';
1878     if (PAL.getFnAttributes() != Attribute::None)
1879       Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1880
1881     Out << "\n          to ";
1882     writeOperand(II->getNormalDest(), true);
1883     Out << " unwind ";
1884     writeOperand(II->getUnwindDest(), true);
1885
1886   } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
1887     Out << ' ';
1888     TypePrinter.print(AI->getType()->getElementType(), Out);
1889     if (!AI->getArraySize() || AI->isArrayAllocation()) {
1890       Out << ", ";
1891       writeOperand(AI->getArraySize(), true);
1892     }
1893     if (AI->getAlignment()) {
1894       Out << ", align " << AI->getAlignment();
1895     }
1896   } else if (isa<CastInst>(I)) {
1897     if (Operand) {
1898       Out << ' ';
1899       writeOperand(Operand, true);   // Work with broken code
1900     }
1901     Out << " to ";
1902     TypePrinter.print(I.getType(), Out);
1903   } else if (isa<VAArgInst>(I)) {
1904     if (Operand) {
1905       Out << ' ';
1906       writeOperand(Operand, true);   // Work with broken code
1907     }
1908     Out << ", ";
1909     TypePrinter.print(I.getType(), Out);
1910   } else if (Operand) {   // Print the normal way.
1911
1912     // PrintAllTypes - Instructions who have operands of all the same type
1913     // omit the type from all but the first operand.  If the instruction has
1914     // different type operands (for example br), then they are all printed.
1915     bool PrintAllTypes = false;
1916     Type *TheType = Operand->getType();
1917
1918     // Select, Store and ShuffleVector always print all types.
1919     if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1920         || isa<ReturnInst>(I)) {
1921       PrintAllTypes = true;
1922     } else {
1923       for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1924         Operand = I.getOperand(i);
1925         // note that Operand shouldn't be null, but the test helps make dump()
1926         // more tolerant of malformed IR
1927         if (Operand && Operand->getType() != TheType) {
1928           PrintAllTypes = true;    // We have differing types!  Print them all!
1929           break;
1930         }
1931       }
1932     }
1933
1934     if (!PrintAllTypes) {
1935       Out << ' ';
1936       TypePrinter.print(TheType, Out);
1937     }
1938
1939     Out << ' ';
1940     for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1941       if (i) Out << ", ";
1942       writeOperand(I.getOperand(i), PrintAllTypes);
1943     }
1944   }
1945
1946   // Print atomic ordering/alignment for memory operations
1947   if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
1948     if (LI->isAtomic())
1949       writeAtomic(LI->getOrdering(), LI->getSynchScope());
1950     if (LI->getAlignment())
1951       Out << ", align " << LI->getAlignment();
1952   } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
1953     if (SI->isAtomic())
1954       writeAtomic(SI->getOrdering(), SI->getSynchScope());
1955     if (SI->getAlignment())
1956       Out << ", align " << SI->getAlignment();
1957   } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
1958     writeAtomic(CXI->getOrdering(), CXI->getSynchScope());
1959   } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
1960     writeAtomic(RMWI->getOrdering(), RMWI->getSynchScope());
1961   } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
1962     writeAtomic(FI->getOrdering(), FI->getSynchScope());
1963   }
1964
1965   // Print Metadata info.
1966   SmallVector<std::pair<unsigned, MDNode*>, 4> InstMD;
1967   I.getAllMetadata(InstMD);
1968   if (!InstMD.empty()) {
1969     SmallVector<StringRef, 8> MDNames;
1970     I.getType()->getContext().getMDKindNames(MDNames);
1971     for (unsigned i = 0, e = InstMD.size(); i != e; ++i) {
1972       unsigned Kind = InstMD[i].first;
1973        if (Kind < MDNames.size()) {
1974          Out << ", !" << MDNames[Kind];
1975       } else {
1976         Out << ", !<unknown kind #" << Kind << ">";
1977       }
1978       Out << ' ';
1979       WriteAsOperandInternal(Out, InstMD[i].second, &TypePrinter, &Machine,
1980                              TheModule);
1981     }
1982   }
1983   printInfoComment(I);
1984 }
1985
1986 static void WriteMDNodeComment(const MDNode *Node,
1987                                formatted_raw_ostream &Out) {
1988   if (Node->getNumOperands() < 1)
1989     return;
1990   ConstantInt *CI = dyn_cast_or_null<ConstantInt>(Node->getOperand(0));
1991   if (!CI) return;
1992   APInt Val = CI->getValue();
1993   APInt Tag = Val & ~APInt(Val.getBitWidth(), LLVMDebugVersionMask);
1994   if (Val.ult(LLVMDebugVersion))
1995     return;
1996
1997   Out.PadToColumn(50);
1998   if (Tag == dwarf::DW_TAG_user_base)
1999     Out << "; [ DW_TAG_user_base ]";
2000   else if (Tag.isIntN(32)) {
2001     if (const char *TagName = dwarf::TagString(Tag.getZExtValue()))
2002       Out << "; [ " << TagName << " ]";
2003   }
2004 }
2005
2006 void AssemblyWriter::writeAllMDNodes() {
2007   SmallVector<const MDNode *, 16> Nodes;
2008   Nodes.resize(Machine.mdn_size());
2009   for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
2010        I != E; ++I)
2011     Nodes[I->second] = cast<MDNode>(I->first);
2012
2013   for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
2014     Out << '!' << i << " = metadata ";
2015     printMDNodeBody(Nodes[i]);
2016   }
2017 }
2018
2019 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
2020   WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
2021   WriteMDNodeComment(Node, Out);
2022   Out << "\n";
2023 }
2024
2025 //===----------------------------------------------------------------------===//
2026 //                       External Interface declarations
2027 //===----------------------------------------------------------------------===//
2028
2029 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2030   SlotTracker SlotTable(this);
2031   formatted_raw_ostream OS(ROS);
2032   AssemblyWriter W(OS, SlotTable, this, AAW);
2033   W.printModule(this);
2034 }
2035
2036 void NamedMDNode::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2037   SlotTracker SlotTable(getParent());
2038   formatted_raw_ostream OS(ROS);
2039   AssemblyWriter W(OS, SlotTable, getParent(), AAW);
2040   W.printNamedMDNode(this);
2041 }
2042
2043 void Type::print(raw_ostream &OS) const {
2044   if (this == 0) {
2045     OS << "<null Type>";
2046     return;
2047   }
2048   TypePrinting TP;
2049   TP.print(const_cast<Type*>(this), OS);
2050
2051   // If the type is a named struct type, print the body as well.
2052   if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
2053     if (!STy->isLiteral()) {
2054       OS << " = type ";
2055       TP.printStructBody(STy, OS);
2056     }
2057 }
2058
2059 void Value::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2060   if (this == 0) {
2061     ROS << "printing a <null> value\n";
2062     return;
2063   }
2064   formatted_raw_ostream OS(ROS);
2065   if (const Instruction *I = dyn_cast<Instruction>(this)) {
2066     const Function *F = I->getParent() ? I->getParent()->getParent() : 0;
2067     SlotTracker SlotTable(F);
2068     AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), AAW);
2069     W.printInstruction(*I);
2070   } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
2071     SlotTracker SlotTable(BB->getParent());
2072     AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), AAW);
2073     W.printBasicBlock(BB);
2074   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
2075     SlotTracker SlotTable(GV->getParent());
2076     AssemblyWriter W(OS, SlotTable, GV->getParent(), AAW);
2077     if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
2078       W.printGlobal(V);
2079     else if (const Function *F = dyn_cast<Function>(GV))
2080       W.printFunction(F);
2081     else
2082       W.printAlias(cast<GlobalAlias>(GV));
2083   } else if (const MDNode *N = dyn_cast<MDNode>(this)) {
2084     const Function *F = N->getFunction();
2085     SlotTracker SlotTable(F);
2086     AssemblyWriter W(OS, SlotTable, F ? F->getParent() : 0, AAW);
2087     W.printMDNodeBody(N);
2088   } else if (const Constant *C = dyn_cast<Constant>(this)) {
2089     TypePrinting TypePrinter;
2090     TypePrinter.print(C->getType(), OS);
2091     OS << ' ';
2092     WriteConstantInternal(OS, C, TypePrinter, 0, 0);
2093   } else if (isa<InlineAsm>(this) || isa<MDString>(this) ||
2094              isa<Argument>(this)) {
2095     WriteAsOperand(OS, this, true, 0);
2096   } else {
2097     // Otherwise we don't know what it is. Call the virtual function to
2098     // allow a subclass to print itself.
2099     printCustom(OS);
2100   }
2101 }
2102
2103 // Value::printCustom - subclasses should override this to implement printing.
2104 void Value::printCustom(raw_ostream &OS) const {
2105   llvm_unreachable("Unknown value to print out!");
2106 }
2107
2108 // Value::dump - allow easy printing of Values from the debugger.
2109 void Value::dump() const { print(dbgs()); dbgs() << '\n'; }
2110
2111 // Type::dump - allow easy printing of Types from the debugger.
2112 void Type::dump() const { print(dbgs()); }
2113
2114 // Module::dump() - Allow printing of Modules from the debugger.
2115 void Module::dump() const { print(dbgs(), 0); }
2116
2117 // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
2118 void NamedMDNode::dump() const { print(dbgs(), 0); }