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