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