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