Move lib/Analysis/DebugInfo.cpp to lib/VMCore/DebugInfo.cpp and
[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::IEEEsingle ||
712         &CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble) {
713       // We would like to output the FP constant value in exponential notation,
714       // but we cannot do this if doing so will lose precision.  Check here to
715       // make sure that we only output it in exponential format if we can parse
716       // the value back and get the same value.
717       //
718       bool ignored;
719       bool isHalf = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEhalf;
720       bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
721       bool isInf = CFP->getValueAPF().isInfinity();
722       bool isNaN = CFP->getValueAPF().isNaN();
723       if (!isHalf && !isInf && !isNaN) {
724         double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
725                                 CFP->getValueAPF().convertToFloat();
726         SmallString<128> StrVal;
727         raw_svector_ostream(StrVal) << Val;
728
729         // Check to make sure that the stringized number is not some string like
730         // "Inf" or NaN, that atof will accept, but the lexer will not.  Check
731         // that the string matches the "[-+]?[0-9]" regex.
732         //
733         if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
734             ((StrVal[0] == '-' || StrVal[0] == '+') &&
735              (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
736           // Reparse stringized version!
737           if (APFloat(APFloat::IEEEdouble, StrVal).convertToDouble() == Val) {
738             Out << StrVal.str();
739             return;
740           }
741         }
742       }
743       // Otherwise we could not reparse it to exactly the same value, so we must
744       // output the string in hexadecimal format!  Note that loading and storing
745       // floating point types changes the bits of NaNs on some hosts, notably
746       // x86, so we must not use these types.
747       assert(sizeof(double) == sizeof(uint64_t) &&
748              "assuming that double is 64 bits!");
749       char Buffer[40];
750       APFloat apf = CFP->getValueAPF();
751       // Halves and floats are represented in ASCII IR as double, convert.
752       if (!isDouble)
753         apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
754                           &ignored);
755       Out << "0x" <<
756               utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()),
757                             Buffer+40);
758       return;
759     }
760
761     // Either half, or some form of long double.
762     // These appear as a magic letter identifying the type, then a
763     // fixed number of hex digits.
764     Out << "0x";
765     // Bit position, in the current word, of the next nibble to print.
766     int shiftcount;
767
768     if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
769       Out << 'K';
770       // api needed to prevent premature destruction
771       APInt api = CFP->getValueAPF().bitcastToAPInt();
772       const uint64_t* p = api.getRawData();
773       uint64_t word = p[1];
774       shiftcount = 12;
775       int width = api.getBitWidth();
776       for (int j=0; j<width; j+=4, shiftcount-=4) {
777         unsigned int nibble = (word>>shiftcount) & 15;
778         if (nibble < 10)
779           Out << (unsigned char)(nibble + '0');
780         else
781           Out << (unsigned char)(nibble - 10 + 'A');
782         if (shiftcount == 0 && j+4 < width) {
783           word = *p;
784           shiftcount = 64;
785           if (width-j-4 < 64)
786             shiftcount = width-j-4;
787         }
788       }
789       return;
790     } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad) {
791       shiftcount = 60;
792       Out << 'L';
793     } else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble) {
794       shiftcount = 60;
795       Out << 'M';
796     } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEhalf) {
797       shiftcount = 12;
798       Out << 'H';
799     } else
800       llvm_unreachable("Unsupported floating point type");
801     // api needed to prevent premature destruction
802     APInt api = CFP->getValueAPF().bitcastToAPInt();
803     const uint64_t* p = api.getRawData();
804     uint64_t word = *p;
805     int width = api.getBitWidth();
806     for (int j=0; j<width; j+=4, shiftcount-=4) {
807       unsigned int nibble = (word>>shiftcount) & 15;
808       if (nibble < 10)
809         Out << (unsigned char)(nibble + '0');
810       else
811         Out << (unsigned char)(nibble - 10 + 'A');
812       if (shiftcount == 0 && j+4 < width) {
813         word = *(++p);
814         shiftcount = 64;
815         if (width-j-4 < 64)
816           shiftcount = width-j-4;
817       }
818     }
819     return;
820   }
821
822   if (isa<ConstantAggregateZero>(CV)) {
823     Out << "zeroinitializer";
824     return;
825   }
826
827   if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
828     Out << "blockaddress(";
829     WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine,
830                            Context);
831     Out << ", ";
832     WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine,
833                            Context);
834     Out << ")";
835     return;
836   }
837
838   if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
839     Type *ETy = CA->getType()->getElementType();
840     Out << '[';
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     Out << ']';
854     return;
855   }
856   
857   if (const ConstantDataArray *CA = dyn_cast<ConstantDataArray>(CV)) {
858     // As a special case, print the array as a string if it is an array of
859     // i8 with ConstantInt values.
860     if (CA->isString()) {
861       Out << "c\"";
862       PrintEscapedString(CA->getAsString(), Out);
863       Out << '"';
864       return;
865     }
866
867     Type *ETy = CA->getType()->getElementType();
868     Out << '[';
869     TypePrinter.print(ETy, Out);
870     Out << ' ';
871     WriteAsOperandInternal(Out, CA->getElementAsConstant(0),
872                            &TypePrinter, Machine,
873                            Context);
874     for (unsigned i = 1, e = CA->getNumElements(); i != e; ++i) {
875       Out << ", ";
876       TypePrinter.print(ETy, Out);
877       Out << ' ';
878       WriteAsOperandInternal(Out, CA->getElementAsConstant(i), &TypePrinter,
879                              Machine, Context);
880     }
881     Out << ']';
882     return;
883   }
884
885
886   if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
887     if (CS->getType()->isPacked())
888       Out << '<';
889     Out << '{';
890     unsigned N = CS->getNumOperands();
891     if (N) {
892       Out << ' ';
893       TypePrinter.print(CS->getOperand(0)->getType(), Out);
894       Out << ' ';
895
896       WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine,
897                              Context);
898
899       for (unsigned i = 1; i < N; i++) {
900         Out << ", ";
901         TypePrinter.print(CS->getOperand(i)->getType(), Out);
902         Out << ' ';
903
904         WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine,
905                                Context);
906       }
907       Out << ' ';
908     }
909
910     Out << '}';
911     if (CS->getType()->isPacked())
912       Out << '>';
913     return;
914   }
915
916   if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) {
917     Type *ETy = CV->getType()->getVectorElementType();
918     Out << '<';
919     TypePrinter.print(ETy, Out);
920     Out << ' ';
921     WriteAsOperandInternal(Out, CV->getAggregateElement(0U), &TypePrinter,
922                            Machine, Context);
923     for (unsigned i = 1, e = CV->getType()->getVectorNumElements(); i != e;++i){
924       Out << ", ";
925       TypePrinter.print(ETy, Out);
926       Out << ' ';
927       WriteAsOperandInternal(Out, CV->getAggregateElement(i), &TypePrinter,
928                              Machine, Context);
929     }
930     Out << '>';
931     return;
932   }
933
934   if (isa<ConstantPointerNull>(CV)) {
935     Out << "null";
936     return;
937   }
938
939   if (isa<UndefValue>(CV)) {
940     Out << "undef";
941     return;
942   }
943
944   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
945     Out << CE->getOpcodeName();
946     WriteOptimizationInfo(Out, CE);
947     if (CE->isCompare())
948       Out << ' ' << getPredicateText(CE->getPredicate());
949     Out << " (";
950
951     for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
952       TypePrinter.print((*OI)->getType(), Out);
953       Out << ' ';
954       WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context);
955       if (OI+1 != CE->op_end())
956         Out << ", ";
957     }
958
959     if (CE->hasIndices()) {
960       ArrayRef<unsigned> Indices = CE->getIndices();
961       for (unsigned i = 0, e = Indices.size(); i != e; ++i)
962         Out << ", " << Indices[i];
963     }
964
965     if (CE->isCast()) {
966       Out << " to ";
967       TypePrinter.print(CE->getType(), Out);
968     }
969
970     Out << ')';
971     return;
972   }
973
974   Out << "<placeholder or erroneous Constant>";
975 }
976
977 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
978                                     TypePrinting *TypePrinter,
979                                     SlotTracker *Machine,
980                                     const Module *Context) {
981   Out << "!{";
982   for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
983     const Value *V = Node->getOperand(mi);
984     if (V == 0)
985       Out << "null";
986     else {
987       TypePrinter->print(V->getType(), Out);
988       Out << ' ';
989       WriteAsOperandInternal(Out, Node->getOperand(mi),
990                              TypePrinter, Machine, Context);
991     }
992     if (mi + 1 != me)
993       Out << ", ";
994   }
995
996   Out << "}";
997 }
998
999
1000 /// WriteAsOperand - Write the name of the specified value out to the specified
1001 /// ostream.  This can be useful when you just want to print int %reg126, not
1002 /// the whole instruction that generated it.
1003 ///
1004 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1005                                    TypePrinting *TypePrinter,
1006                                    SlotTracker *Machine,
1007                                    const Module *Context) {
1008   if (V->hasName()) {
1009     PrintLLVMName(Out, V);
1010     return;
1011   }
1012
1013   const Constant *CV = dyn_cast<Constant>(V);
1014   if (CV && !isa<GlobalValue>(CV)) {
1015     assert(TypePrinter && "Constants require TypePrinting!");
1016     WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context);
1017     return;
1018   }
1019
1020   if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1021     Out << "asm ";
1022     if (IA->hasSideEffects())
1023       Out << "sideeffect ";
1024     if (IA->isAlignStack())
1025       Out << "alignstack ";
1026     Out << '"';
1027     PrintEscapedString(IA->getAsmString(), Out);
1028     Out << "\", \"";
1029     PrintEscapedString(IA->getConstraintString(), Out);
1030     Out << '"';
1031     return;
1032   }
1033
1034   if (const MDNode *N = dyn_cast<MDNode>(V)) {
1035     if (N->isFunctionLocal()) {
1036       // Print metadata inline, not via slot reference number.
1037       WriteMDNodeBodyInternal(Out, N, TypePrinter, Machine, Context);
1038       return;
1039     }
1040
1041     if (!Machine) {
1042       if (N->isFunctionLocal())
1043         Machine = new SlotTracker(N->getFunction());
1044       else
1045         Machine = new SlotTracker(Context);
1046     }
1047     int Slot = Machine->getMetadataSlot(N);
1048     if (Slot == -1)
1049       Out << "<badref>";
1050     else
1051       Out << '!' << Slot;
1052     return;
1053   }
1054
1055   if (const MDString *MDS = dyn_cast<MDString>(V)) {
1056     Out << "!\"";
1057     PrintEscapedString(MDS->getString(), Out);
1058     Out << '"';
1059     return;
1060   }
1061
1062   if (V->getValueID() == Value::PseudoSourceValueVal ||
1063       V->getValueID() == Value::FixedStackPseudoSourceValueVal) {
1064     V->print(Out);
1065     return;
1066   }
1067
1068   char Prefix = '%';
1069   int Slot;
1070   // If we have a SlotTracker, use it.
1071   if (Machine) {
1072     if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1073       Slot = Machine->getGlobalSlot(GV);
1074       Prefix = '@';
1075     } else {
1076       Slot = Machine->getLocalSlot(V);
1077
1078       // If the local value didn't succeed, then we may be referring to a value
1079       // from a different function.  Translate it, as this can happen when using
1080       // address of blocks.
1081       if (Slot == -1)
1082         if ((Machine = createSlotTracker(V))) {
1083           Slot = Machine->getLocalSlot(V);
1084           delete Machine;
1085         }
1086     }
1087   } else if ((Machine = createSlotTracker(V))) {
1088     // Otherwise, create one to get the # and then destroy it.
1089     if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1090       Slot = Machine->getGlobalSlot(GV);
1091       Prefix = '@';
1092     } else {
1093       Slot = Machine->getLocalSlot(V);
1094     }
1095     delete Machine;
1096     Machine = 0;
1097   } else {
1098     Slot = -1;
1099   }
1100
1101   if (Slot != -1)
1102     Out << Prefix << Slot;
1103   else
1104     Out << "<badref>";
1105 }
1106
1107 void llvm::WriteAsOperand(raw_ostream &Out, const Value *V,
1108                           bool PrintType, const Module *Context) {
1109
1110   // Fast path: Don't construct and populate a TypePrinting object if we
1111   // won't be needing any types printed.
1112   if (!PrintType &&
1113       ((!isa<Constant>(V) && !isa<MDNode>(V)) ||
1114        V->hasName() || isa<GlobalValue>(V))) {
1115     WriteAsOperandInternal(Out, V, 0, 0, Context);
1116     return;
1117   }
1118
1119   if (Context == 0) Context = getModuleFromVal(V);
1120
1121   TypePrinting TypePrinter;
1122   if (Context)
1123     TypePrinter.incorporateTypes(*Context);
1124   if (PrintType) {
1125     TypePrinter.print(V->getType(), Out);
1126     Out << ' ';
1127   }
1128
1129   WriteAsOperandInternal(Out, V, &TypePrinter, 0, Context);
1130 }
1131
1132 namespace {
1133
1134 class AssemblyWriter {
1135   formatted_raw_ostream &Out;
1136   SlotTracker &Machine;
1137   const Module *TheModule;
1138   TypePrinting TypePrinter;
1139   AssemblyAnnotationWriter *AnnotationWriter;
1140
1141 public:
1142   inline AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
1143                         const Module *M,
1144                         AssemblyAnnotationWriter *AAW)
1145     : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
1146     if (M)
1147       TypePrinter.incorporateTypes(*M);
1148   }
1149
1150   void printMDNodeBody(const MDNode *MD);
1151   void printNamedMDNode(const NamedMDNode *NMD);
1152
1153   void printModule(const Module *M);
1154
1155   void writeOperand(const Value *Op, bool PrintType);
1156   void writeParamOperand(const Value *Operand, Attributes Attrs);
1157   void writeAtomic(AtomicOrdering Ordering, SynchronizationScope SynchScope);
1158
1159   void writeAllMDNodes();
1160
1161   void printTypeIdentities();
1162   void printGlobal(const GlobalVariable *GV);
1163   void printAlias(const GlobalAlias *GV);
1164   void printFunction(const Function *F);
1165   void printArgument(const Argument *FA, Attributes Attrs);
1166   void printBasicBlock(const BasicBlock *BB);
1167   void printInstruction(const Instruction &I);
1168
1169 private:
1170   // printInfoComment - Print a little comment after the instruction indicating
1171   // which slot it occupies.
1172   void printInfoComment(const Value &V);
1173 };
1174 }  // end of anonymous namespace
1175
1176 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
1177   if (Operand == 0) {
1178     Out << "<null operand!>";
1179     return;
1180   }
1181   if (PrintType) {
1182     TypePrinter.print(Operand->getType(), Out);
1183     Out << ' ';
1184   }
1185   WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
1186 }
1187
1188 void AssemblyWriter::writeAtomic(AtomicOrdering Ordering,
1189                                  SynchronizationScope SynchScope) {
1190   if (Ordering == NotAtomic)
1191     return;
1192
1193   switch (SynchScope) {
1194   case SingleThread: Out << " singlethread"; break;
1195   case CrossThread: break;
1196   }
1197
1198   switch (Ordering) {
1199   default: Out << " <bad ordering " << int(Ordering) << ">"; break;
1200   case Unordered: Out << " unordered"; break;
1201   case Monotonic: Out << " monotonic"; break;
1202   case Acquire: Out << " acquire"; break;
1203   case Release: Out << " release"; break;
1204   case AcquireRelease: Out << " acq_rel"; break;
1205   case SequentiallyConsistent: Out << " seq_cst"; break;
1206   }
1207 }
1208
1209 void AssemblyWriter::writeParamOperand(const Value *Operand,
1210                                        Attributes Attrs) {
1211   if (Operand == 0) {
1212     Out << "<null operand!>";
1213     return;
1214   }
1215
1216   // Print the type
1217   TypePrinter.print(Operand->getType(), Out);
1218   // Print parameter attributes list
1219   if (Attrs != Attribute::None)
1220     Out << ' ' << Attribute::getAsString(Attrs);
1221   Out << ' ';
1222   // Print the operand
1223   WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
1224 }
1225
1226 void AssemblyWriter::printModule(const Module *M) {
1227   if (!M->getModuleIdentifier().empty() &&
1228       // Don't print the ID if it will start a new line (which would
1229       // require a comment char before it).
1230       M->getModuleIdentifier().find('\n') == std::string::npos)
1231     Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1232
1233   if (!M->getDataLayout().empty())
1234     Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
1235   if (!M->getTargetTriple().empty())
1236     Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1237
1238   if (!M->getModuleInlineAsm().empty()) {
1239     // Split the string into lines, to make it easier to read the .ll file.
1240     std::string Asm = M->getModuleInlineAsm();
1241     size_t CurPos = 0;
1242     size_t NewLine = Asm.find_first_of('\n', CurPos);
1243     Out << '\n';
1244     while (NewLine != std::string::npos) {
1245       // We found a newline, print the portion of the asm string from the
1246       // last newline up to this newline.
1247       Out << "module asm \"";
1248       PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1249                          Out);
1250       Out << "\"\n";
1251       CurPos = NewLine+1;
1252       NewLine = Asm.find_first_of('\n', CurPos);
1253     }
1254     std::string rest(Asm.begin()+CurPos, Asm.end());
1255     if (!rest.empty()) {
1256       Out << "module asm \"";
1257       PrintEscapedString(rest, Out);
1258       Out << "\"\n";
1259     }
1260   }
1261
1262   // Loop over the dependent libraries and emit them.
1263   Module::lib_iterator LI = M->lib_begin();
1264   Module::lib_iterator LE = M->lib_end();
1265   if (LI != LE) {
1266     Out << '\n';
1267     Out << "deplibs = [ ";
1268     while (LI != LE) {
1269       Out << '"' << *LI << '"';
1270       ++LI;
1271       if (LI != LE)
1272         Out << ", ";
1273     }
1274     Out << " ]";
1275   }
1276
1277   printTypeIdentities();
1278
1279   // Output all globals.
1280   if (!M->global_empty()) Out << '\n';
1281   for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1282        I != E; ++I)
1283     printGlobal(I);
1284
1285   // Output all aliases.
1286   if (!M->alias_empty()) Out << "\n";
1287   for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1288        I != E; ++I)
1289     printAlias(I);
1290
1291   // Output all of the functions.
1292   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1293     printFunction(I);
1294
1295   // Output named metadata.
1296   if (!M->named_metadata_empty()) Out << '\n';
1297
1298   for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
1299        E = M->named_metadata_end(); I != E; ++I)
1300     printNamedMDNode(I);
1301
1302   // Output metadata.
1303   if (!Machine.mdn_empty()) {
1304     Out << '\n';
1305     writeAllMDNodes();
1306   }
1307 }
1308
1309 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
1310   Out << '!';
1311   StringRef Name = NMD->getName();
1312   if (Name.empty()) {
1313     Out << "<empty name> ";
1314   } else {
1315     if (isalpha(Name[0]) || Name[0] == '-' || Name[0] == '$' ||
1316         Name[0] == '.' || Name[0] == '_')
1317       Out << Name[0];
1318     else
1319       Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F);
1320     for (unsigned i = 1, e = Name.size(); i != e; ++i) {
1321       unsigned char C = Name[i];
1322       if (isalnum(C) || C == '-' || C == '$' || C == '.' || C == '_')
1323         Out << C;
1324       else
1325         Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
1326     }
1327   }
1328   Out << " = !{";
1329   for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1330     if (i) Out << ", ";
1331     int Slot = Machine.getMetadataSlot(NMD->getOperand(i));
1332     if (Slot == -1)
1333       Out << "<badref>";
1334     else
1335       Out << '!' << Slot;
1336   }
1337   Out << "}\n";
1338 }
1339
1340
1341 static void PrintLinkage(GlobalValue::LinkageTypes LT,
1342                          formatted_raw_ostream &Out) {
1343   switch (LT) {
1344   case GlobalValue::ExternalLinkage: break;
1345   case GlobalValue::PrivateLinkage:       Out << "private ";        break;
1346   case GlobalValue::LinkerPrivateLinkage: Out << "linker_private "; break;
1347   case GlobalValue::LinkerPrivateWeakLinkage:
1348     Out << "linker_private_weak ";
1349     break;
1350   case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
1351     Out << "linker_private_weak_def_auto ";
1352     break;
1353   case GlobalValue::InternalLinkage:      Out << "internal ";       break;
1354   case GlobalValue::LinkOnceAnyLinkage:   Out << "linkonce ";       break;
1355   case GlobalValue::LinkOnceODRLinkage:   Out << "linkonce_odr ";   break;
1356   case GlobalValue::WeakAnyLinkage:       Out << "weak ";           break;
1357   case GlobalValue::WeakODRLinkage:       Out << "weak_odr ";       break;
1358   case GlobalValue::CommonLinkage:        Out << "common ";         break;
1359   case GlobalValue::AppendingLinkage:     Out << "appending ";      break;
1360   case GlobalValue::DLLImportLinkage:     Out << "dllimport ";      break;
1361   case GlobalValue::DLLExportLinkage:     Out << "dllexport ";      break;
1362   case GlobalValue::ExternalWeakLinkage:  Out << "extern_weak ";    break;
1363   case GlobalValue::AvailableExternallyLinkage:
1364     Out << "available_externally ";
1365     break;
1366   }
1367 }
1368
1369
1370 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1371                             formatted_raw_ostream &Out) {
1372   switch (Vis) {
1373   case GlobalValue::DefaultVisibility: break;
1374   case GlobalValue::HiddenVisibility:    Out << "hidden "; break;
1375   case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1376   }
1377 }
1378
1379 static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM,
1380                                   formatted_raw_ostream &Out) {
1381   switch (TLM) {
1382     case GlobalVariable::NotThreadLocal:
1383       break;
1384     case GlobalVariable::GeneralDynamicTLSModel:
1385       Out << "thread_local ";
1386       break;
1387     case GlobalVariable::LocalDynamicTLSModel:
1388       Out << "thread_local(localdynamic) ";
1389       break;
1390     case GlobalVariable::InitialExecTLSModel:
1391       Out << "thread_local(initialexec) ";
1392       break;
1393     case GlobalVariable::LocalExecTLSModel:
1394       Out << "thread_local(localexec) ";
1395       break;
1396   }
1397 }
1398
1399 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1400   if (GV->isMaterializable())
1401     Out << "; Materializable\n";
1402
1403   WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent());
1404   Out << " = ";
1405
1406   if (!GV->hasInitializer() && GV->hasExternalLinkage())
1407     Out << "external ";
1408
1409   PrintLinkage(GV->getLinkage(), Out);
1410   PrintVisibility(GV->getVisibility(), Out);
1411   PrintThreadLocalModel(GV->getThreadLocalMode(), Out);
1412
1413   if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1414     Out << "addrspace(" << AddressSpace << ") ";
1415   if (GV->hasUnnamedAddr()) Out << "unnamed_addr ";
1416   Out << (GV->isConstant() ? "constant " : "global ");
1417   TypePrinter.print(GV->getType()->getElementType(), Out);
1418
1419   if (GV->hasInitializer()) {
1420     Out << ' ';
1421     writeOperand(GV->getInitializer(), false);
1422   }
1423
1424   if (GV->hasSection()) {
1425     Out << ", section \"";
1426     PrintEscapedString(GV->getSection(), Out);
1427     Out << '"';
1428   }
1429   if (GV->getAlignment())
1430     Out << ", align " << GV->getAlignment();
1431
1432   printInfoComment(*GV);
1433   Out << '\n';
1434 }
1435
1436 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1437   if (GA->isMaterializable())
1438     Out << "; Materializable\n";
1439
1440   // Don't crash when dumping partially built GA
1441   if (!GA->hasName())
1442     Out << "<<nameless>> = ";
1443   else {
1444     PrintLLVMName(Out, GA);
1445     Out << " = ";
1446   }
1447   PrintVisibility(GA->getVisibility(), Out);
1448
1449   Out << "alias ";
1450
1451   PrintLinkage(GA->getLinkage(), Out);
1452
1453   const Constant *Aliasee = GA->getAliasee();
1454
1455   if (Aliasee == 0) {
1456     TypePrinter.print(GA->getType(), Out);
1457     Out << " <<NULL ALIASEE>>";
1458   } else {
1459     writeOperand(Aliasee, !isa<ConstantExpr>(Aliasee));
1460   }
1461
1462   printInfoComment(*GA);
1463   Out << '\n';
1464 }
1465
1466 void AssemblyWriter::printTypeIdentities() {
1467   if (TypePrinter.NumberedTypes.empty() &&
1468       TypePrinter.NamedTypes.empty())
1469     return;
1470
1471   Out << '\n';
1472
1473   // We know all the numbers that each type is used and we know that it is a
1474   // dense assignment.  Convert the map to an index table.
1475   std::vector<StructType*> NumberedTypes(TypePrinter.NumberedTypes.size());
1476   for (DenseMap<StructType*, unsigned>::iterator I =
1477        TypePrinter.NumberedTypes.begin(), E = TypePrinter.NumberedTypes.end();
1478        I != E; ++I) {
1479     assert(I->second < NumberedTypes.size() && "Didn't get a dense numbering?");
1480     NumberedTypes[I->second] = I->first;
1481   }
1482
1483   // Emit all numbered types.
1484   for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
1485     Out << '%' << i << " = type ";
1486
1487     // Make sure we print out at least one level of the type structure, so
1488     // that we do not get %2 = type %2
1489     TypePrinter.printStructBody(NumberedTypes[i], Out);
1490     Out << '\n';
1491   }
1492
1493   for (unsigned i = 0, e = TypePrinter.NamedTypes.size(); i != e; ++i) {
1494     PrintLLVMName(Out, TypePrinter.NamedTypes[i]->getName(), LocalPrefix);
1495     Out << " = type ";
1496
1497     // Make sure we print out at least one level of the type structure, so
1498     // that we do not get %FILE = type %FILE
1499     TypePrinter.printStructBody(TypePrinter.NamedTypes[i], Out);
1500     Out << '\n';
1501   }
1502 }
1503
1504 /// printFunction - Print all aspects of a function.
1505 ///
1506 void AssemblyWriter::printFunction(const Function *F) {
1507   // Print out the return type and name.
1508   Out << '\n';
1509
1510   if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1511
1512   if (F->isMaterializable())
1513     Out << "; Materializable\n";
1514
1515   if (F->isDeclaration())
1516     Out << "declare ";
1517   else
1518     Out << "define ";
1519
1520   PrintLinkage(F->getLinkage(), Out);
1521   PrintVisibility(F->getVisibility(), Out);
1522
1523   // Print the calling convention.
1524   switch (F->getCallingConv()) {
1525   case CallingConv::C: break;   // default
1526   case CallingConv::Fast:         Out << "fastcc "; break;
1527   case CallingConv::Cold:         Out << "coldcc "; break;
1528   case CallingConv::X86_StdCall:  Out << "x86_stdcallcc "; break;
1529   case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1530   case CallingConv::X86_ThisCall: Out << "x86_thiscallcc "; break;
1531   case CallingConv::ARM_APCS:     Out << "arm_apcscc "; break;
1532   case CallingConv::ARM_AAPCS:    Out << "arm_aapcscc "; break;
1533   case CallingConv::ARM_AAPCS_VFP:Out << "arm_aapcs_vfpcc "; break;
1534   case CallingConv::MSP430_INTR:  Out << "msp430_intrcc "; break;
1535   case CallingConv::PTX_Kernel:   Out << "ptx_kernel "; break;
1536   case CallingConv::PTX_Device:   Out << "ptx_device "; break;
1537   default: Out << "cc" << F->getCallingConv() << " "; break;
1538   }
1539
1540   FunctionType *FT = F->getFunctionType();
1541   const AttrListPtr &Attrs = F->getAttributes();
1542   Attributes RetAttrs = Attrs.getRetAttributes();
1543   if (RetAttrs != Attribute::None)
1544     Out <<  Attribute::getAsString(Attrs.getRetAttributes()) << ' ';
1545   TypePrinter.print(F->getReturnType(), Out);
1546   Out << ' ';
1547   WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
1548   Out << '(';
1549   Machine.incorporateFunction(F);
1550
1551   // Loop over the arguments, printing them...
1552
1553   unsigned Idx = 1;
1554   if (!F->isDeclaration()) {
1555     // If this isn't a declaration, print the argument names as well.
1556     for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1557          I != E; ++I) {
1558       // Insert commas as we go... the first arg doesn't get a comma
1559       if (I != F->arg_begin()) Out << ", ";
1560       printArgument(I, Attrs.getParamAttributes(Idx));
1561       Idx++;
1562     }
1563   } else {
1564     // Otherwise, print the types from the function type.
1565     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1566       // Insert commas as we go... the first arg doesn't get a comma
1567       if (i) Out << ", ";
1568
1569       // Output type...
1570       TypePrinter.print(FT->getParamType(i), Out);
1571
1572       Attributes ArgAttrs = Attrs.getParamAttributes(i+1);
1573       if (ArgAttrs != Attribute::None)
1574         Out << ' ' << Attribute::getAsString(ArgAttrs);
1575     }
1576   }
1577
1578   // Finish printing arguments...
1579   if (FT->isVarArg()) {
1580     if (FT->getNumParams()) Out << ", ";
1581     Out << "...";  // Output varargs portion of signature!
1582   }
1583   Out << ')';
1584   if (F->hasUnnamedAddr())
1585     Out << " unnamed_addr";
1586   Attributes FnAttrs = Attrs.getFnAttributes();
1587   if (FnAttrs != Attribute::None)
1588     Out << ' ' << Attribute::getAsString(Attrs.getFnAttributes());
1589   if (F->hasSection()) {
1590     Out << " section \"";
1591     PrintEscapedString(F->getSection(), Out);
1592     Out << '"';
1593   }
1594   if (F->getAlignment())
1595     Out << " align " << F->getAlignment();
1596   if (F->hasGC())
1597     Out << " gc \"" << F->getGC() << '"';
1598   if (F->isDeclaration()) {
1599     Out << '\n';
1600   } else {
1601     Out << " {";
1602     // Output all of the function's basic blocks.
1603     for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1604       printBasicBlock(I);
1605
1606     Out << "}\n";
1607   }
1608
1609   Machine.purgeFunction();
1610 }
1611
1612 /// printArgument - This member is called for every argument that is passed into
1613 /// the function.  Simply print it out
1614 ///
1615 void AssemblyWriter::printArgument(const Argument *Arg,
1616                                    Attributes Attrs) {
1617   // Output type...
1618   TypePrinter.print(Arg->getType(), Out);
1619
1620   // Output parameter attributes list
1621   if (Attrs != Attribute::None)
1622     Out << ' ' << Attribute::getAsString(Attrs);
1623
1624   // Output name, if available...
1625   if (Arg->hasName()) {
1626     Out << ' ';
1627     PrintLLVMName(Out, Arg);
1628   }
1629 }
1630
1631 /// printBasicBlock - This member is called for each basic block in a method.
1632 ///
1633 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1634   if (BB->hasName()) {              // Print out the label if it exists...
1635     Out << "\n";
1636     PrintLLVMName(Out, BB->getName(), LabelPrefix);
1637     Out << ':';
1638   } else if (!BB->use_empty()) {      // Don't print block # of no uses...
1639     Out << "\n; <label>:";
1640     int Slot = Machine.getLocalSlot(BB);
1641     if (Slot != -1)
1642       Out << Slot;
1643     else
1644       Out << "<badref>";
1645   }
1646
1647   if (BB->getParent() == 0) {
1648     Out.PadToColumn(50);
1649     Out << "; Error: Block without parent!";
1650   } else if (BB != &BB->getParent()->getEntryBlock()) {  // Not the entry block?
1651     // Output predecessors for the block.
1652     Out.PadToColumn(50);
1653     Out << ";";
1654     const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1655
1656     if (PI == PE) {
1657       Out << " No predecessors!";
1658     } else {
1659       Out << " preds = ";
1660       writeOperand(*PI, false);
1661       for (++PI; PI != PE; ++PI) {
1662         Out << ", ";
1663         writeOperand(*PI, false);
1664       }
1665     }
1666   }
1667
1668   Out << "\n";
1669
1670   if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1671
1672   // Output all of the instructions in the basic block...
1673   for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1674     printInstruction(*I);
1675     Out << '\n';
1676   }
1677
1678   if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1679 }
1680
1681 /// printInfoComment - Print a little comment after the instruction indicating
1682 /// which slot it occupies.
1683 ///
1684 void AssemblyWriter::printInfoComment(const Value &V) {
1685   if (AnnotationWriter) {
1686     AnnotationWriter->printInfoComment(V, Out);
1687     return;
1688   }
1689 }
1690
1691 // This member is called for each Instruction in a function..
1692 void AssemblyWriter::printInstruction(const Instruction &I) {
1693   if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1694
1695   // Print out indentation for an instruction.
1696   Out << "  ";
1697
1698   // Print out name if it exists...
1699   if (I.hasName()) {
1700     PrintLLVMName(Out, &I);
1701     Out << " = ";
1702   } else if (!I.getType()->isVoidTy()) {
1703     // Print out the def slot taken.
1704     int SlotNum = Machine.getLocalSlot(&I);
1705     if (SlotNum == -1)
1706       Out << "<badref> = ";
1707     else
1708       Out << '%' << SlotNum << " = ";
1709   }
1710
1711   if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall())
1712     Out << "tail ";
1713
1714   // Print out the opcode...
1715   Out << I.getOpcodeName();
1716
1717   // If this is an atomic load or store, print out the atomic marker.
1718   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isAtomic()) ||
1719       (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
1720     Out << " atomic";
1721
1722   // If this is a volatile operation, print out the volatile marker.
1723   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isVolatile()) ||
1724       (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
1725       (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
1726       (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
1727     Out << " volatile";
1728
1729   // Print out optimization information.
1730   WriteOptimizationInfo(Out, &I);
1731
1732   // Print out the compare instruction predicates
1733   if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1734     Out << ' ' << getPredicateText(CI->getPredicate());
1735
1736   // Print out the atomicrmw operation
1737   if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
1738     writeAtomicRMWOperation(Out, RMWI->getOperation());
1739
1740   // Print out the type of the operands...
1741   const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1742
1743   // Special case conditional branches to swizzle the condition out to the front
1744   if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
1745     BranchInst &BI(cast<BranchInst>(I));
1746     Out << ' ';
1747     writeOperand(BI.getCondition(), true);
1748     Out << ", ";
1749     writeOperand(BI.getSuccessor(0), true);
1750     Out << ", ";
1751     writeOperand(BI.getSuccessor(1), true);
1752
1753   } else if (isa<SwitchInst>(I)) {
1754     SwitchInst& SI(cast<SwitchInst>(I));
1755     // Special case switch instruction to get formatting nice and correct.
1756     Out << ' ';
1757     writeOperand(SI.getCondition(), true);
1758     Out << ", ";
1759     writeOperand(SI.getDefaultDest(), true);
1760     Out << " [";
1761     for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end();
1762          i != e; ++i) {
1763       Out << "\n    ";
1764       writeOperand(i.getCaseValue(), true);
1765       Out << ", ";
1766       writeOperand(i.getCaseSuccessor(), true);
1767     }
1768     Out << "\n  ]";
1769   } else if (isa<IndirectBrInst>(I)) {
1770     // Special case indirectbr instruction to get formatting nice and correct.
1771     Out << ' ';
1772     writeOperand(Operand, true);
1773     Out << ", [";
1774
1775     for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1776       if (i != 1)
1777         Out << ", ";
1778       writeOperand(I.getOperand(i), true);
1779     }
1780     Out << ']';
1781   } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
1782     Out << ' ';
1783     TypePrinter.print(I.getType(), Out);
1784     Out << ' ';
1785
1786     for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
1787       if (op) Out << ", ";
1788       Out << "[ ";
1789       writeOperand(PN->getIncomingValue(op), false); Out << ", ";
1790       writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
1791     }
1792   } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1793     Out << ' ';
1794     writeOperand(I.getOperand(0), true);
1795     for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1796       Out << ", " << *i;
1797   } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1798     Out << ' ';
1799     writeOperand(I.getOperand(0), true); Out << ", ";
1800     writeOperand(I.getOperand(1), true);
1801     for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1802       Out << ", " << *i;
1803   } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
1804     Out << ' ';
1805     TypePrinter.print(I.getType(), Out);
1806     Out << " personality ";
1807     writeOperand(I.getOperand(0), true); Out << '\n';
1808
1809     if (LPI->isCleanup())
1810       Out << "          cleanup";
1811
1812     for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
1813       if (i != 0 || LPI->isCleanup()) Out << "\n";
1814       if (LPI->isCatch(i))
1815         Out << "          catch ";
1816       else
1817         Out << "          filter ";
1818
1819       writeOperand(LPI->getClause(i), true);
1820     }
1821   } else if (isa<ReturnInst>(I) && !Operand) {
1822     Out << " void";
1823   } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1824     // Print the calling convention being used.
1825     switch (CI->getCallingConv()) {
1826     case CallingConv::C: break;   // default
1827     case CallingConv::Fast:  Out << " fastcc"; break;
1828     case CallingConv::Cold:  Out << " coldcc"; break;
1829     case CallingConv::X86_StdCall:  Out << " x86_stdcallcc"; break;
1830     case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1831     case CallingConv::X86_ThisCall: Out << " x86_thiscallcc"; break;
1832     case CallingConv::ARM_APCS:     Out << " arm_apcscc "; break;
1833     case CallingConv::ARM_AAPCS:    Out << " arm_aapcscc "; break;
1834     case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1835     case CallingConv::MSP430_INTR:  Out << " msp430_intrcc "; break;
1836     case CallingConv::PTX_Kernel:   Out << " ptx_kernel"; break;
1837     case CallingConv::PTX_Device:   Out << " ptx_device"; break;
1838     default: Out << " cc" << CI->getCallingConv(); break;
1839     }
1840
1841     Operand = CI->getCalledValue();
1842     PointerType *PTy = cast<PointerType>(Operand->getType());
1843     FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1844     Type *RetTy = FTy->getReturnType();
1845     const AttrListPtr &PAL = CI->getAttributes();
1846
1847     if (PAL.getRetAttributes() != Attribute::None)
1848       Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1849
1850     // If possible, print out the short form of the call instruction.  We can
1851     // only do this if the first argument is a pointer to a nonvararg function,
1852     // and if the return type is not a pointer to a function.
1853     //
1854     Out << ' ';
1855     if (!FTy->isVarArg() &&
1856         (!RetTy->isPointerTy() ||
1857          !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
1858       TypePrinter.print(RetTy, Out);
1859       Out << ' ';
1860       writeOperand(Operand, false);
1861     } else {
1862       writeOperand(Operand, true);
1863     }
1864     Out << '(';
1865     for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
1866       if (op > 0)
1867         Out << ", ";
1868       writeParamOperand(CI->getArgOperand(op), PAL.getParamAttributes(op + 1));
1869     }
1870     Out << ')';
1871     if (PAL.getFnAttributes() != Attribute::None)
1872       Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1873   } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1874     Operand = II->getCalledValue();
1875     PointerType *PTy = cast<PointerType>(Operand->getType());
1876     FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1877     Type *RetTy = FTy->getReturnType();
1878     const AttrListPtr &PAL = II->getAttributes();
1879
1880     // Print the calling convention being used.
1881     switch (II->getCallingConv()) {
1882     case CallingConv::C: break;   // default
1883     case CallingConv::Fast:  Out << " fastcc"; break;
1884     case CallingConv::Cold:  Out << " coldcc"; break;
1885     case CallingConv::X86_StdCall:  Out << " x86_stdcallcc"; break;
1886     case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1887     case CallingConv::X86_ThisCall: Out << " x86_thiscallcc"; break;
1888     case CallingConv::ARM_APCS:     Out << " arm_apcscc "; break;
1889     case CallingConv::ARM_AAPCS:    Out << " arm_aapcscc "; break;
1890     case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1891     case CallingConv::MSP430_INTR:  Out << " msp430_intrcc "; break;
1892     case CallingConv::PTX_Kernel:   Out << " ptx_kernel"; break;
1893     case CallingConv::PTX_Device:   Out << " ptx_device"; break;
1894     default: Out << " cc" << II->getCallingConv(); break;
1895     }
1896
1897     if (PAL.getRetAttributes() != Attribute::None)
1898       Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1899
1900     // If possible, print out the short form of the invoke instruction. We can
1901     // only do this if the first argument is a pointer to a nonvararg function,
1902     // and if the return type is not a pointer to a function.
1903     //
1904     Out << ' ';
1905     if (!FTy->isVarArg() &&
1906         (!RetTy->isPointerTy() ||
1907          !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
1908       TypePrinter.print(RetTy, Out);
1909       Out << ' ';
1910       writeOperand(Operand, false);
1911     } else {
1912       writeOperand(Operand, true);
1913     }
1914     Out << '(';
1915     for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
1916       if (op)
1917         Out << ", ";
1918       writeParamOperand(II->getArgOperand(op), PAL.getParamAttributes(op + 1));
1919     }
1920
1921     Out << ')';
1922     if (PAL.getFnAttributes() != Attribute::None)
1923       Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1924
1925     Out << "\n          to ";
1926     writeOperand(II->getNormalDest(), true);
1927     Out << " unwind ";
1928     writeOperand(II->getUnwindDest(), true);
1929
1930   } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
1931     Out << ' ';
1932     TypePrinter.print(AI->getType()->getElementType(), Out);
1933     if (!AI->getArraySize() || AI->isArrayAllocation()) {
1934       Out << ", ";
1935       writeOperand(AI->getArraySize(), true);
1936     }
1937     if (AI->getAlignment()) {
1938       Out << ", align " << AI->getAlignment();
1939     }
1940   } else if (isa<CastInst>(I)) {
1941     if (Operand) {
1942       Out << ' ';
1943       writeOperand(Operand, true);   // Work with broken code
1944     }
1945     Out << " to ";
1946     TypePrinter.print(I.getType(), Out);
1947   } else if (isa<VAArgInst>(I)) {
1948     if (Operand) {
1949       Out << ' ';
1950       writeOperand(Operand, true);   // Work with broken code
1951     }
1952     Out << ", ";
1953     TypePrinter.print(I.getType(), Out);
1954   } else if (Operand) {   // Print the normal way.
1955
1956     // PrintAllTypes - Instructions who have operands of all the same type
1957     // omit the type from all but the first operand.  If the instruction has
1958     // different type operands (for example br), then they are all printed.
1959     bool PrintAllTypes = false;
1960     Type *TheType = Operand->getType();
1961
1962     // Select, Store and ShuffleVector always print all types.
1963     if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1964         || isa<ReturnInst>(I)) {
1965       PrintAllTypes = true;
1966     } else {
1967       for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1968         Operand = I.getOperand(i);
1969         // note that Operand shouldn't be null, but the test helps make dump()
1970         // more tolerant of malformed IR
1971         if (Operand && Operand->getType() != TheType) {
1972           PrintAllTypes = true;    // We have differing types!  Print them all!
1973           break;
1974         }
1975       }
1976     }
1977
1978     if (!PrintAllTypes) {
1979       Out << ' ';
1980       TypePrinter.print(TheType, Out);
1981     }
1982
1983     Out << ' ';
1984     for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1985       if (i) Out << ", ";
1986       writeOperand(I.getOperand(i), PrintAllTypes);
1987     }
1988   }
1989
1990   // Print atomic ordering/alignment for memory operations
1991   if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
1992     if (LI->isAtomic())
1993       writeAtomic(LI->getOrdering(), LI->getSynchScope());
1994     if (LI->getAlignment())
1995       Out << ", align " << LI->getAlignment();
1996   } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
1997     if (SI->isAtomic())
1998       writeAtomic(SI->getOrdering(), SI->getSynchScope());
1999     if (SI->getAlignment())
2000       Out << ", align " << SI->getAlignment();
2001   } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
2002     writeAtomic(CXI->getOrdering(), CXI->getSynchScope());
2003   } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
2004     writeAtomic(RMWI->getOrdering(), RMWI->getSynchScope());
2005   } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
2006     writeAtomic(FI->getOrdering(), FI->getSynchScope());
2007   }
2008
2009   // Print Metadata info.
2010   SmallVector<std::pair<unsigned, MDNode*>, 4> InstMD;
2011   I.getAllMetadata(InstMD);
2012   if (!InstMD.empty()) {
2013     SmallVector<StringRef, 8> MDNames;
2014     I.getType()->getContext().getMDKindNames(MDNames);
2015     for (unsigned i = 0, e = InstMD.size(); i != e; ++i) {
2016       unsigned Kind = InstMD[i].first;
2017        if (Kind < MDNames.size()) {
2018          Out << ", !" << MDNames[Kind];
2019       } else {
2020         Out << ", !<unknown kind #" << Kind << ">";
2021       }
2022       Out << ' ';
2023       WriteAsOperandInternal(Out, InstMD[i].second, &TypePrinter, &Machine,
2024                              TheModule);
2025     }
2026   }
2027   printInfoComment(I);
2028 }
2029
2030 static void WriteMDNodeComment(const MDNode *Node,
2031                                formatted_raw_ostream &Out) {
2032   if (Node->getNumOperands() < 1)
2033     return;
2034   ConstantInt *CI = dyn_cast_or_null<ConstantInt>(Node->getOperand(0));
2035   if (!CI) return;
2036   APInt Val = CI->getValue();
2037   APInt Tag = Val & ~APInt(Val.getBitWidth(), LLVMDebugVersionMask);
2038   if (Val.ult(LLVMDebugVersion11))
2039     return;
2040
2041   Out.PadToColumn(50);
2042   if (Tag == dwarf::DW_TAG_user_base)
2043     Out << "; [ DW_TAG_user_base ]";
2044   else if (Tag.isIntN(32)) {
2045     if (const char *TagName = dwarf::TagString(Tag.getZExtValue()))
2046       Out << "; [ " << TagName << " ]";
2047   }
2048 }
2049
2050 void AssemblyWriter::writeAllMDNodes() {
2051   SmallVector<const MDNode *, 16> Nodes;
2052   Nodes.resize(Machine.mdn_size());
2053   for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
2054        I != E; ++I)
2055     Nodes[I->second] = cast<MDNode>(I->first);
2056
2057   for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
2058     Out << '!' << i << " = metadata ";
2059     printMDNodeBody(Nodes[i]);
2060   }
2061 }
2062
2063 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
2064   WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
2065   WriteMDNodeComment(Node, Out);
2066   Out << "\n";
2067 }
2068
2069 //===----------------------------------------------------------------------===//
2070 //                       External Interface declarations
2071 //===----------------------------------------------------------------------===//
2072
2073 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2074   SlotTracker SlotTable(this);
2075   formatted_raw_ostream OS(ROS);
2076   AssemblyWriter W(OS, SlotTable, this, AAW);
2077   W.printModule(this);
2078 }
2079
2080 void NamedMDNode::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2081   SlotTracker SlotTable(getParent());
2082   formatted_raw_ostream OS(ROS);
2083   AssemblyWriter W(OS, SlotTable, getParent(), AAW);
2084   W.printNamedMDNode(this);
2085 }
2086
2087 void Type::print(raw_ostream &OS) const {
2088   if (this == 0) {
2089     OS << "<null Type>";
2090     return;
2091   }
2092   TypePrinting TP;
2093   TP.print(const_cast<Type*>(this), OS);
2094
2095   // If the type is a named struct type, print the body as well.
2096   if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
2097     if (!STy->isLiteral()) {
2098       OS << " = type ";
2099       TP.printStructBody(STy, OS);
2100     }
2101 }
2102
2103 void Value::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2104   if (this == 0) {
2105     ROS << "printing a <null> value\n";
2106     return;
2107   }
2108   formatted_raw_ostream OS(ROS);
2109   if (const Instruction *I = dyn_cast<Instruction>(this)) {
2110     const Function *F = I->getParent() ? I->getParent()->getParent() : 0;
2111     SlotTracker SlotTable(F);
2112     AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), AAW);
2113     W.printInstruction(*I);
2114   } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
2115     SlotTracker SlotTable(BB->getParent());
2116     AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), AAW);
2117     W.printBasicBlock(BB);
2118   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
2119     SlotTracker SlotTable(GV->getParent());
2120     AssemblyWriter W(OS, SlotTable, GV->getParent(), AAW);
2121     if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
2122       W.printGlobal(V);
2123     else if (const Function *F = dyn_cast<Function>(GV))
2124       W.printFunction(F);
2125     else
2126       W.printAlias(cast<GlobalAlias>(GV));
2127   } else if (const MDNode *N = dyn_cast<MDNode>(this)) {
2128     const Function *F = N->getFunction();
2129     SlotTracker SlotTable(F);
2130     AssemblyWriter W(OS, SlotTable, F ? F->getParent() : 0, AAW);
2131     W.printMDNodeBody(N);
2132   } else if (const Constant *C = dyn_cast<Constant>(this)) {
2133     TypePrinting TypePrinter;
2134     TypePrinter.print(C->getType(), OS);
2135     OS << ' ';
2136     WriteConstantInternal(OS, C, TypePrinter, 0, 0);
2137   } else if (isa<InlineAsm>(this) || isa<MDString>(this) ||
2138              isa<Argument>(this)) {
2139     WriteAsOperand(OS, this, true, 0);
2140   } else {
2141     // Otherwise we don't know what it is. Call the virtual function to
2142     // allow a subclass to print itself.
2143     printCustom(OS);
2144   }
2145 }
2146
2147 // Value::printCustom - subclasses should override this to implement printing.
2148 void Value::printCustom(raw_ostream &OS) const {
2149   llvm_unreachable("Unknown value to print out!");
2150 }
2151
2152 // Value::dump - allow easy printing of Values from the debugger.
2153 void Value::dump() const { print(dbgs()); dbgs() << '\n'; }
2154
2155 // Type::dump - allow easy printing of Types from the debugger.
2156 void Type::dump() const { print(dbgs()); }
2157
2158 // Module::dump() - Allow printing of Modules from the debugger.
2159 void Module::dump() const { print(dbgs(), 0); }
2160
2161 // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
2162 void NamedMDNode::dump() const { print(dbgs(), 0); }