Fix C Backend to generate code that works with Microsoft C for the benefit of
[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 was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This library converts LLVM code to C code, compilable by GCC and other C
11 // compilers.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "CTargetMachine.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Module.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Pass.h"
22 #include "llvm/PassManager.h"
23 #include "llvm/TypeSymbolTable.h"
24 #include "llvm/Intrinsics.h"
25 #include "llvm/IntrinsicInst.h"
26 #include "llvm/InlineAsm.h"
27 #include "llvm/Analysis/ConstantsScanner.h"
28 #include "llvm/Analysis/FindUsedTypes.h"
29 #include "llvm/Analysis/LoopInfo.h"
30 #include "llvm/CodeGen/IntrinsicLowering.h"
31 #include "llvm/Transforms/Scalar.h"
32 #include "llvm/Target/TargetMachineRegistry.h"
33 #include "llvm/Target/TargetAsmInfo.h"
34 #include "llvm/Target/TargetData.h"
35 #include "llvm/Support/CallSite.h"
36 #include "llvm/Support/CFG.h"
37 #include "llvm/Support/GetElementPtrTypeIterator.h"
38 #include "llvm/Support/InstVisitor.h"
39 #include "llvm/Support/Mangler.h"
40 #include "llvm/Support/MathExtras.h"
41 #include "llvm/ADT/StringExtras.h"
42 #include "llvm/ADT/STLExtras.h"
43 #include "llvm/Support/MathExtras.h"
44 #include "llvm/Config/config.h"
45 #include <algorithm>
46 #include <sstream>
47 using namespace llvm;
48
49 namespace {
50   // Register the target.
51   RegisterTarget<CTargetMachine> X("c", "  C backend");
52
53   /// CBackendNameAllUsedStructsAndMergeFunctions - This pass inserts names for
54   /// any unnamed structure types that are used by the program, and merges
55   /// external functions with the same name.
56   ///
57   class CBackendNameAllUsedStructsAndMergeFunctions : public ModulePass {
58     void getAnalysisUsage(AnalysisUsage &AU) const {
59       AU.addRequired<FindUsedTypes>();
60     }
61
62     virtual const char *getPassName() const {
63       return "C backend type canonicalizer";
64     }
65
66     virtual bool runOnModule(Module &M);
67   };
68
69   /// CWriter - This class is the main chunk of code that converts an LLVM
70   /// module to a C translation unit.
71   class CWriter : public FunctionPass, public InstVisitor<CWriter> {
72     std::ostream &Out;
73     IntrinsicLowering *IL;
74     Mangler *Mang;
75     LoopInfo *LI;
76     const Module *TheModule;
77     const TargetAsmInfo* TAsm;
78     const TargetData* TD;
79     std::map<const Type *, std::string> TypeNames;
80
81     std::map<const ConstantFP *, unsigned> FPConstantMap;
82   public:
83     CWriter(std::ostream &o) : Out(o), IL(0), Mang(0), LI(0), TheModule(0), 
84                                TAsm(0), TD(0) {}
85
86     virtual const char *getPassName() const { return "C backend"; }
87
88     void getAnalysisUsage(AnalysisUsage &AU) const {
89       AU.addRequired<LoopInfo>();
90       AU.setPreservesAll();
91     }
92
93     virtual bool doInitialization(Module &M);
94
95     bool runOnFunction(Function &F) {
96       LI = &getAnalysis<LoopInfo>();
97
98       // Get rid of intrinsics we can't handle.
99       lowerIntrinsics(F);
100
101       // Output all floating point constants that cannot be printed accurately.
102       printFloatingPointConstants(F);
103
104       printFunction(F);
105       FPConstantMap.clear();
106       return false;
107     }
108
109     virtual bool doFinalization(Module &M) {
110       // Free memory...
111       delete Mang;
112       TypeNames.clear();
113       return false;
114     }
115
116     std::ostream &printType(std::ostream &Out, const Type *Ty, 
117                             bool isSigned = false,
118                             const std::string &VariableName = "",
119                             bool IgnoreName = false);
120     std::ostream &printSimpleType(std::ostream &Out, const Type *Ty, 
121                                      bool isSigned, 
122                                      const std::string &NameSoFar = "");
123
124     void printStructReturnPointerFunctionType(std::ostream &Out,
125                                               const PointerType *Ty);
126     
127     void writeOperand(Value *Operand);
128     void writeOperandRaw(Value *Operand);
129     void writeOperandInternal(Value *Operand);
130     void writeOperandWithCast(Value* Operand, unsigned Opcode);
131     void writeOperandWithCast(Value* Operand, ICmpInst::Predicate predicate);
132     bool writeInstructionCast(const Instruction &I);
133
134   private :
135     std::string InterpretASMConstraint(InlineAsm::ConstraintInfo& c);
136
137     void lowerIntrinsics(Function &F);
138
139     void printModule(Module *M);
140     void printModuleTypes(const TypeSymbolTable &ST);
141     void printContainedStructs(const Type *Ty, std::set<const StructType *> &);
142     void printFloatingPointConstants(Function &F);
143     void printFunctionSignature(const Function *F, bool Prototype);
144
145     void printFunction(Function &);
146     void printBasicBlock(BasicBlock *BB);
147     void printLoop(Loop *L);
148
149     void printCast(unsigned opcode, const Type *SrcTy, const Type *DstTy);
150     void printConstant(Constant *CPV);
151     void printConstantWithCast(Constant *CPV, unsigned Opcode);
152     bool printConstExprCast(const ConstantExpr *CE);
153     void printConstantArray(ConstantArray *CPA);
154     void printConstantVector(ConstantVector *CP);
155
156     // isInlinableInst - Attempt to inline instructions into their uses to build
157     // trees as much as possible.  To do this, we have to consistently decide
158     // what is acceptable to inline, so that variable declarations don't get
159     // printed and an extra copy of the expr is not emitted.
160     //
161     static bool isInlinableInst(const Instruction &I) {
162       // Always inline cmp instructions, even if they are shared by multiple
163       // expressions.  GCC generates horrible code if we don't.
164       if (isa<CmpInst>(I)) 
165         return true;
166
167       // Must be an expression, must be used exactly once.  If it is dead, we
168       // emit it inline where it would go.
169       if (I.getType() == Type::VoidTy || !I.hasOneUse() ||
170           isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
171           isa<LoadInst>(I) || isa<VAArgInst>(I))
172         // Don't inline a load across a store or other bad things!
173         return false;
174
175       // Must not be used in inline asm
176       if (I.hasOneUse() && isInlineAsm(*I.use_back())) return false;
177
178       // Only inline instruction it if it's use is in the same BB as the inst.
179       return I.getParent() == cast<Instruction>(I.use_back())->getParent();
180     }
181
182     // isDirectAlloca - Define fixed sized allocas in the entry block as direct
183     // variables which are accessed with the & operator.  This causes GCC to
184     // generate significantly better code than to emit alloca calls directly.
185     //
186     static const AllocaInst *isDirectAlloca(const Value *V) {
187       const AllocaInst *AI = dyn_cast<AllocaInst>(V);
188       if (!AI) return false;
189       if (AI->isArrayAllocation())
190         return 0;   // FIXME: we can also inline fixed size array allocas!
191       if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
192         return 0;
193       return AI;
194     }
195     
196     // isInlineAsm - Check if the instruction is a call to an inline asm chunk
197     static bool isInlineAsm(const Instruction& I) {
198       if (isa<CallInst>(&I) && isa<InlineAsm>(I.getOperand(0)))
199         return true;
200       return false;
201     }
202     
203     // Instruction visitation functions
204     friend class InstVisitor<CWriter>;
205
206     void visitReturnInst(ReturnInst &I);
207     void visitBranchInst(BranchInst &I);
208     void visitSwitchInst(SwitchInst &I);
209     void visitInvokeInst(InvokeInst &I) {
210       assert(0 && "Lowerinvoke pass didn't work!");
211     }
212
213     void visitUnwindInst(UnwindInst &I) {
214       assert(0 && "Lowerinvoke pass didn't work!");
215     }
216     void visitUnreachableInst(UnreachableInst &I);
217
218     void visitPHINode(PHINode &I);
219     void visitBinaryOperator(Instruction &I);
220     void visitICmpInst(ICmpInst &I);
221     void visitFCmpInst(FCmpInst &I);
222
223     void visitCastInst (CastInst &I);
224     void visitSelectInst(SelectInst &I);
225     void visitCallInst (CallInst &I);
226     void visitInlineAsm(CallInst &I);
227
228     void visitMallocInst(MallocInst &I);
229     void visitAllocaInst(AllocaInst &I);
230     void visitFreeInst  (FreeInst   &I);
231     void visitLoadInst  (LoadInst   &I);
232     void visitStoreInst (StoreInst  &I);
233     void visitGetElementPtrInst(GetElementPtrInst &I);
234     void visitVAArgInst (VAArgInst &I);
235
236     void visitInstruction(Instruction &I) {
237       cerr << "C Writer does not know about " << I;
238       abort();
239     }
240
241     void outputLValue(Instruction *I) {
242       Out << "  " << GetValueName(I) << " = ";
243     }
244
245     bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
246     void printPHICopiesForSuccessor(BasicBlock *CurBlock,
247                                     BasicBlock *Successor, unsigned Indent);
248     void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
249                             unsigned Indent);
250     void printIndexingExpression(Value *Ptr, gep_type_iterator I,
251                                  gep_type_iterator E);
252
253     std::string GetValueName(const Value *Operand);
254   };
255 }
256
257 /// This method inserts names for any unnamed structure types that are used by
258 /// the program, and removes names from structure types that are not used by the
259 /// program.
260 ///
261 bool CBackendNameAllUsedStructsAndMergeFunctions::runOnModule(Module &M) {
262   // Get a set of types that are used by the program...
263   std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
264
265   // Loop over the module symbol table, removing types from UT that are
266   // already named, and removing names for types that are not used.
267   //
268   TypeSymbolTable &TST = M.getTypeSymbolTable();
269   for (TypeSymbolTable::iterator TI = TST.begin(), TE = TST.end();
270        TI != TE; ) {
271     TypeSymbolTable::iterator I = TI++;
272     
273     // If this isn't a struct type, remove it from our set of types to name.
274     // This simplifies emission later.
275     if (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second)) {
276       TST.remove(I);
277     } else {
278       // If this is not used, remove it from the symbol table.
279       std::set<const Type *>::iterator UTI = UT.find(I->second);
280       if (UTI == UT.end())
281         TST.remove(I);
282       else
283         UT.erase(UTI);    // Only keep one name for this type.
284     }
285   }
286
287   // UT now contains types that are not named.  Loop over it, naming
288   // structure types.
289   //
290   bool Changed = false;
291   unsigned RenameCounter = 0;
292   for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
293        I != E; ++I)
294     if (const StructType *ST = dyn_cast<StructType>(*I)) {
295       while (M.addTypeName("unnamed"+utostr(RenameCounter), ST))
296         ++RenameCounter;
297       Changed = true;
298     }
299       
300       
301   // Loop over all external functions and globals.  If we have two with
302   // identical names, merge them.
303   // FIXME: This code should disappear when we don't allow values with the same
304   // names when they have different types!
305   std::map<std::string, GlobalValue*> ExtSymbols;
306   for (Module::iterator I = M.begin(), E = M.end(); I != E;) {
307     Function *GV = I++;
308     if (GV->isDeclaration() && GV->hasName()) {
309       std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
310         = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
311       if (!X.second) {
312         // Found a conflict, replace this global with the previous one.
313         GlobalValue *OldGV = X.first->second;
314         GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
315         GV->eraseFromParent();
316         Changed = true;
317       }
318     }
319   }
320   // Do the same for globals.
321   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
322        I != E;) {
323     GlobalVariable *GV = I++;
324     if (GV->isDeclaration() && GV->hasName()) {
325       std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
326         = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
327       if (!X.second) {
328         // Found a conflict, replace this global with the previous one.
329         GlobalValue *OldGV = X.first->second;
330         GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
331         GV->eraseFromParent();
332         Changed = true;
333       }
334     }
335   }
336   
337   return Changed;
338 }
339
340 /// printStructReturnPointerFunctionType - This is like printType for a struct
341 /// return type, except, instead of printing the type as void (*)(Struct*, ...)
342 /// print it as "Struct (*)(...)", for struct return functions.
343 void CWriter::printStructReturnPointerFunctionType(std::ostream &Out,
344                                                    const PointerType *TheTy) {
345   const FunctionType *FTy = cast<FunctionType>(TheTy->getElementType());
346   std::stringstream FunctionInnards;
347   FunctionInnards << " (*) (";
348   bool PrintedType = false;
349
350   FunctionType::param_iterator I = FTy->param_begin(), E = FTy->param_end();
351   const Type *RetTy = cast<PointerType>(I->get())->getElementType();
352   unsigned Idx = 1;
353   for (++I; I != E; ++I) {
354     if (PrintedType)
355       FunctionInnards << ", ";
356     printType(FunctionInnards, *I, 
357         /*isSigned=*/FTy->paramHasAttr(Idx, FunctionType::SExtAttribute), "");
358     PrintedType = true;
359   }
360   if (FTy->isVarArg()) {
361     if (PrintedType)
362       FunctionInnards << ", ...";
363   } else if (!PrintedType) {
364     FunctionInnards << "void";
365   }
366   FunctionInnards << ')';
367   std::string tstr = FunctionInnards.str();
368   printType(Out, RetTy, 
369       /*isSigned=*/FTy->paramHasAttr(0, FunctionType::SExtAttribute), tstr);
370 }
371
372 std::ostream &
373 CWriter::printSimpleType(std::ostream &Out, const Type *Ty, bool isSigned,
374                             const std::string &NameSoFar) {
375   assert((Ty->isPrimitiveType() || Ty->isInteger()) && 
376          "Invalid type for printSimpleType");
377   switch (Ty->getTypeID()) {
378   case Type::VoidTyID:   return Out << "void " << NameSoFar;
379   case Type::IntegerTyID: {
380     unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
381     if (NumBits == 1) 
382       return Out << "bool " << NameSoFar;
383     else if (NumBits <= 8)
384       return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
385     else if (NumBits <= 16)
386       return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
387     else if (NumBits <= 32)
388       return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
389     else { 
390       assert(NumBits <= 64 && "Bit widths > 64 not implemented yet");
391       return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
392     }
393   }
394   case Type::FloatTyID:  return Out << "float "   << NameSoFar;
395   case Type::DoubleTyID: return Out << "double "  << NameSoFar;
396   default :
397     cerr << "Unknown primitive type: " << *Ty << "\n";
398     abort();
399   }
400 }
401
402 // Pass the Type* and the variable name and this prints out the variable
403 // declaration.
404 //
405 std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
406                                  bool isSigned, const std::string &NameSoFar,
407                                  bool IgnoreName) {
408   if (Ty->isPrimitiveType() || Ty->isInteger()) {
409     printSimpleType(Out, Ty, isSigned, NameSoFar);
410     return Out;
411   }
412
413   // Check to see if the type is named.
414   if (!IgnoreName || isa<OpaqueType>(Ty)) {
415     std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
416     if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
417   }
418
419   switch (Ty->getTypeID()) {
420   case Type::FunctionTyID: {
421     const FunctionType *FTy = cast<FunctionType>(Ty);
422     std::stringstream FunctionInnards;
423     FunctionInnards << " (" << NameSoFar << ") (";
424     unsigned Idx = 1;
425     for (FunctionType::param_iterator I = FTy->param_begin(),
426            E = FTy->param_end(); I != E; ++I) {
427       if (I != FTy->param_begin())
428         FunctionInnards << ", ";
429       printType(FunctionInnards, *I, 
430          /*isSigned=*/FTy->paramHasAttr(Idx, FunctionType::SExtAttribute), "");
431       ++Idx;
432     }
433     if (FTy->isVarArg()) {
434       if (FTy->getNumParams())
435         FunctionInnards << ", ...";
436     } else if (!FTy->getNumParams()) {
437       FunctionInnards << "void";
438     }
439     FunctionInnards << ')';
440     std::string tstr = FunctionInnards.str();
441     printType(Out, FTy->getReturnType(), 
442         /*isSigned=*/FTy->paramHasAttr(0, FunctionType::SExtAttribute), tstr);
443     return Out;
444   }
445   case Type::StructTyID: {
446     const StructType *STy = cast<StructType>(Ty);
447     Out << NameSoFar + " {\n";
448     unsigned Idx = 0;
449     for (StructType::element_iterator I = STy->element_begin(),
450            E = STy->element_end(); I != E; ++I) {
451       Out << "  ";
452       printType(Out, *I, false, "field" + utostr(Idx++));
453       Out << ";\n";
454     }
455     return Out << '}';
456   }
457
458   case Type::PointerTyID: {
459     const PointerType *PTy = cast<PointerType>(Ty);
460     std::string ptrName = "*" + NameSoFar;
461
462     if (isa<ArrayType>(PTy->getElementType()) ||
463         isa<VectorType>(PTy->getElementType()))
464       ptrName = "(" + ptrName + ")";
465
466     return printType(Out, PTy->getElementType(), false, ptrName);
467   }
468
469   case Type::ArrayTyID: {
470     const ArrayType *ATy = cast<ArrayType>(Ty);
471     unsigned NumElements = ATy->getNumElements();
472     if (NumElements == 0) NumElements = 1;
473     return printType(Out, ATy->getElementType(), false,
474                      NameSoFar + "[" + utostr(NumElements) + "]");
475   }
476
477   case Type::VectorTyID: {
478     const VectorType *PTy = cast<VectorType>(Ty);
479     unsigned NumElements = PTy->getNumElements();
480     if (NumElements == 0) NumElements = 1;
481     return printType(Out, PTy->getElementType(), false,
482                      NameSoFar + "[" + utostr(NumElements) + "]");
483   }
484
485   case Type::OpaqueTyID: {
486     static int Count = 0;
487     std::string TyName = "struct opaque_" + itostr(Count++);
488     assert(TypeNames.find(Ty) == TypeNames.end());
489     TypeNames[Ty] = TyName;
490     return Out << TyName << ' ' << NameSoFar;
491   }
492   default:
493     assert(0 && "Unhandled case in getTypeProps!");
494     abort();
495   }
496
497   return Out;
498 }
499
500 void CWriter::printConstantArray(ConstantArray *CPA) {
501
502   // As a special case, print the array as a string if it is an array of
503   // ubytes or an array of sbytes with positive values.
504   //
505   const Type *ETy = CPA->getType()->getElementType();
506   bool isString = (ETy == Type::Int8Ty || ETy == Type::Int8Ty);
507
508   // Make sure the last character is a null char, as automatically added by C
509   if (isString && (CPA->getNumOperands() == 0 ||
510                    !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
511     isString = false;
512
513   if (isString) {
514     Out << '\"';
515     // Keep track of whether the last number was a hexadecimal escape
516     bool LastWasHex = false;
517
518     // Do not include the last character, which we know is null
519     for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
520       unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getZExtValue();
521
522       // Print it out literally if it is a printable character.  The only thing
523       // to be careful about is when the last letter output was a hex escape
524       // code, in which case we have to be careful not to print out hex digits
525       // explicitly (the C compiler thinks it is a continuation of the previous
526       // character, sheesh...)
527       //
528       if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
529         LastWasHex = false;
530         if (C == '"' || C == '\\')
531           Out << "\\" << C;
532         else
533           Out << C;
534       } else {
535         LastWasHex = false;
536         switch (C) {
537         case '\n': Out << "\\n"; break;
538         case '\t': Out << "\\t"; break;
539         case '\r': Out << "\\r"; break;
540         case '\v': Out << "\\v"; break;
541         case '\a': Out << "\\a"; break;
542         case '\"': Out << "\\\""; break;
543         case '\'': Out << "\\\'"; break;
544         default:
545           Out << "\\x";
546           Out << (char)(( C/16  < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
547           Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
548           LastWasHex = true;
549           break;
550         }
551       }
552     }
553     Out << '\"';
554   } else {
555     Out << '{';
556     if (CPA->getNumOperands()) {
557       Out << ' ';
558       printConstant(cast<Constant>(CPA->getOperand(0)));
559       for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
560         Out << ", ";
561         printConstant(cast<Constant>(CPA->getOperand(i)));
562       }
563     }
564     Out << " }";
565   }
566 }
567
568 void CWriter::printConstantVector(ConstantVector *CP) {
569   Out << '{';
570   if (CP->getNumOperands()) {
571     Out << ' ';
572     printConstant(cast<Constant>(CP->getOperand(0)));
573     for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
574       Out << ", ";
575       printConstant(cast<Constant>(CP->getOperand(i)));
576     }
577   }
578   Out << " }";
579 }
580
581 // isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
582 // textually as a double (rather than as a reference to a stack-allocated
583 // variable). We decide this by converting CFP to a string and back into a
584 // double, and then checking whether the conversion results in a bit-equal
585 // double to the original value of CFP. This depends on us and the target C
586 // compiler agreeing on the conversion process (which is pretty likely since we
587 // only deal in IEEE FP).
588 //
589 static bool isFPCSafeToPrint(const ConstantFP *CFP) {
590 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
591   char Buffer[100];
592   sprintf(Buffer, "%a", CFP->getValue());
593
594   if (!strncmp(Buffer, "0x", 2) ||
595       !strncmp(Buffer, "-0x", 3) ||
596       !strncmp(Buffer, "+0x", 3))
597     return atof(Buffer) == CFP->getValue();
598   return false;
599 #else
600   std::string StrVal = ftostr(CFP->getValue());
601
602   while (StrVal[0] == ' ')
603     StrVal.erase(StrVal.begin());
604
605   // Check to make sure that the stringized number is not some string like "Inf"
606   // or NaN.  Check that the string matches the "[-+]?[0-9]" regex.
607   if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
608       ((StrVal[0] == '-' || StrVal[0] == '+') &&
609        (StrVal[1] >= '0' && StrVal[1] <= '9')))
610     // Reparse stringized version!
611     return atof(StrVal.c_str()) == CFP->getValue();
612   return false;
613 #endif
614 }
615
616 /// Print out the casting for a cast operation. This does the double casting
617 /// necessary for conversion to the destination type, if necessary. 
618 /// @brief Print a cast
619 void CWriter::printCast(unsigned opc, const Type *SrcTy, const Type *DstTy) {
620   // Print the destination type cast
621   switch (opc) {
622     case Instruction::UIToFP:
623     case Instruction::SIToFP:
624     case Instruction::IntToPtr:
625     case Instruction::Trunc:
626     case Instruction::BitCast:
627     case Instruction::FPExt:
628     case Instruction::FPTrunc: // For these the DstTy sign doesn't matter
629       Out << '(';
630       printType(Out, DstTy);
631       Out << ')';
632       break;
633     case Instruction::ZExt:
634     case Instruction::PtrToInt:
635     case Instruction::FPToUI: // For these, make sure we get an unsigned dest
636       Out << '(';
637       printSimpleType(Out, DstTy, false);
638       Out << ')';
639       break;
640     case Instruction::SExt: 
641     case Instruction::FPToSI: // For these, make sure we get a signed dest
642       Out << '(';
643       printSimpleType(Out, DstTy, true);
644       Out << ')';
645       break;
646     default:
647       assert(0 && "Invalid cast opcode");
648   }
649
650   // Print the source type cast
651   switch (opc) {
652     case Instruction::UIToFP:
653     case Instruction::ZExt:
654       Out << '(';
655       printSimpleType(Out, SrcTy, false);
656       Out << ')';
657       break;
658     case Instruction::SIToFP:
659     case Instruction::SExt:
660       Out << '(';
661       printSimpleType(Out, SrcTy, true); 
662       Out << ')';
663       break;
664     case Instruction::IntToPtr:
665     case Instruction::PtrToInt:
666       // Avoid "cast to pointer from integer of different size" warnings
667       Out << "(unsigned long)";
668       break;
669     case Instruction::Trunc:
670     case Instruction::BitCast:
671     case Instruction::FPExt:
672     case Instruction::FPTrunc:
673     case Instruction::FPToSI:
674     case Instruction::FPToUI:
675       break; // These don't need a source cast.
676     default:
677       assert(0 && "Invalid cast opcode");
678       break;
679   }
680 }
681
682 // printConstant - The LLVM Constant to C Constant converter.
683 void CWriter::printConstant(Constant *CPV) {
684   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
685     switch (CE->getOpcode()) {
686     case Instruction::Trunc:
687     case Instruction::ZExt:
688     case Instruction::SExt:
689     case Instruction::FPTrunc:
690     case Instruction::FPExt:
691     case Instruction::UIToFP:
692     case Instruction::SIToFP:
693     case Instruction::FPToUI:
694     case Instruction::FPToSI:
695     case Instruction::PtrToInt:
696     case Instruction::IntToPtr:
697     case Instruction::BitCast:
698       Out << "(";
699       printCast(CE->getOpcode(), CE->getOperand(0)->getType(), CE->getType());
700       if (CE->getOpcode() == Instruction::SExt &&
701           CE->getOperand(0)->getType() == Type::Int1Ty) {
702         // Make sure we really sext from bool here by subtracting from 0
703         Out << "0-";
704       }
705       printConstant(CE->getOperand(0));
706       if (CE->getType() == Type::Int1Ty &&
707           (CE->getOpcode() == Instruction::Trunc ||
708            CE->getOpcode() == Instruction::FPToUI ||
709            CE->getOpcode() == Instruction::FPToSI ||
710            CE->getOpcode() == Instruction::PtrToInt)) {
711         // Make sure we really truncate to bool here by anding with 1
712         Out << "&1u";
713       }
714       Out << ')';
715       return;
716
717     case Instruction::GetElementPtr:
718       Out << "(&(";
719       printIndexingExpression(CE->getOperand(0), gep_type_begin(CPV),
720                               gep_type_end(CPV));
721       Out << "))";
722       return;
723     case Instruction::Select:
724       Out << '(';
725       printConstant(CE->getOperand(0));
726       Out << '?';
727       printConstant(CE->getOperand(1));
728       Out << ':';
729       printConstant(CE->getOperand(2));
730       Out << ')';
731       return;
732     case Instruction::Add:
733     case Instruction::Sub:
734     case Instruction::Mul:
735     case Instruction::SDiv:
736     case Instruction::UDiv:
737     case Instruction::FDiv:
738     case Instruction::URem:
739     case Instruction::SRem:
740     case Instruction::FRem:
741     case Instruction::And:
742     case Instruction::Or:
743     case Instruction::Xor:
744     case Instruction::ICmp:
745     case Instruction::Shl:
746     case Instruction::LShr:
747     case Instruction::AShr:
748     {
749       Out << '(';
750       bool NeedsClosingParens = printConstExprCast(CE); 
751       printConstantWithCast(CE->getOperand(0), CE->getOpcode());
752       switch (CE->getOpcode()) {
753       case Instruction::Add: Out << " + "; break;
754       case Instruction::Sub: Out << " - "; break;
755       case Instruction::Mul: Out << " * "; break;
756       case Instruction::URem:
757       case Instruction::SRem: 
758       case Instruction::FRem: Out << " % "; break;
759       case Instruction::UDiv: 
760       case Instruction::SDiv: 
761       case Instruction::FDiv: Out << " / "; break;
762       case Instruction::And: Out << " & "; break;
763       case Instruction::Or:  Out << " | "; break;
764       case Instruction::Xor: Out << " ^ "; break;
765       case Instruction::Shl: Out << " << "; break;
766       case Instruction::LShr:
767       case Instruction::AShr: Out << " >> "; break;
768       case Instruction::ICmp:
769         switch (CE->getPredicate()) {
770           case ICmpInst::ICMP_EQ: Out << " == "; break;
771           case ICmpInst::ICMP_NE: Out << " != "; break;
772           case ICmpInst::ICMP_SLT: 
773           case ICmpInst::ICMP_ULT: Out << " < "; break;
774           case ICmpInst::ICMP_SLE:
775           case ICmpInst::ICMP_ULE: Out << " <= "; break;
776           case ICmpInst::ICMP_SGT:
777           case ICmpInst::ICMP_UGT: Out << " > "; break;
778           case ICmpInst::ICMP_SGE:
779           case ICmpInst::ICMP_UGE: Out << " >= "; break;
780           default: assert(0 && "Illegal ICmp predicate");
781         }
782         break;
783       default: assert(0 && "Illegal opcode here!");
784       }
785       printConstantWithCast(CE->getOperand(1), CE->getOpcode());
786       if (NeedsClosingParens)
787         Out << "))";
788       Out << ')';
789       return;
790     }
791     case Instruction::FCmp: {
792       Out << '('; 
793       bool NeedsClosingParens = printConstExprCast(CE); 
794       if (CE->getPredicate() == FCmpInst::FCMP_FALSE)
795         Out << "0";
796       else if (CE->getPredicate() == FCmpInst::FCMP_TRUE)
797         Out << "1";
798       else {
799         const char* op = 0;
800         switch (CE->getPredicate()) {
801         default: assert(0 && "Illegal FCmp predicate");
802         case FCmpInst::FCMP_ORD: op = "ord"; break;
803         case FCmpInst::FCMP_UNO: op = "uno"; break;
804         case FCmpInst::FCMP_UEQ: op = "ueq"; break;
805         case FCmpInst::FCMP_UNE: op = "une"; break;
806         case FCmpInst::FCMP_ULT: op = "ult"; break;
807         case FCmpInst::FCMP_ULE: op = "ule"; break;
808         case FCmpInst::FCMP_UGT: op = "ugt"; break;
809         case FCmpInst::FCMP_UGE: op = "uge"; break;
810         case FCmpInst::FCMP_OEQ: op = "oeq"; break;
811         case FCmpInst::FCMP_ONE: op = "one"; break;
812         case FCmpInst::FCMP_OLT: op = "olt"; break;
813         case FCmpInst::FCMP_OLE: op = "ole"; break;
814         case FCmpInst::FCMP_OGT: op = "ogt"; break;
815         case FCmpInst::FCMP_OGE: op = "oge"; break;
816         }
817         Out << "llvm_fcmp_" << op << "(";
818         printConstantWithCast(CE->getOperand(0), CE->getOpcode());
819         Out << ", ";
820         printConstantWithCast(CE->getOperand(1), CE->getOpcode());
821         Out << ")";
822       }
823       if (NeedsClosingParens)
824         Out << "))";
825       Out << ')';
826     }
827     default:
828       cerr << "CWriter Error: Unhandled constant expression: "
829            << *CE << "\n";
830       abort();
831     }
832   } else if (isa<UndefValue>(CPV) && CPV->getType()->isFirstClassType()) {
833     Out << "((";
834     printType(Out, CPV->getType()); // sign doesn't matter
835     Out << ")/*UNDEF*/0)";
836     return;
837   }
838
839   if (ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
840     const Type* Ty = CI->getType();
841     if (Ty == Type::Int1Ty)
842       Out << (CI->getZExtValue() ? '1' : '0') ;
843     else {
844       Out << "((";
845       printSimpleType(Out, Ty, false) << ')';
846       if (CI->isMinValue(true)) 
847         Out << CI->getZExtValue() << 'u';
848       else
849         Out << CI->getSExtValue();
850       if (Ty->getPrimitiveSizeInBits() > 32)
851         Out << "ll";
852       Out << ')';
853     }
854     return;
855   } 
856
857   switch (CPV->getType()->getTypeID()) {
858   case Type::FloatTyID:
859   case Type::DoubleTyID: {
860     ConstantFP *FPC = cast<ConstantFP>(CPV);
861     std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
862     if (I != FPConstantMap.end()) {
863       // Because of FP precision problems we must load from a stack allocated
864       // value that holds the value in hex.
865       Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
866           << "*)&FPConstant" << I->second << ')';
867     } else {
868       if (IsNAN(FPC->getValue())) {
869         // The value is NaN
870
871         // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
872         // it's 0x7ff4.
873         const unsigned long QuietNaN = 0x7ff8UL;
874         //const unsigned long SignalNaN = 0x7ff4UL;
875
876         // We need to grab the first part of the FP #
877         char Buffer[100];
878
879         uint64_t ll = DoubleToBits(FPC->getValue());
880         sprintf(Buffer, "0x%llx", static_cast<long long>(ll));
881
882         std::string Num(&Buffer[0], &Buffer[6]);
883         unsigned long Val = strtoul(Num.c_str(), 0, 16);
884
885         if (FPC->getType() == Type::FloatTy)
886           Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
887               << Buffer << "\") /*nan*/ ";
888         else
889           Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
890               << Buffer << "\") /*nan*/ ";
891       } else if (IsInf(FPC->getValue())) {
892         // The value is Inf
893         if (FPC->getValue() < 0) Out << '-';
894         Out << "LLVM_INF" << (FPC->getType() == Type::FloatTy ? "F" : "")
895             << " /*inf*/ ";
896       } else {
897         std::string Num;
898 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
899         // Print out the constant as a floating point number.
900         char Buffer[100];
901         sprintf(Buffer, "%a", FPC->getValue());
902         Num = Buffer;
903 #else
904         Num = ftostr(FPC->getValue());
905 #endif
906         Out << Num;
907       }
908     }
909     break;
910   }
911
912   case Type::ArrayTyID:
913     if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
914       const ArrayType *AT = cast<ArrayType>(CPV->getType());
915       Out << '{';
916       if (AT->getNumElements()) {
917         Out << ' ';
918         Constant *CZ = Constant::getNullValue(AT->getElementType());
919         printConstant(CZ);
920         for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
921           Out << ", ";
922           printConstant(CZ);
923         }
924       }
925       Out << " }";
926     } else {
927       printConstantArray(cast<ConstantArray>(CPV));
928     }
929     break;
930
931   case Type::VectorTyID:
932     if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
933       const VectorType *AT = cast<VectorType>(CPV->getType());
934       Out << '{';
935       if (AT->getNumElements()) {
936         Out << ' ';
937         Constant *CZ = Constant::getNullValue(AT->getElementType());
938         printConstant(CZ);
939         for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
940           Out << ", ";
941           printConstant(CZ);
942         }
943       }
944       Out << " }";
945     } else {
946       printConstantVector(cast<ConstantVector>(CPV));
947     }
948     break;
949
950   case Type::StructTyID:
951     if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
952       const StructType *ST = cast<StructType>(CPV->getType());
953       Out << '{';
954       if (ST->getNumElements()) {
955         Out << ' ';
956         printConstant(Constant::getNullValue(ST->getElementType(0)));
957         for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
958           Out << ", ";
959           printConstant(Constant::getNullValue(ST->getElementType(i)));
960         }
961       }
962       Out << " }";
963     } else {
964       Out << '{';
965       if (CPV->getNumOperands()) {
966         Out << ' ';
967         printConstant(cast<Constant>(CPV->getOperand(0)));
968         for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
969           Out << ", ";
970           printConstant(cast<Constant>(CPV->getOperand(i)));
971         }
972       }
973       Out << " }";
974     }
975     break;
976
977   case Type::PointerTyID:
978     if (isa<ConstantPointerNull>(CPV)) {
979       Out << "((";
980       printType(Out, CPV->getType()); // sign doesn't matter
981       Out << ")/*NULL*/0)";
982       break;
983     } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
984       writeOperand(GV);
985       break;
986     }
987     // FALL THROUGH
988   default:
989     cerr << "Unknown constant type: " << *CPV << "\n";
990     abort();
991   }
992 }
993
994 // Some constant expressions need to be casted back to the original types
995 // because their operands were casted to the expected type. This function takes
996 // care of detecting that case and printing the cast for the ConstantExpr.
997 bool CWriter::printConstExprCast(const ConstantExpr* CE) {
998   bool NeedsExplicitCast = false;
999   const Type *Ty = CE->getOperand(0)->getType();
1000   bool TypeIsSigned = false;
1001   switch (CE->getOpcode()) {
1002   case Instruction::LShr:
1003   case Instruction::URem: 
1004   case Instruction::UDiv: NeedsExplicitCast = true; break;
1005   case Instruction::AShr:
1006   case Instruction::SRem: 
1007   case Instruction::SDiv: NeedsExplicitCast = true; TypeIsSigned = true; break;
1008   case Instruction::SExt:
1009     Ty = CE->getType();
1010     NeedsExplicitCast = true;
1011     TypeIsSigned = true;
1012     break;
1013   case Instruction::ZExt:
1014   case Instruction::Trunc:
1015   case Instruction::FPTrunc:
1016   case Instruction::FPExt:
1017   case Instruction::UIToFP:
1018   case Instruction::SIToFP:
1019   case Instruction::FPToUI:
1020   case Instruction::FPToSI:
1021   case Instruction::PtrToInt:
1022   case Instruction::IntToPtr:
1023   case Instruction::BitCast:
1024     Ty = CE->getType();
1025     NeedsExplicitCast = true;
1026     break;
1027   default: break;
1028   }
1029   if (NeedsExplicitCast) {
1030     Out << "((";
1031     if (Ty->isInteger() && Ty != Type::Int1Ty)
1032       printSimpleType(Out, Ty, TypeIsSigned);
1033     else
1034       printType(Out, Ty); // not integer, sign doesn't matter
1035     Out << ")(";
1036   }
1037   return NeedsExplicitCast;
1038 }
1039
1040 //  Print a constant assuming that it is the operand for a given Opcode. The
1041 //  opcodes that care about sign need to cast their operands to the expected
1042 //  type before the operation proceeds. This function does the casting.
1043 void CWriter::printConstantWithCast(Constant* CPV, unsigned Opcode) {
1044
1045   // Extract the operand's type, we'll need it.
1046   const Type* OpTy = CPV->getType();
1047
1048   // Indicate whether to do the cast or not.
1049   bool shouldCast = false;
1050   bool typeIsSigned = false;
1051
1052   // Based on the Opcode for which this Constant is being written, determine
1053   // the new type to which the operand should be casted by setting the value
1054   // of OpTy. If we change OpTy, also set shouldCast to true so it gets
1055   // casted below.
1056   switch (Opcode) {
1057     default:
1058       // for most instructions, it doesn't matter
1059       break; 
1060     case Instruction::LShr:
1061     case Instruction::UDiv:
1062     case Instruction::URem:
1063       shouldCast = true;
1064       break;
1065     case Instruction::AShr:
1066     case Instruction::SDiv:
1067     case Instruction::SRem:
1068       shouldCast = true;
1069       typeIsSigned = true;
1070       break;
1071   }
1072
1073   // Write out the casted constant if we should, otherwise just write the
1074   // operand.
1075   if (shouldCast) {
1076     Out << "((";
1077     printSimpleType(Out, OpTy, typeIsSigned);
1078     Out << ")";
1079     printConstant(CPV);
1080     Out << ")";
1081   } else 
1082     printConstant(CPV);
1083 }
1084
1085 std::string CWriter::GetValueName(const Value *Operand) {
1086   std::string Name;
1087
1088   if (!isa<GlobalValue>(Operand) && Operand->getName() != "") {
1089     std::string VarName;
1090
1091     Name = Operand->getName();
1092     VarName.reserve(Name.capacity());
1093
1094     for (std::string::iterator I = Name.begin(), E = Name.end();
1095          I != E; ++I) {
1096       char ch = *I;
1097
1098       if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
1099             (ch >= '0' && ch <= '9') || ch == '_'))
1100         VarName += '_';
1101       else
1102         VarName += ch;
1103     }
1104
1105     Name = "llvm_cbe_" + VarName;
1106   } else {
1107     Name = Mang->getValueName(Operand);
1108   }
1109
1110   return Name;
1111 }
1112
1113 void CWriter::writeOperandInternal(Value *Operand) {
1114   if (Instruction *I = dyn_cast<Instruction>(Operand))
1115     if (isInlinableInst(*I) && !isDirectAlloca(I)) {
1116       // Should we inline this instruction to build a tree?
1117       Out << '(';
1118       visit(*I);
1119       Out << ')';
1120       return;
1121     }
1122
1123   Constant* CPV = dyn_cast<Constant>(Operand);
1124
1125   if (CPV && !isa<GlobalValue>(CPV))
1126     printConstant(CPV);
1127   else
1128     Out << GetValueName(Operand);
1129 }
1130
1131 void CWriter::writeOperandRaw(Value *Operand) {
1132   Constant* CPV = dyn_cast<Constant>(Operand);
1133   if (CPV && !isa<GlobalValue>(CPV)) {
1134     printConstant(CPV);
1135   } else {
1136     Out << GetValueName(Operand);
1137   }
1138 }
1139
1140 void CWriter::writeOperand(Value *Operand) {
1141   if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
1142     Out << "(&";  // Global variables are referenced as their addresses by llvm
1143
1144   writeOperandInternal(Operand);
1145
1146   if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
1147     Out << ')';
1148 }
1149
1150 // Some instructions need to have their result value casted back to the 
1151 // original types because their operands were casted to the expected type. 
1152 // This function takes care of detecting that case and printing the cast 
1153 // for the Instruction.
1154 bool CWriter::writeInstructionCast(const Instruction &I) {
1155   const Type *Ty = I.getOperand(0)->getType();
1156   switch (I.getOpcode()) {
1157   case Instruction::LShr:
1158   case Instruction::URem: 
1159   case Instruction::UDiv: 
1160     Out << "((";
1161     printSimpleType(Out, Ty, false);
1162     Out << ")(";
1163     return true;
1164   case Instruction::AShr:
1165   case Instruction::SRem: 
1166   case Instruction::SDiv: 
1167     Out << "((";
1168     printSimpleType(Out, Ty, true);
1169     Out << ")(";
1170     return true;
1171   default: break;
1172   }
1173   return false;
1174 }
1175
1176 // Write the operand with a cast to another type based on the Opcode being used.
1177 // This will be used in cases where an instruction has specific type
1178 // requirements (usually signedness) for its operands. 
1179 void CWriter::writeOperandWithCast(Value* Operand, unsigned Opcode) {
1180
1181   // Extract the operand's type, we'll need it.
1182   const Type* OpTy = Operand->getType();
1183
1184   // Indicate whether to do the cast or not.
1185   bool shouldCast = false;
1186
1187   // Indicate whether the cast should be to a signed type or not.
1188   bool castIsSigned = false;
1189
1190   // Based on the Opcode for which this Operand is being written, determine
1191   // the new type to which the operand should be casted by setting the value
1192   // of OpTy. If we change OpTy, also set shouldCast to true.
1193   switch (Opcode) {
1194     default:
1195       // for most instructions, it doesn't matter
1196       break; 
1197     case Instruction::LShr:
1198     case Instruction::UDiv:
1199     case Instruction::URem: // Cast to unsigned first
1200       shouldCast = true;
1201       castIsSigned = false;
1202       break;
1203     case Instruction::AShr:
1204     case Instruction::SDiv:
1205     case Instruction::SRem: // Cast to signed first
1206       shouldCast = true;
1207       castIsSigned = true;
1208       break;
1209   }
1210
1211   // Write out the casted operand if we should, otherwise just write the
1212   // operand.
1213   if (shouldCast) {
1214     Out << "((";
1215     printSimpleType(Out, OpTy, castIsSigned);
1216     Out << ")";
1217     writeOperand(Operand);
1218     Out << ")";
1219   } else 
1220     writeOperand(Operand);
1221 }
1222
1223 // Write the operand with a cast to another type based on the icmp predicate 
1224 // being used. 
1225 void CWriter::writeOperandWithCast(Value* Operand, ICmpInst::Predicate predicate) {
1226
1227   // Extract the operand's type, we'll need it.
1228   const Type* OpTy = Operand->getType();
1229
1230   // Indicate whether to do the cast or not.
1231   bool shouldCast = false;
1232
1233   // Indicate whether the cast should be to a signed type or not.
1234   bool castIsSigned = false;
1235
1236   // Based on the Opcode for which this Operand is being written, determine
1237   // the new type to which the operand should be casted by setting the value
1238   // of OpTy. If we change OpTy, also set shouldCast to true.
1239   switch (predicate) {
1240     default:
1241       // for eq and ne, it doesn't matter
1242       break; 
1243     case ICmpInst::ICMP_UGT:
1244     case ICmpInst::ICMP_UGE:
1245     case ICmpInst::ICMP_ULT:
1246     case ICmpInst::ICMP_ULE:
1247       shouldCast = true;
1248       break;
1249     case ICmpInst::ICMP_SGT:
1250     case ICmpInst::ICMP_SGE:
1251     case ICmpInst::ICMP_SLT:
1252     case ICmpInst::ICMP_SLE:
1253       shouldCast = true;
1254       castIsSigned = true;
1255       break;
1256   }
1257
1258   // Write out the casted operand if we should, otherwise just write the
1259   // operand.
1260   if (shouldCast) {
1261     Out << "((";
1262     if (OpTy->isInteger() && OpTy != Type::Int1Ty)
1263       printSimpleType(Out, OpTy, castIsSigned);
1264     else
1265       printType(Out, OpTy); // not integer, sign doesn't matter
1266     Out << ")";
1267     writeOperand(Operand);
1268     Out << ")";
1269   } else 
1270     writeOperand(Operand);
1271 }
1272
1273 // generateCompilerSpecificCode - This is where we add conditional compilation
1274 // directives to cater to specific compilers as need be.
1275 //
1276 static void generateCompilerSpecificCode(std::ostream& Out) {
1277   // Alloca is hard to get, and we don't want to include stdlib.h here.
1278   Out << "/* get a declaration for alloca */\n"
1279       << "#if defined(__CYGWIN__) || defined(__MINGW32__)\n"
1280       << "extern void *_alloca(unsigned long);\n"
1281       << "#define alloca(x) _alloca(x)\n"
1282       << "#elif defined(__APPLE__)\n"
1283       << "extern void *__builtin_alloca(unsigned long);\n"
1284       << "#define alloca(x) __builtin_alloca(x)\n"
1285       << "#define longjmp _longjmp\n"
1286       << "#define setjmp _setjmp\n"
1287       << "#elif defined(__sun__)\n"
1288       << "#if defined(__sparcv9)\n"
1289       << "extern void *__builtin_alloca(unsigned long);\n"
1290       << "#else\n"
1291       << "extern void *__builtin_alloca(unsigned int);\n"
1292       << "#endif\n"
1293       << "#define alloca(x) __builtin_alloca(x)\n"
1294       << "#elif defined(__FreeBSD__) || defined(__OpenBSD__)\n"
1295       << "#define alloca(x) __builtin_alloca(x)\n"
1296       << "#elif defined(_MSC_VER)\n"
1297       << "#define inline\n"
1298       << "#define alloca(x) _alloca(x)\n"
1299       << "#else\n"
1300       << "#include <alloca.h>\n"
1301       << "#endif\n\n";
1302
1303   // We output GCC specific attributes to preserve 'linkonce'ness on globals.
1304   // If we aren't being compiled with GCC, just drop these attributes.
1305   Out << "#ifndef __GNUC__  /* Can only support \"linkonce\" vars with GCC */\n"
1306       << "#define __attribute__(X)\n"
1307       << "#endif\n\n";
1308
1309   // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
1310   Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1311       << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
1312       << "#elif defined(__GNUC__)\n"
1313       << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
1314       << "#else\n"
1315       << "#define __EXTERNAL_WEAK__\n"
1316       << "#endif\n\n";
1317
1318   // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
1319   Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1320       << "#define __ATTRIBUTE_WEAK__\n"
1321       << "#elif defined(__GNUC__)\n"
1322       << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
1323       << "#else\n"
1324       << "#define __ATTRIBUTE_WEAK__\n"
1325       << "#endif\n\n";
1326
1327   // Add hidden visibility support. FIXME: APPLE_CC?
1328   Out << "#if defined(__GNUC__)\n"
1329       << "#define __HIDDEN__ __attribute__((visibility(\"hidden\")))\n"
1330       << "#endif\n\n";
1331     
1332   // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
1333   // From the GCC documentation:
1334   //
1335   //   double __builtin_nan (const char *str)
1336   //
1337   // This is an implementation of the ISO C99 function nan.
1338   //
1339   // Since ISO C99 defines this function in terms of strtod, which we do
1340   // not implement, a description of the parsing is in order. The string is
1341   // parsed as by strtol; that is, the base is recognized by leading 0 or
1342   // 0x prefixes. The number parsed is placed in the significand such that
1343   // the least significant bit of the number is at the least significant
1344   // bit of the significand. The number is truncated to fit the significand
1345   // field provided. The significand is forced to be a quiet NaN.
1346   //
1347   // This function, if given a string literal, is evaluated early enough
1348   // that it is considered a compile-time constant.
1349   //
1350   //   float __builtin_nanf (const char *str)
1351   //
1352   // Similar to __builtin_nan, except the return type is float.
1353   //
1354   //   double __builtin_inf (void)
1355   //
1356   // Similar to __builtin_huge_val, except a warning is generated if the
1357   // target floating-point format does not support infinities. This
1358   // function is suitable for implementing the ISO C99 macro INFINITY.
1359   //
1360   //   float __builtin_inff (void)
1361   //
1362   // Similar to __builtin_inf, except the return type is float.
1363   Out << "#ifdef __GNUC__\n"
1364       << "#define LLVM_NAN(NanStr)   __builtin_nan(NanStr)   /* Double */\n"
1365       << "#define LLVM_NANF(NanStr)  __builtin_nanf(NanStr)  /* Float */\n"
1366       << "#define LLVM_NANS(NanStr)  __builtin_nans(NanStr)  /* Double */\n"
1367       << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
1368       << "#define LLVM_INF           __builtin_inf()         /* Double */\n"
1369       << "#define LLVM_INFF          __builtin_inff()        /* Float */\n"
1370       << "#define LLVM_PREFETCH(addr,rw,locality) "
1371                               "__builtin_prefetch(addr,rw,locality)\n"
1372       << "#define __ATTRIBUTE_CTOR__ __attribute__((constructor))\n"
1373       << "#define __ATTRIBUTE_DTOR__ __attribute__((destructor))\n"
1374       << "#define LLVM_ASM           __asm__\n"
1375       << "#else\n"
1376       << "#define LLVM_NAN(NanStr)   ((double)0.0)           /* Double */\n"
1377       << "#define LLVM_NANF(NanStr)  0.0F                    /* Float */\n"
1378       << "#define LLVM_NANS(NanStr)  ((double)0.0)           /* Double */\n"
1379       << "#define LLVM_NANSF(NanStr) 0.0F                    /* Float */\n"
1380       << "#define LLVM_INF           ((double)0.0)           /* Double */\n"
1381       << "#define LLVM_INFF          0.0F                    /* Float */\n"
1382       << "#define LLVM_PREFETCH(addr,rw,locality)            /* PREFETCH */\n"
1383       << "#define __ATTRIBUTE_CTOR__\n"
1384       << "#define __ATTRIBUTE_DTOR__\n"
1385       << "#define LLVM_ASM(X)\n"
1386       << "#endif\n\n";
1387
1388   // Output target-specific code that should be inserted into main.
1389   Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
1390   // On X86, set the FP control word to 64-bits of precision instead of 80 bits.
1391   Out << "#if defined(__GNUC__) && !defined(__llvm__)\n"
1392       << "#if defined(i386) || defined(__i386__) || defined(__i386) || "
1393       << "defined(__x86_64__)\n"
1394       << "#undef CODE_FOR_MAIN\n"
1395       << "#define CODE_FOR_MAIN() \\\n"
1396       << "  {short F;__asm__ (\"fnstcw %0\" : \"=m\" (*&F)); \\\n"
1397       << "  F=(F&~0x300)|0x200;__asm__(\"fldcw %0\"::\"m\"(*&F));}\n"
1398       << "#endif\n#endif\n";
1399
1400 }
1401
1402 /// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
1403 /// the StaticTors set.
1404 static void FindStaticTors(GlobalVariable *GV, std::set<Function*> &StaticTors){
1405   ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
1406   if (!InitList) return;
1407   
1408   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
1409     if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
1410       if (CS->getNumOperands() != 2) return;  // Not array of 2-element structs.
1411       
1412       if (CS->getOperand(1)->isNullValue())
1413         return;  // Found a null terminator, exit printing.
1414       Constant *FP = CS->getOperand(1);
1415       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
1416         if (CE->isCast())
1417           FP = CE->getOperand(0);
1418       if (Function *F = dyn_cast<Function>(FP))
1419         StaticTors.insert(F);
1420     }
1421 }
1422
1423 enum SpecialGlobalClass {
1424   NotSpecial = 0,
1425   GlobalCtors, GlobalDtors,
1426   NotPrinted
1427 };
1428
1429 /// getGlobalVariableClass - If this is a global that is specially recognized
1430 /// by LLVM, return a code that indicates how we should handle it.
1431 static SpecialGlobalClass getGlobalVariableClass(const GlobalVariable *GV) {
1432   // If this is a global ctors/dtors list, handle it now.
1433   if (GV->hasAppendingLinkage() && GV->use_empty()) {
1434     if (GV->getName() == "llvm.global_ctors")
1435       return GlobalCtors;
1436     else if (GV->getName() == "llvm.global_dtors")
1437       return GlobalDtors;
1438   }
1439   
1440   // Otherwise, it it is other metadata, don't print it.  This catches things
1441   // like debug information.
1442   if (GV->getSection() == "llvm.metadata")
1443     return NotPrinted;
1444   
1445   return NotSpecial;
1446 }
1447
1448
1449 bool CWriter::doInitialization(Module &M) {
1450   // Initialize
1451   TheModule = &M;
1452
1453   TD = new TargetData(&M);
1454   IL = new IntrinsicLowering(*TD);
1455   IL->AddPrototypes(M);
1456
1457   // Ensure that all structure types have names...
1458   Mang = new Mangler(M);
1459   Mang->markCharUnacceptable('.');
1460
1461   // Keep track of which functions are static ctors/dtors so they can have
1462   // an attribute added to their prototypes.
1463   std::set<Function*> StaticCtors, StaticDtors;
1464   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1465        I != E; ++I) {
1466     switch (getGlobalVariableClass(I)) {
1467     default: break;
1468     case GlobalCtors:
1469       FindStaticTors(I, StaticCtors);
1470       break;
1471     case GlobalDtors:
1472       FindStaticTors(I, StaticDtors);
1473       break;
1474     }
1475   }
1476   
1477   // get declaration for alloca
1478   Out << "/* Provide Declarations */\n";
1479   Out << "#include <stdarg.h>\n";      // Varargs support
1480   Out << "#include <setjmp.h>\n";      // Unwind support
1481   generateCompilerSpecificCode(Out);
1482
1483   // Provide a definition for `bool' if not compiling with a C++ compiler.
1484   Out << "\n"
1485       << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
1486
1487       << "\n\n/* Support for floating point constants */\n"
1488       << "typedef unsigned long long ConstantDoubleTy;\n"
1489       << "typedef unsigned int        ConstantFloatTy;\n"
1490
1491       << "\n\n/* Global Declarations */\n";
1492
1493   // First output all the declarations for the program, because C requires
1494   // Functions & globals to be declared before they are used.
1495   //
1496
1497   // Loop over the symbol table, emitting all named constants...
1498   printModuleTypes(M.getTypeSymbolTable());
1499
1500   // Global variable declarations...
1501   if (!M.global_empty()) {
1502     Out << "\n/* External Global Variable Declarations */\n";
1503     for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1504          I != E; ++I) {
1505       if (I->hasExternalLinkage()) {
1506         Out << "extern ";
1507         printType(Out, I->getType()->getElementType(), false, 
1508                   GetValueName(I));
1509         Out << ";\n";
1510       } else if (I->hasDLLImportLinkage()) {
1511         Out << "__declspec(dllimport) ";
1512         printType(Out, I->getType()->getElementType(), false, 
1513                   GetValueName(I));
1514         Out << ";\n";        
1515       } else if (I->hasExternalWeakLinkage()) {
1516         Out << "extern ";
1517         printType(Out, I->getType()->getElementType(), false,
1518                   GetValueName(I));
1519         Out << " __EXTERNAL_WEAK__ ;\n";
1520       }
1521     }
1522   }
1523
1524   // Function declarations
1525   Out << "\n/* Function Declarations */\n";
1526   Out << "double fmod(double, double);\n";   // Support for FP rem
1527   Out << "float fmodf(float, float);\n";
1528   
1529   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1530     // Don't print declarations for intrinsic functions.
1531     if (!I->getIntrinsicID() && I->getName() != "setjmp" && 
1532         I->getName() != "longjmp" && I->getName() != "_setjmp") {
1533       if (I->hasExternalWeakLinkage())
1534         Out << "extern ";
1535       printFunctionSignature(I, true);
1536       if (I->hasWeakLinkage() || I->hasLinkOnceLinkage()) 
1537         Out << " __ATTRIBUTE_WEAK__";
1538       if (I->hasExternalWeakLinkage())
1539         Out << " __EXTERNAL_WEAK__";
1540       if (StaticCtors.count(I))
1541         Out << " __ATTRIBUTE_CTOR__";
1542       if (StaticDtors.count(I))
1543         Out << " __ATTRIBUTE_DTOR__";
1544       if (I->hasHiddenVisibility())
1545         Out << " __HIDDEN__";
1546       
1547       if (I->hasName() && I->getName()[0] == 1)
1548         Out << " LLVM_ASM(\"" << I->getName().c_str()+1 << "\")";
1549           
1550       Out << ";\n";
1551     }
1552   }
1553
1554   // Output the global variable declarations
1555   if (!M.global_empty()) {
1556     Out << "\n\n/* Global Variable Declarations */\n";
1557     for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1558          I != E; ++I)
1559       if (!I->isDeclaration()) {
1560         // Ignore special globals, such as debug info.
1561         if (getGlobalVariableClass(I))
1562           continue;
1563         
1564         if (I->hasInternalLinkage())
1565           Out << "static ";
1566         else
1567           Out << "extern ";
1568         printType(Out, I->getType()->getElementType(), false, 
1569                   GetValueName(I));
1570
1571         if (I->hasLinkOnceLinkage())
1572           Out << " __attribute__((common))";
1573         else if (I->hasWeakLinkage())
1574           Out << " __ATTRIBUTE_WEAK__";
1575         else if (I->hasExternalWeakLinkage())
1576           Out << " __EXTERNAL_WEAK__";
1577         if (I->hasHiddenVisibility())
1578           Out << " __HIDDEN__";
1579         Out << ";\n";
1580       }
1581   }
1582
1583   // Output the global variable definitions and contents...
1584   if (!M.global_empty()) {
1585     Out << "\n\n/* Global Variable Definitions and Initialization */\n";
1586     for (Module::global_iterator I = M.global_begin(), E = M.global_end(); 
1587          I != E; ++I)
1588       if (!I->isDeclaration()) {
1589         // Ignore special globals, such as debug info.
1590         if (getGlobalVariableClass(I))
1591           continue;
1592         
1593         if (I->hasInternalLinkage())
1594           Out << "static ";
1595         else if (I->hasDLLImportLinkage())
1596           Out << "__declspec(dllimport) ";
1597         else if (I->hasDLLExportLinkage())
1598           Out << "__declspec(dllexport) ";
1599             
1600         printType(Out, I->getType()->getElementType(), false, 
1601                   GetValueName(I));
1602         if (I->hasLinkOnceLinkage())
1603           Out << " __attribute__((common))";
1604         else if (I->hasWeakLinkage())
1605           Out << " __ATTRIBUTE_WEAK__";
1606
1607         if (I->hasHiddenVisibility())
1608           Out << " __HIDDEN__";
1609         
1610         // If the initializer is not null, emit the initializer.  If it is null,
1611         // we try to avoid emitting large amounts of zeros.  The problem with
1612         // this, however, occurs when the variable has weak linkage.  In this
1613         // case, the assembler will complain about the variable being both weak
1614         // and common, so we disable this optimization.
1615         if (!I->getInitializer()->isNullValue()) {
1616           Out << " = " ;
1617           writeOperand(I->getInitializer());
1618         } else if (I->hasWeakLinkage()) {
1619           // We have to specify an initializer, but it doesn't have to be
1620           // complete.  If the value is an aggregate, print out { 0 }, and let
1621           // the compiler figure out the rest of the zeros.
1622           Out << " = " ;
1623           if (isa<StructType>(I->getInitializer()->getType()) ||
1624               isa<ArrayType>(I->getInitializer()->getType()) ||
1625               isa<VectorType>(I->getInitializer()->getType())) {
1626             Out << "{ 0 }";
1627           } else {
1628             // Just print it out normally.
1629             writeOperand(I->getInitializer());
1630           }
1631         }
1632         Out << ";\n";
1633       }
1634   }
1635
1636   if (!M.empty())
1637     Out << "\n\n/* Function Bodies */\n";
1638
1639   // Emit some helper functions for dealing with FCMP instruction's 
1640   // predicates
1641   Out << "static inline int llvm_fcmp_ord(double X, double Y) { ";
1642   Out << "return X == X && Y == Y; }\n";
1643   Out << "static inline int llvm_fcmp_uno(double X, double Y) { ";
1644   Out << "return X != X || Y != Y; }\n";
1645   Out << "static inline int llvm_fcmp_ueq(double X, double Y) { ";
1646   Out << "return X == Y || llvm_fcmp_uno(X, Y); }\n";
1647   Out << "static inline int llvm_fcmp_une(double X, double Y) { ";
1648   Out << "return X != Y; }\n";
1649   Out << "static inline int llvm_fcmp_ult(double X, double Y) { ";
1650   Out << "return X <  Y || llvm_fcmp_uno(X, Y); }\n";
1651   Out << "static inline int llvm_fcmp_ugt(double X, double Y) { ";
1652   Out << "return X >  Y || llvm_fcmp_uno(X, Y); }\n";
1653   Out << "static inline int llvm_fcmp_ule(double X, double Y) { ";
1654   Out << "return X <= Y || llvm_fcmp_uno(X, Y); }\n";
1655   Out << "static inline int llvm_fcmp_uge(double X, double Y) { ";
1656   Out << "return X >= Y || llvm_fcmp_uno(X, Y); }\n";
1657   Out << "static inline int llvm_fcmp_oeq(double X, double Y) { ";
1658   Out << "return X == Y ; }\n";
1659   Out << "static inline int llvm_fcmp_one(double X, double Y) { ";
1660   Out << "return X != Y && llvm_fcmp_ord(X, Y); }\n";
1661   Out << "static inline int llvm_fcmp_olt(double X, double Y) { ";
1662   Out << "return X <  Y ; }\n";
1663   Out << "static inline int llvm_fcmp_ogt(double X, double Y) { ";
1664   Out << "return X >  Y ; }\n";
1665   Out << "static inline int llvm_fcmp_ole(double X, double Y) { ";
1666   Out << "return X <= Y ; }\n";
1667   Out << "static inline int llvm_fcmp_oge(double X, double Y) { ";
1668   Out << "return X >= Y ; }\n";
1669   return false;
1670 }
1671
1672
1673 /// Output all floating point constants that cannot be printed accurately...
1674 void CWriter::printFloatingPointConstants(Function &F) {
1675   // Scan the module for floating point constants.  If any FP constant is used
1676   // in the function, we want to redirect it here so that we do not depend on
1677   // the precision of the printed form, unless the printed form preserves
1678   // precision.
1679   //
1680   static unsigned FPCounter = 0;
1681   for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
1682        I != E; ++I)
1683     if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
1684       if (!isFPCSafeToPrint(FPC) && // Do not put in FPConstantMap if safe.
1685           !FPConstantMap.count(FPC)) {
1686         double Val = FPC->getValue();
1687
1688         FPConstantMap[FPC] = FPCounter;  // Number the FP constants
1689
1690         if (FPC->getType() == Type::DoubleTy) {
1691           Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
1692               << " = 0x" << std::hex << DoubleToBits(Val) << std::dec
1693               << "ULL;    /* " << Val << " */\n";
1694         } else if (FPC->getType() == Type::FloatTy) {
1695           Out << "static const ConstantFloatTy FPConstant" << FPCounter++
1696               << " = 0x" << std::hex << FloatToBits(Val) << std::dec
1697               << "U;    /* " << Val << " */\n";
1698         } else
1699           assert(0 && "Unknown float type!");
1700       }
1701
1702   Out << '\n';
1703 }
1704
1705
1706 /// printSymbolTable - Run through symbol table looking for type names.  If a
1707 /// type name is found, emit its declaration...
1708 ///
1709 void CWriter::printModuleTypes(const TypeSymbolTable &TST) {
1710   Out << "/* Helper union for bitcasts */\n";
1711   Out << "typedef union {\n";
1712   Out << "  unsigned int Int32;\n";
1713   Out << "  unsigned long long Int64;\n";
1714   Out << "  float Float;\n";
1715   Out << "  double Double;\n";
1716   Out << "} llvmBitCastUnion;\n";
1717
1718   // We are only interested in the type plane of the symbol table.
1719   TypeSymbolTable::const_iterator I   = TST.begin();
1720   TypeSymbolTable::const_iterator End = TST.end();
1721
1722   // If there are no type names, exit early.
1723   if (I == End) return;
1724
1725   // Print out forward declarations for structure types before anything else!
1726   Out << "/* Structure forward decls */\n";
1727   for (; I != End; ++I) {
1728     std::string Name = "struct l_" + Mang->makeNameProper(I->first);
1729     Out << Name << ";\n";
1730     TypeNames.insert(std::make_pair(I->second, Name));
1731   }
1732
1733   Out << '\n';
1734
1735   // Now we can print out typedefs.  Above, we guaranteed that this can only be
1736   // for struct or opaque types.
1737   Out << "/* Typedefs */\n";
1738   for (I = TST.begin(); I != End; ++I) {
1739     std::string Name = "l_" + Mang->makeNameProper(I->first);
1740     Out << "typedef ";
1741     printType(Out, I->second, false, Name);
1742     Out << ";\n";
1743   }
1744
1745   Out << '\n';
1746
1747   // Keep track of which structures have been printed so far...
1748   std::set<const StructType *> StructPrinted;
1749
1750   // Loop over all structures then push them into the stack so they are
1751   // printed in the correct order.
1752   //
1753   Out << "/* Structure contents */\n";
1754   for (I = TST.begin(); I != End; ++I)
1755     if (const StructType *STy = dyn_cast<StructType>(I->second))
1756       // Only print out used types!
1757       printContainedStructs(STy, StructPrinted);
1758 }
1759
1760 // Push the struct onto the stack and recursively push all structs
1761 // this one depends on.
1762 //
1763 // TODO:  Make this work properly with vector types
1764 //
1765 void CWriter::printContainedStructs(const Type *Ty,
1766                                     std::set<const StructType*> &StructPrinted){
1767   // Don't walk through pointers.
1768   if (isa<PointerType>(Ty) || Ty->isPrimitiveType() || Ty->isInteger()) return;
1769   
1770   // Print all contained types first.
1771   for (Type::subtype_iterator I = Ty->subtype_begin(),
1772        E = Ty->subtype_end(); I != E; ++I)
1773     printContainedStructs(*I, StructPrinted);
1774   
1775   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1776     // Check to see if we have already printed this struct.
1777     if (StructPrinted.insert(STy).second) {
1778       // Print structure type out.
1779       std::string Name = TypeNames[STy];
1780       printType(Out, STy, false, Name, true);
1781       Out << ";\n\n";
1782     }
1783   }
1784 }
1785
1786 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
1787   /// isStructReturn - Should this function actually return a struct by-value?
1788   bool isStructReturn = F->getFunctionType()->isStructReturn();
1789   
1790   if (F->hasInternalLinkage()) Out << "static ";
1791   if (F->hasDLLImportLinkage()) Out << "__declspec(dllimport) ";
1792   if (F->hasDLLExportLinkage()) Out << "__declspec(dllexport) ";  
1793   switch (F->getCallingConv()) {
1794    case CallingConv::X86_StdCall:
1795     Out << "__stdcall ";
1796     break;
1797    case CallingConv::X86_FastCall:
1798     Out << "__fastcall ";
1799     break;
1800   }
1801   
1802   // Loop over the arguments, printing them...
1803   const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
1804
1805   std::stringstream FunctionInnards;
1806
1807   // Print out the name...
1808   FunctionInnards << GetValueName(F) << '(';
1809
1810   bool PrintedArg = false;
1811   if (!F->isDeclaration()) {
1812     if (!F->arg_empty()) {
1813       Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1814       
1815       // If this is a struct-return function, don't print the hidden
1816       // struct-return argument.
1817       if (isStructReturn) {
1818         assert(I != E && "Invalid struct return function!");
1819         ++I;
1820       }
1821       
1822       std::string ArgName;
1823       unsigned Idx = 1;
1824       for (; I != E; ++I) {
1825         if (PrintedArg) FunctionInnards << ", ";
1826         if (I->hasName() || !Prototype)
1827           ArgName = GetValueName(I);
1828         else
1829           ArgName = "";
1830         printType(FunctionInnards, I->getType(), 
1831             /*isSigned=*/FT->paramHasAttr(Idx, FunctionType::SExtAttribute), 
1832             ArgName);
1833         PrintedArg = true;
1834         ++Idx;
1835       }
1836     }
1837   } else {
1838     // Loop over the arguments, printing them.
1839     FunctionType::param_iterator I = FT->param_begin(), E = FT->param_end();
1840     
1841     // If this is a struct-return function, don't print the hidden
1842     // struct-return argument.
1843     if (isStructReturn) {
1844       assert(I != E && "Invalid struct return function!");
1845       ++I;
1846     }
1847     
1848     unsigned Idx = 1;
1849     for (; I != E; ++I) {
1850       if (PrintedArg) FunctionInnards << ", ";
1851       printType(FunctionInnards, *I,
1852              /*isSigned=*/FT->paramHasAttr(Idx, FunctionType::SExtAttribute));
1853       PrintedArg = true;
1854       ++Idx;
1855     }
1856   }
1857
1858   // Finish printing arguments... if this is a vararg function, print the ...,
1859   // unless there are no known types, in which case, we just emit ().
1860   //
1861   if (FT->isVarArg() && PrintedArg) {
1862     if (PrintedArg) FunctionInnards << ", ";
1863     FunctionInnards << "...";  // Output varargs portion of signature!
1864   } else if (!FT->isVarArg() && !PrintedArg) {
1865     FunctionInnards << "void"; // ret() -> ret(void) in C.
1866   }
1867   FunctionInnards << ')';
1868   
1869   // Get the return tpe for the function.
1870   const Type *RetTy;
1871   if (!isStructReturn)
1872     RetTy = F->getReturnType();
1873   else {
1874     // If this is a struct-return function, print the struct-return type.
1875     RetTy = cast<PointerType>(FT->getParamType(0))->getElementType();
1876   }
1877     
1878   // Print out the return type and the signature built above.
1879   printType(Out, RetTy, 
1880             /*isSigned=*/FT->paramHasAttr(0, FunctionType::SExtAttribute), 
1881             FunctionInnards.str());
1882 }
1883
1884 static inline bool isFPIntBitCast(const Instruction &I) {
1885   if (!isa<BitCastInst>(I))
1886     return false;
1887   const Type *SrcTy = I.getOperand(0)->getType();
1888   const Type *DstTy = I.getType();
1889   return (SrcTy->isFloatingPoint() && DstTy->isInteger()) ||
1890          (DstTy->isFloatingPoint() && SrcTy->isInteger());
1891 }
1892
1893 void CWriter::printFunction(Function &F) {
1894   /// isStructReturn - Should this function actually return a struct by-value?
1895   bool isStructReturn = F.getFunctionType()->isStructReturn();
1896
1897   printFunctionSignature(&F, false);
1898   Out << " {\n";
1899   
1900   // If this is a struct return function, handle the result with magic.
1901   if (isStructReturn) {
1902     const Type *StructTy =
1903       cast<PointerType>(F.arg_begin()->getType())->getElementType();
1904     Out << "  ";
1905     printType(Out, StructTy, false, "StructReturn");
1906     Out << ";  /* Struct return temporary */\n";
1907
1908     Out << "  ";
1909     printType(Out, F.arg_begin()->getType(), false, 
1910               GetValueName(F.arg_begin()));
1911     Out << " = &StructReturn;\n";
1912   }
1913
1914   bool PrintedVar = false;
1915   
1916   // print local variable information for the function
1917   for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
1918     if (const AllocaInst *AI = isDirectAlloca(&*I)) {
1919       Out << "  ";
1920       printType(Out, AI->getAllocatedType(), false, GetValueName(AI));
1921       Out << ";    /* Address-exposed local */\n";
1922       PrintedVar = true;
1923     } else if (I->getType() != Type::VoidTy && !isInlinableInst(*I)) {
1924       Out << "  ";
1925       printType(Out, I->getType(), false, GetValueName(&*I));
1926       Out << ";\n";
1927
1928       if (isa<PHINode>(*I)) {  // Print out PHI node temporaries as well...
1929         Out << "  ";
1930         printType(Out, I->getType(), false,
1931                   GetValueName(&*I)+"__PHI_TEMPORARY");
1932         Out << ";\n";
1933       }
1934       PrintedVar = true;
1935     }
1936     // We need a temporary for the BitCast to use so it can pluck a value out
1937     // of a union to do the BitCast. This is separate from the need for a
1938     // variable to hold the result of the BitCast. 
1939     if (isFPIntBitCast(*I)) {
1940       Out << "  llvmBitCastUnion " << GetValueName(&*I)
1941           << "__BITCAST_TEMPORARY;\n";
1942       PrintedVar = true;
1943     }
1944   }
1945
1946   if (PrintedVar)
1947     Out << '\n';
1948
1949   if (F.hasExternalLinkage() && F.getName() == "main")
1950     Out << "  CODE_FOR_MAIN();\n";
1951
1952   // print the basic blocks
1953   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1954     if (Loop *L = LI->getLoopFor(BB)) {
1955       if (L->getHeader() == BB && L->getParentLoop() == 0)
1956         printLoop(L);
1957     } else {
1958       printBasicBlock(BB);
1959     }
1960   }
1961
1962   Out << "}\n\n";
1963 }
1964
1965 void CWriter::printLoop(Loop *L) {
1966   Out << "  do {     /* Syntactic loop '" << L->getHeader()->getName()
1967       << "' to make GCC happy */\n";
1968   for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
1969     BasicBlock *BB = L->getBlocks()[i];
1970     Loop *BBLoop = LI->getLoopFor(BB);
1971     if (BBLoop == L)
1972       printBasicBlock(BB);
1973     else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
1974       printLoop(BBLoop);
1975   }
1976   Out << "  } while (1); /* end of syntactic loop '"
1977       << L->getHeader()->getName() << "' */\n";
1978 }
1979
1980 void CWriter::printBasicBlock(BasicBlock *BB) {
1981
1982   // Don't print the label for the basic block if there are no uses, or if
1983   // the only terminator use is the predecessor basic block's terminator.
1984   // We have to scan the use list because PHI nodes use basic blocks too but
1985   // do not require a label to be generated.
1986   //
1987   bool NeedsLabel = false;
1988   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1989     if (isGotoCodeNecessary(*PI, BB)) {
1990       NeedsLabel = true;
1991       break;
1992     }
1993
1994   if (NeedsLabel) Out << GetValueName(BB) << ":\n";
1995
1996   // Output all of the instructions in the basic block...
1997   for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
1998        ++II) {
1999     if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
2000       if (II->getType() != Type::VoidTy && !isInlineAsm(*II))
2001         outputLValue(II);
2002       else
2003         Out << "  ";
2004       visit(*II);
2005       Out << ";\n";
2006     }
2007   }
2008
2009   // Don't emit prefix or suffix for the terminator...
2010   visit(*BB->getTerminator());
2011 }
2012
2013
2014 // Specific Instruction type classes... note that all of the casts are
2015 // necessary because we use the instruction classes as opaque types...
2016 //
2017 void CWriter::visitReturnInst(ReturnInst &I) {
2018   // If this is a struct return function, return the temporary struct.
2019   bool isStructReturn = I.getParent()->getParent()->
2020     getFunctionType()->isStructReturn();
2021
2022   if (isStructReturn) {
2023     Out << "  return StructReturn;\n";
2024     return;
2025   }
2026   
2027   // Don't output a void return if this is the last basic block in the function
2028   if (I.getNumOperands() == 0 &&
2029       &*--I.getParent()->getParent()->end() == I.getParent() &&
2030       !I.getParent()->size() == 1) {
2031     return;
2032   }
2033
2034   Out << "  return";
2035   if (I.getNumOperands()) {
2036     Out << ' ';
2037     writeOperand(I.getOperand(0));
2038   }
2039   Out << ";\n";
2040 }
2041
2042 void CWriter::visitSwitchInst(SwitchInst &SI) {
2043
2044   Out << "  switch (";
2045   writeOperand(SI.getOperand(0));
2046   Out << ") {\n  default:\n";
2047   printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
2048   printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
2049   Out << ";\n";
2050   for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
2051     Out << "  case ";
2052     writeOperand(SI.getOperand(i));
2053     Out << ":\n";
2054     BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
2055     printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
2056     printBranchToBlock(SI.getParent(), Succ, 2);
2057     if (Function::iterator(Succ) == next(Function::iterator(SI.getParent())))
2058       Out << "    break;\n";
2059   }
2060   Out << "  }\n";
2061 }
2062
2063 void CWriter::visitUnreachableInst(UnreachableInst &I) {
2064   Out << "  /*UNREACHABLE*/;\n";
2065 }
2066
2067 bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
2068   /// FIXME: This should be reenabled, but loop reordering safe!!
2069   return true;
2070
2071   if (next(Function::iterator(From)) != Function::iterator(To))
2072     return true;  // Not the direct successor, we need a goto.
2073
2074   //isa<SwitchInst>(From->getTerminator())
2075
2076   if (LI->getLoopFor(From) != LI->getLoopFor(To))
2077     return true;
2078   return false;
2079 }
2080
2081 void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
2082                                           BasicBlock *Successor,
2083                                           unsigned Indent) {
2084   for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
2085     PHINode *PN = cast<PHINode>(I);
2086     // Now we have to do the printing.
2087     Value *IV = PN->getIncomingValueForBlock(CurBlock);
2088     if (!isa<UndefValue>(IV)) {
2089       Out << std::string(Indent, ' ');
2090       Out << "  " << GetValueName(I) << "__PHI_TEMPORARY = ";
2091       writeOperand(IV);
2092       Out << ";   /* for PHI node */\n";
2093     }
2094   }
2095 }
2096
2097 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
2098                                  unsigned Indent) {
2099   if (isGotoCodeNecessary(CurBB, Succ)) {
2100     Out << std::string(Indent, ' ') << "  goto ";
2101     writeOperand(Succ);
2102     Out << ";\n";
2103   }
2104 }
2105
2106 // Branch instruction printing - Avoid printing out a branch to a basic block
2107 // that immediately succeeds the current one.
2108 //
2109 void CWriter::visitBranchInst(BranchInst &I) {
2110
2111   if (I.isConditional()) {
2112     if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
2113       Out << "  if (";
2114       writeOperand(I.getCondition());
2115       Out << ") {\n";
2116
2117       printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
2118       printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
2119
2120       if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
2121         Out << "  } else {\n";
2122         printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
2123         printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
2124       }
2125     } else {
2126       // First goto not necessary, assume second one is...
2127       Out << "  if (!";
2128       writeOperand(I.getCondition());
2129       Out << ") {\n";
2130
2131       printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
2132       printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
2133     }
2134
2135     Out << "  }\n";
2136   } else {
2137     printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
2138     printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
2139   }
2140   Out << "\n";
2141 }
2142
2143 // PHI nodes get copied into temporary values at the end of predecessor basic
2144 // blocks.  We now need to copy these temporary values into the REAL value for
2145 // the PHI.
2146 void CWriter::visitPHINode(PHINode &I) {
2147   writeOperand(&I);
2148   Out << "__PHI_TEMPORARY";
2149 }
2150
2151
2152 void CWriter::visitBinaryOperator(Instruction &I) {
2153   // binary instructions, shift instructions, setCond instructions.
2154   assert(!isa<PointerType>(I.getType()));
2155
2156   // We must cast the results of binary operations which might be promoted.
2157   bool needsCast = false;
2158   if ((I.getType() == Type::Int8Ty) || (I.getType() == Type::Int16Ty) 
2159       || (I.getType() == Type::FloatTy)) {
2160     needsCast = true;
2161     Out << "((";
2162     printType(Out, I.getType(), false);
2163     Out << ")(";
2164   }
2165
2166   // If this is a negation operation, print it out as such.  For FP, we don't
2167   // want to print "-0.0 - X".
2168   if (BinaryOperator::isNeg(&I)) {
2169     Out << "-(";
2170     writeOperand(BinaryOperator::getNegArgument(cast<BinaryOperator>(&I)));
2171     Out << ")";
2172   } else if (I.getOpcode() == Instruction::FRem) {
2173     // Output a call to fmod/fmodf instead of emitting a%b
2174     if (I.getType() == Type::FloatTy)
2175       Out << "fmodf(";
2176     else
2177       Out << "fmod(";
2178     writeOperand(I.getOperand(0));
2179     Out << ", ";
2180     writeOperand(I.getOperand(1));
2181     Out << ")";
2182   } else {
2183
2184     // Write out the cast of the instruction's value back to the proper type
2185     // if necessary.
2186     bool NeedsClosingParens = writeInstructionCast(I);
2187
2188     // Certain instructions require the operand to be forced to a specific type
2189     // so we use writeOperandWithCast here instead of writeOperand. Similarly
2190     // below for operand 1
2191     writeOperandWithCast(I.getOperand(0), I.getOpcode());
2192
2193     switch (I.getOpcode()) {
2194     case Instruction::Add:  Out << " + "; break;
2195     case Instruction::Sub:  Out << " - "; break;
2196     case Instruction::Mul:  Out << " * "; break;
2197     case Instruction::URem:
2198     case Instruction::SRem:
2199     case Instruction::FRem: Out << " % "; break;
2200     case Instruction::UDiv:
2201     case Instruction::SDiv: 
2202     case Instruction::FDiv: Out << " / "; break;
2203     case Instruction::And:  Out << " & "; break;
2204     case Instruction::Or:   Out << " | "; break;
2205     case Instruction::Xor:  Out << " ^ "; break;
2206     case Instruction::Shl : Out << " << "; break;
2207     case Instruction::LShr:
2208     case Instruction::AShr: Out << " >> "; break;
2209     default: cerr << "Invalid operator type!" << I; abort();
2210     }
2211
2212     writeOperandWithCast(I.getOperand(1), I.getOpcode());
2213     if (NeedsClosingParens)
2214       Out << "))";
2215   }
2216
2217   if (needsCast) {
2218     Out << "))";
2219   }
2220 }
2221
2222 void CWriter::visitICmpInst(ICmpInst &I) {
2223   // We must cast the results of icmp which might be promoted.
2224   bool needsCast = false;
2225
2226   // Write out the cast of the instruction's value back to the proper type
2227   // if necessary.
2228   bool NeedsClosingParens = writeInstructionCast(I);
2229
2230   // Certain icmp predicate require the operand to be forced to a specific type
2231   // so we use writeOperandWithCast here instead of writeOperand. Similarly
2232   // below for operand 1
2233   writeOperandWithCast(I.getOperand(0), I.getPredicate());
2234
2235   switch (I.getPredicate()) {
2236   case ICmpInst::ICMP_EQ:  Out << " == "; break;
2237   case ICmpInst::ICMP_NE:  Out << " != "; break;
2238   case ICmpInst::ICMP_ULE:
2239   case ICmpInst::ICMP_SLE: Out << " <= "; break;
2240   case ICmpInst::ICMP_UGE:
2241   case ICmpInst::ICMP_SGE: Out << " >= "; break;
2242   case ICmpInst::ICMP_ULT:
2243   case ICmpInst::ICMP_SLT: Out << " < "; break;
2244   case ICmpInst::ICMP_UGT:
2245   case ICmpInst::ICMP_SGT: Out << " > "; break;
2246   default: cerr << "Invalid icmp predicate!" << I; abort();
2247   }
2248
2249   writeOperandWithCast(I.getOperand(1), I.getPredicate());
2250   if (NeedsClosingParens)
2251     Out << "))";
2252
2253   if (needsCast) {
2254     Out << "))";
2255   }
2256 }
2257
2258 void CWriter::visitFCmpInst(FCmpInst &I) {
2259   if (I.getPredicate() == FCmpInst::FCMP_FALSE) {
2260     Out << "0";
2261     return;
2262   }
2263   if (I.getPredicate() == FCmpInst::FCMP_TRUE) {
2264     Out << "1";
2265     return;
2266   }
2267
2268   const char* op = 0;
2269   switch (I.getPredicate()) {
2270   default: assert(0 && "Illegal FCmp predicate");
2271   case FCmpInst::FCMP_ORD: op = "ord"; break;
2272   case FCmpInst::FCMP_UNO: op = "uno"; break;
2273   case FCmpInst::FCMP_UEQ: op = "ueq"; break;
2274   case FCmpInst::FCMP_UNE: op = "une"; break;
2275   case FCmpInst::FCMP_ULT: op = "ult"; break;
2276   case FCmpInst::FCMP_ULE: op = "ule"; break;
2277   case FCmpInst::FCMP_UGT: op = "ugt"; break;
2278   case FCmpInst::FCMP_UGE: op = "uge"; break;
2279   case FCmpInst::FCMP_OEQ: op = "oeq"; break;
2280   case FCmpInst::FCMP_ONE: op = "one"; break;
2281   case FCmpInst::FCMP_OLT: op = "olt"; break;
2282   case FCmpInst::FCMP_OLE: op = "ole"; break;
2283   case FCmpInst::FCMP_OGT: op = "ogt"; break;
2284   case FCmpInst::FCMP_OGE: op = "oge"; break;
2285   }
2286
2287   Out << "llvm_fcmp_" << op << "(";
2288   // Write the first operand
2289   writeOperand(I.getOperand(0));
2290   Out << ", ";
2291   // Write the second operand
2292   writeOperand(I.getOperand(1));
2293   Out << ")";
2294 }
2295
2296 static const char * getFloatBitCastField(const Type *Ty) {
2297   switch (Ty->getTypeID()) {
2298     default: assert(0 && "Invalid Type");
2299     case Type::FloatTyID:  return "Float";
2300     case Type::DoubleTyID: return "Double";
2301     case Type::IntegerTyID: {
2302       unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
2303       if (NumBits <= 32)
2304         return "Int32";
2305       else
2306         return "Int64";
2307     }
2308   }
2309 }
2310
2311 void CWriter::visitCastInst(CastInst &I) {
2312   const Type *DstTy = I.getType();
2313   const Type *SrcTy = I.getOperand(0)->getType();
2314   Out << '(';
2315   if (isFPIntBitCast(I)) {
2316     // These int<->float and long<->double casts need to be handled specially
2317     Out << GetValueName(&I) << "__BITCAST_TEMPORARY." 
2318         << getFloatBitCastField(I.getOperand(0)->getType()) << " = ";
2319     writeOperand(I.getOperand(0));
2320     Out << ", " << GetValueName(&I) << "__BITCAST_TEMPORARY."
2321         << getFloatBitCastField(I.getType());
2322   } else {
2323     printCast(I.getOpcode(), SrcTy, DstTy);
2324     if (I.getOpcode() == Instruction::SExt && SrcTy == Type::Int1Ty) {
2325       // Make sure we really get a sext from bool by subtracing the bool from 0
2326       Out << "0-";
2327     }
2328     writeOperand(I.getOperand(0));
2329     if (DstTy == Type::Int1Ty && 
2330         (I.getOpcode() == Instruction::Trunc ||
2331          I.getOpcode() == Instruction::FPToUI ||
2332          I.getOpcode() == Instruction::FPToSI ||
2333          I.getOpcode() == Instruction::PtrToInt)) {
2334       // Make sure we really get a trunc to bool by anding the operand with 1 
2335       Out << "&1u";
2336     }
2337   }
2338   Out << ')';
2339 }
2340
2341 void CWriter::visitSelectInst(SelectInst &I) {
2342   Out << "((";
2343   writeOperand(I.getCondition());
2344   Out << ") ? (";
2345   writeOperand(I.getTrueValue());
2346   Out << ") : (";
2347   writeOperand(I.getFalseValue());
2348   Out << "))";
2349 }
2350
2351
2352 void CWriter::lowerIntrinsics(Function &F) {
2353   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
2354     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
2355       if (CallInst *CI = dyn_cast<CallInst>(I++))
2356         if (Function *F = CI->getCalledFunction())
2357           switch (F->getIntrinsicID()) {
2358           case Intrinsic::not_intrinsic:
2359           case Intrinsic::vastart:
2360           case Intrinsic::vacopy:
2361           case Intrinsic::vaend:
2362           case Intrinsic::returnaddress:
2363           case Intrinsic::frameaddress:
2364           case Intrinsic::setjmp:
2365           case Intrinsic::longjmp:
2366           case Intrinsic::prefetch:
2367           case Intrinsic::dbg_stoppoint:
2368           case Intrinsic::powi_f32:
2369           case Intrinsic::powi_f64:
2370             // We directly implement these intrinsics
2371             break;
2372           default:
2373             // If this is an intrinsic that directly corresponds to a GCC
2374             // builtin, we handle it.
2375             const char *BuiltinName = "";
2376 #define GET_GCC_BUILTIN_NAME
2377 #include "llvm/Intrinsics.gen"
2378 #undef GET_GCC_BUILTIN_NAME
2379             // If we handle it, don't lower it.
2380             if (BuiltinName[0]) break;
2381             
2382             // All other intrinsic calls we must lower.
2383             Instruction *Before = 0;
2384             if (CI != &BB->front())
2385               Before = prior(BasicBlock::iterator(CI));
2386
2387             IL->LowerIntrinsicCall(CI);
2388             if (Before) {        // Move iterator to instruction after call
2389               I = Before; ++I;
2390             } else {
2391               I = BB->begin();
2392             }
2393             break;
2394           }
2395 }
2396
2397
2398
2399 void CWriter::visitCallInst(CallInst &I) {
2400   //check if we have inline asm
2401   if (isInlineAsm(I)) {
2402     visitInlineAsm(I);
2403     return;
2404   }
2405
2406   bool WroteCallee = false;
2407
2408   // Handle intrinsic function calls first...
2409   if (Function *F = I.getCalledFunction())
2410     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
2411       switch (ID) {
2412       default: {
2413         // If this is an intrinsic that directly corresponds to a GCC
2414         // builtin, we emit it here.
2415         const char *BuiltinName = "";
2416 #define GET_GCC_BUILTIN_NAME
2417 #include "llvm/Intrinsics.gen"
2418 #undef GET_GCC_BUILTIN_NAME
2419         assert(BuiltinName[0] && "Unknown LLVM intrinsic!");
2420
2421         Out << BuiltinName;
2422         WroteCallee = true;
2423         break;
2424       }
2425       case Intrinsic::vastart:
2426         Out << "0; ";
2427
2428         Out << "va_start(*(va_list*)";
2429         writeOperand(I.getOperand(1));
2430         Out << ", ";
2431         // Output the last argument to the enclosing function...
2432         if (I.getParent()->getParent()->arg_empty()) {
2433           cerr << "The C backend does not currently support zero "
2434                << "argument varargs functions, such as '"
2435                << I.getParent()->getParent()->getName() << "'!\n";
2436           abort();
2437         }
2438         writeOperand(--I.getParent()->getParent()->arg_end());
2439         Out << ')';
2440         return;
2441       case Intrinsic::vaend:
2442         if (!isa<ConstantPointerNull>(I.getOperand(1))) {
2443           Out << "0; va_end(*(va_list*)";
2444           writeOperand(I.getOperand(1));
2445           Out << ')';
2446         } else {
2447           Out << "va_end(*(va_list*)0)";
2448         }
2449         return;
2450       case Intrinsic::vacopy:
2451         Out << "0; ";
2452         Out << "va_copy(*(va_list*)";
2453         writeOperand(I.getOperand(1));
2454         Out << ", *(va_list*)";
2455         writeOperand(I.getOperand(2));
2456         Out << ')';
2457         return;
2458       case Intrinsic::returnaddress:
2459         Out << "__builtin_return_address(";
2460         writeOperand(I.getOperand(1));
2461         Out << ')';
2462         return;
2463       case Intrinsic::frameaddress:
2464         Out << "__builtin_frame_address(";
2465         writeOperand(I.getOperand(1));
2466         Out << ')';
2467         return;
2468       case Intrinsic::powi_f32:
2469       case Intrinsic::powi_f64:
2470         Out << "__builtin_powi(";
2471         writeOperand(I.getOperand(1));
2472         Out << ", ";
2473         writeOperand(I.getOperand(2));
2474         Out << ')';
2475         return;
2476       case Intrinsic::setjmp:
2477         Out << "setjmp(*(jmp_buf*)";
2478         writeOperand(I.getOperand(1));
2479         Out << ')';
2480         return;
2481       case Intrinsic::longjmp:
2482         Out << "longjmp(*(jmp_buf*)";
2483         writeOperand(I.getOperand(1));
2484         Out << ", ";
2485         writeOperand(I.getOperand(2));
2486         Out << ')';
2487         return;
2488       case Intrinsic::prefetch:
2489         Out << "LLVM_PREFETCH((const void *)";
2490         writeOperand(I.getOperand(1));
2491         Out << ", ";
2492         writeOperand(I.getOperand(2));
2493         Out << ", ";
2494         writeOperand(I.getOperand(3));
2495         Out << ")";
2496         return;
2497       case Intrinsic::dbg_stoppoint: {
2498         // If we use writeOperand directly we get a "u" suffix which is rejected
2499         // by gcc.
2500         DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
2501
2502         Out << "\n#line "
2503             << SPI.getLine()
2504             << " \"" << SPI.getDirectory()
2505             << SPI.getFileName() << "\"\n";
2506         return;
2507       }
2508       }
2509     }
2510
2511   Value *Callee = I.getCalledValue();
2512
2513   const PointerType  *PTy   = cast<PointerType>(Callee->getType());
2514   const FunctionType *FTy   = cast<FunctionType>(PTy->getElementType());
2515
2516   // If this is a call to a struct-return function, assign to the first
2517   // parameter instead of passing it to the call.
2518   bool isStructRet = FTy->isStructReturn();
2519   if (isStructRet) {
2520     Out << "*(";
2521     writeOperand(I.getOperand(1));
2522     Out << ") = ";
2523   }
2524   
2525   if (I.isTailCall()) Out << " /*tail*/ ";
2526   
2527   if (!WroteCallee) {
2528     // If this is an indirect call to a struct return function, we need to cast
2529     // the pointer.
2530     bool NeedsCast = isStructRet && !isa<Function>(Callee);
2531
2532     // GCC is a real PITA.  It does not permit codegening casts of functions to
2533     // function pointers if they are in a call (it generates a trap instruction
2534     // instead!).  We work around this by inserting a cast to void* in between
2535     // the function and the function pointer cast.  Unfortunately, we can't just
2536     // form the constant expression here, because the folder will immediately
2537     // nuke it.
2538     //
2539     // Note finally, that this is completely unsafe.  ANSI C does not guarantee
2540     // that void* and function pointers have the same size. :( To deal with this
2541     // in the common case, we handle casts where the number of arguments passed
2542     // match exactly.
2543     //
2544     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee))
2545       if (CE->isCast())
2546         if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) {
2547           NeedsCast = true;
2548           Callee = RF;
2549         }
2550   
2551     if (NeedsCast) {
2552       // Ok, just cast the pointer type.
2553       Out << "((";
2554       if (!isStructRet)
2555         printType(Out, I.getCalledValue()->getType());
2556       else
2557         printStructReturnPointerFunctionType(Out, 
2558                              cast<PointerType>(I.getCalledValue()->getType()));
2559       Out << ")(void*)";
2560     }
2561     writeOperand(Callee);
2562     if (NeedsCast) Out << ')';
2563   }
2564
2565   Out << '(';
2566
2567   unsigned NumDeclaredParams = FTy->getNumParams();
2568
2569   CallSite::arg_iterator AI = I.op_begin()+1, AE = I.op_end();
2570   unsigned ArgNo = 0;
2571   if (isStructRet) {   // Skip struct return argument.
2572     ++AI;
2573     ++ArgNo;
2574   }
2575       
2576   bool PrintedArg = false;
2577   unsigned Idx = 1;
2578   for (; AI != AE; ++AI, ++ArgNo, ++Idx) {
2579     if (PrintedArg) Out << ", ";
2580     if (ArgNo < NumDeclaredParams &&
2581         (*AI)->getType() != FTy->getParamType(ArgNo)) {
2582       Out << '(';
2583       printType(Out, FTy->getParamType(ArgNo), 
2584             /*isSigned=*/FTy->paramHasAttr(Idx, FunctionType::SExtAttribute));
2585       Out << ')';
2586     }
2587     writeOperand(*AI);
2588     PrintedArg = true;
2589   }
2590   Out << ')';
2591 }
2592
2593
2594 //This converts the llvm constraint string to something gcc is expecting.
2595 //TODO: work out platform independent constraints and factor those out
2596 //      of the per target tables
2597 //      handle multiple constraint codes
2598 std::string CWriter::InterpretASMConstraint(InlineAsm::ConstraintInfo& c) {
2599
2600   assert(c.Codes.size() == 1 && "Too many asm constraint codes to handle");
2601
2602   const char** table = 0;
2603   
2604   //Grab the translation table from TargetAsmInfo if it exists
2605   if (!TAsm) {
2606     std::string E;
2607     const TargetMachineRegistry::Entry* Match = 
2608       TargetMachineRegistry::getClosestStaticTargetForModule(*TheModule, E);
2609     if (Match) {
2610       //Per platform Target Machines don't exist, so create it
2611       // this must be done only once
2612       const TargetMachine* TM = Match->CtorFn(*TheModule, "");
2613       TAsm = TM->getTargetAsmInfo();
2614     }
2615   }
2616   if (TAsm)
2617     table = TAsm->getAsmCBE();
2618
2619   //Search the translation table if it exists
2620   for (int i = 0; table && table[i]; i += 2)
2621     if (c.Codes[0] == table[i])
2622       return table[i+1];
2623
2624   //default is identity
2625   return c.Codes[0];
2626 }
2627
2628 //TODO: import logic from AsmPrinter.cpp
2629 static std::string gccifyAsm(std::string asmstr) {
2630   for (std::string::size_type i = 0; i != asmstr.size(); ++i)
2631     if (asmstr[i] == '\n')
2632       asmstr.replace(i, 1, "\\n");
2633     else if (asmstr[i] == '\t')
2634       asmstr.replace(i, 1, "\\t");
2635     else if (asmstr[i] == '$') {
2636       if (asmstr[i + 1] == '{') {
2637         std::string::size_type a = asmstr.find_first_of(':', i + 1);
2638         std::string::size_type b = asmstr.find_first_of('}', i + 1);
2639         std::string n = "%" + 
2640           asmstr.substr(a + 1, b - a - 1) +
2641           asmstr.substr(i + 2, a - i - 2);
2642         asmstr.replace(i, b - i + 1, n);
2643         i += n.size() - 1;
2644       } else
2645         asmstr.replace(i, 1, "%");
2646     }
2647     else if (asmstr[i] == '%')//grr
2648       { asmstr.replace(i, 1, "%%"); ++i;}
2649   
2650   return asmstr;
2651 }
2652
2653 //TODO: assumptions about what consume arguments from the call are likely wrong
2654 //      handle communitivity
2655 void CWriter::visitInlineAsm(CallInst &CI) {
2656   InlineAsm* as = cast<InlineAsm>(CI.getOperand(0));
2657   std::vector<InlineAsm::ConstraintInfo> Constraints = as->ParseConstraints();
2658   std::vector<std::pair<std::string, Value*> > Input;
2659   std::vector<std::pair<std::string, Value*> > Output;
2660   std::string Clobber;
2661   int count = CI.getType() == Type::VoidTy ? 1 : 0;
2662   for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
2663          E = Constraints.end(); I != E; ++I) {
2664     assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
2665     std::string c = 
2666       InterpretASMConstraint(*I);
2667     switch(I->Type) {
2668     default:
2669       assert(0 && "Unknown asm constraint");
2670       break;
2671     case InlineAsm::isInput: {
2672       if (c.size()) {
2673         Input.push_back(std::make_pair(c, count ? CI.getOperand(count) : &CI));
2674         ++count; //consume arg
2675       }
2676       break;
2677     }
2678     case InlineAsm::isOutput: {
2679       if (c.size()) {
2680         Output.push_back(std::make_pair("="+((I->isEarlyClobber ? "&" : "")+c),
2681                                         count ? CI.getOperand(count) : &CI));
2682         ++count; //consume arg
2683       }
2684       break;
2685     }
2686     case InlineAsm::isClobber: {
2687       if (c.size()) 
2688         Clobber += ",\"" + c + "\"";
2689       break;
2690     }
2691     }
2692   }
2693   
2694   //fix up the asm string for gcc
2695   std::string asmstr = gccifyAsm(as->getAsmString());
2696   
2697   Out << "__asm__ volatile (\"" << asmstr << "\"\n";
2698   Out << "        :";
2699   for (std::vector<std::pair<std::string, Value*> >::iterator I = Output.begin(),
2700          E = Output.end(); I != E; ++I) {
2701     Out << "\"" << I->first << "\"(";
2702     writeOperandRaw(I->second);
2703     Out << ")";
2704     if (I + 1 != E)
2705       Out << ",";
2706   }
2707   Out << "\n        :";
2708   for (std::vector<std::pair<std::string, Value*> >::iterator I = Input.begin(),
2709          E = Input.end(); I != E; ++I) {
2710     Out << "\"" << I->first << "\"(";
2711     writeOperandRaw(I->second);
2712     Out << ")";
2713     if (I + 1 != E)
2714       Out << ",";
2715   }
2716   if (Clobber.size())
2717     Out << "\n        :" << Clobber.substr(1);
2718   Out << ")";
2719 }
2720
2721 void CWriter::visitMallocInst(MallocInst &I) {
2722   assert(0 && "lowerallocations pass didn't work!");
2723 }
2724
2725 void CWriter::visitAllocaInst(AllocaInst &I) {
2726   Out << '(';
2727   printType(Out, I.getType());
2728   Out << ") alloca(sizeof(";
2729   printType(Out, I.getType()->getElementType());
2730   Out << ')';
2731   if (I.isArrayAllocation()) {
2732     Out << " * " ;
2733     writeOperand(I.getOperand(0));
2734   }
2735   Out << ')';
2736 }
2737
2738 void CWriter::visitFreeInst(FreeInst &I) {
2739   assert(0 && "lowerallocations pass didn't work!");
2740 }
2741
2742 void CWriter::printIndexingExpression(Value *Ptr, gep_type_iterator I,
2743                                       gep_type_iterator E) {
2744   bool HasImplicitAddress = false;
2745   // If accessing a global value with no indexing, avoid *(&GV) syndrome
2746   if (isa<GlobalValue>(Ptr)) {
2747     HasImplicitAddress = true;
2748   } else if (isDirectAlloca(Ptr)) {
2749     HasImplicitAddress = true;
2750   }
2751
2752   if (I == E) {
2753     if (!HasImplicitAddress)
2754       Out << '*';  // Implicit zero first argument: '*x' is equivalent to 'x[0]'
2755
2756     writeOperandInternal(Ptr);
2757     return;
2758   }
2759
2760   const Constant *CI = dyn_cast<Constant>(I.getOperand());
2761   if (HasImplicitAddress && (!CI || !CI->isNullValue()))
2762     Out << "(&";
2763
2764   writeOperandInternal(Ptr);
2765
2766   if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
2767     Out << ')';
2768     HasImplicitAddress = false;  // HIA is only true if we haven't addressed yet
2769   }
2770
2771   assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
2772          "Can only have implicit address with direct accessing");
2773
2774   if (HasImplicitAddress) {
2775     ++I;
2776   } else if (CI && CI->isNullValue()) {
2777     gep_type_iterator TmpI = I; ++TmpI;
2778
2779     // Print out the -> operator if possible...
2780     if (TmpI != E && isa<StructType>(*TmpI)) {
2781       Out << (HasImplicitAddress ? "." : "->");
2782       Out << "field" << cast<ConstantInt>(TmpI.getOperand())->getZExtValue();
2783       I = ++TmpI;
2784     }
2785   }
2786
2787   for (; I != E; ++I)
2788     if (isa<StructType>(*I)) {
2789       Out << ".field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
2790     } else {
2791       Out << '[';
2792       writeOperand(I.getOperand());
2793       Out << ']';
2794     }
2795 }
2796
2797 void CWriter::visitLoadInst(LoadInst &I) {
2798   Out << '*';
2799   if (I.isVolatile()) {
2800     Out << "((";
2801     printType(Out, I.getType(), false, "volatile*");
2802     Out << ")";
2803   }
2804
2805   writeOperand(I.getOperand(0));
2806
2807   if (I.isVolatile())
2808     Out << ')';
2809 }
2810
2811 void CWriter::visitStoreInst(StoreInst &I) {
2812   Out << '*';
2813   if (I.isVolatile()) {
2814     Out << "((";
2815     printType(Out, I.getOperand(0)->getType(), false, " volatile*");
2816     Out << ")";
2817   }
2818   writeOperand(I.getPointerOperand());
2819   if (I.isVolatile()) Out << ')';
2820   Out << " = ";
2821   Value *Operand = I.getOperand(0);
2822   Constant *BitMask = 0;
2823   if (const IntegerType* ITy = dyn_cast<IntegerType>(Operand->getType()))
2824     if (!ITy->isPowerOf2ByteWidth())
2825       // We have a bit width that doesn't match an even power-of-2 byte
2826       // size. Consequently we must & the value with the type's bit mask
2827       BitMask = ConstantInt::get(ITy, ITy->getBitMask());
2828   if (BitMask)
2829     Out << "((";
2830   writeOperand(Operand);
2831   if (BitMask) {
2832     Out << ") & ";
2833     printConstant(BitMask);
2834     Out << ")"; 
2835   }
2836 }
2837
2838 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
2839   Out << '&';
2840   printIndexingExpression(I.getPointerOperand(), gep_type_begin(I),
2841                           gep_type_end(I));
2842 }
2843
2844 void CWriter::visitVAArgInst(VAArgInst &I) {
2845   Out << "va_arg(*(va_list*)";
2846   writeOperand(I.getOperand(0));
2847   Out << ", ";
2848   printType(Out, I.getType());
2849   Out << ");\n ";
2850 }
2851
2852 //===----------------------------------------------------------------------===//
2853 //                       External Interface declaration
2854 //===----------------------------------------------------------------------===//
2855
2856 bool CTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
2857                                               std::ostream &o,
2858                                               CodeGenFileType FileType,
2859                                               bool Fast) {
2860   if (FileType != TargetMachine::AssemblyFile) return true;
2861
2862   PM.add(createLowerGCPass());
2863   PM.add(createLowerAllocationsPass(true));
2864   PM.add(createLowerInvokePass());
2865   PM.add(createCFGSimplificationPass());   // clean up after lower invoke.
2866   PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
2867   PM.add(new CWriter(o));
2868   return false;
2869 }