Fix a bug introduced by the Getelementptr change
[oota-llvm.git] / lib / Target / CBackend / Writer.cpp
1 //===-- Writer.cpp - Library for converting LLVM code to C ----------------===//
2 //
3 // This library implements the functionality defined in llvm/Assembly/CWriter.h
4 //
5 // TODO : Recursive types.
6 //
7 //===-----------------------------------------------------------------------==//
8
9 #include "llvm/Assembly/CWriter.h"
10 #include "llvm/Constants.h"
11 #include "llvm/DerivedTypes.h"
12 #include "llvm/Module.h"
13 #include "llvm/iMemory.h"
14 #include "llvm/iTerminators.h"
15 #include "llvm/iPHINode.h"
16 #include "llvm/iOther.h"
17 #include "llvm/iOperators.h"
18 #include "llvm/Pass.h"
19 #include "llvm/SymbolTable.h"
20 #include "llvm/SlotCalculator.h"
21 #include "llvm/Analysis/FindUsedTypes.h"
22 #include "llvm/Support/InstVisitor.h"
23 #include "llvm/Support/InstIterator.h"
24 #include "Support/StringExtras.h"
25 #include "Support/STLExtras.h"
26 #include <algorithm>
27 #include <set>
28 using std::string;
29 using std::map;
30 using std::ostream;
31
32 namespace {
33   class CWriter : public Pass, public InstVisitor<CWriter> {
34     ostream &Out; 
35     SlotCalculator *Table;
36     const Module *TheModule;
37     map<const Type *, string> TypeNames;
38     std::set<const Value*> MangledGlobals;
39   public:
40     CWriter(ostream &o) : Out(o) {}
41
42     void getAnalysisUsage(AnalysisUsage &AU) const {
43       AU.setPreservesAll();
44       AU.addRequired<FindUsedTypes>();
45     }
46
47     virtual bool run(Module &M) {
48       // Initialize
49       Table = new SlotCalculator(&M, false);
50       TheModule = &M;
51
52       // Ensure that all structure types have names...
53       bool Changed = nameAllUsedStructureTypes(M);
54
55       // Run...
56       printModule(&M);
57
58       // Free memory...
59       delete Table;
60       TypeNames.clear();
61       MangledGlobals.clear();
62       return false;
63     }
64
65     ostream &printType(const Type *Ty, const string &VariableName = "",
66                        bool IgnoreName = false, bool namedContext = true);
67
68     void writeOperand(Value *Operand);
69     void writeOperandInternal(Value *Operand);
70
71     string getValueName(const Value *V);
72
73   private :
74     bool nameAllUsedStructureTypes(Module &M);
75     void printModule(Module *M);
76     void printSymbolTable(const SymbolTable &ST);
77     void printGlobal(const GlobalVariable *GV);
78     void printFunctionSignature(const Function *F, bool Prototype);
79
80     void printFunction(Function *);
81
82     void printConstant(Constant *CPV);
83     void printConstantArray(ConstantArray *CPA);
84
85     // isInlinableInst - Attempt to inline instructions into their uses to build
86     // trees as much as possible.  To do this, we have to consistently decide
87     // what is acceptable to inline, so that variable declarations don't get
88     // printed and an extra copy of the expr is not emitted.
89     //
90     static bool isInlinableInst(const Instruction &I) {
91       // Must be an expression, must be used exactly once.  If it is dead, we
92       // emit it inline where it would go.
93       if (I.getType() == Type::VoidTy || I.use_size() != 1 ||
94           isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I))
95         return false;
96
97       // Only inline instruction it it's use is in the same BB as the inst.
98       return I.getParent() == cast<Instruction>(I.use_back())->getParent();
99     }
100
101     // Instruction visitation functions
102     friend class InstVisitor<CWriter>;
103
104     void visitReturnInst(ReturnInst &I);
105     void visitBranchInst(BranchInst &I);
106
107     void visitPHINode(PHINode &I) {}
108     void visitBinaryOperator(Instruction &I);
109
110     void visitCastInst (CastInst &I);
111     void visitCallInst (CallInst &I);
112     void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
113
114     void visitMallocInst(MallocInst &I);
115     void visitAllocaInst(AllocaInst &I);
116     void visitFreeInst  (FreeInst   &I);
117     void visitLoadInst  (LoadInst   &I);
118     void visitStoreInst (StoreInst  &I);
119     void visitGetElementPtrInst(GetElementPtrInst &I);
120
121     void visitInstruction(Instruction &I) {
122       std::cerr << "C Writer does not know about " << I;
123       abort();
124     }
125
126     void outputLValue(Instruction *I) {
127       Out << "  " << getValueName(I) << " = ";
128     }
129     void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
130                             unsigned Indent);
131     void printIndexingExpression(Value *Ptr, User::op_iterator I,
132                                  User::op_iterator E);
133   };
134 }
135
136 // We dont want identifier names with ., space, -  in them. 
137 // So we replace them with _
138 static string makeNameProper(string x) {
139   string tmp;
140   for (string::iterator sI = x.begin(), sEnd = x.end(); sI != sEnd; sI++)
141     switch (*sI) {
142     case '.': tmp += "d_"; break;
143     case ' ': tmp += "s_"; break;
144     case '-': tmp += "D_"; break;
145     default:  tmp += *sI;
146     }
147
148   return tmp;
149 }
150
151 string CWriter::getValueName(const Value *V) {
152   if (V->hasName()) {              // Print out the label if it exists...
153     if (isa<GlobalValue>(V) &&     // Do not mangle globals...
154         cast<GlobalValue>(V)->hasExternalLinkage() && // Unless it's internal or
155         !MangledGlobals.count(V))  // Unless the name would collide if we don't
156       return makeNameProper(V->getName());
157
158     return "l" + utostr(V->getType()->getUniqueID()) + "_" +
159            makeNameProper(V->getName());      
160   }
161
162   int Slot = Table->getValSlot(V);
163   assert(Slot >= 0 && "Invalid value!");
164   return "ltmp_" + itostr(Slot) + "_" + utostr(V->getType()->getUniqueID());
165 }
166
167 // A pointer type should not use parens around *'s alone, e.g., (**)
168 inline bool ptrTypeNameNeedsParens(const string &NameSoFar) {
169   return (NameSoFar.find_last_not_of('*') != std::string::npos);
170 }
171
172 // Pass the Type* and the variable name and this prints out the variable
173 // declaration.
174 //
175 ostream &CWriter::printType(const Type *Ty, const string &NameSoFar,
176                             bool IgnoreName, bool namedContext) {
177   if (Ty->isPrimitiveType())
178     switch (Ty->getPrimitiveID()) {
179     case Type::VoidTyID:   return Out << "void "               << NameSoFar;
180     case Type::BoolTyID:   return Out << "bool "               << NameSoFar;
181     case Type::UByteTyID:  return Out << "unsigned char "      << NameSoFar;
182     case Type::SByteTyID:  return Out << "signed char "        << NameSoFar;
183     case Type::UShortTyID: return Out << "unsigned short "     << NameSoFar;
184     case Type::ShortTyID:  return Out << "short "              << NameSoFar;
185     case Type::UIntTyID:   return Out << "unsigned "           << NameSoFar;
186     case Type::IntTyID:    return Out << "int "                << NameSoFar;
187     case Type::ULongTyID:  return Out << "unsigned long long " << NameSoFar;
188     case Type::LongTyID:   return Out << "signed long long "   << NameSoFar;
189     case Type::FloatTyID:  return Out << "float "              << NameSoFar;
190     case Type::DoubleTyID: return Out << "double "             << NameSoFar;
191     default :
192       std::cerr << "Unknown primitive type: " << Ty << "\n";
193       abort();
194     }
195   
196   // Check to see if the type is named.
197   if (!IgnoreName) {
198     map<const Type *, string>::iterator I = TypeNames.find(Ty);
199     if (I != TypeNames.end()) {
200       return Out << I->second << " " << NameSoFar;
201     }
202   }  
203
204   switch (Ty->getPrimitiveID()) {
205   case Type::FunctionTyID: {
206     const FunctionType *MTy = cast<FunctionType>(Ty);
207     printType(MTy->getReturnType(), "");
208     Out << " " << NameSoFar << " (";
209
210     for (FunctionType::ParamTypes::const_iterator
211            I = MTy->getParamTypes().begin(),
212            E = MTy->getParamTypes().end(); I != E; ++I) {
213       if (I != MTy->getParamTypes().begin())
214         Out << ", ";
215       printType(*I, "");
216     }
217     if (MTy->isVarArg()) {
218       if (!MTy->getParamTypes().empty()) 
219         Out << ", ";
220       Out << "...";
221     }
222     return Out << ")";
223   }
224   case Type::StructTyID: {
225     const StructType *STy = cast<StructType>(Ty);
226     Out << NameSoFar + " {\n";
227     unsigned Idx = 0;
228     for (StructType::ElementTypes::const_iterator
229            I = STy->getElementTypes().begin(),
230            E = STy->getElementTypes().end(); I != E; ++I) {
231       Out << "  ";
232       printType(*I, "field" + utostr(Idx++));
233       Out << ";\n";
234     }
235     return Out << "}";
236   }  
237
238   case Type::PointerTyID: {
239     const PointerType *PTy = cast<PointerType>(Ty);
240     std::string ptrName = "*" + NameSoFar;
241
242     // Do not need parens around "* NameSoFar" if NameSoFar consists only
243     // of zero or more '*' chars *and* this is not an unnamed pointer type
244     // such as the result type in a cast statement.  Otherwise, enclose in ( ).
245     if (ptrTypeNameNeedsParens(NameSoFar) || !namedContext)
246       ptrName = "(" + ptrName + ")";    // 
247
248     return printType(PTy->getElementType(), ptrName);
249   }
250
251   case Type::ArrayTyID: {
252     const ArrayType *ATy = cast<ArrayType>(Ty);
253     unsigned NumElements = ATy->getNumElements();
254     return printType(ATy->getElementType(),
255                      NameSoFar + "[" + utostr(NumElements) + "]");
256   }
257   default:
258     assert(0 && "Unhandled case in getTypeProps!");
259     abort();
260   }
261
262   return Out;
263 }
264
265 void CWriter::printConstantArray(ConstantArray *CPA) {
266
267   // As a special case, print the array as a string if it is an array of
268   // ubytes or an array of sbytes with positive values.
269   // 
270   const Type *ETy = CPA->getType()->getElementType();
271   bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
272
273   // Make sure the last character is a null char, as automatically added by C
274   if (CPA->getNumOperands() == 0 ||
275       !cast<Constant>(*(CPA->op_end()-1))->isNullValue())
276     isString = false;
277   
278   if (isString) {
279     Out << "\"";
280     // Do not include the last character, which we know is null
281     for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
282       unsigned char C = (ETy == Type::SByteTy) ?
283         (unsigned char)cast<ConstantSInt>(CPA->getOperand(i))->getValue() :
284         (unsigned char)cast<ConstantUInt>(CPA->getOperand(i))->getValue();
285       
286       if (isprint(C)) {
287         Out << C;
288       } else {
289         switch (C) {
290         case '\n': Out << "\\n"; break;
291         case '\t': Out << "\\t"; break;
292         case '\r': Out << "\\r"; break;
293         case '\v': Out << "\\v"; break;
294         case '\a': Out << "\\a"; break;
295         default:
296           Out << "\\x";
297           Out << ( C/16  < 10) ? ( C/16 +'0') : ( C/16 -10+'A');
298           Out << ((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A');
299           break;
300         }
301       }
302     }
303     Out << "\"";
304   } else {
305     Out << "{";
306     if (CPA->getNumOperands()) {
307       Out << " ";
308       printConstant(cast<Constant>(CPA->getOperand(0)));
309       for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
310         Out << ", ";
311         printConstant(cast<Constant>(CPA->getOperand(i)));
312       }
313     }
314     Out << " }";
315   }
316 }
317
318
319 // printConstant - The LLVM Constant to C Constant converter.
320 void CWriter::printConstant(Constant *CPV) {
321   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
322     switch (CE->getOpcode()) {
323     case Instruction::Cast:
324       Out << "((";
325       printType(CPV->getType());
326       Out << ")";
327       printConstant(cast<Constant>(CPV->getOperand(0)));
328       Out << ")";
329       return;
330
331     case Instruction::GetElementPtr:
332       Out << "&(";
333       printIndexingExpression(CPV->getOperand(0),
334                               CPV->op_begin()+1, CPV->op_end());
335       Out << ")";
336       return;
337     case Instruction::Add:
338       Out << "(";
339       printConstant(cast<Constant>(CPV->getOperand(0)));
340       Out << " + ";
341       printConstant(cast<Constant>(CPV->getOperand(1)));
342       Out << ")";
343       return;
344     case Instruction::Sub:
345       Out << "(";
346       printConstant(cast<Constant>(CPV->getOperand(0)));
347       Out << " - ";
348       printConstant(cast<Constant>(CPV->getOperand(1)));
349       Out << ")";
350       return;
351
352     default:
353       std::cerr << "CWriter Error: Unhandled constant expression: "
354                 << CE << "\n";
355       abort();
356     }
357   }
358
359   switch (CPV->getType()->getPrimitiveID()) {
360   case Type::BoolTyID:
361     Out << (CPV == ConstantBool::False ? "0" : "1"); break;
362   case Type::SByteTyID:
363   case Type::ShortTyID:
364   case Type::IntTyID:
365     Out << cast<ConstantSInt>(CPV)->getValue(); break;
366   case Type::LongTyID:
367     Out << cast<ConstantSInt>(CPV)->getValue() << "ll"; break;
368
369   case Type::UByteTyID:
370   case Type::UShortTyID:
371     Out << cast<ConstantUInt>(CPV)->getValue(); break;
372   case Type::UIntTyID:
373     Out << cast<ConstantUInt>(CPV)->getValue() << "u"; break;
374   case Type::ULongTyID:
375     Out << cast<ConstantUInt>(CPV)->getValue() << "ull"; break;
376
377   case Type::FloatTyID:
378   case Type::DoubleTyID:
379     Out << cast<ConstantFP>(CPV)->getValue(); break;
380
381   case Type::ArrayTyID:
382     printConstantArray(cast<ConstantArray>(CPV));
383     break;
384
385   case Type::StructTyID: {
386     Out << "{";
387     if (CPV->getNumOperands()) {
388       Out << " ";
389       printConstant(cast<Constant>(CPV->getOperand(0)));
390       for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
391         Out << ", ";
392         printConstant(cast<Constant>(CPV->getOperand(i)));
393       }
394     }
395     Out << " }";
396     break;
397   }
398
399   case Type::PointerTyID:
400     if (isa<ConstantPointerNull>(CPV)) {
401       Out << "((";
402       printType(CPV->getType(), "");
403       Out << ")NULL)";
404       break;
405     } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CPV)) {
406       writeOperand(CPR->getValue());
407       break;
408     }
409     // FALL THROUGH
410   default:
411     std::cerr << "Unknown constant type: " << CPV << "\n";
412     abort();
413   }
414 }
415
416 void CWriter::writeOperandInternal(Value *Operand) {
417   if (Instruction *I = dyn_cast<Instruction>(Operand))
418     if (isInlinableInst(*I)) {
419       // Should we inline this instruction to build a tree?
420       Out << "(";
421       visit(*I);
422       Out << ")";    
423       return;
424     }
425   
426   if (Operand->hasName()) {   
427     Out << getValueName(Operand);
428   } else if (Constant *CPV = dyn_cast<Constant>(Operand)) {
429     printConstant(CPV); 
430   } else {
431     int Slot = Table->getValSlot(Operand);
432     assert(Slot >= 0 && "Malformed LLVM!");
433     Out << "ltmp_" << Slot << "_" << Operand->getType()->getUniqueID();
434   }
435 }
436
437 void CWriter::writeOperand(Value *Operand) {
438   if (isa<GlobalVariable>(Operand))
439     Out << "(&";  // Global variables are references as their addresses by llvm
440
441   writeOperandInternal(Operand);
442
443   if (isa<GlobalVariable>(Operand))
444     Out << ")";
445 }
446
447 // nameAllUsedStructureTypes - If there are structure types in the module that
448 // are used but do not have names assigned to them in the symbol table yet then
449 // we assign them names now.
450 //
451 bool CWriter::nameAllUsedStructureTypes(Module &M) {
452   // Get a set of types that are used by the program...
453   std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
454
455   // Loop over the module symbol table, removing types from UT that are already
456   // named.
457   //
458   SymbolTable *MST = M.getSymbolTableSure();
459   if (MST->find(Type::TypeTy) != MST->end())
460     for (SymbolTable::type_iterator I = MST->type_begin(Type::TypeTy),
461            E = MST->type_end(Type::TypeTy); I != E; ++I)
462       UT.erase(cast<Type>(I->second));
463
464   // UT now contains types that are not named.  Loop over it, naming structure
465   // types.
466   //
467   bool Changed = false;
468   for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
469        I != E; ++I)
470     if (const StructType *ST = dyn_cast<StructType>(*I)) {
471       ((Value*)ST)->setName("unnamed", MST);
472       Changed = true;
473     }
474   return Changed;
475 }
476
477 void CWriter::printModule(Module *M) {
478   // Calculate which global values have names that will collide when we throw
479   // away type information.
480   {  // Scope to delete the FoundNames set when we are done with it...
481     std::set<string> FoundNames;
482     for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
483       if (I->hasName())                      // If the global has a name...
484         if (FoundNames.count(I->getName()))  // And the name is already used
485           MangledGlobals.insert(I);          // Mangle the name
486         else
487           FoundNames.insert(I->getName());   // Otherwise, keep track of name
488
489     for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
490       if (I->hasName())                      // If the global has a name...
491         if (FoundNames.count(I->getName()))  // And the name is already used
492           MangledGlobals.insert(I);          // Mangle the name
493         else
494           FoundNames.insert(I->getName());   // Otherwise, keep track of name
495   }
496
497   // printing stdlib inclusion
498   // Out << "#include <stdlib.h>\n";
499
500   // get declaration for alloca
501   Out << "/* Provide Declarations */\n"
502       << "#include <malloc.h>\n"
503       << "#include <alloca.h>\n\n"
504
505     // Provide a definition for null if one does not already exist,
506     // and for `bool' if not compiling with a C++ compiler.
507       << "#ifndef NULL\n#define NULL 0\n#endif\n\n"
508       << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
509
510       << "\n\n/* Global Declarations */\n";
511
512   // First output all the declarations for the program, because C requires
513   // Functions & globals to be declared before they are used.
514   //
515
516   // Loop over the symbol table, emitting all named constants...
517   if (M->hasSymbolTable())
518     printSymbolTable(*M->getSymbolTable());
519
520   // Global variable declarations...
521   if (!M->gempty()) {
522     Out << "\n/* Global Variable Declarations */\n";
523     for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) {
524       Out << (I->hasExternalLinkage() ? "extern " : "static ");
525       printType(I->getType()->getElementType(), getValueName(I));
526       Out << ";\n";
527     }
528   }
529
530   // Function declarations
531   if (!M->empty()) {
532     Out << "\n/* Function Declarations */\n";
533     for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
534       printFunctionSignature(I, true);
535       Out << ";\n";
536     }
537   }
538
539   // Output the global variable contents...
540   if (!M->gempty()) {
541     Out << "\n\n/* Global Data */\n";
542     for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) {
543       if (I->hasInternalLinkage()) Out << "static ";
544       printType(I->getType()->getElementType(), getValueName(I));
545       
546       if (I->hasInitializer()) {
547         Out << " = " ;
548         writeOperand(I->getInitializer());
549       }
550       Out << ";\n";
551     }
552   }
553
554   // Output all of the functions...
555   if (!M->empty()) {
556     Out << "\n\n/* Function Bodies */\n";
557     for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
558       printFunction(I);
559   }
560 }
561
562
563 // printSymbolTable - Run through symbol table looking for named constants
564 // if a named constant is found, emit it's declaration...
565 // Assuming that symbol table has only types and constants.
566 void CWriter::printSymbolTable(const SymbolTable &ST) {
567   for (SymbolTable::const_iterator TI = ST.begin(); TI != ST.end(); ++TI) {
568     SymbolTable::type_const_iterator I = ST.type_begin(TI->first);
569     SymbolTable::type_const_iterator End = ST.type_end(TI->first);
570     
571     for (; I != End; ++I)
572       if (const Type *Ty = dyn_cast<StructType>(I->second)) {
573         string Name = "struct l_" + makeNameProper(I->first);
574         Out << Name << ";\n";
575         TypeNames.insert(std::make_pair(Ty, Name));
576       }
577   }
578
579   Out << "\n";
580
581   for (SymbolTable::const_iterator TI = ST.begin(); TI != ST.end(); ++TI) {
582     SymbolTable::type_const_iterator I = ST.type_begin(TI->first);
583     SymbolTable::type_const_iterator End = ST.type_end(TI->first);
584     
585     for (; I != End; ++I) {
586       const Value *V = I->second;
587       if (const Type *Ty = dyn_cast<Type>(V)) {
588         string Name = "l_" + makeNameProper(I->first);
589         if (isa<StructType>(Ty))
590           Name = "struct " + makeNameProper(Name);
591         else
592           Out << "typedef ";
593
594         printType(Ty, Name, true);
595         Out << ";\n";
596       }
597     }
598   }
599 }
600
601
602 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
603   if (F->hasInternalLinkage()) Out << "static ";
604   
605   // Loop over the arguments, printing them...
606   const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
607   
608   // Print out the return type and name...
609   printType(F->getReturnType());
610   Out << getValueName(F) << "(";
611     
612   if (!F->isExternal()) {
613     if (!F->aempty()) {
614       string ArgName;
615       if (F->abegin()->hasName() || !Prototype)
616         ArgName = getValueName(F->abegin());
617
618       printType(F->afront().getType(), ArgName);
619
620       for (Function::const_aiterator I = ++F->abegin(), E = F->aend();
621            I != E; ++I) {
622         Out << ", ";
623         if (I->hasName() || !Prototype)
624           ArgName = getValueName(I);
625         else 
626           ArgName = "";
627         printType(I->getType(), ArgName);
628       }
629     }
630   } else {
631     // Loop over the arguments, printing them...
632     for (FunctionType::ParamTypes::const_iterator I = 
633            FT->getParamTypes().begin(),
634            E = FT->getParamTypes().end(); I != E; ++I) {
635       if (I != FT->getParamTypes().begin()) Out << ", ";
636       printType(*I);
637     }
638   }
639
640   // Finish printing arguments...
641   if (FT->isVarArg()) {
642     if (FT->getParamTypes().size()) Out << ", ";
643     Out << "...";  // Output varargs portion of signature!
644   }
645   Out << ")";
646 }
647
648
649 void CWriter::printFunction(Function *F) {
650   if (F->isExternal()) return;
651
652   Table->incorporateFunction(F);
653
654   printFunctionSignature(F, false);
655   Out << " {\n";
656
657   // print local variable information for the function
658   for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
659     if ((*I)->getType() != Type::VoidTy && !isInlinableInst(**I)) {
660       Out << "  ";
661       printType((*I)->getType(), getValueName(*I));
662       Out << ";\n";
663     }
664  
665   // print the basic blocks
666   for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
667     BasicBlock *Prev = BB->getPrev();
668
669     // Don't print the label for the basic block if there are no uses, or if the
670     // only terminator use is the precessor basic block's terminator.  We have
671     // to scan the use list because PHI nodes use basic blocks too but do not
672     // require a label to be generated.
673     //
674     bool NeedsLabel = false;
675     for (Value::use_iterator UI = BB->use_begin(), UE = BB->use_end();
676          UI != UE; ++UI)
677       if (TerminatorInst *TI = dyn_cast<TerminatorInst>(*UI))
678         if (TI != Prev->getTerminator()) {
679           NeedsLabel = true;
680           break;        
681         }
682
683     if (NeedsLabel) Out << getValueName(BB) << ":\n";
684
685     // Output all of the instructions in the basic block...
686     for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E; ++II){
687       if (!isInlinableInst(*II) && !isa<PHINode>(*II)) {
688         if (II->getType() != Type::VoidTy)
689           outputLValue(II);
690         else
691           Out << "  ";
692         visit(*II);
693         Out << ";\n";
694       }
695     }
696
697     // Don't emit prefix or suffix for the terminator...
698     visit(*BB->getTerminator());
699   }
700   
701   Out << "}\n\n";
702   Table->purgeFunction();
703 }
704
705 // Specific Instruction type classes... note that all of the casts are
706 // neccesary because we use the instruction classes as opaque types...
707 //
708 void CWriter::visitReturnInst(ReturnInst &I) {
709   // Don't output a void return if this is the last basic block in the function
710   if (I.getNumOperands() == 0 && 
711       &*--I.getParent()->getParent()->end() == I.getParent() &&
712       !I.getParent()->size() == 1) {
713     return;
714   }
715
716   Out << "  return";
717   if (I.getNumOperands()) {
718     Out << " ";
719     writeOperand(I.getOperand(0));
720   }
721   Out << ";\n";
722 }
723
724 static bool isGotoCodeNeccessary(BasicBlock *From, BasicBlock *To) {
725   // If PHI nodes need copies, we need the copy code...
726   if (isa<PHINode>(To->front()) ||
727       From->getNext() != To)      // Not directly successor, need goto
728     return true;
729
730   // Otherwise we don't need the code.
731   return false;
732 }
733
734 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
735                                            unsigned Indent) {
736   for (BasicBlock::iterator I = Succ->begin();
737        PHINode *PN = dyn_cast<PHINode>(&*I); ++I) {
738     //  now we have to do the printing
739     Out << string(Indent, ' ');
740     outputLValue(PN);
741     writeOperand(PN->getIncomingValue(PN->getBasicBlockIndex(CurBB)));
742     Out << ";   /* for PHI node */\n";
743   }
744
745   if (CurBB->getNext() != Succ) {
746     Out << string(Indent, ' ') << "  goto ";
747     writeOperand(Succ);
748     Out << ";\n";
749   }
750 }
751
752 // Brach instruction printing - Avoid printing out a brach to a basic block that
753 // immediately succeeds the current one.
754 //
755 void CWriter::visitBranchInst(BranchInst &I) {
756   if (I.isConditional()) {
757     if (isGotoCodeNeccessary(I.getParent(), I.getSuccessor(0))) {
758       Out << "  if (";
759       writeOperand(I.getCondition());
760       Out << ") {\n";
761       
762       printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
763       
764       if (isGotoCodeNeccessary(I.getParent(), I.getSuccessor(1))) {
765         Out << "  } else {\n";
766         printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
767       }
768     } else {
769       // First goto not neccesary, assume second one is...
770       Out << "  if (!";
771       writeOperand(I.getCondition());
772       Out << ") {\n";
773
774       printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
775     }
776
777     Out << "  }\n";
778   } else {
779     printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
780   }
781   Out << "\n";
782 }
783
784
785 void CWriter::visitBinaryOperator(Instruction &I) {
786   // binary instructions, shift instructions, setCond instructions.
787   if (isa<PointerType>(I.getType())) {
788     Out << "(";
789     printType(I.getType());
790     Out << ")";
791   }
792       
793   if (isa<PointerType>(I.getType())) Out << "(long long)";
794   writeOperand(I.getOperand(0));
795
796   switch (I.getOpcode()) {
797   case Instruction::Add: Out << " + "; break;
798   case Instruction::Sub: Out << " - "; break;
799   case Instruction::Mul: Out << "*"; break;
800   case Instruction::Div: Out << "/"; break;
801   case Instruction::Rem: Out << "%"; break;
802   case Instruction::And: Out << " & "; break;
803   case Instruction::Or: Out << " | "; break;
804   case Instruction::Xor: Out << " ^ "; break;
805   case Instruction::SetEQ: Out << " == "; break;
806   case Instruction::SetNE: Out << " != "; break;
807   case Instruction::SetLE: Out << " <= "; break;
808   case Instruction::SetGE: Out << " >= "; break;
809   case Instruction::SetLT: Out << " < "; break;
810   case Instruction::SetGT: Out << " > "; break;
811   case Instruction::Shl : Out << " << "; break;
812   case Instruction::Shr : Out << " >> "; break;
813   default: std::cerr << "Invalid operator type!" << I; abort();
814   }
815
816   if (isa<PointerType>(I.getType())) Out << "(long long)";
817   writeOperand(I.getOperand(1));
818 }
819
820 void CWriter::visitCastInst(CastInst &I) {
821   Out << "(";
822   printType(I.getType(), string(""),/*ignoreName*/false, /*namedContext*/false);
823   Out << ")";
824   writeOperand(I.getOperand(0));
825 }
826
827 void CWriter::visitCallInst(CallInst &I) {
828   const PointerType  *PTy   = cast<PointerType>(I.getCalledValue()->getType());
829   const FunctionType *FTy   = cast<FunctionType>(PTy->getElementType());
830   const Type         *RetTy = FTy->getReturnType();
831   
832   writeOperand(I.getOperand(0));
833   Out << "(";
834
835   if (I.getNumOperands() > 1) {
836     writeOperand(I.getOperand(1));
837
838     for (unsigned op = 2, Eop = I.getNumOperands(); op != Eop; ++op) {
839       Out << ", ";
840       writeOperand(I.getOperand(op));
841     }
842   }
843   Out << ")";
844 }  
845
846 void CWriter::visitMallocInst(MallocInst &I) {
847   Out << "(";
848   printType(I.getType());
849   Out << ")malloc(sizeof(";
850   printType(I.getType()->getElementType());
851   Out << ")";
852
853   if (I.isArrayAllocation()) {
854     Out << " * " ;
855     writeOperand(I.getOperand(0));
856   }
857   Out << ")";
858 }
859
860 void CWriter::visitAllocaInst(AllocaInst &I) {
861   Out << "(";
862   printType(I.getType());
863   Out << ") alloca(sizeof(";
864   printType(I.getType()->getElementType());
865   Out << ")";
866   if (I.isArrayAllocation()) {
867     Out << " * " ;
868     writeOperand(I.getOperand(0));
869   }
870   Out << ")";
871 }
872
873 void CWriter::visitFreeInst(FreeInst &I) {
874   Out << "free(";
875   writeOperand(I.getOperand(0));
876   Out << ")";
877 }
878
879 void CWriter::printIndexingExpression(Value *Ptr, User::op_iterator I,
880                                       User::op_iterator E) {
881   bool HasImplicitAddress = false;
882   // If accessing a global value with no indexing, avoid *(&GV) syndrome
883   if (GlobalValue *V = dyn_cast<GlobalValue>(Ptr)) {
884     HasImplicitAddress = true;
885   } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Ptr)) {
886     HasImplicitAddress = true;
887     Ptr = CPR->getValue();         // Get to the global...
888   }
889
890   if (I == E) {
891     if (!HasImplicitAddress)
892       Out << "*";  // Implicit zero first argument: '*x' is equivalent to 'x[0]'
893
894     writeOperandInternal(Ptr);
895     return;
896   }
897
898   const Constant *CI = dyn_cast<Constant>(I->get());
899   if (HasImplicitAddress && (!CI || !CI->isNullValue()))
900     Out << "(&";
901
902   writeOperandInternal(Ptr);
903
904   if (HasImplicitAddress && (!CI || !CI->isNullValue()))
905     Out << ")";
906
907   // Print out the -> operator if possible...
908   if (CI && CI->isNullValue() && I+1 != E) {
909     if ((*(I+1))->getType() == Type::UByteTy) {
910       Out << (HasImplicitAddress ? "." : "->");
911       Out << "field" << cast<ConstantUInt>(*(I+1))->getValue();
912       I += 2;
913     } else {  // First array index of 0: Just skip it
914       ++I;
915     }
916   }
917
918   for (; I != E; ++I)
919     if ((*I)->getType() == Type::LongTy) {
920       Out << "[((int) (";                 // sign-extend from 32 (to 64) bits
921       writeOperand(*I);
922       Out << " * sizeof(";
923       printType(cast<PointerType>(Ptr->getType())->getElementType());
924       Out << "))) / sizeof(";
925       printType(cast<PointerType>(Ptr->getType())->getElementType());
926       Out << ")]";
927     } else {
928       Out << ".field" << cast<ConstantUInt>(*I)->getValue();
929     }
930 }
931
932 void CWriter::visitLoadInst(LoadInst &I) {
933   Out << "*";
934   writeOperand(I.getOperand(0));
935 }
936
937 void CWriter::visitStoreInst(StoreInst &I) {
938   Out << "*";
939   writeOperand(I.getPointerOperand());
940   Out << " = ";
941   writeOperand(I.getOperand(0));
942 }
943
944 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
945   Out << "&";
946   printIndexingExpression(I.getPointerOperand(), I.idx_begin(), I.idx_end());
947 }
948
949 //===----------------------------------------------------------------------===//
950 //                       External Interface declaration
951 //===----------------------------------------------------------------------===//
952
953 Pass *createWriteToCPass(std::ostream &o) { return new CWriter(o); }