Fix bug: 2002-08-20-UnnamedArgument.c
[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 = false) {
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     return printType(PTy->getElementType(), "(*" + NameSoFar + ")");
214   }
215
216   case Type::ArrayTyID: {
217     const ArrayType *ATy = cast<ArrayType>(Ty);
218     unsigned NumElements = ATy->getNumElements();
219     return printType(ATy->getElementType(),
220                      NameSoFar + "[" + utostr(NumElements) + "]");
221   }
222   default:
223     assert(0 && "Unhandled case in getTypeProps!");
224     abort();
225   }
226
227   return Out;
228 }
229
230 void CWriter::printConstantArray(ConstantArray *CPA) {
231
232   // As a special case, print the array as a string if it is an array of
233   // ubytes or an array of sbytes with positive values.
234   // 
235   const Type *ETy = CPA->getType()->getElementType();
236   bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
237
238   // Make sure the last character is a null char, as automatically added by C
239   if (CPA->getNumOperands() == 0 ||
240       !cast<Constant>(*(CPA->op_end()-1))->isNullValue())
241     isString = false;
242   
243   if (isString) {
244     Out << "\"";
245     // Do not include the last character, which we know is null
246     for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
247       unsigned char C = (ETy == Type::SByteTy) ?
248         (unsigned char)cast<ConstantSInt>(CPA->getOperand(i))->getValue() :
249         (unsigned char)cast<ConstantUInt>(CPA->getOperand(i))->getValue();
250       
251       if (isprint(C)) {
252         Out << C;
253       } else {
254         switch (C) {
255         case '\n': Out << "\\n"; break;
256         case '\t': Out << "\\t"; break;
257         case '\r': Out << "\\r"; break;
258         case '\v': Out << "\\v"; break;
259         case '\a': Out << "\\a"; break;
260         default:
261           Out << "\\x";
262           Out << ( C/16  < 10) ? ( C/16 +'0') : ( C/16 -10+'A');
263           Out << ((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A');
264           break;
265         }
266       }
267     }
268     Out << "\"";
269   } else {
270     Out << "{";
271     if (CPA->getNumOperands()) {
272       Out << " ";
273       printConstant(cast<Constant>(CPA->getOperand(0)));
274       for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
275         Out << ", ";
276         printConstant(cast<Constant>(CPA->getOperand(i)));
277       }
278     }
279     Out << " }";
280   }
281 }
282
283
284 // printConstant - The LLVM Constant to C Constant converter.
285 void CWriter::printConstant(Constant *CPV) {
286   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
287     switch (CE->getOpcode()) {
288     case Instruction::Cast:
289       Out << "((";
290       printType(CPV->getType());
291       Out << ")";
292       printConstant(cast<Constant>(CPV->getOperand(0)));
293       Out << ")";
294       return;
295
296     case Instruction::GetElementPtr:
297       Out << "&(";
298       printIndexingExpression(CPV->getOperand(0),
299                               CPV->op_begin()+1, CPV->op_end());
300       Out << ")";
301       return;
302     case Instruction::Add:
303       Out << "(";
304       printConstant(cast<Constant>(CPV->getOperand(0)));
305       Out << " + ";
306       printConstant(cast<Constant>(CPV->getOperand(1)));
307       Out << ")";
308       return;
309     case Instruction::Sub:
310       Out << "(";
311       printConstant(cast<Constant>(CPV->getOperand(0)));
312       Out << " - ";
313       printConstant(cast<Constant>(CPV->getOperand(1)));
314       Out << ")";
315       return;
316
317     default:
318       std::cerr << "CWriter Error: Unhandled constant expression: "
319                 << CE << "\n";
320       abort();
321     }
322   }
323
324   switch (CPV->getType()->getPrimitiveID()) {
325   case Type::BoolTyID:
326     Out << (CPV == ConstantBool::False ? "0" : "1"); break;
327   case Type::SByteTyID:
328   case Type::ShortTyID:
329   case Type::IntTyID:
330     Out << cast<ConstantSInt>(CPV)->getValue(); break;
331   case Type::LongTyID:
332     Out << cast<ConstantSInt>(CPV)->getValue() << "ll"; break;
333
334   case Type::UByteTyID:
335   case Type::UShortTyID:
336     Out << cast<ConstantUInt>(CPV)->getValue(); break;
337   case Type::UIntTyID:
338     Out << cast<ConstantUInt>(CPV)->getValue() << "u"; break;
339   case Type::ULongTyID:
340     Out << cast<ConstantUInt>(CPV)->getValue() << "ull"; break;
341
342   case Type::FloatTyID:
343   case Type::DoubleTyID:
344     Out << cast<ConstantFP>(CPV)->getValue(); break;
345
346   case Type::ArrayTyID:
347     printConstantArray(cast<ConstantArray>(CPV));
348     break;
349
350   case Type::StructTyID: {
351     Out << "{";
352     if (CPV->getNumOperands()) {
353       Out << " ";
354       printConstant(cast<Constant>(CPV->getOperand(0)));
355       for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
356         Out << ", ";
357         printConstant(cast<Constant>(CPV->getOperand(i)));
358       }
359     }
360     Out << " }";
361     break;
362   }
363
364   case Type::PointerTyID:
365     if (isa<ConstantPointerNull>(CPV)) {
366       Out << "((";
367       printType(CPV->getType(), "");
368       Out << ")NULL)";
369       break;
370     } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CPV)) {
371       writeOperand(CPR->getValue());
372       break;
373     }
374     // FALL THROUGH
375   default:
376     std::cerr << "Unknown constant type: " << CPV << "\n";
377     abort();
378   }
379 }
380
381 void CWriter::writeOperandInternal(Value *Operand) {
382   if (Instruction *I = dyn_cast<Instruction>(Operand))
383     if (isInlinableInst(*I)) {
384       // Should we inline this instruction to build a tree?
385       Out << "(";
386       visit(*I);
387       Out << ")";    
388       return;
389     }
390   
391   if (Operand->hasName()) {   
392     Out << getValueName(Operand);
393   } else if (Constant *CPV = dyn_cast<Constant>(Operand)) {
394     printConstant(CPV); 
395   } else {
396     int Slot = Table.getValSlot(Operand);
397     assert(Slot >= 0 && "Malformed LLVM!");
398     Out << "ltmp_" << Slot << "_" << Operand->getType()->getUniqueID();
399   }
400 }
401
402 void CWriter::writeOperand(Value *Operand) {
403   if (isa<GlobalVariable>(Operand))
404     Out << "(&";  // Global variables are references as their addresses by llvm
405
406   writeOperandInternal(Operand);
407
408   if (isa<GlobalVariable>(Operand))
409     Out << ")";
410 }
411
412 void CWriter::printModule(Module *M) {
413   // Calculate which global values have names that will collide when we throw
414   // away type information.
415   {  // Scope to delete the FoundNames set when we are done with it...
416     std::set<string> FoundNames;
417     for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
418       if (I->hasName())                      // If the global has a name...
419         if (FoundNames.count(I->getName()))  // And the name is already used
420           MangledGlobals.insert(I);          // Mangle the name
421         else
422           FoundNames.insert(I->getName());   // Otherwise, keep track of name
423
424     for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
425       if (I->hasName())                      // If the global has a name...
426         if (FoundNames.count(I->getName()))  // And the name is already used
427           MangledGlobals.insert(I);          // Mangle the name
428         else
429           FoundNames.insert(I->getName());   // Otherwise, keep track of name
430   }
431
432
433   // printing stdlib inclusion
434   // Out << "#include <stdlib.h>\n";
435
436   // get declaration for alloca
437   Out << "/* Provide Declarations */\n"
438       << "#include <malloc.h>\n"
439       << "#include <alloca.h>\n\n"
440
441     // Provide a definition for null if one does not already exist.
442       << "#ifndef NULL\n#define NULL 0\n#endif\n\n"
443       << "typedef unsigned char bool;\n"
444
445       << "\n\n/* Global Declarations */\n";
446
447   // First output all the declarations for the program, because C requires
448   // Functions & globals to be declared before they are used.
449   //
450
451   // Loop over the symbol table, emitting all named constants...
452   if (M->hasSymbolTable())
453     printSymbolTable(*M->getSymbolTable());
454
455   // Global variable declarations...
456   if (!M->gempty()) {
457     Out << "\n/* Global Variable Declarations */\n";
458     for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) {
459       Out << (I->hasExternalLinkage() ? "extern " : "static ");
460       printType(I->getType()->getElementType(), getValueName(I));
461       Out << ";\n";
462     }
463   }
464
465   // Function declarations
466   if (!M->empty()) {
467     Out << "\n/* Function Declarations */\n";
468     for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
469       printFunctionSignature(I, true);
470       Out << ";\n";
471     }
472   }
473
474   // Output the global variable contents...
475   if (!M->gempty()) {
476     Out << "\n\n/* Global Data */\n";
477     for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) {
478       if (I->hasInternalLinkage()) Out << "static ";
479       printType(I->getType()->getElementType(), getValueName(I));
480       
481       if (I->hasInitializer()) {
482         Out << " = " ;
483         writeOperand(I->getInitializer());
484       }
485       Out << ";\n";
486     }
487   }
488
489   // Output all of the functions...
490   if (!M->empty()) {
491     Out << "\n\n/* Function Bodies */\n";
492     for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
493       printFunction(I);
494   }
495 }
496
497
498 // printSymbolTable - Run through symbol table looking for named constants
499 // if a named constant is found, emit it's declaration...
500 // Assuming that symbol table has only types and constants.
501 void CWriter::printSymbolTable(const SymbolTable &ST) {
502   for (SymbolTable::const_iterator TI = ST.begin(); TI != ST.end(); ++TI) {
503     SymbolTable::type_const_iterator I = ST.type_begin(TI->first);
504     SymbolTable::type_const_iterator End = ST.type_end(TI->first);
505     
506     for (; I != End; ++I)
507       if (const Type *Ty = dyn_cast<StructType>(I->second)) {
508         string Name = "struct l_" + makeNameProper(I->first);
509         Out << Name << ";\n";
510         TypeNames.insert(std::make_pair(Ty, Name));
511       }
512   }
513
514   Out << "\n";
515
516   for (SymbolTable::const_iterator TI = ST.begin(); TI != ST.end(); ++TI) {
517     SymbolTable::type_const_iterator I = ST.type_begin(TI->first);
518     SymbolTable::type_const_iterator End = ST.type_end(TI->first);
519     
520     for (; I != End; ++I) {
521       const Value *V = I->second;
522       if (const Type *Ty = dyn_cast<Type>(V)) {
523         string Name = "l_" + makeNameProper(I->first);
524         if (isa<StructType>(Ty))
525           Name = "struct " + makeNameProper(Name);
526         else
527           Out << "typedef ";
528
529         printType(Ty, Name, true);
530         Out << ";\n";
531       }
532     }
533   }
534 }
535
536
537 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
538   if (F->hasInternalLinkage()) Out << "static ";
539   
540   // Loop over the arguments, printing them...
541   const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
542   
543   // Print out the return type and name...
544   printType(F->getReturnType());
545   Out << getValueName(F) << "(";
546     
547   if (!F->isExternal()) {
548     if (!F->aempty()) {
549       string ArgName;
550       if (F->abegin()->hasName() || !Prototype)
551         ArgName = getValueName(F->abegin());
552
553       printType(F->afront().getType(), ArgName);
554
555       for (Function::const_aiterator I = ++F->abegin(), E = F->aend();
556            I != E; ++I) {
557         Out << ", ";
558         if (I->hasName() || !Prototype)
559           ArgName = getValueName(I);
560         else 
561           ArgName = "";
562         printType(I->getType(), ArgName);
563       }
564     }
565   } else {
566     // Loop over the arguments, printing them...
567     for (FunctionType::ParamTypes::const_iterator I = 
568            FT->getParamTypes().begin(),
569            E = FT->getParamTypes().end(); I != E; ++I) {
570       if (I != FT->getParamTypes().begin()) Out << ", ";
571       printType(*I);
572     }
573   }
574
575   // Finish printing arguments...
576   if (FT->isVarArg()) {
577     if (FT->getParamTypes().size()) Out << ", ";
578     Out << "...";  // Output varargs portion of signature!
579   }
580   Out << ")";
581 }
582
583
584 void CWriter::printFunction(Function *F) {
585   if (F->isExternal()) return;
586
587   Table.incorporateFunction(F);
588
589   printFunctionSignature(F, false);
590   Out << " {\n";
591
592   // print local variable information for the function
593   for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
594     if ((*I)->getType() != Type::VoidTy && !isInlinableInst(**I)) {
595       Out << "  ";
596       printType((*I)->getType(), getValueName(*I));
597       Out << ";\n";
598     }
599  
600   // print the basic blocks
601   for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
602     BasicBlock *Prev = BB->getPrev();
603
604     // Don't print the label for the basic block if there are no uses, or if the
605     // only terminator use is the precessor basic block's terminator.  We have
606     // to scan the use list because PHI nodes use basic blocks too but do not
607     // require a label to be generated.
608     //
609     bool NeedsLabel = false;
610     for (Value::use_iterator UI = BB->use_begin(), UE = BB->use_end();
611          UI != UE; ++UI)
612       if (TerminatorInst *TI = dyn_cast<TerminatorInst>(*UI))
613         if (TI != Prev->getTerminator()) {
614           NeedsLabel = true;
615           break;        
616         }
617
618     if (NeedsLabel) Out << getValueName(BB) << ":\n";
619
620     // Output all of the instructions in the basic block...
621     for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E; ++II){
622       if (!isInlinableInst(*II) && !isa<PHINode>(*II)) {
623         if (II->getType() != Type::VoidTy)
624           outputLValue(II);
625         else
626           Out << "  ";
627         visit(*II);
628         Out << ";\n";
629       }
630     }
631
632     // Don't emit prefix or suffix for the terminator...
633     visit(*BB->getTerminator());
634   }
635   
636   Out << "}\n\n";
637   Table.purgeFunction();
638 }
639
640 // Specific Instruction type classes... note that all of the casts are
641 // neccesary because we use the instruction classes as opaque types...
642 //
643 void CWriter::visitReturnInst(ReturnInst &I) {
644   // Don't output a void return if this is the last basic block in the function
645   if (I.getNumOperands() == 0 && 
646       &*--I.getParent()->getParent()->end() == I.getParent() &&
647       !I.getParent()->size() == 1) {
648     return;
649   }
650
651   Out << "  return";
652   if (I.getNumOperands()) {
653     Out << " ";
654     writeOperand(I.getOperand(0));
655   }
656   Out << ";\n";
657 }
658
659 static bool isGotoCodeNeccessary(BasicBlock *From, BasicBlock *To) {
660   // If PHI nodes need copies, we need the copy code...
661   if (isa<PHINode>(To->front()) ||
662       From->getNext() != To)      // Not directly successor, need goto
663     return true;
664
665   // Otherwise we don't need the code.
666   return false;
667 }
668
669 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
670                                            unsigned Indent) {
671   for (BasicBlock::iterator I = Succ->begin();
672        PHINode *PN = dyn_cast<PHINode>(&*I); ++I) {
673     //  now we have to do the printing
674     Out << string(Indent, ' ');
675     outputLValue(PN);
676     writeOperand(PN->getIncomingValue(PN->getBasicBlockIndex(CurBB)));
677     Out << ";   /* for PHI node */\n";
678   }
679
680   if (CurBB->getNext() != Succ) {
681     Out << string(Indent, ' ') << "  goto ";
682     writeOperand(Succ);
683     Out << ";\n";
684   }
685 }
686
687 // Brach instruction printing - Avoid printing out a brach to a basic block that
688 // immediately succeeds the current one.
689 //
690 void CWriter::visitBranchInst(BranchInst &I) {
691   if (I.isConditional()) {
692     if (isGotoCodeNeccessary(I.getParent(), I.getSuccessor(0))) {
693       Out << "  if (";
694       writeOperand(I.getCondition());
695       Out << ") {\n";
696       
697       printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
698       
699       if (isGotoCodeNeccessary(I.getParent(), I.getSuccessor(1))) {
700         Out << "  } else {\n";
701         printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
702       }
703     } else {
704       // First goto not neccesary, assume second one is...
705       Out << "  if (!";
706       writeOperand(I.getCondition());
707       Out << ") {\n";
708
709       printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
710     }
711
712     Out << "  }\n";
713   } else {
714     printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
715   }
716   Out << "\n";
717 }
718
719
720 void CWriter::visitBinaryOperator(Instruction &I) {
721   // binary instructions, shift instructions, setCond instructions.
722   if (isa<PointerType>(I.getType())) {
723     Out << "(";
724     printType(I.getType());
725     Out << ")";
726   }
727       
728   if (isa<PointerType>(I.getType())) Out << "(long long)";
729   writeOperand(I.getOperand(0));
730
731   switch (I.getOpcode()) {
732   case Instruction::Add: Out << " + "; break;
733   case Instruction::Sub: Out << " - "; break;
734   case Instruction::Mul: Out << "*"; break;
735   case Instruction::Div: Out << "/"; break;
736   case Instruction::Rem: Out << "%"; break;
737   case Instruction::And: Out << " & "; break;
738   case Instruction::Or: Out << " | "; break;
739   case Instruction::Xor: Out << " ^ "; break;
740   case Instruction::SetEQ: Out << " == "; break;
741   case Instruction::SetNE: Out << " != "; break;
742   case Instruction::SetLE: Out << " <= "; break;
743   case Instruction::SetGE: Out << " >= "; break;
744   case Instruction::SetLT: Out << " < "; break;
745   case Instruction::SetGT: Out << " > "; break;
746   case Instruction::Shl : Out << " << "; break;
747   case Instruction::Shr : Out << " >> "; break;
748   default: std::cerr << "Invalid operator type!" << I; abort();
749   }
750
751   if (isa<PointerType>(I.getType())) Out << "(long long)";
752   writeOperand(I.getOperand(1));
753 }
754
755 void CWriter::visitCastInst(CastInst &I) {
756   Out << "(";
757   printType(I.getType());
758   Out << ")";
759   writeOperand(I.getOperand(0));
760 }
761
762 void CWriter::visitCallInst(CallInst &I) {
763   const PointerType  *PTy   = cast<PointerType>(I.getCalledValue()->getType());
764   const FunctionType *FTy   = cast<FunctionType>(PTy->getElementType());
765   const Type         *RetTy = FTy->getReturnType();
766   
767   Out << getValueName(I.getOperand(0)) << "(";
768
769   if (I.getNumOperands() > 1) {
770     writeOperand(I.getOperand(1));
771
772     for (unsigned op = 2, Eop = I.getNumOperands(); op != Eop; ++op) {
773       Out << ", ";
774       writeOperand(I.getOperand(op));
775     }
776   }
777   Out << ")";
778 }  
779
780 void CWriter::visitMallocInst(MallocInst &I) {
781   Out << "(";
782   printType(I.getType());
783   Out << ")malloc(sizeof(";
784   printType(I.getType()->getElementType());
785   Out << ")";
786
787   if (I.isArrayAllocation()) {
788     Out << " * " ;
789     writeOperand(I.getOperand(0));
790   }
791   Out << ")";
792 }
793
794 void CWriter::visitAllocaInst(AllocaInst &I) {
795   Out << "(";
796   printType(I.getType());
797   Out << ") alloca(sizeof(";
798   printType(I.getType()->getElementType());
799   Out << ")";
800   if (I.isArrayAllocation()) {
801     Out << " * " ;
802     writeOperand(I.getOperand(0));
803   }
804   Out << ")";
805 }
806
807 void CWriter::visitFreeInst(FreeInst &I) {
808   Out << "free(";
809   writeOperand(I.getOperand(0));
810   Out << ")";
811 }
812
813 void CWriter::printIndexingExpression(Value *Ptr, User::op_iterator I,
814                                       User::op_iterator E) {
815   bool HasImplicitAddress = false;
816   // If accessing a global value with no indexing, avoid *(&GV) syndrome
817   if (GlobalValue *V = dyn_cast<GlobalValue>(Ptr)) {
818     HasImplicitAddress = true;
819   } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Ptr)) {
820     HasImplicitAddress = true;
821     Ptr = CPR->getValue();         // Get to the global...
822   }
823
824   if (I == E) {
825     if (!HasImplicitAddress)
826       Out << "*";  // Implicit zero first argument: '*x' is equivalent to 'x[0]'
827
828     writeOperandInternal(Ptr);
829     return;
830   }
831
832   const Constant *CI = dyn_cast<Constant>(I->get());
833   if (HasImplicitAddress && (!CI || !CI->isNullValue()))
834     Out << "(&";
835
836   writeOperandInternal(Ptr);
837
838   if (HasImplicitAddress && (!CI || !CI->isNullValue()))
839     Out << ")";
840
841   // Print out the -> operator if possible...
842   if (CI && CI->isNullValue() && I+1 != E) {
843     if ((*(I+1))->getType() == Type::UByteTy) {
844       Out << (HasImplicitAddress ? "." : "->");
845       Out << "field" << cast<ConstantUInt>(*(I+1))->getValue();
846       I += 2;
847     } else {  // Performing array indexing. Just skip the 0
848       ++I;
849     }
850   } else if (HasImplicitAddress) {
851     
852   }
853     
854   for (; I != E; ++I)
855     if ((*I)->getType() == Type::UIntTy) {
856       Out << "[";
857       writeOperand(*I);
858       Out << "]";
859     } else {
860       Out << ".field" << cast<ConstantUInt>(*I)->getValue();
861     }
862 }
863
864 void CWriter::visitLoadInst(LoadInst &I) {
865   printIndexingExpression(I.getPointerOperand(), I.idx_begin(), I.idx_end());
866 }
867
868 void CWriter::visitStoreInst(StoreInst &I) {
869   printIndexingExpression(I.getPointerOperand(), I.idx_begin(), I.idx_end());
870   Out << " = ";
871   writeOperand(I.getOperand(0));
872 }
873
874 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
875   Out << "&";
876   printIndexingExpression(I.getPointerOperand(), I.idx_begin(), I.idx_end());
877 }
878
879 //===----------------------------------------------------------------------===//
880 //                       External Interface declaration
881 //===----------------------------------------------------------------------===//
882
883 void WriteToC(const Module *M, ostream &Out) {
884   assert(M && "You can't write a null module!!");
885   SlotCalculator SlotTable(M, false);
886   CWriter W(Out, SlotTable, M);
887   W.write((Module*)M);
888   Out.flush();
889 }