Gut the type printing code so there is only one copy of it instead of 3
[oota-llvm.git] / lib / Target / CBackend / CBackend.cpp
1 //===-- Writer.cpp - Library for writing C files --------------------------===//
2 //
3 // This library implements the functionality defined in llvm/Assembly/CWriter.h
4 // and CLocalVars.h
5 //
6 // TODO : Recursive types.
7 //
8 //===-----------------------------------------------------------------------==//
9
10 #include "llvm/Assembly/CWriter.h"
11 #include "CLocalVars.h"
12 #include "llvm/SlotCalculator.h"
13 #include "llvm/Constants.h"
14 #include "llvm/DerivedTypes.h"
15 #include "llvm/Module.h"
16 #include "llvm/GlobalVariable.h"
17 #include "llvm/Function.h"
18 #include "llvm/Argument.h"
19 #include "llvm/BasicBlock.h"
20 #include "llvm/iMemory.h"
21 #include "llvm/iTerminators.h"
22 #include "llvm/iPHINode.h"
23 #include "llvm/iOther.h"
24 #include "llvm/iOperators.h"
25 #include "llvm/SymbolTable.h"
26 #include "llvm/Support/InstVisitor.h"
27 #include "Support/StringExtras.h"
28 #include "Support/STLExtras.h"
29
30 #include <algorithm>
31 #include <strstream>
32 using std::string;
33 using std::map;
34 using std::vector;
35 using std::ostream;
36
37 //===-----------------------------------------------------------------------==//
38 //
39 // Implementation of the CLocalVars methods
40
41 // Appends a variable to the LocalVars map if it does not already exist
42 // Also check that the type exists on the map.
43 void CLocalVars::addLocalVar(const Type *t, const string & var) {
44   if (!LocalVars.count(t) || 
45       find(LocalVars[t].begin(), LocalVars[t].end(), var) 
46       == LocalVars[t].end()) {
47       LocalVars[t].push_back(var);
48   } 
49 }
50
51 static std::string getConstStrValue(const Constant* CPV);
52
53
54 static std::string getConstArrayStrValue(const Constant* CPV) {
55   std::string Result;
56   
57   // As a special case, print the array as a string if it is an array of
58   // ubytes or an array of sbytes with positive values.
59   // 
60   const Type *ETy = cast<ArrayType>(CPV->getType())->getElementType();
61   bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
62
63   if (ETy == Type::SByteTy) {
64     for (unsigned i = 0; i < CPV->getNumOperands(); ++i)
65       if (ETy == Type::SByteTy &&
66           cast<ConstantSInt>(CPV->getOperand(i))->getValue() < 0) {
67         isString = false;
68         break;
69       }
70   }
71   if (isString) {
72     // Make sure the last character is a null char, as automatically added by C
73     if (CPV->getNumOperands() == 0 ||
74         !cast<Constant>(*(CPV->op_end()-1))->isNullValue())
75       isString = false;
76   }
77   
78   if (isString) {
79     Result = "\"";
80     // Do not include the last character, which we know is null
81     for (unsigned i = 0, e = CPV->getNumOperands()-1; i != e; ++i) {
82       unsigned char C = (ETy == Type::SByteTy) ?
83         (unsigned char)cast<ConstantSInt>(CPV->getOperand(i))->getValue() :
84         (unsigned char)cast<ConstantUInt>(CPV->getOperand(i))->getValue();
85       
86       if (isprint(C)) {
87         Result += C;
88       } else {
89         switch (C) {
90         case '\n': Result += "\\n"; break;
91         case '\t': Result += "\\t"; break;
92         case '\r': Result += "\\r"; break;
93         case '\v': Result += "\\v"; break;
94         case '\a': Result += "\\a"; break;
95         default:
96           Result += "\\x";
97           Result += ( C/16  < 10) ? ( C/16 +'0') : ( C/16 -10+'A');
98           Result += ((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A');
99           break;
100         }
101       }
102     }
103     Result += "\"";
104     
105   } else {
106     Result = "{";
107     if (CPV->getNumOperands()) {
108       Result += " " +  getConstStrValue(cast<Constant>(CPV->getOperand(0)));
109       for (unsigned i = 1; i < CPV->getNumOperands(); i++)
110         Result += ", " + getConstStrValue(cast<Constant>(CPV->getOperand(i)));
111     }
112     Result += " }";
113   }
114   
115   return Result;
116 }
117
118 static std::string getConstStrValue(const Constant* CPV) {
119   switch (CPV->getType()->getPrimitiveID()) {
120   case Type::BoolTyID:
121     return CPV == ConstantBool::False ? "0" : "1";
122   case Type::SByteTyID:
123   case Type::ShortTyID:
124   case Type::IntTyID:
125     return itostr(cast<ConstantSInt>(CPV)->getValue());
126   case Type::LongTyID:
127     return itostr(cast<ConstantSInt>(CPV)->getValue()) + "ll";
128
129   case Type::UByteTyID:
130     return utostr(cast<ConstantUInt>(CPV)->getValue());
131   case Type::UShortTyID:
132     return utostr(cast<ConstantUInt>(CPV)->getValue());
133   case Type::UIntTyID:
134     return utostr(cast<ConstantUInt>(CPV)->getValue())+"u";
135   case Type::ULongTyID:
136     return utostr(cast<ConstantUInt>(CPV)->getValue())+"ull";
137
138   case Type::FloatTyID:
139   case Type::DoubleTyID:
140     return ftostr(cast<ConstantFP>(CPV)->getValue());
141
142   case Type::ArrayTyID:
143     return getConstArrayStrValue(CPV);
144
145   case Type::StructTyID: {
146     std::string Result = "{";
147     if (CPV->getNumOperands()) {
148       Result += " " + getConstStrValue(cast<Constant>(CPV->getOperand(0)));
149       for (unsigned i = 1; i < CPV->getNumOperands(); i++)
150         Result += ", " + getConstStrValue(cast<Constant>(CPV->getOperand(i)));
151     }
152     return Result + " }";
153   }
154
155   default:
156     cerr << "Unknown constant type: " << CPV << "\n";
157     abort();
158   }
159 }
160
161 // Internal function
162 // Pass the Type* variable and and the variable name and this prints out the 
163 // variable declaration.
164 // This is different from calcTypeName because if you need to declare an array
165 // the size of the array would appear after the variable name itself
166 // For eg. int a[10];
167 static string calcTypeNameVar(const Type *Ty,
168                               map<const Type *, string> &TypeNames, 
169                               const string &NameSoFar, bool ignoreName = false){
170   if (Ty->isPrimitiveType())
171     switch (Ty->getPrimitiveID()) {
172     case Type::BoolTyID: 
173       return "bool " + NameSoFar;
174     case Type::UByteTyID: 
175       return "unsigned char " + NameSoFar;
176     case Type::SByteTyID:
177       return "signed char " + NameSoFar;
178     case Type::UShortTyID:
179       return "unsigned long long " + NameSoFar;
180     case Type::ULongTyID:
181       return "unsigned long long " + NameSoFar;
182     case Type::LongTyID:
183       return "signed long long " + NameSoFar;
184     case Type::UIntTyID:
185       return "unsigned " + NameSoFar;
186     default :
187       return Ty->getDescription() + " " + NameSoFar;
188     }
189   
190   // Check to see if the type is named.
191   if (!ignoreName) {
192     map<const Type *, string>::iterator I = TypeNames.find(Ty);
193     if (I != TypeNames.end())
194       return I->second + " " + NameSoFar;
195   }  
196
197   string Result;
198   switch (Ty->getPrimitiveID()) {
199   case Type::FunctionTyID: {
200     const FunctionType *MTy = cast<const FunctionType>(Ty);
201     Result += calcTypeNameVar(MTy->getReturnType(), TypeNames, "");
202     Result += " " + NameSoFar;
203     Result += " (";
204     for (FunctionType::ParamTypes::const_iterator
205            I = MTy->getParamTypes().begin(),
206            E = MTy->getParamTypes().end(); I != E; ++I) {
207       if (I != MTy->getParamTypes().begin())
208         Result += ", ";
209       Result += calcTypeNameVar(*I, TypeNames, "");
210     }
211     if (MTy->isVarArg()) {
212       if (!MTy->getParamTypes().empty()) 
213         Result += ", ";
214       Result += "...";
215     }
216     Result += ")";
217     break;
218   }
219   case Type::StructTyID: {
220     const StructType *STy = cast<const StructType>(Ty);
221     Result = " struct {\n ";
222     int indx = 0;
223     for (StructType::ElementTypes::const_iterator
224            I = STy->getElementTypes().begin(),
225            E = STy->getElementTypes().end(); I != E; ++I) {
226       Result += calcTypeNameVar(*I, TypeNames, "field" + itostr(indx++));
227       Result += ";\n ";
228     }
229     Result += " }";
230     Result += " " + NameSoFar;
231     break;
232   }  
233
234   case Type::PointerTyID: {
235     Result = calcTypeNameVar(cast<const PointerType>(Ty)->getElementType(), 
236                              TypeNames, "(*" + NameSoFar + ")");
237     break;
238   }
239   
240   case Type::ArrayTyID: {
241     const ArrayType *ATy = cast<const ArrayType>(Ty);
242     int NumElements = ATy->getNumElements();
243     Result = calcTypeNameVar(ATy->getElementType(),  TypeNames, 
244                              NameSoFar + "[" + itostr(NumElements) + "]");
245     break;
246   }
247   default:
248     assert(0 && "Unhandled case in getTypeProps!");
249     Result = "<error>";
250   }
251
252   return Result;
253 }
254
255 namespace {
256   class CWriter {
257     ostream& Out; 
258     SlotCalculator &Table;
259     const Module *TheModule;
260     map<const Type *, string> TypeNames;
261   public:
262     inline CWriter(ostream &o, SlotCalculator &Tab, const Module *M)
263       : Out(o), Table(Tab), TheModule(M) {
264     }
265     
266     inline void write(const Module *M) { printModule(M); }
267
268     ostream& printTypeVar(const Type *Ty, const string &VariableName) {
269       return Out << calcTypeNameVar(Ty, TypeNames, VariableName);
270     }
271
272     ostream& printType(const Type *Ty) {
273       return Out << calcTypeNameVar(Ty, TypeNames, "");
274     }
275
276     void writeOperand(const Value *Operand);
277
278     string getValueName(const Value *V);
279   private :
280
281     void printModule(const Module *M);
282     void printSymbolTable(const SymbolTable &ST);
283     void printGlobal(const GlobalVariable *GV);
284     void printFunctionSignature(const Function *F);
285     void printFunctionDecl(const Function *F); // Print just the forward decl
286     void printFunctionArgument(const Argument *FA);
287     
288     void printFunction(const Function *);
289     
290     void outputBasicBlock(const BasicBlock *);
291   };
292   /* END class CWriter */
293
294
295   /* CLASS InstLocalVarsVisitor */
296   class InstLocalVarsVisitor : public InstVisitor<InstLocalVarsVisitor> {
297     CWriter& CW;
298     void handleTerminator(TerminatorInst *tI, int indx);
299   public:
300     CLocalVars CLV;
301     
302     InstLocalVarsVisitor(CWriter &cw) : CW(cw) {}
303     
304     void visitInstruction(Instruction *I) {
305       if (I->getType() != Type::VoidTy)
306         CLV.addLocalVar(I->getType(), CW.getValueName(I));
307     }
308
309     void visitBranchInst(BranchInst *I) {
310       handleTerminator(I, 0);
311       if (I->isConditional())
312         handleTerminator(I, 1);
313     }
314   };
315 }
316
317 void InstLocalVarsVisitor::handleTerminator(TerminatorInst *tI,int indx) {
318   BasicBlock *bb = tI->getSuccessor(indx);
319
320   BasicBlock::const_iterator insIt = bb->begin();
321   while (insIt != bb->end()) {
322     if (const PHINode *pI = dyn_cast<PHINode>(*insIt)) {
323       // Its a phinode!
324       // Calculate the incoming index for this
325       assert(pI->getBasicBlockIndex(tI->getParent()) != -1);
326
327       CLV.addLocalVar(pI->getType(), CW.getValueName(pI));
328     } else
329       break;
330     insIt++;
331   }
332 }
333
334 namespace {
335   /* CLASS CInstPrintVisitor */
336
337   class CInstPrintVisitor: public InstVisitor<CInstPrintVisitor> {
338     CWriter& CW;
339     SlotCalculator& Table;
340     ostream &Out;
341
342     void outputLValue(Instruction *);
343     void printPhiFromNextBlock(TerminatorInst *tI, int indx);
344     void printIndexingExpr(MemAccessInst *MAI);
345
346   public:
347     CInstPrintVisitor (CWriter &cw, SlotCalculator& table, ostream& o) 
348       : CW(cw), Table(table), Out(o) {}
349     
350     void visitCastInst(CastInst *I);
351     void visitCallInst(CallInst *I);
352     void visitShiftInst(ShiftInst *I) { visitBinaryOperator(I); }
353     void visitReturnInst(ReturnInst *I);
354     void visitBranchInst(BranchInst *I);
355     void visitSwitchInst(SwitchInst *I);
356     void visitInvokeInst(InvokeInst *I) ;
357     void visitMallocInst(MallocInst *I);
358     void visitAllocaInst(AllocaInst *I);
359     void visitFreeInst(FreeInst   *I);
360     void visitLoadInst(LoadInst   *I);
361     void visitStoreInst(StoreInst  *I);
362     void visitGetElementPtrInst(GetElementPtrInst *I);
363     void visitPHINode(PHINode *I) {}
364
365     void visitNot(GenericUnaryInst *I);
366     void visitBinaryOperator(Instruction *I);
367   };
368 }
369
370 void CInstPrintVisitor::outputLValue(Instruction *I) {
371   Out << "  " << CW.getValueName(I) << " = ";
372 }
373
374 void CInstPrintVisitor::printPhiFromNextBlock(TerminatorInst *tI, int indx) {
375   BasicBlock *bb = tI->getSuccessor(indx);
376   BasicBlock::const_iterator insIt = bb->begin();
377   while (insIt != bb->end()) {
378     if (PHINode *pI = dyn_cast<PHINode>(*insIt)) {
379       //Its a phinode!
380       //Calculate the incoming index for this
381       int incindex = pI->getBasicBlockIndex(tI->getParent());
382       if (incindex != -1) {
383         //now we have to do the printing
384         outputLValue(pI);
385         CW.writeOperand(pI->getIncomingValue(incindex));
386         Out << ";\n";
387       }
388     }
389     else break;
390     insIt++;
391   }
392 }
393
394 // Implement all "other" instructions, except for PHINode
395 void CInstPrintVisitor::visitCastInst(CastInst *I) {
396   outputLValue(I);
397   Out << "(";
398   CW.printType(I->getType());
399   Out << ")";
400   CW.writeOperand(I->getOperand(0));
401   Out << ";\n";
402 }
403
404 void CInstPrintVisitor::visitCallInst(CallInst *I) {
405   if (I->getType() != Type::VoidTy)
406     outputLValue(I);
407   else
408     Out << "  ";
409
410   const PointerType  *PTy   = cast<PointerType>(I->getCalledValue()->getType());
411   const FunctionType *FTy   = cast<FunctionType>(PTy->getElementType());
412   const Type         *RetTy = FTy->getReturnType();
413   
414   Out << CW.getValueName(I->getOperand(0)) << "(";
415
416   if (I->getNumOperands() > 1) {
417     CW.writeOperand(I->getOperand(1));
418
419     for (unsigned op = 2, Eop = I->getNumOperands(); op != Eop; ++op) {
420       Out << ", ";
421       CW.writeOperand(I->getOperand(op));
422     }
423   }
424   Out << ");\n";
425
426  
427 // Specific Instruction type classes... note that all of the casts are
428 // neccesary because we use the instruction classes as opaque types...
429 //
430 void CInstPrintVisitor::visitReturnInst(ReturnInst *I) {
431   Out << "  return";
432   if (I->getNumOperands()) {
433     Out << " ";
434     CW.writeOperand(I->getOperand(0));
435   }
436   Out << ";\n";
437 }
438
439 void CInstPrintVisitor::visitBranchInst(BranchInst *I) {
440   TerminatorInst *tI = cast<TerminatorInst>(I);
441   if (I->isConditional()) {
442     Out << "  if (";
443     CW.writeOperand(I->getCondition());
444     Out << ") {\n";
445     printPhiFromNextBlock(tI,0);
446     Out << "    goto ";
447     CW.writeOperand(I->getOperand(0));
448     Out << ";\n";
449     Out << "  } else {\n";
450     printPhiFromNextBlock(tI,1);
451     Out << "    goto ";
452     CW.writeOperand(I->getOperand(1));
453     Out << ";\n  }\n";
454   } else {
455     printPhiFromNextBlock(tI,0);
456     Out << "  goto ";
457     CW.writeOperand(I->getOperand(0));
458     Out << ";\n";
459   }
460   Out << "\n";
461 }
462
463 void CInstPrintVisitor::visitSwitchInst(SwitchInst *I) {
464   assert(0 && "Switch not implemented!");
465 }
466
467 void CInstPrintVisitor::visitInvokeInst(InvokeInst *I) {
468   assert(0 && "Invoke not implemented!");
469 }
470
471 void CInstPrintVisitor::visitMallocInst(MallocInst *I) {
472   outputLValue(I);
473   Out << "(";
474   CW.printType(I->getType()->getElementType());
475   Out << "*)malloc(sizeof(";
476   CW.printTypeVar(I->getType()->getElementType(), "");
477   Out << ")";
478
479   if (I->isArrayAllocation()) {
480     Out << " * " ;
481     CW.writeOperand(I->getOperand(0));
482   }
483   Out << ");";
484 }
485
486 void CInstPrintVisitor::visitAllocaInst(AllocaInst *I) {
487   outputLValue(I);
488   Out << "(";
489   CW.printTypeVar(I->getType(), "");
490   Out << ") alloca(sizeof(";
491   CW.printTypeVar(I->getType()->getElementType(), "");
492   Out << ")";
493   if (I->isArrayAllocation()) {
494     Out << " * " ;
495     CW.writeOperand(I->getOperand(0));
496   }
497   Out << ");\n";
498 }
499
500 void CInstPrintVisitor::visitFreeInst(FreeInst   *I) {
501   Out << "free(";
502   CW.writeOperand(I->getOperand(0));
503   Out << ");\n";
504 }
505
506 void CInstPrintVisitor::printIndexingExpr(MemAccessInst *MAI) {
507   CW.writeOperand(MAI->getPointerOperand());
508
509   for (MemAccessInst::op_iterator I = MAI->idx_begin(), E = MAI->idx_end();
510        I != E; ++I)
511     if ((*I)->getType() == Type::UIntTy) {
512       Out << "[";
513       CW.writeOperand(*I);
514       Out << "]";
515     } else {
516       Out << ".field" << cast<ConstantUInt>(*I)->getValue();
517     }
518 }
519
520 void CInstPrintVisitor::visitLoadInst(LoadInst *I) {
521   outputLValue(I);
522   printIndexingExpr(I);
523   Out << ";\n";
524 }
525
526 void CInstPrintVisitor::visitStoreInst(StoreInst *I) {
527   Out << "  ";
528   printIndexingExpr(I);
529   Out << " = ";
530   CW.writeOperand(I->getOperand(0));
531   Out << ";\n";
532 }
533
534 void CInstPrintVisitor::visitGetElementPtrInst(GetElementPtrInst *I) {
535   outputLValue(I);
536   Out << "&";
537   printIndexingExpr(I);
538   Out << ";\n";
539 }
540
541 void CInstPrintVisitor::visitNot(GenericUnaryInst *I) {
542   outputLValue(I);
543   Out << "~";
544   CW.writeOperand(I->getOperand(0));
545   Out << ";\n";
546 }
547
548 void CInstPrintVisitor::visitBinaryOperator(Instruction *I) {
549   // binary instructions, shift instructions, setCond instructions.
550   outputLValue(I);
551   if (isa<PointerType>(I->getType())) {
552     Out << "(";
553     CW.printType(I->getType());
554     Out << ")";
555   }
556       
557   if (isa<PointerType>(I->getType())) Out << "(long long)";
558   CW.writeOperand(I->getOperand(0));
559
560   switch (I->getOpcode()) {
561   case Instruction::Add: Out << " + "; break;
562   case Instruction::Sub: Out << " - "; break;
563   case Instruction::Mul: Out << "*"; break;
564   case Instruction::Div: Out << "/"; break;
565   case Instruction::Rem: Out << "%"; break;
566   case Instruction::And: Out << " & "; break;
567   case Instruction::Or: Out << " | "; break;
568   case Instruction::Xor: Out << " ^ "; break;
569   case Instruction::SetEQ: Out << " == "; break;
570   case Instruction::SetNE: Out << " != "; break;
571   case Instruction::SetLE: Out << " <= "; break;
572   case Instruction::SetGE: Out << " >= "; break;
573   case Instruction::SetLT: Out << " < "; break;
574   case Instruction::SetGT: Out << " > "; break;
575   case Instruction::Shl : Out << " << "; break;
576   case Instruction::Shr : Out << " >> "; break;
577   default: cerr << "Invalid operator type!" << I; abort();
578   }
579
580   if (isa<PointerType>(I->getType())) Out << "(long long)";
581   CW.writeOperand(I->getOperand(1));
582   Out << ";\n";
583 }
584
585 /* END : CInstPrintVisitor implementation */
586
587 // We dont want identifier names with ., space, -  in them. 
588 // So we replace them with _
589 static string makeNameProper(string x) {
590   string tmp;
591   for (string::iterator sI = x.begin(), sEnd = x.end(); sI != sEnd; sI++)
592     switch (*sI) {
593     case '.': tmp += "_d"; break;
594     case ' ': tmp += "_s"; break;
595     case '-': tmp += "_D"; break;
596     case '_': tmp += "__"; break;
597     default:  tmp += *sI;
598     }
599
600   return tmp;
601 }
602
603 string CWriter::getValueName(const Value *V) {
604   if (V->hasName()) {             // Print out the label if it exists...
605     if (isa<GlobalValue>(V))  // Do not mangle globals...
606       return makeNameProper(V->getName());
607
608     return "l" + utostr(V->getType()->getUniqueID()) + "_" +
609            makeNameProper(V->getName());      
610   }
611
612   int Slot = Table.getValSlot(V);
613   assert(Slot >= 0 && "Invalid value!");
614   return "ltmp_" + itostr(Slot) + "_" + utostr(V->getType()->getUniqueID());
615 }
616
617 void CWriter::printModule(const Module *M) {
618   // printing stdlib inclusion
619   // Out << "#include <stdlib.h>\n";
620
621   // get declaration for alloca
622   Out << "/* Provide Declarations */\n"
623       << "#include <alloca.h>\n\n"
624
625     // Provide a definition for null if one does not already exist.
626       << "#ifndef NULL\n#define NULL 0\n#endif\n\n"
627       << "typedef unsigned char bool;\n"
628
629       << "\n\n/* Global Symbols */\n";
630
631   // Loop over the symbol table, emitting all named constants...
632   if (M->hasSymbolTable())
633     printSymbolTable(*M->getSymbolTable());
634
635   Out << "\n\n/* Global Data */\n";
636   for_each(M->gbegin(), M->gend(), 
637            bind_obj(this, &CWriter::printGlobal));
638
639   // First output all the declarations of the functions as C requires Functions 
640   // be declared before they are used.
641   //
642   Out << "\n\n/* Function Declarations */\n";
643   for_each(M->begin(), M->end(), bind_obj(this, &CWriter::printFunctionDecl));
644   
645   // Output all of the functions...
646   Out << "\n\n/* Function Bodies */\n";
647   for_each(M->begin(), M->end(), bind_obj(this, &CWriter::printFunction));
648 }
649
650 // prints the global constants
651 void CWriter::printGlobal(const GlobalVariable *GV) {
652   if (GV->hasInternalLinkage()) Out << "static ";
653
654   printTypeVar(GV->getType()->getElementType(), getValueName(GV));
655
656   if (GV->hasInitializer()) {
657     Out << " = " ;
658     writeOperand(GV->getInitializer());
659   }
660
661   Out << ";\n";
662 }
663
664 // printSymbolTable - Run through symbol table looking for named constants
665 // if a named constant is found, emit it's declaration...
666 // Assuming that symbol table has only types and constants.
667 void CWriter::printSymbolTable(const SymbolTable &ST) {
668   for (SymbolTable::const_iterator TI = ST.begin(); TI != ST.end(); ++TI) {
669     SymbolTable::type_const_iterator I = ST.type_begin(TI->first);
670     SymbolTable::type_const_iterator End = ST.type_end(TI->first);
671     
672     for (; I != End; ++I)
673       if (const Type *Ty = dyn_cast<const StructType>(I->second)) {
674         string Name = "struct l_" + I->first;
675         Out << Name << ";\n";
676
677         TypeNames.insert(std::make_pair(Ty, Name));
678       }
679   }
680
681   Out << "\n";
682
683   for (SymbolTable::const_iterator TI = ST.begin(); TI != ST.end(); ++TI) {
684     SymbolTable::type_const_iterator I = ST.type_begin(TI->first);
685     SymbolTable::type_const_iterator End = ST.type_end(TI->first);
686     
687     for (; I != End; ++I) {
688       const Value *V = I->second;
689       if (const Type *Ty = dyn_cast<const Type>(V)) {
690         Out << "typedef ";
691         string Name = "l_" + I->first;
692         if (isa<StructType>(Ty)) Name = "struct " + Name;
693         Out << calcTypeNameVar(Ty, TypeNames, Name, true) << ";\n";
694       }
695     }
696   }
697 }
698
699
700 // printFunctionDecl - Print function declaration
701 //
702 void CWriter::printFunctionDecl(const Function *F) {
703   printFunctionSignature(F);
704   Out << ";\n";
705 }
706
707 void CWriter::printFunctionSignature(const Function *F) {
708   if (F->hasInternalLinkage()) Out << "static ";
709   
710   // Loop over the arguments, printing them...
711   const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
712   
713   // Print out the return type and name...
714   printType(F->getReturnType());
715   Out << " " << getValueName(F) << "(";
716     
717   if (!F->isExternal()) {
718     for_each(F->getArgumentList().begin(), F->getArgumentList().end(),
719              bind_obj(this, &CWriter::printFunctionArgument));
720   } else {
721     // Loop over the arguments, printing them...
722     for (FunctionType::ParamTypes::const_iterator I = 
723            FT->getParamTypes().begin(),
724            E = FT->getParamTypes().end(); I != E; ++I) {
725       if (I != FT->getParamTypes().begin()) Out << ", ";
726       printType(*I);
727     }
728   }
729
730   // Finish printing arguments...
731   if (FT->isVarArg()) {
732     if (FT->getParamTypes().size()) Out << ", ";
733     Out << "...";  // Output varargs portion of signature!
734   }
735   Out << ")";
736 }
737
738
739 // printFunctionArgument - This member is called for every argument that 
740 // is passed into the method.  Simply print it out
741 //
742 void CWriter::printFunctionArgument(const Argument *Arg) {
743   // Insert commas as we go... the first arg doesn't get a comma
744   if (Arg != Arg->getParent()->getArgumentList().front()) Out << ", ";
745   
746   // Output type...
747   printTypeVar(Arg->getType(), getValueName(Arg));
748 }
749
750 void CWriter::printFunction(const Function *F) {
751   if (F->isExternal()) return;
752
753   Table.incorporateFunction(F);
754
755   // Process each of the basic blocks, gather information and call the  
756   // output methods on the CLocalVars and Function* objects.
757     
758   // gather local variable information for each basic block
759   InstLocalVarsVisitor ILV(*this);
760   ILV.visit((Function *)F);
761
762   printFunctionSignature(F);
763   Out << " {\n";
764
765   // Loop over the symbol table, emitting all named constants...
766   if (F->hasSymbolTable())
767     printSymbolTable(*F->getSymbolTable()); 
768   
769   // print the local variables
770   // we assume that every local variable is alloca'ed in the C code.
771   std::map<const Type*, VarListType> &locals = ILV.CLV.LocalVars;
772   
773   map<const Type*, VarListType>::iterator iter;
774   for (iter = locals.begin(); iter != locals.end(); ++iter) {
775     VarListType::iterator listiter;
776     for (listiter = iter->second.begin(); listiter != iter->second.end(); 
777          ++listiter) {
778       Out << "  ";
779       printTypeVar(iter->first, *listiter);
780       Out << ";\n";
781     }
782   }
783  
784   // print the basic blocks
785   for_each(F->begin(), F->end(), bind_obj(this, &CWriter::outputBasicBlock));
786   
787   Out << "}\n";
788   Table.purgeFunction();
789 }
790
791 void CWriter::outputBasicBlock(const BasicBlock* BB) {
792   Out << getValueName(BB) << ":\n";
793
794   // Output all of the instructions in the basic block...
795   // print the basic blocks
796   CInstPrintVisitor CIPV(*this, Table, Out);
797   CIPV.visit((BasicBlock *) BB);
798 }
799
800 void CWriter::writeOperand(const Value *Operand) {
801   if (isa<GlobalVariable>(Operand))
802     Out << "(&";  // Global variables are references as their addresses by llvm
803
804   if (Operand->hasName()) {   
805     Out << getValueName(Operand);
806   } else if (const Constant *CPV = dyn_cast<const Constant>(Operand)) {
807     if (isa<ConstantPointerNull>(CPV))
808       Out << "NULL";
809     else
810       Out << getConstStrValue(CPV); 
811   } else {
812     int Slot = Table.getValSlot(Operand);
813     assert(Slot >= 0 && "Malformed LLVM!");
814     Out << "ltmp_" << Slot << "_" << Operand->getType()->getUniqueID();
815   }
816
817   if (isa<GlobalVariable>(Operand))
818     Out << ")";
819 }
820
821
822 //===----------------------------------------------------------------------===//
823 //                       External Interface declaration
824 //===----------------------------------------------------------------------===//
825
826 void WriteToC(const Module *M, ostream &Out) {
827   assert(M && "You can't write a null module!!");
828   SlotCalculator SlotTable(M, false);
829   CWriter W(Out, SlotTable, M);
830   W.write(M);
831   Out.flush();
832 }