Use the autoconf macro John wrote
[oota-llvm.git] / lib / Target / CBackend / CBackend.cpp
1 //===-- Writer.cpp - Library for converting LLVM code to C ----------------===//
2 //
3 // This library converts LLVM code to C code, compilable by GCC.
4 //
5 //===----------------------------------------------------------------------===//
6
7 #include "llvm/Assembly/CWriter.h"
8 #include "llvm/Constants.h"
9 #include "llvm/DerivedTypes.h"
10 #include "llvm/Module.h"
11 #include "llvm/Instructions.h"
12 #include "llvm/Pass.h"
13 #include "llvm/SymbolTable.h"
14 #include "llvm/Intrinsics.h"
15 #include "llvm/Analysis/FindUsedTypes.h"
16 #include "llvm/Analysis/ConstantsScanner.h"
17 #include "llvm/Support/InstVisitor.h"
18 #include "llvm/Support/InstIterator.h"
19 #include "llvm/Support/CallSite.h"
20 #include "llvm/Support/Mangler.h"
21 #include "Support/StringExtras.h"
22 #include "Support/STLExtras.h"
23 #include "Config/config.h"
24 #include <algorithm>
25 #include <sstream>
26
27 namespace {
28   class CWriter : public Pass, public InstVisitor<CWriter> {
29     std::ostream &Out; 
30     Mangler *Mang;
31     const Module *TheModule;
32     std::map<const Type *, std::string> TypeNames;
33     std::set<const Value*> MangledGlobals;
34     bool needsMalloc, emittedInvoke;
35
36     std::map<const ConstantFP *, unsigned> FPConstantMap;
37   public:
38     CWriter(std::ostream &o) : Out(o) {}
39
40     void getAnalysisUsage(AnalysisUsage &AU) const {
41       AU.setPreservesAll();
42       AU.addRequired<FindUsedTypes>();
43     }
44
45     virtual bool run(Module &M) {
46       // Initialize
47       TheModule = &M;
48
49       // Ensure that all structure types have names...
50       bool Changed = nameAllUsedStructureTypes(M);
51       Mang = new Mangler(M);
52
53       // Run...
54       printModule(&M);
55
56       // Free memory...
57       delete Mang;
58       TypeNames.clear();
59       MangledGlobals.clear();
60       return false;
61     }
62
63     std::ostream &printType(std::ostream &Out, const Type *Ty,
64                             const std::string &VariableName = "",
65                             bool IgnoreName = false, bool namedContext = true);
66
67     void writeOperand(Value *Operand);
68     void writeOperandInternal(Value *Operand);
69
70   private :
71     bool nameAllUsedStructureTypes(Module &M);
72     void printModule(Module *M);
73     void printFloatingPointConstants(Module &M);
74     void printSymbolTable(const SymbolTable &ST);
75     void printContainedStructs(const Type *Ty, std::set<const StructType *> &);
76     void printFunctionSignature(const Function *F, bool Prototype);
77
78     void printFunction(Function *);
79
80     void printConstant(Constant *CPV);
81     void printConstantArray(ConstantArray *CPA);
82
83     // isInlinableInst - Attempt to inline instructions into their uses to build
84     // trees as much as possible.  To do this, we have to consistently decide
85     // what is acceptable to inline, so that variable declarations don't get
86     // printed and an extra copy of the expr is not emitted.
87     //
88     static bool isInlinableInst(const Instruction &I) {
89       // Must be an expression, must be used exactly once.  If it is dead, we
90       // emit it inline where it would go.
91       if (I.getType() == Type::VoidTy || I.use_size() != 1 ||
92           isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) || 
93           isa<LoadInst>(I) || isa<VarArgInst>(I))
94         // Don't inline a load across a store or other bad things!
95         return false;
96
97       // Only inline instruction it it's use is in the same BB as the inst.
98       return I.getParent() == cast<Instruction>(I.use_back())->getParent();
99     }
100
101     // isDirectAlloca - Define fixed sized allocas in the entry block as direct
102     // variables which are accessed with the & operator.  This causes GCC to
103     // generate significantly better code than to emit alloca calls directly.
104     //
105     static const AllocaInst *isDirectAlloca(const Value *V) {
106       const AllocaInst *AI = dyn_cast<AllocaInst>(V);
107       if (!AI) return false;
108       if (AI->isArrayAllocation())
109         return 0;   // FIXME: we can also inline fixed size array allocas!
110       if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
111         return 0;
112       return AI;
113     }
114
115     // Instruction visitation functions
116     friend class InstVisitor<CWriter>;
117
118     void visitReturnInst(ReturnInst &I);
119     void visitBranchInst(BranchInst &I);
120     void visitSwitchInst(SwitchInst &I);
121     void visitInvokeInst(InvokeInst &I);
122     void visitUnwindInst(UnwindInst &I);
123
124     void visitPHINode(PHINode &I);
125     void visitBinaryOperator(Instruction &I);
126
127     void visitCastInst (CastInst &I);
128     void visitCallInst (CallInst &I);
129     void visitCallSite (CallSite CS);
130     void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
131
132     void visitMallocInst(MallocInst &I);
133     void visitAllocaInst(AllocaInst &I);
134     void visitFreeInst  (FreeInst   &I);
135     void visitLoadInst  (LoadInst   &I);
136     void visitStoreInst (StoreInst  &I);
137     void visitGetElementPtrInst(GetElementPtrInst &I);
138     void visitVarArgInst(VarArgInst &I);
139
140     void visitInstruction(Instruction &I) {
141       std::cerr << "C Writer does not know about " << I;
142       abort();
143     }
144
145     void outputLValue(Instruction *I) {
146       Out << "  " << Mang->getValueName(I) << " = ";
147     }
148     void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
149                             unsigned Indent);
150     void printIndexingExpression(Value *Ptr, User::op_iterator I,
151                                  User::op_iterator E);
152   };
153 }
154
155 // A pointer type should not use parens around *'s alone, e.g., (**)
156 inline bool ptrTypeNameNeedsParens(const std::string &NameSoFar) {
157   return NameSoFar.find_last_not_of('*') != std::string::npos;
158 }
159
160 // Pass the Type* and the variable name and this prints out the variable
161 // declaration.
162 //
163 std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
164                                  const std::string &NameSoFar,
165                                  bool IgnoreName, bool namedContext) {
166   if (Ty->isPrimitiveType())
167     switch (Ty->getPrimitiveID()) {
168     case Type::VoidTyID:   return Out << "void "               << NameSoFar;
169     case Type::BoolTyID:   return Out << "bool "               << NameSoFar;
170     case Type::UByteTyID:  return Out << "unsigned char "      << NameSoFar;
171     case Type::SByteTyID:  return Out << "signed char "        << NameSoFar;
172     case Type::UShortTyID: return Out << "unsigned short "     << NameSoFar;
173     case Type::ShortTyID:  return Out << "short "              << NameSoFar;
174     case Type::UIntTyID:   return Out << "unsigned "           << NameSoFar;
175     case Type::IntTyID:    return Out << "int "                << NameSoFar;
176     case Type::ULongTyID:  return Out << "unsigned long long " << NameSoFar;
177     case Type::LongTyID:   return Out << "signed long long "   << NameSoFar;
178     case Type::FloatTyID:  return Out << "float "              << NameSoFar;
179     case Type::DoubleTyID: return Out << "double "             << NameSoFar;
180     default :
181       std::cerr << "Unknown primitive type: " << Ty << "\n";
182       abort();
183     }
184   
185   // Check to see if the type is named.
186   if (!IgnoreName || isa<OpaqueType>(Ty)) {
187     std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
188     if (I != TypeNames.end()) return Out << I->second << " " << NameSoFar;
189   }
190
191   switch (Ty->getPrimitiveID()) {
192   case Type::FunctionTyID: {
193     const FunctionType *MTy = cast<FunctionType>(Ty);
194     std::stringstream FunctionInnards; 
195     FunctionInnards << " (" << NameSoFar << ") (";
196     for (FunctionType::ParamTypes::const_iterator
197            I = MTy->getParamTypes().begin(),
198            E = MTy->getParamTypes().end(); I != E; ++I) {
199       if (I != MTy->getParamTypes().begin())
200         FunctionInnards << ", ";
201       printType(FunctionInnards, *I, "");
202     }
203     if (MTy->isVarArg()) {
204       if (!MTy->getParamTypes().empty()) 
205         FunctionInnards << ", ...";
206     } else if (MTy->getParamTypes().empty()) {
207       FunctionInnards << "void";
208     }
209     FunctionInnards << ")";
210     std::string tstr = FunctionInnards.str();
211     printType(Out, MTy->getReturnType(), tstr);
212     return Out;
213   }
214   case Type::StructTyID: {
215     const StructType *STy = cast<StructType>(Ty);
216     Out << NameSoFar + " {\n";
217     unsigned Idx = 0;
218     for (StructType::ElementTypes::const_iterator
219            I = STy->getElementTypes().begin(),
220            E = STy->getElementTypes().end(); I != E; ++I) {
221       Out << "  ";
222       printType(Out, *I, "field" + utostr(Idx++));
223       Out << ";\n";
224     }
225     return Out << "}";
226   }  
227
228   case Type::PointerTyID: {
229     const PointerType *PTy = cast<PointerType>(Ty);
230     std::string ptrName = "*" + NameSoFar;
231
232     // Do not need parens around "* NameSoFar" if NameSoFar consists only
233     // of zero or more '*' chars *and* this is not an unnamed pointer type
234     // such as the result type in a cast statement.  Otherwise, enclose in ( ).
235     if (ptrTypeNameNeedsParens(NameSoFar) || !namedContext || 
236         PTy->getElementType()->getPrimitiveID() == Type::ArrayTyID)
237       ptrName = "(" + ptrName + ")";    // 
238
239     return printType(Out, PTy->getElementType(), ptrName);
240   }
241
242   case Type::ArrayTyID: {
243     const ArrayType *ATy = cast<ArrayType>(Ty);
244     unsigned NumElements = ATy->getNumElements();
245     return printType(Out, ATy->getElementType(),
246                      NameSoFar + "[" + utostr(NumElements) + "]");
247   }
248
249   case Type::OpaqueTyID: {
250     static int Count = 0;
251     std::string TyName = "struct opaque_" + itostr(Count++);
252     assert(TypeNames.find(Ty) == TypeNames.end());
253     TypeNames[Ty] = TyName;
254     return Out << TyName << " " << NameSoFar;
255   }
256   default:
257     assert(0 && "Unhandled case in getTypeProps!");
258     abort();
259   }
260
261   return Out;
262 }
263
264 void CWriter::printConstantArray(ConstantArray *CPA) {
265
266   // As a special case, print the array as a string if it is an array of
267   // ubytes or an array of sbytes with positive values.
268   // 
269   const Type *ETy = CPA->getType()->getElementType();
270   bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
271
272   // Make sure the last character is a null char, as automatically added by C
273   if (isString && (CPA->getNumOperands() == 0 ||
274                    !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
275     isString = false;
276   
277   if (isString) {
278     Out << "\"";
279     // Keep track of whether the last number was a hexadecimal escape
280     bool LastWasHex = false;
281
282     // Do not include the last character, which we know is null
283     for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
284       unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getRawValue();
285       
286       // Print it out literally if it is a printable character.  The only thing
287       // to be careful about is when the last letter output was a hex escape
288       // code, in which case we have to be careful not to print out hex digits
289       // explicitly (the C compiler thinks it is a continuation of the previous
290       // character, sheesh...)
291       //
292       if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
293         LastWasHex = false;
294         if (C == '"' || C == '\\')
295           Out << "\\" << C;
296         else
297           Out << C;
298       } else {
299         LastWasHex = false;
300         switch (C) {
301         case '\n': Out << "\\n"; break;
302         case '\t': Out << "\\t"; break;
303         case '\r': Out << "\\r"; break;
304         case '\v': Out << "\\v"; break;
305         case '\a': Out << "\\a"; break;
306         case '\"': Out << "\\\""; break;
307         case '\'': Out << "\\\'"; break;           
308         default:
309           Out << "\\x";
310           Out << (char)(( C/16  < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
311           Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
312           LastWasHex = true;
313           break;
314         }
315       }
316     }
317     Out << "\"";
318   } else {
319     Out << "{";
320     if (CPA->getNumOperands()) {
321       Out << " ";
322       printConstant(cast<Constant>(CPA->getOperand(0)));
323       for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
324         Out << ", ";
325         printConstant(cast<Constant>(CPA->getOperand(i)));
326       }
327     }
328     Out << " }";
329   }
330 }
331
332 // isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
333 // textually as a double (rather than as a reference to a stack-allocated
334 // variable). We decide this by converting CFP to a string and back into a
335 // double, and then checking whether the conversion results in a bit-equal
336 // double to the original value of CFP. This depends on us and the target C
337 // compiler agreeing on the conversion process (which is pretty likely since we
338 // only deal in IEEE FP).
339 //
340 static bool isFPCSafeToPrint(const ConstantFP *CFP) {
341 #if HAVE_PRINTF_A
342   char Buffer[100];
343   sprintf(Buffer, "%a", CFP->getValue());
344
345   if (!strncmp(Buffer, "0x", 2) ||
346       !strncmp(Buffer, "-0x", 3) ||
347       !strncmp(Buffer, "+0x", 3))
348     return atof(Buffer) == CFP->getValue();
349   return false;
350 #else
351   std::string StrVal = ftostr(CFP->getValue());
352
353   while (StrVal[0] == ' ')
354     StrVal.erase(StrVal.begin());
355
356   // Check to make sure that the stringized number is not some string like "Inf"
357   // or NaN.  Check that the string matches the "[-+]?[0-9]" regex.
358   if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
359       ((StrVal[0] == '-' || StrVal[0] == '+') &&
360        (StrVal[1] >= '0' && StrVal[1] <= '9')))
361     // Reparse stringized version!
362     return atof(StrVal.c_str()) == CFP->getValue();
363   return false;
364 #endif
365 }
366
367 // printConstant - The LLVM Constant to C Constant converter.
368 void CWriter::printConstant(Constant *CPV) {
369   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
370     switch (CE->getOpcode()) {
371     case Instruction::Cast:
372       Out << "((";
373       printType(Out, CPV->getType());
374       Out << ")";
375       printConstant(CE->getOperand(0));
376       Out << ")";
377       return;
378
379     case Instruction::GetElementPtr:
380       Out << "(&(";
381       printIndexingExpression(CE->getOperand(0),
382                               CPV->op_begin()+1, CPV->op_end());
383       Out << "))";
384       return;
385     case Instruction::Add:
386     case Instruction::Sub:
387     case Instruction::Mul:
388     case Instruction::Div:
389     case Instruction::Rem:
390     case Instruction::SetEQ:
391     case Instruction::SetNE:
392     case Instruction::SetLT:
393     case Instruction::SetLE:
394     case Instruction::SetGT:
395     case Instruction::SetGE:
396       Out << "(";
397       printConstant(CE->getOperand(0));
398       switch (CE->getOpcode()) {
399       case Instruction::Add: Out << " + "; break;
400       case Instruction::Sub: Out << " - "; break;
401       case Instruction::Mul: Out << " * "; break;
402       case Instruction::Div: Out << " / "; break;
403       case Instruction::Rem: Out << " % "; break;
404       case Instruction::SetEQ: Out << " == "; break;
405       case Instruction::SetNE: Out << " != "; break;
406       case Instruction::SetLT: Out << " < "; break;
407       case Instruction::SetLE: Out << " <= "; break;
408       case Instruction::SetGT: Out << " > "; break;
409       case Instruction::SetGE: Out << " >= "; break;
410       default: assert(0 && "Illegal opcode here!");
411       }
412       printConstant(CE->getOperand(1));
413       Out << ")";
414       return;
415
416     default:
417       std::cerr << "CWriter Error: Unhandled constant expression: "
418                 << CE << "\n";
419       abort();
420     }
421   }
422
423   switch (CPV->getType()->getPrimitiveID()) {
424   case Type::BoolTyID:
425     Out << (CPV == ConstantBool::False ? "0" : "1"); break;
426   case Type::SByteTyID:
427   case Type::ShortTyID:
428     Out << cast<ConstantSInt>(CPV)->getValue(); break;
429   case Type::IntTyID:
430     if ((int)cast<ConstantSInt>(CPV)->getValue() == (int)0x80000000)
431       Out << "((int)0x80000000)";   // Handle MININT specially to avoid warning
432     else
433       Out << cast<ConstantSInt>(CPV)->getValue();
434     break;
435
436   case Type::LongTyID:
437     Out << cast<ConstantSInt>(CPV)->getValue() << "ll"; break;
438
439   case Type::UByteTyID:
440   case Type::UShortTyID:
441     Out << cast<ConstantUInt>(CPV)->getValue(); break;
442   case Type::UIntTyID:
443     Out << cast<ConstantUInt>(CPV)->getValue() << "u"; break;
444   case Type::ULongTyID:
445     Out << cast<ConstantUInt>(CPV)->getValue() << "ull"; break;
446
447   case Type::FloatTyID:
448   case Type::DoubleTyID: {
449     ConstantFP *FPC = cast<ConstantFP>(CPV);
450     std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
451     if (I != FPConstantMap.end()) {
452       // Because of FP precision problems we must load from a stack allocated
453       // value that holds the value in hex.
454       Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
455           << "*)&FPConstant" << I->second << ")";
456     } else {
457 #if HAVE_PRINTF_A
458       // Print out the constant as a floating point number.
459       char Buffer[100];
460       sprintf(Buffer, "%a", FPC->getValue());
461       Out << Buffer << " /*" << FPC->getValue() << "*/ ";
462 #else
463       Out << ftostr(FPC->getValue());
464 #endif
465     }
466     break;
467   }
468
469   case Type::ArrayTyID:
470     printConstantArray(cast<ConstantArray>(CPV));
471     break;
472
473   case Type::StructTyID: {
474     Out << "{";
475     if (CPV->getNumOperands()) {
476       Out << " ";
477       printConstant(cast<Constant>(CPV->getOperand(0)));
478       for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
479         Out << ", ";
480         printConstant(cast<Constant>(CPV->getOperand(i)));
481       }
482     }
483     Out << " }";
484     break;
485   }
486
487   case Type::PointerTyID:
488     if (isa<ConstantPointerNull>(CPV)) {
489       Out << "((";
490       printType(Out, CPV->getType());
491       Out << ")/*NULL*/0)";
492       break;
493     } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CPV)) {
494       writeOperand(CPR->getValue());
495       break;
496     }
497     // FALL THROUGH
498   default:
499     std::cerr << "Unknown constant type: " << CPV << "\n";
500     abort();
501   }
502 }
503
504 void CWriter::writeOperandInternal(Value *Operand) {
505   if (Instruction *I = dyn_cast<Instruction>(Operand))
506     if (isInlinableInst(*I) && !isDirectAlloca(I)) {
507       // Should we inline this instruction to build a tree?
508       Out << "(";
509       visit(*I);
510       Out << ")";    
511       return;
512     }
513   
514   if (Constant *CPV = dyn_cast<Constant>(Operand)) {
515     printConstant(CPV); 
516   } else {
517     Out << Mang->getValueName(Operand);
518   }
519 }
520
521 void CWriter::writeOperand(Value *Operand) {
522   if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
523     Out << "(&";  // Global variables are references as their addresses by llvm
524
525   writeOperandInternal(Operand);
526
527   if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
528     Out << ")";
529 }
530
531 // nameAllUsedStructureTypes - If there are structure types in the module that
532 // are used but do not have names assigned to them in the symbol table yet then
533 // we assign them names now.
534 //
535 bool CWriter::nameAllUsedStructureTypes(Module &M) {
536   // Get a set of types that are used by the program...
537   std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
538
539   // Loop over the module symbol table, removing types from UT that are already
540   // named.
541   //
542   SymbolTable &MST = M.getSymbolTable();
543   if (MST.find(Type::TypeTy) != MST.end())
544     for (SymbolTable::type_iterator I = MST.type_begin(Type::TypeTy),
545            E = MST.type_end(Type::TypeTy); I != E; ++I)
546       UT.erase(cast<Type>(I->second));
547
548   // UT now contains types that are not named.  Loop over it, naming structure
549   // types.
550   //
551   bool Changed = false;
552   for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
553        I != E; ++I)
554     if (const StructType *ST = dyn_cast<StructType>(*I)) {
555       ((Value*)ST)->setName("unnamed", &MST);
556       Changed = true;
557     }
558   return Changed;
559 }
560
561 // generateCompilerSpecificCode - This is where we add conditional compilation
562 // directives to cater to specific compilers as need be.
563 //
564 static void generateCompilerSpecificCode(std::ostream& Out) {
565   // Alloca is hard to get, and we don't want to include stdlib.h here...
566   Out << "/* get a declaration for alloca */\n"
567       << "#ifdef sun\n"
568       << "extern void *__builtin_alloca(unsigned long);\n"
569       << "#define alloca(x) __builtin_alloca(x)\n"
570       << "#else\n"
571       << "#ifndef __FreeBSD__\n"
572       << "#include <alloca.h>\n"
573       << "#endif\n"
574       << "#endif\n\n";
575
576   // We output GCC specific attributes to preserve 'linkonce'ness on globals.
577   // If we aren't being compiled with GCC, just drop these attributes.
578   Out << "#ifndef __GNUC__  /* Can only support \"linkonce\" vars with GCC */\n"
579       << "#define __attribute__(X)\n"
580       << "#endif\n";
581 }
582
583 void CWriter::printModule(Module *M) {
584   // Calculate which global values have names that will collide when we throw
585   // away type information.
586   {  // Scope to delete the FoundNames set when we are done with it...
587     std::set<std::string> FoundNames;
588     for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
589       if (I->hasName())                      // If the global has a name...
590         if (FoundNames.count(I->getName()))  // And the name is already used
591           MangledGlobals.insert(I);          // Mangle the name
592         else
593           FoundNames.insert(I->getName());   // Otherwise, keep track of name
594
595     for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
596       if (I->hasName())                      // If the global has a name...
597         if (FoundNames.count(I->getName()))  // And the name is already used
598           MangledGlobals.insert(I);          // Mangle the name
599         else
600           FoundNames.insert(I->getName());   // Otherwise, keep track of name
601   }
602
603   // get declaration for alloca
604   Out << "/* Provide Declarations */\n";
605   Out << "#include <stdarg.h>\n";
606   Out << "#include <setjmp.h>\n";
607   generateCompilerSpecificCode(Out);
608   
609   // Provide a definition for `bool' if not compiling with a C++ compiler.
610   Out << "\n"
611       << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
612     
613       << "\n\n/* Support for floating point constants */\n"
614       << "typedef unsigned long long ConstantDoubleTy;\n"
615       << "typedef unsigned int        ConstantFloatTy;\n"
616     
617       << "\n\n/* Support for the invoke instruction */\n"
618       << "extern struct __llvm_jmpbuf_list_t {\n"
619       << "  jmp_buf buf; struct __llvm_jmpbuf_list_t *next;\n"
620       << "} *__llvm_jmpbuf_list;\n"
621
622       << "\n\n/* Global Declarations */\n";
623
624   // First output all the declarations for the program, because C requires
625   // Functions & globals to be declared before they are used.
626   //
627
628   // Loop over the symbol table, emitting all named constants...
629   printSymbolTable(M->getSymbolTable());
630
631   // Global variable declarations...
632   if (!M->gempty()) {
633     Out << "\n/* External Global Variable Declarations */\n";
634     for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) {
635       if (I->hasExternalLinkage()) {
636         Out << "extern ";
637         printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
638         Out << ";\n";
639       }
640     }
641   }
642
643   // Function declarations
644   if (!M->empty()) {
645     Out << "\n/* Function Declarations */\n";
646     needsMalloc = true;
647     for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
648       // If the function is external and the name collides don't print it.
649       // Sometimes the bytecode likes to have multiple "declarations" for
650       // external functions
651       if ((I->hasInternalLinkage() || !MangledGlobals.count(I)) &&
652           !I->getIntrinsicID()) {
653         printFunctionSignature(I, true);
654         Out << ";\n";
655       }
656     }
657   }
658
659   // Print Malloc prototype if needed
660   if (needsMalloc) {
661     Out << "\n/* Malloc to make sun happy */\n";
662     Out << "extern void * malloc();\n\n";
663   }
664
665   // Output the global variable declarations
666   if (!M->gempty()) {
667     Out << "\n\n/* Global Variable Declarations */\n";
668     for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
669       if (!I->isExternal()) {
670         Out << "extern ";
671         printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
672       
673         Out << ";\n";
674       }
675   }
676
677   // Output the global variable definitions and contents...
678   if (!M->gempty()) {
679     Out << "\n\n/* Global Variable Definitions and Initialization */\n";
680     for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
681       if (!I->isExternal()) {
682         if (I->hasInternalLinkage())
683           Out << "static ";
684         printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
685         if (I->hasLinkOnceLinkage())
686           Out << " __attribute__((common))";
687         if (!I->getInitializer()->isNullValue()) {
688           Out << " = " ;
689           writeOperand(I->getInitializer());
690         }
691         Out << ";\n";
692       }
693   }
694
695   // Output all floating point constants that cannot be printed accurately...
696   printFloatingPointConstants(*M);
697   
698   // Output all of the functions...
699   emittedInvoke = false;
700   if (!M->empty()) {
701     Out << "\n\n/* Function Bodies */\n";
702     for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
703       printFunction(I);
704   }
705
706   // If the program included an invoke instruction, we need to output the
707   // support code for it here!
708   if (emittedInvoke) {
709     Out << "\n/* More support for the invoke instruction */\n"
710         << "struct __llvm_jmpbuf_list_t *__llvm_jmpbuf_list "
711         << "__attribute__((common)) = 0;\n";
712   }
713
714   // Done with global FP constants
715   FPConstantMap.clear();
716 }
717
718 /// Output all floating point constants that cannot be printed accurately...
719 void CWriter::printFloatingPointConstants(Module &M) {
720   union {
721     double D;
722     unsigned long long U;
723   } DBLUnion;
724
725   union {
726     float F;
727     unsigned U;
728   } FLTUnion;
729
730   // Scan the module for floating point constants.  If any FP constant is used
731   // in the function, we want to redirect it here so that we do not depend on
732   // the precision of the printed form, unless the printed form preserves
733   // precision.
734   //
735   unsigned FPCounter = 0;
736   for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
737     for (constant_iterator I = constant_begin(F), E = constant_end(F);
738          I != E; ++I)
739       if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
740         if (!isFPCSafeToPrint(FPC) && // Do not put in FPConstantMap if safe.
741             !FPConstantMap.count(FPC)) {
742           double Val = FPC->getValue();
743           
744           FPConstantMap[FPC] = FPCounter;  // Number the FP constants
745           
746           if (FPC->getType() == Type::DoubleTy) {
747             DBLUnion.D = Val;
748             Out << "const ConstantDoubleTy FPConstant" << FPCounter++
749                 << " = 0x" << std::hex << DBLUnion.U << std::dec
750                 << "ULL;    /* " << Val << " */\n";
751           } else if (FPC->getType() == Type::FloatTy) {
752             FLTUnion.F = Val;
753             Out << "const ConstantFloatTy FPConstant" << FPCounter++
754                 << " = 0x" << std::hex << FLTUnion.U << std::dec
755                 << "U;    /* " << Val << " */\n";
756           } else
757             assert(0 && "Unknown float type!");
758         }
759   
760   Out << "\n";
761  }
762
763
764 /// printSymbolTable - Run through symbol table looking for type names.  If a
765 /// type name is found, emit it's declaration...
766 ///
767 void CWriter::printSymbolTable(const SymbolTable &ST) {
768   // If there are no type names, exit early.
769   if (ST.find(Type::TypeTy) == ST.end())
770     return;
771
772   // We are only interested in the type plane of the symbol table...
773   SymbolTable::type_const_iterator I   = ST.type_begin(Type::TypeTy);
774   SymbolTable::type_const_iterator End = ST.type_end(Type::TypeTy);
775   
776   // Print out forward declarations for structure types before anything else!
777   Out << "/* Structure forward decls */\n";
778   for (; I != End; ++I)
779     if (const Type *STy = dyn_cast<StructType>(I->second)) {
780       std::string Name = "struct l_" + Mangler::makeNameProper(I->first);
781       Out << Name << ";\n";
782       TypeNames.insert(std::make_pair(STy, Name));
783     }
784
785   Out << "\n";
786
787   // Now we can print out typedefs...
788   Out << "/* Typedefs */\n";
789   for (I = ST.type_begin(Type::TypeTy); I != End; ++I) {
790     const Type *Ty = cast<Type>(I->second);
791     std::string Name = "l_" + Mangler::makeNameProper(I->first);
792     Out << "typedef ";
793     printType(Out, Ty, Name);
794     Out << ";\n";
795   }
796
797   Out << "\n";
798
799   // Keep track of which structures have been printed so far...
800   std::set<const StructType *> StructPrinted;
801
802   // Loop over all structures then push them into the stack so they are
803   // printed in the correct order.
804   //
805   Out << "/* Structure contents */\n";
806   for (I = ST.type_begin(Type::TypeTy); I != End; ++I)
807     if (const StructType *STy = dyn_cast<StructType>(I->second))
808       printContainedStructs(STy, StructPrinted);
809 }
810
811 // Push the struct onto the stack and recursively push all structs
812 // this one depends on.
813 void CWriter::printContainedStructs(const Type *Ty,
814                                     std::set<const StructType*> &StructPrinted){
815   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
816     //Check to see if we have already printed this struct
817     if (StructPrinted.count(STy) == 0) {
818       // Print all contained types first...
819       for (StructType::ElementTypes::const_iterator
820              I = STy->getElementTypes().begin(),
821              E = STy->getElementTypes().end(); I != E; ++I) {
822         const Type *Ty1 = I->get();
823         if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
824           printContainedStructs(*I, StructPrinted);
825       }
826       
827       //Print structure type out..
828       StructPrinted.insert(STy);
829       std::string Name = TypeNames[STy];  
830       printType(Out, STy, Name, true);
831       Out << ";\n\n";
832     }
833
834     // If it is an array, check contained types and continue
835   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)){
836     const Type *Ty1 = ATy->getElementType();
837     if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
838       printContainedStructs(Ty1, StructPrinted);
839   }
840 }
841
842
843 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
844   // If the program provides its own malloc prototype we don't need
845   // to include the general one.  
846   if (Mang->getValueName(F) == "malloc")
847     needsMalloc = false;
848
849   if (F->hasInternalLinkage()) Out << "static ";
850   if (F->hasLinkOnceLinkage()) Out << "inline ";
851   
852   // Loop over the arguments, printing them...
853   const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
854   
855   std::stringstream FunctionInnards; 
856     
857   // Print out the name...
858   FunctionInnards << Mang->getValueName(F) << "(";
859     
860   if (!F->isExternal()) {
861     if (!F->aempty()) {
862       std::string ArgName;
863       if (F->abegin()->hasName() || !Prototype)
864         ArgName = Mang->getValueName(F->abegin());
865       printType(FunctionInnards, F->afront().getType(), ArgName);
866       for (Function::const_aiterator I = ++F->abegin(), E = F->aend();
867            I != E; ++I) {
868         FunctionInnards << ", ";
869         if (I->hasName() || !Prototype)
870           ArgName = Mang->getValueName(I);
871         else 
872           ArgName = "";
873         printType(FunctionInnards, I->getType(), ArgName);
874       }
875     }
876   } else {
877     // Loop over the arguments, printing them...
878     for (FunctionType::ParamTypes::const_iterator I = 
879            FT->getParamTypes().begin(),
880            E = FT->getParamTypes().end(); I != E; ++I) {
881       if (I != FT->getParamTypes().begin()) FunctionInnards << ", ";
882       printType(FunctionInnards, *I);
883     }
884   }
885
886   // Finish printing arguments... if this is a vararg function, print the ...,
887   // unless there are no known types, in which case, we just emit ().
888   //
889   if (FT->isVarArg() && !FT->getParamTypes().empty()) {
890     if (FT->getParamTypes().size()) FunctionInnards << ", ";
891     FunctionInnards << "...";  // Output varargs portion of signature!
892   }
893   FunctionInnards << ")";
894   // Print out the return type and the entire signature for that matter
895   printType(Out, F->getReturnType(), FunctionInnards.str());
896 }
897
898 void CWriter::printFunction(Function *F) {
899   if (F->isExternal()) return;
900
901   printFunctionSignature(F, false);
902   Out << " {\n";
903
904   // print local variable information for the function
905   for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
906     if (const AllocaInst *AI = isDirectAlloca(*I)) {
907       Out << "  ";
908       printType(Out, AI->getAllocatedType(), Mang->getValueName(AI));
909       Out << ";    /* Address exposed local */\n";
910     } else if ((*I)->getType() != Type::VoidTy && !isInlinableInst(**I)) {
911       Out << "  ";
912       printType(Out, (*I)->getType(), Mang->getValueName(*I));
913       Out << ";\n";
914       
915       if (isa<PHINode>(*I)) {  // Print out PHI node temporaries as well...
916         Out << "  ";
917         printType(Out, (*I)->getType(),
918                   Mang->getValueName(*I)+"__PHI_TEMPORARY");
919         Out << ";\n";
920       }
921     }
922
923   Out << "\n";
924
925   // print the basic blocks
926   for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
927     BasicBlock *Prev = BB->getPrev();
928
929     // Don't print the label for the basic block if there are no uses, or if the
930     // only terminator use is the predecessor basic block's terminator.  We have
931     // to scan the use list because PHI nodes use basic blocks too but do not
932     // require a label to be generated.
933     //
934     bool NeedsLabel = false;
935     for (Value::use_iterator UI = BB->use_begin(), UE = BB->use_end();
936          UI != UE; ++UI)
937       if (TerminatorInst *TI = dyn_cast<TerminatorInst>(*UI))
938         if (TI != Prev->getTerminator() ||
939             isa<SwitchInst>(Prev->getTerminator()) ||
940             isa<InvokeInst>(Prev->getTerminator())) {
941           NeedsLabel = true;
942           break;        
943         }
944
945     if (NeedsLabel) Out << Mang->getValueName(BB) << ":\n";
946
947     // Output all of the instructions in the basic block...
948     for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E; ++II){
949       if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
950         if (II->getType() != Type::VoidTy)
951           outputLValue(II);
952         else
953           Out << "  ";
954         visit(*II);
955         Out << ";\n";
956       }
957     }
958
959     // Don't emit prefix or suffix for the terminator...
960     visit(*BB->getTerminator());
961   }
962   
963   Out << "}\n\n";
964 }
965
966 // Specific Instruction type classes... note that all of the casts are
967 // necessary because we use the instruction classes as opaque types...
968 //
969 void CWriter::visitReturnInst(ReturnInst &I) {
970   // Don't output a void return if this is the last basic block in the function
971   if (I.getNumOperands() == 0 && 
972       &*--I.getParent()->getParent()->end() == I.getParent() &&
973       !I.getParent()->size() == 1) {
974     return;
975   }
976
977   Out << "  return";
978   if (I.getNumOperands()) {
979     Out << " ";
980     writeOperand(I.getOperand(0));
981   }
982   Out << ";\n";
983 }
984
985 void CWriter::visitSwitchInst(SwitchInst &SI) {
986   Out << "  switch (";
987   writeOperand(SI.getOperand(0));
988   Out << ") {\n  default:\n";
989   printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
990   Out << ";\n";
991   for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
992     Out << "  case ";
993     writeOperand(SI.getOperand(i));
994     Out << ":\n";
995     BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
996     printBranchToBlock(SI.getParent(), Succ, 2);
997     if (Succ == SI.getParent()->getNext())
998       Out << "    break;\n";
999   }
1000   Out << "  }\n";
1001 }
1002
1003 void CWriter::visitInvokeInst(InvokeInst &II) {
1004   Out << "  {\n"
1005       << "    struct __llvm_jmpbuf_list_t Entry;\n"
1006       << "    Entry.next = __llvm_jmpbuf_list;\n"
1007       << "    if (setjmp(Entry.buf)) {\n"
1008       << "      __llvm_jmpbuf_list = Entry.next;\n";
1009   printBranchToBlock(II.getParent(), II.getExceptionalDest(), 4);
1010   Out << "    }\n"
1011       << "    __llvm_jmpbuf_list = &Entry;\n"
1012       << "    ";
1013
1014   if (II.getType() != Type::VoidTy) outputLValue(&II);
1015   visitCallSite(&II);
1016   Out << ";\n"
1017       << "    __llvm_jmpbuf_list = Entry.next;\n"
1018       << "  }\n";
1019   printBranchToBlock(II.getParent(), II.getNormalDest(), 0);
1020   emittedInvoke = true;
1021 }
1022
1023
1024 void CWriter::visitUnwindInst(UnwindInst &I) {
1025   // The unwind instructions causes a control flow transfer out of the current
1026   // function, unwinding the stack until a caller who used the invoke
1027   // instruction is found.  In this context, we code generated the invoke
1028   // instruction to add an entry to the top of the jmpbuf_list.  Thus, here we
1029   // just have to longjmp to the specified handler.
1030   Out << "  if (__llvm_jmpbuf_list == 0) {  /* unwind */\n"
1031       << "    extern write();\n"
1032       << "    ((void (*)(int, void*, unsigned))write)(2,\n"
1033       << "           \"throw found with no handler!\\n\", 31); abort();\n"
1034       << "  }\n"
1035       << "  longjmp(__llvm_jmpbuf_list->buf, 1);\n";
1036   emittedInvoke = true;
1037 }
1038
1039 static bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
1040   // If PHI nodes need copies, we need the copy code...
1041   if (isa<PHINode>(To->front()) ||
1042       From->getNext() != To)      // Not directly successor, need goto
1043     return true;
1044
1045   // Otherwise we don't need the code.
1046   return false;
1047 }
1048
1049 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
1050                                  unsigned Indent) {
1051   for (BasicBlock::iterator I = Succ->begin();
1052        PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1053     //  now we have to do the printing
1054     Out << std::string(Indent, ' ');
1055     Out << "  " << Mang->getValueName(I) << "__PHI_TEMPORARY = ";
1056     writeOperand(PN->getIncomingValue(PN->getBasicBlockIndex(CurBB)));
1057     Out << ";   /* for PHI node */\n";
1058   }
1059
1060   if (CurBB->getNext() != Succ || isa<InvokeInst>(CurBB->getTerminator())) {
1061     Out << std::string(Indent, ' ') << "  goto ";
1062     writeOperand(Succ);
1063     Out << ";\n";
1064   }
1065 }
1066
1067 // Branch instruction printing - Avoid printing out a branch to a basic block
1068 // that immediately succeeds the current one.
1069 //
1070 void CWriter::visitBranchInst(BranchInst &I) {
1071   if (I.isConditional()) {
1072     if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
1073       Out << "  if (";
1074       writeOperand(I.getCondition());
1075       Out << ") {\n";
1076       
1077       printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
1078       
1079       if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
1080         Out << "  } else {\n";
1081         printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
1082       }
1083     } else {
1084       // First goto not necessary, assume second one is...
1085       Out << "  if (!";
1086       writeOperand(I.getCondition());
1087       Out << ") {\n";
1088
1089       printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
1090     }
1091
1092     Out << "  }\n";
1093   } else {
1094     printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
1095   }
1096   Out << "\n";
1097 }
1098
1099 // PHI nodes get copied into temporary values at the end of predecessor basic
1100 // blocks.  We now need to copy these temporary values into the REAL value for
1101 // the PHI.
1102 void CWriter::visitPHINode(PHINode &I) {
1103   writeOperand(&I);
1104   Out << "__PHI_TEMPORARY";
1105 }
1106
1107
1108 void CWriter::visitBinaryOperator(Instruction &I) {
1109   // binary instructions, shift instructions, setCond instructions.
1110   assert(!isa<PointerType>(I.getType()));
1111
1112   // We must cast the results of binary operations which might be promoted.
1113   bool needsCast = false;
1114   if ((I.getType() == Type::UByteTy) || (I.getType() == Type::SByteTy)
1115       || (I.getType() == Type::UShortTy) || (I.getType() == Type::ShortTy)
1116       || (I.getType() == Type::FloatTy)) {
1117     needsCast = true;
1118     Out << "((";
1119     printType(Out, I.getType(), "", false, false);
1120     Out << ")(";
1121   }
1122       
1123   writeOperand(I.getOperand(0));
1124
1125   switch (I.getOpcode()) {
1126   case Instruction::Add: Out << " + "; break;
1127   case Instruction::Sub: Out << " - "; break;
1128   case Instruction::Mul: Out << "*"; break;
1129   case Instruction::Div: Out << "/"; break;
1130   case Instruction::Rem: Out << "%"; break;
1131   case Instruction::And: Out << " & "; break;
1132   case Instruction::Or: Out << " | "; break;
1133   case Instruction::Xor: Out << " ^ "; break;
1134   case Instruction::SetEQ: Out << " == "; break;
1135   case Instruction::SetNE: Out << " != "; break;
1136   case Instruction::SetLE: Out << " <= "; break;
1137   case Instruction::SetGE: Out << " >= "; break;
1138   case Instruction::SetLT: Out << " < "; break;
1139   case Instruction::SetGT: Out << " > "; break;
1140   case Instruction::Shl : Out << " << "; break;
1141   case Instruction::Shr : Out << " >> "; break;
1142   default: std::cerr << "Invalid operator type!" << I; abort();
1143   }
1144
1145   writeOperand(I.getOperand(1));
1146
1147   if (needsCast) {
1148     Out << "))";
1149   }
1150 }
1151
1152 void CWriter::visitCastInst(CastInst &I) {
1153   if (I.getType() == Type::BoolTy) {
1154     Out << "(";
1155     writeOperand(I.getOperand(0));
1156     Out << " != 0)";
1157     return;
1158   }
1159   Out << "(";
1160   printType(Out, I.getType(), "", /*ignoreName*/false, /*namedContext*/false);
1161   Out << ")";
1162   if (isa<PointerType>(I.getType())&&I.getOperand(0)->getType()->isIntegral() ||
1163       isa<PointerType>(I.getOperand(0)->getType())&&I.getType()->isIntegral()) {
1164     // Avoid "cast to pointer from integer of different size" warnings
1165     Out << "(long)";  
1166   }
1167   
1168   writeOperand(I.getOperand(0));
1169 }
1170
1171 void CWriter::visitCallInst(CallInst &I) {
1172   // Handle intrinsic function calls first...
1173   if (Function *F = I.getCalledFunction())
1174     if (LLVMIntrinsic::ID ID = (LLVMIntrinsic::ID)F->getIntrinsicID()) {
1175       switch (ID) {
1176       default:  assert(0 && "Unknown LLVM intrinsic!");
1177       case LLVMIntrinsic::va_start: 
1178         Out << "va_start(*(va_list*)";
1179         writeOperand(I.getOperand(1));
1180         Out << ", ";
1181         // Output the last argument to the enclosing function...
1182         writeOperand(&I.getParent()->getParent()->aback());
1183         Out << ")";
1184         return;
1185       case LLVMIntrinsic::va_end:
1186         Out << "va_end(*(va_list*)";
1187         writeOperand(I.getOperand(1));
1188         Out << ")";
1189         return;
1190       case LLVMIntrinsic::va_copy:
1191         Out << "va_copy(*(va_list*)";
1192         writeOperand(I.getOperand(1));
1193         Out << ", (va_list)";
1194         writeOperand(I.getOperand(2));
1195         Out << ")";
1196         return;
1197
1198       case LLVMIntrinsic::setjmp:
1199       case LLVMIntrinsic::sigsetjmp:
1200         // This intrinsic should never exist in the program, but until we get
1201         // setjmp/longjmp transformations going on, we should codegen it to
1202         // something reasonable.  This will allow code that never calls longjmp
1203         // to work.
1204         Out << "0";
1205         return;
1206       case LLVMIntrinsic::longjmp:
1207       case LLVMIntrinsic::siglongjmp:
1208         // Longjmp is not implemented, and never will be.  It would cause an
1209         // exception throw.
1210         Out << "abort()";
1211         return;
1212       }
1213     }
1214   visitCallSite(&I);
1215 }
1216
1217 void CWriter::visitCallSite(CallSite CS) {
1218   const PointerType  *PTy   = cast<PointerType>(CS.getCalledValue()->getType());
1219   const FunctionType *FTy   = cast<FunctionType>(PTy->getElementType());
1220   const Type         *RetTy = FTy->getReturnType();
1221   
1222   writeOperand(CS.getCalledValue());
1223   Out << "(";
1224
1225   if (CS.arg_begin() != CS.arg_end()) {
1226     CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
1227     writeOperand(*AI);
1228
1229     for (++AI; AI != AE; ++AI) {
1230       Out << ", ";
1231       writeOperand(*AI);
1232     }
1233   }
1234   Out << ")";
1235 }  
1236
1237 void CWriter::visitMallocInst(MallocInst &I) {
1238   Out << "(";
1239   printType(Out, I.getType());
1240   Out << ")malloc(sizeof(";
1241   printType(Out, I.getType()->getElementType());
1242   Out << ")";
1243
1244   if (I.isArrayAllocation()) {
1245     Out << " * " ;
1246     writeOperand(I.getOperand(0));
1247   }
1248   Out << ")";
1249 }
1250
1251 void CWriter::visitAllocaInst(AllocaInst &I) {
1252   Out << "(";
1253   printType(Out, I.getType());
1254   Out << ") alloca(sizeof(";
1255   printType(Out, I.getType()->getElementType());
1256   Out << ")";
1257   if (I.isArrayAllocation()) {
1258     Out << " * " ;
1259     writeOperand(I.getOperand(0));
1260   }
1261   Out << ")";
1262 }
1263
1264 void CWriter::visitFreeInst(FreeInst &I) {
1265   Out << "free((char*)";
1266   writeOperand(I.getOperand(0));
1267   Out << ")";
1268 }
1269
1270 void CWriter::printIndexingExpression(Value *Ptr, User::op_iterator I,
1271                                       User::op_iterator E) {
1272   bool HasImplicitAddress = false;
1273   // If accessing a global value with no indexing, avoid *(&GV) syndrome
1274   if (GlobalValue *V = dyn_cast<GlobalValue>(Ptr)) {
1275     HasImplicitAddress = true;
1276   } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Ptr)) {
1277     HasImplicitAddress = true;
1278     Ptr = CPR->getValue();         // Get to the global...
1279   } else if (isDirectAlloca(Ptr)) {
1280     HasImplicitAddress = true;
1281   }
1282
1283   if (I == E) {
1284     if (!HasImplicitAddress)
1285       Out << "*";  // Implicit zero first argument: '*x' is equivalent to 'x[0]'
1286
1287     writeOperandInternal(Ptr);
1288     return;
1289   }
1290
1291   const Constant *CI = dyn_cast<Constant>(I);
1292   if (HasImplicitAddress && (!CI || !CI->isNullValue()))
1293     Out << "(&";
1294
1295   writeOperandInternal(Ptr);
1296
1297   if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
1298     Out << ")";
1299     HasImplicitAddress = false;  // HIA is only true if we haven't addressed yet
1300   }
1301
1302   assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
1303          "Can only have implicit address with direct accessing");
1304
1305   if (HasImplicitAddress) {
1306     ++I;
1307   } else if (CI && CI->isNullValue() && I+1 != E) {
1308     // Print out the -> operator if possible...
1309     if ((*(I+1))->getType() == Type::UByteTy) {
1310       Out << (HasImplicitAddress ? "." : "->");
1311       Out << "field" << cast<ConstantUInt>(*(I+1))->getValue();
1312       I += 2;
1313     } 
1314   }
1315
1316   for (; I != E; ++I)
1317     if ((*I)->getType() == Type::LongTy) {
1318       Out << "[";
1319       writeOperand(*I);
1320       Out << "]";
1321     } else {
1322       Out << ".field" << cast<ConstantUInt>(*I)->getValue();
1323     }
1324 }
1325
1326 void CWriter::visitLoadInst(LoadInst &I) {
1327   Out << "*";
1328   writeOperand(I.getOperand(0));
1329 }
1330
1331 void CWriter::visitStoreInst(StoreInst &I) {
1332   Out << "*";
1333   writeOperand(I.getPointerOperand());
1334   Out << " = ";
1335   writeOperand(I.getOperand(0));
1336 }
1337
1338 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
1339   Out << "&";
1340   printIndexingExpression(I.getPointerOperand(), I.idx_begin(), I.idx_end());
1341 }
1342
1343 void CWriter::visitVarArgInst(VarArgInst &I) {
1344   Out << "va_arg((va_list)*";
1345   writeOperand(I.getOperand(0));
1346   Out << ", ";
1347   printType(Out, I.getType(), "", /*ignoreName*/false, /*namedContext*/false);
1348   Out << ")";  
1349 }
1350
1351
1352 //===----------------------------------------------------------------------===//
1353 //                       External Interface declaration
1354 //===----------------------------------------------------------------------===//
1355
1356 Pass *createWriteToCPass(std::ostream &o) { return new CWriter(o); }