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