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