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