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