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