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