bcc5fbf60ae6ca7f71483313aad9c41ade6194cc
[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 "CTargetMachine.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Module.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Pass.h"
22 #include "llvm/PassManager.h"
23 #include "llvm/SymbolTable.h"
24 #include "llvm/Intrinsics.h"
25 #include "llvm/IntrinsicInst.h"
26 #include "llvm/Analysis/ConstantsScanner.h"
27 #include "llvm/Analysis/FindUsedTypes.h"
28 #include "llvm/Analysis/LoopInfo.h"
29 #include "llvm/CodeGen/IntrinsicLowering.h"
30 #include "llvm/Transforms/Scalar.h"
31 #include "llvm/Target/TargetMachineRegistry.h"
32 #include "llvm/Support/CallSite.h"
33 #include "llvm/Support/CFG.h"
34 #include "llvm/Support/GetElementPtrTypeIterator.h"
35 #include "llvm/Support/InstVisitor.h"
36 #include "llvm/Support/Mangler.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/ADT/StringExtras.h"
39 #include "llvm/ADT/STLExtras.h"
40 #include "llvm/Support/MathExtras.h"
41 #include "llvm/Config/config.h"
42 #include <algorithm>
43 #include <iostream>
44 #include <ios>
45 #include <sstream>
46 using namespace llvm;
47
48 namespace {
49   // Register the target.
50   RegisterTarget<CTargetMachine> X("c", "  C backend");
51
52   /// CBackendNameAllUsedStructsAndMergeFunctions - This pass inserts names for
53   /// any unnamed structure types that are used by the program, and merges
54   /// external functions with the same name.
55   ///
56   class CBackendNameAllUsedStructsAndMergeFunctions : public ModulePass {
57     void getAnalysisUsage(AnalysisUsage &AU) const {
58       AU.addRequired<FindUsedTypes>();
59     }
60
61     virtual const char *getPassName() const {
62       return "C backend type canonicalizer";
63     }
64
65     virtual bool runOnModule(Module &M);
66   };
67
68   /// CWriter - This class is the main chunk of code that converts an LLVM
69   /// module to a C translation unit.
70   class CWriter : public FunctionPass, public InstVisitor<CWriter> {
71     std::ostream &Out;
72     IntrinsicLowering IL;
73     Mangler *Mang;
74     LoopInfo *LI;
75     const Module *TheModule;
76     std::map<const Type *, std::string> TypeNames;
77
78     std::map<const ConstantFP *, unsigned> FPConstantMap;
79   public:
80     CWriter(std::ostream &o) : Out(o) {}
81
82     virtual const char *getPassName() const { return "C backend"; }
83
84     void getAnalysisUsage(AnalysisUsage &AU) const {
85       AU.addRequired<LoopInfo>();
86       AU.setPreservesAll();
87     }
88
89     virtual bool doInitialization(Module &M);
90
91     bool runOnFunction(Function &F) {
92       LI = &getAnalysis<LoopInfo>();
93
94       // Get rid of intrinsics we can't handle.
95       lowerIntrinsics(F);
96
97       // Output all floating point constants that cannot be printed accurately.
98       printFloatingPointConstants(F);
99
100       // Ensure that no local symbols conflict with global symbols.
101       F.renameLocalSymbols();
102
103       printFunction(F);
104       FPConstantMap.clear();
105       return false;
106     }
107
108     virtual bool doFinalization(Module &M) {
109       // Free memory...
110       delete Mang;
111       TypeNames.clear();
112       return false;
113     }
114
115     std::ostream &printType(std::ostream &Out, const Type *Ty,
116                             const std::string &VariableName = "",
117                             bool IgnoreName = false);
118
119     void printStructReturnPointerFunctionType(std::ostream &Out,
120                                               const PointerType *Ty);
121     
122     void writeOperand(Value *Operand);
123     void writeOperandInternal(Value *Operand);
124     void writeOperandWithCast(Value* Operand, unsigned Opcode);
125     bool writeInstructionCast(const Instruction &I);
126
127   private :
128     void lowerIntrinsics(Function &F);
129
130     void printModule(Module *M);
131     void printModuleTypes(const SymbolTable &ST);
132     void printContainedStructs(const Type *Ty, std::set<const StructType *> &);
133     void printFloatingPointConstants(Function &F);
134     void printFunctionSignature(const Function *F, bool Prototype);
135
136     void printFunction(Function &);
137     void printBasicBlock(BasicBlock *BB);
138     void printLoop(Loop *L);
139
140     void printCast(unsigned opcode, const Type *SrcTy, const Type *DstTy);
141     void printConstant(Constant *CPV);
142     void printConstantWithCast(Constant *CPV, unsigned Opcode);
143     bool printConstExprCast(const ConstantExpr *CE);
144     void printConstantArray(ConstantArray *CPA);
145     void printConstantPacked(ConstantPacked *CP);
146
147     // isInlinableInst - Attempt to inline instructions into their uses to build
148     // trees as much as possible.  To do this, we have to consistently decide
149     // what is acceptable to inline, so that variable declarations don't get
150     // printed and an extra copy of the expr is not emitted.
151     //
152     static bool isInlinableInst(const Instruction &I) {
153       // Always inline setcc instructions, even if they are shared by multiple
154       // expressions.  GCC generates horrible code if we don't.
155       if (isa<SetCondInst>(I)) return true;
156
157       // Must be an expression, must be used exactly once.  If it is dead, we
158       // emit it inline where it would go.
159       if (I.getType() == Type::VoidTy || !I.hasOneUse() ||
160           isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
161           isa<LoadInst>(I) || isa<VAArgInst>(I))
162         // Don't inline a load across a store or other bad things!
163         return false;
164
165       // Only inline instruction it it's use is in the same BB as the inst.
166       return I.getParent() == cast<Instruction>(I.use_back())->getParent();
167     }
168
169     // isDirectAlloca - Define fixed sized allocas in the entry block as direct
170     // variables which are accessed with the & operator.  This causes GCC to
171     // generate significantly better code than to emit alloca calls directly.
172     //
173     static const AllocaInst *isDirectAlloca(const Value *V) {
174       const AllocaInst *AI = dyn_cast<AllocaInst>(V);
175       if (!AI) return false;
176       if (AI->isArrayAllocation())
177         return 0;   // FIXME: we can also inline fixed size array allocas!
178       if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
179         return 0;
180       return AI;
181     }
182
183     // Instruction visitation functions
184     friend class InstVisitor<CWriter>;
185
186     void visitReturnInst(ReturnInst &I);
187     void visitBranchInst(BranchInst &I);
188     void visitSwitchInst(SwitchInst &I);
189     void visitInvokeInst(InvokeInst &I) {
190       assert(0 && "Lowerinvoke pass didn't work!");
191     }
192
193     void visitUnwindInst(UnwindInst &I) {
194       assert(0 && "Lowerinvoke pass didn't work!");
195     }
196     void visitUnreachableInst(UnreachableInst &I);
197
198     void visitPHINode(PHINode &I);
199     void visitBinaryOperator(Instruction &I);
200
201     void visitCastInst (CastInst &I);
202     void visitSelectInst(SelectInst &I);
203     void visitCallInst (CallInst &I);
204     void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
205
206     void visitMallocInst(MallocInst &I);
207     void visitAllocaInst(AllocaInst &I);
208     void visitFreeInst  (FreeInst   &I);
209     void visitLoadInst  (LoadInst   &I);
210     void visitStoreInst (StoreInst  &I);
211     void visitGetElementPtrInst(GetElementPtrInst &I);
212     void visitVAArgInst (VAArgInst &I);
213
214     void visitInstruction(Instruction &I) {
215       std::cerr << "C Writer does not know about " << I;
216       abort();
217     }
218
219     void outputLValue(Instruction *I) {
220       Out << "  " << Mang->getValueName(I) << " = ";
221     }
222
223     bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
224     void printPHICopiesForSuccessor(BasicBlock *CurBlock,
225                                     BasicBlock *Successor, unsigned Indent);
226     void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
227                             unsigned Indent);
228     void printIndexingExpression(Value *Ptr, gep_type_iterator I,
229                                  gep_type_iterator E);
230   };
231 }
232
233 /// This method inserts names for any unnamed structure types that are used by
234 /// the program, and removes names from structure types that are not used by the
235 /// program.
236 ///
237 bool CBackendNameAllUsedStructsAndMergeFunctions::runOnModule(Module &M) {
238   // Get a set of types that are used by the program...
239   std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
240
241   // Loop over the module symbol table, removing types from UT that are
242   // already named, and removing names for types that are not used.
243   //
244   SymbolTable &MST = M.getSymbolTable();
245   for (SymbolTable::type_iterator TI = MST.type_begin(), TE = MST.type_end();
246        TI != TE; ) {
247     SymbolTable::type_iterator I = TI++;
248
249     // If this is not used, remove it from the symbol table.
250     std::set<const Type *>::iterator UTI = UT.find(I->second);
251     if (UTI == UT.end())
252       MST.remove(I);
253     else
254       UT.erase(UTI);    // Only keep one name for this type.
255   }
256
257   // UT now contains types that are not named.  Loop over it, naming
258   // structure types.
259   //
260   bool Changed = false;
261   unsigned RenameCounter = 0;
262   for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
263        I != E; ++I)
264     if (const StructType *ST = dyn_cast<StructType>(*I)) {
265       while (M.addTypeName("unnamed"+utostr(RenameCounter), ST))
266         ++RenameCounter;
267       Changed = true;
268     }
269       
270       
271   // Loop over all external functions and globals.  If we have two with
272   // identical names, merge them.
273   // FIXME: This code should disappear when we don't allow values with the same
274   // names when they have different types!
275   std::map<std::string, GlobalValue*> ExtSymbols;
276   for (Module::iterator I = M.begin(), E = M.end(); I != E;) {
277     Function *GV = I++;
278     if (GV->isExternal() && GV->hasName()) {
279       std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
280         = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
281       if (!X.second) {
282         // Found a conflict, replace this global with the previous one.
283         GlobalValue *OldGV = X.first->second;
284         GV->replaceAllUsesWith(ConstantExpr::getCast(OldGV, GV->getType()));
285         GV->eraseFromParent();
286         Changed = true;
287       }
288     }
289   }
290   // Do the same for globals.
291   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
292        I != E;) {
293     GlobalVariable *GV = I++;
294     if (GV->isExternal() && GV->hasName()) {
295       std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
296         = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
297       if (!X.second) {
298         // Found a conflict, replace this global with the previous one.
299         GlobalValue *OldGV = X.first->second;
300         GV->replaceAllUsesWith(ConstantExpr::getCast(OldGV, GV->getType()));
301         GV->eraseFromParent();
302         Changed = true;
303       }
304     }
305   }
306   
307   return Changed;
308 }
309
310 /// printStructReturnPointerFunctionType - This is like printType for a struct
311 /// return type, except, instead of printing the type as void (*)(Struct*, ...)
312 /// print it as "Struct (*)(...)", for struct return functions.
313 void CWriter::printStructReturnPointerFunctionType(std::ostream &Out,
314                                                    const PointerType *TheTy) {
315   const FunctionType *FTy = cast<FunctionType>(TheTy->getElementType());
316   std::stringstream FunctionInnards;
317   FunctionInnards << " (*) (";
318   bool PrintedType = false;
319
320   FunctionType::param_iterator I = FTy->param_begin(), E = FTy->param_end();
321   const Type *RetTy = cast<PointerType>(I->get())->getElementType();
322   for (++I; I != E; ++I) {
323     if (PrintedType)
324       FunctionInnards << ", ";
325     printType(FunctionInnards, *I, "");
326     PrintedType = true;
327   }
328   if (FTy->isVarArg()) {
329     if (PrintedType)
330       FunctionInnards << ", ...";
331   } else if (!PrintedType) {
332     FunctionInnards << "void";
333   }
334   FunctionInnards << ')';
335   std::string tstr = FunctionInnards.str();
336   printType(Out, RetTy, tstr);
337 }
338
339
340 // Pass the Type* and the variable name and this prints out the variable
341 // declaration.
342 //
343 std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
344                                  const std::string &NameSoFar,
345                                  bool IgnoreName) {
346   if (Ty->isPrimitiveType())
347     switch (Ty->getTypeID()) {
348     case Type::VoidTyID:   return Out << "void "               << NameSoFar;
349     case Type::BoolTyID:   return Out << "bool "               << NameSoFar;
350     case Type::UByteTyID:  return Out << "unsigned char "      << NameSoFar;
351     case Type::SByteTyID:  return Out << "signed char "        << NameSoFar;
352     case Type::UShortTyID: return Out << "unsigned short "     << NameSoFar;
353     case Type::ShortTyID:  return Out << "short "              << NameSoFar;
354     case Type::UIntTyID:   return Out << "unsigned "           << NameSoFar;
355     case Type::IntTyID:    return Out << "int "                << NameSoFar;
356     case Type::ULongTyID:  return Out << "unsigned long long " << NameSoFar;
357     case Type::LongTyID:   return Out << "signed long long "   << NameSoFar;
358     case Type::FloatTyID:  return Out << "float "              << NameSoFar;
359     case Type::DoubleTyID: return Out << "double "             << NameSoFar;
360     default :
361       std::cerr << "Unknown primitive type: " << *Ty << "\n";
362       abort();
363     }
364
365   // Check to see if the type is named.
366   if (!IgnoreName || isa<OpaqueType>(Ty)) {
367     std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
368     if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
369   }
370
371   switch (Ty->getTypeID()) {
372   case Type::FunctionTyID: {
373     const FunctionType *FTy = cast<FunctionType>(Ty);
374     std::stringstream FunctionInnards;
375     FunctionInnards << " (" << NameSoFar << ") (";
376     for (FunctionType::param_iterator I = FTy->param_begin(),
377            E = FTy->param_end(); I != E; ++I) {
378       if (I != FTy->param_begin())
379         FunctionInnards << ", ";
380       printType(FunctionInnards, *I, "");
381     }
382     if (FTy->isVarArg()) {
383       if (FTy->getNumParams())
384         FunctionInnards << ", ...";
385     } else if (!FTy->getNumParams()) {
386       FunctionInnards << "void";
387     }
388     FunctionInnards << ')';
389     std::string tstr = FunctionInnards.str();
390     printType(Out, FTy->getReturnType(), tstr);
391     return Out;
392   }
393   case Type::StructTyID: {
394     const StructType *STy = cast<StructType>(Ty);
395     Out << NameSoFar + " {\n";
396     unsigned Idx = 0;
397     for (StructType::element_iterator I = STy->element_begin(),
398            E = STy->element_end(); I != E; ++I) {
399       Out << "  ";
400       printType(Out, *I, "field" + utostr(Idx++));
401       Out << ";\n";
402     }
403     return Out << '}';
404   }
405
406   case Type::PointerTyID: {
407     const PointerType *PTy = cast<PointerType>(Ty);
408     std::string ptrName = "*" + NameSoFar;
409
410     if (isa<ArrayType>(PTy->getElementType()) ||
411         isa<PackedType>(PTy->getElementType()))
412       ptrName = "(" + ptrName + ")";
413
414     return printType(Out, PTy->getElementType(), ptrName);
415   }
416
417   case Type::ArrayTyID: {
418     const ArrayType *ATy = cast<ArrayType>(Ty);
419     unsigned NumElements = ATy->getNumElements();
420     if (NumElements == 0) NumElements = 1;
421     return printType(Out, ATy->getElementType(),
422                      NameSoFar + "[" + utostr(NumElements) + "]");
423   }
424
425   case Type::PackedTyID: {
426     const PackedType *PTy = cast<PackedType>(Ty);
427     unsigned NumElements = PTy->getNumElements();
428     if (NumElements == 0) NumElements = 1;
429     return printType(Out, PTy->getElementType(),
430                      NameSoFar + "[" + utostr(NumElements) + "]");
431   }
432
433   case Type::OpaqueTyID: {
434     static int Count = 0;
435     std::string TyName = "struct opaque_" + itostr(Count++);
436     assert(TypeNames.find(Ty) == TypeNames.end());
437     TypeNames[Ty] = TyName;
438     return Out << TyName << ' ' << NameSoFar;
439   }
440   default:
441     assert(0 && "Unhandled case in getTypeProps!");
442     abort();
443   }
444
445   return Out;
446 }
447
448 void CWriter::printConstantArray(ConstantArray *CPA) {
449
450   // As a special case, print the array as a string if it is an array of
451   // ubytes or an array of sbytes with positive values.
452   //
453   const Type *ETy = CPA->getType()->getElementType();
454   bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
455
456   // Make sure the last character is a null char, as automatically added by C
457   if (isString && (CPA->getNumOperands() == 0 ||
458                    !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
459     isString = false;
460
461   if (isString) {
462     Out << '\"';
463     // Keep track of whether the last number was a hexadecimal escape
464     bool LastWasHex = false;
465
466     // Do not include the last character, which we know is null
467     for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
468       unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getZExtValue();
469
470       // Print it out literally if it is a printable character.  The only thing
471       // to be careful about is when the last letter output was a hex escape
472       // code, in which case we have to be careful not to print out hex digits
473       // explicitly (the C compiler thinks it is a continuation of the previous
474       // character, sheesh...)
475       //
476       if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
477         LastWasHex = false;
478         if (C == '"' || C == '\\')
479           Out << "\\" << C;
480         else
481           Out << C;
482       } else {
483         LastWasHex = false;
484         switch (C) {
485         case '\n': Out << "\\n"; break;
486         case '\t': Out << "\\t"; break;
487         case '\r': Out << "\\r"; break;
488         case '\v': Out << "\\v"; break;
489         case '\a': Out << "\\a"; break;
490         case '\"': Out << "\\\""; break;
491         case '\'': Out << "\\\'"; break;
492         default:
493           Out << "\\x";
494           Out << (char)(( C/16  < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
495           Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
496           LastWasHex = true;
497           break;
498         }
499       }
500     }
501     Out << '\"';
502   } else {
503     Out << '{';
504     if (CPA->getNumOperands()) {
505       Out << ' ';
506       printConstant(cast<Constant>(CPA->getOperand(0)));
507       for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
508         Out << ", ";
509         printConstant(cast<Constant>(CPA->getOperand(i)));
510       }
511     }
512     Out << " }";
513   }
514 }
515
516 void CWriter::printConstantPacked(ConstantPacked *CP) {
517   Out << '{';
518   if (CP->getNumOperands()) {
519     Out << ' ';
520     printConstant(cast<Constant>(CP->getOperand(0)));
521     for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
522       Out << ", ";
523       printConstant(cast<Constant>(CP->getOperand(i)));
524     }
525   }
526   Out << " }";
527 }
528
529 // isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
530 // textually as a double (rather than as a reference to a stack-allocated
531 // variable). We decide this by converting CFP to a string and back into a
532 // double, and then checking whether the conversion results in a bit-equal
533 // double to the original value of CFP. This depends on us and the target C
534 // compiler agreeing on the conversion process (which is pretty likely since we
535 // only deal in IEEE FP).
536 //
537 static bool isFPCSafeToPrint(const ConstantFP *CFP) {
538 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
539   char Buffer[100];
540   sprintf(Buffer, "%a", CFP->getValue());
541
542   if (!strncmp(Buffer, "0x", 2) ||
543       !strncmp(Buffer, "-0x", 3) ||
544       !strncmp(Buffer, "+0x", 3))
545     return atof(Buffer) == CFP->getValue();
546   return false;
547 #else
548   std::string StrVal = ftostr(CFP->getValue());
549
550   while (StrVal[0] == ' ')
551     StrVal.erase(StrVal.begin());
552
553   // Check to make sure that the stringized number is not some string like "Inf"
554   // or NaN.  Check that the string matches the "[-+]?[0-9]" regex.
555   if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
556       ((StrVal[0] == '-' || StrVal[0] == '+') &&
557        (StrVal[1] >= '0' && StrVal[1] <= '9')))
558     // Reparse stringized version!
559     return atof(StrVal.c_str()) == CFP->getValue();
560   return false;
561 #endif
562 }
563
564 /// Print out the casting for a cast operation. This does the double casting
565 /// necessary for conversion to the destination type, if necessary. 
566 /// @returns true if a closing paren is necessary
567 /// @brief Print a cast
568 void CWriter::printCast(unsigned opc, const Type *SrcTy, const Type *DstTy) {
569   Out << '(';
570   printType(Out, DstTy);
571   Out << ')';
572   switch (opc) {
573     case Instruction::UIToFP:
574     case Instruction::ZExt:
575       if (SrcTy->isSigned()) {
576         Out << '(';
577         printType(Out, SrcTy->getUnsignedVersion());
578         Out << ')';
579       }
580       break;
581     case Instruction::SIToFP:
582     case Instruction::SExt:
583       if (SrcTy->isUnsigned()) {
584         Out << '(';
585         printType(Out, SrcTy->getSignedVersion());
586         Out << ')';
587       }
588       break;
589     case Instruction::IntToPtr:
590     case Instruction::PtrToInt:
591         // Avoid "cast to pointer from integer of different size" warnings
592         Out << "(unsigned long)";
593         break;
594     case Instruction::Trunc:
595     case Instruction::BitCast:
596     case Instruction::FPExt:
597     case Instruction::FPTrunc:
598     case Instruction::FPToSI:
599     case Instruction::FPToUI:
600     default:
601       break;
602   }
603 }
604
605 // printConstant - The LLVM Constant to C Constant converter.
606 void CWriter::printConstant(Constant *CPV) {
607   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
608     switch (CE->getOpcode()) {
609     case Instruction::Trunc:
610     case Instruction::ZExt:
611     case Instruction::SExt:
612     case Instruction::FPTrunc:
613     case Instruction::FPExt:
614     case Instruction::UIToFP:
615     case Instruction::SIToFP:
616     case Instruction::FPToUI:
617     case Instruction::FPToSI:
618     case Instruction::PtrToInt:
619     case Instruction::IntToPtr:
620     case Instruction::BitCast:
621       Out << "(";
622       printCast(CE->getOpcode(), CE->getOperand(0)->getType(), CE->getType());
623       if (CE->getOpcode() == Instruction::SExt &&
624           CE->getOperand(0)->getType() == Type::BoolTy) {
625         // Make sure we really sext from bool here by subtracting from 0
626         Out << "0-";
627       }
628       printConstant(CE->getOperand(0));
629       if (CE->getOpcode() == Instruction::Trunc && 
630           CE->getType() == Type::BoolTy) {
631         // Make sure we really truncate to bool here by anding with 1
632         Out << "&1u";
633       }
634       Out << ')';
635       return;
636
637     case Instruction::GetElementPtr:
638       Out << "(&(";
639       printIndexingExpression(CE->getOperand(0), gep_type_begin(CPV),
640                               gep_type_end(CPV));
641       Out << "))";
642       return;
643     case Instruction::Select:
644       Out << '(';
645       printConstant(CE->getOperand(0));
646       Out << '?';
647       printConstant(CE->getOperand(1));
648       Out << ':';
649       printConstant(CE->getOperand(2));
650       Out << ')';
651       return;
652     case Instruction::Add:
653     case Instruction::Sub:
654     case Instruction::Mul:
655     case Instruction::SDiv:
656     case Instruction::UDiv:
657     case Instruction::FDiv:
658     case Instruction::URem:
659     case Instruction::SRem:
660     case Instruction::FRem:
661     case Instruction::And:
662     case Instruction::Or:
663     case Instruction::Xor:
664     case Instruction::SetEQ:
665     case Instruction::SetNE:
666     case Instruction::SetLT:
667     case Instruction::SetLE:
668     case Instruction::SetGT:
669     case Instruction::SetGE:
670     case Instruction::Shl:
671     case Instruction::LShr:
672     case Instruction::AShr:
673     {
674       Out << '(';
675       bool NeedsClosingParens = printConstExprCast(CE); 
676       printConstantWithCast(CE->getOperand(0), CE->getOpcode());
677       switch (CE->getOpcode()) {
678       case Instruction::Add: Out << " + "; break;
679       case Instruction::Sub: Out << " - "; break;
680       case Instruction::Mul: Out << " * "; break;
681       case Instruction::URem:
682       case Instruction::SRem: 
683       case Instruction::FRem: Out << " % "; break;
684       case Instruction::UDiv: 
685       case Instruction::SDiv: 
686       case Instruction::FDiv: Out << " / "; break;
687       case Instruction::And: Out << " & "; break;
688       case Instruction::Or:  Out << " | "; break;
689       case Instruction::Xor: Out << " ^ "; break;
690       case Instruction::SetEQ: Out << " == "; break;
691       case Instruction::SetNE: Out << " != "; break;
692       case Instruction::SetLT: Out << " < "; break;
693       case Instruction::SetLE: Out << " <= "; break;
694       case Instruction::SetGT: Out << " > "; break;
695       case Instruction::SetGE: Out << " >= "; break;
696       case Instruction::Shl: Out << " << "; break;
697       case Instruction::LShr:
698       case Instruction::AShr: Out << " >> "; break;
699       default: assert(0 && "Illegal opcode here!");
700       }
701       printConstantWithCast(CE->getOperand(1), CE->getOpcode());
702       if (NeedsClosingParens)
703         Out << "))";
704       Out << ')';
705       return;
706     }
707
708     default:
709       std::cerr << "CWriter Error: Unhandled constant expression: "
710                 << *CE << "\n";
711       abort();
712     }
713   } else if (isa<UndefValue>(CPV) && CPV->getType()->isFirstClassType()) {
714     Out << "((";
715     printType(Out, CPV->getType());
716     Out << ")/*UNDEF*/0)";
717     return;
718   }
719
720   switch (CPV->getType()->getTypeID()) {
721   case Type::BoolTyID:
722     Out << (cast<ConstantBool>(CPV)->getValue() ? '1' : '0');
723     break;
724   case Type::SByteTyID:
725   case Type::ShortTyID:
726     Out << cast<ConstantInt>(CPV)->getSExtValue();
727     break;
728   case Type::IntTyID:
729     if ((int)cast<ConstantInt>(CPV)->getSExtValue() == (int)0x80000000)
730       Out << "((int)0x80000000U)";   // Handle MININT specially to avoid warning
731     else
732       Out << cast<ConstantInt>(CPV)->getSExtValue();
733     break;
734
735   case Type::LongTyID:
736     if (cast<ConstantInt>(CPV)->isMinValue())
737       Out << "(/*INT64_MIN*/(-9223372036854775807LL)-1)";
738     else
739       Out << cast<ConstantInt>(CPV)->getSExtValue() << "ll";
740     break;
741
742   case Type::UByteTyID:
743   case Type::UShortTyID:
744     Out << cast<ConstantInt>(CPV)->getZExtValue();
745     break;
746   case Type::UIntTyID:
747     Out << cast<ConstantInt>(CPV)->getZExtValue() << 'u';
748     break;
749   case Type::ULongTyID:
750     Out << cast<ConstantInt>(CPV)->getZExtValue() << "ull";
751     break;
752
753   case Type::FloatTyID:
754   case Type::DoubleTyID: {
755     ConstantFP *FPC = cast<ConstantFP>(CPV);
756     std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
757     if (I != FPConstantMap.end()) {
758       // Because of FP precision problems we must load from a stack allocated
759       // value that holds the value in hex.
760       Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
761           << "*)&FPConstant" << I->second << ')';
762     } else {
763       if (IsNAN(FPC->getValue())) {
764         // The value is NaN
765
766         // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
767         // it's 0x7ff4.
768         const unsigned long QuietNaN = 0x7ff8UL;
769         //const unsigned long SignalNaN = 0x7ff4UL;
770
771         // We need to grab the first part of the FP #
772         char Buffer[100];
773
774         uint64_t ll = DoubleToBits(FPC->getValue());
775         sprintf(Buffer, "0x%llx", static_cast<long long>(ll));
776
777         std::string Num(&Buffer[0], &Buffer[6]);
778         unsigned long Val = strtoul(Num.c_str(), 0, 16);
779
780         if (FPC->getType() == Type::FloatTy)
781           Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
782               << Buffer << "\") /*nan*/ ";
783         else
784           Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
785               << Buffer << "\") /*nan*/ ";
786       } else if (IsInf(FPC->getValue())) {
787         // The value is Inf
788         if (FPC->getValue() < 0) Out << '-';
789         Out << "LLVM_INF" << (FPC->getType() == Type::FloatTy ? "F" : "")
790             << " /*inf*/ ";
791       } else {
792         std::string Num;
793 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
794         // Print out the constant as a floating point number.
795         char Buffer[100];
796         sprintf(Buffer, "%a", FPC->getValue());
797         Num = Buffer;
798 #else
799         Num = ftostr(FPC->getValue());
800 #endif
801         Out << Num;
802       }
803     }
804     break;
805   }
806
807   case Type::ArrayTyID:
808     if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
809       const ArrayType *AT = cast<ArrayType>(CPV->getType());
810       Out << '{';
811       if (AT->getNumElements()) {
812         Out << ' ';
813         Constant *CZ = Constant::getNullValue(AT->getElementType());
814         printConstant(CZ);
815         for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
816           Out << ", ";
817           printConstant(CZ);
818         }
819       }
820       Out << " }";
821     } else {
822       printConstantArray(cast<ConstantArray>(CPV));
823     }
824     break;
825
826   case Type::PackedTyID:
827     if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
828       const PackedType *AT = cast<PackedType>(CPV->getType());
829       Out << '{';
830       if (AT->getNumElements()) {
831         Out << ' ';
832         Constant *CZ = Constant::getNullValue(AT->getElementType());
833         printConstant(CZ);
834         for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
835           Out << ", ";
836           printConstant(CZ);
837         }
838       }
839       Out << " }";
840     } else {
841       printConstantPacked(cast<ConstantPacked>(CPV));
842     }
843     break;
844
845   case Type::StructTyID:
846     if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
847       const StructType *ST = cast<StructType>(CPV->getType());
848       Out << '{';
849       if (ST->getNumElements()) {
850         Out << ' ';
851         printConstant(Constant::getNullValue(ST->getElementType(0)));
852         for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
853           Out << ", ";
854           printConstant(Constant::getNullValue(ST->getElementType(i)));
855         }
856       }
857       Out << " }";
858     } else {
859       Out << '{';
860       if (CPV->getNumOperands()) {
861         Out << ' ';
862         printConstant(cast<Constant>(CPV->getOperand(0)));
863         for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
864           Out << ", ";
865           printConstant(cast<Constant>(CPV->getOperand(i)));
866         }
867       }
868       Out << " }";
869     }
870     break;
871
872   case Type::PointerTyID:
873     if (isa<ConstantPointerNull>(CPV)) {
874       Out << "((";
875       printType(Out, CPV->getType());
876       Out << ")/*NULL*/0)";
877       break;
878     } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
879       writeOperand(GV);
880       break;
881     }
882     // FALL THROUGH
883   default:
884     std::cerr << "Unknown constant type: " << *CPV << "\n";
885     abort();
886   }
887 }
888
889 // Some constant expressions need to be casted back to the original types
890 // because their operands were casted to the expected type. This function takes
891 // care of detecting that case and printing the cast for the ConstantExpr.
892 bool CWriter::printConstExprCast(const ConstantExpr* CE) {
893   bool NeedsExplicitCast = false;
894   const Type *Ty = CE->getOperand(0)->getType();
895   switch (CE->getOpcode()) {
896   case Instruction::LShr:
897   case Instruction::URem: 
898   case Instruction::UDiv: 
899     NeedsExplicitCast = Ty->isSigned(); break;
900   case Instruction::AShr:
901   case Instruction::SRem: 
902   case Instruction::SDiv: 
903     NeedsExplicitCast = Ty->isUnsigned(); break;
904   case Instruction::ZExt:
905   case Instruction::SExt:
906   case Instruction::Trunc:
907   case Instruction::FPTrunc:
908   case Instruction::FPExt:
909   case Instruction::UIToFP:
910   case Instruction::SIToFP:
911   case Instruction::FPToUI:
912   case Instruction::FPToSI:
913   case Instruction::PtrToInt:
914   case Instruction::IntToPtr:
915   case Instruction::BitCast:
916     Ty = CE->getType();
917     NeedsExplicitCast = true;
918     break;
919   default: break;
920   }
921   if (NeedsExplicitCast) {
922     Out << "((";
923     printType(Out, Ty);
924     Out << ")(";
925   }
926   return NeedsExplicitCast;
927 }
928
929 //  Print a constant assuming that it is the operand for a given Opcode. The
930 //  opcodes that care about sign need to cast their operands to the expected
931 //  type before the operation proceeds. This function does the casting.
932 void CWriter::printConstantWithCast(Constant* CPV, unsigned Opcode) {
933
934   // Extract the operand's type, we'll need it.
935   const Type* OpTy = CPV->getType();
936
937   // Indicate whether to do the cast or not.
938   bool shouldCast = false;
939
940   // Based on the Opcode for which this Constant is being written, determine
941   // the new type to which the operand should be casted by setting the value
942   // of OpTy. If we change OpTy, also set shouldCast to true so it gets
943   // casted below.
944   switch (Opcode) {
945     default:
946       // for most instructions, it doesn't matter
947       break; 
948     case Instruction::LShr:
949     case Instruction::UDiv:
950     case Instruction::URem:
951       // For UDiv/URem get correct type
952       if (OpTy->isSigned()) {
953         OpTy = OpTy->getUnsignedVersion();
954         shouldCast = true;
955       }
956       break;
957     case Instruction::AShr:
958     case Instruction::SDiv:
959     case Instruction::SRem:
960       // For SDiv/SRem get correct type
961       if (OpTy->isUnsigned()) {
962         OpTy = OpTy->getSignedVersion();
963         shouldCast = true;
964       }
965       break;
966   }
967
968   // Write out the casted constant if we should, otherwise just write the
969   // operand.
970   if (shouldCast) {
971     Out << "((";
972     printType(Out, OpTy);
973     Out << ")";
974     printConstant(CPV);
975     Out << ")";
976   } else 
977     writeOperand(CPV);
978
979 }
980
981 void CWriter::writeOperandInternal(Value *Operand) {
982   if (Instruction *I = dyn_cast<Instruction>(Operand))
983     if (isInlinableInst(*I) && !isDirectAlloca(I)) {
984       // Should we inline this instruction to build a tree?
985       Out << '(';
986       visit(*I);
987       Out << ')';
988       return;
989     }
990
991   Constant* CPV = dyn_cast<Constant>(Operand);
992   if (CPV && !isa<GlobalValue>(CPV)) {
993     printConstant(CPV);
994   } else {
995     Out << Mang->getValueName(Operand);
996   }
997 }
998
999 void CWriter::writeOperand(Value *Operand) {
1000   if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
1001     Out << "(&";  // Global variables are referenced as their addresses by llvm
1002
1003   writeOperandInternal(Operand);
1004
1005   if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
1006     Out << ')';
1007 }
1008
1009 // Some instructions need to have their result value casted back to the 
1010 // original types because their operands were casted to the expected type. 
1011 // This function takes care of detecting that case and printing the cast 
1012 // for the Instruction.
1013 bool CWriter::writeInstructionCast(const Instruction &I) {
1014   bool NeedsExplicitCast = false;
1015   const Type *Ty = I.getOperand(0)->getType();
1016   switch (I.getOpcode()) {
1017   case Instruction::LShr:
1018   case Instruction::URem: 
1019   case Instruction::UDiv: 
1020     NeedsExplicitCast = Ty->isSigned(); break;
1021   case Instruction::AShr:
1022   case Instruction::SRem: 
1023   case Instruction::SDiv: 
1024     NeedsExplicitCast = Ty->isUnsigned(); break;
1025   case Instruction::ZExt:
1026   case Instruction::SExt:
1027   case Instruction::Trunc:
1028   case Instruction::FPTrunc:
1029   case Instruction::FPExt:
1030   case Instruction::UIToFP:
1031   case Instruction::SIToFP:
1032   case Instruction::FPToUI:
1033   case Instruction::FPToSI:
1034   case Instruction::PtrToInt:
1035   case Instruction::IntToPtr:
1036   case Instruction::BitCast:
1037     Ty = I.getType();
1038     NeedsExplicitCast = true;
1039     break;
1040   default: break;
1041   }
1042   if (NeedsExplicitCast) {
1043     Out << "((";
1044     printType(Out, Ty);
1045     Out << ")(";
1046   }
1047   return NeedsExplicitCast;
1048 }
1049
1050 // Write the operand with a cast to another type based on the Opcode being used.
1051 // This will be used in cases where an instruction has specific type
1052 // requirements (usually signedness) for its operands. 
1053 void CWriter::writeOperandWithCast(Value* Operand, unsigned Opcode) {
1054
1055   // Extract the operand's type, we'll need it.
1056   const Type* OpTy = Operand->getType();
1057
1058   // Indicate whether to do the cast or not.
1059   bool shouldCast = false;
1060
1061   // Based on the Opcode for which this Operand is being written, determine
1062   // the new type to which the operand should be casted by setting the value
1063   // of OpTy. If we change OpTy, also set shouldCast to true.
1064   switch (Opcode) {
1065     default:
1066       // for most instructions, it doesn't matter
1067       break; 
1068     case Instruction::LShr:
1069     case Instruction::UDiv:
1070     case Instruction::URem:
1071       // For UDiv to have unsigned operands
1072       if (OpTy->isSigned()) {
1073         OpTy = OpTy->getUnsignedVersion();
1074         shouldCast = true;
1075       }
1076       break;
1077     case Instruction::AShr:
1078     case Instruction::SDiv:
1079     case Instruction::SRem:
1080       if (OpTy->isUnsigned()) {
1081         OpTy = OpTy->getSignedVersion();
1082         shouldCast = true;
1083       }
1084       break;
1085   }
1086
1087   // Write out the casted operand if we should, otherwise just write the
1088   // operand.
1089   if (shouldCast) {
1090     Out << "((";
1091     printType(Out, OpTy);
1092     Out << ")";
1093     writeOperand(Operand);
1094     Out << ")";
1095   } else 
1096     writeOperand(Operand);
1097
1098 }
1099
1100 // generateCompilerSpecificCode - This is where we add conditional compilation
1101 // directives to cater to specific compilers as need be.
1102 //
1103 static void generateCompilerSpecificCode(std::ostream& Out) {
1104   // Alloca is hard to get, and we don't want to include stdlib.h here.
1105   Out << "/* get a declaration for alloca */\n"
1106       << "#if defined(__CYGWIN__) || defined(__MINGW32__)\n"
1107       << "extern void *_alloca(unsigned long);\n"
1108       << "#define alloca(x) _alloca(x)\n"
1109       << "#elif defined(__APPLE__)\n"
1110       << "extern void *__builtin_alloca(unsigned long);\n"
1111       << "#define alloca(x) __builtin_alloca(x)\n"
1112       << "#elif defined(__sun__)\n"
1113       << "#if defined(__sparcv9)\n"
1114       << "extern void *__builtin_alloca(unsigned long);\n"
1115       << "#else\n"
1116       << "extern void *__builtin_alloca(unsigned int);\n"
1117       << "#endif\n"
1118       << "#define alloca(x) __builtin_alloca(x)\n"
1119       << "#elif defined(__FreeBSD__) || defined(__OpenBSD__)\n"
1120       << "#define alloca(x) __builtin_alloca(x)\n"
1121       << "#elif !defined(_MSC_VER)\n"
1122       << "#include <alloca.h>\n"
1123       << "#endif\n\n";
1124
1125   // We output GCC specific attributes to preserve 'linkonce'ness on globals.
1126   // If we aren't being compiled with GCC, just drop these attributes.
1127   Out << "#ifndef __GNUC__  /* Can only support \"linkonce\" vars with GCC */\n"
1128       << "#define __attribute__(X)\n"
1129       << "#endif\n\n";
1130
1131 #if 0
1132   // At some point, we should support "external weak" vs. "weak" linkages.
1133   // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
1134   Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1135       << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
1136       << "#elif defined(__GNUC__)\n"
1137       << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
1138       << "#else\n"
1139       << "#define __EXTERNAL_WEAK__\n"
1140       << "#endif\n\n";
1141 #endif
1142
1143   // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
1144   Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1145       << "#define __ATTRIBUTE_WEAK__\n"
1146       << "#elif defined(__GNUC__)\n"
1147       << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
1148       << "#else\n"
1149       << "#define __ATTRIBUTE_WEAK__\n"
1150       << "#endif\n\n";
1151
1152   // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
1153   // From the GCC documentation:
1154   //
1155   //   double __builtin_nan (const char *str)
1156   //
1157   // This is an implementation of the ISO C99 function nan.
1158   //
1159   // Since ISO C99 defines this function in terms of strtod, which we do
1160   // not implement, a description of the parsing is in order. The string is
1161   // parsed as by strtol; that is, the base is recognized by leading 0 or
1162   // 0x prefixes. The number parsed is placed in the significand such that
1163   // the least significant bit of the number is at the least significant
1164   // bit of the significand. The number is truncated to fit the significand
1165   // field provided. The significand is forced to be a quiet NaN.
1166   //
1167   // This function, if given a string literal, is evaluated early enough
1168   // that it is considered a compile-time constant.
1169   //
1170   //   float __builtin_nanf (const char *str)
1171   //
1172   // Similar to __builtin_nan, except the return type is float.
1173   //
1174   //   double __builtin_inf (void)
1175   //
1176   // Similar to __builtin_huge_val, except a warning is generated if the
1177   // target floating-point format does not support infinities. This
1178   // function is suitable for implementing the ISO C99 macro INFINITY.
1179   //
1180   //   float __builtin_inff (void)
1181   //
1182   // Similar to __builtin_inf, except the return type is float.
1183   Out << "#ifdef __GNUC__\n"
1184       << "#define LLVM_NAN(NanStr)   __builtin_nan(NanStr)   /* Double */\n"
1185       << "#define LLVM_NANF(NanStr)  __builtin_nanf(NanStr)  /* Float */\n"
1186       << "#define LLVM_NANS(NanStr)  __builtin_nans(NanStr)  /* Double */\n"
1187       << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
1188       << "#define LLVM_INF           __builtin_inf()         /* Double */\n"
1189       << "#define LLVM_INFF          __builtin_inff()        /* Float */\n"
1190       << "#define LLVM_PREFETCH(addr,rw,locality) "
1191                               "__builtin_prefetch(addr,rw,locality)\n"
1192       << "#define __ATTRIBUTE_CTOR__ __attribute__((constructor))\n"
1193       << "#define __ATTRIBUTE_DTOR__ __attribute__((destructor))\n"
1194       << "#define LLVM_ASM           __asm__\n"
1195       << "#else\n"
1196       << "#define LLVM_NAN(NanStr)   ((double)0.0)           /* Double */\n"
1197       << "#define LLVM_NANF(NanStr)  0.0F                    /* Float */\n"
1198       << "#define LLVM_NANS(NanStr)  ((double)0.0)           /* Double */\n"
1199       << "#define LLVM_NANSF(NanStr) 0.0F                    /* Float */\n"
1200       << "#define LLVM_INF           ((double)0.0)           /* Double */\n"
1201       << "#define LLVM_INFF          0.0F                    /* Float */\n"
1202       << "#define LLVM_PREFETCH(addr,rw,locality)            /* PREFETCH */\n"
1203       << "#define __ATTRIBUTE_CTOR__\n"
1204       << "#define __ATTRIBUTE_DTOR__\n"
1205       << "#define LLVM_ASM(X)\n"
1206       << "#endif\n\n";
1207
1208   // Output target-specific code that should be inserted into main.
1209   Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
1210   // On X86, set the FP control word to 64-bits of precision instead of 80 bits.
1211   Out << "#if defined(__GNUC__) && !defined(__llvm__)\n"
1212       << "#if defined(i386) || defined(__i386__) || defined(__i386) || "
1213       << "defined(__x86_64__)\n"
1214       << "#undef CODE_FOR_MAIN\n"
1215       << "#define CODE_FOR_MAIN() \\\n"
1216       << "  {short F;__asm__ (\"fnstcw %0\" : \"=m\" (*&F)); \\\n"
1217       << "  F=(F&~0x300)|0x200;__asm__(\"fldcw %0\"::\"m\"(*&F));}\n"
1218       << "#endif\n#endif\n";
1219
1220 }
1221
1222 /// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
1223 /// the StaticTors set.
1224 static void FindStaticTors(GlobalVariable *GV, std::set<Function*> &StaticTors){
1225   ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
1226   if (!InitList) return;
1227   
1228   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
1229     if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
1230       if (CS->getNumOperands() != 2) return;  // Not array of 2-element structs.
1231       
1232       if (CS->getOperand(1)->isNullValue())
1233         return;  // Found a null terminator, exit printing.
1234       Constant *FP = CS->getOperand(1);
1235       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
1236         if (CE->isCast())
1237           FP = CE->getOperand(0);
1238       if (Function *F = dyn_cast<Function>(FP))
1239         StaticTors.insert(F);
1240     }
1241 }
1242
1243 enum SpecialGlobalClass {
1244   NotSpecial = 0,
1245   GlobalCtors, GlobalDtors,
1246   NotPrinted
1247 };
1248
1249 /// getGlobalVariableClass - If this is a global that is specially recognized
1250 /// by LLVM, return a code that indicates how we should handle it.
1251 static SpecialGlobalClass getGlobalVariableClass(const GlobalVariable *GV) {
1252   // If this is a global ctors/dtors list, handle it now.
1253   if (GV->hasAppendingLinkage() && GV->use_empty()) {
1254     if (GV->getName() == "llvm.global_ctors")
1255       return GlobalCtors;
1256     else if (GV->getName() == "llvm.global_dtors")
1257       return GlobalDtors;
1258   }
1259   
1260   // Otherwise, it it is other metadata, don't print it.  This catches things
1261   // like debug information.
1262   if (GV->getSection() == "llvm.metadata")
1263     return NotPrinted;
1264   
1265   return NotSpecial;
1266 }
1267
1268
1269 bool CWriter::doInitialization(Module &M) {
1270   // Initialize
1271   TheModule = &M;
1272
1273   IL.AddPrototypes(M);
1274
1275   // Ensure that all structure types have names...
1276   Mang = new Mangler(M);
1277   Mang->markCharUnacceptable('.');
1278
1279   // Keep track of which functions are static ctors/dtors so they can have
1280   // an attribute added to their prototypes.
1281   std::set<Function*> StaticCtors, StaticDtors;
1282   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1283        I != E; ++I) {
1284     switch (getGlobalVariableClass(I)) {
1285     default: break;
1286     case GlobalCtors:
1287       FindStaticTors(I, StaticCtors);
1288       break;
1289     case GlobalDtors:
1290       FindStaticTors(I, StaticDtors);
1291       break;
1292     }
1293   }
1294   
1295   // get declaration for alloca
1296   Out << "/* Provide Declarations */\n";
1297   Out << "#include <stdarg.h>\n";      // Varargs support
1298   Out << "#include <setjmp.h>\n";      // Unwind support
1299   generateCompilerSpecificCode(Out);
1300
1301   // Provide a definition for `bool' if not compiling with a C++ compiler.
1302   Out << "\n"
1303       << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
1304
1305       << "\n\n/* Support for floating point constants */\n"
1306       << "typedef unsigned long long ConstantDoubleTy;\n"
1307       << "typedef unsigned int        ConstantFloatTy;\n"
1308
1309       << "\n\n/* Global Declarations */\n";
1310
1311   // First output all the declarations for the program, because C requires
1312   // Functions & globals to be declared before they are used.
1313   //
1314
1315   // Loop over the symbol table, emitting all named constants...
1316   printModuleTypes(M.getSymbolTable());
1317
1318   // Global variable declarations...
1319   if (!M.global_empty()) {
1320     Out << "\n/* External Global Variable Declarations */\n";
1321     for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1322          I != E; ++I) {
1323       if (I->hasExternalLinkage()) {
1324         Out << "extern ";
1325         printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
1326         Out << ";\n";
1327       } else if (I->hasDLLImportLinkage()) {
1328         Out << "__declspec(dllimport) ";
1329         printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
1330         Out << ";\n";        
1331       }      
1332     }
1333   }
1334
1335   // Function declarations
1336   Out << "\n/* Function Declarations */\n";
1337   Out << "double fmod(double, double);\n";   // Support for FP rem
1338   Out << "float fmodf(float, float);\n";
1339   
1340   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1341     // Don't print declarations for intrinsic functions.
1342     if (!I->getIntrinsicID() && I->getName() != "setjmp" && 
1343         I->getName() != "longjmp" && I->getName() != "_setjmp") {
1344       printFunctionSignature(I, true);
1345       if (I->hasWeakLinkage() || I->hasLinkOnceLinkage()) 
1346         Out << " __ATTRIBUTE_WEAK__";
1347       if (StaticCtors.count(I))
1348         Out << " __ATTRIBUTE_CTOR__";
1349       if (StaticDtors.count(I))
1350         Out << " __ATTRIBUTE_DTOR__";
1351       
1352       if (I->hasName() && I->getName()[0] == 1)
1353         Out << " LLVM_ASM(\"" << I->getName().c_str()+1 << "\")";
1354           
1355       Out << ";\n";
1356     }
1357   }
1358
1359   // Output the global variable declarations
1360   if (!M.global_empty()) {
1361     Out << "\n\n/* Global Variable Declarations */\n";
1362     for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1363          I != E; ++I)
1364       if (!I->isExternal()) {
1365         // Ignore special globals, such as debug info.
1366         if (getGlobalVariableClass(I))
1367           continue;
1368         
1369         if (I->hasInternalLinkage())
1370           Out << "static ";
1371         else
1372           Out << "extern ";
1373         printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
1374
1375         if (I->hasLinkOnceLinkage())
1376           Out << " __attribute__((common))";
1377         else if (I->hasWeakLinkage())
1378           Out << " __ATTRIBUTE_WEAK__";
1379         Out << ";\n";
1380       }
1381   }
1382
1383   // Output the global variable definitions and contents...
1384   if (!M.global_empty()) {
1385     Out << "\n\n/* Global Variable Definitions and Initialization */\n";
1386     for (Module::global_iterator I = M.global_begin(), E = M.global_end(); 
1387          I != E; ++I)
1388       if (!I->isExternal()) {
1389         // Ignore special globals, such as debug info.
1390         if (getGlobalVariableClass(I))
1391           continue;
1392         
1393         if (I->hasInternalLinkage())
1394           Out << "static ";
1395         else if (I->hasDLLImportLinkage())
1396           Out << "__declspec(dllimport) ";
1397         else if (I->hasDLLExportLinkage())
1398           Out << "__declspec(dllexport) ";
1399             
1400         printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
1401         if (I->hasLinkOnceLinkage())
1402           Out << " __attribute__((common))";
1403         else if (I->hasWeakLinkage())
1404           Out << " __ATTRIBUTE_WEAK__";
1405
1406         // If the initializer is not null, emit the initializer.  If it is null,
1407         // we try to avoid emitting large amounts of zeros.  The problem with
1408         // this, however, occurs when the variable has weak linkage.  In this
1409         // case, the assembler will complain about the variable being both weak
1410         // and common, so we disable this optimization.
1411         if (!I->getInitializer()->isNullValue()) {
1412           Out << " = " ;
1413           writeOperand(I->getInitializer());
1414         } else if (I->hasWeakLinkage()) {
1415           // We have to specify an initializer, but it doesn't have to be
1416           // complete.  If the value is an aggregate, print out { 0 }, and let
1417           // the compiler figure out the rest of the zeros.
1418           Out << " = " ;
1419           if (isa<StructType>(I->getInitializer()->getType()) ||
1420               isa<ArrayType>(I->getInitializer()->getType()) ||
1421               isa<PackedType>(I->getInitializer()->getType())) {
1422             Out << "{ 0 }";
1423           } else {
1424             // Just print it out normally.
1425             writeOperand(I->getInitializer());
1426           }
1427         }
1428         Out << ";\n";
1429       }
1430   }
1431
1432   if (!M.empty())
1433     Out << "\n\n/* Function Bodies */\n";
1434   return false;
1435 }
1436
1437
1438 /// Output all floating point constants that cannot be printed accurately...
1439 void CWriter::printFloatingPointConstants(Function &F) {
1440   // Scan the module for floating point constants.  If any FP constant is used
1441   // in the function, we want to redirect it here so that we do not depend on
1442   // the precision of the printed form, unless the printed form preserves
1443   // precision.
1444   //
1445   static unsigned FPCounter = 0;
1446   for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
1447        I != E; ++I)
1448     if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
1449       if (!isFPCSafeToPrint(FPC) && // Do not put in FPConstantMap if safe.
1450           !FPConstantMap.count(FPC)) {
1451         double Val = FPC->getValue();
1452
1453         FPConstantMap[FPC] = FPCounter;  // Number the FP constants
1454
1455         if (FPC->getType() == Type::DoubleTy) {
1456           Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
1457               << " = 0x" << std::hex << DoubleToBits(Val) << std::dec
1458               << "ULL;    /* " << Val << " */\n";
1459         } else if (FPC->getType() == Type::FloatTy) {
1460           Out << "static const ConstantFloatTy FPConstant" << FPCounter++
1461               << " = 0x" << std::hex << FloatToBits(Val) << std::dec
1462               << "U;    /* " << Val << " */\n";
1463         } else
1464           assert(0 && "Unknown float type!");
1465       }
1466
1467   Out << '\n';
1468 }
1469
1470
1471 /// printSymbolTable - Run through symbol table looking for type names.  If a
1472 /// type name is found, emit its declaration...
1473 ///
1474 void CWriter::printModuleTypes(const SymbolTable &ST) {
1475   // We are only interested in the type plane of the symbol table.
1476   SymbolTable::type_const_iterator I   = ST.type_begin();
1477   SymbolTable::type_const_iterator End = ST.type_end();
1478
1479   // If there are no type names, exit early.
1480   if (I == End) return;
1481
1482   // Print out forward declarations for structure types before anything else!
1483   Out << "/* Structure forward decls */\n";
1484   for (; I != End; ++I)
1485     if (const Type *STy = dyn_cast<StructType>(I->second)) {
1486       std::string Name = "struct l_" + Mang->makeNameProper(I->first);
1487       Out << Name << ";\n";
1488       TypeNames.insert(std::make_pair(STy, Name));
1489     }
1490
1491   Out << '\n';
1492
1493   // Now we can print out typedefs...
1494   Out << "/* Typedefs */\n";
1495   for (I = ST.type_begin(); I != End; ++I) {
1496     const Type *Ty = cast<Type>(I->second);
1497     std::string Name = "l_" + Mang->makeNameProper(I->first);
1498     Out << "typedef ";
1499     printType(Out, Ty, Name);
1500     Out << ";\n";
1501   }
1502
1503   Out << '\n';
1504
1505   // Keep track of which structures have been printed so far...
1506   std::set<const StructType *> StructPrinted;
1507
1508   // Loop over all structures then push them into the stack so they are
1509   // printed in the correct order.
1510   //
1511   Out << "/* Structure contents */\n";
1512   for (I = ST.type_begin(); I != End; ++I)
1513     if (const StructType *STy = dyn_cast<StructType>(I->second))
1514       // Only print out used types!
1515       printContainedStructs(STy, StructPrinted);
1516 }
1517
1518 // Push the struct onto the stack and recursively push all structs
1519 // this one depends on.
1520 //
1521 // TODO:  Make this work properly with packed types
1522 //
1523 void CWriter::printContainedStructs(const Type *Ty,
1524                                     std::set<const StructType*> &StructPrinted){
1525   // Don't walk through pointers.
1526   if (isa<PointerType>(Ty) || Ty->isPrimitiveType()) return;
1527   
1528   // Print all contained types first.
1529   for (Type::subtype_iterator I = Ty->subtype_begin(),
1530        E = Ty->subtype_end(); I != E; ++I)
1531     printContainedStructs(*I, StructPrinted);
1532   
1533   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1534     // Check to see if we have already printed this struct.
1535     if (StructPrinted.insert(STy).second) {
1536       // Print structure type out.
1537       std::string Name = TypeNames[STy];
1538       printType(Out, STy, Name, true);
1539       Out << ";\n\n";
1540     }
1541   }
1542 }
1543
1544 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
1545   /// isCStructReturn - Should this function actually return a struct by-value?
1546   bool isCStructReturn = F->getCallingConv() == CallingConv::CSRet;
1547   
1548   if (F->hasInternalLinkage()) Out << "static ";
1549   if (F->hasDLLImportLinkage()) Out << "__declspec(dllimport) ";
1550   if (F->hasDLLExportLinkage()) Out << "__declspec(dllexport) ";  
1551   switch (F->getCallingConv()) {
1552    case CallingConv::X86_StdCall:
1553     Out << "__stdcall ";
1554     break;
1555    case CallingConv::X86_FastCall:
1556     Out << "__fastcall ";
1557     break;
1558   }
1559   
1560   // Loop over the arguments, printing them...
1561   const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
1562
1563   std::stringstream FunctionInnards;
1564
1565   // Print out the name...
1566   FunctionInnards << Mang->getValueName(F) << '(';
1567
1568   bool PrintedArg = false;
1569   if (!F->isExternal()) {
1570     if (!F->arg_empty()) {
1571       Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1572       
1573       // If this is a struct-return function, don't print the hidden
1574       // struct-return argument.
1575       if (isCStructReturn) {
1576         assert(I != E && "Invalid struct return function!");
1577         ++I;
1578       }
1579       
1580       std::string ArgName;
1581       for (; I != E; ++I) {
1582         if (PrintedArg) FunctionInnards << ", ";
1583         if (I->hasName() || !Prototype)
1584           ArgName = Mang->getValueName(I);
1585         else
1586           ArgName = "";
1587         printType(FunctionInnards, I->getType(), ArgName);
1588         PrintedArg = true;
1589       }
1590     }
1591   } else {
1592     // Loop over the arguments, printing them.
1593     FunctionType::param_iterator I = FT->param_begin(), E = FT->param_end();
1594     
1595     // If this is a struct-return function, don't print the hidden
1596     // struct-return argument.
1597     if (isCStructReturn) {
1598       assert(I != E && "Invalid struct return function!");
1599       ++I;
1600     }
1601     
1602     for (; I != E; ++I) {
1603       if (PrintedArg) FunctionInnards << ", ";
1604       printType(FunctionInnards, *I);
1605       PrintedArg = true;
1606     }
1607   }
1608
1609   // Finish printing arguments... if this is a vararg function, print the ...,
1610   // unless there are no known types, in which case, we just emit ().
1611   //
1612   if (FT->isVarArg() && PrintedArg) {
1613     if (PrintedArg) FunctionInnards << ", ";
1614     FunctionInnards << "...";  // Output varargs portion of signature!
1615   } else if (!FT->isVarArg() && !PrintedArg) {
1616     FunctionInnards << "void"; // ret() -> ret(void) in C.
1617   }
1618   FunctionInnards << ')';
1619   
1620   // Get the return tpe for the function.
1621   const Type *RetTy;
1622   if (!isCStructReturn)
1623     RetTy = F->getReturnType();
1624   else {
1625     // If this is a struct-return function, print the struct-return type.
1626     RetTy = cast<PointerType>(FT->getParamType(0))->getElementType();
1627   }
1628     
1629   // Print out the return type and the signature built above.
1630   printType(Out, RetTy, FunctionInnards.str());
1631 }
1632
1633 void CWriter::printFunction(Function &F) {
1634   printFunctionSignature(&F, false);
1635   Out << " {\n";
1636   
1637   // If this is a struct return function, handle the result with magic.
1638   if (F.getCallingConv() == CallingConv::CSRet) {
1639     const Type *StructTy =
1640       cast<PointerType>(F.arg_begin()->getType())->getElementType();
1641     Out << "  ";
1642     printType(Out, StructTy, "StructReturn");
1643     Out << ";  /* Struct return temporary */\n";
1644
1645     Out << "  ";
1646     printType(Out, F.arg_begin()->getType(), Mang->getValueName(F.arg_begin()));
1647     Out << " = &StructReturn;\n";
1648   }
1649
1650   bool PrintedVar = false;
1651   
1652   // print local variable information for the function
1653   for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I)
1654     if (const AllocaInst *AI = isDirectAlloca(&*I)) {
1655       Out << "  ";
1656       printType(Out, AI->getAllocatedType(), Mang->getValueName(AI));
1657       Out << ";    /* Address-exposed local */\n";
1658       PrintedVar = true;
1659     } else if (I->getType() != Type::VoidTy && !isInlinableInst(*I)) {
1660       Out << "  ";
1661       printType(Out, I->getType(), Mang->getValueName(&*I));
1662       Out << ";\n";
1663
1664       if (isa<PHINode>(*I)) {  // Print out PHI node temporaries as well...
1665         Out << "  ";
1666         printType(Out, I->getType(),
1667                   Mang->getValueName(&*I)+"__PHI_TEMPORARY");
1668         Out << ";\n";
1669       }
1670       PrintedVar = true;
1671     }
1672
1673   if (PrintedVar)
1674     Out << '\n';
1675
1676   if (F.hasExternalLinkage() && F.getName() == "main")
1677     Out << "  CODE_FOR_MAIN();\n";
1678
1679   // print the basic blocks
1680   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1681     if (Loop *L = LI->getLoopFor(BB)) {
1682       if (L->getHeader() == BB && L->getParentLoop() == 0)
1683         printLoop(L);
1684     } else {
1685       printBasicBlock(BB);
1686     }
1687   }
1688
1689   Out << "}\n\n";
1690 }
1691
1692 void CWriter::printLoop(Loop *L) {
1693   Out << "  do {     /* Syntactic loop '" << L->getHeader()->getName()
1694       << "' to make GCC happy */\n";
1695   for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
1696     BasicBlock *BB = L->getBlocks()[i];
1697     Loop *BBLoop = LI->getLoopFor(BB);
1698     if (BBLoop == L)
1699       printBasicBlock(BB);
1700     else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
1701       printLoop(BBLoop);
1702   }
1703   Out << "  } while (1); /* end of syntactic loop '"
1704       << L->getHeader()->getName() << "' */\n";
1705 }
1706
1707 void CWriter::printBasicBlock(BasicBlock *BB) {
1708
1709   // Don't print the label for the basic block if there are no uses, or if
1710   // the only terminator use is the predecessor basic block's terminator.
1711   // We have to scan the use list because PHI nodes use basic blocks too but
1712   // do not require a label to be generated.
1713   //
1714   bool NeedsLabel = false;
1715   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1716     if (isGotoCodeNecessary(*PI, BB)) {
1717       NeedsLabel = true;
1718       break;
1719     }
1720
1721   if (NeedsLabel) Out << Mang->getValueName(BB) << ":\n";
1722
1723   // Output all of the instructions in the basic block...
1724   for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
1725        ++II) {
1726     if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
1727       if (II->getType() != Type::VoidTy)
1728         outputLValue(II);
1729       else
1730         Out << "  ";
1731       visit(*II);
1732       Out << ";\n";
1733     }
1734   }
1735
1736   // Don't emit prefix or suffix for the terminator...
1737   visit(*BB->getTerminator());
1738 }
1739
1740
1741 // Specific Instruction type classes... note that all of the casts are
1742 // necessary because we use the instruction classes as opaque types...
1743 //
1744 void CWriter::visitReturnInst(ReturnInst &I) {
1745   // If this is a struct return function, return the temporary struct.
1746   if (I.getParent()->getParent()->getCallingConv() == CallingConv::CSRet) {
1747     Out << "  return StructReturn;\n";
1748     return;
1749   }
1750   
1751   // Don't output a void return if this is the last basic block in the function
1752   if (I.getNumOperands() == 0 &&
1753       &*--I.getParent()->getParent()->end() == I.getParent() &&
1754       !I.getParent()->size() == 1) {
1755     return;
1756   }
1757
1758   Out << "  return";
1759   if (I.getNumOperands()) {
1760     Out << ' ';
1761     writeOperand(I.getOperand(0));
1762   }
1763   Out << ";\n";
1764 }
1765
1766 void CWriter::visitSwitchInst(SwitchInst &SI) {
1767
1768   Out << "  switch (";
1769   writeOperand(SI.getOperand(0));
1770   Out << ") {\n  default:\n";
1771   printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
1772   printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
1773   Out << ";\n";
1774   for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
1775     Out << "  case ";
1776     writeOperand(SI.getOperand(i));
1777     Out << ":\n";
1778     BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
1779     printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
1780     printBranchToBlock(SI.getParent(), Succ, 2);
1781     if (Function::iterator(Succ) == next(Function::iterator(SI.getParent())))
1782       Out << "    break;\n";
1783   }
1784   Out << "  }\n";
1785 }
1786
1787 void CWriter::visitUnreachableInst(UnreachableInst &I) {
1788   Out << "  /*UNREACHABLE*/;\n";
1789 }
1790
1791 bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
1792   /// FIXME: This should be reenabled, but loop reordering safe!!
1793   return true;
1794
1795   if (next(Function::iterator(From)) != Function::iterator(To))
1796     return true;  // Not the direct successor, we need a goto.
1797
1798   //isa<SwitchInst>(From->getTerminator())
1799
1800   if (LI->getLoopFor(From) != LI->getLoopFor(To))
1801     return true;
1802   return false;
1803 }
1804
1805 void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
1806                                           BasicBlock *Successor,
1807                                           unsigned Indent) {
1808   for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
1809     PHINode *PN = cast<PHINode>(I);
1810     // Now we have to do the printing.
1811     Value *IV = PN->getIncomingValueForBlock(CurBlock);
1812     if (!isa<UndefValue>(IV)) {
1813       Out << std::string(Indent, ' ');
1814       Out << "  " << Mang->getValueName(I) << "__PHI_TEMPORARY = ";
1815       writeOperand(IV);
1816       Out << ";   /* for PHI node */\n";
1817     }
1818   }
1819 }
1820
1821 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
1822                                  unsigned Indent) {
1823   if (isGotoCodeNecessary(CurBB, Succ)) {
1824     Out << std::string(Indent, ' ') << "  goto ";
1825     writeOperand(Succ);
1826     Out << ";\n";
1827   }
1828 }
1829
1830 // Branch instruction printing - Avoid printing out a branch to a basic block
1831 // that immediately succeeds the current one.
1832 //
1833 void CWriter::visitBranchInst(BranchInst &I) {
1834
1835   if (I.isConditional()) {
1836     if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
1837       Out << "  if (";
1838       writeOperand(I.getCondition());
1839       Out << ") {\n";
1840
1841       printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
1842       printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
1843
1844       if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
1845         Out << "  } else {\n";
1846         printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
1847         printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
1848       }
1849     } else {
1850       // First goto not necessary, assume second one is...
1851       Out << "  if (!";
1852       writeOperand(I.getCondition());
1853       Out << ") {\n";
1854
1855       printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
1856       printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
1857     }
1858
1859     Out << "  }\n";
1860   } else {
1861     printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
1862     printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
1863   }
1864   Out << "\n";
1865 }
1866
1867 // PHI nodes get copied into temporary values at the end of predecessor basic
1868 // blocks.  We now need to copy these temporary values into the REAL value for
1869 // the PHI.
1870 void CWriter::visitPHINode(PHINode &I) {
1871   writeOperand(&I);
1872   Out << "__PHI_TEMPORARY";
1873 }
1874
1875
1876 void CWriter::visitBinaryOperator(Instruction &I) {
1877   // binary instructions, shift instructions, setCond instructions.
1878   assert(!isa<PointerType>(I.getType()));
1879
1880   // We must cast the results of binary operations which might be promoted.
1881   bool needsCast = false;
1882   if ((I.getType() == Type::UByteTy) || (I.getType() == Type::SByteTy)
1883       || (I.getType() == Type::UShortTy) || (I.getType() == Type::ShortTy)
1884       || (I.getType() == Type::FloatTy)) {
1885     needsCast = true;
1886     Out << "((";
1887     printType(Out, I.getType());
1888     Out << ")(";
1889   }
1890
1891   // If this is a negation operation, print it out as such.  For FP, we don't
1892   // want to print "-0.0 - X".
1893   if (BinaryOperator::isNeg(&I)) {
1894     Out << "-(";
1895     writeOperand(BinaryOperator::getNegArgument(cast<BinaryOperator>(&I)));
1896     Out << ")";
1897   } else if (I.getOpcode() == Instruction::FRem) {
1898     // Output a call to fmod/fmodf instead of emitting a%b
1899     if (I.getType() == Type::FloatTy)
1900       Out << "fmodf(";
1901     else
1902       Out << "fmod(";
1903     writeOperand(I.getOperand(0));
1904     Out << ", ";
1905     writeOperand(I.getOperand(1));
1906     Out << ")";
1907   } else {
1908
1909     // Write out the cast of the instruction's value back to the proper type
1910     // if necessary.
1911     bool NeedsClosingParens = writeInstructionCast(I);
1912
1913     // Certain instructions require the operand to be forced to a specific type
1914     // so we use writeOperandWithCast here instead of writeOperand. Similarly
1915     // below for operand 1
1916     writeOperandWithCast(I.getOperand(0), I.getOpcode());
1917
1918     switch (I.getOpcode()) {
1919     case Instruction::Add: Out << " + "; break;
1920     case Instruction::Sub: Out << " - "; break;
1921     case Instruction::Mul: Out << '*'; break;
1922     case Instruction::URem:
1923     case Instruction::SRem:
1924     case Instruction::FRem: Out << '%'; break;
1925     case Instruction::UDiv:
1926     case Instruction::SDiv: 
1927     case Instruction::FDiv: Out << '/'; break;
1928     case Instruction::And: Out << " & "; break;
1929     case Instruction::Or: Out << " | "; break;
1930     case Instruction::Xor: Out << " ^ "; break;
1931     case Instruction::SetEQ: Out << " == "; break;
1932     case Instruction::SetNE: Out << " != "; break;
1933     case Instruction::SetLE: Out << " <= "; break;
1934     case Instruction::SetGE: Out << " >= "; break;
1935     case Instruction::SetLT: Out << " < "; break;
1936     case Instruction::SetGT: Out << " > "; break;
1937     case Instruction::Shl : Out << " << "; break;
1938     case Instruction::LShr:
1939     case Instruction::AShr: Out << " >> "; break;
1940     default: std::cerr << "Invalid operator type!" << I; abort();
1941     }
1942
1943     writeOperandWithCast(I.getOperand(1), I.getOpcode());
1944     if (NeedsClosingParens)
1945       Out << "))";
1946   }
1947
1948   if (needsCast) {
1949     Out << "))";
1950   }
1951 }
1952
1953 void CWriter::visitCastInst(CastInst &I) {
1954   const Type *DstTy = I.getType();
1955   const Type *SrcTy = I.getOperand(0)->getType();
1956   Out << '(';
1957   printCast(I.getOpcode(), SrcTy, DstTy);
1958   if (I.getOpcode() == Instruction::SExt && SrcTy == Type::BoolTy) {
1959     // Make sure we really get a sext from bool by subtracing the bool from 0
1960     Out << "0-";
1961   }
1962   writeOperand(I.getOperand(0));
1963   if (I.getOpcode() == Instruction::Trunc && DstTy == Type::BoolTy) {
1964     // Make sure we really get a trunc to bool by anding the operand with 1 
1965     Out << "&1u";
1966   }
1967   Out << ')';
1968 }
1969
1970 void CWriter::visitSelectInst(SelectInst &I) {
1971   Out << "((";
1972   writeOperand(I.getCondition());
1973   Out << ") ? (";
1974   writeOperand(I.getTrueValue());
1975   Out << ") : (";
1976   writeOperand(I.getFalseValue());
1977   Out << "))";
1978 }
1979
1980
1981 void CWriter::lowerIntrinsics(Function &F) {
1982   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1983     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1984       if (CallInst *CI = dyn_cast<CallInst>(I++))
1985         if (Function *F = CI->getCalledFunction())
1986           switch (F->getIntrinsicID()) {
1987           case Intrinsic::not_intrinsic:
1988           case Intrinsic::vastart:
1989           case Intrinsic::vacopy:
1990           case Intrinsic::vaend:
1991           case Intrinsic::returnaddress:
1992           case Intrinsic::frameaddress:
1993           case Intrinsic::setjmp:
1994           case Intrinsic::longjmp:
1995           case Intrinsic::prefetch:
1996           case Intrinsic::dbg_stoppoint:
1997           case Intrinsic::powi_f32:
1998           case Intrinsic::powi_f64:
1999             // We directly implement these intrinsics
2000             break;
2001           default:
2002             // If this is an intrinsic that directly corresponds to a GCC
2003             // builtin, we handle it.
2004             const char *BuiltinName = "";
2005 #define GET_GCC_BUILTIN_NAME
2006 #include "llvm/Intrinsics.gen"
2007 #undef GET_GCC_BUILTIN_NAME
2008             // If we handle it, don't lower it.
2009             if (BuiltinName[0]) break;
2010             
2011             // All other intrinsic calls we must lower.
2012             Instruction *Before = 0;
2013             if (CI != &BB->front())
2014               Before = prior(BasicBlock::iterator(CI));
2015
2016             IL.LowerIntrinsicCall(CI);
2017             if (Before) {        // Move iterator to instruction after call
2018               I = Before; ++I;
2019             } else {
2020               I = BB->begin();
2021             }
2022             break;
2023           }
2024 }
2025
2026
2027
2028 void CWriter::visitCallInst(CallInst &I) {
2029   bool WroteCallee = false;
2030
2031   // Handle intrinsic function calls first...
2032   if (Function *F = I.getCalledFunction())
2033     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
2034       switch (ID) {
2035       default: {
2036         // If this is an intrinsic that directly corresponds to a GCC
2037         // builtin, we emit it here.
2038         const char *BuiltinName = "";
2039 #define GET_GCC_BUILTIN_NAME
2040 #include "llvm/Intrinsics.gen"
2041 #undef GET_GCC_BUILTIN_NAME
2042         assert(BuiltinName[0] && "Unknown LLVM intrinsic!");
2043
2044         Out << BuiltinName;
2045         WroteCallee = true;
2046         break;
2047       }
2048       case Intrinsic::vastart:
2049         Out << "0; ";
2050
2051         Out << "va_start(*(va_list*)";
2052         writeOperand(I.getOperand(1));
2053         Out << ", ";
2054         // Output the last argument to the enclosing function...
2055         if (I.getParent()->getParent()->arg_empty()) {
2056           std::cerr << "The C backend does not currently support zero "
2057                     << "argument varargs functions, such as '"
2058                     << I.getParent()->getParent()->getName() << "'!\n";
2059           abort();
2060         }
2061         writeOperand(--I.getParent()->getParent()->arg_end());
2062         Out << ')';
2063         return;
2064       case Intrinsic::vaend:
2065         if (!isa<ConstantPointerNull>(I.getOperand(1))) {
2066           Out << "0; va_end(*(va_list*)";
2067           writeOperand(I.getOperand(1));
2068           Out << ')';
2069         } else {
2070           Out << "va_end(*(va_list*)0)";
2071         }
2072         return;
2073       case Intrinsic::vacopy:
2074         Out << "0; ";
2075         Out << "va_copy(*(va_list*)";
2076         writeOperand(I.getOperand(1));
2077         Out << ", *(va_list*)";
2078         writeOperand(I.getOperand(2));
2079         Out << ')';
2080         return;
2081       case Intrinsic::returnaddress:
2082         Out << "__builtin_return_address(";
2083         writeOperand(I.getOperand(1));
2084         Out << ')';
2085         return;
2086       case Intrinsic::frameaddress:
2087         Out << "__builtin_frame_address(";
2088         writeOperand(I.getOperand(1));
2089         Out << ')';
2090         return;
2091       case Intrinsic::powi_f32:
2092       case Intrinsic::powi_f64:
2093         Out << "__builtin_powi(";
2094         writeOperand(I.getOperand(1));
2095         Out << ", ";
2096         writeOperand(I.getOperand(2));
2097         Out << ')';
2098         return;
2099       case Intrinsic::setjmp:
2100 #if defined(HAVE__SETJMP) && defined(HAVE__LONGJMP)
2101         Out << "_";  // Use _setjmp on systems that support it!
2102 #endif
2103         Out << "setjmp(*(jmp_buf*)";
2104         writeOperand(I.getOperand(1));
2105         Out << ')';
2106         return;
2107       case Intrinsic::longjmp:
2108 #if defined(HAVE__SETJMP) && defined(HAVE__LONGJMP)
2109         Out << "_";  // Use _longjmp on systems that support it!
2110 #endif
2111         Out << "longjmp(*(jmp_buf*)";
2112         writeOperand(I.getOperand(1));
2113         Out << ", ";
2114         writeOperand(I.getOperand(2));
2115         Out << ')';
2116         return;
2117       case Intrinsic::prefetch:
2118         Out << "LLVM_PREFETCH((const void *)";
2119         writeOperand(I.getOperand(1));
2120         Out << ", ";
2121         writeOperand(I.getOperand(2));
2122         Out << ", ";
2123         writeOperand(I.getOperand(3));
2124         Out << ")";
2125         return;
2126       case Intrinsic::dbg_stoppoint: {
2127         // If we use writeOperand directly we get a "u" suffix which is rejected
2128         // by gcc.
2129         DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
2130
2131         Out << "\n#line "
2132             << SPI.getLine()
2133             << " \"" << SPI.getDirectory()
2134             << SPI.getFileName() << "\"\n";
2135         return;
2136       }
2137       }
2138     }
2139
2140   Value *Callee = I.getCalledValue();
2141
2142   // If this is a call to a struct-return function, assign to the first
2143   // parameter instead of passing it to the call.
2144   bool isStructRet = I.getCallingConv() == CallingConv::CSRet;
2145   if (isStructRet) {
2146     Out << "*(";
2147     writeOperand(I.getOperand(1));
2148     Out << ") = ";
2149   }
2150   
2151   if (I.isTailCall()) Out << " /*tail*/ ";
2152
2153   const PointerType  *PTy   = cast<PointerType>(Callee->getType());
2154   const FunctionType *FTy   = cast<FunctionType>(PTy->getElementType());
2155   
2156   if (!WroteCallee) {
2157     // If this is an indirect call to a struct return function, we need to cast
2158     // the pointer.
2159     bool NeedsCast = isStructRet && !isa<Function>(Callee);
2160
2161     // GCC is a real PITA.  It does not permit codegening casts of functions to
2162     // function pointers if they are in a call (it generates a trap instruction
2163     // instead!).  We work around this by inserting a cast to void* in between
2164     // the function and the function pointer cast.  Unfortunately, we can't just
2165     // form the constant expression here, because the folder will immediately
2166     // nuke it.
2167     //
2168     // Note finally, that this is completely unsafe.  ANSI C does not guarantee
2169     // that void* and function pointers have the same size. :( To deal with this
2170     // in the common case, we handle casts where the number of arguments passed
2171     // match exactly.
2172     //
2173     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee))
2174       if (CE->isCast())
2175         if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) {
2176           NeedsCast = true;
2177           Callee = RF;
2178         }
2179   
2180     if (NeedsCast) {
2181       // Ok, just cast the pointer type.
2182       Out << "((";
2183       if (!isStructRet)
2184         printType(Out, I.getCalledValue()->getType());
2185       else
2186         printStructReturnPointerFunctionType(Out, 
2187                              cast<PointerType>(I.getCalledValue()->getType()));
2188       Out << ")(void*)";
2189     }
2190     writeOperand(Callee);
2191     if (NeedsCast) Out << ')';
2192   }
2193
2194   Out << '(';
2195
2196   unsigned NumDeclaredParams = FTy->getNumParams();
2197
2198   CallSite::arg_iterator AI = I.op_begin()+1, AE = I.op_end();
2199   unsigned ArgNo = 0;
2200   if (isStructRet) {   // Skip struct return argument.
2201     ++AI;
2202     ++ArgNo;
2203   }
2204       
2205   bool PrintedArg = false;
2206   for (; AI != AE; ++AI, ++ArgNo) {
2207     if (PrintedArg) Out << ", ";
2208     if (ArgNo < NumDeclaredParams &&
2209         (*AI)->getType() != FTy->getParamType(ArgNo)) {
2210       Out << '(';
2211       printType(Out, FTy->getParamType(ArgNo));
2212       Out << ')';
2213     }
2214     writeOperand(*AI);
2215     PrintedArg = true;
2216   }
2217   Out << ')';
2218 }
2219
2220 void CWriter::visitMallocInst(MallocInst &I) {
2221   assert(0 && "lowerallocations pass didn't work!");
2222 }
2223
2224 void CWriter::visitAllocaInst(AllocaInst &I) {
2225   Out << '(';
2226   printType(Out, I.getType());
2227   Out << ") alloca(sizeof(";
2228   printType(Out, I.getType()->getElementType());
2229   Out << ')';
2230   if (I.isArrayAllocation()) {
2231     Out << " * " ;
2232     writeOperand(I.getOperand(0));
2233   }
2234   Out << ')';
2235 }
2236
2237 void CWriter::visitFreeInst(FreeInst &I) {
2238   assert(0 && "lowerallocations pass didn't work!");
2239 }
2240
2241 void CWriter::printIndexingExpression(Value *Ptr, gep_type_iterator I,
2242                                       gep_type_iterator E) {
2243   bool HasImplicitAddress = false;
2244   // If accessing a global value with no indexing, avoid *(&GV) syndrome
2245   if (isa<GlobalValue>(Ptr)) {
2246     HasImplicitAddress = true;
2247   } else if (isDirectAlloca(Ptr)) {
2248     HasImplicitAddress = true;
2249   }
2250
2251   if (I == E) {
2252     if (!HasImplicitAddress)
2253       Out << '*';  // Implicit zero first argument: '*x' is equivalent to 'x[0]'
2254
2255     writeOperandInternal(Ptr);
2256     return;
2257   }
2258
2259   const Constant *CI = dyn_cast<Constant>(I.getOperand());
2260   if (HasImplicitAddress && (!CI || !CI->isNullValue()))
2261     Out << "(&";
2262
2263   writeOperandInternal(Ptr);
2264
2265   if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
2266     Out << ')';
2267     HasImplicitAddress = false;  // HIA is only true if we haven't addressed yet
2268   }
2269
2270   assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
2271          "Can only have implicit address with direct accessing");
2272
2273   if (HasImplicitAddress) {
2274     ++I;
2275   } else if (CI && CI->isNullValue()) {
2276     gep_type_iterator TmpI = I; ++TmpI;
2277
2278     // Print out the -> operator if possible...
2279     if (TmpI != E && isa<StructType>(*TmpI)) {
2280       Out << (HasImplicitAddress ? "." : "->");
2281       Out << "field" << cast<ConstantInt>(TmpI.getOperand())->getZExtValue();
2282       I = ++TmpI;
2283     }
2284   }
2285
2286   for (; I != E; ++I)
2287     if (isa<StructType>(*I)) {
2288       Out << ".field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
2289     } else {
2290       Out << '[';
2291       writeOperand(I.getOperand());
2292       Out << ']';
2293     }
2294 }
2295
2296 void CWriter::visitLoadInst(LoadInst &I) {
2297   Out << '*';
2298   if (I.isVolatile()) {
2299     Out << "((";
2300     printType(Out, I.getType(), "volatile*");
2301     Out << ")";
2302   }
2303
2304   writeOperand(I.getOperand(0));
2305
2306   if (I.isVolatile())
2307     Out << ')';
2308 }
2309
2310 void CWriter::visitStoreInst(StoreInst &I) {
2311   Out << '*';
2312   if (I.isVolatile()) {
2313     Out << "((";
2314     printType(Out, I.getOperand(0)->getType(), " volatile*");
2315     Out << ")";
2316   }
2317   writeOperand(I.getPointerOperand());
2318   if (I.isVolatile()) Out << ')';
2319   Out << " = ";
2320   writeOperand(I.getOperand(0));
2321 }
2322
2323 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
2324   Out << '&';
2325   printIndexingExpression(I.getPointerOperand(), gep_type_begin(I),
2326                           gep_type_end(I));
2327 }
2328
2329 void CWriter::visitVAArgInst(VAArgInst &I) {
2330   Out << "va_arg(*(va_list*)";
2331   writeOperand(I.getOperand(0));
2332   Out << ", ";
2333   printType(Out, I.getType());
2334   Out << ");\n ";
2335 }
2336
2337 //===----------------------------------------------------------------------===//
2338 //                       External Interface declaration
2339 //===----------------------------------------------------------------------===//
2340
2341 bool CTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
2342                                               std::ostream &o,
2343                                               CodeGenFileType FileType,
2344                                               bool Fast) {
2345   if (FileType != TargetMachine::AssemblyFile) return true;
2346
2347   PM.add(createLowerGCPass());
2348   PM.add(createLowerAllocationsPass(true));
2349   PM.add(createLowerInvokePass());
2350   PM.add(createCFGSimplificationPass());   // clean up after lower invoke.
2351   PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
2352   PM.add(new CWriter(o));
2353   return false;
2354 }