Fix bug: CBackend/2003-06-01-NullPointerType.ll
[oota-llvm.git] / lib / Target / CBackend / Writer.cpp
1 //===-- Writer.cpp - Library for converting LLVM code to C ----------------===//
2 //
3 // This library converts LLVM code to C code, compilable by GCC.
4 //
5 //===----------------------------------------------------------------------===//
6
7 #include "llvm/Assembly/CWriter.h"
8 #include "llvm/Constants.h"
9 #include "llvm/DerivedTypes.h"
10 #include "llvm/Module.h"
11 #include "llvm/Instructions.h"
12 #include "llvm/Pass.h"
13 #include "llvm/SymbolTable.h"
14 #include "llvm/Intrinsics.h"
15 #include "llvm/SlotCalculator.h"
16 #include "llvm/Analysis/FindUsedTypes.h"
17 #include "llvm/Analysis/ConstantsScanner.h"
18 #include "llvm/Support/InstVisitor.h"
19 #include "llvm/Support/InstIterator.h"
20 #include "Support/StringExtras.h"
21 #include "Support/STLExtras.h"
22 #include <algorithm>
23 #include <set>
24 #include <sstream>
25
26 namespace {
27   class CWriter : public Pass, public InstVisitor<CWriter> {
28     std::ostream &Out; 
29     SlotCalculator *Table;
30     const Module *TheModule;
31     std::map<const Type *, std::string> TypeNames;
32     std::set<const Value*> MangledGlobals;
33     bool needsMalloc;
34
35     std::map<const ConstantFP *, unsigned> FPConstantMap;
36   public:
37     CWriter(std::ostream &o) : Out(o) {}
38
39     void getAnalysisUsage(AnalysisUsage &AU) const {
40       AU.setPreservesAll();
41       AU.addRequired<FindUsedTypes>();
42     }
43
44     virtual bool run(Module &M) {
45       // Initialize
46       Table = new SlotCalculator(&M, false);
47       TheModule = &M;
48
49       // Ensure that all structure types have names...
50       bool Changed = nameAllUsedStructureTypes(M);
51
52       // Run...
53       printModule(&M);
54
55       // Free memory...
56       delete Table;
57       TypeNames.clear();
58       MangledGlobals.clear();
59       return false;
60     }
61
62     std::ostream &printType(std::ostream &Out, const Type *Ty,
63                             const std::string &VariableName = "",
64                             bool IgnoreName = false, bool namedContext = true);
65
66     void writeOperand(Value *Operand);
67     void writeOperandInternal(Value *Operand);
68
69     std::string getValueName(const Value *V);
70
71   private :
72     bool nameAllUsedStructureTypes(Module &M);
73     void printModule(Module *M);
74     void printSymbolTable(const SymbolTable &ST);
75     void printContainedStructs(const Type *Ty, std::set<const StructType *> &);
76     void printGlobal(const GlobalVariable *GV);
77     void printFunctionSignature(const Function *F, bool Prototype);
78
79     void printFunction(Function *);
80
81     void printConstant(Constant *CPV);
82     void printConstantArray(ConstantArray *CPA);
83
84     // isInlinableInst - Attempt to inline instructions into their uses to build
85     // trees as much as possible.  To do this, we have to consistently decide
86     // what is acceptable to inline, so that variable declarations don't get
87     // printed and an extra copy of the expr is not emitted.
88     //
89     static bool isInlinableInst(const Instruction &I) {
90       // Must be an expression, must be used exactly once.  If it is dead, we
91       // emit it inline where it would go.
92       if (I.getType() == Type::VoidTy || I.use_size() != 1 ||
93           isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) || 
94           isa<LoadInst>(I)) // Don't inline a load across a store!
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     void visitSwitchInst(SwitchInst &I);
107
108     void visitPHINode(PHINode &I);
109     void visitBinaryOperator(Instruction &I);
110
111     void visitCastInst (CastInst &I);
112     void visitCallInst (CallInst &I);
113     void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
114
115     void visitMallocInst(MallocInst &I);
116     void visitAllocaInst(AllocaInst &I);
117     void visitFreeInst  (FreeInst   &I);
118     void visitLoadInst  (LoadInst   &I);
119     void visitStoreInst (StoreInst  &I);
120     void visitGetElementPtrInst(GetElementPtrInst &I);
121     void visitVarArgInst(VarArgInst &I);
122
123     void visitInstruction(Instruction &I) {
124       std::cerr << "C Writer does not know about " << I;
125       abort();
126     }
127
128     void outputLValue(Instruction *I) {
129       Out << "  " << getValueName(I) << " = ";
130     }
131     void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
132                             unsigned Indent);
133     void printIndexingExpression(Value *Ptr, User::op_iterator I,
134                                  User::op_iterator E);
135   };
136 }
137
138 // We dont want identifier names with ., space, -  in them. 
139 // So we replace them with _
140 static std::string makeNameProper(std::string x) {
141   std::string tmp;
142   for (std::string::iterator sI = x.begin(), sEnd = x.end(); sI != sEnd; sI++)
143     switch (*sI) {
144     case '.': tmp += "d_"; break;
145     case ' ': tmp += "s_"; break;
146     case '-': tmp += "D_"; break;
147     default:  tmp += *sI;
148     }
149
150   return tmp;
151 }
152
153 std::string CWriter::getValueName(const Value *V) {
154   if (V->hasName()) {              // Print out the label if it exists...
155     if (isa<GlobalValue>(V) &&     // Do not mangle globals...
156         (cast<GlobalValue>(V)->hasExternalLinkage() &&// Unless it's internal or
157          !MangledGlobals.count(V))) // Unless the name would collide if we don't
158       return makeNameProper(V->getName());
159
160     return "l" + utostr(V->getType()->getUniqueID()) + "_" +
161            makeNameProper(V->getName());      
162   }
163
164   int Slot = Table->getValSlot(V);
165   assert(Slot >= 0 && "Invalid value!");
166   return "ltmp_" + itostr(Slot) + "_" + utostr(V->getType()->getUniqueID());
167 }
168
169 // A pointer type should not use parens around *'s alone, e.g., (**)
170 inline bool ptrTypeNameNeedsParens(const std::string &NameSoFar) {
171   return (NameSoFar.find_last_not_of('*') != std::string::npos);
172 }
173
174 // Pass the Type* and the variable name and this prints out the variable
175 // declaration.
176 //
177 std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
178                                  const std::string &NameSoFar,
179                                  bool IgnoreName, bool namedContext) {
180   if (Ty->isPrimitiveType())
181     switch (Ty->getPrimitiveID()) {
182     case Type::VoidTyID:   return Out << "void "               << NameSoFar;
183     case Type::BoolTyID:   return Out << "bool "               << NameSoFar;
184     case Type::UByteTyID:  return Out << "unsigned char "      << NameSoFar;
185     case Type::SByteTyID:  return Out << "signed char "        << NameSoFar;
186     case Type::UShortTyID: return Out << "unsigned short "     << NameSoFar;
187     case Type::ShortTyID:  return Out << "short "              << NameSoFar;
188     case Type::UIntTyID:   return Out << "unsigned "           << NameSoFar;
189     case Type::IntTyID:    return Out << "int "                << NameSoFar;
190     case Type::ULongTyID:  return Out << "unsigned long long " << NameSoFar;
191     case Type::LongTyID:   return Out << "signed long long "   << NameSoFar;
192     case Type::FloatTyID:  return Out << "float "              << NameSoFar;
193     case Type::DoubleTyID: return Out << "double "             << NameSoFar;
194     default :
195       std::cerr << "Unknown primitive type: " << Ty << "\n";
196       abort();
197     }
198   
199   // Check to see if the type is named.
200   if (!IgnoreName || isa<OpaqueType>(Ty)) {
201     std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
202     if (I != TypeNames.end()) {
203       return Out << I->second << " " << NameSoFar;
204     }
205   }
206
207   switch (Ty->getPrimitiveID()) {
208   case Type::FunctionTyID: {
209     const FunctionType *MTy = cast<FunctionType>(Ty);
210     std::stringstream FunctionInards; 
211     FunctionInards << " (" << NameSoFar << ") (";
212     for (FunctionType::ParamTypes::const_iterator
213            I = MTy->getParamTypes().begin(),
214            E = MTy->getParamTypes().end(); I != E; ++I) {
215       if (I != MTy->getParamTypes().begin())
216         FunctionInards << ", ";
217       printType(FunctionInards, *I, "");
218     }
219     if (MTy->isVarArg()) {
220       if (!MTy->getParamTypes().empty()) 
221         FunctionInards << ", ...";
222     } else if (MTy->getParamTypes().empty()) {
223       FunctionInards << "void";
224     }
225     FunctionInards << ")";
226     std::string tstr = FunctionInards.str();
227     printType(Out, MTy->getReturnType(), tstr);
228     return Out;
229   }
230   case Type::StructTyID: {
231     const StructType *STy = cast<StructType>(Ty);
232     Out << NameSoFar + " {\n";
233     unsigned Idx = 0;
234     for (StructType::ElementTypes::const_iterator
235            I = STy->getElementTypes().begin(),
236            E = STy->getElementTypes().end(); I != E; ++I) {
237       Out << "  ";
238       printType(Out, *I, "field" + utostr(Idx++));
239       Out << ";\n";
240     }
241     return Out << "}";
242   }  
243
244   case Type::PointerTyID: {
245     const PointerType *PTy = cast<PointerType>(Ty);
246     std::string ptrName = "*" + NameSoFar;
247
248     // Do not need parens around "* NameSoFar" if NameSoFar consists only
249     // of zero or more '*' chars *and* this is not an unnamed pointer type
250     // such as the result type in a cast statement.  Otherwise, enclose in ( ).
251     if (ptrTypeNameNeedsParens(NameSoFar) || !namedContext || 
252         PTy->getElementType()->getPrimitiveID() == Type::ArrayTyID)
253       ptrName = "(" + ptrName + ")";    // 
254
255     return printType(Out, PTy->getElementType(), ptrName);
256   }Out <<"--";
257
258   case Type::ArrayTyID: {
259     const ArrayType *ATy = cast<ArrayType>(Ty);
260     unsigned NumElements = ATy->getNumElements();
261     return printType(Out, ATy->getElementType(),
262                      NameSoFar + "[" + utostr(NumElements) + "]");
263   }
264
265   case Type::OpaqueTyID: {
266     static int Count = 0;
267     std::string TyName = "struct opaque_" + itostr(Count++);
268     assert(TypeNames.find(Ty) == TypeNames.end());
269     TypeNames[Ty] = TyName;
270     return Out << TyName << " " << NameSoFar;
271   }
272   default:
273     assert(0 && "Unhandled case in getTypeProps!");
274     abort();
275   }
276
277   return Out;
278 }
279
280 void CWriter::printConstantArray(ConstantArray *CPA) {
281
282   // As a special case, print the array as a string if it is an array of
283   // ubytes or an array of sbytes with positive values.
284   // 
285   const Type *ETy = CPA->getType()->getElementType();
286   bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
287
288   // Make sure the last character is a null char, as automatically added by C
289   if (CPA->getNumOperands() == 0 ||
290       !cast<Constant>(*(CPA->op_end()-1))->isNullValue())
291     isString = false;
292   
293   if (isString) {
294     Out << "\"";
295     // Do not include the last character, which we know is null
296     for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
297       unsigned char C = (ETy == Type::SByteTy) ?
298         (unsigned char)cast<ConstantSInt>(CPA->getOperand(i))->getValue() :
299         (unsigned char)cast<ConstantUInt>(CPA->getOperand(i))->getValue();
300       
301       if (isprint(C)) {
302         if (C == '"' || C == '\\')
303           Out << "\\" << C;
304         else
305           Out << C;
306       } else {
307         switch (C) {
308         case '\n': Out << "\\n"; break;
309         case '\t': Out << "\\t"; break;
310         case '\r': Out << "\\r"; break;
311         case '\v': Out << "\\v"; break;
312         case '\a': Out << "\\a"; break;
313         case '\"': Out << "\\\""; break;
314         case '\'': Out << "\\\'"; break;           
315         default:
316           Out << "\\x";
317           Out << ( C/16  < 10) ? ( C/16 +'0') : ( C/16 -10+'A');
318           Out << ((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A');
319           break;
320         }
321       }
322     }
323     Out << "\"";
324   } else {
325     Out << "{";
326     if (CPA->getNumOperands()) {
327       Out << " ";
328       printConstant(cast<Constant>(CPA->getOperand(0)));
329       for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
330         Out << ", ";
331         printConstant(cast<Constant>(CPA->getOperand(i)));
332       }
333     }
334     Out << " }";
335   }
336 }
337
338
339 // printConstant - The LLVM Constant to C Constant converter.
340 void CWriter::printConstant(Constant *CPV) {
341   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
342     switch (CE->getOpcode()) {
343     case Instruction::Cast:
344       Out << "((";
345       printType(Out, CPV->getType());
346       Out << ")";
347       printConstant(CE->getOperand(0));
348       Out << ")";
349       return;
350
351     case Instruction::GetElementPtr:
352       Out << "(&(";
353       printIndexingExpression(CE->getOperand(0),
354                               CPV->op_begin()+1, CPV->op_end());
355       Out << "))";
356       return;
357     case Instruction::Add:
358       Out << "(";
359       printConstant(CE->getOperand(0));
360       Out << " + ";
361       printConstant(CE->getOperand(1));
362       Out << ")";
363       return;
364     case Instruction::Sub:
365       Out << "(";
366       printConstant(CE->getOperand(0));
367       Out << " - ";
368       printConstant(CE->getOperand(1));
369       Out << ")";
370       return;
371
372     default:
373       std::cerr << "CWriter Error: Unhandled constant expression: "
374                 << CE << "\n";
375       abort();
376     }
377   }
378
379   switch (CPV->getType()->getPrimitiveID()) {
380   case Type::BoolTyID:
381     Out << (CPV == ConstantBool::False ? "0" : "1"); break;
382   case Type::SByteTyID:
383   case Type::ShortTyID:
384     Out << cast<ConstantSInt>(CPV)->getValue(); break;
385   case Type::IntTyID:
386     if ((int)cast<ConstantSInt>(CPV)->getValue() == (int)0x80000000)
387       Out << "((int)0x80000000)";   // Handle MININT specially to avoid warning
388     else
389       Out << cast<ConstantSInt>(CPV)->getValue();
390     break;
391
392   case Type::LongTyID:
393     Out << cast<ConstantSInt>(CPV)->getValue() << "ll"; break;
394
395   case Type::UByteTyID:
396   case Type::UShortTyID:
397     Out << cast<ConstantUInt>(CPV)->getValue(); break;
398   case Type::UIntTyID:
399     Out << cast<ConstantUInt>(CPV)->getValue() << "u"; break;
400   case Type::ULongTyID:
401     Out << cast<ConstantUInt>(CPV)->getValue() << "ull"; break;
402
403   case Type::FloatTyID:
404   case Type::DoubleTyID: {
405     ConstantFP *FPC = cast<ConstantFP>(CPV);
406     std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
407     if (I != FPConstantMap.end()) {
408       // Because of FP precision problems we must load from a stack allocated
409       // value that holds the value in hex.
410       Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
411           << "*)&FloatConstant" << I->second << ")";
412     } else {
413       Out << FPC->getValue();
414     }
415     break;
416   }
417
418   case Type::ArrayTyID:
419     printConstantArray(cast<ConstantArray>(CPV));
420     break;
421
422   case Type::StructTyID: {
423     Out << "{";
424     if (CPV->getNumOperands()) {
425       Out << " ";
426       printConstant(cast<Constant>(CPV->getOperand(0)));
427       for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
428         Out << ", ";
429         printConstant(cast<Constant>(CPV->getOperand(i)));
430       }
431     }
432     Out << " }";
433     break;
434   }
435
436   case Type::PointerTyID:
437     if (isa<ConstantPointerNull>(CPV)) {
438       Out << "((";
439       printType(Out, CPV->getType());
440       Out << ")/*NULL*/0)";
441       break;
442     } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CPV)) {
443       writeOperand(CPR->getValue());
444       break;
445     }
446     // FALL THROUGH
447   default:
448     std::cerr << "Unknown constant type: " << CPV << "\n";
449     abort();
450   }
451 }
452
453 void CWriter::writeOperandInternal(Value *Operand) {
454   if (Instruction *I = dyn_cast<Instruction>(Operand))
455     if (isInlinableInst(*I)) {
456       // Should we inline this instruction to build a tree?
457       Out << "(";
458       visit(*I);
459       Out << ")";    
460       return;
461     }
462   
463   if (Operand->hasName()) {  
464     Out << getValueName(Operand);
465   } else if (Constant *CPV = dyn_cast<Constant>(Operand)) {
466     printConstant(CPV); 
467   } else {
468     int Slot = Table->getValSlot(Operand);
469     assert(Slot >= 0 && "Malformed LLVM!");
470     Out << "ltmp_" << Slot << "_" << Operand->getType()->getUniqueID();
471   }
472 }
473
474 void CWriter::writeOperand(Value *Operand) {
475   if (isa<GlobalVariable>(Operand))
476     Out << "(&";  // Global variables are references as their addresses by llvm
477
478   writeOperandInternal(Operand);
479
480   if (isa<GlobalVariable>(Operand))
481     Out << ")";
482 }
483
484 // nameAllUsedStructureTypes - If there are structure types in the module that
485 // are used but do not have names assigned to them in the symbol table yet then
486 // we assign them names now.
487 //
488 bool CWriter::nameAllUsedStructureTypes(Module &M) {
489   // Get a set of types that are used by the program...
490   std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
491
492   // Loop over the module symbol table, removing types from UT that are already
493   // named.
494   //
495   SymbolTable &MST = M.getSymbolTable();
496   if (MST.find(Type::TypeTy) != MST.end())
497     for (SymbolTable::type_iterator I = MST.type_begin(Type::TypeTy),
498            E = MST.type_end(Type::TypeTy); I != E; ++I)
499       UT.erase(cast<Type>(I->second));
500
501   // UT now contains types that are not named.  Loop over it, naming structure
502   // types.
503   //
504   bool Changed = false;
505   for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
506        I != E; ++I)
507     if (const StructType *ST = dyn_cast<StructType>(*I)) {
508       ((Value*)ST)->setName("unnamed", &MST);
509       Changed = true;
510     }
511   return Changed;
512 }
513
514 static void generateAllocaDecl(std::ostream& Out) {
515   // On SunOS, we need to insert the alloca macro & proto for the builtin.
516   Out << "#ifdef sun\n"
517       << "extern void *__builtin_alloca(unsigned long);\n"
518       << "#define alloca(x) __builtin_alloca(x)\n"
519       << "#else\n"
520       << "#include <alloca.h>\n"
521       << "#endif\n\n";
522 }
523
524 void CWriter::printModule(Module *M) {
525   // Calculate which global values have names that will collide when we throw
526   // away type information.
527   {  // Scope to delete the FoundNames set when we are done with it...
528     std::set<std::string> FoundNames;
529     for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
530       if (I->hasName())                      // If the global has a name...
531         if (FoundNames.count(I->getName()))  // And the name is already used
532           MangledGlobals.insert(I);          // Mangle the name
533         else
534           FoundNames.insert(I->getName());   // Otherwise, keep track of name
535
536     for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
537       if (I->hasName())                      // If the global has a name...
538         if (FoundNames.count(I->getName()))  // And the name is already used
539           MangledGlobals.insert(I);          // Mangle the name
540         else
541           FoundNames.insert(I->getName());   // Otherwise, keep track of name
542   }
543
544   // get declaration for alloca
545   Out << "/* Provide Declarations */\n";
546   generateAllocaDecl(Out);
547   Out << "#include <stdarg.h>\n";
548   Out << "#include <setjmp.h>\n";
549   
550   // Provide a definition for `bool' if not compiling with a C++ compiler.
551   Out << "\n"
552       << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
553     
554       << "\n\n/* Support for floating point constants */\n"
555       << "typedef unsigned long long ConstantDoubleTy;\n"
556       << "typedef unsigned int        ConstantFloatTy;\n"
557     
558       << "\n\n/* Global Declarations */\n";
559
560   // First output all the declarations for the program, because C requires
561   // Functions & globals to be declared before they are used.
562   //
563
564   // Loop over the symbol table, emitting all named constants...
565   printSymbolTable(M->getSymbolTable());
566
567   // Global variable declarations...
568   if (!M->gempty()) {
569     Out << "\n/* External Global Variable Declarations */\n";
570     for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) {
571       if (I->hasExternalLinkage()) {
572         Out << "extern ";
573         printType(Out, I->getType()->getElementType(), getValueName(I));
574         Out << ";\n";
575       }
576     }
577   }
578
579   // Function declarations
580   if (!M->empty()) {
581     Out << "\n/* Function Declarations */\n";
582     needsMalloc = true;
583     for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
584       // If the function is external and the name collides don't print it.
585       // Sometimes the bytecode likes to have multiple "declarations" for
586       // external functions
587       if ((I->hasInternalLinkage() || !MangledGlobals.count(I)) &&
588           !I->getIntrinsicID()) {
589         printFunctionSignature(I, true);
590         Out << ";\n";
591       }
592     }
593   }
594
595   // Print Malloc prototype if needed
596   if (needsMalloc){
597     Out << "\n/* Malloc to make sun happy */\n";
598     Out << "extern void * malloc(size_t);\n\n";
599   }
600
601   // Output the global variable declerations
602   if (!M->gempty()) {
603     Out << "\n\n/* Global Variable Declerations */\n";
604     for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
605       if (!I->isExternal()) {
606         Out << "extern ";
607         printType(Out, I->getType()->getElementType(), getValueName(I));
608       
609         Out << ";\n";
610       }
611   }
612
613   
614   // Output the global variable definitions and contents...
615   if (!M->gempty()) {
616     Out << "\n\n/* Global Variable Definitions and Initialization */\n";
617     for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
618       if (!I->isExternal()) {
619         if (I->hasInternalLinkage())
620           Out << "static ";
621         printType(Out, I->getType()->getElementType(), getValueName(I));
622       
623         Out << " = " ;
624         writeOperand(I->getInitializer());
625         Out << ";\n";
626       }
627   }
628
629   // Output all of the functions...
630   if (!M->empty()) {
631     Out << "\n\n/* Function Bodies */\n";
632     for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
633       printFunction(I);
634   }
635 }
636
637
638 /// printSymbolTable - Run through symbol table looking for type names.  If a
639 /// type name is found, emit it's declaration...
640 ///
641 void CWriter::printSymbolTable(const SymbolTable &ST) {
642   // If there are no type names, exit early.
643   if (ST.find(Type::TypeTy) == ST.end())
644     return;
645
646   // We are only interested in the type plane of the symbol table...
647   SymbolTable::type_const_iterator I   = ST.type_begin(Type::TypeTy);
648   SymbolTable::type_const_iterator End = ST.type_end(Type::TypeTy);
649   
650   // Print out forward declarations for structure types before anything else!
651   Out << "/* Structure forward decls */\n";
652   for (; I != End; ++I)
653     if (const Type *STy = dyn_cast<StructType>(I->second)) {
654       std::string Name = "struct l_" + makeNameProper(I->first);
655       Out << Name << ";\n";
656       TypeNames.insert(std::make_pair(STy, Name));
657     }
658
659   Out << "\n";
660
661   // Now we can print out typedefs...
662   Out << "/* Typedefs */\n";
663   for (I = ST.type_begin(Type::TypeTy); I != End; ++I) {
664     const Type *Ty = cast<Type>(I->second);
665     std::string Name = "l_" + makeNameProper(I->first);
666     Out << "typedef ";
667     printType(Out, Ty, Name);
668     Out << ";\n";
669   }
670
671   Out << "\n";
672
673   // Keep track of which structures have been printed so far...
674   std::set<const StructType *> StructPrinted;
675
676   // Loop over all structures then push them into the stack so they are
677   // printed in the correct order.
678   //
679   Out << "/* Structure contents */\n";
680   for (I = ST.type_begin(Type::TypeTy); I != End; ++I)
681     if (const StructType *STy = dyn_cast<StructType>(I->second))
682       printContainedStructs(STy, StructPrinted);
683 }
684
685 // Push the struct onto the stack and recursively push all structs
686 // this one depends on.
687 void CWriter::printContainedStructs(const Type *Ty,
688                                     std::set<const StructType*> &StructPrinted){
689   if (const StructType *STy = dyn_cast<StructType>(Ty)){
690     //Check to see if we have already printed this struct
691     if (StructPrinted.count(STy) == 0) {
692       // Print all contained types first...
693       for (StructType::ElementTypes::const_iterator
694              I = STy->getElementTypes().begin(),
695              E = STy->getElementTypes().end(); I != E; ++I) {
696         const Type *Ty1 = I->get();
697         if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
698           printContainedStructs(*I, StructPrinted);
699       }
700       
701       //Print structure type out..
702       StructPrinted.insert(STy);
703       std::string Name = TypeNames[STy];  
704       printType(Out, STy, Name, true);
705       Out << ";\n\n";
706     }
707
708     // If it is an array, check contained types and continue
709   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)){
710     const Type *Ty1 = ATy->getElementType();
711     if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
712       printContainedStructs(Ty1, StructPrinted);
713   }
714 }
715
716
717 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
718   // If the program provides it's own malloc prototype we don't need
719   // to include the general one.  
720   if (getValueName(F) == "malloc")
721     needsMalloc = false;
722   if (F->hasInternalLinkage()) Out << "static ";  
723   // Loop over the arguments, printing them...
724   const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
725   
726   std::stringstream FunctionInards; 
727     
728   // Print out the name...
729   FunctionInards << getValueName(F) << "(";
730     
731   if (!F->isExternal()) {
732     if (!F->aempty()) {
733       std::string ArgName;
734       if (F->abegin()->hasName() || !Prototype)
735         ArgName = getValueName(F->abegin());
736       printType(FunctionInards, F->afront().getType(), ArgName);
737       for (Function::const_aiterator I = ++F->abegin(), E = F->aend();
738            I != E; ++I) {
739         FunctionInards << ", ";
740         if (I->hasName() || !Prototype)
741           ArgName = getValueName(I);
742         else 
743           ArgName = "";
744         printType(FunctionInards, I->getType(), ArgName);
745       }
746     }
747   } else {
748     // Loop over the arguments, printing them...
749     for (FunctionType::ParamTypes::const_iterator I = 
750            FT->getParamTypes().begin(),
751            E = FT->getParamTypes().end(); I != E; ++I) {
752       if (I != FT->getParamTypes().begin()) FunctionInards << ", ";
753       printType(FunctionInards, *I);
754     }
755   }
756
757   // Finish printing arguments... if this is a vararg function, print the ...,
758   // unless there are no known types, in which case, we just emit ().
759   //
760   if (FT->isVarArg() && !FT->getParamTypes().empty()) {
761     if (FT->getParamTypes().size()) FunctionInards << ", ";
762     FunctionInards << "...";  // Output varargs portion of signature!
763   }
764   FunctionInards << ")";
765   // Print out the return type and the entire signature for that matter
766   printType(Out, F->getReturnType(), FunctionInards.str());
767   
768 }
769
770
771 void CWriter::printFunction(Function *F) {
772   if (F->isExternal()) return;
773
774   Table->incorporateFunction(F);
775
776   printFunctionSignature(F, false);
777   Out << " {\n";
778
779   // print local variable information for the function
780   for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
781     if ((*I)->getType() != Type::VoidTy && !isInlinableInst(**I)) {
782       Out << "  ";
783       printType(Out, (*I)->getType(), getValueName(*I));
784       Out << ";\n";
785
786       if (isa<PHINode>(*I)) {  // Print out PHI node temporaries as well...
787         Out << "  ";
788         printType(Out, (*I)->getType(), getValueName(*I)+"__PHI_TEMPORARY");
789         Out << ";\n";
790       }
791     }
792
793   Out << "\n";
794
795   // Scan the function for floating point constants.  If any FP constant is used
796   // in the function, we want to redirect it here so that we do not depend on
797   // the precision of the printed form.
798   //
799   unsigned FPCounter = 0;
800   for (constant_iterator I = constant_begin(F), E = constant_end(F); I != E;++I)
801     if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
802       if (FPConstantMap.find(FPC) == FPConstantMap.end()) {
803         double Val = FPC->getValue();
804         
805         FPConstantMap[FPC] = FPCounter;  // Number the FP constants
806
807         if (FPC->getType() == Type::DoubleTy)
808           Out << "  const ConstantDoubleTy FloatConstant" << FPCounter++
809               << " = 0x" << std::hex << *(unsigned long long*)&Val << std::dec
810               << ";    /* " << Val << " */\n";
811         else if (FPC->getType() == Type::FloatTy) {
812           float fVal = Val;
813           Out << "  const ConstantFloatTy FloatConstant" << FPCounter++
814               << " = 0x" << std::hex << *(unsigned*)&fVal << std::dec
815               << ";    /* " << Val << " */\n";
816         } else
817           assert(0 && "Unknown float type!");
818       }
819
820   Out << "\n";
821  
822   // print the basic blocks
823   for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
824     BasicBlock *Prev = BB->getPrev();
825
826     // Don't print the label for the basic block if there are no uses, or if the
827     // only terminator use is the precessor basic block's terminator.  We have
828     // to scan the use list because PHI nodes use basic blocks too but do not
829     // require a label to be generated.
830     //
831     bool NeedsLabel = false;
832     for (Value::use_iterator UI = BB->use_begin(), UE = BB->use_end();
833          UI != UE; ++UI)
834       if (TerminatorInst *TI = dyn_cast<TerminatorInst>(*UI))
835         if (TI != Prev->getTerminator() ||
836             isa<SwitchInst>(Prev->getTerminator())) {
837           NeedsLabel = true;
838           break;        
839         }
840
841     if (NeedsLabel) Out << getValueName(BB) << ":\n";
842
843     // Output all of the instructions in the basic block...
844     for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E; ++II){
845       if (!isInlinableInst(*II)) {
846         if (II->getType() != Type::VoidTy)
847           outputLValue(II);
848         else
849           Out << "  ";
850         visit(*II);
851         Out << ";\n";
852       }
853     }
854
855     // Don't emit prefix or suffix for the terminator...
856     visit(*BB->getTerminator());
857   }
858   
859   Out << "}\n\n";
860   Table->purgeFunction();
861   FPConstantMap.clear();
862 }
863
864 // Specific Instruction type classes... note that all of the casts are
865 // neccesary because we use the instruction classes as opaque types...
866 //
867 void CWriter::visitReturnInst(ReturnInst &I) {
868   // Don't output a void return if this is the last basic block in the function
869   if (I.getNumOperands() == 0 && 
870       &*--I.getParent()->getParent()->end() == I.getParent() &&
871       !I.getParent()->size() == 1) {
872     return;
873   }
874
875   Out << "  return";
876   if (I.getNumOperands()) {
877     Out << " ";
878     writeOperand(I.getOperand(0));
879   }
880   Out << ";\n";
881 }
882
883 void CWriter::visitSwitchInst(SwitchInst &SI) {
884   Out << "  switch (";
885   writeOperand(SI.getOperand(0));
886   Out << ") {\n  default:\n";
887   printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
888   Out << ";\n";
889   for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
890     Out << "  case ";
891     writeOperand(SI.getOperand(i));
892     Out << ":\n";
893     BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
894     printBranchToBlock(SI.getParent(), Succ, 2);
895     if (Succ == SI.getParent()->getNext())
896       Out << "    break;\n";
897   }
898   Out << "  }\n";
899 }
900
901
902 static bool isGotoCodeNeccessary(BasicBlock *From, BasicBlock *To) {
903   // If PHI nodes need copies, we need the copy code...
904   if (isa<PHINode>(To->front()) ||
905       From->getNext() != To)      // Not directly successor, need goto
906     return true;
907
908   // Otherwise we don't need the code.
909   return false;
910 }
911
912 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
913                                            unsigned Indent) {
914   for (BasicBlock::iterator I = Succ->begin();
915        PHINode *PN = dyn_cast<PHINode>(I); ++I) {
916     //  now we have to do the printing
917     Out << std::string(Indent, ' ');
918     Out << "  " << getValueName(I) << "__PHI_TEMPORARY = ";
919     writeOperand(PN->getIncomingValue(PN->getBasicBlockIndex(CurBB)));
920     Out << ";   /* for PHI node */\n";
921   }
922
923   if (CurBB->getNext() != Succ) {
924     Out << std::string(Indent, ' ') << "  goto ";
925     writeOperand(Succ);
926     Out << ";\n";
927   }
928 }
929
930 // Brach instruction printing - Avoid printing out a brach to a basic block that
931 // immediately succeeds the current one.
932 //
933 void CWriter::visitBranchInst(BranchInst &I) {
934   if (I.isConditional()) {
935     if (isGotoCodeNeccessary(I.getParent(), I.getSuccessor(0))) {
936       Out << "  if (";
937       writeOperand(I.getCondition());
938       Out << ") {\n";
939       
940       printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
941       
942       if (isGotoCodeNeccessary(I.getParent(), I.getSuccessor(1))) {
943         Out << "  } else {\n";
944         printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
945       }
946     } else {
947       // First goto not neccesary, assume second one is...
948       Out << "  if (!";
949       writeOperand(I.getCondition());
950       Out << ") {\n";
951
952       printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
953     }
954
955     Out << "  }\n";
956   } else {
957     printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
958   }
959   Out << "\n";
960 }
961
962 // PHI nodes get copied into temporary values at the end of predecessor basic
963 // blocks.  We now need to copy these temporary values into the REAL value for
964 // the PHI.
965 void CWriter::visitPHINode(PHINode &I) {
966   writeOperand(&I);
967   Out << "__PHI_TEMPORARY";
968 }
969
970
971 void CWriter::visitBinaryOperator(Instruction &I) {
972   // binary instructions, shift instructions, setCond instructions.
973   assert(!isa<PointerType>(I.getType()));
974       
975   writeOperand(I.getOperand(0));
976
977   switch (I.getOpcode()) {
978   case Instruction::Add: Out << " + "; break;
979   case Instruction::Sub: Out << " - "; break;
980   case Instruction::Mul: Out << "*"; break;
981   case Instruction::Div: Out << "/"; break;
982   case Instruction::Rem: Out << "%"; break;
983   case Instruction::And: Out << " & "; break;
984   case Instruction::Or: Out << " | "; break;
985   case Instruction::Xor: Out << " ^ "; break;
986   case Instruction::SetEQ: Out << " == "; break;
987   case Instruction::SetNE: Out << " != "; break;
988   case Instruction::SetLE: Out << " <= "; break;
989   case Instruction::SetGE: Out << " >= "; break;
990   case Instruction::SetLT: Out << " < "; break;
991   case Instruction::SetGT: Out << " > "; break;
992   case Instruction::Shl : Out << " << "; break;
993   case Instruction::Shr : Out << " >> "; break;
994   default: std::cerr << "Invalid operator type!" << I; abort();
995   }
996
997   writeOperand(I.getOperand(1));
998 }
999
1000 void CWriter::visitCastInst(CastInst &I) {
1001   if (I.getType() == Type::BoolTy) {
1002     Out << "(";
1003     writeOperand(I.getOperand(0));
1004     Out << " != 0)";
1005     return;
1006   }
1007   Out << "(";
1008   printType(Out, I.getType(), "", /*ignoreName*/false, /*namedContext*/false);
1009   Out << ")";
1010   if (isa<PointerType>(I.getType())&&I.getOperand(0)->getType()->isIntegral() ||
1011       isa<PointerType>(I.getOperand(0)->getType())&&I.getType()->isIntegral()) {
1012     // Avoid "cast to pointer from integer of different size" warnings
1013     Out << "(long)";  
1014   }
1015   
1016   writeOperand(I.getOperand(0));
1017 }
1018
1019 void CWriter::visitCallInst(CallInst &I) {
1020   // Handle intrinsic function calls first...
1021   if (Function *F = I.getCalledFunction())
1022     if (LLVMIntrinsic::ID ID = (LLVMIntrinsic::ID)F->getIntrinsicID()) {
1023       switch (ID) {
1024       default:  assert(0 && "Unknown LLVM intrinsic!");
1025       case LLVMIntrinsic::va_start: 
1026         Out << "va_start((va_list)*";
1027         writeOperand(I.getOperand(1));
1028         Out << ", ";
1029         // Output the last argument to the enclosing function...
1030         writeOperand(&I.getParent()->getParent()->aback());
1031         Out << ")";
1032         return;
1033       case LLVMIntrinsic::va_end:
1034         Out << "va_end((va_list)*";
1035         writeOperand(I.getOperand(1));
1036         Out << ")";
1037         return;
1038       case LLVMIntrinsic::va_copy:
1039         Out << "va_copy((va_list)*";
1040         writeOperand(I.getOperand(1));
1041         Out << ", (va_list)";
1042         writeOperand(I.getOperand(2));
1043         Out << ")";
1044         return;
1045         
1046       case LLVMIntrinsic::setjmp:
1047         Out << "setjmp((jmp_buf)";
1048         writeOperand(I.getOperand(1));
1049         Out << ")";
1050         return;
1051       case LLVMIntrinsic::longjmp:
1052         Out << "longjmp((jmp_buf)";
1053         writeOperand(I.getOperand(1));
1054         Out << ", ";
1055         writeOperand(I.getOperand(2));
1056         Out << ")";
1057         return;
1058       }
1059     }
1060
1061   const PointerType  *PTy   = cast<PointerType>(I.getCalledValue()->getType());
1062   const FunctionType *FTy   = cast<FunctionType>(PTy->getElementType());
1063   const Type         *RetTy = FTy->getReturnType();
1064   
1065   writeOperand(I.getOperand(0));
1066   Out << "(";
1067
1068   if (I.getNumOperands() > 1) {
1069     writeOperand(I.getOperand(1));
1070
1071     for (unsigned op = 2, Eop = I.getNumOperands(); op != Eop; ++op) {
1072       Out << ", ";
1073       writeOperand(I.getOperand(op));
1074     }
1075   }
1076   Out << ")";
1077 }  
1078
1079 void CWriter::visitMallocInst(MallocInst &I) {
1080   Out << "(";
1081   printType(Out, I.getType());
1082   Out << ")malloc(sizeof(";
1083   printType(Out, I.getType()->getElementType());
1084   Out << ")";
1085
1086   if (I.isArrayAllocation()) {
1087     Out << " * " ;
1088     writeOperand(I.getOperand(0));
1089   }
1090   Out << ")";
1091 }
1092
1093 void CWriter::visitAllocaInst(AllocaInst &I) {
1094   Out << "(";
1095   printType(Out, I.getType());
1096   Out << ") alloca(sizeof(";
1097   printType(Out, I.getType()->getElementType());
1098   Out << ")";
1099   if (I.isArrayAllocation()) {
1100     Out << " * " ;
1101     writeOperand(I.getOperand(0));
1102   }
1103   Out << ")";
1104 }
1105
1106 void CWriter::visitFreeInst(FreeInst &I) {
1107   Out << "free(";
1108   writeOperand(I.getOperand(0));
1109   Out << ")";
1110 }
1111
1112 void CWriter::printIndexingExpression(Value *Ptr, User::op_iterator I,
1113                                       User::op_iterator E) {
1114   bool HasImplicitAddress = false;
1115   // If accessing a global value with no indexing, avoid *(&GV) syndrome
1116   if (GlobalValue *V = dyn_cast<GlobalValue>(Ptr)) {
1117     HasImplicitAddress = true;
1118   } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Ptr)) {
1119     HasImplicitAddress = true;
1120     Ptr = CPR->getValue();         // Get to the global...
1121   }
1122
1123   if (I == E) {
1124     if (!HasImplicitAddress)
1125       Out << "*";  // Implicit zero first argument: '*x' is equivalent to 'x[0]'
1126
1127     writeOperandInternal(Ptr);
1128     return;
1129   }
1130
1131   const Constant *CI = dyn_cast<Constant>(I);
1132   if (HasImplicitAddress && (!CI || !CI->isNullValue()))
1133     Out << "(&";
1134
1135   writeOperandInternal(Ptr);
1136
1137   if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
1138     Out << ")";
1139     HasImplicitAddress = false;  // HIA is only true if we haven't addressed yet
1140   }
1141
1142   assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
1143          "Can only have implicit address with direct accessing");
1144
1145   if (HasImplicitAddress) {
1146     ++I;
1147   } else if (CI && CI->isNullValue() && I+1 != E) {
1148     // Print out the -> operator if possible...
1149     if ((*(I+1))->getType() == Type::UByteTy) {
1150       Out << (HasImplicitAddress ? "." : "->");
1151       Out << "field" << cast<ConstantUInt>(*(I+1))->getValue();
1152       I += 2;
1153     } 
1154   }
1155
1156   for (; I != E; ++I)
1157     if ((*I)->getType() == Type::LongTy) {
1158       Out << "[";
1159       writeOperand(*I);
1160       Out << "]";
1161     } else {
1162       Out << ".field" << cast<ConstantUInt>(*I)->getValue();
1163     }
1164 }
1165
1166 void CWriter::visitLoadInst(LoadInst &I) {
1167   Out << "*";
1168   writeOperand(I.getOperand(0));
1169 }
1170
1171 void CWriter::visitStoreInst(StoreInst &I) {
1172   Out << "*";
1173   writeOperand(I.getPointerOperand());
1174   Out << " = ";
1175   writeOperand(I.getOperand(0));
1176 }
1177
1178 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
1179   Out << "&";
1180   printIndexingExpression(I.getPointerOperand(), I.idx_begin(), I.idx_end());
1181 }
1182
1183 void CWriter::visitVarArgInst(VarArgInst &I) {
1184   Out << "va_arg((va_list)*";
1185   writeOperand(I.getOperand(0));
1186   Out << ", ";
1187   printType(Out, I.getType(), "", /*ignoreName*/false, /*namedContext*/false);
1188   Out << ")";  
1189 }
1190
1191
1192 //===----------------------------------------------------------------------===//
1193 //                       External Interface declaration
1194 //===----------------------------------------------------------------------===//
1195
1196 Pass *createWriteToCPass(std::ostream &o) { return new CWriter(o); }