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