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