Sign-extend array index expressions to work correctly on non-32 bit machines.
[oota-llvm.git] / lib / Target / CBackend / Writer.cpp
1 //===-- Writer.cpp - Library for converting LLVM code to C ----------------===//
2 //
3 // This library implements the functionality defined in llvm/Assembly/CWriter.h
4 //
5 // TODO : Recursive types.
6 //
7 //===-----------------------------------------------------------------------==//
8
9 #include "llvm/Assembly/CWriter.h"
10 #include "llvm/Constants.h"
11 #include "llvm/DerivedTypes.h"
12 #include "llvm/Module.h"
13 #include "llvm/iMemory.h"
14 #include "llvm/iTerminators.h"
15 #include "llvm/iPHINode.h"
16 #include "llvm/iOther.h"
17 #include "llvm/iOperators.h"
18 #include "llvm/SymbolTable.h"
19 #include "llvm/SlotCalculator.h"
20 #include "llvm/Support/InstVisitor.h"
21 #include "llvm/Support/InstIterator.h"
22 #include "Support/StringExtras.h"
23 #include "Support/STLExtras.h"
24 #include <algorithm>
25 #include <set>
26 using std::string;
27 using std::map;
28 using std::ostream;
29
30 namespace {
31   class CWriter : public InstVisitor<CWriter> {
32     ostream& Out; 
33     SlotCalculator &Table;
34     const Module *TheModule;
35     map<const Type *, string> TypeNames;
36     std::set<const Value*> MangledGlobals;
37   public:
38     inline CWriter(ostream &o, SlotCalculator &Tab, const Module *M)
39       : Out(o), Table(Tab), TheModule(M) {
40     }
41     
42     inline void write(Module *M) { printModule(M); }
43
44     ostream &printType(const Type *Ty, const string &VariableName = "",
45                        bool IgnoreName = false);
46
47     void writeOperand(Value *Operand);
48     void writeOperandInternal(Value *Operand);
49
50     string getValueName(const Value *V);
51
52   private :
53     void printModule(Module *M);
54     void printSymbolTable(const SymbolTable &ST);
55     void printGlobal(const GlobalVariable *GV);
56     void printFunctionSignature(const Function *F, bool Prototype);
57
58     void printFunction(Function *);
59
60     void printConstant(Constant *CPV);
61     void printConstantArray(ConstantArray *CPA);
62
63     // isInlinableInst - Attempt to inline instructions into their uses to build
64     // trees as much as possible.  To do this, we have to consistently decide
65     // what is acceptable to inline, so that variable declarations don't get
66     // printed and an extra copy of the expr is not emitted.
67     //
68     static bool isInlinableInst(const Instruction &I) {
69       // Must be an expression, must be used exactly once.  If it is dead, we
70       // emit it inline where it would go.
71       if (I.getType() == Type::VoidTy || I.use_size() != 1 ||
72           isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I))
73         return false;
74
75       // Only inline instruction it it's use is in the same BB as the inst.
76       return I.getParent() == cast<Instruction>(I.use_back())->getParent();
77     }
78
79     // Instruction visitation functions
80     friend class InstVisitor<CWriter>;
81
82     void visitReturnInst(ReturnInst &I);
83     void visitBranchInst(BranchInst &I);
84
85     void visitPHINode(PHINode &I) {}
86     void visitBinaryOperator(Instruction &I);
87
88     void visitCastInst (CastInst &I);
89     void visitCallInst (CallInst &I);
90     void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
91
92     void visitMallocInst(MallocInst &I);
93     void visitAllocaInst(AllocaInst &I);
94     void visitFreeInst  (FreeInst   &I);
95     void visitLoadInst  (LoadInst   &I);
96     void visitStoreInst (StoreInst  &I);
97     void visitGetElementPtrInst(GetElementPtrInst &I);
98
99     void visitInstruction(Instruction &I) {
100       std::cerr << "C Writer does not know about " << I;
101       abort();
102     }
103
104     void outputLValue(Instruction *I) {
105       Out << "  " << getValueName(I) << " = ";
106     }
107     void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
108                             unsigned Indent);
109     void printIndexingExpression(Value *Ptr, User::op_iterator I,
110                                  User::op_iterator E);
111   };
112 }
113
114 // We dont want identifier names with ., space, -  in them. 
115 // So we replace them with _
116 static string makeNameProper(string x) {
117   string tmp;
118   for (string::iterator sI = x.begin(), sEnd = x.end(); sI != sEnd; sI++)
119     switch (*sI) {
120     case '.': tmp += "d_"; break;
121     case ' ': tmp += "s_"; break;
122     case '-': tmp += "D_"; break;
123     default:  tmp += *sI;
124     }
125
126   return tmp;
127 }
128
129 string CWriter::getValueName(const Value *V) {
130   if (V->hasName()) {              // Print out the label if it exists...
131     if (isa<GlobalValue>(V) &&     // Do not mangle globals...
132         cast<GlobalValue>(V)->hasExternalLinkage() && // Unless it's internal or
133         !MangledGlobals.count(V))  // Unless the name would collide if we don't
134       return makeNameProper(V->getName());
135
136     return "l" + utostr(V->getType()->getUniqueID()) + "_" +
137            makeNameProper(V->getName());      
138   }
139
140   int Slot = Table.getValSlot(V);
141   assert(Slot >= 0 && "Invalid value!");
142   return "ltmp_" + itostr(Slot) + "_" + utostr(V->getType()->getUniqueID());
143 }
144
145 // Pass the Type* and the variable name and this prints out the variable
146 // declaration.
147 //
148 ostream &CWriter::printType(const Type *Ty, const string &NameSoFar,
149                             bool IgnoreName) {
150   if (Ty->isPrimitiveType())
151     switch (Ty->getPrimitiveID()) {
152     case Type::VoidTyID:   return Out << "void "               << NameSoFar;
153     case Type::BoolTyID:   return Out << "bool "               << NameSoFar;
154     case Type::UByteTyID:  return Out << "unsigned char "      << NameSoFar;
155     case Type::SByteTyID:  return Out << "signed char "        << NameSoFar;
156     case Type::UShortTyID: return Out << "unsigned short "     << NameSoFar;
157     case Type::ShortTyID:  return Out << "short "              << NameSoFar;
158     case Type::UIntTyID:   return Out << "unsigned "           << NameSoFar;
159     case Type::IntTyID:    return Out << "int "                << NameSoFar;
160     case Type::ULongTyID:  return Out << "unsigned long long " << NameSoFar;
161     case Type::LongTyID:   return Out << "signed long long "   << NameSoFar;
162     case Type::FloatTyID:  return Out << "float "              << NameSoFar;
163     case Type::DoubleTyID: return Out << "double "             << NameSoFar;
164     default :
165       std::cerr << "Unknown primitive type: " << Ty << "\n";
166       abort();
167     }
168   
169   // Check to see if the type is named.
170   if (!IgnoreName) {
171     map<const Type *, string>::iterator I = TypeNames.find(Ty);
172     if (I != TypeNames.end()) {
173       return Out << I->second << " " << NameSoFar;
174     }
175   }  
176
177   switch (Ty->getPrimitiveID()) {
178   case Type::FunctionTyID: {
179     const FunctionType *MTy = cast<FunctionType>(Ty);
180     printType(MTy->getReturnType(), "");
181     Out << " " << NameSoFar << " (";
182
183     for (FunctionType::ParamTypes::const_iterator
184            I = MTy->getParamTypes().begin(),
185            E = MTy->getParamTypes().end(); I != E; ++I) {
186       if (I != MTy->getParamTypes().begin())
187         Out << ", ";
188       printType(*I, "");
189     }
190     if (MTy->isVarArg()) {
191       if (!MTy->getParamTypes().empty()) 
192         Out << ", ";
193       Out << "...";
194     }
195     return Out << ")";
196   }
197   case Type::StructTyID: {
198     const StructType *STy = cast<StructType>(Ty);
199     Out << NameSoFar + " {\n";
200     unsigned Idx = 0;
201     for (StructType::ElementTypes::const_iterator
202            I = STy->getElementTypes().begin(),
203            E = STy->getElementTypes().end(); I != E; ++I) {
204       Out << "  ";
205       printType(*I, "field" + utostr(Idx++));
206       Out << ";\n";
207     }
208     return Out << "}";
209   }  
210
211   case Type::PointerTyID: {
212     const PointerType *PTy = cast<PointerType>(Ty);
213     std::string ptrName = NameSoFar.length()? "(*"+NameSoFar+")" : string("*");
214     return printType(PTy->getElementType(), ptrName);
215   }
216
217   case Type::ArrayTyID: {
218     const ArrayType *ATy = cast<ArrayType>(Ty);
219     unsigned NumElements = ATy->getNumElements();
220     return printType(ATy->getElementType(),
221                      NameSoFar + "[" + utostr(NumElements) + "]");
222   }
223   default:
224     assert(0 && "Unhandled case in getTypeProps!");
225     abort();
226   }
227
228   return Out;
229 }
230
231 void CWriter::printConstantArray(ConstantArray *CPA) {
232
233   // As a special case, print the array as a string if it is an array of
234   // ubytes or an array of sbytes with positive values.
235   // 
236   const Type *ETy = CPA->getType()->getElementType();
237   bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
238
239   // Make sure the last character is a null char, as automatically added by C
240   if (CPA->getNumOperands() == 0 ||
241       !cast<Constant>(*(CPA->op_end()-1))->isNullValue())
242     isString = false;
243   
244   if (isString) {
245     Out << "\"";
246     // Do not include the last character, which we know is null
247     for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
248       unsigned char C = (ETy == Type::SByteTy) ?
249         (unsigned char)cast<ConstantSInt>(CPA->getOperand(i))->getValue() :
250         (unsigned char)cast<ConstantUInt>(CPA->getOperand(i))->getValue();
251       
252       if (isprint(C)) {
253         Out << C;
254       } else {
255         switch (C) {
256         case '\n': Out << "\\n"; break;
257         case '\t': Out << "\\t"; break;
258         case '\r': Out << "\\r"; break;
259         case '\v': Out << "\\v"; break;
260         case '\a': Out << "\\a"; break;
261         default:
262           Out << "\\x";
263           Out << ( C/16  < 10) ? ( C/16 +'0') : ( C/16 -10+'A');
264           Out << ((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A');
265           break;
266         }
267       }
268     }
269     Out << "\"";
270   } else {
271     Out << "{";
272     if (CPA->getNumOperands()) {
273       Out << " ";
274       printConstant(cast<Constant>(CPA->getOperand(0)));
275       for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
276         Out << ", ";
277         printConstant(cast<Constant>(CPA->getOperand(i)));
278       }
279     }
280     Out << " }";
281   }
282 }
283
284
285 // printConstant - The LLVM Constant to C Constant converter.
286 void CWriter::printConstant(Constant *CPV) {
287   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
288     switch (CE->getOpcode()) {
289     case Instruction::Cast:
290       Out << "((";
291       printType(CPV->getType());
292       Out << ")";
293       printConstant(cast<Constant>(CPV->getOperand(0)));
294       Out << ")";
295       return;
296
297     case Instruction::GetElementPtr:
298       Out << "&(";
299       printIndexingExpression(CPV->getOperand(0),
300                               CPV->op_begin()+1, CPV->op_end());
301       Out << ")";
302       return;
303     case Instruction::Add:
304       Out << "(";
305       printConstant(cast<Constant>(CPV->getOperand(0)));
306       Out << " + ";
307       printConstant(cast<Constant>(CPV->getOperand(1)));
308       Out << ")";
309       return;
310     case Instruction::Sub:
311       Out << "(";
312       printConstant(cast<Constant>(CPV->getOperand(0)));
313       Out << " - ";
314       printConstant(cast<Constant>(CPV->getOperand(1)));
315       Out << ")";
316       return;
317
318     default:
319       std::cerr << "CWriter Error: Unhandled constant expression: "
320                 << CE << "\n";
321       abort();
322     }
323   }
324
325   switch (CPV->getType()->getPrimitiveID()) {
326   case Type::BoolTyID:
327     Out << (CPV == ConstantBool::False ? "0" : "1"); break;
328   case Type::SByteTyID:
329   case Type::ShortTyID:
330   case Type::IntTyID:
331     Out << cast<ConstantSInt>(CPV)->getValue(); break;
332   case Type::LongTyID:
333     Out << cast<ConstantSInt>(CPV)->getValue() << "ll"; break;
334
335   case Type::UByteTyID:
336   case Type::UShortTyID:
337     Out << cast<ConstantUInt>(CPV)->getValue(); break;
338   case Type::UIntTyID:
339     Out << cast<ConstantUInt>(CPV)->getValue() << "u"; break;
340   case Type::ULongTyID:
341     Out << cast<ConstantUInt>(CPV)->getValue() << "ull"; break;
342
343   case Type::FloatTyID:
344   case Type::DoubleTyID:
345     Out << cast<ConstantFP>(CPV)->getValue(); break;
346
347   case Type::ArrayTyID:
348     printConstantArray(cast<ConstantArray>(CPV));
349     break;
350
351   case Type::StructTyID: {
352     Out << "{";
353     if (CPV->getNumOperands()) {
354       Out << " ";
355       printConstant(cast<Constant>(CPV->getOperand(0)));
356       for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
357         Out << ", ";
358         printConstant(cast<Constant>(CPV->getOperand(i)));
359       }
360     }
361     Out << " }";
362     break;
363   }
364
365   case Type::PointerTyID:
366     if (isa<ConstantPointerNull>(CPV)) {
367       Out << "((";
368       printType(CPV->getType(), "");
369       Out << ")NULL)";
370       break;
371     } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CPV)) {
372       writeOperand(CPR->getValue());
373       break;
374     }
375     // FALL THROUGH
376   default:
377     std::cerr << "Unknown constant type: " << CPV << "\n";
378     abort();
379   }
380 }
381
382 void CWriter::writeOperandInternal(Value *Operand) {
383   if (Instruction *I = dyn_cast<Instruction>(Operand))
384     if (isInlinableInst(*I)) {
385       // Should we inline this instruction to build a tree?
386       Out << "(";
387       visit(*I);
388       Out << ")";    
389       return;
390     }
391   
392   if (Operand->hasName()) {   
393     Out << getValueName(Operand);
394   } else if (Constant *CPV = dyn_cast<Constant>(Operand)) {
395     printConstant(CPV); 
396   } else {
397     int Slot = Table.getValSlot(Operand);
398     assert(Slot >= 0 && "Malformed LLVM!");
399     Out << "ltmp_" << Slot << "_" << Operand->getType()->getUniqueID();
400   }
401 }
402
403 void CWriter::writeOperand(Value *Operand) {
404   if (isa<GlobalVariable>(Operand))
405     Out << "(&";  // Global variables are references as their addresses by llvm
406
407   writeOperandInternal(Operand);
408
409   if (isa<GlobalVariable>(Operand))
410     Out << ")";
411 }
412
413 void CWriter::printModule(Module *M) {
414   // Calculate which global values have names that will collide when we throw
415   // away type information.
416   {  // Scope to delete the FoundNames set when we are done with it...
417     std::set<string> FoundNames;
418     for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
419       if (I->hasName())                      // If the global has a name...
420         if (FoundNames.count(I->getName()))  // And the name is already used
421           MangledGlobals.insert(I);          // Mangle the name
422         else
423           FoundNames.insert(I->getName());   // Otherwise, keep track of name
424
425     for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
426       if (I->hasName())                      // If the global has a name...
427         if (FoundNames.count(I->getName()))  // And the name is already used
428           MangledGlobals.insert(I);          // Mangle the name
429         else
430           FoundNames.insert(I->getName());   // Otherwise, keep track of name
431   }
432
433
434   // printing stdlib inclusion
435   // Out << "#include <stdlib.h>\n";
436
437   // get declaration for alloca
438   Out << "/* Provide Declarations */\n"
439       << "#include <malloc.h>\n"
440       << "#include <alloca.h>\n\n"
441
442     // Provide a definition for null if one does not already exist.
443       << "#ifndef NULL\n#define NULL 0\n#endif\n\n"
444       << "typedef unsigned char bool;\n"
445
446       << "\n\n/* Global Declarations */\n";
447
448   // First output all the declarations for the program, because C requires
449   // Functions & globals to be declared before they are used.
450   //
451
452   // Loop over the symbol table, emitting all named constants...
453   if (M->hasSymbolTable())
454     printSymbolTable(*M->getSymbolTable());
455
456   // Global variable declarations...
457   if (!M->gempty()) {
458     Out << "\n/* Global Variable Declarations */\n";
459     for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) {
460       Out << (I->hasExternalLinkage() ? "extern " : "static ");
461       printType(I->getType()->getElementType(), getValueName(I));
462       Out << ";\n";
463     }
464   }
465
466   // Function declarations
467   if (!M->empty()) {
468     Out << "\n/* Function Declarations */\n";
469     for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
470       printFunctionSignature(I, true);
471       Out << ";\n";
472     }
473   }
474
475   // Output the global variable contents...
476   if (!M->gempty()) {
477     Out << "\n\n/* Global Data */\n";
478     for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) {
479       if (I->hasInternalLinkage()) Out << "static ";
480       printType(I->getType()->getElementType(), getValueName(I));
481       
482       if (I->hasInitializer()) {
483         Out << " = " ;
484         writeOperand(I->getInitializer());
485       }
486       Out << ";\n";
487     }
488   }
489
490   // Output all of the functions...
491   if (!M->empty()) {
492     Out << "\n\n/* Function Bodies */\n";
493     for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
494       printFunction(I);
495   }
496 }
497
498
499 // printSymbolTable - Run through symbol table looking for named constants
500 // if a named constant is found, emit it's declaration...
501 // Assuming that symbol table has only types and constants.
502 void CWriter::printSymbolTable(const SymbolTable &ST) {
503   for (SymbolTable::const_iterator TI = ST.begin(); TI != ST.end(); ++TI) {
504     SymbolTable::type_const_iterator I = ST.type_begin(TI->first);
505     SymbolTable::type_const_iterator End = ST.type_end(TI->first);
506     
507     for (; I != End; ++I)
508       if (const Type *Ty = dyn_cast<StructType>(I->second)) {
509         string Name = "struct l_" + makeNameProper(I->first);
510         Out << Name << ";\n";
511         TypeNames.insert(std::make_pair(Ty, Name));
512       }
513   }
514
515   Out << "\n";
516
517   for (SymbolTable::const_iterator TI = ST.begin(); TI != ST.end(); ++TI) {
518     SymbolTable::type_const_iterator I = ST.type_begin(TI->first);
519     SymbolTable::type_const_iterator End = ST.type_end(TI->first);
520     
521     for (; I != End; ++I) {
522       const Value *V = I->second;
523       if (const Type *Ty = dyn_cast<Type>(V)) {
524         string Name = "l_" + makeNameProper(I->first);
525         if (isa<StructType>(Ty))
526           Name = "struct " + makeNameProper(Name);
527         else
528           Out << "typedef ";
529
530         printType(Ty, Name, true);
531         Out << ";\n";
532       }
533     }
534   }
535 }
536
537
538 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
539   if (F->hasInternalLinkage()) Out << "static ";
540   
541   // Loop over the arguments, printing them...
542   const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
543   
544   // Print out the return type and name...
545   printType(F->getReturnType());
546   Out << getValueName(F) << "(";
547     
548   if (!F->isExternal()) {
549     if (!F->aempty()) {
550       string ArgName;
551       if (F->abegin()->hasName() || !Prototype)
552         ArgName = getValueName(F->abegin());
553
554       printType(F->afront().getType(), ArgName);
555
556       for (Function::const_aiterator I = ++F->abegin(), E = F->aend();
557            I != E; ++I) {
558         Out << ", ";
559         if (I->hasName() || !Prototype)
560           ArgName = getValueName(I);
561         else 
562           ArgName = "";
563         printType(I->getType(), ArgName);
564       }
565     }
566   } else {
567     // Loop over the arguments, printing them...
568     for (FunctionType::ParamTypes::const_iterator I = 
569            FT->getParamTypes().begin(),
570            E = FT->getParamTypes().end(); I != E; ++I) {
571       if (I != FT->getParamTypes().begin()) Out << ", ";
572       printType(*I);
573     }
574   }
575
576   // Finish printing arguments...
577   if (FT->isVarArg()) {
578     if (FT->getParamTypes().size()) Out << ", ";
579     Out << "...";  // Output varargs portion of signature!
580   }
581   Out << ")";
582 }
583
584
585 void CWriter::printFunction(Function *F) {
586   if (F->isExternal()) return;
587
588   Table.incorporateFunction(F);
589
590   printFunctionSignature(F, false);
591   Out << " {\n";
592
593   // print local variable information for the function
594   for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
595     if ((*I)->getType() != Type::VoidTy && !isInlinableInst(**I)) {
596       Out << "  ";
597       printType((*I)->getType(), getValueName(*I));
598       Out << ";\n";
599     }
600  
601   // print the basic blocks
602   for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
603     BasicBlock *Prev = BB->getPrev();
604
605     // Don't print the label for the basic block if there are no uses, or if the
606     // only terminator use is the precessor basic block's terminator.  We have
607     // to scan the use list because PHI nodes use basic blocks too but do not
608     // require a label to be generated.
609     //
610     bool NeedsLabel = false;
611     for (Value::use_iterator UI = BB->use_begin(), UE = BB->use_end();
612          UI != UE; ++UI)
613       if (TerminatorInst *TI = dyn_cast<TerminatorInst>(*UI))
614         if (TI != Prev->getTerminator()) {
615           NeedsLabel = true;
616           break;        
617         }
618
619     if (NeedsLabel) Out << getValueName(BB) << ":\n";
620
621     // Output all of the instructions in the basic block...
622     for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E; ++II){
623       if (!isInlinableInst(*II) && !isa<PHINode>(*II)) {
624         if (II->getType() != Type::VoidTy)
625           outputLValue(II);
626         else
627           Out << "  ";
628         visit(*II);
629         Out << ";\n";
630       }
631     }
632
633     // Don't emit prefix or suffix for the terminator...
634     visit(*BB->getTerminator());
635   }
636   
637   Out << "}\n\n";
638   Table.purgeFunction();
639 }
640
641 // Specific Instruction type classes... note that all of the casts are
642 // neccesary because we use the instruction classes as opaque types...
643 //
644 void CWriter::visitReturnInst(ReturnInst &I) {
645   // Don't output a void return if this is the last basic block in the function
646   if (I.getNumOperands() == 0 && 
647       &*--I.getParent()->getParent()->end() == I.getParent() &&
648       !I.getParent()->size() == 1) {
649     return;
650   }
651
652   Out << "  return";
653   if (I.getNumOperands()) {
654     Out << " ";
655     writeOperand(I.getOperand(0));
656   }
657   Out << ";\n";
658 }
659
660 static bool isGotoCodeNeccessary(BasicBlock *From, BasicBlock *To) {
661   // If PHI nodes need copies, we need the copy code...
662   if (isa<PHINode>(To->front()) ||
663       From->getNext() != To)      // Not directly successor, need goto
664     return true;
665
666   // Otherwise we don't need the code.
667   return false;
668 }
669
670 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
671                                            unsigned Indent) {
672   for (BasicBlock::iterator I = Succ->begin();
673        PHINode *PN = dyn_cast<PHINode>(&*I); ++I) {
674     //  now we have to do the printing
675     Out << string(Indent, ' ');
676     outputLValue(PN);
677     writeOperand(PN->getIncomingValue(PN->getBasicBlockIndex(CurBB)));
678     Out << ";   /* for PHI node */\n";
679   }
680
681   if (CurBB->getNext() != Succ) {
682     Out << string(Indent, ' ') << "  goto ";
683     writeOperand(Succ);
684     Out << ";\n";
685   }
686 }
687
688 // Brach instruction printing - Avoid printing out a brach to a basic block that
689 // immediately succeeds the current one.
690 //
691 void CWriter::visitBranchInst(BranchInst &I) {
692   if (I.isConditional()) {
693     if (isGotoCodeNeccessary(I.getParent(), I.getSuccessor(0))) {
694       Out << "  if (";
695       writeOperand(I.getCondition());
696       Out << ") {\n";
697       
698       printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
699       
700       if (isGotoCodeNeccessary(I.getParent(), I.getSuccessor(1))) {
701         Out << "  } else {\n";
702         printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
703       }
704     } else {
705       // First goto not neccesary, assume second one is...
706       Out << "  if (!";
707       writeOperand(I.getCondition());
708       Out << ") {\n";
709
710       printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
711     }
712
713     Out << "  }\n";
714   } else {
715     printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
716   }
717   Out << "\n";
718 }
719
720
721 void CWriter::visitBinaryOperator(Instruction &I) {
722   // binary instructions, shift instructions, setCond instructions.
723   if (isa<PointerType>(I.getType())) {
724     Out << "(";
725     printType(I.getType());
726     Out << ")";
727   }
728       
729   if (isa<PointerType>(I.getType())) Out << "(long long)";
730   writeOperand(I.getOperand(0));
731
732   switch (I.getOpcode()) {
733   case Instruction::Add: Out << " + "; break;
734   case Instruction::Sub: Out << " - "; break;
735   case Instruction::Mul: Out << "*"; break;
736   case Instruction::Div: Out << "/"; break;
737   case Instruction::Rem: Out << "%"; break;
738   case Instruction::And: Out << " & "; break;
739   case Instruction::Or: Out << " | "; break;
740   case Instruction::Xor: Out << " ^ "; break;
741   case Instruction::SetEQ: Out << " == "; break;
742   case Instruction::SetNE: Out << " != "; break;
743   case Instruction::SetLE: Out << " <= "; break;
744   case Instruction::SetGE: Out << " >= "; break;
745   case Instruction::SetLT: Out << " < "; break;
746   case Instruction::SetGT: Out << " > "; break;
747   case Instruction::Shl : Out << " << "; break;
748   case Instruction::Shr : Out << " >> "; break;
749   default: std::cerr << "Invalid operator type!" << I; abort();
750   }
751
752   if (isa<PointerType>(I.getType())) Out << "(long long)";
753   writeOperand(I.getOperand(1));
754 }
755
756 void CWriter::visitCastInst(CastInst &I) {
757   Out << "(";
758   printType(I.getType());
759   Out << ")";
760   writeOperand(I.getOperand(0));
761 }
762
763 void CWriter::visitCallInst(CallInst &I) {
764   const PointerType  *PTy   = cast<PointerType>(I.getCalledValue()->getType());
765   const FunctionType *FTy   = cast<FunctionType>(PTy->getElementType());
766   const Type         *RetTy = FTy->getReturnType();
767   
768   Out << getValueName(I.getOperand(0)) << "(";
769
770   if (I.getNumOperands() > 1) {
771     writeOperand(I.getOperand(1));
772
773     for (unsigned op = 2, Eop = I.getNumOperands(); op != Eop; ++op) {
774       Out << ", ";
775       writeOperand(I.getOperand(op));
776     }
777   }
778   Out << ")";
779 }  
780
781 void CWriter::visitMallocInst(MallocInst &I) {
782   Out << "(";
783   printType(I.getType());
784   Out << ")malloc(sizeof(";
785   printType(I.getType()->getElementType());
786   Out << ")";
787
788   if (I.isArrayAllocation()) {
789     Out << " * " ;
790     writeOperand(I.getOperand(0));
791   }
792   Out << ")";
793 }
794
795 void CWriter::visitAllocaInst(AllocaInst &I) {
796   Out << "(";
797   printType(I.getType());
798   Out << ") alloca(sizeof(";
799   printType(I.getType()->getElementType());
800   Out << ")";
801   if (I.isArrayAllocation()) {
802     Out << " * " ;
803     writeOperand(I.getOperand(0));
804   }
805   Out << ")";
806 }
807
808 void CWriter::visitFreeInst(FreeInst &I) {
809   Out << "free(";
810   writeOperand(I.getOperand(0));
811   Out << ")";
812 }
813
814 void CWriter::printIndexingExpression(Value *Ptr, User::op_iterator I,
815                                       User::op_iterator E) {
816   bool HasImplicitAddress = false;
817   // If accessing a global value with no indexing, avoid *(&GV) syndrome
818   if (GlobalValue *V = dyn_cast<GlobalValue>(Ptr)) {
819     HasImplicitAddress = true;
820   } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Ptr)) {
821     HasImplicitAddress = true;
822     Ptr = CPR->getValue();         // Get to the global...
823   }
824
825   if (I == E) {
826     if (!HasImplicitAddress)
827       Out << "*";  // Implicit zero first argument: '*x' is equivalent to 'x[0]'
828
829     writeOperandInternal(Ptr);
830     return;
831   }
832
833   const Constant *CI = dyn_cast<Constant>(I->get());
834   if (HasImplicitAddress && (!CI || !CI->isNullValue()))
835     Out << "(&";
836
837   writeOperandInternal(Ptr);
838
839   if (HasImplicitAddress && (!CI || !CI->isNullValue()))
840     Out << ")";
841
842   // Print out the -> operator if possible...
843   if (CI && CI->isNullValue() && I+1 != E) {
844     if ((*(I+1))->getType() == Type::UByteTy) {
845       Out << (HasImplicitAddress ? "." : "->");
846       Out << "field" << cast<ConstantUInt>(*(I+1))->getValue();
847       I += 2;
848     } else {  // First array index of 0: Just skip it
849       ++I;
850     }
851   }
852
853   for (; I != E; ++I)
854     if ((*I)->getType() == Type::UIntTy) {
855       Out << "[((int) (";                 // sign-extend from 32 (to 64) bits
856       writeOperand(*I);
857       Out << " * sizeof(";
858       printType(cast<PointerType>(Ptr->getType())->getElementType());
859       Out << "))) / sizeof(";
860       printType(cast<PointerType>(Ptr->getType())->getElementType());
861       Out << ")]";
862     } else {
863       Out << ".field" << cast<ConstantUInt>(*I)->getValue();
864     }
865 }
866
867 void CWriter::visitLoadInst(LoadInst &I) {
868   Out << "*";
869   writeOperand(I.getOperand(0));
870 }
871
872 void CWriter::visitStoreInst(StoreInst &I) {
873   Out << "*";
874   writeOperand(I.getPointerOperand());
875   Out << " = ";
876   writeOperand(I.getOperand(0));
877 }
878
879 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
880   Out << "&";
881   printIndexingExpression(I.getPointerOperand(), I.idx_begin(), I.idx_end());
882 }
883
884 //===----------------------------------------------------------------------===//
885 //                       External Interface declaration
886 //===----------------------------------------------------------------------===//
887
888 void WriteToC(const Module *M, ostream &Out) {
889   assert(M && "You can't write a null module!!");
890   SlotCalculator SlotTable(M, false);
891   CWriter W(Out, SlotTable, M);
892   W.write((Module*)M);
893   Out.flush();
894 }