Add support for 'weak' linkage.
[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.hasOneUse() ||
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         else if (I->hasWeakLinkage())
688           Out << " __attribute__((weak))";
689         if (!I->getInitializer()->isNullValue()) {
690           Out << " = " ;
691           writeOperand(I->getInitializer());
692         }
693         Out << ";\n";
694       }
695   }
696
697   // Output all floating point constants that cannot be printed accurately...
698   printFloatingPointConstants(*M);
699   
700   // Output all of the functions...
701   emittedInvoke = false;
702   if (!M->empty()) {
703     Out << "\n\n/* Function Bodies */\n";
704     for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
705       printFunction(I);
706   }
707
708   // If the program included an invoke instruction, we need to output the
709   // support code for it here!
710   if (emittedInvoke) {
711     Out << "\n/* More support for the invoke instruction */\n"
712         << "struct __llvm_jmpbuf_list_t *__llvm_jmpbuf_list "
713         << "__attribute__((common)) = 0;\n";
714   }
715
716   // Done with global FP constants
717   FPConstantMap.clear();
718 }
719
720 /// Output all floating point constants that cannot be printed accurately...
721 void CWriter::printFloatingPointConstants(Module &M) {
722   union {
723     double D;
724     unsigned long long U;
725   } DBLUnion;
726
727   union {
728     float F;
729     unsigned U;
730   } FLTUnion;
731
732   // Scan the module for floating point constants.  If any FP constant is used
733   // in the function, we want to redirect it here so that we do not depend on
734   // the precision of the printed form, unless the printed form preserves
735   // precision.
736   //
737   unsigned FPCounter = 0;
738   for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
739     for (constant_iterator I = constant_begin(F), E = constant_end(F);
740          I != E; ++I)
741       if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
742         if (!isFPCSafeToPrint(FPC) && // Do not put in FPConstantMap if safe.
743             !FPConstantMap.count(FPC)) {
744           double Val = FPC->getValue();
745           
746           FPConstantMap[FPC] = FPCounter;  // Number the FP constants
747           
748           if (FPC->getType() == Type::DoubleTy) {
749             DBLUnion.D = Val;
750             Out << "const ConstantDoubleTy FPConstant" << FPCounter++
751                 << " = 0x" << std::hex << DBLUnion.U << std::dec
752                 << "ULL;    /* " << Val << " */\n";
753           } else if (FPC->getType() == Type::FloatTy) {
754             FLTUnion.F = Val;
755             Out << "const ConstantFloatTy FPConstant" << FPCounter++
756                 << " = 0x" << std::hex << FLTUnion.U << std::dec
757                 << "U;    /* " << Val << " */\n";
758           } else
759             assert(0 && "Unknown float type!");
760         }
761   
762   Out << "\n";
763  }
764
765
766 /// printSymbolTable - Run through symbol table looking for type names.  If a
767 /// type name is found, emit it's declaration...
768 ///
769 void CWriter::printSymbolTable(const SymbolTable &ST) {
770   // If there are no type names, exit early.
771   if (ST.find(Type::TypeTy) == ST.end())
772     return;
773
774   // We are only interested in the type plane of the symbol table...
775   SymbolTable::type_const_iterator I   = ST.type_begin(Type::TypeTy);
776   SymbolTable::type_const_iterator End = ST.type_end(Type::TypeTy);
777   
778   // Print out forward declarations for structure types before anything else!
779   Out << "/* Structure forward decls */\n";
780   for (; I != End; ++I)
781     if (const Type *STy = dyn_cast<StructType>(I->second)) {
782       std::string Name = "struct l_" + Mangler::makeNameProper(I->first);
783       Out << Name << ";\n";
784       TypeNames.insert(std::make_pair(STy, Name));
785     }
786
787   Out << "\n";
788
789   // Now we can print out typedefs...
790   Out << "/* Typedefs */\n";
791   for (I = ST.type_begin(Type::TypeTy); I != End; ++I) {
792     const Type *Ty = cast<Type>(I->second);
793     std::string Name = "l_" + Mangler::makeNameProper(I->first);
794     Out << "typedef ";
795     printType(Out, Ty, Name);
796     Out << ";\n";
797   }
798
799   Out << "\n";
800
801   // Keep track of which structures have been printed so far...
802   std::set<const StructType *> StructPrinted;
803
804   // Loop over all structures then push them into the stack so they are
805   // printed in the correct order.
806   //
807   Out << "/* Structure contents */\n";
808   for (I = ST.type_begin(Type::TypeTy); I != End; ++I)
809     if (const StructType *STy = dyn_cast<StructType>(I->second))
810       printContainedStructs(STy, StructPrinted);
811 }
812
813 // Push the struct onto the stack and recursively push all structs
814 // this one depends on.
815 void CWriter::printContainedStructs(const Type *Ty,
816                                     std::set<const StructType*> &StructPrinted){
817   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
818     //Check to see if we have already printed this struct
819     if (StructPrinted.count(STy) == 0) {
820       // Print all contained types first...
821       for (StructType::ElementTypes::const_iterator
822              I = STy->getElementTypes().begin(),
823              E = STy->getElementTypes().end(); I != E; ++I) {
824         const Type *Ty1 = I->get();
825         if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
826           printContainedStructs(*I, StructPrinted);
827       }
828       
829       //Print structure type out..
830       StructPrinted.insert(STy);
831       std::string Name = TypeNames[STy];  
832       printType(Out, STy, Name, true);
833       Out << ";\n\n";
834     }
835
836     // If it is an array, check contained types and continue
837   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)){
838     const Type *Ty1 = ATy->getElementType();
839     if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
840       printContainedStructs(Ty1, StructPrinted);
841   }
842 }
843
844
845 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
846   // If the program provides its own malloc prototype we don't need
847   // to include the general one.  
848   if (Mang->getValueName(F) == "malloc")
849     needsMalloc = false;
850
851   if (F->hasInternalLinkage()) Out << "static ";
852   if (F->hasLinkOnceLinkage()) Out << "inline ";
853   
854   // Loop over the arguments, printing them...
855   const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
856   
857   std::stringstream FunctionInnards; 
858     
859   // Print out the name...
860   FunctionInnards << Mang->getValueName(F) << "(";
861     
862   if (!F->isExternal()) {
863     if (!F->aempty()) {
864       std::string ArgName;
865       if (F->abegin()->hasName() || !Prototype)
866         ArgName = Mang->getValueName(F->abegin());
867       printType(FunctionInnards, F->afront().getType(), ArgName);
868       for (Function::const_aiterator I = ++F->abegin(), E = F->aend();
869            I != E; ++I) {
870         FunctionInnards << ", ";
871         if (I->hasName() || !Prototype)
872           ArgName = Mang->getValueName(I);
873         else 
874           ArgName = "";
875         printType(FunctionInnards, I->getType(), ArgName);
876       }
877     }
878   } else {
879     // Loop over the arguments, printing them...
880     for (FunctionType::ParamTypes::const_iterator I = 
881            FT->getParamTypes().begin(),
882            E = FT->getParamTypes().end(); I != E; ++I) {
883       if (I != FT->getParamTypes().begin()) FunctionInnards << ", ";
884       printType(FunctionInnards, *I);
885     }
886   }
887
888   // Finish printing arguments... if this is a vararg function, print the ...,
889   // unless there are no known types, in which case, we just emit ().
890   //
891   if (FT->isVarArg() && !FT->getParamTypes().empty()) {
892     if (FT->getParamTypes().size()) FunctionInnards << ", ";
893     FunctionInnards << "...";  // Output varargs portion of signature!
894   }
895   FunctionInnards << ")";
896   // Print out the return type and the entire signature for that matter
897   printType(Out, F->getReturnType(), FunctionInnards.str());
898
899   if (F->hasWeakLinkage()) Out << " __attribute((weak))";
900 }
901
902 void CWriter::printFunction(Function *F) {
903   if (F->isExternal()) return;
904
905   printFunctionSignature(F, false);
906   Out << " {\n";
907
908   // print local variable information for the function
909   for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
910     if (const AllocaInst *AI = isDirectAlloca(*I)) {
911       Out << "  ";
912       printType(Out, AI->getAllocatedType(), Mang->getValueName(AI));
913       Out << ";    /* Address exposed local */\n";
914     } else if ((*I)->getType() != Type::VoidTy && !isInlinableInst(**I)) {
915       Out << "  ";
916       printType(Out, (*I)->getType(), Mang->getValueName(*I));
917       Out << ";\n";
918       
919       if (isa<PHINode>(*I)) {  // Print out PHI node temporaries as well...
920         Out << "  ";
921         printType(Out, (*I)->getType(),
922                   Mang->getValueName(*I)+"__PHI_TEMPORARY");
923         Out << ";\n";
924       }
925     }
926
927   Out << "\n";
928
929   // print the basic blocks
930   for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
931     BasicBlock *Prev = BB->getPrev();
932
933     // Don't print the label for the basic block if there are no uses, or if the
934     // only terminator use is the predecessor basic block's terminator.  We have
935     // to scan the use list because PHI nodes use basic blocks too but do not
936     // require a label to be generated.
937     //
938     bool NeedsLabel = false;
939     for (Value::use_iterator UI = BB->use_begin(), UE = BB->use_end();
940          UI != UE; ++UI)
941       if (TerminatorInst *TI = dyn_cast<TerminatorInst>(*UI))
942         if (TI != Prev->getTerminator() ||
943             isa<SwitchInst>(Prev->getTerminator()) ||
944             isa<InvokeInst>(Prev->getTerminator())) {
945           NeedsLabel = true;
946           break;        
947         }
948
949     if (NeedsLabel) Out << Mang->getValueName(BB) << ":\n";
950
951     // Output all of the instructions in the basic block...
952     for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E; ++II){
953       if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
954         if (II->getType() != Type::VoidTy)
955           outputLValue(II);
956         else
957           Out << "  ";
958         visit(*II);
959         Out << ";\n";
960       }
961     }
962
963     // Don't emit prefix or suffix for the terminator...
964     visit(*BB->getTerminator());
965   }
966   
967   Out << "}\n\n";
968 }
969
970 // Specific Instruction type classes... note that all of the casts are
971 // necessary because we use the instruction classes as opaque types...
972 //
973 void CWriter::visitReturnInst(ReturnInst &I) {
974   // Don't output a void return if this is the last basic block in the function
975   if (I.getNumOperands() == 0 && 
976       &*--I.getParent()->getParent()->end() == I.getParent() &&
977       !I.getParent()->size() == 1) {
978     return;
979   }
980
981   Out << "  return";
982   if (I.getNumOperands()) {
983     Out << " ";
984     writeOperand(I.getOperand(0));
985   }
986   Out << ";\n";
987 }
988
989 void CWriter::visitSwitchInst(SwitchInst &SI) {
990   Out << "  switch (";
991   writeOperand(SI.getOperand(0));
992   Out << ") {\n  default:\n";
993   printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
994   Out << ";\n";
995   for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
996     Out << "  case ";
997     writeOperand(SI.getOperand(i));
998     Out << ":\n";
999     BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
1000     printBranchToBlock(SI.getParent(), Succ, 2);
1001     if (Succ == SI.getParent()->getNext())
1002       Out << "    break;\n";
1003   }
1004   Out << "  }\n";
1005 }
1006
1007 void CWriter::visitInvokeInst(InvokeInst &II) {
1008   Out << "  {\n"
1009       << "    struct __llvm_jmpbuf_list_t Entry;\n"
1010       << "    Entry.next = __llvm_jmpbuf_list;\n"
1011       << "    if (setjmp(Entry.buf)) {\n"
1012       << "      __llvm_jmpbuf_list = Entry.next;\n";
1013   printBranchToBlock(II.getParent(), II.getExceptionalDest(), 4);
1014   Out << "    }\n"
1015       << "    __llvm_jmpbuf_list = &Entry;\n"
1016       << "    ";
1017
1018   if (II.getType() != Type::VoidTy) outputLValue(&II);
1019   visitCallSite(&II);
1020   Out << ";\n"
1021       << "    __llvm_jmpbuf_list = Entry.next;\n"
1022       << "  }\n";
1023   printBranchToBlock(II.getParent(), II.getNormalDest(), 0);
1024   emittedInvoke = true;
1025 }
1026
1027
1028 void CWriter::visitUnwindInst(UnwindInst &I) {
1029   // The unwind instructions causes a control flow transfer out of the current
1030   // function, unwinding the stack until a caller who used the invoke
1031   // instruction is found.  In this context, we code generated the invoke
1032   // instruction to add an entry to the top of the jmpbuf_list.  Thus, here we
1033   // just have to longjmp to the specified handler.
1034   Out << "  if (__llvm_jmpbuf_list == 0) {  /* unwind */\n"
1035       << "    extern write();\n"
1036       << "    ((void (*)(int, void*, unsigned))write)(2,\n"
1037       << "           \"throw found with no handler!\\n\", 31); abort();\n"
1038       << "  }\n"
1039       << "  longjmp(__llvm_jmpbuf_list->buf, 1);\n";
1040   emittedInvoke = true;
1041 }
1042
1043 static bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
1044   // If PHI nodes need copies, we need the copy code...
1045   if (isa<PHINode>(To->front()) ||
1046       From->getNext() != To)      // Not directly successor, need goto
1047     return true;
1048
1049   // Otherwise we don't need the code.
1050   return false;
1051 }
1052
1053 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
1054                                  unsigned Indent) {
1055   for (BasicBlock::iterator I = Succ->begin();
1056        PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1057     //  now we have to do the printing
1058     Out << std::string(Indent, ' ');
1059     Out << "  " << Mang->getValueName(I) << "__PHI_TEMPORARY = ";
1060     writeOperand(PN->getIncomingValue(PN->getBasicBlockIndex(CurBB)));
1061     Out << ";   /* for PHI node */\n";
1062   }
1063
1064   if (CurBB->getNext() != Succ ||
1065       isa<InvokeInst>(CurBB->getTerminator()) ||
1066       isa<SwitchInst>(CurBB->getTerminator())) {
1067     Out << std::string(Indent, ' ') << "  goto ";
1068     writeOperand(Succ);
1069     Out << ";\n";
1070   }
1071 }
1072
1073 // Branch instruction printing - Avoid printing out a branch to a basic block
1074 // that immediately succeeds the current one.
1075 //
1076 void CWriter::visitBranchInst(BranchInst &I) {
1077   if (I.isConditional()) {
1078     if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
1079       Out << "  if (";
1080       writeOperand(I.getCondition());
1081       Out << ") {\n";
1082       
1083       printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
1084       
1085       if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
1086         Out << "  } else {\n";
1087         printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
1088       }
1089     } else {
1090       // First goto not necessary, assume second one is...
1091       Out << "  if (!";
1092       writeOperand(I.getCondition());
1093       Out << ") {\n";
1094
1095       printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
1096     }
1097
1098     Out << "  }\n";
1099   } else {
1100     printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
1101   }
1102   Out << "\n";
1103 }
1104
1105 // PHI nodes get copied into temporary values at the end of predecessor basic
1106 // blocks.  We now need to copy these temporary values into the REAL value for
1107 // the PHI.
1108 void CWriter::visitPHINode(PHINode &I) {
1109   writeOperand(&I);
1110   Out << "__PHI_TEMPORARY";
1111 }
1112
1113
1114 void CWriter::visitBinaryOperator(Instruction &I) {
1115   // binary instructions, shift instructions, setCond instructions.
1116   assert(!isa<PointerType>(I.getType()));
1117
1118   // We must cast the results of binary operations which might be promoted.
1119   bool needsCast = false;
1120   if ((I.getType() == Type::UByteTy) || (I.getType() == Type::SByteTy)
1121       || (I.getType() == Type::UShortTy) || (I.getType() == Type::ShortTy)
1122       || (I.getType() == Type::FloatTy)) {
1123     needsCast = true;
1124     Out << "((";
1125     printType(Out, I.getType(), "", false, false);
1126     Out << ")(";
1127   }
1128       
1129   writeOperand(I.getOperand(0));
1130
1131   switch (I.getOpcode()) {
1132   case Instruction::Add: Out << " + "; break;
1133   case Instruction::Sub: Out << " - "; break;
1134   case Instruction::Mul: Out << "*"; break;
1135   case Instruction::Div: Out << "/"; break;
1136   case Instruction::Rem: Out << "%"; break;
1137   case Instruction::And: Out << " & "; break;
1138   case Instruction::Or: Out << " | "; break;
1139   case Instruction::Xor: Out << " ^ "; break;
1140   case Instruction::SetEQ: Out << " == "; break;
1141   case Instruction::SetNE: Out << " != "; break;
1142   case Instruction::SetLE: Out << " <= "; break;
1143   case Instruction::SetGE: Out << " >= "; break;
1144   case Instruction::SetLT: Out << " < "; break;
1145   case Instruction::SetGT: Out << " > "; break;
1146   case Instruction::Shl : Out << " << "; break;
1147   case Instruction::Shr : Out << " >> "; break;
1148   default: std::cerr << "Invalid operator type!" << I; abort();
1149   }
1150
1151   writeOperand(I.getOperand(1));
1152
1153   if (needsCast) {
1154     Out << "))";
1155   }
1156 }
1157
1158 void CWriter::visitCastInst(CastInst &I) {
1159   if (I.getType() == Type::BoolTy) {
1160     Out << "(";
1161     writeOperand(I.getOperand(0));
1162     Out << " != 0)";
1163     return;
1164   }
1165   Out << "(";
1166   printType(Out, I.getType(), "", /*ignoreName*/false, /*namedContext*/false);
1167   Out << ")";
1168   if (isa<PointerType>(I.getType())&&I.getOperand(0)->getType()->isIntegral() ||
1169       isa<PointerType>(I.getOperand(0)->getType())&&I.getType()->isIntegral()) {
1170     // Avoid "cast to pointer from integer of different size" warnings
1171     Out << "(long)";  
1172   }
1173   
1174   writeOperand(I.getOperand(0));
1175 }
1176
1177 void CWriter::visitCallInst(CallInst &I) {
1178   // Handle intrinsic function calls first...
1179   if (Function *F = I.getCalledFunction())
1180     if (LLVMIntrinsic::ID ID = (LLVMIntrinsic::ID)F->getIntrinsicID()) {
1181       switch (ID) {
1182       default:  assert(0 && "Unknown LLVM intrinsic!");
1183       case LLVMIntrinsic::va_start: 
1184         Out << "va_start(*(va_list*)";
1185         writeOperand(I.getOperand(1));
1186         Out << ", ";
1187         // Output the last argument to the enclosing function...
1188         writeOperand(&I.getParent()->getParent()->aback());
1189         Out << ")";
1190         return;
1191       case LLVMIntrinsic::va_end:
1192         Out << "va_end(*(va_list*)";
1193         writeOperand(I.getOperand(1));
1194         Out << ")";
1195         return;
1196       case LLVMIntrinsic::va_copy:
1197         Out << "va_copy(*(va_list*)";
1198         writeOperand(I.getOperand(1));
1199         Out << ", (va_list)";
1200         writeOperand(I.getOperand(2));
1201         Out << ")";
1202         return;
1203
1204       case LLVMIntrinsic::setjmp:
1205       case LLVMIntrinsic::sigsetjmp:
1206         // This intrinsic should never exist in the program, but until we get
1207         // setjmp/longjmp transformations going on, we should codegen it to
1208         // something reasonable.  This will allow code that never calls longjmp
1209         // to work.
1210         Out << "0";
1211         return;
1212       case LLVMIntrinsic::longjmp:
1213       case LLVMIntrinsic::siglongjmp:
1214         // Longjmp is not implemented, and never will be.  It would cause an
1215         // exception throw.
1216         Out << "abort()";
1217         return;
1218       }
1219     }
1220   visitCallSite(&I);
1221 }
1222
1223 void CWriter::visitCallSite(CallSite CS) {
1224   const PointerType  *PTy   = cast<PointerType>(CS.getCalledValue()->getType());
1225   const FunctionType *FTy   = cast<FunctionType>(PTy->getElementType());
1226   const Type         *RetTy = FTy->getReturnType();
1227   
1228   writeOperand(CS.getCalledValue());
1229   Out << "(";
1230
1231   if (CS.arg_begin() != CS.arg_end()) {
1232     CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
1233     writeOperand(*AI);
1234
1235     for (++AI; AI != AE; ++AI) {
1236       Out << ", ";
1237       writeOperand(*AI);
1238     }
1239   }
1240   Out << ")";
1241 }  
1242
1243 void CWriter::visitMallocInst(MallocInst &I) {
1244   Out << "(";
1245   printType(Out, I.getType());
1246   Out << ")malloc(sizeof(";
1247   printType(Out, I.getType()->getElementType());
1248   Out << ")";
1249
1250   if (I.isArrayAllocation()) {
1251     Out << " * " ;
1252     writeOperand(I.getOperand(0));
1253   }
1254   Out << ")";
1255 }
1256
1257 void CWriter::visitAllocaInst(AllocaInst &I) {
1258   Out << "(";
1259   printType(Out, I.getType());
1260   Out << ") alloca(sizeof(";
1261   printType(Out, I.getType()->getElementType());
1262   Out << ")";
1263   if (I.isArrayAllocation()) {
1264     Out << " * " ;
1265     writeOperand(I.getOperand(0));
1266   }
1267   Out << ")";
1268 }
1269
1270 void CWriter::visitFreeInst(FreeInst &I) {
1271   Out << "free((char*)";
1272   writeOperand(I.getOperand(0));
1273   Out << ")";
1274 }
1275
1276 void CWriter::printIndexingExpression(Value *Ptr, User::op_iterator I,
1277                                       User::op_iterator E) {
1278   bool HasImplicitAddress = false;
1279   // If accessing a global value with no indexing, avoid *(&GV) syndrome
1280   if (GlobalValue *V = dyn_cast<GlobalValue>(Ptr)) {
1281     HasImplicitAddress = true;
1282   } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Ptr)) {
1283     HasImplicitAddress = true;
1284     Ptr = CPR->getValue();         // Get to the global...
1285   } else if (isDirectAlloca(Ptr)) {
1286     HasImplicitAddress = true;
1287   }
1288
1289   if (I == E) {
1290     if (!HasImplicitAddress)
1291       Out << "*";  // Implicit zero first argument: '*x' is equivalent to 'x[0]'
1292
1293     writeOperandInternal(Ptr);
1294     return;
1295   }
1296
1297   const Constant *CI = dyn_cast<Constant>(I);
1298   if (HasImplicitAddress && (!CI || !CI->isNullValue()))
1299     Out << "(&";
1300
1301   writeOperandInternal(Ptr);
1302
1303   if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
1304     Out << ")";
1305     HasImplicitAddress = false;  // HIA is only true if we haven't addressed yet
1306   }
1307
1308   assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
1309          "Can only have implicit address with direct accessing");
1310
1311   if (HasImplicitAddress) {
1312     ++I;
1313   } else if (CI && CI->isNullValue() && I+1 != E) {
1314     // Print out the -> operator if possible...
1315     if ((*(I+1))->getType() == Type::UByteTy) {
1316       Out << (HasImplicitAddress ? "." : "->");
1317       Out << "field" << cast<ConstantUInt>(*(I+1))->getValue();
1318       I += 2;
1319     } 
1320   }
1321
1322   for (; I != E; ++I)
1323     if ((*I)->getType() == Type::LongTy) {
1324       Out << "[";
1325       writeOperand(*I);
1326       Out << "]";
1327     } else {
1328       Out << ".field" << cast<ConstantUInt>(*I)->getValue();
1329     }
1330 }
1331
1332 void CWriter::visitLoadInst(LoadInst &I) {
1333   Out << "*";
1334   writeOperand(I.getOperand(0));
1335 }
1336
1337 void CWriter::visitStoreInst(StoreInst &I) {
1338   Out << "*";
1339   writeOperand(I.getPointerOperand());
1340   Out << " = ";
1341   writeOperand(I.getOperand(0));
1342 }
1343
1344 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
1345   Out << "&";
1346   printIndexingExpression(I.getPointerOperand(), I.idx_begin(), I.idx_end());
1347 }
1348
1349 void CWriter::visitVarArgInst(VarArgInst &I) {
1350   Out << "va_arg((va_list)*";
1351   writeOperand(I.getOperand(0));
1352   Out << ", ";
1353   printType(Out, I.getType(), "", /*ignoreName*/false, /*namedContext*/false);
1354   Out << ")";  
1355 }
1356
1357
1358 //===----------------------------------------------------------------------===//
1359 //                       External Interface declaration
1360 //===----------------------------------------------------------------------===//
1361
1362 Pass *createWriteToCPass(std::ostream &o) { return new CWriter(o); }