Many random fixes:
[oota-llvm.git] / lib / Target / CBackend / Writer.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 string calcTypeNameVar(const Type *Ty,
52                               map<const Type *, string> &TypeNames, 
53                               string VariableName, string NameSoFar);
54
55 static std::string getConstStrValue(const Constant* CPV);
56
57
58 // We dont want identifier names with ., space, -  in them. 
59 // So we replace them with _
60 static string makeNameProper(string x) {
61   string tmp;
62   for (string::iterator sI = x.begin(), sEnd = x.end(); sI != sEnd; sI++) {
63     if (*sI == '.')
64       tmp += '_';
65     else if (*sI == ' ')
66       tmp += '_';
67     else if (*sI == '-')
68       tmp += "__";
69     else
70       tmp += *sI;
71   }
72   return tmp;
73 }
74
75 static string getConstantName(const Constant *CPV) {
76   return CPV->getName();
77 }
78
79
80 static std::string getConstArrayStrValue(const Constant* CPV) {
81   std::string Result;
82   
83   // As a special case, print the array as a string if it is an array of
84   // ubytes or an array of sbytes with positive values.
85   // 
86   const Type *ETy = cast<ArrayType>(CPV->getType())->getElementType();
87   bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
88
89   if (ETy == Type::SByteTy) {
90     for (unsigned i = 0; i < CPV->getNumOperands(); ++i)
91       if (ETy == Type::SByteTy &&
92           cast<ConstantSInt>(CPV->getOperand(i))->getValue() < 0) {
93         isString = false;
94         break;
95       }
96   }
97   
98   if (isString) {
99     Result = "\"";
100     for (unsigned i = 0; i < CPV->getNumOperands(); ++i) {
101       unsigned char C = (ETy == Type::SByteTy) ?
102         (unsigned char)cast<ConstantSInt>(CPV->getOperand(i))->getValue() :
103         (unsigned char)cast<ConstantUInt>(CPV->getOperand(i))->getValue();
104       
105       if (isprint(C)) {
106         Result += C;
107       } else {
108         Result += "\\x";
109         Result += ( C/16  < 10) ? ( C/16 +'0') : ( C/16 -10+'A');
110         Result += ((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A');
111       }
112     }
113     Result += "\"";
114     
115   } else {
116     Result = "{";
117     if (CPV->getNumOperands()) {
118       Result += " " +  getConstStrValue(cast<Constant>(CPV->getOperand(0)));
119       for (unsigned i = 1; i < CPV->getNumOperands(); i++)
120         Result += ", " + getConstStrValue(cast<Constant>(CPV->getOperand(i)));
121     }
122     Result += " }";
123   }
124   
125   return Result;
126 }
127
128 static std::string getConstStructStrValue(const Constant* CPV) {
129   std::string Result = "{";
130   if (CPV->getNumOperands()) {
131     Result += " " + getConstStrValue(cast<Constant>(CPV->getOperand(0)));
132     for (unsigned i = 1; i < CPV->getNumOperands(); i++)
133       Result += ", " + getConstStrValue(cast<Constant>(CPV->getOperand(i)));
134   }
135
136   return Result + " }";
137 }
138
139 // our own getStrValue function for constant initializers
140 static std::string getConstStrValue(const Constant* CPV) {
141   // Does not handle null pointers, that needs to be checked explicitly
142   string tempstr;
143   if (CPV == ConstantBool::False)
144     return "0";
145   else if (CPV == ConstantBool::True)
146     return "1";
147   
148   else if (isa<ConstantArray>(CPV)) {
149     tempstr = getConstArrayStrValue(CPV);
150   }
151   else  if (isa<ConstantStruct>(CPV)) {
152     tempstr = getConstStructStrValue(CPV);
153   }
154   else if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(CPV)) {
155     tempstr = utostr(CUI->getValue());
156   } 
157   else if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CPV)) {
158     tempstr = itostr(CSI->getValue());
159   }
160   else if (ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
161     tempstr = ftostr(CFP->getValue());
162   }
163   
164   if (CPV->getType() == Type::ULongTy)
165     tempstr += "ull";
166   else if (CPV->getType() == Type::LongTy)
167     tempstr += "ll";
168   else if (CPV->getType() == Type::UIntTy ||
169            CPV->getType() == Type::UShortTy)
170     tempstr += "u";
171   
172   return tempstr;
173
174 }
175
176 // Internal function
177 // Essentially pass the Type* variable, an empty typestack and this prints 
178 // out the C type
179 static string calcTypeName(const Type *Ty, map<const Type *, string> &TypeNames,
180                            string &FunctionInfo) {
181   
182   // Takin' care of the fact that boolean would be int in C
183   // and that ushort would be unsigned short etc.
184   
185   // Base Case
186   if (Ty->isPrimitiveType())
187     switch (Ty->getPrimitiveID()) {
188     case Type::VoidTyID:   return "void";
189     case Type::BoolTyID:   return "bool";
190     case Type::UByteTyID:  return "unsigned char";
191     case Type::SByteTyID:  return "signed char";
192     case Type::UShortTyID: return "unsigned short";
193     case Type::ShortTyID:  return "short";
194     case Type::UIntTyID:   return "unsigned";
195     case Type::IntTyID:    return "int";
196     case Type::ULongTyID:  return "unsigned long long";
197     case Type::LongTyID:   return "signed long long";
198     case Type::FloatTyID:  return "float";
199     case Type::DoubleTyID: return "double";
200     default : assert(0 && "Unknown primitive type!");
201     }
202   
203   // Check to see if the type is named.
204   map<const Type *, string>::iterator I = TypeNames.find(Ty);
205   if (I != TypeNames.end())
206     return I->second;
207   
208   string Result;
209   string MInfo = "";
210   switch (Ty->getPrimitiveID()) {
211   case Type::FunctionTyID: {
212     const FunctionType *MTy = cast<const FunctionType>(Ty);
213     Result = calcTypeName(MTy->getReturnType(), TypeNames, MInfo);
214     if (MInfo != "")
215       Result += ") " + MInfo;
216     Result += "(";
217     FunctionInfo += " (";
218     for (FunctionType::ParamTypes::const_iterator
219            I = MTy->getParamTypes().begin(),
220            E = MTy->getParamTypes().end(); I != E; ++I) {
221       if (I != MTy->getParamTypes().begin())
222         FunctionInfo += ", ";
223       MInfo = "";
224       FunctionInfo += calcTypeName(*I, TypeNames, MInfo);
225       if (MInfo != "")
226         Result += ") " + MInfo;
227     }
228     if (MTy->isVarArg()) {
229       if (!MTy->getParamTypes().empty()) 
230         FunctionInfo += ", ";
231       FunctionInfo += "...";
232     }
233     FunctionInfo += ")";
234     break;
235   }
236   case Type::StructTyID: {
237     string tempstr = "";
238     const StructType *STy = cast<const StructType>(Ty);
239     Result = " struct {\n ";
240     int indx = 0;
241     for (StructType::ElementTypes::const_iterator
242            I = STy->getElementTypes().begin(),
243            E = STy->getElementTypes().end(); I != E; ++I) {
244       Result += calcTypeNameVar(*I, TypeNames, 
245                                 "field" + itostr(indx++), tempstr);
246       Result += ";\n ";
247     }
248     Result += " } ";
249     break;
250   }
251   case Type::PointerTyID:
252     Result = calcTypeName(cast<const PointerType>(Ty)->getElementType(), 
253                           TypeNames, MInfo);
254     Result += "*";
255     break;
256   case Type::ArrayTyID: {
257     const ArrayType *ATy = cast<const ArrayType>(Ty);
258     int NumElements = ATy->getNumElements();
259     Result = calcTypeName(ATy->getElementType(), TypeNames, MInfo);
260     Result += "*";
261     break;
262   }
263   default:
264     assert(0 && "Unhandled case in getTypeProps!");
265     Result = "<error>";
266   }
267
268   return Result;
269 }
270
271 // Internal function
272 // Pass the Type* variable and and the variable name and this prints out the 
273 // variable declaration.
274 // This is different from calcTypeName because if you need to declare an array
275 // the size of the array would appear after the variable name itself
276 // For eg. int a[10];
277 static string calcTypeNameVar(const Type *Ty,
278                               map<const Type *, string> &TypeNames, 
279                               string VariableName, string NameSoFar) {
280   if (Ty->isPrimitiveType())
281     switch (Ty->getPrimitiveID()) {
282     case Type::BoolTyID: 
283       return "bool " + NameSoFar + VariableName;
284     case Type::UByteTyID: 
285       return "unsigned char " + NameSoFar + VariableName;
286     case Type::SByteTyID:
287       return "signed char " + NameSoFar + VariableName;
288     case Type::UShortTyID:
289       return "unsigned long long " + NameSoFar + VariableName;
290     case Type::ULongTyID:
291       return "unsigned long long " + NameSoFar + VariableName;
292     case Type::LongTyID:
293       return "signed long long " + NameSoFar + VariableName;
294     case Type::UIntTyID:
295       return "unsigned " + NameSoFar + VariableName;
296     default :
297       return Ty->getDescription() + " " + NameSoFar + VariableName; 
298     }
299   
300   // Check to see if the type is named.
301   map<const Type *, string>::iterator I = TypeNames.find(Ty);
302   if (I != TypeNames.end())
303     return I->second + " " + NameSoFar + VariableName;
304   
305   string Result;
306   string tempstr = "";
307
308   switch (Ty->getPrimitiveID()) {
309   case Type::FunctionTyID: {
310     string MInfo = "";
311     const FunctionType *MTy = cast<const FunctionType>(Ty);
312     Result += calcTypeName(MTy->getReturnType(), TypeNames, MInfo);
313     if (MInfo != "")
314       Result += ") " + MInfo;
315     Result += " " + NameSoFar + VariableName;
316     Result += " (";
317     for (FunctionType::ParamTypes::const_iterator
318            I = MTy->getParamTypes().begin(),
319            E = MTy->getParamTypes().end(); I != E; ++I) {
320       if (I != MTy->getParamTypes().begin())
321         Result += ", ";
322       MInfo = "";
323       Result += calcTypeName(*I, TypeNames, MInfo);
324       if (MInfo != "")
325         Result += ") " + MInfo;
326     }
327     if (MTy->isVarArg()) {
328       if (!MTy->getParamTypes().empty()) 
329         Result += ", ";
330       Result += "...";
331     }
332     Result += ")";
333     break;
334   }
335   case Type::StructTyID: {
336     const StructType *STy = cast<const StructType>(Ty);
337     Result = " struct {\n ";
338     int indx = 0;
339     for (StructType::ElementTypes::const_iterator
340            I = STy->getElementTypes().begin(),
341            E = STy->getElementTypes().end(); I != E; ++I) {
342       Result += calcTypeNameVar(*I, TypeNames, 
343                                 "field" + itostr(indx++), "");
344       Result += ";\n ";
345     }
346     Result += " }";
347     Result += " " + NameSoFar + VariableName;
348     break;
349   }  
350
351   case Type::PointerTyID: {
352     Result = calcTypeNameVar(cast<const PointerType>(Ty)->getElementType(), 
353                              TypeNames, tempstr, 
354                              "(*" + NameSoFar + VariableName + ")");
355     break;
356   }
357   
358   case Type::ArrayTyID: {
359     const ArrayType *ATy = cast<const ArrayType>(Ty);
360     int NumElements = ATy->getNumElements();
361     Result = calcTypeNameVar(ATy->getElementType(),  TypeNames, 
362                              tempstr, NameSoFar + VariableName + "[" + 
363                              itostr(NumElements) + "]");
364     break;
365   }
366   default:
367     assert(0 && "Unhandled case in getTypeProps!");
368     Result = "<error>";
369   }
370
371   return Result;
372 }
373
374 // printTypeVarInt - The internal guts of printing out a type that has a
375 // potentially named portion and the variable associated with the type.
376 static ostream &printTypeVarInt(ostream &Out, const Type *Ty,
377                              map<const Type *, string> &TypeNames,
378                              const string &VariableName) {
379   // Primitive types always print out their description, regardless of whether
380   // they have been named or not.
381   
382   if (Ty->isPrimitiveType())
383     switch (Ty->getPrimitiveID()) {
384     case Type::BoolTyID: 
385       return Out << "bool " << VariableName;
386     case Type::UByteTyID:
387       return Out << "unsigned char " << VariableName;
388     case Type::SByteTyID:
389       return Out << "signed char " << VariableName;
390     case Type::UShortTyID:
391       return Out << "unsigned long long " << VariableName;
392     case Type::ULongTyID:
393       return Out << "unsigned long long " << VariableName;
394     case Type::LongTyID:
395       return Out << "signed long long " << VariableName;
396     case Type::UIntTyID:
397       return Out << "unsigned " << VariableName;
398     default :
399       return Out << Ty->getDescription() << " " << VariableName; 
400     }
401   
402   // Check to see if the type is named.
403   map<const Type *, string>::iterator I = TypeNames.find(Ty);
404   if (I != TypeNames.end()) return Out << I->second << " " << VariableName;
405   
406   // Otherwise we have a type that has not been named but is a derived type.
407   // Carefully recurse the type hierarchy to print out any contained symbolic
408   // names.
409   //
410   string TypeNameVar, tempstr = "";
411   TypeNameVar = calcTypeNameVar(Ty, TypeNames, VariableName, tempstr);
412   return Out << TypeNameVar;
413 }
414
415 // Internal guts of printing a type name
416 static ostream &printTypeInt(ostream &Out, const Type *Ty,
417                              map<const Type *, string> &TypeNames) {
418   // Primitive types always print out their description, regardless of whether
419   // they have been named or not.
420   
421   if (Ty->isPrimitiveType())
422     switch (Ty->getPrimitiveID()) {
423     case Type::BoolTyID:
424       return Out << "bool";
425     case Type::UByteTyID:
426       return Out << "unsigned char";
427     case Type::SByteTyID:
428       return Out << "signed char";
429     case Type::UShortTyID:
430       return Out << "unsigned short";
431     case Type::ULongTyID:
432       return Out << "unsigned long long";
433     case Type::LongTyID:
434       return Out << "signed long long";
435     case Type::UIntTyID:
436       return Out << "unsigned";
437     default :
438       return Out << Ty->getDescription(); 
439     }
440   
441   // Check to see if the type is named.
442   map<const Type *, string>::iterator I = TypeNames.find(Ty);
443   if (I != TypeNames.end()) return Out << I->second;
444   
445   // Otherwise we have a type that has not been named but is a derived type.
446   // Carefully recurse the type hierarchy to print out any contained symbolic
447   // names.
448   //
449   string MInfo;
450   string TypeName = calcTypeName(Ty, TypeNames, MInfo);
451   // TypeNames.insert(std::make_pair(Ty, TypeName));
452   //Cache type name for later use
453   if (MInfo != "")
454     return Out << TypeName << ")" << MInfo;
455   else
456     return Out << TypeName;
457 }
458
459 namespace {
460
461   //Internal CWriter class mimics AssemblyWriter.
462   class CWriter {
463     ostream& Out; 
464     SlotCalculator &Table;
465     const Module *TheModule;
466     map<const Type *, string> TypeNames;
467   public:
468     inline CWriter(ostream &o, SlotCalculator &Tab, const Module *M)
469       : Out(o), Table(Tab), TheModule(M) {
470     }
471     
472     inline void write(const Module *M) { printModule(M); }
473
474     ostream& printTypeVar(const Type *Ty, const string &VariableName) {
475       return printTypeVarInt(Out, Ty, TypeNames, VariableName);
476     }
477
478
479
480     ostream& printType(const Type *Ty, ostream &Out);
481     void writeOperand(const Value *Operand, ostream &Out,bool PrintName = true);
482
483     string getValueName(const Value *V);
484   private :
485
486     void printModule(const Module *M);
487     void printSymbolTable(const SymbolTable &ST);
488     void printConstant(const Constant *CPV);
489     void printGlobal(const GlobalVariable *GV);
490     void printFunctionSignature(const Function *F);
491     void printFunctionDecl(const Function *F); // Print just the forward decl
492     void printFunctionArgument(const Argument *FA);
493     
494     void printFunction(const Function *);
495     
496     void outputBasicBlock(const BasicBlock *);
497   };
498   /* END class CWriter */
499
500
501   /* CLASS InstLocalVarsVisitor */
502   class InstLocalVarsVisitor : public InstVisitor<InstLocalVarsVisitor> {
503     CWriter& CW;
504     void handleTerminator(TerminatorInst *tI, int indx);
505   public:
506     CLocalVars CLV;
507     
508     InstLocalVarsVisitor(CWriter &cw) : CW(cw) {}
509     
510     void visitInstruction(Instruction *I) {
511       if (I->getType() != Type::VoidTy) {
512         string tempostr = CW.getValueName(I);
513         CLV.addLocalVar(I->getType(), tempostr);
514       }
515     }
516
517     void visitBranchInst(BranchInst *I) {
518       handleTerminator(I, 0);
519       if (I->isConditional())
520         handleTerminator(I, 1);
521     }
522   };
523 }
524
525 void InstLocalVarsVisitor::handleTerminator(TerminatorInst *tI,int indx) {
526   BasicBlock *bb = tI->getSuccessor(indx);
527
528   BasicBlock::const_iterator insIt = bb->begin();
529   while (insIt != bb->end()) {
530     if (const PHINode *pI = dyn_cast<PHINode>(*insIt)) {
531       // Its a phinode!
532       // Calculate the incoming index for this
533       assert(pI->getBasicBlockIndex(tI->getParent()) != -1);
534
535       CLV.addLocalVar(pI->getType(), CW.getValueName(pI));
536     } else
537       break;
538     insIt++;
539   }
540 }
541
542 namespace {
543   /* CLASS CInstPrintVisitor */
544
545   class CInstPrintVisitor: public InstVisitor<CInstPrintVisitor> {
546     CWriter& CW;
547     SlotCalculator& Table;
548     ostream &Out;
549     const Value *Operand;
550
551     void outputLValue(Instruction *);
552     void printPhiFromNextBlock(TerminatorInst *tI, int indx);
553
554   public:
555     CInstPrintVisitor (CWriter &cw, SlotCalculator& table, ostream& o) 
556       : CW(cw), Table(table), Out(o) {
557       
558     }
559     
560     void visitCastInst(CastInst *I);
561     void visitCallInst(CallInst *I);
562     void visitShiftInst(ShiftInst *I) { visitBinaryOperator(I); }
563     void visitReturnInst(ReturnInst *I);
564     void visitBranchInst(BranchInst *I);
565     void visitSwitchInst(SwitchInst *I);
566     void visitInvokeInst(InvokeInst *I) ;
567     void visitMallocInst(MallocInst *I);
568     void visitAllocaInst(AllocaInst *I);
569     void visitFreeInst(FreeInst   *I);
570     void visitLoadInst(LoadInst   *I);
571     void visitStoreInst(StoreInst  *I);
572     void visitGetElementPtrInst(GetElementPtrInst *I);
573     void visitPHINode(PHINode *I) {}
574
575     void visitNot(GenericUnaryInst *I);
576     void visitBinaryOperator(Instruction *I);
577   };
578 }
579
580 void CInstPrintVisitor::outputLValue(Instruction *I) {
581   Out << "  " << CW.getValueName(I) << " = ";
582 }
583
584 void CInstPrintVisitor::printPhiFromNextBlock(TerminatorInst *tI, int indx) {
585   BasicBlock *bb = tI->getSuccessor(indx);
586   BasicBlock::const_iterator insIt = bb->begin();
587   while (insIt != bb->end()) {
588     if (PHINode *pI = dyn_cast<PHINode>(*insIt)) {
589       //Its a phinode!
590       //Calculate the incoming index for this
591       int incindex = pI->getBasicBlockIndex(tI->getParent());
592       if (incindex != -1) {
593         //now we have to do the printing
594         outputLValue(pI);
595         CW.writeOperand(pI->getIncomingValue(incindex), Out);
596         Out << ";\n";
597       }
598     }
599     else break;
600     insIt++;
601   }
602 }
603
604 // Implement all "other" instructions, except for PHINode
605 void CInstPrintVisitor::visitCastInst(CastInst *I) {
606   outputLValue(I);
607   Operand = I->getNumOperands() ? I->getOperand(0) : 0;
608   Out << "(";
609   CW.printType(I->getType(), Out);
610   Out << ")";
611   CW.writeOperand(Operand, Out);
612   Out << ";\n";
613 }
614
615 void CInstPrintVisitor::visitCallInst(CallInst *I) {
616   if (I->getType() != Type::VoidTy)
617     outputLValue(I);
618   else
619     Out << "  ";
620
621   Operand = I->getNumOperands() ? I->getOperand(0) : 0;
622   const PointerType *PTy = dyn_cast<PointerType>(Operand->getType());
623   const FunctionType  *MTy = PTy 
624     ? dyn_cast<FunctionType>(PTy->getElementType()):0;
625   const Type      *RetTy = MTy ? MTy->getReturnType() : 0;
626   
627   // If possible, print out the short form of the call instruction, but we can
628   // only do this if the first argument is a pointer to a nonvararg method,
629   // and if the value returned is not a pointer to a method.
630   //
631   if (RetTy && !MTy->isVarArg() &&
632       (!isa<PointerType>(RetTy)||
633        !isa<FunctionType>(cast<PointerType>(RetTy)))){
634     Out << " ";
635     Out << makeNameProper(Operand->getName());
636   } else {
637     Out << makeNameProper(Operand->getName());      
638   }
639   Out << "(";
640   if (I->getNumOperands() > 1) 
641     CW.writeOperand(I->getOperand(1), Out);
642   for (unsigned op = 2, Eop = I->getNumOperands(); op < Eop; ++op) {
643     Out << ",";
644     CW.writeOperand(I->getOperand(op), Out);
645   }
646   
647   Out << " );\n";
648
649  
650 // Specific Instruction type classes... note that all of the casts are
651 // neccesary because we use the instruction classes as opaque types...
652 //
653 void CInstPrintVisitor::visitReturnInst(ReturnInst *I) {
654   Out << "  return ";
655   if (I->getNumOperands())
656     CW.writeOperand(I->getOperand(0), Out);
657   Out << ";\n";
658 }
659
660 void CInstPrintVisitor::visitBranchInst(BranchInst *I) {
661   TerminatorInst *tI = cast<TerminatorInst>(I);
662   if (I->isConditional()) {
663     Out << "  if (";
664     CW.writeOperand(I->getCondition(), Out);
665     Out << ") {\n";
666     printPhiFromNextBlock(tI,0);
667     Out << "    goto ";
668     CW.writeOperand(I->getOperand(0), Out);
669     Out << ";\n";
670     Out << "  } else {\n";
671     printPhiFromNextBlock(tI,1);
672     Out << "    goto ";
673     CW.writeOperand(I->getOperand(1), Out);
674     Out << ";\n  }\n";
675   } else {
676     printPhiFromNextBlock(tI,0);
677     Out << "  goto ";
678     CW.writeOperand(I->getOperand(0), Out);
679     Out << ";\n";
680   }
681   Out << "\n";
682 }
683
684 void CInstPrintVisitor::visitSwitchInst(SwitchInst *I) {
685   assert(0 && "Switch not implemented!");
686 }
687
688 void CInstPrintVisitor::visitInvokeInst(InvokeInst *I) {
689   assert(0 && "Invoke not implemented!");
690 }
691
692 void CInstPrintVisitor::visitMallocInst(MallocInst *I) {
693   outputLValue(I);
694   Out << "(";
695   CW.printType(I->getType()->getElementType(), Out);
696   Out << "*)malloc(sizeof(";
697   CW.printTypeVar(I->getType()->getElementType(), "");
698   Out << ")";
699
700   if (I->isArrayAllocation()) {
701     Out << " * " ;
702     CW.writeOperand(I->getOperand(0), Out);
703   }
704   Out << ");";
705 }
706
707 void CInstPrintVisitor::visitAllocaInst(AllocaInst *I) {
708   outputLValue(I);
709   Operand = I->getNumOperands() ? I->getOperand(0) : 0;
710   string tempstr = "";
711   Out << "(";
712   CW.printTypeVar(I->getType(), tempstr);
713   Out << ") alloca(sizeof(";
714   CW.printTypeVar(cast<PointerType>(I->getType())->getElementType(), 
715                   tempstr);
716   Out << ")";
717   if (I->getNumOperands()) {
718     Out << " * " ;
719     CW.writeOperand(Operand, Out);
720   }
721   Out << ");\n";
722 }
723
724 void CInstPrintVisitor::visitFreeInst(FreeInst   *I) {
725   Operand = I->getNumOperands() ? I->getOperand(0) : 0;
726   Out << "free(";
727   CW.writeOperand(Operand, Out);
728   Out << ");\n";
729 }
730
731 void CInstPrintVisitor::visitLoadInst(LoadInst   *I) {
732   outputLValue(I);
733   Operand = I->getNumOperands() ? I->getOperand(0) : 0;
734   if (I->getNumOperands() <= 1) {
735     Out << "*";
736     CW.writeOperand(Operand, Out);     
737   }
738   else {
739     //Check if it is an array type or struct type ptr!
740     int arrtype = 1;
741     const PointerType *PTy = dyn_cast<PointerType>(I->getType());
742     if (cast<const PointerType>(Operand->getType())->getElementType()->getPrimitiveID() == Type::StructTyID)
743       arrtype = 0;
744     if (arrtype && isa<GlobalValue>(Operand))
745       Out << "(&";
746     CW.writeOperand(Operand,Out);
747     for (unsigned i = 1, E = I->getNumOperands(); i != E; ++i) {
748       if (i == 1) {
749         if (arrtype || !isa<GlobalValue>(Operand)) {
750           Out << "[";
751           CW.writeOperand(I->getOperand(i),  Out);
752           Out << "]";
753         }
754         if (isa<GlobalValue>(Operand) && arrtype)
755           Out << ")";
756       }
757       else {
758         if (arrtype == 1) Out << "[";
759         else 
760           Out << ".field";
761         CW.writeOperand(I->getOperand(i), Out);
762         if (arrtype == 1) Out << "]";
763       }
764     }
765   }
766   Out << ";\n";
767 }
768
769 void CInstPrintVisitor::visitStoreInst(StoreInst  *I) {
770   Operand = I->getNumOperands() ? I->getOperand(0) : 0;
771   if (I->getNumOperands() <= 2) {
772     Out << "*";
773     CW.writeOperand(I->getOperand(1), Out);
774   }
775   else {
776     //Check if it is an array type or struct type ptr!
777     int arrtype = 1;
778     if (cast<const PointerType>(I->getOperand(1)->getType())->getElementType()->getPrimitiveID() == Type::StructTyID) 
779       arrtype = 0;
780     if (isa<GlobalValue>(I->getOperand(1)) && arrtype)
781       Out << "(&";
782     CW.writeOperand(I->getOperand(1), Out);
783     for (unsigned i = 2, E = I->getNumOperands(); i != E; ++i) {
784       if (i == 2) {
785         if (arrtype || !isa<GlobalValue>(I->getOperand(1))) {
786           Out << "[";
787           CW.writeOperand(I->getOperand(i), Out);
788           Out << "]";
789         }
790         if (isa<GlobalValue>(I->getOperand(1)) && arrtype)
791           Out << ")";
792       }
793       else {
794         if (arrtype == 1) Out << "[";
795         else 
796           Out << ".field";
797         CW.writeOperand(I->getOperand(i), Out);
798         if (arrtype == 1) Out << "]";
799       }
800     }
801   }
802   Out << " = ";
803   CW.writeOperand(Operand, Out);
804   Out << ";\n";
805 }
806
807 void CInstPrintVisitor::visitGetElementPtrInst(GetElementPtrInst *I) {
808   outputLValue(I);
809   Operand = I->getNumOperands() ? I->getOperand(0) : 0;
810   Out << " &(";
811   if (I->getNumOperands() <= 1)
812     CW.writeOperand(Operand, Out);
813   else {
814     //Check if it is an array type or struct type ptr!
815     int arrtype = 1;
816     if ((cast<const PointerType>(Operand->getType()))->getElementType()->getPrimitiveID() == Type::StructTyID) 
817       arrtype = 0;
818     if ((isa<GlobalValue>(Operand)) && arrtype)
819       Out << "(&";    
820     CW.writeOperand(Operand, Out);
821     for (unsigned i = 1, E = I->getNumOperands(); i != E; ++i) {
822       if (i == 1) {
823         if (arrtype || !isa<GlobalValue>(Operand)){
824           Out << "[";
825           CW.writeOperand(I->getOperand(i), Out);
826           Out << "]";
827         }
828         if (isa<GlobalValue>(Operand) && arrtype)
829           Out << ")";
830       }
831       else {
832         if (arrtype == 1) Out << "[";
833         else 
834           Out << ".field";
835         CW.writeOperand(I->getOperand(i), Out);
836         if (arrtype == 1) Out << "]";
837       }
838     }
839   }
840   Out << ");\n";
841 }
842
843 void CInstPrintVisitor::visitNot(GenericUnaryInst *I) {
844   outputLValue(I);
845   Out << "~";
846   CW.writeOperand(I->getOperand(0), Out);
847   Out << ";\n";
848 }
849
850 void CInstPrintVisitor::visitBinaryOperator(Instruction *I) {
851   // binary instructions, shift instructions, setCond instructions.
852   outputLValue(I);
853   if (isa<PointerType>(I->getType())) {
854     Out << "(";
855     CW.printType(I->getType(), Out);
856     Out << ")";
857   }
858       
859   if (isa<PointerType>(I->getType())) Out << "(long long)";
860   CW.writeOperand(I->getOperand(0), Out);
861
862   switch (I->getOpcode()) {
863   case Instruction::Add: Out << "+"; break;
864   case Instruction::Sub: Out << "-"; break;
865   case Instruction::Mul: Out << "*"; break;
866   case Instruction::Div: Out << "/"; break;
867   case Instruction::Rem: Out << "%"; break;
868   case Instruction::And: Out << "&"; break;
869   case Instruction::Or: Out << "|"; break;
870   case Instruction::Xor: Out << "^"; break;
871   case Instruction::SetEQ: Out << "=="; break;
872   case Instruction::SetNE: Out << "!="; break;
873   case Instruction::SetLE: Out << "<="; break;
874   case Instruction::SetGE: Out << ">="; break;
875   case Instruction::SetLT: Out << "<"; break;
876   case Instruction::SetGT: Out << ">"; break;
877   case Instruction::Shl : Out << "<<"; break;
878   case Instruction::Shr : Out << ">>"; break;
879   default: cerr << "Invalid operator type!" << I; abort();
880   }
881
882   if (isa<PointerType>(I->getType())) Out << "(long long)";
883   CW.writeOperand(I->getOperand(1), Out);
884   Out << ";\n";
885 }
886
887 /* END : CInstPrintVisitor implementation */
888
889 string CWriter::getValueName(const Value *V) {
890   if (V->hasName())              // Print out the label if it exists...
891     return "llvm__" + makeNameProper(V->getName()) + "_" +
892            utostr(V->getType()->getUniqueID());
893
894   int Slot = Table.getValSlot(V);
895   assert(Slot >= 0 && "Invalid value!");
896   return "llvm__tmp_" + itostr(Slot) + "_" +
897          utostr(V->getType()->getUniqueID());
898 }
899
900 void CWriter::printModule(const Module *M) {
901   // printing stdlib inclusion
902   // Out << "#include <stdlib.h>\n";
903
904   // get declaration for alloca
905   Out << "/* Provide Declarations */\n"
906       << "#include <alloca.h>\n\n"
907
908     // Provide a definition for null if one does not already exist.
909       << "#ifndef NULL\n#define NULL 0\n#endif\n\n"
910       << "typedef unsigned char bool;\n"
911
912       << "\n\n/* Global Symbols */\n";
913
914   // Loop over the symbol table, emitting all named constants...
915   if (M->hasSymbolTable())
916     printSymbolTable(*M->getSymbolTable());
917
918   Out << "\n\n/* Global Data */\n";
919   for_each(M->gbegin(), M->gend(), 
920            bind_obj(this, &CWriter::printGlobal));
921
922   // First output all the declarations of the functions as C requires Functions 
923   // be declared before they are used.
924   //
925   Out << "\n\n/* Function Declarations */\n";
926   for_each(M->begin(), M->end(), bind_obj(this, &CWriter::printFunctionDecl));
927   
928   // Output all of the functions...
929   Out << "\n\n/* Function Bodies */\n";
930   for_each(M->begin(), M->end(), bind_obj(this, &CWriter::printFunction));
931 }
932
933 // prints the global constants
934 void CWriter::printGlobal(const GlobalVariable *GV) {
935   string tempostr = getValueName(GV);
936   if (GV->hasInternalLinkage()) Out << "static ";
937
938   printTypeVar(GV->getType()->getElementType(), tempostr);
939
940   if (GV->hasInitializer()) {
941     Out << " = " ;
942     writeOperand(GV->getInitializer(), Out, false);
943   }
944
945   Out << ";\n";
946 }
947
948 // printSymbolTable - Run through symbol table looking for named constants
949 // if a named constant is found, emit it's declaration...
950 // Assuming that symbol table has only types and constants.
951 void CWriter::printSymbolTable(const SymbolTable &ST) {
952   // GraphT G;
953   for (SymbolTable::const_iterator TI = ST.begin(); TI != ST.end(); ++TI) {
954     SymbolTable::type_const_iterator I = ST.type_begin(TI->first);
955     SymbolTable::type_const_iterator End = ST.type_end(TI->first);
956     
957     // TODO
958     // Need to run through all the used types in the program
959     // FindUsedTypes &FUT = new FindUsedTypes();
960     // const std::set<const Type *> &UsedTypes = FUT.getTypes();
961     // Filter out the structures printing forward definitions for each of them
962     // and creating the dependency graph.
963     // Print forward definitions to all of them
964     // print the typedefs topologically sorted
965
966     // But for now we have
967     for (; I != End; ++I) {
968       const Value *V = I->second;
969       if (const Constant *CPV = dyn_cast<const Constant>(V)) {
970         printConstant(CPV);
971       } else if (const Type *Ty = dyn_cast<const Type>(V)) {
972         string tempostr;
973         string tempstr = "";
974         Out << "typedef ";
975         tempostr = "llvm__" + I->first;
976         string TypeNameVar = calcTypeNameVar(Ty, TypeNames, 
977                                              tempostr, tempstr);
978         Out << TypeNameVar << ";\n";
979         if (!isa<PointerType>(Ty) ||
980             !cast<PointerType>(Ty)->getElementType()->isPrimitiveType())
981           TypeNames.insert(std::make_pair(Ty, "llvm__"+I->first));
982       }
983     }
984   }
985 }
986
987
988 // printConstant - Print out a constant pool entry...
989 //
990 void CWriter::printConstant(const Constant *CPV) {
991   // TODO
992   // Dinakar : Don't know what to do with unnamed constants
993   // should do something about it later.
994
995   string tempostr = getValueName(CPV);
996   
997   // Print out the constant type...
998   printTypeVar(CPV->getType(), tempostr);
999   
1000   Out << " = ";
1001   // Write the value out now...
1002   writeOperand(CPV, Out, false);
1003   
1004   Out << "\n";
1005 }
1006
1007 // printFunctionDecl - Print function declaration
1008 //
1009 void CWriter::printFunctionDecl(const Function *F) {
1010   printFunctionSignature(F);
1011   Out << ";\n";
1012 }
1013
1014 void CWriter::printFunctionSignature(const Function *F) {
1015   if (F->hasInternalLinkage()) Out << "static ";
1016   
1017   // Loop over the arguments, printing them...
1018   const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
1019   
1020   // Print out the return type and name...
1021   printType(F->getReturnType(), Out);
1022   Out << " " << makeNameProper(F->getName()) << "(";
1023     
1024   if (!F->isExternal()) {
1025     for_each(F->getArgumentList().begin(), F->getArgumentList().end(),
1026              bind_obj(this, &CWriter::printFunctionArgument));
1027   } else {
1028     // Loop over the arguments, printing them...
1029     for (FunctionType::ParamTypes::const_iterator I = 
1030            FT->getParamTypes().begin(),
1031            E = FT->getParamTypes().end(); I != E; ++I) {
1032       if (I != FT->getParamTypes().begin()) Out << ", ";
1033       printType(*I, Out);
1034     }
1035   }
1036
1037   // Finish printing arguments...
1038   if (FT->isVarArg()) {
1039     if (FT->getParamTypes().size()) Out << ", ";
1040     Out << "...";  // Output varargs portion of signature!
1041   }
1042   Out << ")";
1043 }
1044
1045
1046 // printFunctionArgument - This member is called for every argument that 
1047 // is passed into the method.  Simply print it out
1048 //
1049 void CWriter::printFunctionArgument(const Argument *Arg) {
1050   // Insert commas as we go... the first arg doesn't get a comma
1051   if (Arg != Arg->getParent()->getArgumentList().front()) Out << ", ";
1052   
1053   // Output type...
1054   printTypeVar(Arg->getType(), getValueName(Arg));
1055 }
1056
1057 void CWriter::printFunction(const Function *F) {
1058   if (F->isExternal()) return;
1059
1060   Table.incorporateFunction(F);
1061
1062   // Process each of the basic blocks, gather information and call the  
1063   // output methods on the CLocalVars and Function* objects.
1064     
1065   // gather local variable information for each basic block
1066   InstLocalVarsVisitor ILV(*this);
1067   ILV.visit((Function *)F);
1068
1069   printFunctionSignature(F);
1070   Out << " {\n";
1071
1072   // Loop over the symbol table, emitting all named constants...
1073   if (F->hasSymbolTable())
1074     printSymbolTable(*F->getSymbolTable()); 
1075   
1076   // print the local variables
1077   // we assume that every local variable is alloca'ed in the C code.
1078   std::map<const Type*, VarListType> &locals = ILV.CLV.LocalVars;
1079   
1080   map<const Type*, VarListType>::iterator iter;
1081   for (iter = locals.begin(); iter != locals.end(); ++iter) {
1082     VarListType::iterator listiter;
1083     for (listiter = iter->second.begin(); listiter != iter->second.end(); 
1084          ++listiter) {
1085       Out << "  ";
1086       printTypeVar(iter->first, *listiter);
1087       Out << ";\n";
1088     }
1089   }
1090  
1091   // print the basic blocks
1092   for_each(F->begin(), F->end(), bind_obj(this, &CWriter::outputBasicBlock));
1093   
1094   Out << "}\n";
1095   Table.purgeFunction();
1096 }
1097
1098 void CWriter::outputBasicBlock(const BasicBlock* BB) {
1099   Out << getValueName(BB) << ":\n";
1100
1101   // Output all of the instructions in the basic block...
1102   // print the basic blocks
1103   CInstPrintVisitor CIPV(*this, Table, Out);
1104   CIPV.visit((BasicBlock *) BB);
1105 }
1106
1107 // printType - Go to extreme measures to attempt to print out a short, symbolic
1108 // version of a type name.
1109 ostream& CWriter::printType(const Type *Ty, ostream &Out) {
1110   return printTypeInt(Out, Ty, TypeNames);
1111 }
1112
1113
1114 void CWriter::writeOperand(const Value *Operand,
1115                            ostream &Out, bool PrintName = true) {
1116   if (PrintName && Operand->hasName()) {   
1117     // If Operand has a name.
1118     Out << "llvm__" << makeNameProper(Operand->getName()) << "_" << 
1119       Operand->getType()->getUniqueID();
1120     return;
1121   } 
1122   else if (const Constant *CPV = dyn_cast<const Constant>(Operand)) {
1123     if (isa<ConstantPointerNull>(CPV))
1124       Out << "NULL";
1125     else
1126       Out << getConstStrValue(CPV); 
1127   }
1128   else {
1129     int Slot = Table.getValSlot(Operand);
1130     if (Slot >= 0)  
1131       Out << "llvm__tmp_" << Slot << "_" << Operand->getType()->getUniqueID();
1132     else if (PrintName)
1133       Out << "<badref>";
1134   }
1135 }
1136
1137
1138 //===----------------------------------------------------------------------===//
1139 //                       External Interface declaration
1140 //===----------------------------------------------------------------------===//
1141
1142 void WriteToC(const Module *M, ostream &Out) {
1143   assert(M && "You can't write a null module!!");
1144   SlotCalculator SlotTable(M, false);
1145   CWriter W(Out, SlotTable, M);
1146   W.write(M);
1147   Out.flush();
1148 }