implement insertelement.
[oota-llvm.git] / lib / Target / CBackend / CBackend.cpp
1 //===-- CBackend.cpp - Library for converting LLVM code to C --------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // 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/ParamAttrsList.h"
22 #include "llvm/Pass.h"
23 #include "llvm/PassManager.h"
24 #include "llvm/TypeSymbolTable.h"
25 #include "llvm/Intrinsics.h"
26 #include "llvm/IntrinsicInst.h"
27 #include "llvm/InlineAsm.h"
28 #include "llvm/Analysis/ConstantsScanner.h"
29 #include "llvm/Analysis/FindUsedTypes.h"
30 #include "llvm/Analysis/LoopInfo.h"
31 #include "llvm/CodeGen/Passes.h"
32 #include "llvm/CodeGen/IntrinsicLowering.h"
33 #include "llvm/Transforms/Scalar.h"
34 #include "llvm/Target/TargetMachineRegistry.h"
35 #include "llvm/Target/TargetAsmInfo.h"
36 #include "llvm/Target/TargetData.h"
37 #include "llvm/Support/CallSite.h"
38 #include "llvm/Support/CFG.h"
39 #include "llvm/Support/GetElementPtrTypeIterator.h"
40 #include "llvm/Support/InstVisitor.h"
41 #include "llvm/Support/Mangler.h"
42 #include "llvm/Support/MathExtras.h"
43 #include "llvm/ADT/StringExtras.h"
44 #include "llvm/ADT/STLExtras.h"
45 #include "llvm/Support/MathExtras.h"
46 #include "llvm/Config/config.h"
47 #include <algorithm>
48 #include <sstream>
49 using namespace llvm;
50
51 namespace {
52   // Register the target.
53   RegisterTarget<CTargetMachine> X("c", "  C backend");
54
55   /// CBackendNameAllUsedStructsAndMergeFunctions - This pass inserts names for
56   /// any unnamed structure types that are used by the program, and merges
57   /// external functions with the same name.
58   ///
59   class CBackendNameAllUsedStructsAndMergeFunctions : public ModulePass {
60   public:
61     static char ID;
62     CBackendNameAllUsedStructsAndMergeFunctions() 
63       : ModulePass((intptr_t)&ID) {}
64     void getAnalysisUsage(AnalysisUsage &AU) const {
65       AU.addRequired<FindUsedTypes>();
66     }
67
68     virtual const char *getPassName() const {
69       return "C backend type canonicalizer";
70     }
71
72     virtual bool runOnModule(Module &M);
73   };
74
75   char CBackendNameAllUsedStructsAndMergeFunctions::ID = 0;
76
77   /// CWriter - This class is the main chunk of code that converts an LLVM
78   /// module to a C translation unit.
79   class CWriter : public FunctionPass, public InstVisitor<CWriter> {
80     std::ostream &Out;
81     IntrinsicLowering *IL;
82     Mangler *Mang;
83     LoopInfo *LI;
84     const Module *TheModule;
85     const TargetAsmInfo* TAsm;
86     const TargetData* TD;
87     std::map<const Type *, std::string> TypeNames;
88     std::map<const ConstantFP *, unsigned> FPConstantMap;
89     std::set<Function*> intrinsicPrototypesAlreadyGenerated;
90     std::set<const Value*> ByValParams;
91
92   public:
93     static char ID;
94     CWriter(std::ostream &o) 
95       : FunctionPass((intptr_t)&ID), Out(o), IL(0), Mang(0), LI(0), 
96         TheModule(0), TAsm(0), TD(0) {}
97
98     virtual const char *getPassName() const { return "C backend"; }
99
100     void getAnalysisUsage(AnalysisUsage &AU) const {
101       AU.addRequired<LoopInfo>();
102       AU.setPreservesAll();
103     }
104
105     virtual bool doInitialization(Module &M);
106
107     bool runOnFunction(Function &F) {
108       LI = &getAnalysis<LoopInfo>();
109
110       // Get rid of intrinsics we can't handle.
111       lowerIntrinsics(F);
112
113       // Output all floating point constants that cannot be printed accurately.
114       printFloatingPointConstants(F);
115
116       printFunction(F);
117       return false;
118     }
119
120     virtual bool doFinalization(Module &M) {
121       // Free memory...
122       delete Mang;
123       FPConstantMap.clear();
124       TypeNames.clear();
125       intrinsicPrototypesAlreadyGenerated.clear();
126       ByValParams.clear();
127       return false;
128     }
129
130     std::ostream &printType(std::ostream &Out, const Type *Ty, 
131                             bool isSigned = false,
132                             const std::string &VariableName = "",
133                             bool IgnoreName = false,
134                             const ParamAttrsList *PAL = 0);
135     std::ostream &printSimpleType(std::ostream &Out, const Type *Ty, 
136                                   bool isSigned, 
137                                   const std::string &NameSoFar = "");
138
139     void printStructReturnPointerFunctionType(std::ostream &Out,
140                                               const ParamAttrsList *PAL,
141                                               const PointerType *Ty);
142     
143     void writeOperand(Value *Operand);
144     void writeOperandRaw(Value *Operand);
145     void writeOperandInternal(Value *Operand);
146     void writeOperandWithCast(Value* Operand, unsigned Opcode);
147     void writeOperandWithCast(Value* Operand, const ICmpInst &I);
148     bool writeInstructionCast(const Instruction &I);
149
150     void writeMemoryAccess(Value *Operand, const Type *OperandType,
151                            bool IsVolatile, unsigned Alignment);
152
153   private :
154     std::string InterpretASMConstraint(InlineAsm::ConstraintInfo& c);
155
156     void lowerIntrinsics(Function &F);
157
158     void printModule(Module *M);
159     void printModuleTypes(const TypeSymbolTable &ST);
160     void printContainedStructs(const Type *Ty, std::set<const StructType *> &);
161     void printFloatingPointConstants(Function &F);
162     void printFunctionSignature(const Function *F, bool Prototype);
163
164     void printFunction(Function &);
165     void printBasicBlock(BasicBlock *BB);
166     void printLoop(Loop *L);
167
168     void printCast(unsigned opcode, const Type *SrcTy, const Type *DstTy);
169     void printConstant(Constant *CPV);
170     void printConstantWithCast(Constant *CPV, unsigned Opcode);
171     bool printConstExprCast(const ConstantExpr *CE);
172     void printConstantArray(ConstantArray *CPA);
173     void printConstantVector(ConstantVector *CP);
174
175     // isInlinableInst - Attempt to inline instructions into their uses to build
176     // trees as much as possible.  To do this, we have to consistently decide
177     // what is acceptable to inline, so that variable declarations don't get
178     // printed and an extra copy of the expr is not emitted.
179     //
180     static bool isInlinableInst(const Instruction &I) {
181       // Always inline cmp instructions, even if they are shared by multiple
182       // expressions.  GCC generates horrible code if we don't.
183       if (isa<CmpInst>(I)) 
184         return true;
185
186       // Must be an expression, must be used exactly once.  If it is dead, we
187       // emit it inline where it would go.
188       if (I.getType() == Type::VoidTy || !I.hasOneUse() ||
189           isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
190           isa<LoadInst>(I) || isa<VAArgInst>(I) || isa<InsertElementInst>(I))
191         // Don't inline a load across a store or other bad things!
192         return false;
193
194       // Must not be used in inline asm
195       if (I.hasOneUse() && isInlineAsm(*I.use_back())) return false;
196
197       // Only inline instruction it if it's use is in the same BB as the inst.
198       return I.getParent() == cast<Instruction>(I.use_back())->getParent();
199     }
200
201     // isDirectAlloca - Define fixed sized allocas in the entry block as direct
202     // variables which are accessed with the & operator.  This causes GCC to
203     // generate significantly better code than to emit alloca calls directly.
204     //
205     static const AllocaInst *isDirectAlloca(const Value *V) {
206       const AllocaInst *AI = dyn_cast<AllocaInst>(V);
207       if (!AI) return false;
208       if (AI->isArrayAllocation())
209         return 0;   // FIXME: we can also inline fixed size array allocas!
210       if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
211         return 0;
212       return AI;
213     }
214     
215     // isInlineAsm - Check if the instruction is a call to an inline asm chunk
216     static bool isInlineAsm(const Instruction& I) {
217       if (isa<CallInst>(&I) && isa<InlineAsm>(I.getOperand(0)))
218         return true;
219       return false;
220     }
221     
222     // Instruction visitation functions
223     friend class InstVisitor<CWriter>;
224
225     void visitReturnInst(ReturnInst &I);
226     void visitBranchInst(BranchInst &I);
227     void visitSwitchInst(SwitchInst &I);
228     void visitInvokeInst(InvokeInst &I) {
229       assert(0 && "Lowerinvoke pass didn't work!");
230     }
231
232     void visitUnwindInst(UnwindInst &I) {
233       assert(0 && "Lowerinvoke pass didn't work!");
234     }
235     void visitUnreachableInst(UnreachableInst &I);
236
237     void visitPHINode(PHINode &I);
238     void visitBinaryOperator(Instruction &I);
239     void visitICmpInst(ICmpInst &I);
240     void visitFCmpInst(FCmpInst &I);
241
242     void visitCastInst (CastInst &I);
243     void visitSelectInst(SelectInst &I);
244     void visitCallInst (CallInst &I);
245     void visitInlineAsm(CallInst &I);
246
247     void visitMallocInst(MallocInst &I);
248     void visitAllocaInst(AllocaInst &I);
249     void visitFreeInst  (FreeInst   &I);
250     void visitLoadInst  (LoadInst   &I);
251     void visitStoreInst (StoreInst  &I);
252     void visitGetElementPtrInst(GetElementPtrInst &I);
253     void visitVAArgInst (VAArgInst &I);
254     
255     void visitInsertElementInst(InsertElementInst &I);
256
257     void visitInstruction(Instruction &I) {
258       cerr << "C Writer does not know about " << I;
259       abort();
260     }
261
262     void outputLValue(Instruction *I) {
263       Out << "  " << GetValueName(I) << " = ";
264     }
265
266     bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
267     void printPHICopiesForSuccessor(BasicBlock *CurBlock,
268                                     BasicBlock *Successor, unsigned Indent);
269     void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
270                             unsigned Indent);
271     void printIndexingExpression(Value *Ptr, gep_type_iterator I,
272                                  gep_type_iterator E);
273
274     std::string GetValueName(const Value *Operand);
275   };
276 }
277
278 char CWriter::ID = 0;
279
280 /// This method inserts names for any unnamed structure types that are used by
281 /// the program, and removes names from structure types that are not used by the
282 /// program.
283 ///
284 bool CBackendNameAllUsedStructsAndMergeFunctions::runOnModule(Module &M) {
285   // Get a set of types that are used by the program...
286   std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
287
288   // Loop over the module symbol table, removing types from UT that are
289   // already named, and removing names for types that are not used.
290   //
291   TypeSymbolTable &TST = M.getTypeSymbolTable();
292   for (TypeSymbolTable::iterator TI = TST.begin(), TE = TST.end();
293        TI != TE; ) {
294     TypeSymbolTable::iterator I = TI++;
295     
296     // If this isn't a struct type, remove it from our set of types to name.
297     // This simplifies emission later.
298     if (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second)) {
299       TST.remove(I);
300     } else {
301       // If this is not used, remove it from the symbol table.
302       std::set<const Type *>::iterator UTI = UT.find(I->second);
303       if (UTI == UT.end())
304         TST.remove(I);
305       else
306         UT.erase(UTI);    // Only keep one name for this type.
307     }
308   }
309
310   // UT now contains types that are not named.  Loop over it, naming
311   // structure types.
312   //
313   bool Changed = false;
314   unsigned RenameCounter = 0;
315   for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
316        I != E; ++I)
317     if (const StructType *ST = dyn_cast<StructType>(*I)) {
318       while (M.addTypeName("unnamed"+utostr(RenameCounter), ST))
319         ++RenameCounter;
320       Changed = true;
321     }
322       
323       
324   // Loop over all external functions and globals.  If we have two with
325   // identical names, merge them.
326   // FIXME: This code should disappear when we don't allow values with the same
327   // names when they have different types!
328   std::map<std::string, GlobalValue*> ExtSymbols;
329   for (Module::iterator I = M.begin(), E = M.end(); I != E;) {
330     Function *GV = I++;
331     if (GV->isDeclaration() && GV->hasName()) {
332       std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
333         = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
334       if (!X.second) {
335         // Found a conflict, replace this global with the previous one.
336         GlobalValue *OldGV = X.first->second;
337         GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
338         GV->eraseFromParent();
339         Changed = true;
340       }
341     }
342   }
343   // Do the same for globals.
344   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
345        I != E;) {
346     GlobalVariable *GV = I++;
347     if (GV->isDeclaration() && GV->hasName()) {
348       std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
349         = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
350       if (!X.second) {
351         // Found a conflict, replace this global with the previous one.
352         GlobalValue *OldGV = X.first->second;
353         GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
354         GV->eraseFromParent();
355         Changed = true;
356       }
357     }
358   }
359   
360   return Changed;
361 }
362
363 /// printStructReturnPointerFunctionType - This is like printType for a struct
364 /// return type, except, instead of printing the type as void (*)(Struct*, ...)
365 /// print it as "Struct (*)(...)", for struct return functions.
366 void CWriter::printStructReturnPointerFunctionType(std::ostream &Out,
367                                                    const ParamAttrsList *PAL,
368                                                    const PointerType *TheTy) {
369   const FunctionType *FTy = cast<FunctionType>(TheTy->getElementType());
370   std::stringstream FunctionInnards;
371   FunctionInnards << " (*) (";
372   bool PrintedType = false;
373
374   FunctionType::param_iterator I = FTy->param_begin(), E = FTy->param_end();
375   const Type *RetTy = cast<PointerType>(I->get())->getElementType();
376   unsigned Idx = 1;
377   for (++I, ++Idx; I != E; ++I, ++Idx) {
378     if (PrintedType)
379       FunctionInnards << ", ";
380     const Type *ArgTy = *I;
381     if (PAL && PAL->paramHasAttr(Idx, ParamAttr::ByVal)) {
382       assert(isa<PointerType>(ArgTy));
383       ArgTy = cast<PointerType>(ArgTy)->getElementType();
384     }
385     printType(FunctionInnards, ArgTy,
386         /*isSigned=*/PAL && PAL->paramHasAttr(Idx, ParamAttr::SExt), "");
387     PrintedType = true;
388   }
389   if (FTy->isVarArg()) {
390     if (PrintedType)
391       FunctionInnards << ", ...";
392   } else if (!PrintedType) {
393     FunctionInnards << "void";
394   }
395   FunctionInnards << ')';
396   std::string tstr = FunctionInnards.str();
397   printType(Out, RetTy, 
398       /*isSigned=*/PAL && PAL->paramHasAttr(0, ParamAttr::SExt), tstr);
399 }
400
401 std::ostream &
402 CWriter::printSimpleType(std::ostream &Out, const Type *Ty, bool isSigned,
403                          const std::string &NameSoFar) {
404   assert((Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) && 
405          "Invalid type for printSimpleType");
406   switch (Ty->getTypeID()) {
407   case Type::VoidTyID:   return Out << "void " << NameSoFar;
408   case Type::IntegerTyID: {
409     unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
410     if (NumBits == 1) 
411       return Out << "bool " << NameSoFar;
412     else if (NumBits <= 8)
413       return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
414     else if (NumBits <= 16)
415       return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
416     else if (NumBits <= 32)
417       return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
418     else { 
419       assert(NumBits <= 64 && "Bit widths > 64 not implemented yet");
420       return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
421     }
422   }
423   case Type::FloatTyID:  return Out << "float "   << NameSoFar;
424   case Type::DoubleTyID: return Out << "double "  << NameSoFar;
425   // Lacking emulation of FP80 on PPC, etc., we assume whichever of these is
426   // present matches host 'long double'.
427   case Type::X86_FP80TyID:
428   case Type::PPC_FP128TyID:
429   case Type::FP128TyID:  return Out << "long double " << NameSoFar;
430       
431   case Type::VectorTyID: {
432     const VectorType *VTy = cast<VectorType>(Ty);
433     return printSimpleType(Out, VTy->getElementType(), isSigned,
434                      " __attribute__((vector_size(" +
435                      utostr(TD->getABITypeSize(VTy)) + " ))) " + NameSoFar);
436   }
437     
438   default:
439     cerr << "Unknown primitive type: " << *Ty << "\n";
440     abort();
441   }
442 }
443
444 // Pass the Type* and the variable name and this prints out the variable
445 // declaration.
446 //
447 std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
448                                  bool isSigned, const std::string &NameSoFar,
449                                  bool IgnoreName, const ParamAttrsList* PAL) {
450   if (Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) {
451     printSimpleType(Out, Ty, isSigned, NameSoFar);
452     return Out;
453   }
454
455   // Check to see if the type is named.
456   if (!IgnoreName || isa<OpaqueType>(Ty)) {
457     std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
458     if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
459   }
460
461   switch (Ty->getTypeID()) {
462   case Type::FunctionTyID: {
463     const FunctionType *FTy = cast<FunctionType>(Ty);
464     std::stringstream FunctionInnards;
465     FunctionInnards << " (" << NameSoFar << ") (";
466     unsigned Idx = 1;
467     for (FunctionType::param_iterator I = FTy->param_begin(),
468            E = FTy->param_end(); I != E; ++I) {
469       const Type *ArgTy = *I;
470       if (PAL && PAL->paramHasAttr(Idx, ParamAttr::ByVal)) {
471         assert(isa<PointerType>(ArgTy));
472         ArgTy = cast<PointerType>(ArgTy)->getElementType();
473       }
474       if (I != FTy->param_begin())
475         FunctionInnards << ", ";
476       printType(FunctionInnards, ArgTy,
477         /*isSigned=*/PAL && PAL->paramHasAttr(Idx, ParamAttr::SExt), "");
478       ++Idx;
479     }
480     if (FTy->isVarArg()) {
481       if (FTy->getNumParams())
482         FunctionInnards << ", ...";
483     } else if (!FTy->getNumParams()) {
484       FunctionInnards << "void";
485     }
486     FunctionInnards << ')';
487     std::string tstr = FunctionInnards.str();
488     printType(Out, FTy->getReturnType(), 
489       /*isSigned=*/PAL && PAL->paramHasAttr(0, ParamAttr::SExt), tstr);
490     return Out;
491   }
492   case Type::StructTyID: {
493     const StructType *STy = cast<StructType>(Ty);
494     Out << NameSoFar + " {\n";
495     unsigned Idx = 0;
496     for (StructType::element_iterator I = STy->element_begin(),
497            E = STy->element_end(); I != E; ++I) {
498       Out << "  ";
499       printType(Out, *I, false, "field" + utostr(Idx++));
500       Out << ";\n";
501     }
502     Out << '}';
503     if (STy->isPacked())
504       Out << " __attribute__ ((packed))";
505     return Out;
506   }
507
508   case Type::PointerTyID: {
509     const PointerType *PTy = cast<PointerType>(Ty);
510     std::string ptrName = "*" + NameSoFar;
511
512     if (isa<ArrayType>(PTy->getElementType()) ||
513         isa<VectorType>(PTy->getElementType()))
514       ptrName = "(" + ptrName + ")";
515
516     if (PAL)
517       // Must be a function ptr cast!
518       return printType(Out, PTy->getElementType(), false, ptrName, true, PAL);
519     return printType(Out, PTy->getElementType(), false, ptrName);
520   }
521
522   case Type::ArrayTyID: {
523     const ArrayType *ATy = cast<ArrayType>(Ty);
524     unsigned NumElements = ATy->getNumElements();
525     if (NumElements == 0) NumElements = 1;
526     return printType(Out, ATy->getElementType(), false,
527                      NameSoFar + "[" + utostr(NumElements) + "]");
528   }
529
530   case Type::OpaqueTyID: {
531     static int Count = 0;
532     std::string TyName = "struct opaque_" + itostr(Count++);
533     assert(TypeNames.find(Ty) == TypeNames.end());
534     TypeNames[Ty] = TyName;
535     return Out << TyName << ' ' << NameSoFar;
536   }
537   default:
538     assert(0 && "Unhandled case in getTypeProps!");
539     abort();
540   }
541
542   return Out;
543 }
544
545 void CWriter::printConstantArray(ConstantArray *CPA) {
546
547   // As a special case, print the array as a string if it is an array of
548   // ubytes or an array of sbytes with positive values.
549   //
550   const Type *ETy = CPA->getType()->getElementType();
551   bool isString = (ETy == Type::Int8Ty || ETy == Type::Int8Ty);
552
553   // Make sure the last character is a null char, as automatically added by C
554   if (isString && (CPA->getNumOperands() == 0 ||
555                    !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
556     isString = false;
557
558   if (isString) {
559     Out << '\"';
560     // Keep track of whether the last number was a hexadecimal escape
561     bool LastWasHex = false;
562
563     // Do not include the last character, which we know is null
564     for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
565       unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getZExtValue();
566
567       // Print it out literally if it is a printable character.  The only thing
568       // to be careful about is when the last letter output was a hex escape
569       // code, in which case we have to be careful not to print out hex digits
570       // explicitly (the C compiler thinks it is a continuation of the previous
571       // character, sheesh...)
572       //
573       if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
574         LastWasHex = false;
575         if (C == '"' || C == '\\')
576           Out << "\\" << C;
577         else
578           Out << C;
579       } else {
580         LastWasHex = false;
581         switch (C) {
582         case '\n': Out << "\\n"; break;
583         case '\t': Out << "\\t"; break;
584         case '\r': Out << "\\r"; break;
585         case '\v': Out << "\\v"; break;
586         case '\a': Out << "\\a"; break;
587         case '\"': Out << "\\\""; break;
588         case '\'': Out << "\\\'"; break;
589         default:
590           Out << "\\x";
591           Out << (char)(( C/16  < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
592           Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
593           LastWasHex = true;
594           break;
595         }
596       }
597     }
598     Out << '\"';
599   } else {
600     Out << '{';
601     if (CPA->getNumOperands()) {
602       Out << ' ';
603       printConstant(cast<Constant>(CPA->getOperand(0)));
604       for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
605         Out << ", ";
606         printConstant(cast<Constant>(CPA->getOperand(i)));
607       }
608     }
609     Out << " }";
610   }
611 }
612
613 void CWriter::printConstantVector(ConstantVector *CP) {
614   Out << '{';
615   if (CP->getNumOperands()) {
616     Out << ' ';
617     printConstant(cast<Constant>(CP->getOperand(0)));
618     for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
619       Out << ", ";
620       printConstant(cast<Constant>(CP->getOperand(i)));
621     }
622   }
623   Out << " }";
624 }
625
626 // isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
627 // textually as a double (rather than as a reference to a stack-allocated
628 // variable). We decide this by converting CFP to a string and back into a
629 // double, and then checking whether the conversion results in a bit-equal
630 // double to the original value of CFP. This depends on us and the target C
631 // compiler agreeing on the conversion process (which is pretty likely since we
632 // only deal in IEEE FP).
633 //
634 static bool isFPCSafeToPrint(const ConstantFP *CFP) {
635   // Do long doubles in hex for now.
636   if (CFP->getType()!=Type::FloatTy && CFP->getType()!=Type::DoubleTy)
637     return false;
638   APFloat APF = APFloat(CFP->getValueAPF());  // copy
639   if (CFP->getType()==Type::FloatTy)
640     APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven);
641 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
642   char Buffer[100];
643   sprintf(Buffer, "%a", APF.convertToDouble());
644   if (!strncmp(Buffer, "0x", 2) ||
645       !strncmp(Buffer, "-0x", 3) ||
646       !strncmp(Buffer, "+0x", 3))
647     return APF.bitwiseIsEqual(APFloat(atof(Buffer)));
648   return false;
649 #else
650   std::string StrVal = ftostr(APF);
651
652   while (StrVal[0] == ' ')
653     StrVal.erase(StrVal.begin());
654
655   // Check to make sure that the stringized number is not some string like "Inf"
656   // or NaN.  Check that the string matches the "[-+]?[0-9]" regex.
657   if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
658       ((StrVal[0] == '-' || StrVal[0] == '+') &&
659        (StrVal[1] >= '0' && StrVal[1] <= '9')))
660     // Reparse stringized version!
661     return APF.bitwiseIsEqual(APFloat(atof(StrVal.c_str())));
662   return false;
663 #endif
664 }
665
666 /// Print out the casting for a cast operation. This does the double casting
667 /// necessary for conversion to the destination type, if necessary. 
668 /// @brief Print a cast
669 void CWriter::printCast(unsigned opc, const Type *SrcTy, const Type *DstTy) {
670   // Print the destination type cast
671   switch (opc) {
672     case Instruction::UIToFP:
673     case Instruction::SIToFP:
674     case Instruction::IntToPtr:
675     case Instruction::Trunc:
676     case Instruction::BitCast:
677     case Instruction::FPExt:
678     case Instruction::FPTrunc: // For these the DstTy sign doesn't matter
679       Out << '(';
680       printType(Out, DstTy);
681       Out << ')';
682       break;
683     case Instruction::ZExt:
684     case Instruction::PtrToInt:
685     case Instruction::FPToUI: // For these, make sure we get an unsigned dest
686       Out << '(';
687       printSimpleType(Out, DstTy, false);
688       Out << ')';
689       break;
690     case Instruction::SExt: 
691     case Instruction::FPToSI: // For these, make sure we get a signed dest
692       Out << '(';
693       printSimpleType(Out, DstTy, true);
694       Out << ')';
695       break;
696     default:
697       assert(0 && "Invalid cast opcode");
698   }
699
700   // Print the source type cast
701   switch (opc) {
702     case Instruction::UIToFP:
703     case Instruction::ZExt:
704       Out << '(';
705       printSimpleType(Out, SrcTy, false);
706       Out << ')';
707       break;
708     case Instruction::SIToFP:
709     case Instruction::SExt:
710       Out << '(';
711       printSimpleType(Out, SrcTy, true); 
712       Out << ')';
713       break;
714     case Instruction::IntToPtr:
715     case Instruction::PtrToInt:
716       // Avoid "cast to pointer from integer of different size" warnings
717       Out << "(unsigned long)";
718       break;
719     case Instruction::Trunc:
720     case Instruction::BitCast:
721     case Instruction::FPExt:
722     case Instruction::FPTrunc:
723     case Instruction::FPToSI:
724     case Instruction::FPToUI:
725       break; // These don't need a source cast.
726     default:
727       assert(0 && "Invalid cast opcode");
728       break;
729   }
730 }
731
732 // printConstant - The LLVM Constant to C Constant converter.
733 void CWriter::printConstant(Constant *CPV) {
734   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
735     switch (CE->getOpcode()) {
736     case Instruction::Trunc:
737     case Instruction::ZExt:
738     case Instruction::SExt:
739     case Instruction::FPTrunc:
740     case Instruction::FPExt:
741     case Instruction::UIToFP:
742     case Instruction::SIToFP:
743     case Instruction::FPToUI:
744     case Instruction::FPToSI:
745     case Instruction::PtrToInt:
746     case Instruction::IntToPtr:
747     case Instruction::BitCast:
748       Out << "(";
749       printCast(CE->getOpcode(), CE->getOperand(0)->getType(), CE->getType());
750       if (CE->getOpcode() == Instruction::SExt &&
751           CE->getOperand(0)->getType() == Type::Int1Ty) {
752         // Make sure we really sext from bool here by subtracting from 0
753         Out << "0-";
754       }
755       printConstant(CE->getOperand(0));
756       if (CE->getType() == Type::Int1Ty &&
757           (CE->getOpcode() == Instruction::Trunc ||
758            CE->getOpcode() == Instruction::FPToUI ||
759            CE->getOpcode() == Instruction::FPToSI ||
760            CE->getOpcode() == Instruction::PtrToInt)) {
761         // Make sure we really truncate to bool here by anding with 1
762         Out << "&1u";
763       }
764       Out << ')';
765       return;
766
767     case Instruction::GetElementPtr:
768       Out << "(&(";
769       printIndexingExpression(CE->getOperand(0), gep_type_begin(CPV),
770                               gep_type_end(CPV));
771       Out << "))";
772       return;
773     case Instruction::Select:
774       Out << '(';
775       printConstant(CE->getOperand(0));
776       Out << '?';
777       printConstant(CE->getOperand(1));
778       Out << ':';
779       printConstant(CE->getOperand(2));
780       Out << ')';
781       return;
782     case Instruction::Add:
783     case Instruction::Sub:
784     case Instruction::Mul:
785     case Instruction::SDiv:
786     case Instruction::UDiv:
787     case Instruction::FDiv:
788     case Instruction::URem:
789     case Instruction::SRem:
790     case Instruction::FRem:
791     case Instruction::And:
792     case Instruction::Or:
793     case Instruction::Xor:
794     case Instruction::ICmp:
795     case Instruction::Shl:
796     case Instruction::LShr:
797     case Instruction::AShr:
798     {
799       Out << '(';
800       bool NeedsClosingParens = printConstExprCast(CE); 
801       printConstantWithCast(CE->getOperand(0), CE->getOpcode());
802       switch (CE->getOpcode()) {
803       case Instruction::Add: Out << " + "; break;
804       case Instruction::Sub: Out << " - "; break;
805       case Instruction::Mul: Out << " * "; break;
806       case Instruction::URem:
807       case Instruction::SRem: 
808       case Instruction::FRem: Out << " % "; break;
809       case Instruction::UDiv: 
810       case Instruction::SDiv: 
811       case Instruction::FDiv: Out << " / "; break;
812       case Instruction::And: Out << " & "; break;
813       case Instruction::Or:  Out << " | "; break;
814       case Instruction::Xor: Out << " ^ "; break;
815       case Instruction::Shl: Out << " << "; break;
816       case Instruction::LShr:
817       case Instruction::AShr: Out << " >> "; break;
818       case Instruction::ICmp:
819         switch (CE->getPredicate()) {
820           case ICmpInst::ICMP_EQ: Out << " == "; break;
821           case ICmpInst::ICMP_NE: Out << " != "; break;
822           case ICmpInst::ICMP_SLT: 
823           case ICmpInst::ICMP_ULT: Out << " < "; break;
824           case ICmpInst::ICMP_SLE:
825           case ICmpInst::ICMP_ULE: Out << " <= "; break;
826           case ICmpInst::ICMP_SGT:
827           case ICmpInst::ICMP_UGT: Out << " > "; break;
828           case ICmpInst::ICMP_SGE:
829           case ICmpInst::ICMP_UGE: Out << " >= "; break;
830           default: assert(0 && "Illegal ICmp predicate");
831         }
832         break;
833       default: assert(0 && "Illegal opcode here!");
834       }
835       printConstantWithCast(CE->getOperand(1), CE->getOpcode());
836       if (NeedsClosingParens)
837         Out << "))";
838       Out << ')';
839       return;
840     }
841     case Instruction::FCmp: {
842       Out << '('; 
843       bool NeedsClosingParens = printConstExprCast(CE); 
844       if (CE->getPredicate() == FCmpInst::FCMP_FALSE)
845         Out << "0";
846       else if (CE->getPredicate() == FCmpInst::FCMP_TRUE)
847         Out << "1";
848       else {
849         const char* op = 0;
850         switch (CE->getPredicate()) {
851         default: assert(0 && "Illegal FCmp predicate");
852         case FCmpInst::FCMP_ORD: op = "ord"; break;
853         case FCmpInst::FCMP_UNO: op = "uno"; break;
854         case FCmpInst::FCMP_UEQ: op = "ueq"; break;
855         case FCmpInst::FCMP_UNE: op = "une"; break;
856         case FCmpInst::FCMP_ULT: op = "ult"; break;
857         case FCmpInst::FCMP_ULE: op = "ule"; break;
858         case FCmpInst::FCMP_UGT: op = "ugt"; break;
859         case FCmpInst::FCMP_UGE: op = "uge"; break;
860         case FCmpInst::FCMP_OEQ: op = "oeq"; break;
861         case FCmpInst::FCMP_ONE: op = "one"; break;
862         case FCmpInst::FCMP_OLT: op = "olt"; break;
863         case FCmpInst::FCMP_OLE: op = "ole"; break;
864         case FCmpInst::FCMP_OGT: op = "ogt"; break;
865         case FCmpInst::FCMP_OGE: op = "oge"; break;
866         }
867         Out << "llvm_fcmp_" << op << "(";
868         printConstantWithCast(CE->getOperand(0), CE->getOpcode());
869         Out << ", ";
870         printConstantWithCast(CE->getOperand(1), CE->getOpcode());
871         Out << ")";
872       }
873       if (NeedsClosingParens)
874         Out << "))";
875       Out << ')';
876       return;
877     }
878     default:
879       cerr << "CWriter Error: Unhandled constant expression: "
880            << *CE << "\n";
881       abort();
882     }
883   } else if (isa<UndefValue>(CPV) && CPV->getType()->isFirstClassType()) {
884     Out << "((";
885     printType(Out, CPV->getType()); // sign doesn't matter
886     Out << ")/*UNDEF*/0)";
887     return;
888   }
889
890   if (ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
891     const Type* Ty = CI->getType();
892     if (Ty == Type::Int1Ty)
893       Out << (CI->getZExtValue() ? '1' : '0');
894     else if (Ty == Type::Int32Ty)
895       Out << CI->getZExtValue() << 'u';
896     else if (Ty->getPrimitiveSizeInBits() > 32)
897       Out << CI->getZExtValue() << "ull";
898     else {
899       Out << "((";
900       printSimpleType(Out, Ty, false) << ')';
901       if (CI->isMinValue(true)) 
902         Out << CI->getZExtValue() << 'u';
903       else
904         Out << CI->getSExtValue();
905        Out << ')';
906     }
907     return;
908   } 
909
910   switch (CPV->getType()->getTypeID()) {
911   case Type::FloatTyID:
912   case Type::DoubleTyID: 
913   case Type::X86_FP80TyID:
914   case Type::PPC_FP128TyID:
915   case Type::FP128TyID: {
916     ConstantFP *FPC = cast<ConstantFP>(CPV);
917     std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
918     if (I != FPConstantMap.end()) {
919       // Because of FP precision problems we must load from a stack allocated
920       // value that holds the value in hex.
921       Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : 
922                        FPC->getType() == Type::DoubleTy ? "double" :
923                        "long double")
924           << "*)&FPConstant" << I->second << ')';
925     } else {
926       assert(FPC->getType() == Type::FloatTy || 
927              FPC->getType() == Type::DoubleTy);
928       double V = FPC->getType() == Type::FloatTy ? 
929                  FPC->getValueAPF().convertToFloat() : 
930                  FPC->getValueAPF().convertToDouble();
931       if (IsNAN(V)) {
932         // The value is NaN
933
934         // FIXME the actual NaN bits should be emitted.
935         // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
936         // it's 0x7ff4.
937         const unsigned long QuietNaN = 0x7ff8UL;
938         //const unsigned long SignalNaN = 0x7ff4UL;
939
940         // We need to grab the first part of the FP #
941         char Buffer[100];
942
943         uint64_t ll = DoubleToBits(V);
944         sprintf(Buffer, "0x%llx", static_cast<long long>(ll));
945
946         std::string Num(&Buffer[0], &Buffer[6]);
947         unsigned long Val = strtoul(Num.c_str(), 0, 16);
948
949         if (FPC->getType() == Type::FloatTy)
950           Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
951               << Buffer << "\") /*nan*/ ";
952         else
953           Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
954               << Buffer << "\") /*nan*/ ";
955       } else if (IsInf(V)) {
956         // The value is Inf
957         if (V < 0) Out << '-';
958         Out << "LLVM_INF" << (FPC->getType() == Type::FloatTy ? "F" : "")
959             << " /*inf*/ ";
960       } else {
961         std::string Num;
962 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
963         // Print out the constant as a floating point number.
964         char Buffer[100];
965         sprintf(Buffer, "%a", V);
966         Num = Buffer;
967 #else
968         Num = ftostr(FPC->getValueAPF());
969 #endif
970        Out << Num;
971       }
972     }
973     break;
974   }
975
976   case Type::ArrayTyID:
977     if (ConstantArray *CA = cast<ConstantArray>(CPV)) {
978       printConstantArray(CA);
979     } else {
980       assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
981       const ArrayType *AT = cast<ArrayType>(CPV->getType());
982       Out << '{';
983       if (AT->getNumElements()) {
984         Out << ' ';
985         Constant *CZ = Constant::getNullValue(AT->getElementType());
986         printConstant(CZ);
987         for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
988           Out << ", ";
989           printConstant(CZ);
990         }
991       }
992       Out << " }";
993     }
994     break;
995
996   case Type::VectorTyID:
997     // Use C99 compound expression literal initializer syntax.
998     Out << "(";
999     printType(Out, CPV->getType());
1000     Out << ")";
1001     if (ConstantVector *CV = cast<ConstantVector>(CPV)) {
1002       printConstantVector(CV);
1003     } else {
1004       assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
1005       const VectorType *VT = cast<VectorType>(CPV->getType());
1006       Out << "{ ";
1007       Constant *CZ = Constant::getNullValue(VT->getElementType());
1008       printConstant(CZ);
1009       for (unsigned i = 1, e = VT->getNumElements(); i != e; ++i) {
1010         Out << ", ";
1011         printConstant(CZ);
1012       }
1013       Out << " }";
1014     }
1015     break;
1016
1017   case Type::StructTyID:
1018     if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
1019       const StructType *ST = cast<StructType>(CPV->getType());
1020       Out << '{';
1021       if (ST->getNumElements()) {
1022         Out << ' ';
1023         printConstant(Constant::getNullValue(ST->getElementType(0)));
1024         for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
1025           Out << ", ";
1026           printConstant(Constant::getNullValue(ST->getElementType(i)));
1027         }
1028       }
1029       Out << " }";
1030     } else {
1031       Out << '{';
1032       if (CPV->getNumOperands()) {
1033         Out << ' ';
1034         printConstant(cast<Constant>(CPV->getOperand(0)));
1035         for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
1036           Out << ", ";
1037           printConstant(cast<Constant>(CPV->getOperand(i)));
1038         }
1039       }
1040       Out << " }";
1041     }
1042     break;
1043
1044   case Type::PointerTyID:
1045     if (isa<ConstantPointerNull>(CPV)) {
1046       Out << "((";
1047       printType(Out, CPV->getType()); // sign doesn't matter
1048       Out << ")/*NULL*/0)";
1049       break;
1050     } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
1051       writeOperand(GV);
1052       break;
1053     }
1054     // FALL THROUGH
1055   default:
1056     cerr << "Unknown constant type: " << *CPV << "\n";
1057     abort();
1058   }
1059 }
1060
1061 // Some constant expressions need to be casted back to the original types
1062 // because their operands were casted to the expected type. This function takes
1063 // care of detecting that case and printing the cast for the ConstantExpr.
1064 bool CWriter::printConstExprCast(const ConstantExpr* CE) {
1065   bool NeedsExplicitCast = false;
1066   const Type *Ty = CE->getOperand(0)->getType();
1067   bool TypeIsSigned = false;
1068   switch (CE->getOpcode()) {
1069   case Instruction::LShr:
1070   case Instruction::URem: 
1071   case Instruction::UDiv: NeedsExplicitCast = true; break;
1072   case Instruction::AShr:
1073   case Instruction::SRem: 
1074   case Instruction::SDiv: NeedsExplicitCast = true; TypeIsSigned = true; break;
1075   case Instruction::SExt:
1076     Ty = CE->getType();
1077     NeedsExplicitCast = true;
1078     TypeIsSigned = true;
1079     break;
1080   case Instruction::ZExt:
1081   case Instruction::Trunc:
1082   case Instruction::FPTrunc:
1083   case Instruction::FPExt:
1084   case Instruction::UIToFP:
1085   case Instruction::SIToFP:
1086   case Instruction::FPToUI:
1087   case Instruction::FPToSI:
1088   case Instruction::PtrToInt:
1089   case Instruction::IntToPtr:
1090   case Instruction::BitCast:
1091     Ty = CE->getType();
1092     NeedsExplicitCast = true;
1093     break;
1094   default: break;
1095   }
1096   if (NeedsExplicitCast) {
1097     Out << "((";
1098     if (Ty->isInteger() && Ty != Type::Int1Ty)
1099       printSimpleType(Out, Ty, TypeIsSigned);
1100     else
1101       printType(Out, Ty); // not integer, sign doesn't matter
1102     Out << ")(";
1103   }
1104   return NeedsExplicitCast;
1105 }
1106
1107 //  Print a constant assuming that it is the operand for a given Opcode. The
1108 //  opcodes that care about sign need to cast their operands to the expected
1109 //  type before the operation proceeds. This function does the casting.
1110 void CWriter::printConstantWithCast(Constant* CPV, unsigned Opcode) {
1111
1112   // Extract the operand's type, we'll need it.
1113   const Type* OpTy = CPV->getType();
1114
1115   // Indicate whether to do the cast or not.
1116   bool shouldCast = false;
1117   bool typeIsSigned = false;
1118
1119   // Based on the Opcode for which this Constant is being written, determine
1120   // the new type to which the operand should be casted by setting the value
1121   // of OpTy. If we change OpTy, also set shouldCast to true so it gets
1122   // casted below.
1123   switch (Opcode) {
1124     default:
1125       // for most instructions, it doesn't matter
1126       break; 
1127     case Instruction::LShr:
1128     case Instruction::UDiv:
1129     case Instruction::URem:
1130       shouldCast = true;
1131       break;
1132     case Instruction::AShr:
1133     case Instruction::SDiv:
1134     case Instruction::SRem:
1135       shouldCast = true;
1136       typeIsSigned = true;
1137       break;
1138   }
1139
1140   // Write out the casted constant if we should, otherwise just write the
1141   // operand.
1142   if (shouldCast) {
1143     Out << "((";
1144     printSimpleType(Out, OpTy, typeIsSigned);
1145     Out << ")";
1146     printConstant(CPV);
1147     Out << ")";
1148   } else 
1149     printConstant(CPV);
1150 }
1151
1152 std::string CWriter::GetValueName(const Value *Operand) {
1153   std::string Name;
1154
1155   if (!isa<GlobalValue>(Operand) && Operand->getName() != "") {
1156     std::string VarName;
1157
1158     Name = Operand->getName();
1159     VarName.reserve(Name.capacity());
1160
1161     for (std::string::iterator I = Name.begin(), E = Name.end();
1162          I != E; ++I) {
1163       char ch = *I;
1164
1165       if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
1166             (ch >= '0' && ch <= '9') || ch == '_')) {
1167         char buffer[5];
1168         sprintf(buffer, "_%x_", ch);
1169         VarName += buffer;
1170       } else
1171         VarName += ch;
1172     }
1173
1174     Name = "llvm_cbe_" + VarName;
1175   } else {
1176     Name = Mang->getValueName(Operand);
1177   }
1178
1179   return Name;
1180 }
1181
1182 void CWriter::writeOperandInternal(Value *Operand) {
1183   if (Instruction *I = dyn_cast<Instruction>(Operand))
1184     if (isInlinableInst(*I) && !isDirectAlloca(I)) {
1185       // Should we inline this instruction to build a tree?
1186       Out << '(';
1187       visit(*I);
1188       Out << ')';
1189       return;
1190     }
1191
1192   Constant* CPV = dyn_cast<Constant>(Operand);
1193
1194   if (CPV && !isa<GlobalValue>(CPV))
1195     printConstant(CPV);
1196   else
1197     Out << GetValueName(Operand);
1198 }
1199
1200 void CWriter::writeOperandRaw(Value *Operand) {
1201   Constant* CPV = dyn_cast<Constant>(Operand);
1202   if (CPV && !isa<GlobalValue>(CPV)) {
1203     printConstant(CPV);
1204   } else {
1205     Out << GetValueName(Operand);
1206   }
1207 }
1208
1209 void CWriter::writeOperand(Value *Operand) {
1210   if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
1211     Out << "(&";  // Global variables are referenced as their addresses by llvm
1212
1213   writeOperandInternal(Operand);
1214
1215   if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
1216     Out << ')';
1217 }
1218
1219 // Some instructions need to have their result value casted back to the 
1220 // original types because their operands were casted to the expected type. 
1221 // This function takes care of detecting that case and printing the cast 
1222 // for the Instruction.
1223 bool CWriter::writeInstructionCast(const Instruction &I) {
1224   const Type *Ty = I.getOperand(0)->getType();
1225   switch (I.getOpcode()) {
1226   case Instruction::LShr:
1227   case Instruction::URem: 
1228   case Instruction::UDiv: 
1229     Out << "((";
1230     printSimpleType(Out, Ty, false);
1231     Out << ")(";
1232     return true;
1233   case Instruction::AShr:
1234   case Instruction::SRem: 
1235   case Instruction::SDiv: 
1236     Out << "((";
1237     printSimpleType(Out, Ty, true);
1238     Out << ")(";
1239     return true;
1240   default: break;
1241   }
1242   return false;
1243 }
1244
1245 // Write the operand with a cast to another type based on the Opcode being used.
1246 // This will be used in cases where an instruction has specific type
1247 // requirements (usually signedness) for its operands. 
1248 void CWriter::writeOperandWithCast(Value* Operand, unsigned Opcode) {
1249
1250   // Extract the operand's type, we'll need it.
1251   const Type* OpTy = Operand->getType();
1252
1253   // Indicate whether to do the cast or not.
1254   bool shouldCast = false;
1255
1256   // Indicate whether the cast should be to a signed type or not.
1257   bool castIsSigned = false;
1258
1259   // Based on the Opcode for which this Operand is being written, determine
1260   // the new type to which the operand should be casted by setting the value
1261   // of OpTy. If we change OpTy, also set shouldCast to true.
1262   switch (Opcode) {
1263     default:
1264       // for most instructions, it doesn't matter
1265       break; 
1266     case Instruction::LShr:
1267     case Instruction::UDiv:
1268     case Instruction::URem: // Cast to unsigned first
1269       shouldCast = true;
1270       castIsSigned = false;
1271       break;
1272     case Instruction::GetElementPtr:
1273     case Instruction::AShr:
1274     case Instruction::SDiv:
1275     case Instruction::SRem: // Cast to signed first
1276       shouldCast = true;
1277       castIsSigned = true;
1278       break;
1279   }
1280
1281   // Write out the casted operand if we should, otherwise just write the
1282   // operand.
1283   if (shouldCast) {
1284     Out << "((";
1285     printSimpleType(Out, OpTy, castIsSigned);
1286     Out << ")";
1287     writeOperand(Operand);
1288     Out << ")";
1289   } else 
1290     writeOperand(Operand);
1291 }
1292
1293 // Write the operand with a cast to another type based on the icmp predicate 
1294 // being used. 
1295 void CWriter::writeOperandWithCast(Value* Operand, const ICmpInst &Cmp) {
1296   // This has to do a cast to ensure the operand has the right signedness. 
1297   // Also, if the operand is a pointer, we make sure to cast to an integer when
1298   // doing the comparison both for signedness and so that the C compiler doesn't
1299   // optimize things like "p < NULL" to false (p may contain an integer value
1300   // f.e.).
1301   bool shouldCast = Cmp.isRelational();
1302
1303   // Write out the casted operand if we should, otherwise just write the
1304   // operand.
1305   if (!shouldCast) {
1306     writeOperand(Operand);
1307     return;
1308   }
1309   
1310   // Should this be a signed comparison?  If so, convert to signed.
1311   bool castIsSigned = Cmp.isSignedPredicate();
1312
1313   // If the operand was a pointer, convert to a large integer type.
1314   const Type* OpTy = Operand->getType();
1315   if (isa<PointerType>(OpTy))
1316     OpTy = TD->getIntPtrType();
1317   
1318   Out << "((";
1319   printSimpleType(Out, OpTy, castIsSigned);
1320   Out << ")";
1321   writeOperand(Operand);
1322   Out << ")";
1323 }
1324
1325 // generateCompilerSpecificCode - This is where we add conditional compilation
1326 // directives to cater to specific compilers as need be.
1327 //
1328 static void generateCompilerSpecificCode(std::ostream& Out) {
1329   // Alloca is hard to get, and we don't want to include stdlib.h here.
1330   Out << "/* get a declaration for alloca */\n"
1331       << "#if defined(__CYGWIN__) || defined(__MINGW32__)\n"
1332       << "#define  alloca(x) __builtin_alloca((x))\n"
1333       << "#define _alloca(x) __builtin_alloca((x))\n"    
1334       << "#elif defined(__APPLE__)\n"
1335       << "extern void *__builtin_alloca(unsigned long);\n"
1336       << "#define alloca(x) __builtin_alloca(x)\n"
1337       << "#define longjmp _longjmp\n"
1338       << "#define setjmp _setjmp\n"
1339       << "#elif defined(__sun__)\n"
1340       << "#if defined(__sparcv9)\n"
1341       << "extern void *__builtin_alloca(unsigned long);\n"
1342       << "#else\n"
1343       << "extern void *__builtin_alloca(unsigned int);\n"
1344       << "#endif\n"
1345       << "#define alloca(x) __builtin_alloca(x)\n"
1346       << "#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)\n"
1347       << "#define alloca(x) __builtin_alloca(x)\n"
1348       << "#elif defined(_MSC_VER)\n"
1349       << "#define inline _inline\n"
1350       << "#define alloca(x) _alloca(x)\n"
1351       << "#else\n"
1352       << "#include <alloca.h>\n"
1353       << "#endif\n\n";
1354
1355   // We output GCC specific attributes to preserve 'linkonce'ness on globals.
1356   // If we aren't being compiled with GCC, just drop these attributes.
1357   Out << "#ifndef __GNUC__  /* Can only support \"linkonce\" vars with GCC */\n"
1358       << "#define __attribute__(X)\n"
1359       << "#endif\n\n";
1360
1361   // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
1362   Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1363       << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
1364       << "#elif defined(__GNUC__)\n"
1365       << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
1366       << "#else\n"
1367       << "#define __EXTERNAL_WEAK__\n"
1368       << "#endif\n\n";
1369
1370   // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
1371   Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1372       << "#define __ATTRIBUTE_WEAK__\n"
1373       << "#elif defined(__GNUC__)\n"
1374       << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
1375       << "#else\n"
1376       << "#define __ATTRIBUTE_WEAK__\n"
1377       << "#endif\n\n";
1378
1379   // Add hidden visibility support. FIXME: APPLE_CC?
1380   Out << "#if defined(__GNUC__)\n"
1381       << "#define __HIDDEN__ __attribute__((visibility(\"hidden\")))\n"
1382       << "#endif\n\n";
1383     
1384   // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
1385   // From the GCC documentation:
1386   //
1387   //   double __builtin_nan (const char *str)
1388   //
1389   // This is an implementation of the ISO C99 function nan.
1390   //
1391   // Since ISO C99 defines this function in terms of strtod, which we do
1392   // not implement, a description of the parsing is in order. The string is
1393   // parsed as by strtol; that is, the base is recognized by leading 0 or
1394   // 0x prefixes. The number parsed is placed in the significand such that
1395   // the least significant bit of the number is at the least significant
1396   // bit of the significand. The number is truncated to fit the significand
1397   // field provided. The significand is forced to be a quiet NaN.
1398   //
1399   // This function, if given a string literal, is evaluated early enough
1400   // that it is considered a compile-time constant.
1401   //
1402   //   float __builtin_nanf (const char *str)
1403   //
1404   // Similar to __builtin_nan, except the return type is float.
1405   //
1406   //   double __builtin_inf (void)
1407   //
1408   // Similar to __builtin_huge_val, except a warning is generated if the
1409   // target floating-point format does not support infinities. This
1410   // function is suitable for implementing the ISO C99 macro INFINITY.
1411   //
1412   //   float __builtin_inff (void)
1413   //
1414   // Similar to __builtin_inf, except the return type is float.
1415   Out << "#ifdef __GNUC__\n"
1416       << "#define LLVM_NAN(NanStr)   __builtin_nan(NanStr)   /* Double */\n"
1417       << "#define LLVM_NANF(NanStr)  __builtin_nanf(NanStr)  /* Float */\n"
1418       << "#define LLVM_NANS(NanStr)  __builtin_nans(NanStr)  /* Double */\n"
1419       << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
1420       << "#define LLVM_INF           __builtin_inf()         /* Double */\n"
1421       << "#define LLVM_INFF          __builtin_inff()        /* Float */\n"
1422       << "#define LLVM_PREFETCH(addr,rw,locality) "
1423                               "__builtin_prefetch(addr,rw,locality)\n"
1424       << "#define __ATTRIBUTE_CTOR__ __attribute__((constructor))\n"
1425       << "#define __ATTRIBUTE_DTOR__ __attribute__((destructor))\n"
1426       << "#define LLVM_ASM           __asm__\n"
1427       << "#else\n"
1428       << "#define LLVM_NAN(NanStr)   ((double)0.0)           /* Double */\n"
1429       << "#define LLVM_NANF(NanStr)  0.0F                    /* Float */\n"
1430       << "#define LLVM_NANS(NanStr)  ((double)0.0)           /* Double */\n"
1431       << "#define LLVM_NANSF(NanStr) 0.0F                    /* Float */\n"
1432       << "#define LLVM_INF           ((double)0.0)           /* Double */\n"
1433       << "#define LLVM_INFF          0.0F                    /* Float */\n"
1434       << "#define LLVM_PREFETCH(addr,rw,locality)            /* PREFETCH */\n"
1435       << "#define __ATTRIBUTE_CTOR__\n"
1436       << "#define __ATTRIBUTE_DTOR__\n"
1437       << "#define LLVM_ASM(X)\n"
1438       << "#endif\n\n";
1439   
1440   Out << "#if __GNUC__ < 4 /* Old GCC's, or compilers not GCC */ \n"
1441       << "#define __builtin_stack_save() 0   /* not implemented */\n"
1442       << "#define __builtin_stack_restore(X) /* noop */\n"
1443       << "#endif\n\n";
1444
1445   // Output target-specific code that should be inserted into main.
1446   Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
1447 }
1448
1449 /// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
1450 /// the StaticTors set.
1451 static void FindStaticTors(GlobalVariable *GV, std::set<Function*> &StaticTors){
1452   ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
1453   if (!InitList) return;
1454   
1455   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
1456     if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
1457       if (CS->getNumOperands() != 2) return;  // Not array of 2-element structs.
1458       
1459       if (CS->getOperand(1)->isNullValue())
1460         return;  // Found a null terminator, exit printing.
1461       Constant *FP = CS->getOperand(1);
1462       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
1463         if (CE->isCast())
1464           FP = CE->getOperand(0);
1465       if (Function *F = dyn_cast<Function>(FP))
1466         StaticTors.insert(F);
1467     }
1468 }
1469
1470 enum SpecialGlobalClass {
1471   NotSpecial = 0,
1472   GlobalCtors, GlobalDtors,
1473   NotPrinted
1474 };
1475
1476 /// getGlobalVariableClass - If this is a global that is specially recognized
1477 /// by LLVM, return a code that indicates how we should handle it.
1478 static SpecialGlobalClass getGlobalVariableClass(const GlobalVariable *GV) {
1479   // If this is a global ctors/dtors list, handle it now.
1480   if (GV->hasAppendingLinkage() && GV->use_empty()) {
1481     if (GV->getName() == "llvm.global_ctors")
1482       return GlobalCtors;
1483     else if (GV->getName() == "llvm.global_dtors")
1484       return GlobalDtors;
1485   }
1486   
1487   // Otherwise, it it is other metadata, don't print it.  This catches things
1488   // like debug information.
1489   if (GV->getSection() == "llvm.metadata")
1490     return NotPrinted;
1491   
1492   return NotSpecial;
1493 }
1494
1495
1496 bool CWriter::doInitialization(Module &M) {
1497   // Initialize
1498   TheModule = &M;
1499
1500   TD = new TargetData(&M);
1501   IL = new IntrinsicLowering(*TD);
1502   IL->AddPrototypes(M);
1503
1504   // Ensure that all structure types have names...
1505   Mang = new Mangler(M);
1506   Mang->markCharUnacceptable('.');
1507
1508   // Keep track of which functions are static ctors/dtors so they can have
1509   // an attribute added to their prototypes.
1510   std::set<Function*> StaticCtors, StaticDtors;
1511   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1512        I != E; ++I) {
1513     switch (getGlobalVariableClass(I)) {
1514     default: break;
1515     case GlobalCtors:
1516       FindStaticTors(I, StaticCtors);
1517       break;
1518     case GlobalDtors:
1519       FindStaticTors(I, StaticDtors);
1520       break;
1521     }
1522   }
1523   
1524   // get declaration for alloca
1525   Out << "/* Provide Declarations */\n";
1526   Out << "#include <stdarg.h>\n";      // Varargs support
1527   Out << "#include <setjmp.h>\n";      // Unwind support
1528   generateCompilerSpecificCode(Out);
1529
1530   // Provide a definition for `bool' if not compiling with a C++ compiler.
1531   Out << "\n"
1532       << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
1533
1534       << "\n\n/* Support for floating point constants */\n"
1535       << "typedef unsigned long long ConstantDoubleTy;\n"
1536       << "typedef unsigned int        ConstantFloatTy;\n"
1537       << "typedef struct { unsigned long long f1; unsigned short f2; "
1538          "unsigned short pad[3]; } ConstantFP80Ty;\n"
1539       // This is used for both kinds of 128-bit long double; meaning differs.
1540       << "typedef struct { unsigned long long f1; unsigned long long f2; }"
1541          " ConstantFP128Ty;\n"
1542       << "\n\n/* Global Declarations */\n";
1543
1544   // First output all the declarations for the program, because C requires
1545   // Functions & globals to be declared before they are used.
1546   //
1547
1548   // Loop over the symbol table, emitting all named constants...
1549   printModuleTypes(M.getTypeSymbolTable());
1550
1551   // Global variable declarations...
1552   if (!M.global_empty()) {
1553     Out << "\n/* External Global Variable Declarations */\n";
1554     for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1555          I != E; ++I) {
1556
1557       if (I->hasExternalLinkage() || I->hasExternalWeakLinkage())
1558         Out << "extern ";
1559       else if (I->hasDLLImportLinkage())
1560         Out << "__declspec(dllimport) ";
1561       else
1562         continue; // Internal Global
1563
1564       // Thread Local Storage
1565       if (I->isThreadLocal())
1566         Out << "__thread ";
1567
1568       printType(Out, I->getType()->getElementType(), false, GetValueName(I));
1569
1570       if (I->hasExternalWeakLinkage())
1571          Out << " __EXTERNAL_WEAK__";
1572       Out << ";\n";
1573     }
1574   }
1575
1576   // Function declarations
1577   Out << "\n/* Function Declarations */\n";
1578   Out << "double fmod(double, double);\n";   // Support for FP rem
1579   Out << "float fmodf(float, float);\n";
1580   Out << "long double fmodl(long double, long double);\n";
1581   
1582   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1583     // Don't print declarations for intrinsic functions.
1584     if (!I->isIntrinsic() && I->getName() != "setjmp" &&
1585         I->getName() != "longjmp" && I->getName() != "_setjmp") {
1586       if (I->hasExternalWeakLinkage())
1587         Out << "extern ";
1588       printFunctionSignature(I, true);
1589       if (I->hasWeakLinkage() || I->hasLinkOnceLinkage()) 
1590         Out << " __ATTRIBUTE_WEAK__";
1591       if (I->hasExternalWeakLinkage())
1592         Out << " __EXTERNAL_WEAK__";
1593       if (StaticCtors.count(I))
1594         Out << " __ATTRIBUTE_CTOR__";
1595       if (StaticDtors.count(I))
1596         Out << " __ATTRIBUTE_DTOR__";
1597       if (I->hasHiddenVisibility())
1598         Out << " __HIDDEN__";
1599       
1600       if (I->hasName() && I->getName()[0] == 1)
1601         Out << " LLVM_ASM(\"" << I->getName().c_str()+1 << "\")";
1602           
1603       Out << ";\n";
1604     }
1605   }
1606
1607   // Output the global variable declarations
1608   if (!M.global_empty()) {
1609     Out << "\n\n/* Global Variable Declarations */\n";
1610     for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1611          I != E; ++I)
1612       if (!I->isDeclaration()) {
1613         // Ignore special globals, such as debug info.
1614         if (getGlobalVariableClass(I))
1615           continue;
1616
1617         if (I->hasInternalLinkage())
1618           Out << "static ";
1619         else
1620           Out << "extern ";
1621
1622         // Thread Local Storage
1623         if (I->isThreadLocal())
1624           Out << "__thread ";
1625
1626         printType(Out, I->getType()->getElementType(), false, 
1627                   GetValueName(I));
1628
1629         if (I->hasLinkOnceLinkage())
1630           Out << " __attribute__((common))";
1631         else if (I->hasWeakLinkage())
1632           Out << " __ATTRIBUTE_WEAK__";
1633         else if (I->hasExternalWeakLinkage())
1634           Out << " __EXTERNAL_WEAK__";
1635         if (I->hasHiddenVisibility())
1636           Out << " __HIDDEN__";
1637         Out << ";\n";
1638       }
1639   }
1640
1641   // Output the global variable definitions and contents...
1642   if (!M.global_empty()) {
1643     Out << "\n\n/* Global Variable Definitions and Initialization */\n";
1644     for (Module::global_iterator I = M.global_begin(), E = M.global_end(); 
1645          I != E; ++I)
1646       if (!I->isDeclaration()) {
1647         // Ignore special globals, such as debug info.
1648         if (getGlobalVariableClass(I))
1649           continue;
1650
1651         if (I->hasInternalLinkage())
1652           Out << "static ";
1653         else if (I->hasDLLImportLinkage())
1654           Out << "__declspec(dllimport) ";
1655         else if (I->hasDLLExportLinkage())
1656           Out << "__declspec(dllexport) ";
1657
1658         // Thread Local Storage
1659         if (I->isThreadLocal())
1660           Out << "__thread ";
1661
1662         printType(Out, I->getType()->getElementType(), false, 
1663                   GetValueName(I));
1664         if (I->hasLinkOnceLinkage())
1665           Out << " __attribute__((common))";
1666         else if (I->hasWeakLinkage())
1667           Out << " __ATTRIBUTE_WEAK__";
1668
1669         if (I->hasHiddenVisibility())
1670           Out << " __HIDDEN__";
1671         
1672         // If the initializer is not null, emit the initializer.  If it is null,
1673         // we try to avoid emitting large amounts of zeros.  The problem with
1674         // this, however, occurs when the variable has weak linkage.  In this
1675         // case, the assembler will complain about the variable being both weak
1676         // and common, so we disable this optimization.
1677         if (!I->getInitializer()->isNullValue()) {
1678           Out << " = " ;
1679           writeOperand(I->getInitializer());
1680         } else if (I->hasWeakLinkage()) {
1681           // We have to specify an initializer, but it doesn't have to be
1682           // complete.  If the value is an aggregate, print out { 0 }, and let
1683           // the compiler figure out the rest of the zeros.
1684           Out << " = " ;
1685           if (isa<StructType>(I->getInitializer()->getType()) ||
1686               isa<ArrayType>(I->getInitializer()->getType()) ||
1687               isa<VectorType>(I->getInitializer()->getType())) {
1688             Out << "{ 0 }";
1689           } else {
1690             // Just print it out normally.
1691             writeOperand(I->getInitializer());
1692           }
1693         }
1694         Out << ";\n";
1695       }
1696   }
1697
1698   if (!M.empty())
1699     Out << "\n\n/* Function Bodies */\n";
1700
1701   // Emit some helper functions for dealing with FCMP instruction's 
1702   // predicates
1703   Out << "static inline int llvm_fcmp_ord(double X, double Y) { ";
1704   Out << "return X == X && Y == Y; }\n";
1705   Out << "static inline int llvm_fcmp_uno(double X, double Y) { ";
1706   Out << "return X != X || Y != Y; }\n";
1707   Out << "static inline int llvm_fcmp_ueq(double X, double Y) { ";
1708   Out << "return X == Y || llvm_fcmp_uno(X, Y); }\n";
1709   Out << "static inline int llvm_fcmp_une(double X, double Y) { ";
1710   Out << "return X != Y; }\n";
1711   Out << "static inline int llvm_fcmp_ult(double X, double Y) { ";
1712   Out << "return X <  Y || llvm_fcmp_uno(X, Y); }\n";
1713   Out << "static inline int llvm_fcmp_ugt(double X, double Y) { ";
1714   Out << "return X >  Y || llvm_fcmp_uno(X, Y); }\n";
1715   Out << "static inline int llvm_fcmp_ule(double X, double Y) { ";
1716   Out << "return X <= Y || llvm_fcmp_uno(X, Y); }\n";
1717   Out << "static inline int llvm_fcmp_uge(double X, double Y) { ";
1718   Out << "return X >= Y || llvm_fcmp_uno(X, Y); }\n";
1719   Out << "static inline int llvm_fcmp_oeq(double X, double Y) { ";
1720   Out << "return X == Y ; }\n";
1721   Out << "static inline int llvm_fcmp_one(double X, double Y) { ";
1722   Out << "return X != Y && llvm_fcmp_ord(X, Y); }\n";
1723   Out << "static inline int llvm_fcmp_olt(double X, double Y) { ";
1724   Out << "return X <  Y ; }\n";
1725   Out << "static inline int llvm_fcmp_ogt(double X, double Y) { ";
1726   Out << "return X >  Y ; }\n";
1727   Out << "static inline int llvm_fcmp_ole(double X, double Y) { ";
1728   Out << "return X <= Y ; }\n";
1729   Out << "static inline int llvm_fcmp_oge(double X, double Y) { ";
1730   Out << "return X >= Y ; }\n";
1731   return false;
1732 }
1733
1734
1735 /// Output all floating point constants that cannot be printed accurately...
1736 void CWriter::printFloatingPointConstants(Function &F) {
1737   // Scan the module for floating point constants.  If any FP constant is used
1738   // in the function, we want to redirect it here so that we do not depend on
1739   // the precision of the printed form, unless the printed form preserves
1740   // precision.
1741   //
1742   static unsigned FPCounter = 0;
1743   for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
1744        I != E; ++I)
1745     if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
1746       if (!isFPCSafeToPrint(FPC) && // Do not put in FPConstantMap if safe.
1747           !FPConstantMap.count(FPC)) {
1748         FPConstantMap[FPC] = FPCounter;  // Number the FP constants
1749
1750         if (FPC->getType() == Type::DoubleTy) {
1751           double Val = FPC->getValueAPF().convertToDouble();
1752           uint64_t i = FPC->getValueAPF().convertToAPInt().getZExtValue();
1753           Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
1754               << " = 0x" << std::hex << i << std::dec
1755               << "ULL;    /* " << Val << " */\n";
1756         } else if (FPC->getType() == Type::FloatTy) {
1757           float Val = FPC->getValueAPF().convertToFloat();
1758           uint32_t i = (uint32_t)FPC->getValueAPF().convertToAPInt().
1759                                     getZExtValue();
1760           Out << "static const ConstantFloatTy FPConstant" << FPCounter++
1761               << " = 0x" << std::hex << i << std::dec
1762               << "U;    /* " << Val << " */\n";
1763         } else if (FPC->getType() == Type::X86_FP80Ty) {
1764           // api needed to prevent premature destruction
1765           APInt api = FPC->getValueAPF().convertToAPInt();
1766           const uint64_t *p = api.getRawData();
1767           Out << "static const ConstantFP80Ty FPConstant" << FPCounter++
1768               << " = { 0x" << std::hex
1769               << ((uint16_t)p[1] | (p[0] & 0xffffffffffffLL)<<16)
1770               << ", 0x" << (uint16_t)(p[0] >> 48) << ",0,0,0"
1771               << "}; /* Long double constant */\n" << std::dec;
1772         } else if (FPC->getType() == Type::PPC_FP128Ty) {
1773           APInt api = FPC->getValueAPF().convertToAPInt();
1774           const uint64_t *p = api.getRawData();
1775           Out << "static const ConstantFP128Ty FPConstant" << FPCounter++
1776               << " = { 0x" << std::hex
1777               << p[0] << ", 0x" << p[1]
1778               << "}; /* Long double constant */\n" << std::dec;
1779
1780         } else
1781           assert(0 && "Unknown float type!");
1782       }
1783
1784   Out << '\n';
1785 }
1786
1787
1788 /// printSymbolTable - Run through symbol table looking for type names.  If a
1789 /// type name is found, emit its declaration...
1790 ///
1791 void CWriter::printModuleTypes(const TypeSymbolTable &TST) {
1792   Out << "/* Helper union for bitcasts */\n";
1793   Out << "typedef union {\n";
1794   Out << "  unsigned int Int32;\n";
1795   Out << "  unsigned long long Int64;\n";
1796   Out << "  float Float;\n";
1797   Out << "  double Double;\n";
1798   Out << "} llvmBitCastUnion;\n";
1799
1800   // We are only interested in the type plane of the symbol table.
1801   TypeSymbolTable::const_iterator I   = TST.begin();
1802   TypeSymbolTable::const_iterator End = TST.end();
1803
1804   // If there are no type names, exit early.
1805   if (I == End) return;
1806
1807   // Print out forward declarations for structure types before anything else!
1808   Out << "/* Structure forward decls */\n";
1809   for (; I != End; ++I) {
1810     std::string Name = "struct l_" + Mang->makeNameProper(I->first);
1811     Out << Name << ";\n";
1812     TypeNames.insert(std::make_pair(I->second, Name));
1813   }
1814
1815   Out << '\n';
1816
1817   // Now we can print out typedefs.  Above, we guaranteed that this can only be
1818   // for struct or opaque types.
1819   Out << "/* Typedefs */\n";
1820   for (I = TST.begin(); I != End; ++I) {
1821     std::string Name = "l_" + Mang->makeNameProper(I->first);
1822     Out << "typedef ";
1823     printType(Out, I->second, false, Name);
1824     Out << ";\n";
1825   }
1826
1827   Out << '\n';
1828
1829   // Keep track of which structures have been printed so far...
1830   std::set<const StructType *> StructPrinted;
1831
1832   // Loop over all structures then push them into the stack so they are
1833   // printed in the correct order.
1834   //
1835   Out << "/* Structure contents */\n";
1836   for (I = TST.begin(); I != End; ++I)
1837     if (const StructType *STy = dyn_cast<StructType>(I->second))
1838       // Only print out used types!
1839       printContainedStructs(STy, StructPrinted);
1840 }
1841
1842 // Push the struct onto the stack and recursively push all structs
1843 // this one depends on.
1844 //
1845 // TODO:  Make this work properly with vector types
1846 //
1847 void CWriter::printContainedStructs(const Type *Ty,
1848                                     std::set<const StructType*> &StructPrinted){
1849   // Don't walk through pointers.
1850   if (isa<PointerType>(Ty) || Ty->isPrimitiveType() || Ty->isInteger()) return;
1851   
1852   // Print all contained types first.
1853   for (Type::subtype_iterator I = Ty->subtype_begin(),
1854        E = Ty->subtype_end(); I != E; ++I)
1855     printContainedStructs(*I, StructPrinted);
1856   
1857   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1858     // Check to see if we have already printed this struct.
1859     if (StructPrinted.insert(STy).second) {
1860       // Print structure type out.
1861       std::string Name = TypeNames[STy];
1862       printType(Out, STy, false, Name, true);
1863       Out << ";\n\n";
1864     }
1865   }
1866 }
1867
1868 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
1869   /// isStructReturn - Should this function actually return a struct by-value?
1870   bool isStructReturn = F->isStructReturn();
1871   
1872   if (F->hasInternalLinkage()) Out << "static ";
1873   if (F->hasDLLImportLinkage()) Out << "__declspec(dllimport) ";
1874   if (F->hasDLLExportLinkage()) Out << "__declspec(dllexport) ";  
1875   switch (F->getCallingConv()) {
1876    case CallingConv::X86_StdCall:
1877     Out << "__stdcall ";
1878     break;
1879    case CallingConv::X86_FastCall:
1880     Out << "__fastcall ";
1881     break;
1882   }
1883   
1884   // Loop over the arguments, printing them...
1885   const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
1886   const ParamAttrsList *PAL = F->getParamAttrs();
1887
1888   std::stringstream FunctionInnards;
1889
1890   // Print out the name...
1891   FunctionInnards << GetValueName(F) << '(';
1892
1893   bool PrintedArg = false;
1894   if (!F->isDeclaration()) {
1895     if (!F->arg_empty()) {
1896       Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1897       unsigned Idx = 1;
1898       
1899       // If this is a struct-return function, don't print the hidden
1900       // struct-return argument.
1901       if (isStructReturn) {
1902         assert(I != E && "Invalid struct return function!");
1903         ++I;
1904         ++Idx;
1905       }
1906       
1907       std::string ArgName;
1908       for (; I != E; ++I) {
1909         if (PrintedArg) FunctionInnards << ", ";
1910         if (I->hasName() || !Prototype)
1911           ArgName = GetValueName(I);
1912         else
1913           ArgName = "";
1914         const Type *ArgTy = I->getType();
1915         if (PAL && PAL->paramHasAttr(Idx, ParamAttr::ByVal)) {
1916           assert(isa<PointerType>(ArgTy));
1917           ArgTy = cast<PointerType>(ArgTy)->getElementType();
1918           const Value *Arg = &(*I);
1919           ByValParams.insert(Arg);
1920         }
1921         printType(FunctionInnards, ArgTy,
1922             /*isSigned=*/PAL && PAL->paramHasAttr(Idx, ParamAttr::SExt),
1923             ArgName);
1924         PrintedArg = true;
1925         ++Idx;
1926       }
1927     }
1928   } else {
1929     // Loop over the arguments, printing them.
1930     FunctionType::param_iterator I = FT->param_begin(), E = FT->param_end();
1931     unsigned Idx = 1;
1932     
1933     // If this is a struct-return function, don't print the hidden
1934     // struct-return argument.
1935     if (isStructReturn) {
1936       assert(I != E && "Invalid struct return function!");
1937       ++I;
1938       ++Idx;
1939     }
1940     
1941     for (; I != E; ++I) {
1942       if (PrintedArg) FunctionInnards << ", ";
1943       const Type *ArgTy = *I;
1944       if (PAL && PAL->paramHasAttr(Idx, ParamAttr::ByVal)) {
1945         assert(isa<PointerType>(ArgTy));
1946         ArgTy = cast<PointerType>(ArgTy)->getElementType();
1947       }
1948       printType(FunctionInnards, ArgTy,
1949              /*isSigned=*/PAL && PAL->paramHasAttr(Idx, ParamAttr::SExt));
1950       PrintedArg = true;
1951       ++Idx;
1952     }
1953   }
1954
1955   // Finish printing arguments... if this is a vararg function, print the ...,
1956   // unless there are no known types, in which case, we just emit ().
1957   //
1958   if (FT->isVarArg() && PrintedArg) {
1959     if (PrintedArg) FunctionInnards << ", ";
1960     FunctionInnards << "...";  // Output varargs portion of signature!
1961   } else if (!FT->isVarArg() && !PrintedArg) {
1962     FunctionInnards << "void"; // ret() -> ret(void) in C.
1963   }
1964   FunctionInnards << ')';
1965   
1966   // Get the return tpe for the function.
1967   const Type *RetTy;
1968   if (!isStructReturn)
1969     RetTy = F->getReturnType();
1970   else {
1971     // If this is a struct-return function, print the struct-return type.
1972     RetTy = cast<PointerType>(FT->getParamType(0))->getElementType();
1973   }
1974     
1975   // Print out the return type and the signature built above.
1976   printType(Out, RetTy, 
1977             /*isSigned=*/ PAL && PAL->paramHasAttr(0, ParamAttr::SExt),
1978             FunctionInnards.str());
1979 }
1980
1981 static inline bool isFPIntBitCast(const Instruction &I) {
1982   if (!isa<BitCastInst>(I))
1983     return false;
1984   const Type *SrcTy = I.getOperand(0)->getType();
1985   const Type *DstTy = I.getType();
1986   return (SrcTy->isFloatingPoint() && DstTy->isInteger()) ||
1987          (DstTy->isFloatingPoint() && SrcTy->isInteger());
1988 }
1989
1990 void CWriter::printFunction(Function &F) {
1991   /// isStructReturn - Should this function actually return a struct by-value?
1992   bool isStructReturn = F.isStructReturn();
1993
1994   printFunctionSignature(&F, false);
1995   Out << " {\n";
1996   
1997   // If this is a struct return function, handle the result with magic.
1998   if (isStructReturn) {
1999     const Type *StructTy =
2000       cast<PointerType>(F.arg_begin()->getType())->getElementType();
2001     Out << "  ";
2002     printType(Out, StructTy, false, "StructReturn");
2003     Out << ";  /* Struct return temporary */\n";
2004
2005     Out << "  ";
2006     printType(Out, F.arg_begin()->getType(), false, 
2007               GetValueName(F.arg_begin()));
2008     Out << " = &StructReturn;\n";
2009   }
2010
2011   bool PrintedVar = false;
2012   
2013   // print local variable information for the function
2014   for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
2015     if (const AllocaInst *AI = isDirectAlloca(&*I)) {
2016       Out << "  ";
2017       printType(Out, AI->getAllocatedType(), false, GetValueName(AI));
2018       Out << ";    /* Address-exposed local */\n";
2019       PrintedVar = true;
2020     } else if (I->getType() != Type::VoidTy && !isInlinableInst(*I)) {
2021       Out << "  ";
2022       printType(Out, I->getType(), false, GetValueName(&*I));
2023       Out << ";\n";
2024
2025       if (isa<PHINode>(*I)) {  // Print out PHI node temporaries as well...
2026         Out << "  ";
2027         printType(Out, I->getType(), false,
2028                   GetValueName(&*I)+"__PHI_TEMPORARY");
2029         Out << ";\n";
2030       }
2031       PrintedVar = true;
2032     }
2033     // We need a temporary for the BitCast to use so it can pluck a value out
2034     // of a union to do the BitCast. This is separate from the need for a
2035     // variable to hold the result of the BitCast. 
2036     if (isFPIntBitCast(*I)) {
2037       Out << "  llvmBitCastUnion " << GetValueName(&*I)
2038           << "__BITCAST_TEMPORARY;\n";
2039       PrintedVar = true;
2040     }
2041   }
2042
2043   if (PrintedVar)
2044     Out << '\n';
2045
2046   if (F.hasExternalLinkage() && F.getName() == "main")
2047     Out << "  CODE_FOR_MAIN();\n";
2048
2049   // print the basic blocks
2050   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
2051     if (Loop *L = LI->getLoopFor(BB)) {
2052       if (L->getHeader() == BB && L->getParentLoop() == 0)
2053         printLoop(L);
2054     } else {
2055       printBasicBlock(BB);
2056     }
2057   }
2058
2059   Out << "}\n\n";
2060 }
2061
2062 void CWriter::printLoop(Loop *L) {
2063   Out << "  do {     /* Syntactic loop '" << L->getHeader()->getName()
2064       << "' to make GCC happy */\n";
2065   for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
2066     BasicBlock *BB = L->getBlocks()[i];
2067     Loop *BBLoop = LI->getLoopFor(BB);
2068     if (BBLoop == L)
2069       printBasicBlock(BB);
2070     else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
2071       printLoop(BBLoop);
2072   }
2073   Out << "  } while (1); /* end of syntactic loop '"
2074       << L->getHeader()->getName() << "' */\n";
2075 }
2076
2077 void CWriter::printBasicBlock(BasicBlock *BB) {
2078
2079   // Don't print the label for the basic block if there are no uses, or if
2080   // the only terminator use is the predecessor basic block's terminator.
2081   // We have to scan the use list because PHI nodes use basic blocks too but
2082   // do not require a label to be generated.
2083   //
2084   bool NeedsLabel = false;
2085   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
2086     if (isGotoCodeNecessary(*PI, BB)) {
2087       NeedsLabel = true;
2088       break;
2089     }
2090
2091   if (NeedsLabel) Out << GetValueName(BB) << ":\n";
2092
2093   // Output all of the instructions in the basic block...
2094   for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
2095        ++II) {
2096     if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
2097       if (II->getType() != Type::VoidTy && !isInlineAsm(*II))
2098         outputLValue(II);
2099       else
2100         Out << "  ";
2101       visit(*II);
2102       Out << ";\n";
2103     }
2104   }
2105
2106   // Don't emit prefix or suffix for the terminator...
2107   visit(*BB->getTerminator());
2108 }
2109
2110
2111 // Specific Instruction type classes... note that all of the casts are
2112 // necessary because we use the instruction classes as opaque types...
2113 //
2114 void CWriter::visitReturnInst(ReturnInst &I) {
2115   // If this is a struct return function, return the temporary struct.
2116   bool isStructReturn = I.getParent()->getParent()->isStructReturn();
2117
2118   if (isStructReturn) {
2119     Out << "  return StructReturn;\n";
2120     return;
2121   }
2122   
2123   // Don't output a void return if this is the last basic block in the function
2124   if (I.getNumOperands() == 0 &&
2125       &*--I.getParent()->getParent()->end() == I.getParent() &&
2126       !I.getParent()->size() == 1) {
2127     return;
2128   }
2129
2130   Out << "  return";
2131   if (I.getNumOperands()) {
2132     Out << ' ';
2133     writeOperand(I.getOperand(0));
2134   }
2135   Out << ";\n";
2136 }
2137
2138 void CWriter::visitSwitchInst(SwitchInst &SI) {
2139
2140   Out << "  switch (";
2141   writeOperand(SI.getOperand(0));
2142   Out << ") {\n  default:\n";
2143   printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
2144   printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
2145   Out << ";\n";
2146   for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
2147     Out << "  case ";
2148     writeOperand(SI.getOperand(i));
2149     Out << ":\n";
2150     BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
2151     printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
2152     printBranchToBlock(SI.getParent(), Succ, 2);
2153     if (Function::iterator(Succ) == next(Function::iterator(SI.getParent())))
2154       Out << "    break;\n";
2155   }
2156   Out << "  }\n";
2157 }
2158
2159 void CWriter::visitUnreachableInst(UnreachableInst &I) {
2160   Out << "  /*UNREACHABLE*/;\n";
2161 }
2162
2163 bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
2164   /// FIXME: This should be reenabled, but loop reordering safe!!
2165   return true;
2166
2167   if (next(Function::iterator(From)) != Function::iterator(To))
2168     return true;  // Not the direct successor, we need a goto.
2169
2170   //isa<SwitchInst>(From->getTerminator())
2171
2172   if (LI->getLoopFor(From) != LI->getLoopFor(To))
2173     return true;
2174   return false;
2175 }
2176
2177 void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
2178                                           BasicBlock *Successor,
2179                                           unsigned Indent) {
2180   for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
2181     PHINode *PN = cast<PHINode>(I);
2182     // Now we have to do the printing.
2183     Value *IV = PN->getIncomingValueForBlock(CurBlock);
2184     if (!isa<UndefValue>(IV)) {
2185       Out << std::string(Indent, ' ');
2186       Out << "  " << GetValueName(I) << "__PHI_TEMPORARY = ";
2187       writeOperand(IV);
2188       Out << ";   /* for PHI node */\n";
2189     }
2190   }
2191 }
2192
2193 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
2194                                  unsigned Indent) {
2195   if (isGotoCodeNecessary(CurBB, Succ)) {
2196     Out << std::string(Indent, ' ') << "  goto ";
2197     writeOperand(Succ);
2198     Out << ";\n";
2199   }
2200 }
2201
2202 // Branch instruction printing - Avoid printing out a branch to a basic block
2203 // that immediately succeeds the current one.
2204 //
2205 void CWriter::visitBranchInst(BranchInst &I) {
2206
2207   if (I.isConditional()) {
2208     if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
2209       Out << "  if (";
2210       writeOperand(I.getCondition());
2211       Out << ") {\n";
2212
2213       printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
2214       printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
2215
2216       if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
2217         Out << "  } else {\n";
2218         printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
2219         printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
2220       }
2221     } else {
2222       // First goto not necessary, assume second one is...
2223       Out << "  if (!";
2224       writeOperand(I.getCondition());
2225       Out << ") {\n";
2226
2227       printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
2228       printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
2229     }
2230
2231     Out << "  }\n";
2232   } else {
2233     printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
2234     printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
2235   }
2236   Out << "\n";
2237 }
2238
2239 // PHI nodes get copied into temporary values at the end of predecessor basic
2240 // blocks.  We now need to copy these temporary values into the REAL value for
2241 // the PHI.
2242 void CWriter::visitPHINode(PHINode &I) {
2243   writeOperand(&I);
2244   Out << "__PHI_TEMPORARY";
2245 }
2246
2247
2248 void CWriter::visitBinaryOperator(Instruction &I) {
2249   // binary instructions, shift instructions, setCond instructions.
2250   assert(!isa<PointerType>(I.getType()));
2251
2252   // We must cast the results of binary operations which might be promoted.
2253   bool needsCast = false;
2254   if ((I.getType() == Type::Int8Ty) || (I.getType() == Type::Int16Ty) 
2255       || (I.getType() == Type::FloatTy)) {
2256     needsCast = true;
2257     Out << "((";
2258     printType(Out, I.getType(), false);
2259     Out << ")(";
2260   }
2261
2262   // If this is a negation operation, print it out as such.  For FP, we don't
2263   // want to print "-0.0 - X".
2264   if (BinaryOperator::isNeg(&I)) {
2265     Out << "-(";
2266     writeOperand(BinaryOperator::getNegArgument(cast<BinaryOperator>(&I)));
2267     Out << ")";
2268   } else if (I.getOpcode() == Instruction::FRem) {
2269     // Output a call to fmod/fmodf instead of emitting a%b
2270     if (I.getType() == Type::FloatTy)
2271       Out << "fmodf(";
2272     else if (I.getType() == Type::DoubleTy)
2273       Out << "fmod(";
2274     else  // all 3 flavors of long double
2275       Out << "fmodl(";
2276     writeOperand(I.getOperand(0));
2277     Out << ", ";
2278     writeOperand(I.getOperand(1));
2279     Out << ")";
2280   } else {
2281
2282     // Write out the cast of the instruction's value back to the proper type
2283     // if necessary.
2284     bool NeedsClosingParens = writeInstructionCast(I);
2285
2286     // Certain instructions require the operand to be forced to a specific type
2287     // so we use writeOperandWithCast here instead of writeOperand. Similarly
2288     // below for operand 1
2289     writeOperandWithCast(I.getOperand(0), I.getOpcode());
2290
2291     switch (I.getOpcode()) {
2292     case Instruction::Add:  Out << " + "; break;
2293     case Instruction::Sub:  Out << " - "; break;
2294     case Instruction::Mul:  Out << " * "; break;
2295     case Instruction::URem:
2296     case Instruction::SRem:
2297     case Instruction::FRem: Out << " % "; break;
2298     case Instruction::UDiv:
2299     case Instruction::SDiv: 
2300     case Instruction::FDiv: Out << " / "; break;
2301     case Instruction::And:  Out << " & "; break;
2302     case Instruction::Or:   Out << " | "; break;
2303     case Instruction::Xor:  Out << " ^ "; break;
2304     case Instruction::Shl : Out << " << "; break;
2305     case Instruction::LShr:
2306     case Instruction::AShr: Out << " >> "; break;
2307     default: cerr << "Invalid operator type!" << I; abort();
2308     }
2309
2310     writeOperandWithCast(I.getOperand(1), I.getOpcode());
2311     if (NeedsClosingParens)
2312       Out << "))";
2313   }
2314
2315   if (needsCast) {
2316     Out << "))";
2317   }
2318 }
2319
2320 void CWriter::visitICmpInst(ICmpInst &I) {
2321   // We must cast the results of icmp which might be promoted.
2322   bool needsCast = false;
2323
2324   // Write out the cast of the instruction's value back to the proper type
2325   // if necessary.
2326   bool NeedsClosingParens = writeInstructionCast(I);
2327
2328   // Certain icmp predicate require the operand to be forced to a specific type
2329   // so we use writeOperandWithCast here instead of writeOperand. Similarly
2330   // below for operand 1
2331   writeOperandWithCast(I.getOperand(0), I);
2332
2333   switch (I.getPredicate()) {
2334   case ICmpInst::ICMP_EQ:  Out << " == "; break;
2335   case ICmpInst::ICMP_NE:  Out << " != "; break;
2336   case ICmpInst::ICMP_ULE:
2337   case ICmpInst::ICMP_SLE: Out << " <= "; break;
2338   case ICmpInst::ICMP_UGE:
2339   case ICmpInst::ICMP_SGE: Out << " >= "; break;
2340   case ICmpInst::ICMP_ULT:
2341   case ICmpInst::ICMP_SLT: Out << " < "; break;
2342   case ICmpInst::ICMP_UGT:
2343   case ICmpInst::ICMP_SGT: Out << " > "; break;
2344   default: cerr << "Invalid icmp predicate!" << I; abort();
2345   }
2346
2347   writeOperandWithCast(I.getOperand(1), I);
2348   if (NeedsClosingParens)
2349     Out << "))";
2350
2351   if (needsCast) {
2352     Out << "))";
2353   }
2354 }
2355
2356 void CWriter::visitFCmpInst(FCmpInst &I) {
2357   if (I.getPredicate() == FCmpInst::FCMP_FALSE) {
2358     Out << "0";
2359     return;
2360   }
2361   if (I.getPredicate() == FCmpInst::FCMP_TRUE) {
2362     Out << "1";
2363     return;
2364   }
2365
2366   const char* op = 0;
2367   switch (I.getPredicate()) {
2368   default: assert(0 && "Illegal FCmp predicate");
2369   case FCmpInst::FCMP_ORD: op = "ord"; break;
2370   case FCmpInst::FCMP_UNO: op = "uno"; break;
2371   case FCmpInst::FCMP_UEQ: op = "ueq"; break;
2372   case FCmpInst::FCMP_UNE: op = "une"; break;
2373   case FCmpInst::FCMP_ULT: op = "ult"; break;
2374   case FCmpInst::FCMP_ULE: op = "ule"; break;
2375   case FCmpInst::FCMP_UGT: op = "ugt"; break;
2376   case FCmpInst::FCMP_UGE: op = "uge"; break;
2377   case FCmpInst::FCMP_OEQ: op = "oeq"; break;
2378   case FCmpInst::FCMP_ONE: op = "one"; break;
2379   case FCmpInst::FCMP_OLT: op = "olt"; break;
2380   case FCmpInst::FCMP_OLE: op = "ole"; break;
2381   case FCmpInst::FCMP_OGT: op = "ogt"; break;
2382   case FCmpInst::FCMP_OGE: op = "oge"; break;
2383   }
2384
2385   Out << "llvm_fcmp_" << op << "(";
2386   // Write the first operand
2387   writeOperand(I.getOperand(0));
2388   Out << ", ";
2389   // Write the second operand
2390   writeOperand(I.getOperand(1));
2391   Out << ")";
2392 }
2393
2394 static const char * getFloatBitCastField(const Type *Ty) {
2395   switch (Ty->getTypeID()) {
2396     default: assert(0 && "Invalid Type");
2397     case Type::FloatTyID:  return "Float";
2398     case Type::DoubleTyID: return "Double";
2399     case Type::IntegerTyID: {
2400       unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
2401       if (NumBits <= 32)
2402         return "Int32";
2403       else
2404         return "Int64";
2405     }
2406   }
2407 }
2408
2409 void CWriter::visitCastInst(CastInst &I) {
2410   const Type *DstTy = I.getType();
2411   const Type *SrcTy = I.getOperand(0)->getType();
2412   Out << '(';
2413   if (isFPIntBitCast(I)) {
2414     // These int<->float and long<->double casts need to be handled specially
2415     Out << GetValueName(&I) << "__BITCAST_TEMPORARY." 
2416         << getFloatBitCastField(I.getOperand(0)->getType()) << " = ";
2417     writeOperand(I.getOperand(0));
2418     Out << ", " << GetValueName(&I) << "__BITCAST_TEMPORARY."
2419         << getFloatBitCastField(I.getType());
2420   } else {
2421     printCast(I.getOpcode(), SrcTy, DstTy);
2422     if (I.getOpcode() == Instruction::SExt && SrcTy == Type::Int1Ty) {
2423       // Make sure we really get a sext from bool by subtracing the bool from 0
2424       Out << "0-";
2425     }
2426     // If it's a byval parameter being casted, then takes its address.
2427     bool isByVal = ByValParams.count(I.getOperand(0));
2428     if (isByVal) {
2429       assert(I.getOpcode() == Instruction::BitCast &&
2430              "ByVal aggregate parameter must ptr type");
2431       Out << '&';
2432     }
2433     writeOperand(I.getOperand(0));
2434     if (DstTy == Type::Int1Ty && 
2435         (I.getOpcode() == Instruction::Trunc ||
2436          I.getOpcode() == Instruction::FPToUI ||
2437          I.getOpcode() == Instruction::FPToSI ||
2438          I.getOpcode() == Instruction::PtrToInt)) {
2439       // Make sure we really get a trunc to bool by anding the operand with 1 
2440       Out << "&1u";
2441     }
2442   }
2443   Out << ')';
2444 }
2445
2446 void CWriter::visitSelectInst(SelectInst &I) {
2447   Out << "((";
2448   writeOperand(I.getCondition());
2449   Out << ") ? (";
2450   writeOperand(I.getTrueValue());
2451   Out << ") : (";
2452   writeOperand(I.getFalseValue());
2453   Out << "))";
2454 }
2455
2456
2457 void CWriter::lowerIntrinsics(Function &F) {
2458   // This is used to keep track of intrinsics that get generated to a lowered
2459   // function. We must generate the prototypes before the function body which
2460   // will only be expanded on first use (by the loop below).
2461   std::vector<Function*> prototypesToGen;
2462
2463   // Examine all the instructions in this function to find the intrinsics that
2464   // need to be lowered.
2465   for (Function::iterator BB = F.begin(), EE = F.end(); BB != EE; ++BB)
2466     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
2467       if (CallInst *CI = dyn_cast<CallInst>(I++))
2468         if (Function *F = CI->getCalledFunction())
2469           switch (F->getIntrinsicID()) {
2470           case Intrinsic::not_intrinsic:
2471           case Intrinsic::memory_barrier:
2472           case Intrinsic::vastart:
2473           case Intrinsic::vacopy:
2474           case Intrinsic::vaend:
2475           case Intrinsic::returnaddress:
2476           case Intrinsic::frameaddress:
2477           case Intrinsic::setjmp:
2478           case Intrinsic::longjmp:
2479           case Intrinsic::prefetch:
2480           case Intrinsic::dbg_stoppoint:
2481           case Intrinsic::powi:
2482             // We directly implement these intrinsics
2483             break;
2484           default:
2485             // If this is an intrinsic that directly corresponds to a GCC
2486             // builtin, we handle it.
2487             const char *BuiltinName = "";
2488 #define GET_GCC_BUILTIN_NAME
2489 #include "llvm/Intrinsics.gen"
2490 #undef GET_GCC_BUILTIN_NAME
2491             // If we handle it, don't lower it.
2492             if (BuiltinName[0]) break;
2493             
2494             // All other intrinsic calls we must lower.
2495             Instruction *Before = 0;
2496             if (CI != &BB->front())
2497               Before = prior(BasicBlock::iterator(CI));
2498
2499             IL->LowerIntrinsicCall(CI);
2500             if (Before) {        // Move iterator to instruction after call
2501               I = Before; ++I;
2502             } else {
2503               I = BB->begin();
2504             }
2505             // If the intrinsic got lowered to another call, and that call has
2506             // a definition then we need to make sure its prototype is emitted
2507             // before any calls to it.
2508             if (CallInst *Call = dyn_cast<CallInst>(I))
2509               if (Function *NewF = Call->getCalledFunction())
2510                 if (!NewF->isDeclaration())
2511                   prototypesToGen.push_back(NewF);
2512
2513             break;
2514           }
2515
2516   // We may have collected some prototypes to emit in the loop above. 
2517   // Emit them now, before the function that uses them is emitted. But,
2518   // be careful not to emit them twice.
2519   std::vector<Function*>::iterator I = prototypesToGen.begin();
2520   std::vector<Function*>::iterator E = prototypesToGen.end();
2521   for ( ; I != E; ++I) {
2522     if (intrinsicPrototypesAlreadyGenerated.insert(*I).second) {
2523       Out << '\n';
2524       printFunctionSignature(*I, true);
2525       Out << ";\n";
2526     }
2527   }
2528 }
2529
2530
2531 void CWriter::visitCallInst(CallInst &I) {
2532   //check if we have inline asm
2533   if (isInlineAsm(I)) {
2534     visitInlineAsm(I);
2535     return;
2536   }
2537
2538   bool WroteCallee = false;
2539
2540   // Handle intrinsic function calls first...
2541   if (Function *F = I.getCalledFunction())
2542     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
2543       switch (ID) {
2544       default: {
2545         // If this is an intrinsic that directly corresponds to a GCC
2546         // builtin, we emit it here.
2547         const char *BuiltinName = "";
2548 #define GET_GCC_BUILTIN_NAME
2549 #include "llvm/Intrinsics.gen"
2550 #undef GET_GCC_BUILTIN_NAME
2551         assert(BuiltinName[0] && "Unknown LLVM intrinsic!");
2552
2553         Out << BuiltinName;
2554         WroteCallee = true;
2555         break;
2556       }
2557       case Intrinsic::memory_barrier:
2558         Out << "0; __sync_syncronize()";
2559         return;
2560       case Intrinsic::vastart:
2561         Out << "0; ";
2562
2563         Out << "va_start(*(va_list*)";
2564         writeOperand(I.getOperand(1));
2565         Out << ", ";
2566         // Output the last argument to the enclosing function...
2567         if (I.getParent()->getParent()->arg_empty()) {
2568           cerr << "The C backend does not currently support zero "
2569                << "argument varargs functions, such as '"
2570                << I.getParent()->getParent()->getName() << "'!\n";
2571           abort();
2572         }
2573         writeOperand(--I.getParent()->getParent()->arg_end());
2574         Out << ')';
2575         return;
2576       case Intrinsic::vaend:
2577         if (!isa<ConstantPointerNull>(I.getOperand(1))) {
2578           Out << "0; va_end(*(va_list*)";
2579           writeOperand(I.getOperand(1));
2580           Out << ')';
2581         } else {
2582           Out << "va_end(*(va_list*)0)";
2583         }
2584         return;
2585       case Intrinsic::vacopy:
2586         Out << "0; ";
2587         Out << "va_copy(*(va_list*)";
2588         writeOperand(I.getOperand(1));
2589         Out << ", *(va_list*)";
2590         writeOperand(I.getOperand(2));
2591         Out << ')';
2592         return;
2593       case Intrinsic::returnaddress:
2594         Out << "__builtin_return_address(";
2595         writeOperand(I.getOperand(1));
2596         Out << ')';
2597         return;
2598       case Intrinsic::frameaddress:
2599         Out << "__builtin_frame_address(";
2600         writeOperand(I.getOperand(1));
2601         Out << ')';
2602         return;
2603       case Intrinsic::powi:
2604         Out << "__builtin_powi(";
2605         writeOperand(I.getOperand(1));
2606         Out << ", ";
2607         writeOperand(I.getOperand(2));
2608         Out << ')';
2609         return;
2610       case Intrinsic::setjmp:
2611         Out << "setjmp(*(jmp_buf*)";
2612         writeOperand(I.getOperand(1));
2613         Out << ')';
2614         return;
2615       case Intrinsic::longjmp:
2616         Out << "longjmp(*(jmp_buf*)";
2617         writeOperand(I.getOperand(1));
2618         Out << ", ";
2619         writeOperand(I.getOperand(2));
2620         Out << ')';
2621         return;
2622       case Intrinsic::prefetch:
2623         Out << "LLVM_PREFETCH((const void *)";
2624         writeOperand(I.getOperand(1));
2625         Out << ", ";
2626         writeOperand(I.getOperand(2));
2627         Out << ", ";
2628         writeOperand(I.getOperand(3));
2629         Out << ")";
2630         return;
2631       case Intrinsic::stacksave:
2632         // Emit this as: Val = 0; *((void**)&Val) = __builtin_stack_save()
2633         // to work around GCC bugs (see PR1809).
2634         Out << "0; *((void**)&" << GetValueName(&I)
2635             << ") = __builtin_stack_save()";
2636         return;
2637       case Intrinsic::dbg_stoppoint: {
2638         // If we use writeOperand directly we get a "u" suffix which is rejected
2639         // by gcc.
2640         DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
2641
2642         Out << "\n#line "
2643             << SPI.getLine()
2644             << " \"" << SPI.getDirectory()
2645             << SPI.getFileName() << "\"\n";
2646         return;
2647       }
2648       }
2649     }
2650
2651   Value *Callee = I.getCalledValue();
2652
2653   const PointerType  *PTy   = cast<PointerType>(Callee->getType());
2654   const FunctionType *FTy   = cast<FunctionType>(PTy->getElementType());
2655
2656   // If this is a call to a struct-return function, assign to the first
2657   // parameter instead of passing it to the call.
2658   const ParamAttrsList *PAL = I.getParamAttrs();
2659   bool hasByVal = I.hasByValArgument();
2660   bool isStructRet = I.isStructReturn();
2661   if (isStructRet) {
2662     bool isByVal = ByValParams.count(I.getOperand(1));
2663     if (!isByVal) Out << "*(";
2664     writeOperand(I.getOperand(1));
2665     if (!isByVal) Out << ")";
2666     Out << " = ";
2667   }
2668   
2669   if (I.isTailCall()) Out << " /*tail*/ ";
2670   
2671   if (!WroteCallee) {
2672     // If this is an indirect call to a struct return function, we need to cast
2673     // the pointer. Ditto for indirect calls with byval arguments.
2674     bool NeedsCast = (hasByVal || isStructRet) && !isa<Function>(Callee);
2675
2676     // GCC is a real PITA.  It does not permit codegening casts of functions to
2677     // function pointers if they are in a call (it generates a trap instruction
2678     // instead!).  We work around this by inserting a cast to void* in between
2679     // the function and the function pointer cast.  Unfortunately, we can't just
2680     // form the constant expression here, because the folder will immediately
2681     // nuke it.
2682     //
2683     // Note finally, that this is completely unsafe.  ANSI C does not guarantee
2684     // that void* and function pointers have the same size. :( To deal with this
2685     // in the common case, we handle casts where the number of arguments passed
2686     // match exactly.
2687     //
2688     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee))
2689       if (CE->isCast())
2690         if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) {
2691           NeedsCast = true;
2692           Callee = RF;
2693         }
2694   
2695     if (NeedsCast) {
2696       // Ok, just cast the pointer type.
2697       Out << "((";
2698       if (isStructRet)
2699         printStructReturnPointerFunctionType(Out, PAL,
2700                              cast<PointerType>(I.getCalledValue()->getType()));
2701       else if (hasByVal)
2702         printType(Out, I.getCalledValue()->getType(), false, "", true, PAL);
2703       else
2704         printType(Out, I.getCalledValue()->getType());
2705       Out << ")(void*)";
2706     }
2707     writeOperand(Callee);
2708     if (NeedsCast) Out << ')';
2709   }
2710
2711   Out << '(';
2712
2713   unsigned NumDeclaredParams = FTy->getNumParams();
2714
2715   CallSite::arg_iterator AI = I.op_begin()+1, AE = I.op_end();
2716   unsigned ArgNo = 0;
2717   if (isStructRet) {   // Skip struct return argument.
2718     ++AI;
2719     ++ArgNo;
2720   }
2721       
2722   bool PrintedArg = false;
2723   for (; AI != AE; ++AI, ++ArgNo) {
2724     if (PrintedArg) Out << ", ";
2725     if (ArgNo < NumDeclaredParams &&
2726         (*AI)->getType() != FTy->getParamType(ArgNo)) {
2727       Out << '(';
2728       printType(Out, FTy->getParamType(ArgNo), 
2729             /*isSigned=*/PAL && PAL->paramHasAttr(ArgNo+1, ParamAttr::SExt));
2730       Out << ')';
2731     }
2732     // Check if the argument is expected to be passed by value.
2733     bool isOutByVal = PAL && PAL->paramHasAttr(ArgNo+1, ParamAttr::ByVal);
2734     // Check if this argument itself is passed in by reference. 
2735     bool isInByVal = ByValParams.count(*AI);
2736     if (isOutByVal && !isInByVal)
2737       Out << "*(";
2738     else if (!isOutByVal && isInByVal)
2739       Out << "&(";
2740     writeOperand(*AI);
2741     if (isOutByVal ^ isInByVal)
2742       Out << ")";
2743     PrintedArg = true;
2744   }
2745   Out << ')';
2746 }
2747
2748
2749 //This converts the llvm constraint string to something gcc is expecting.
2750 //TODO: work out platform independent constraints and factor those out
2751 //      of the per target tables
2752 //      handle multiple constraint codes
2753 std::string CWriter::InterpretASMConstraint(InlineAsm::ConstraintInfo& c) {
2754
2755   assert(c.Codes.size() == 1 && "Too many asm constraint codes to handle");
2756
2757   const char** table = 0;
2758   
2759   //Grab the translation table from TargetAsmInfo if it exists
2760   if (!TAsm) {
2761     std::string E;
2762     const TargetMachineRegistry::entry* Match = 
2763       TargetMachineRegistry::getClosestStaticTargetForModule(*TheModule, E);
2764     if (Match) {
2765       //Per platform Target Machines don't exist, so create it
2766       // this must be done only once
2767       const TargetMachine* TM = Match->CtorFn(*TheModule, "");
2768       TAsm = TM->getTargetAsmInfo();
2769     }
2770   }
2771   if (TAsm)
2772     table = TAsm->getAsmCBE();
2773
2774   //Search the translation table if it exists
2775   for (int i = 0; table && table[i]; i += 2)
2776     if (c.Codes[0] == table[i])
2777       return table[i+1];
2778
2779   //default is identity
2780   return c.Codes[0];
2781 }
2782
2783 //TODO: import logic from AsmPrinter.cpp
2784 static std::string gccifyAsm(std::string asmstr) {
2785   for (std::string::size_type i = 0; i != asmstr.size(); ++i)
2786     if (asmstr[i] == '\n')
2787       asmstr.replace(i, 1, "\\n");
2788     else if (asmstr[i] == '\t')
2789       asmstr.replace(i, 1, "\\t");
2790     else if (asmstr[i] == '$') {
2791       if (asmstr[i + 1] == '{') {
2792         std::string::size_type a = asmstr.find_first_of(':', i + 1);
2793         std::string::size_type b = asmstr.find_first_of('}', i + 1);
2794         std::string n = "%" + 
2795           asmstr.substr(a + 1, b - a - 1) +
2796           asmstr.substr(i + 2, a - i - 2);
2797         asmstr.replace(i, b - i + 1, n);
2798         i += n.size() - 1;
2799       } else
2800         asmstr.replace(i, 1, "%");
2801     }
2802     else if (asmstr[i] == '%')//grr
2803       { asmstr.replace(i, 1, "%%"); ++i;}
2804   
2805   return asmstr;
2806 }
2807
2808 //TODO: assumptions about what consume arguments from the call are likely wrong
2809 //      handle communitivity
2810 void CWriter::visitInlineAsm(CallInst &CI) {
2811   InlineAsm* as = cast<InlineAsm>(CI.getOperand(0));
2812   std::vector<InlineAsm::ConstraintInfo> Constraints = as->ParseConstraints();
2813   std::vector<std::pair<std::string, Value*> > Input;
2814   std::vector<std::pair<std::string, Value*> > Output;
2815   std::string Clobber;
2816   int count = CI.getType() == Type::VoidTy ? 1 : 0;
2817   for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
2818          E = Constraints.end(); I != E; ++I) {
2819     assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
2820     std::string c = 
2821       InterpretASMConstraint(*I);
2822     switch(I->Type) {
2823     default:
2824       assert(0 && "Unknown asm constraint");
2825       break;
2826     case InlineAsm::isInput: {
2827       if (c.size()) {
2828         Input.push_back(std::make_pair(c, count ? CI.getOperand(count) : &CI));
2829         ++count; //consume arg
2830       }
2831       break;
2832     }
2833     case InlineAsm::isOutput: {
2834       if (c.size()) {
2835         Output.push_back(std::make_pair("="+((I->isEarlyClobber ? "&" : "")+c),
2836                                         count ? CI.getOperand(count) : &CI));
2837         ++count; //consume arg
2838       }
2839       break;
2840     }
2841     case InlineAsm::isClobber: {
2842       if (c.size()) 
2843         Clobber += ",\"" + c + "\"";
2844       break;
2845     }
2846     }
2847   }
2848   
2849   //fix up the asm string for gcc
2850   std::string asmstr = gccifyAsm(as->getAsmString());
2851   
2852   Out << "__asm__ volatile (\"" << asmstr << "\"\n";
2853   Out << "        :";
2854   for (std::vector<std::pair<std::string, Value*> >::iterator I = Output.begin(),
2855          E = Output.end(); I != E; ++I) {
2856     Out << "\"" << I->first << "\"(";
2857     writeOperandRaw(I->second);
2858     Out << ")";
2859     if (I + 1 != E)
2860       Out << ",";
2861   }
2862   Out << "\n        :";
2863   for (std::vector<std::pair<std::string, Value*> >::iterator I = Input.begin(),
2864          E = Input.end(); I != E; ++I) {
2865     Out << "\"" << I->first << "\"(";
2866     writeOperandRaw(I->second);
2867     Out << ")";
2868     if (I + 1 != E)
2869       Out << ",";
2870   }
2871   if (Clobber.size())
2872     Out << "\n        :" << Clobber.substr(1);
2873   Out << ")";
2874 }
2875
2876 void CWriter::visitMallocInst(MallocInst &I) {
2877   assert(0 && "lowerallocations pass didn't work!");
2878 }
2879
2880 void CWriter::visitAllocaInst(AllocaInst &I) {
2881   Out << '(';
2882   printType(Out, I.getType());
2883   Out << ") alloca(sizeof(";
2884   printType(Out, I.getType()->getElementType());
2885   Out << ')';
2886   if (I.isArrayAllocation()) {
2887     Out << " * " ;
2888     writeOperand(I.getOperand(0));
2889   }
2890   Out << ')';
2891 }
2892
2893 void CWriter::visitFreeInst(FreeInst &I) {
2894   assert(0 && "lowerallocations pass didn't work!");
2895 }
2896
2897 void CWriter::printIndexingExpression(Value *Ptr, gep_type_iterator I,
2898                                       gep_type_iterator E) {
2899   bool HasImplicitAddress = false;
2900   // If accessing a global value with no indexing, avoid *(&GV) syndrome
2901   if (isa<GlobalValue>(Ptr)) {
2902     HasImplicitAddress = true;
2903   } else if (isDirectAlloca(Ptr)) {
2904     HasImplicitAddress = true;
2905   }
2906
2907   if (I == E) {
2908     if (!HasImplicitAddress)
2909       Out << '*';  // Implicit zero first argument: '*x' is equivalent to 'x[0]'
2910
2911     writeOperandInternal(Ptr);
2912     return;
2913   }
2914
2915   const Constant *CI = dyn_cast<Constant>(I.getOperand());
2916   if (HasImplicitAddress && (!CI || !CI->isNullValue()))
2917     Out << "(&";
2918
2919   writeOperandInternal(Ptr);
2920
2921   if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
2922     Out << ')';
2923     HasImplicitAddress = false;  // HIA is only true if we haven't addressed yet
2924   }
2925
2926   assert((!HasImplicitAddress || (CI && CI->isNullValue())) &&
2927          "Can only have implicit address with direct accessing");
2928
2929   if (HasImplicitAddress) {
2930     ++I;
2931   } else if (CI && CI->isNullValue()) {
2932     gep_type_iterator TmpI = I; ++TmpI;
2933
2934     // Print out the -> operator if possible...
2935     if (TmpI != E && isa<StructType>(*TmpI)) {
2936       // Check if it's actually an aggregate parameter passed by value.
2937       bool isByVal = ByValParams.count(Ptr);
2938       Out << ((HasImplicitAddress || isByVal) ? "." : "->");
2939       Out << "field" << cast<ConstantInt>(TmpI.getOperand())->getZExtValue();
2940       I = ++TmpI;
2941     }
2942   }
2943
2944   for (; I != E; ++I)
2945     if (isa<StructType>(*I)) {
2946       Out << ".field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
2947     } else {
2948       Out << '[';
2949       writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
2950       Out << ']';
2951     }
2952 }
2953
2954 void CWriter::writeMemoryAccess(Value *Operand, const Type *OperandType,
2955                                 bool IsVolatile, unsigned Alignment) {
2956
2957   bool IsUnaligned = Alignment &&
2958     Alignment < TD->getABITypeAlignment(OperandType);
2959
2960   if (!IsUnaligned)
2961     Out << '*';
2962   if (IsVolatile || IsUnaligned) {
2963     Out << "((";
2964     if (IsUnaligned)
2965       Out << "struct __attribute__ ((packed, aligned(" << Alignment << "))) {";
2966     printType(Out, OperandType, false, IsUnaligned ? "data" : "volatile*");
2967     if (IsUnaligned) {
2968       Out << "; } ";
2969       if (IsVolatile) Out << "volatile ";
2970       Out << "*";
2971     }
2972     Out << ")";
2973   }
2974
2975   writeOperand(Operand);
2976
2977   if (IsVolatile || IsUnaligned) {
2978     Out << ')';
2979     if (IsUnaligned)
2980       Out << "->data";
2981   }
2982 }
2983
2984 void CWriter::visitLoadInst(LoadInst &I) {
2985
2986   writeMemoryAccess(I.getOperand(0), I.getType(), I.isVolatile(),
2987                     I.getAlignment());
2988
2989 }
2990
2991 void CWriter::visitStoreInst(StoreInst &I) {
2992
2993   writeMemoryAccess(I.getPointerOperand(), I.getOperand(0)->getType(),
2994                     I.isVolatile(), I.getAlignment());
2995   Out << " = ";
2996   Value *Operand = I.getOperand(0);
2997   Constant *BitMask = 0;
2998   if (const IntegerType* ITy = dyn_cast<IntegerType>(Operand->getType()))
2999     if (!ITy->isPowerOf2ByteWidth())
3000       // We have a bit width that doesn't match an even power-of-2 byte
3001       // size. Consequently we must & the value with the type's bit mask
3002       BitMask = ConstantInt::get(ITy, ITy->getBitMask());
3003   if (BitMask)
3004     Out << "((";
3005   writeOperand(Operand);
3006   if (BitMask) {
3007     Out << ") & ";
3008     printConstant(BitMask);
3009     Out << ")"; 
3010   }
3011 }
3012
3013 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
3014   Out << '&';
3015   printIndexingExpression(I.getPointerOperand(), gep_type_begin(I),
3016                           gep_type_end(I));
3017 }
3018
3019 void CWriter::visitVAArgInst(VAArgInst &I) {
3020   Out << "va_arg(*(va_list*)";
3021   writeOperand(I.getOperand(0));
3022   Out << ", ";
3023   printType(Out, I.getType());
3024   Out << ");\n ";
3025 }
3026
3027 void CWriter::visitInsertElementInst(InsertElementInst &I) {
3028   const Type *EltTy = I.getType()->getElementType();
3029   writeOperand(I.getOperand(0));
3030   Out << ";\n  ";
3031   Out << "((";
3032   printType(Out, PointerType::getUnqual(EltTy));
3033   Out << ")(&" << GetValueName(&I) << "))[";
3034   writeOperand(I.getOperand(1));
3035   Out << "] = (";
3036   writeOperand(I.getOperand(2));
3037   Out << ")";
3038 }
3039
3040
3041 //===----------------------------------------------------------------------===//
3042 //                       External Interface declaration
3043 //===----------------------------------------------------------------------===//
3044
3045 bool CTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
3046                                               std::ostream &o,
3047                                               CodeGenFileType FileType,
3048                                               bool Fast) {
3049   if (FileType != TargetMachine::AssemblyFile) return true;
3050
3051   PM.add(createGCLoweringPass());
3052   PM.add(createLowerAllocationsPass(true));
3053   PM.add(createLowerInvokePass());
3054   PM.add(createCFGSimplificationPass());   // clean up after lower invoke.
3055   PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
3056   PM.add(new CWriter(o));
3057   PM.add(createCollectorMetadataDeleter());
3058   return false;
3059 }