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