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