Don't print extra spaces in vector and array constants. This makes
[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/AsmAnnotationWriter.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/InlineAsm.h"
24 #include "llvm/Instruction.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Module.h"
27 #include "llvm/ValueSymbolTable.h"
28 #include "llvm/TypeSymbolTable.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/StringExtras.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/Support/CFG.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include <algorithm>
36 #include <cctype>
37 using namespace llvm;
38
39 // Make virtual table appear in this compilation unit.
40 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
41
42 //===----------------------------------------------------------------------===//
43 // Helper Functions
44 //===----------------------------------------------------------------------===//
45
46 static const Module *getModuleFromVal(const Value *V) {
47   if (const Argument *MA = dyn_cast<Argument>(V))
48     return MA->getParent() ? MA->getParent()->getParent() : 0;
49   
50   if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
51     return BB->getParent() ? BB->getParent()->getParent() : 0;
52   
53   if (const Instruction *I = dyn_cast<Instruction>(V)) {
54     const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
55     return M ? M->getParent() : 0;
56   }
57   
58   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
59     return GV->getParent();
60   return 0;
61 }
62
63 // PrintEscapedString - Print each character of the specified string, escaping
64 // it if it is not printable or if it is an escape char.
65 static void PrintEscapedString(const char *Str, unsigned Length,
66                                raw_ostream &Out) {
67   for (unsigned i = 0; i != Length; ++i) {
68     unsigned char C = Str[i];
69     if (isprint(C) && C != '\\' && C != '"' && isprint(C))
70       Out << C;
71     else
72       Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
73   }
74 }
75
76 // PrintEscapedString - Print each character of the specified string, escaping
77 // it if it is not printable or if it is an escape char.
78 static void PrintEscapedString(const std::string &Str, raw_ostream &Out) {
79   PrintEscapedString(Str.c_str(), Str.size(), Out);
80 }
81
82 enum PrefixType {
83   GlobalPrefix,
84   LabelPrefix,
85   LocalPrefix,
86   NoPrefix
87 };
88
89 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
90 /// prefixed with % (if the string only contains simple characters) or is
91 /// surrounded with ""'s (if it has special chars in it).  Print it out.
92 static void PrintLLVMName(raw_ostream &OS, const char *NameStr,
93                           unsigned NameLen, PrefixType Prefix) {
94   assert(NameStr && "Cannot get empty name!");
95   switch (Prefix) {
96   default: assert(0 && "Bad prefix!");
97   case NoPrefix: break;
98   case GlobalPrefix: OS << '@'; break;
99   case LabelPrefix:  break;
100   case LocalPrefix:  OS << '%'; break;
101   }      
102   
103   // Scan the name to see if it needs quotes first.
104   bool NeedsQuotes = isdigit(NameStr[0]);
105   if (!NeedsQuotes) {
106     for (unsigned i = 0; i != NameLen; ++i) {
107       char C = NameStr[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.write(NameStr, NameLen);
118     return;
119   }
120   
121   // Okay, we need quotes.  Output the quotes and escape any scary characters as
122   // needed.
123   OS << '"';
124   PrintEscapedString(NameStr, NameLen, OS);
125   OS << '"';
126 }
127
128 /// getLLVMName - Turn the specified string into an 'LLVM name', which is
129 /// surrounded with ""'s and escaped if it has special chars in it.
130 static std::string getLLVMName(const std::string &Name) {
131   assert(!Name.empty() && "Cannot get empty name!");
132   std::string result;
133   raw_string_ostream OS(result);
134   PrintLLVMName(OS, Name.c_str(), Name.length(), NoPrefix);
135   return OS.str();
136 }
137
138 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
139 /// prefixed with % (if the string only contains simple characters) or is
140 /// surrounded with ""'s (if it has special chars in it).  Print it out.
141 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
142   PrintLLVMName(OS, V->getNameStart(), V->getNameLen(),
143                 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
144 }
145
146
147
148 //===----------------------------------------------------------------------===//
149 // SlotTracker Class: Enumerate slot numbers for unnamed values
150 //===----------------------------------------------------------------------===//
151
152 namespace {
153
154 /// This class provides computation of slot numbers for LLVM Assembly writing.
155 ///
156 class SlotTracker {
157 public:
158   /// ValueMap - A mapping of Values to slot numbers
159   typedef DenseMap<const Value*, unsigned> ValueMap;
160   
161 private:  
162   /// TheModule - The module for which we are holding slot numbers
163   const Module* TheModule;
164   
165   /// TheFunction - The function for which we are holding slot numbers
166   const Function* TheFunction;
167   bool FunctionProcessed;
168   
169   /// mMap - The TypePlanes map for the module level data
170   ValueMap mMap;
171   unsigned mNext;
172   
173   /// fMap - The TypePlanes map for the function level data
174   ValueMap fMap;
175   unsigned fNext;
176   
177 public:
178   /// Construct from a module
179   explicit SlotTracker(const Module *M);
180   /// Construct from a function, starting out in incorp state.
181   explicit SlotTracker(const Function *F);
182
183   /// Return the slot number of the specified value in it's type
184   /// plane.  If something is not in the SlotTracker, return -1.
185   int getLocalSlot(const Value *V);
186   int getGlobalSlot(const GlobalValue *V);
187
188   /// If you'd like to deal with a function instead of just a module, use
189   /// this method to get its data into the SlotTracker.
190   void incorporateFunction(const Function *F) {
191     TheFunction = F;
192     FunctionProcessed = false;
193   }
194
195   /// After calling incorporateFunction, use this method to remove the
196   /// most recently incorporated function from the SlotTracker. This
197   /// will reset the state of the machine back to just the module contents.
198   void purgeFunction();
199
200   // Implementation Details
201 private:
202   /// This function does the actual initialization.
203   inline void initialize();
204
205   /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
206   void CreateModuleSlot(const GlobalValue *V);
207   
208   /// CreateFunctionSlot - Insert the specified Value* into the slot table.
209   void CreateFunctionSlot(const Value *V);
210
211   /// Add all of the module level global variables (and their initializers)
212   /// and function declarations, but not the contents of those functions.
213   void processModule();
214
215   /// Add all of the functions arguments, basic blocks, and instructions
216   void processFunction();
217
218   SlotTracker(const SlotTracker &);  // DO NOT IMPLEMENT
219   void operator=(const SlotTracker &);  // DO NOT IMPLEMENT
220 };
221
222 }  // end anonymous namespace
223
224
225 static SlotTracker *createSlotTracker(const Value *V) {
226   if (const Argument *FA = dyn_cast<Argument>(V))
227     return new SlotTracker(FA->getParent());
228   
229   if (const Instruction *I = dyn_cast<Instruction>(V))
230     return new SlotTracker(I->getParent()->getParent());
231   
232   if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
233     return new SlotTracker(BB->getParent());
234   
235   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
236     return new SlotTracker(GV->getParent());
237   
238   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
239     return new SlotTracker(GA->getParent());    
240   
241   if (const Function *Func = dyn_cast<Function>(V))
242     return new SlotTracker(Func);
243   
244   return 0;
245 }
246
247 #if 0
248 #define ST_DEBUG(X) cerr << X
249 #else
250 #define ST_DEBUG(X)
251 #endif
252
253 // Module level constructor. Causes the contents of the Module (sans functions)
254 // to be added to the slot table.
255 SlotTracker::SlotTracker(const Module *M)
256   : TheModule(M), TheFunction(0), FunctionProcessed(false), mNext(0), fNext(0) {
257 }
258
259 // Function level constructor. Causes the contents of the Module and the one
260 // function provided to be added to the slot table.
261 SlotTracker::SlotTracker(const Function *F)
262   : TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false),
263     mNext(0), fNext(0) {
264 }
265
266 inline void SlotTracker::initialize() {
267   if (TheModule) {
268     processModule();
269     TheModule = 0; ///< Prevent re-processing next time we're called.
270   }
271   
272   if (TheFunction && !FunctionProcessed)
273     processFunction();
274 }
275
276 // Iterate through all the global variables, functions, and global
277 // variable initializers and create slots for them.
278 void SlotTracker::processModule() {
279   ST_DEBUG("begin processModule!\n");
280   
281   // Add all of the unnamed global variables to the value table.
282   for (Module::const_global_iterator I = TheModule->global_begin(),
283        E = TheModule->global_end(); I != E; ++I)
284     if (!I->hasName()) 
285       CreateModuleSlot(I);
286   
287   // Add all the unnamed functions to the table.
288   for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
289        I != E; ++I)
290     if (!I->hasName())
291       CreateModuleSlot(I);
292   
293   ST_DEBUG("end processModule!\n");
294 }
295
296
297 // Process the arguments, basic blocks, and instructions  of a function.
298 void SlotTracker::processFunction() {
299   ST_DEBUG("begin processFunction!\n");
300   fNext = 0;
301   
302   // Add all the function arguments with no names.
303   for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
304       AE = TheFunction->arg_end(); AI != AE; ++AI)
305     if (!AI->hasName())
306       CreateFunctionSlot(AI);
307   
308   ST_DEBUG("Inserting Instructions:\n");
309   
310   // Add all of the basic blocks and instructions with no names.
311   for (Function::const_iterator BB = TheFunction->begin(),
312        E = TheFunction->end(); BB != E; ++BB) {
313     if (!BB->hasName())
314       CreateFunctionSlot(BB);
315     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
316       if (I->getType() != Type::VoidTy && !I->hasName())
317         CreateFunctionSlot(I);
318   }
319   
320   FunctionProcessed = true;
321   
322   ST_DEBUG("end processFunction!\n");
323 }
324
325 /// Clean up after incorporating a function. This is the only way to get out of
326 /// the function incorporation state that affects get*Slot/Create*Slot. Function
327 /// incorporation state is indicated by TheFunction != 0.
328 void SlotTracker::purgeFunction() {
329   ST_DEBUG("begin purgeFunction!\n");
330   fMap.clear(); // Simply discard the function level map
331   TheFunction = 0;
332   FunctionProcessed = false;
333   ST_DEBUG("end purgeFunction!\n");
334 }
335
336 /// getGlobalSlot - Get the slot number of a global value.
337 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
338   // Check for uninitialized state and do lazy initialization.
339   initialize();
340   
341   // Find the type plane in the module map
342   ValueMap::iterator MI = mMap.find(V);
343   return MI == mMap.end() ? -1 : (int)MI->second;
344 }
345
346
347 /// getLocalSlot - Get the slot number for a value that is local to a function.
348 int SlotTracker::getLocalSlot(const Value *V) {
349   assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
350   
351   // Check for uninitialized state and do lazy initialization.
352   initialize();
353   
354   ValueMap::iterator FI = fMap.find(V);
355   return FI == fMap.end() ? -1 : (int)FI->second;
356 }
357
358
359 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
360 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
361   assert(V && "Can't insert a null Value into SlotTracker!");
362   assert(V->getType() != Type::VoidTy && "Doesn't need a slot!");
363   assert(!V->hasName() && "Doesn't need a slot!");
364   
365   unsigned DestSlot = mNext++;
366   mMap[V] = DestSlot;
367   
368   ST_DEBUG("  Inserting value [" << V->getType() << "] = " << V << " slot=" <<
369            DestSlot << " [");
370   // G = Global, F = Function, A = Alias, o = other
371   ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
372             (isa<Function>(V) ? 'F' :
373              (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
374 }
375
376
377 /// CreateSlot - Create a new slot for the specified value if it has no name.
378 void SlotTracker::CreateFunctionSlot(const Value *V) {
379   assert(V->getType() != Type::VoidTy && !V->hasName() &&
380          "Doesn't need a slot!");
381   
382   unsigned DestSlot = fNext++;
383   fMap[V] = DestSlot;
384   
385   // G = Global, F = Function, o = other
386   ST_DEBUG("  Inserting value [" << V->getType() << "] = " << V << " slot=" <<
387            DestSlot << " [o]\n");
388 }  
389
390
391
392 //===----------------------------------------------------------------------===//
393 // AsmWriter Implementation
394 //===----------------------------------------------------------------------===//
395
396 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
397                                std::map<const Type *, std::string> &TypeTable,
398                                    SlotTracker *Machine);
399
400
401
402 /// fillTypeNameTable - If the module has a symbol table, take all global types
403 /// and stuff their names into the TypeNames map.
404 ///
405 static void fillTypeNameTable(const Module *M,
406                               std::map<const Type *, std::string> &TypeNames) {
407   if (!M) return;
408   const TypeSymbolTable &ST = M->getTypeSymbolTable();
409   TypeSymbolTable::const_iterator TI = ST.begin();
410   for (; TI != ST.end(); ++TI) {
411     // As a heuristic, don't insert pointer to primitive types, because
412     // they are used too often to have a single useful name.
413     //
414     const Type *Ty = cast<Type>(TI->second);
415     if (!isa<PointerType>(Ty) ||
416         !cast<PointerType>(Ty)->getElementType()->isPrimitiveType() ||
417         !cast<PointerType>(Ty)->getElementType()->isInteger() ||
418         isa<OpaqueType>(cast<PointerType>(Ty)->getElementType()))
419       TypeNames.insert(std::make_pair(Ty, '%' + getLLVMName(TI->first)));
420   }
421 }
422
423
424
425 static void calcTypeName(const Type *Ty,
426                          std::vector<const Type *> &TypeStack,
427                          std::map<const Type *, std::string> &TypeNames,
428                          std::string &Result) {
429   if (Ty->isInteger() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))) {
430     Result += Ty->getDescription();  // Base case
431     return;
432   }
433
434   // Check to see if the type is named.
435   std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
436   if (I != TypeNames.end()) {
437     Result += I->second;
438     return;
439   }
440
441   if (isa<OpaqueType>(Ty)) {
442     Result += "opaque";
443     return;
444   }
445
446   // Check to see if the Type is already on the stack...
447   unsigned Slot = 0, CurSize = TypeStack.size();
448   while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
449
450   // This is another base case for the recursion.  In this case, we know
451   // that we have looped back to a type that we have previously visited.
452   // Generate the appropriate upreference to handle this.
453   if (Slot < CurSize) {
454     Result += "\\" + utostr(CurSize-Slot);     // Here's the upreference
455     return;
456   }
457
458   TypeStack.push_back(Ty);    // Recursive case: Add us to the stack..
459
460   switch (Ty->getTypeID()) {
461   case Type::IntegerTyID: {
462     unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
463     Result += "i" + utostr(BitWidth);
464     break;
465   }
466   case Type::FunctionTyID: {
467     const FunctionType *FTy = cast<FunctionType>(Ty);
468     calcTypeName(FTy->getReturnType(), TypeStack, TypeNames, Result);
469     Result += " (";
470     for (FunctionType::param_iterator I = FTy->param_begin(),
471          E = FTy->param_end(); I != E; ++I) {
472       if (I != FTy->param_begin())
473         Result += ", ";
474       calcTypeName(*I, TypeStack, TypeNames, Result);
475     }
476     if (FTy->isVarArg()) {
477       if (FTy->getNumParams()) Result += ", ";
478       Result += "...";
479     }
480     Result += ")";
481     break;
482   }
483   case Type::StructTyID: {
484     const StructType *STy = cast<StructType>(Ty);
485     if (STy->isPacked())
486       Result += '<';
487     Result += "{ ";
488     for (StructType::element_iterator I = STy->element_begin(),
489            E = STy->element_end(); I != E; ++I) {
490       calcTypeName(*I, TypeStack, TypeNames, Result);
491       if (next(I) != STy->element_end())
492         Result += ',';
493       Result += ' ';
494     }
495     Result += '}';
496     if (STy->isPacked())
497       Result += '>';
498     break;
499   }
500   case Type::PointerTyID: {
501     const PointerType *PTy = cast<PointerType>(Ty);
502     calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result);
503     if (unsigned AddressSpace = PTy->getAddressSpace())
504       Result += " addrspace(" + utostr(AddressSpace) + ")";
505     Result += "*";
506     break;
507   }
508   case Type::ArrayTyID: {
509     const ArrayType *ATy = cast<ArrayType>(Ty);
510     Result += "[" + utostr(ATy->getNumElements()) + " x ";
511     calcTypeName(ATy->getElementType(), TypeStack, TypeNames, Result);
512     Result += "]";
513     break;
514   }
515   case Type::VectorTyID: {
516     const VectorType *PTy = cast<VectorType>(Ty);
517     Result += "<" + utostr(PTy->getNumElements()) + " x ";
518     calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result);
519     Result += ">";
520     break;
521   }
522   case Type::OpaqueTyID:
523     Result += "opaque";
524     break;
525   default:
526     Result += "<unrecognized-type>";
527     break;
528   }
529
530   TypeStack.pop_back();       // Remove self from stack...
531 }
532
533
534 /// printTypeInt - The internal guts of printing out a type that has a
535 /// potentially named portion.
536 ///
537 static void printTypeInt(raw_ostream &Out, const Type *Ty,
538                          std::map<const Type *, std::string> &TypeNames) {
539   // Primitive types always print out their description, regardless of whether
540   // they have been named or not.
541   //
542   if (Ty->isInteger() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))) {
543     Out << Ty->getDescription();
544     return;
545   }
546
547   // Check to see if the type is named.
548   std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
549   if (I != TypeNames.end()) {
550     Out << I->second;
551     return;
552   }
553
554   // Otherwise we have a type that has not been named but is a derived type.
555   // Carefully recurse the type hierarchy to print out any contained symbolic
556   // names.
557   //
558   std::vector<const Type *> TypeStack;
559   std::string TypeName;
560   calcTypeName(Ty, TypeStack, TypeNames, TypeName);
561   TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
562   Out << TypeName;
563 }
564
565
566 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
567 /// type, iff there is an entry in the modules symbol table for the specified
568 /// type or one of it's component types. This is slower than a simple x << Type
569 ///
570 void llvm::WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
571                              const Module *M) {
572   raw_os_ostream RO(Out);
573   WriteTypeSymbolic(RO, Ty, M);
574 }
575
576 void llvm::WriteTypeSymbolic(raw_ostream &Out, const Type *Ty, const Module *M){
577   Out << ' ';
578
579   // If they want us to print out a type, but there is no context, we can't
580   // print it symbolically.
581   if (!M) {
582     Out << Ty->getDescription();
583   } else {
584     std::map<const Type *, std::string> TypeNames;
585     fillTypeNameTable(M, TypeNames);
586     printTypeInt(Out, Ty, TypeNames);
587   }
588 }
589
590 static const char *getPredicateText(unsigned predicate) {
591   const char * pred = "unknown";
592   switch (predicate) {
593     case FCmpInst::FCMP_FALSE: pred = "false"; break;
594     case FCmpInst::FCMP_OEQ:   pred = "oeq"; break;
595     case FCmpInst::FCMP_OGT:   pred = "ogt"; break;
596     case FCmpInst::FCMP_OGE:   pred = "oge"; break;
597     case FCmpInst::FCMP_OLT:   pred = "olt"; break;
598     case FCmpInst::FCMP_OLE:   pred = "ole"; break;
599     case FCmpInst::FCMP_ONE:   pred = "one"; break;
600     case FCmpInst::FCMP_ORD:   pred = "ord"; break;
601     case FCmpInst::FCMP_UNO:   pred = "uno"; break;
602     case FCmpInst::FCMP_UEQ:   pred = "ueq"; break;
603     case FCmpInst::FCMP_UGT:   pred = "ugt"; break;
604     case FCmpInst::FCMP_UGE:   pred = "uge"; break;
605     case FCmpInst::FCMP_ULT:   pred = "ult"; break;
606     case FCmpInst::FCMP_ULE:   pred = "ule"; break;
607     case FCmpInst::FCMP_UNE:   pred = "une"; break;
608     case FCmpInst::FCMP_TRUE:  pred = "true"; break;
609     case ICmpInst::ICMP_EQ:    pred = "eq"; break;
610     case ICmpInst::ICMP_NE:    pred = "ne"; break;
611     case ICmpInst::ICMP_SGT:   pred = "sgt"; break;
612     case ICmpInst::ICMP_SGE:   pred = "sge"; break;
613     case ICmpInst::ICMP_SLT:   pred = "slt"; break;
614     case ICmpInst::ICMP_SLE:   pred = "sle"; break;
615     case ICmpInst::ICMP_UGT:   pred = "ugt"; break;
616     case ICmpInst::ICMP_UGE:   pred = "uge"; break;
617     case ICmpInst::ICMP_ULT:   pred = "ult"; break;
618     case ICmpInst::ICMP_ULE:   pred = "ule"; break;
619   }
620   return pred;
621 }
622
623 static void WriteConstantInt(raw_ostream &Out, const Constant *CV,
624                              std::map<const Type *, std::string> &TypeTable,
625                              SlotTracker *Machine) {
626   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
627     if (CI->getType() == Type::Int1Ty) {
628       Out << (CI->getZExtValue() ? "true" : "false");
629       return;
630     }
631     Out << CI->getValue();
632     return;
633   }
634   
635   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
636     if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble ||
637         &CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle) {
638       // We would like to output the FP constant value in exponential notation,
639       // but we cannot do this if doing so will lose precision.  Check here to
640       // make sure that we only output it in exponential format if we can parse
641       // the value back and get the same value.
642       //
643       bool ignored;
644       bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
645       double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
646                               CFP->getValueAPF().convertToFloat();
647       std::string StrVal = ftostr(CFP->getValueAPF());
648
649       // Check to make sure that the stringized number is not some string like
650       // "Inf" or NaN, that atof will accept, but the lexer will not.  Check
651       // that the string matches the "[-+]?[0-9]" regex.
652       //
653       if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
654           ((StrVal[0] == '-' || StrVal[0] == '+') &&
655            (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
656         // Reparse stringized version!
657         if (atof(StrVal.c_str()) == Val) {
658           Out << StrVal;
659           return;
660         }
661       }
662       // Otherwise we could not reparse it to exactly the same value, so we must
663       // output the string in hexadecimal format!  Note that loading and storing
664       // floating point types changes the bits of NaNs on some hosts, notably
665       // x86, so we must not use these types.
666       assert(sizeof(double) == sizeof(uint64_t) &&
667              "assuming that double is 64 bits!");
668       char Buffer[40];
669       APFloat apf = CFP->getValueAPF();
670       // Floats are represented in ASCII IR as double, convert.
671       if (!isDouble)
672         apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, 
673                           &ignored);
674       Out << "0x" << 
675               utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()), 
676                             Buffer+40);
677       return;
678     }
679     
680     // Some form of long double.  These appear as a magic letter identifying
681     // the type, then a fixed number of hex digits.
682     Out << "0x";
683     if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended)
684       Out << 'K';
685     else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad)
686       Out << 'L';
687     else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble)
688       Out << 'M';
689     else
690       assert(0 && "Unsupported floating point type");
691     // api needed to prevent premature destruction
692     APInt api = CFP->getValueAPF().bitcastToAPInt();
693     const uint64_t* p = api.getRawData();
694     uint64_t word = *p;
695     int shiftcount=60;
696     int width = api.getBitWidth();
697     for (int j=0; j<width; j+=4, shiftcount-=4) {
698       unsigned int nibble = (word>>shiftcount) & 15;
699       if (nibble < 10)
700         Out << (unsigned char)(nibble + '0');
701       else
702         Out << (unsigned char)(nibble - 10 + 'A');
703       if (shiftcount == 0 && j+4 < width) {
704         word = *(++p);
705         shiftcount = 64;
706         if (width-j-4 < 64)
707           shiftcount = width-j-4;
708       }
709     }
710     return;
711   }
712   
713   if (isa<ConstantAggregateZero>(CV)) {
714     Out << "zeroinitializer";
715     return;
716   }
717   
718   if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
719     // As a special case, print the array as a string if it is an array of
720     // i8 with ConstantInt values.
721     //
722     const Type *ETy = CA->getType()->getElementType();
723     if (CA->isString()) {
724       Out << "c\"";
725       PrintEscapedString(CA->getAsString(), Out);
726       Out << '"';
727     } else {                // Cannot output in string format...
728       Out << '[';
729       if (CA->getNumOperands()) {
730         printTypeInt(Out, ETy, TypeTable);
731         Out << ' ';
732         WriteAsOperandInternal(Out, CA->getOperand(0),
733                                TypeTable, Machine);
734         for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
735           Out << ", ";
736           printTypeInt(Out, ETy, TypeTable);
737           Out << ' ';
738           WriteAsOperandInternal(Out, CA->getOperand(i), TypeTable, Machine);
739         }
740       }
741       Out << ']';
742     }
743     return;
744   }
745   
746   if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
747     if (CS->getType()->isPacked())
748       Out << '<';
749     Out << '{';
750     unsigned N = CS->getNumOperands();
751     if (N) {
752       Out << ' ';
753       printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
754       Out << ' ';
755
756       WriteAsOperandInternal(Out, CS->getOperand(0), TypeTable, Machine);
757
758       for (unsigned i = 1; i < N; i++) {
759         Out << ", ";
760         printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
761         Out << ' ';
762
763         WriteAsOperandInternal(Out, CS->getOperand(i), TypeTable, Machine);
764       }
765       Out << ' ';
766     }
767  
768     Out << '}';
769     if (CS->getType()->isPacked())
770       Out << '>';
771     return;
772   }
773   
774   if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
775     const Type *ETy = CP->getType()->getElementType();
776     assert(CP->getNumOperands() > 0 &&
777            "Number of operands for a PackedConst must be > 0");
778     Out << '<';
779     printTypeInt(Out, ETy, TypeTable);
780     Out << ' ';
781     WriteAsOperandInternal(Out, CP->getOperand(0), TypeTable, Machine);
782     for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
783       Out << ", ";
784       printTypeInt(Out, ETy, TypeTable);
785       Out << ' ';
786       WriteAsOperandInternal(Out, CP->getOperand(i), TypeTable, Machine);
787     }
788     Out << '>';
789     return;
790   }
791   
792   if (isa<ConstantPointerNull>(CV)) {
793     Out << "null";
794     return;
795   }
796   
797   if (isa<UndefValue>(CV)) {
798     Out << "undef";
799     return;
800   }
801
802   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
803     Out << CE->getOpcodeName();
804     if (CE->isCompare())
805       Out << ' ' << getPredicateText(CE->getPredicate());
806     Out << " (";
807
808     for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
809       printTypeInt(Out, (*OI)->getType(), TypeTable);
810       Out << ' ';
811       WriteAsOperandInternal(Out, *OI, TypeTable, Machine);
812       if (OI+1 != CE->op_end())
813         Out << ", ";
814     }
815
816     if (CE->hasIndices()) {
817       const SmallVector<unsigned, 4> &Indices = CE->getIndices();
818       for (unsigned i = 0, e = Indices.size(); i != e; ++i)
819         Out << ", " << Indices[i];
820     }
821
822     if (CE->isCast()) {
823       Out << " to ";
824       printTypeInt(Out, CE->getType(), TypeTable);
825     }
826
827     Out << ')';
828     return;
829   }
830   
831   Out << "<placeholder or erroneous Constant>";
832 }
833
834
835 /// WriteAsOperand - Write the name of the specified value out to the specified
836 /// ostream.  This can be useful when you just want to print int %reg126, not
837 /// the whole instruction that generated it.
838 ///
839 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
840                                   std::map<const Type*, std::string> &TypeTable,
841                                    SlotTracker *Machine) {
842   if (V->hasName()) {
843     PrintLLVMName(Out, V);
844     return;
845   }
846   
847   const Constant *CV = dyn_cast<Constant>(V);
848   if (CV && !isa<GlobalValue>(CV)) {
849     WriteConstantInt(Out, CV, TypeTable, Machine);
850     return;
851   }
852   
853   if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
854     Out << "asm ";
855     if (IA->hasSideEffects())
856       Out << "sideeffect ";
857     Out << '"';
858     PrintEscapedString(IA->getAsmString(), Out);
859     Out << "\", \"";
860     PrintEscapedString(IA->getConstraintString(), Out);
861     Out << '"';
862     return;
863   }
864   
865   char Prefix = '%';
866   int Slot;
867   if (Machine) {
868     if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
869       Slot = Machine->getGlobalSlot(GV);
870       Prefix = '@';
871     } else {
872       Slot = Machine->getLocalSlot(V);
873     }
874   } else {
875     Machine = createSlotTracker(V);
876     if (Machine) {
877       if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
878         Slot = Machine->getGlobalSlot(GV);
879         Prefix = '@';
880       } else {
881         Slot = Machine->getLocalSlot(V);
882       }
883     } else {
884       Slot = -1;
885     }
886     delete Machine;
887   }
888   
889   if (Slot != -1)
890     Out << Prefix << Slot;
891   else
892     Out << "<badref>";
893 }
894
895 /// WriteAsOperand - Write the name of the specified value out to the specified
896 /// ostream.  This can be useful when you just want to print int %reg126, not
897 /// the whole instruction that generated it.
898 ///
899 void llvm::WriteAsOperand(std::ostream &Out, const Value *V, bool PrintType,
900                           const Module *Context) {
901   raw_os_ostream OS(Out);
902   WriteAsOperand(OS, V, PrintType, Context);
903 }
904
905 void llvm::WriteAsOperand(raw_ostream &Out, const Value *V, bool PrintType,
906                           const Module *Context) {
907   std::map<const Type *, std::string> TypeNames;
908   if (Context == 0) Context = getModuleFromVal(V);
909
910   if (Context)
911     fillTypeNameTable(Context, TypeNames);
912
913   if (PrintType) {
914     printTypeInt(Out, V->getType(), TypeNames);
915     Out << ' ';
916   }
917
918   WriteAsOperandInternal(Out, V, TypeNames, 0);
919 }
920
921
922 namespace {
923
924 class AssemblyWriter {
925   raw_ostream &Out;
926   SlotTracker &Machine;
927   const Module *TheModule;
928   std::map<const Type *, std::string> TypeNames;
929   AssemblyAnnotationWriter *AnnotationWriter;
930 public:
931   inline AssemblyWriter(raw_ostream &o, SlotTracker &Mac, const Module *M,
932                         AssemblyAnnotationWriter *AAW)
933     : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
934
935     // If the module has a symbol table, take all global types and stuff their
936     // names into the TypeNames map.
937     //
938     fillTypeNameTable(M, TypeNames);
939   }
940
941   void write(const Module *M) { printModule(M);       }
942   
943   void write(const GlobalValue *G) {
944     if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(G))
945       printGlobal(GV);
946     else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(G))
947       printAlias(GA);
948     else if (const Function *F = dyn_cast<Function>(G))
949       printFunction(F);
950     else
951       assert(0 && "Unknown global");
952   }
953   
954   void write(const BasicBlock *BB)    { printBasicBlock(BB);  }
955   void write(const Instruction *I)    { printInstruction(*I); }
956   void write(const Type *Ty)          { printType(Ty);        }
957
958   void writeOperand(const Value *Op, bool PrintType);
959   void writeParamOperand(const Value *Operand, Attributes Attrs);
960
961   const Module* getModule() { return TheModule; }
962
963 private:
964   void printModule(const Module *M);
965   void printTypeSymbolTable(const TypeSymbolTable &ST);
966   void printGlobal(const GlobalVariable *GV);
967   void printAlias(const GlobalAlias *GV);
968   void printFunction(const Function *F);
969   void printArgument(const Argument *FA, Attributes Attrs);
970   void printBasicBlock(const BasicBlock *BB);
971   void printInstruction(const Instruction &I);
972
973   // printType - Go to extreme measures to attempt to print out a short,
974   // symbolic version of a type name.
975   //
976   void printType(const Type *Ty) {
977     printTypeInt(Out, Ty, TypeNames);
978   }
979
980   // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
981   // without considering any symbolic types that we may have equal to it.
982   //
983   void printTypeAtLeastOneLevel(const Type *Ty);
984
985   // printInfoComment - Print a little comment after the instruction indicating
986   // which slot it occupies.
987   void printInfoComment(const Value &V);
988 };
989 }  // end of llvm namespace
990
991 /// printTypeAtLeastOneLevel - Print out one level of the possibly complex type
992 /// without considering any symbolic types that we may have equal to it.
993 ///
994 void AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
995   if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
996     Out << "i" << utostr(ITy->getBitWidth());
997     return;
998   }
999   
1000   if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
1001     printType(FTy->getReturnType());
1002     Out << " (";
1003     for (FunctionType::param_iterator I = FTy->param_begin(),
1004            E = FTy->param_end(); I != E; ++I) {
1005       if (I != FTy->param_begin())
1006         Out << ", ";
1007       printType(*I);
1008     }
1009     if (FTy->isVarArg()) {
1010       if (FTy->getNumParams()) Out << ", ";
1011       Out << "...";
1012     }
1013     Out << ')';
1014     return;
1015   }
1016   
1017   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1018     if (STy->isPacked())
1019       Out << '<';
1020     Out << "{ ";
1021     for (StructType::element_iterator I = STy->element_begin(),
1022            E = STy->element_end(); I != E; ++I) {
1023       if (I != STy->element_begin())
1024         Out << ", ";
1025       printType(*I);
1026     }
1027     Out << " }";
1028     if (STy->isPacked())
1029       Out << '>';
1030     return;
1031   }
1032   
1033   if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1034     printType(PTy->getElementType());
1035     if (unsigned AddressSpace = PTy->getAddressSpace())
1036       Out << " addrspace(" << AddressSpace << ")";
1037     Out << '*';
1038     return;
1039   } 
1040   
1041   if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1042     Out << '[' << ATy->getNumElements() << " x ";
1043     printType(ATy->getElementType());
1044     Out << ']';
1045     return;
1046   }
1047   
1048   if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
1049     Out << '<' << PTy->getNumElements() << " x ";
1050     printType(PTy->getElementType());
1051     Out << '>';
1052     return;
1053   }
1054   
1055   if (isa<OpaqueType>(Ty)) {
1056     Out << "opaque";
1057     return;
1058   }
1059   
1060   if (!Ty->isPrimitiveType())
1061     Out << "<unknown derived type>";
1062   printType(Ty);
1063 }
1064
1065
1066 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
1067   if (Operand == 0) {
1068     Out << "<null operand!>";
1069   } else {
1070     if (PrintType) {
1071       printType(Operand->getType());
1072       Out << ' ';
1073     }
1074     WriteAsOperandInternal(Out, Operand, TypeNames, &Machine);
1075   }
1076 }
1077
1078 void AssemblyWriter::writeParamOperand(const Value *Operand, 
1079                                        Attributes Attrs) {
1080   if (Operand == 0) {
1081     Out << "<null operand!>";
1082   } else {
1083     // Print the type
1084     printType(Operand->getType());
1085     // Print parameter attributes list
1086     if (Attrs != Attribute::None)
1087       Out << ' ' << Attribute::getAsString(Attrs);
1088     Out << ' ';
1089     // Print the operand
1090     WriteAsOperandInternal(Out, Operand, TypeNames, &Machine);
1091   }
1092 }
1093
1094 void AssemblyWriter::printModule(const Module *M) {
1095   if (!M->getModuleIdentifier().empty() &&
1096       // Don't print the ID if it will start a new line (which would
1097       // require a comment char before it).
1098       M->getModuleIdentifier().find('\n') == std::string::npos)
1099     Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1100
1101   if (!M->getDataLayout().empty())
1102     Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
1103   if (!M->getTargetTriple().empty())
1104     Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1105
1106   if (!M->getModuleInlineAsm().empty()) {
1107     // Split the string into lines, to make it easier to read the .ll file.
1108     std::string Asm = M->getModuleInlineAsm();
1109     size_t CurPos = 0;
1110     size_t NewLine = Asm.find_first_of('\n', CurPos);
1111     while (NewLine != std::string::npos) {
1112       // We found a newline, print the portion of the asm string from the
1113       // last newline up to this newline.
1114       Out << "module asm \"";
1115       PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1116                          Out);
1117       Out << "\"\n";
1118       CurPos = NewLine+1;
1119       NewLine = Asm.find_first_of('\n', CurPos);
1120     }
1121     Out << "module asm \"";
1122     PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1123     Out << "\"\n";
1124   }
1125   
1126   // Loop over the dependent libraries and emit them.
1127   Module::lib_iterator LI = M->lib_begin();
1128   Module::lib_iterator LE = M->lib_end();
1129   if (LI != LE) {
1130     Out << "deplibs = [ ";
1131     while (LI != LE) {
1132       Out << '"' << *LI << '"';
1133       ++LI;
1134       if (LI != LE)
1135         Out << ", ";
1136     }
1137     Out << " ]\n";
1138   }
1139
1140   // Loop over the symbol table, emitting all named constants.
1141   printTypeSymbolTable(M->getTypeSymbolTable());
1142
1143   for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1144        I != E; ++I)
1145     printGlobal(I);
1146   
1147   // Output all aliases.
1148   if (!M->alias_empty()) Out << "\n";
1149   for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1150        I != E; ++I)
1151     printAlias(I);
1152
1153   // Output all of the functions.
1154   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1155     printFunction(I);
1156 }
1157
1158 static void PrintLinkage(GlobalValue::LinkageTypes LT, raw_ostream &Out) {
1159   switch (LT) {
1160   case GlobalValue::PrivateLinkage:      Out << "private "; break;
1161   case GlobalValue::InternalLinkage:     Out << "internal "; break;
1162   case GlobalValue::LinkOnceLinkage:     Out << "linkonce "; break;
1163   case GlobalValue::WeakLinkage:         Out << "weak "; break;
1164   case GlobalValue::CommonLinkage:       Out << "common "; break;
1165   case GlobalValue::AppendingLinkage:    Out << "appending "; break;
1166   case GlobalValue::DLLImportLinkage:    Out << "dllimport "; break;
1167   case GlobalValue::DLLExportLinkage:    Out << "dllexport "; break;
1168   case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;      
1169   case GlobalValue::ExternalLinkage: break;
1170   case GlobalValue::GhostLinkage:
1171     Out << "GhostLinkage not allowed in AsmWriter!\n";
1172     abort();
1173   }
1174 }
1175       
1176
1177 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1178                             raw_ostream &Out) {
1179   switch (Vis) {
1180   default: assert(0 && "Invalid visibility style!");
1181   case GlobalValue::DefaultVisibility: break;
1182   case GlobalValue::HiddenVisibility:    Out << "hidden "; break;
1183   case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1184   }
1185 }
1186
1187 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1188   if (GV->hasName()) {
1189     PrintLLVMName(Out, GV);
1190     Out << " = ";
1191   }
1192
1193   if (!GV->hasInitializer() && GV->hasExternalLinkage())
1194     Out << "external ";
1195   
1196   PrintLinkage(GV->getLinkage(), Out);
1197   PrintVisibility(GV->getVisibility(), Out);
1198
1199   if (GV->isThreadLocal()) Out << "thread_local ";
1200   if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1201     Out << "addrspace(" << AddressSpace << ") ";
1202   Out << (GV->isConstant() ? "constant " : "global ");
1203   printType(GV->getType()->getElementType());
1204
1205   if (GV->hasInitializer()) {
1206     Out << ' ';
1207     writeOperand(GV->getInitializer(), false);
1208   }
1209     
1210   if (GV->hasSection())
1211     Out << ", section \"" << GV->getSection() << '"';
1212   if (GV->getAlignment())
1213     Out << ", align " << GV->getAlignment();
1214
1215   printInfoComment(*GV);
1216   Out << '\n';
1217 }
1218
1219 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1220   // Don't crash when dumping partially built GA
1221   if (!GA->hasName())
1222     Out << "<<nameless>> = ";
1223   else {
1224     PrintLLVMName(Out, GA);
1225     Out << " = ";
1226   }
1227   PrintVisibility(GA->getVisibility(), Out);
1228
1229   Out << "alias ";
1230
1231   PrintLinkage(GA->getLinkage(), Out);
1232   
1233   const Constant *Aliasee = GA->getAliasee();
1234     
1235   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) {
1236     printType(GV->getType());
1237     Out << ' ';
1238     PrintLLVMName(Out, GV);
1239   } else if (const Function *F = dyn_cast<Function>(Aliasee)) {
1240     printType(F->getFunctionType());
1241     Out << "* ";
1242
1243     if (F->hasName())
1244       PrintLLVMName(Out, F);
1245     else
1246       Out << "@\"\"";
1247   } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Aliasee)) {
1248     printType(GA->getType());
1249     Out << " ";
1250     PrintLLVMName(Out, GA);
1251   } else {
1252     const ConstantExpr *CE = 0;
1253     if ((CE = dyn_cast<ConstantExpr>(Aliasee)) &&
1254         (CE->getOpcode() == Instruction::BitCast)) {
1255       writeOperand(CE, false);    
1256     } else
1257       assert(0 && "Unsupported aliasee");
1258   }
1259   
1260   printInfoComment(*GA);
1261   Out << '\n';
1262 }
1263
1264 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
1265   // Print the types.
1266   for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
1267        TI != TE; ++TI) {
1268     Out << '\t';
1269     PrintLLVMName(Out, &TI->first[0], TI->first.size(), LocalPrefix);
1270     Out << " = type ";
1271
1272     // Make sure we print out at least one level of the type structure, so
1273     // that we do not get %FILE = type %FILE
1274     //
1275     printTypeAtLeastOneLevel(TI->second);
1276     Out << '\n';
1277   }
1278 }
1279
1280 /// printFunction - Print all aspects of a function.
1281 ///
1282 void AssemblyWriter::printFunction(const Function *F) {
1283   // Print out the return type and name.
1284   Out << '\n';
1285
1286   if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1287
1288   if (F->isDeclaration())
1289     Out << "declare ";
1290   else
1291     Out << "define ";
1292   
1293   PrintLinkage(F->getLinkage(), Out);
1294   PrintVisibility(F->getVisibility(), Out);
1295
1296   // Print the calling convention.
1297   switch (F->getCallingConv()) {
1298   case CallingConv::C: break;   // default
1299   case CallingConv::Fast:         Out << "fastcc "; break;
1300   case CallingConv::Cold:         Out << "coldcc "; break;
1301   case CallingConv::X86_StdCall:  Out << "x86_stdcallcc "; break;
1302   case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break; 
1303   default: Out << "cc" << F->getCallingConv() << " "; break;
1304   }
1305
1306   const FunctionType *FT = F->getFunctionType();
1307   const AttrListPtr &Attrs = F->getAttributes();
1308   Attributes RetAttrs = Attrs.getRetAttributes();
1309   if (RetAttrs != Attribute::None)
1310     Out <<  Attribute::getAsString(Attrs.getRetAttributes()) << ' ';
1311   printType(F->getReturnType());
1312   Out << ' ';
1313   if (F->hasName())
1314     PrintLLVMName(Out, F);
1315   else
1316     Out << "@\"\"";
1317   Out << '(';
1318   Machine.incorporateFunction(F);
1319
1320   // Loop over the arguments, printing them...
1321
1322   unsigned Idx = 1;
1323   if (!F->isDeclaration()) {
1324     // If this isn't a declaration, print the argument names as well.
1325     for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1326          I != E; ++I) {
1327       // Insert commas as we go... the first arg doesn't get a comma
1328       if (I != F->arg_begin()) Out << ", ";
1329       printArgument(I, Attrs.getParamAttributes(Idx));
1330       Idx++;
1331     }
1332   } else {
1333     // Otherwise, print the types from the function type.
1334     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1335       // Insert commas as we go... the first arg doesn't get a comma
1336       if (i) Out << ", ";
1337       
1338       // Output type...
1339       printType(FT->getParamType(i));
1340       
1341       Attributes ArgAttrs = Attrs.getParamAttributes(i+1);
1342       if (ArgAttrs != Attribute::None)
1343         Out << ' ' << Attribute::getAsString(ArgAttrs);
1344     }
1345   }
1346
1347   // Finish printing arguments...
1348   if (FT->isVarArg()) {
1349     if (FT->getNumParams()) Out << ", ";
1350     Out << "...";  // Output varargs portion of signature!
1351   }
1352   Out << ')';
1353   Attributes FnAttrs = Attrs.getFnAttributes();
1354   if (FnAttrs != Attribute::None)
1355     Out << ' ' << Attribute::getAsString(Attrs.getFnAttributes());
1356   if (F->hasSection())
1357     Out << " section \"" << F->getSection() << '"';
1358   if (F->getAlignment())
1359     Out << " align " << F->getAlignment();
1360   if (F->hasGC())
1361     Out << " gc \"" << F->getGC() << '"';
1362   if (F->isDeclaration()) {
1363     Out << "\n";
1364   } else {
1365     Out << " {";
1366
1367     // Output all of its basic blocks... for the function
1368     for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1369       printBasicBlock(I);
1370
1371     Out << "}\n";
1372   }
1373
1374   Machine.purgeFunction();
1375 }
1376
1377 /// printArgument - This member is called for every argument that is passed into
1378 /// the function.  Simply print it out
1379 ///
1380 void AssemblyWriter::printArgument(const Argument *Arg, 
1381                                    Attributes Attrs) {
1382   // Output type...
1383   printType(Arg->getType());
1384
1385   // Output parameter attributes list
1386   if (Attrs != Attribute::None)
1387     Out << ' ' << Attribute::getAsString(Attrs);
1388
1389   // Output name, if available...
1390   if (Arg->hasName()) {
1391     Out << ' ';
1392     PrintLLVMName(Out, Arg);
1393   }
1394 }
1395
1396 /// printBasicBlock - This member is called for each basic block in a method.
1397 ///
1398 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1399   if (BB->hasName()) {              // Print out the label if it exists...
1400     Out << "\n";
1401     PrintLLVMName(Out, BB->getNameStart(), BB->getNameLen(), LabelPrefix);
1402     Out << ':';
1403   } else if (!BB->use_empty()) {      // Don't print block # of no uses...
1404     Out << "\n; <label>:";
1405     int Slot = Machine.getLocalSlot(BB);
1406     if (Slot != -1)
1407       Out << Slot;
1408     else
1409       Out << "<badref>";
1410   }
1411
1412   if (BB->getParent() == 0)
1413     Out << "\t\t; Error: Block without parent!";
1414   else if (BB != &BB->getParent()->getEntryBlock()) {  // Not the entry block?
1415     // Output predecessors for the block...
1416     Out << "\t\t;";
1417     pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1418     
1419     if (PI == PE) {
1420       Out << " No predecessors!";
1421     } else {
1422       Out << " preds = ";
1423       writeOperand(*PI, false);
1424       for (++PI; PI != PE; ++PI) {
1425         Out << ", ";
1426         writeOperand(*PI, false);
1427       }
1428     }
1429   }
1430
1431   Out << "\n";
1432
1433   if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1434
1435   // Output all of the instructions in the basic block...
1436   for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1437     printInstruction(*I);
1438
1439   if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1440 }
1441
1442
1443 /// printInfoComment - Print a little comment after the instruction indicating
1444 /// which slot it occupies.
1445 ///
1446 void AssemblyWriter::printInfoComment(const Value &V) {
1447   if (V.getType() != Type::VoidTy) {
1448     Out << "\t\t; <";
1449     printType(V.getType());
1450     Out << '>';
1451
1452     if (!V.hasName() && !isa<Instruction>(V)) {
1453       int SlotNum;
1454       if (const GlobalValue *GV = dyn_cast<GlobalValue>(&V))
1455         SlotNum = Machine.getGlobalSlot(GV);
1456       else
1457         SlotNum = Machine.getLocalSlot(&V);
1458       if (SlotNum == -1)
1459         Out << ":<badref>";
1460       else
1461         Out << ':' << SlotNum; // Print out the def slot taken.
1462     }
1463     Out << " [#uses=" << V.getNumUses() << ']';  // Output # uses
1464   }
1465 }
1466
1467 // This member is called for each Instruction in a function..
1468 void AssemblyWriter::printInstruction(const Instruction &I) {
1469   if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1470
1471   Out << '\t';
1472
1473   // Print out name if it exists...
1474   if (I.hasName()) {
1475     PrintLLVMName(Out, &I);
1476     Out << " = ";
1477   } else if (I.getType() != Type::VoidTy) {
1478     // Print out the def slot taken.
1479     int SlotNum = Machine.getLocalSlot(&I);
1480     if (SlotNum == -1)
1481       Out << "<badref> = ";
1482     else
1483       Out << '%' << SlotNum << " = ";
1484   }
1485
1486   // If this is a volatile load or store, print out the volatile marker.
1487   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isVolatile()) ||
1488       (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1489       Out << "volatile ";
1490   } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1491     // If this is a call, check if it's a tail call.
1492     Out << "tail ";
1493   }
1494
1495   // Print out the opcode...
1496   Out << I.getOpcodeName();
1497
1498   // Print out the compare instruction predicates
1499   if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1500     Out << ' ' << getPredicateText(CI->getPredicate());
1501
1502   // Print out the type of the operands...
1503   const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1504
1505   // Special case conditional branches to swizzle the condition out to the front
1506   if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
1507     BranchInst &BI(cast<BranchInst>(I));
1508     Out << ' ';
1509     writeOperand(BI.getCondition(), true);
1510     Out << ", ";
1511     writeOperand(BI.getSuccessor(0), true);
1512     Out << ", ";
1513     writeOperand(BI.getSuccessor(1), true);
1514
1515   } else if (isa<SwitchInst>(I)) {
1516     // Special case switch statement to get formatting nice and correct...
1517     Out << ' ';
1518     writeOperand(Operand        , true);
1519     Out << ", ";
1520     writeOperand(I.getOperand(1), true);
1521     Out << " [";
1522
1523     for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1524       Out << "\n\t\t";
1525       writeOperand(I.getOperand(op  ), true);
1526       Out << ", ";
1527       writeOperand(I.getOperand(op+1), true);
1528     }
1529     Out << "\n\t]";
1530   } else if (isa<PHINode>(I)) {
1531     Out << ' ';
1532     printType(I.getType());
1533     Out << ' ';
1534
1535     for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1536       if (op) Out << ", ";
1537       Out << "[ ";
1538       writeOperand(I.getOperand(op  ), false); Out << ", ";
1539       writeOperand(I.getOperand(op+1), false); Out << " ]";
1540     }
1541   } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1542     Out << ' ';
1543     writeOperand(I.getOperand(0), true);
1544     for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1545       Out << ", " << *i;
1546   } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1547     Out << ' ';
1548     writeOperand(I.getOperand(0), true); Out << ", ";
1549     writeOperand(I.getOperand(1), true);
1550     for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1551       Out << ", " << *i;
1552   } else if (isa<ReturnInst>(I) && !Operand) {
1553     Out << " void";
1554   } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1555     // Print the calling convention being used.
1556     switch (CI->getCallingConv()) {
1557     case CallingConv::C: break;   // default
1558     case CallingConv::Fast:  Out << " fastcc"; break;
1559     case CallingConv::Cold:  Out << " coldcc"; break;
1560     case CallingConv::X86_StdCall:  Out << " x86_stdcallcc"; break;
1561     case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break; 
1562     default: Out << " cc" << CI->getCallingConv(); break;
1563     }
1564
1565     const PointerType    *PTy = cast<PointerType>(Operand->getType());
1566     const FunctionType   *FTy = cast<FunctionType>(PTy->getElementType());
1567     const Type         *RetTy = FTy->getReturnType();
1568     const AttrListPtr &PAL = CI->getAttributes();
1569
1570     if (PAL.getRetAttributes() != Attribute::None)
1571       Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1572
1573     // If possible, print out the short form of the call instruction.  We can
1574     // only do this if the first argument is a pointer to a nonvararg function,
1575     // and if the return type is not a pointer to a function.
1576     //
1577     Out << ' ';
1578     if (!FTy->isVarArg() &&
1579         (!isa<PointerType>(RetTy) ||
1580          !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1581       printType(RetTy);
1582       Out << ' ';
1583       writeOperand(Operand, false);
1584     } else {
1585       writeOperand(Operand, true);
1586     }
1587     Out << '(';
1588     for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) {
1589       if (op > 1)
1590         Out << ", ";
1591       writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op));
1592     }
1593     Out << ')';
1594     if (PAL.getFnAttributes() != Attribute::None)
1595       Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1596   } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1597     const PointerType    *PTy = cast<PointerType>(Operand->getType());
1598     const FunctionType   *FTy = cast<FunctionType>(PTy->getElementType());
1599     const Type         *RetTy = FTy->getReturnType();
1600     const AttrListPtr &PAL = II->getAttributes();
1601
1602     // Print the calling convention being used.
1603     switch (II->getCallingConv()) {
1604     case CallingConv::C: break;   // default
1605     case CallingConv::Fast:  Out << " fastcc"; break;
1606     case CallingConv::Cold:  Out << " coldcc"; break;
1607     case CallingConv::X86_StdCall:  Out << " x86_stdcallcc"; break;
1608     case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1609     default: Out << " cc" << II->getCallingConv(); break;
1610     }
1611
1612     if (PAL.getRetAttributes() != Attribute::None)
1613       Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1614
1615     // If possible, print out the short form of the invoke instruction. We can
1616     // only do this if the first argument is a pointer to a nonvararg function,
1617     // and if the return type is not a pointer to a function.
1618     //
1619     Out << ' ';
1620     if (!FTy->isVarArg() &&
1621         (!isa<PointerType>(RetTy) ||
1622          !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1623       printType(RetTy);
1624       Out << ' ';
1625       writeOperand(Operand, false);
1626     } else {
1627       writeOperand(Operand, true);
1628     }
1629     Out << '(';
1630     for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) {
1631       if (op > 3)
1632         Out << ", ";
1633       writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op-2));
1634     }
1635
1636     Out << ')';
1637     if (PAL.getFnAttributes() != Attribute::None)
1638       Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1639
1640     Out << "\n\t\t\tto ";
1641     writeOperand(II->getNormalDest(), true);
1642     Out << " unwind ";
1643     writeOperand(II->getUnwindDest(), true);
1644
1645   } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1646     Out << ' ';
1647     printType(AI->getType()->getElementType());
1648     if (AI->isArrayAllocation()) {
1649       Out << ", ";
1650       writeOperand(AI->getArraySize(), true);
1651     }
1652     if (AI->getAlignment()) {
1653       Out << ", align " << AI->getAlignment();
1654     }
1655   } else if (isa<CastInst>(I)) {
1656     if (Operand) {
1657       Out << ' ';
1658       writeOperand(Operand, true);   // Work with broken code
1659     }
1660     Out << " to ";
1661     printType(I.getType());
1662   } else if (isa<VAArgInst>(I)) {
1663     if (Operand) {
1664       Out << ' ';
1665       writeOperand(Operand, true);   // Work with broken code
1666     }
1667     Out << ", ";
1668     printType(I.getType());
1669   } else if (Operand) {   // Print the normal way...
1670
1671     // PrintAllTypes - Instructions who have operands of all the same type
1672     // omit the type from all but the first operand.  If the instruction has
1673     // different type operands (for example br), then they are all printed.
1674     bool PrintAllTypes = false;
1675     const Type *TheType = Operand->getType();
1676
1677     // Select, Store and ShuffleVector always print all types.
1678     if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1679         || isa<ReturnInst>(I)) {
1680       PrintAllTypes = true;
1681     } else {
1682       for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1683         Operand = I.getOperand(i);
1684         // note that Operand shouldn't be null, but the test helps make dump()
1685         // more tolerant of malformed IR
1686         if (Operand && Operand->getType() != TheType) {
1687           PrintAllTypes = true;    // We have differing types!  Print them all!
1688           break;
1689         }
1690       }
1691     }
1692
1693     if (!PrintAllTypes) {
1694       Out << ' ';
1695       printType(TheType);
1696     }
1697
1698     Out << ' ';
1699     for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1700       if (i) Out << ", ";
1701       writeOperand(I.getOperand(i), PrintAllTypes);
1702     }
1703   }
1704   
1705   // Print post operand alignment for load/store
1706   if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) {
1707     Out << ", align " << cast<LoadInst>(I).getAlignment();
1708   } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) {
1709     Out << ", align " << cast<StoreInst>(I).getAlignment();
1710   }
1711
1712   printInfoComment(I);
1713   Out << '\n';
1714 }
1715
1716
1717 //===----------------------------------------------------------------------===//
1718 //                       External Interface declarations
1719 //===----------------------------------------------------------------------===//
1720
1721 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1722   raw_os_ostream OS(o);
1723   print(OS, AAW);
1724 }
1725 void Module::print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const {
1726   SlotTracker SlotTable(this);
1727   AssemblyWriter W(OS, SlotTable, this, AAW);
1728   W.write(this);
1729 }
1730
1731 void Type::print(std::ostream &o) const {
1732   raw_os_ostream OS(o);
1733   print(OS);
1734 }
1735
1736 void Type::print(raw_ostream &o) const {
1737   if (this == 0)
1738     o << "<null Type>";
1739   else
1740     o << getDescription();
1741 }
1742
1743 void Value::print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const {
1744   if (this == 0) {
1745     OS << "printing a <null> value\n";
1746     return;
1747   }
1748
1749   if (const Instruction *I = dyn_cast<Instruction>(this)) {
1750     const Function *F = I->getParent() ? I->getParent()->getParent() : 0;
1751     SlotTracker SlotTable(F);
1752     AssemblyWriter W(OS, SlotTable, F ? F->getParent() : 0, AAW);
1753     W.write(I);
1754   } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
1755     SlotTracker SlotTable(BB->getParent());
1756     AssemblyWriter W(OS, SlotTable,
1757                      BB->getParent() ? BB->getParent()->getParent() : 0, AAW);
1758     W.write(BB);
1759   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
1760     SlotTracker SlotTable(GV->getParent());
1761     AssemblyWriter W(OS, SlotTable, GV->getParent(), 0);
1762     W.write(GV);
1763   } else if (const Constant *C = dyn_cast<Constant>(this)) {
1764     OS << C->getType()->getDescription() << ' ';
1765     std::map<const Type *, std::string> TypeTable;
1766     WriteConstantInt(OS, C, TypeTable, 0);
1767   } else if (const Argument *A = dyn_cast<Argument>(this)) {
1768     WriteAsOperand(OS, this, true,
1769                    A->getParent() ? A->getParent()->getParent() : 0);
1770   } else if (isa<InlineAsm>(this)) {
1771     WriteAsOperand(OS, this, true, 0);
1772   } else {
1773     assert(0 && "Unknown value to print out!");
1774   }
1775 }
1776
1777 void Value::print(std::ostream &O, AssemblyAnnotationWriter *AAW) const {
1778   raw_os_ostream OS(O);
1779   print(OS, AAW);
1780 }
1781
1782 // Value::dump - allow easy printing of Values from the debugger.
1783 void Value::dump() const { print(errs()); errs() << '\n'; errs().flush(); }
1784
1785 // Type::dump - allow easy printing of Types from the debugger.
1786 void Type::dump() const { print(errs()); errs() << '\n'; errs().flush(); }
1787
1788 // Type::dump - allow easy printing of Types from the debugger.
1789 // This one uses type names from the given context module
1790 void Type::dump(const Module *Context) const {
1791   WriteTypeSymbolic(errs(), this, Context);
1792   errs() << '\n';
1793   errs().flush();
1794 }
1795
1796 // Module::dump() - Allow printing of Modules from the debugger.
1797 void Module::dump() const { print(errs(), 0); errs().flush(); }
1798
1799