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