LLVM API Documentation

Target/CBackend/Writer.cpp

Go to the documentation of this file.
00001 //===-- Writer.cpp - Library for converting LLVM code to C ----------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file was developed by the LLVM research group and is distributed under
00006 // the University of Illinois Open Source License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This library converts LLVM code to C code, compilable by GCC and other C
00011 // compilers.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "CTargetMachine.h"
00016 #include "llvm/CallingConv.h"
00017 #include "llvm/Constants.h"
00018 #include "llvm/DerivedTypes.h"
00019 #include "llvm/Module.h"
00020 #include "llvm/Instructions.h"
00021 #include "llvm/Pass.h"
00022 #include "llvm/PassManager.h"
00023 #include "llvm/SymbolTable.h"
00024 #include "llvm/Intrinsics.h"
00025 #include "llvm/IntrinsicInst.h"
00026 #include "llvm/Analysis/ConstantsScanner.h"
00027 #include "llvm/Analysis/FindUsedTypes.h"
00028 #include "llvm/Analysis/LoopInfo.h"
00029 #include "llvm/CodeGen/IntrinsicLowering.h"
00030 #include "llvm/Transforms/Scalar.h"
00031 #include "llvm/Target/TargetMachineRegistry.h"
00032 #include "llvm/Support/CallSite.h"
00033 #include "llvm/Support/CFG.h"
00034 #include "llvm/Support/GetElementPtrTypeIterator.h"
00035 #include "llvm/Support/InstVisitor.h"
00036 #include "llvm/Support/Mangler.h"
00037 #include "llvm/Support/MathExtras.h"
00038 #include "llvm/ADT/StringExtras.h"
00039 #include "llvm/ADT/STLExtras.h"
00040 #include "llvm/Support/MathExtras.h"
00041 #include "llvm/Config/config.h"
00042 #include <algorithm>
00043 #include <iostream>
00044 #include <ios>
00045 #include <sstream>
00046 using namespace llvm;
00047 
00048 namespace {
00049   // Register the target.
00050   RegisterTarget<CTargetMachine> X("c", "  C backend");
00051 
00052   /// CBackendNameAllUsedStructsAndMergeFunctions - This pass inserts names for
00053   /// any unnamed structure types that are used by the program, and merges
00054   /// external functions with the same name.
00055   ///
00056   class CBackendNameAllUsedStructsAndMergeFunctions : public ModulePass {
00057     void getAnalysisUsage(AnalysisUsage &AU) const {
00058       AU.addRequired<FindUsedTypes>();
00059     }
00060 
00061     virtual const char *getPassName() const {
00062       return "C backend type canonicalizer";
00063     }
00064 
00065     virtual bool runOnModule(Module &M);
00066   };
00067 
00068   /// CWriter - This class is the main chunk of code that converts an LLVM
00069   /// module to a C translation unit.
00070   class CWriter : public FunctionPass, public InstVisitor<CWriter> {
00071     std::ostream &Out;
00072     DefaultIntrinsicLowering IL;
00073     Mangler *Mang;
00074     LoopInfo *LI;
00075     const Module *TheModule;
00076     std::map<const Type *, std::string> TypeNames;
00077 
00078     std::map<const ConstantFP *, unsigned> FPConstantMap;
00079   public:
00080     CWriter(std::ostream &o) : Out(o) {}
00081 
00082     virtual const char *getPassName() const { return "C backend"; }
00083 
00084     void getAnalysisUsage(AnalysisUsage &AU) const {
00085       AU.addRequired<LoopInfo>();
00086       AU.setPreservesAll();
00087     }
00088 
00089     virtual bool doInitialization(Module &M);
00090 
00091     bool runOnFunction(Function &F) {
00092       LI = &getAnalysis<LoopInfo>();
00093 
00094       // Get rid of intrinsics we can't handle.
00095       lowerIntrinsics(F);
00096 
00097       // Output all floating point constants that cannot be printed accurately.
00098       printFloatingPointConstants(F);
00099 
00100       // Ensure that no local symbols conflict with global symbols.
00101       F.renameLocalSymbols();
00102 
00103       printFunction(F);
00104       FPConstantMap.clear();
00105       return false;
00106     }
00107 
00108     virtual bool doFinalization(Module &M) {
00109       // Free memory...
00110       delete Mang;
00111       TypeNames.clear();
00112       return false;
00113     }
00114 
00115     std::ostream &printType(std::ostream &Out, const Type *Ty,
00116                             const std::string &VariableName = "",
00117                             bool IgnoreName = false);
00118 
00119     void printStructReturnPointerFunctionType(std::ostream &Out,
00120                                               const PointerType *Ty);
00121     
00122     void writeOperand(Value *Operand);
00123     void writeOperandInternal(Value *Operand);
00124 
00125   private :
00126     void lowerIntrinsics(Function &F);
00127 
00128     void printModule(Module *M);
00129     void printModuleTypes(const SymbolTable &ST);
00130     void printContainedStructs(const Type *Ty, std::set<const StructType *> &);
00131     void printFloatingPointConstants(Function &F);
00132     void printFunctionSignature(const Function *F, bool Prototype);
00133 
00134     void printFunction(Function &);
00135     void printBasicBlock(BasicBlock *BB);
00136     void printLoop(Loop *L);
00137 
00138     void printConstant(Constant *CPV);
00139     void printConstantArray(ConstantArray *CPA);
00140     void printConstantPacked(ConstantPacked *CP);
00141 
00142     // isInlinableInst - Attempt to inline instructions into their uses to build
00143     // trees as much as possible.  To do this, we have to consistently decide
00144     // what is acceptable to inline, so that variable declarations don't get
00145     // printed and an extra copy of the expr is not emitted.
00146     //
00147     static bool isInlinableInst(const Instruction &I) {
00148       // Always inline setcc instructions, even if they are shared by multiple
00149       // expressions.  GCC generates horrible code if we don't.
00150       if (isa<SetCondInst>(I)) return true;
00151 
00152       // Must be an expression, must be used exactly once.  If it is dead, we
00153       // emit it inline where it would go.
00154       if (I.getType() == Type::VoidTy || !I.hasOneUse() ||
00155           isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
00156           isa<LoadInst>(I) || isa<VAArgInst>(I))
00157         // Don't inline a load across a store or other bad things!
00158         return false;
00159 
00160       // Only inline instruction it it's use is in the same BB as the inst.
00161       return I.getParent() == cast<Instruction>(I.use_back())->getParent();
00162     }
00163 
00164     // isDirectAlloca - Define fixed sized allocas in the entry block as direct
00165     // variables which are accessed with the & operator.  This causes GCC to
00166     // generate significantly better code than to emit alloca calls directly.
00167     //
00168     static const AllocaInst *isDirectAlloca(const Value *V) {
00169       const AllocaInst *AI = dyn_cast<AllocaInst>(V);
00170       if (!AI) return false;
00171       if (AI->isArrayAllocation())
00172         return 0;   // FIXME: we can also inline fixed size array allocas!
00173       if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
00174         return 0;
00175       return AI;
00176     }
00177 
00178     // Instruction visitation functions
00179     friend class InstVisitor<CWriter>;
00180 
00181     void visitReturnInst(ReturnInst &I);
00182     void visitBranchInst(BranchInst &I);
00183     void visitSwitchInst(SwitchInst &I);
00184     void visitInvokeInst(InvokeInst &I) {
00185       assert(0 && "Lowerinvoke pass didn't work!");
00186     }
00187 
00188     void visitUnwindInst(UnwindInst &I) {
00189       assert(0 && "Lowerinvoke pass didn't work!");
00190     }
00191     void visitUnreachableInst(UnreachableInst &I);
00192 
00193     void visitPHINode(PHINode &I);
00194     void visitBinaryOperator(Instruction &I);
00195 
00196     void visitCastInst (CastInst &I);
00197     void visitSelectInst(SelectInst &I);
00198     void visitCallInst (CallInst &I);
00199     void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
00200 
00201     void visitMallocInst(MallocInst &I);
00202     void visitAllocaInst(AllocaInst &I);
00203     void visitFreeInst  (FreeInst   &I);
00204     void visitLoadInst  (LoadInst   &I);
00205     void visitStoreInst (StoreInst  &I);
00206     void visitGetElementPtrInst(GetElementPtrInst &I);
00207     void visitVAArgInst (VAArgInst &I);
00208 
00209     void visitInstruction(Instruction &I) {
00210       std::cerr << "C Writer does not know about " << I;
00211       abort();
00212     }
00213 
00214     void outputLValue(Instruction *I) {
00215       Out << "  " << Mang->getValueName(I) << " = ";
00216     }
00217 
00218     bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
00219     void printPHICopiesForSuccessor(BasicBlock *CurBlock,
00220                                     BasicBlock *Successor, unsigned Indent);
00221     void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
00222                             unsigned Indent);
00223     void printIndexingExpression(Value *Ptr, gep_type_iterator I,
00224                                  gep_type_iterator E);
00225   };
00226 }
00227 
00228 /// This method inserts names for any unnamed structure types that are used by
00229 /// the program, and removes names from structure types that are not used by the
00230 /// program.
00231 ///
00232 bool CBackendNameAllUsedStructsAndMergeFunctions::runOnModule(Module &M) {
00233   // Get a set of types that are used by the program...
00234   std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
00235 
00236   // Loop over the module symbol table, removing types from UT that are
00237   // already named, and removing names for types that are not used.
00238   //
00239   SymbolTable &MST = M.getSymbolTable();
00240   for (SymbolTable::type_iterator TI = MST.type_begin(), TE = MST.type_end();
00241        TI != TE; ) {
00242     SymbolTable::type_iterator I = TI++;
00243 
00244     // If this is not used, remove it from the symbol table.
00245     std::set<const Type *>::iterator UTI = UT.find(I->second);
00246     if (UTI == UT.end())
00247       MST.remove(I);
00248     else
00249       UT.erase(UTI);    // Only keep one name for this type.
00250   }
00251 
00252   // UT now contains types that are not named.  Loop over it, naming
00253   // structure types.
00254   //
00255   bool Changed = false;
00256   unsigned RenameCounter = 0;
00257   for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
00258        I != E; ++I)
00259     if (const StructType *ST = dyn_cast<StructType>(*I)) {
00260       while (M.addTypeName("unnamed"+utostr(RenameCounter), ST))
00261         ++RenameCounter;
00262       Changed = true;
00263     }
00264       
00265       
00266   // Loop over all external functions and globals.  If we have two with
00267   // identical names, merge them.
00268   // FIXME: This code should disappear when we don't allow values with the same
00269   // names when they have different types!
00270   std::map<std::string, GlobalValue*> ExtSymbols;
00271   for (Module::iterator I = M.begin(), E = M.end(); I != E;) {
00272     Function *GV = I++;
00273     if (GV->isExternal() && GV->hasName()) {
00274       std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
00275         = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
00276       if (!X.second) {
00277         // Found a conflict, replace this global with the previous one.
00278         GlobalValue *OldGV = X.first->second;
00279         GV->replaceAllUsesWith(ConstantExpr::getCast(OldGV, GV->getType()));
00280         GV->eraseFromParent();
00281         Changed = true;
00282       }
00283     }
00284   }
00285   // Do the same for globals.
00286   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
00287        I != E;) {
00288     GlobalVariable *GV = I++;
00289     if (GV->isExternal() && GV->hasName()) {
00290       std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
00291         = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
00292       if (!X.second) {
00293         // Found a conflict, replace this global with the previous one.
00294         GlobalValue *OldGV = X.first->second;
00295         GV->replaceAllUsesWith(ConstantExpr::getCast(OldGV, GV->getType()));
00296         GV->eraseFromParent();
00297         Changed = true;
00298       }
00299     }
00300   }
00301   
00302   return Changed;
00303 }
00304 
00305 /// printStructReturnPointerFunctionType - This is like printType for a struct
00306 /// return type, except, instead of printing the type as void (*)(Struct*, ...)
00307 /// print it as "Struct (*)(...)", for struct return functions.
00308 void CWriter::printStructReturnPointerFunctionType(std::ostream &Out,
00309                                                    const PointerType *TheTy) {
00310   const FunctionType *FTy = cast<FunctionType>(TheTy->getElementType());
00311   std::stringstream FunctionInnards;
00312   FunctionInnards << " (*) (";
00313   bool PrintedType = false;
00314 
00315   FunctionType::param_iterator I = FTy->param_begin(), E = FTy->param_end();
00316   const Type *RetTy = cast<PointerType>(I->get())->getElementType();
00317   for (++I; I != E; ++I) {
00318     if (PrintedType)
00319       FunctionInnards << ", ";
00320     printType(FunctionInnards, *I, "");
00321     PrintedType = true;
00322   }
00323   if (FTy->isVarArg()) {
00324     if (PrintedType)
00325       FunctionInnards << ", ...";
00326   } else if (!PrintedType) {
00327     FunctionInnards << "void";
00328   }
00329   FunctionInnards << ')';
00330   std::string tstr = FunctionInnards.str();
00331   printType(Out, RetTy, tstr);
00332 }
00333 
00334 
00335 // Pass the Type* and the variable name and this prints out the variable
00336 // declaration.
00337 //
00338 std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
00339                                  const std::string &NameSoFar,
00340                                  bool IgnoreName) {
00341   if (Ty->isPrimitiveType())
00342     switch (Ty->getTypeID()) {
00343     case Type::VoidTyID:   return Out << "void "               << NameSoFar;
00344     case Type::BoolTyID:   return Out << "bool "               << NameSoFar;
00345     case Type::UByteTyID:  return Out << "unsigned char "      << NameSoFar;
00346     case Type::SByteTyID:  return Out << "signed char "        << NameSoFar;
00347     case Type::UShortTyID: return Out << "unsigned short "     << NameSoFar;
00348     case Type::ShortTyID:  return Out << "short "              << NameSoFar;
00349     case Type::UIntTyID:   return Out << "unsigned "           << NameSoFar;
00350     case Type::IntTyID:    return Out << "int "                << NameSoFar;
00351     case Type::ULongTyID:  return Out << "unsigned long long " << NameSoFar;
00352     case Type::LongTyID:   return Out << "signed long long "   << NameSoFar;
00353     case Type::FloatTyID:  return Out << "float "              << NameSoFar;
00354     case Type::DoubleTyID: return Out << "double "             << NameSoFar;
00355     default :
00356       std::cerr << "Unknown primitive type: " << *Ty << "\n";
00357       abort();
00358     }
00359 
00360   // Check to see if the type is named.
00361   if (!IgnoreName || isa<OpaqueType>(Ty)) {
00362     std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
00363     if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
00364   }
00365 
00366   switch (Ty->getTypeID()) {
00367   case Type::FunctionTyID: {
00368     const FunctionType *FTy = cast<FunctionType>(Ty);
00369     std::stringstream FunctionInnards;
00370     FunctionInnards << " (" << NameSoFar << ") (";
00371     for (FunctionType::param_iterator I = FTy->param_begin(),
00372            E = FTy->param_end(); I != E; ++I) {
00373       if (I != FTy->param_begin())
00374         FunctionInnards << ", ";
00375       printType(FunctionInnards, *I, "");
00376     }
00377     if (FTy->isVarArg()) {
00378       if (FTy->getNumParams())
00379         FunctionInnards << ", ...";
00380     } else if (!FTy->getNumParams()) {
00381       FunctionInnards << "void";
00382     }
00383     FunctionInnards << ')';
00384     std::string tstr = FunctionInnards.str();
00385     printType(Out, FTy->getReturnType(), tstr);
00386     return Out;
00387   }
00388   case Type::StructTyID: {
00389     const StructType *STy = cast<StructType>(Ty);
00390     Out << NameSoFar + " {\n";
00391     unsigned Idx = 0;
00392     for (StructType::element_iterator I = STy->element_begin(),
00393            E = STy->element_end(); I != E; ++I) {
00394       Out << "  ";
00395       printType(Out, *I, "field" + utostr(Idx++));
00396       Out << ";\n";
00397     }
00398     return Out << '}';
00399   }
00400 
00401   case Type::PointerTyID: {
00402     const PointerType *PTy = cast<PointerType>(Ty);
00403     std::string ptrName = "*" + NameSoFar;
00404 
00405     if (isa<ArrayType>(PTy->getElementType()) ||
00406         isa<PackedType>(PTy->getElementType()))
00407       ptrName = "(" + ptrName + ")";
00408 
00409     return printType(Out, PTy->getElementType(), ptrName);
00410   }
00411 
00412   case Type::ArrayTyID: {
00413     const ArrayType *ATy = cast<ArrayType>(Ty);
00414     unsigned NumElements = ATy->getNumElements();
00415     if (NumElements == 0) NumElements = 1;
00416     return printType(Out, ATy->getElementType(),
00417                      NameSoFar + "[" + utostr(NumElements) + "]");
00418   }
00419 
00420   case Type::PackedTyID: {
00421     const PackedType *PTy = cast<PackedType>(Ty);
00422     unsigned NumElements = PTy->getNumElements();
00423     if (NumElements == 0) NumElements = 1;
00424     return printType(Out, PTy->getElementType(),
00425                      NameSoFar + "[" + utostr(NumElements) + "]");
00426   }
00427 
00428   case Type::OpaqueTyID: {
00429     static int Count = 0;
00430     std::string TyName = "struct opaque_" + itostr(Count++);
00431     assert(TypeNames.find(Ty) == TypeNames.end());
00432     TypeNames[Ty] = TyName;
00433     return Out << TyName << ' ' << NameSoFar;
00434   }
00435   default:
00436     assert(0 && "Unhandled case in getTypeProps!");
00437     abort();
00438   }
00439 
00440   return Out;
00441 }
00442 
00443 void CWriter::printConstantArray(ConstantArray *CPA) {
00444 
00445   // As a special case, print the array as a string if it is an array of
00446   // ubytes or an array of sbytes with positive values.
00447   //
00448   const Type *ETy = CPA->getType()->getElementType();
00449   bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
00450 
00451   // Make sure the last character is a null char, as automatically added by C
00452   if (isString && (CPA->getNumOperands() == 0 ||
00453                    !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
00454     isString = false;
00455 
00456   if (isString) {
00457     Out << '\"';
00458     // Keep track of whether the last number was a hexadecimal escape
00459     bool LastWasHex = false;
00460 
00461     // Do not include the last character, which we know is null
00462     for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
00463       unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getRawValue();
00464 
00465       // Print it out literally if it is a printable character.  The only thing
00466       // to be careful about is when the last letter output was a hex escape
00467       // code, in which case we have to be careful not to print out hex digits
00468       // explicitly (the C compiler thinks it is a continuation of the previous
00469       // character, sheesh...)
00470       //
00471       if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
00472         LastWasHex = false;
00473         if (C == '"' || C == '\\')
00474           Out << "\\" << C;
00475         else
00476           Out << C;
00477       } else {
00478         LastWasHex = false;
00479         switch (C) {
00480         case '\n': Out << "\\n"; break;
00481         case '\t': Out << "\\t"; break;
00482         case '\r': Out << "\\r"; break;
00483         case '\v': Out << "\\v"; break;
00484         case '\a': Out << "\\a"; break;
00485         case '\"': Out << "\\\""; break;
00486         case '\'': Out << "\\\'"; break;
00487         default:
00488           Out << "\\x";
00489           Out << (char)(( C/16  < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
00490           Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
00491           LastWasHex = true;
00492           break;
00493         }
00494       }
00495     }
00496     Out << '\"';
00497   } else {
00498     Out << '{';
00499     if (CPA->getNumOperands()) {
00500       Out << ' ';
00501       printConstant(cast<Constant>(CPA->getOperand(0)));
00502       for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
00503         Out << ", ";
00504         printConstant(cast<Constant>(CPA->getOperand(i)));
00505       }
00506     }
00507     Out << " }";
00508   }
00509 }
00510 
00511 void CWriter::printConstantPacked(ConstantPacked *CP) {
00512   Out << '{';
00513   if (CP->getNumOperands()) {
00514     Out << ' ';
00515     printConstant(cast<Constant>(CP->getOperand(0)));
00516     for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
00517       Out << ", ";
00518       printConstant(cast<Constant>(CP->getOperand(i)));
00519     }
00520   }
00521   Out << " }";
00522 }
00523 
00524 // isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
00525 // textually as a double (rather than as a reference to a stack-allocated
00526 // variable). We decide this by converting CFP to a string and back into a
00527 // double, and then checking whether the conversion results in a bit-equal
00528 // double to the original value of CFP. This depends on us and the target C
00529 // compiler agreeing on the conversion process (which is pretty likely since we
00530 // only deal in IEEE FP).
00531 //
00532 static bool isFPCSafeToPrint(const ConstantFP *CFP) {
00533 #if HAVE_PRINTF_A
00534   char Buffer[100];
00535   sprintf(Buffer, "%a", CFP->getValue());
00536 
00537   if (!strncmp(Buffer, "0x", 2) ||
00538       !strncmp(Buffer, "-0x", 3) ||
00539       !strncmp(Buffer, "+0x", 3))
00540     return atof(Buffer) == CFP->getValue();
00541   return false;
00542 #else
00543   std::string StrVal = ftostr(CFP->getValue());
00544 
00545   while (StrVal[0] == ' ')
00546     StrVal.erase(StrVal.begin());
00547 
00548   // Check to make sure that the stringized number is not some string like "Inf"
00549   // or NaN.  Check that the string matches the "[-+]?[0-9]" regex.
00550   if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
00551       ((StrVal[0] == '-' || StrVal[0] == '+') &&
00552        (StrVal[1] >= '0' && StrVal[1] <= '9')))
00553     // Reparse stringized version!
00554     return atof(StrVal.c_str()) == CFP->getValue();
00555   return false;
00556 #endif
00557 }
00558 
00559 // printConstant - The LLVM Constant to C Constant converter.
00560 void CWriter::printConstant(Constant *CPV) {
00561   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
00562     switch (CE->getOpcode()) {
00563     case Instruction::Cast:
00564       Out << "((";
00565       printType(Out, CPV->getType());
00566       Out << ')';
00567       printConstant(CE->getOperand(0));
00568       Out << ')';
00569       return;
00570 
00571     case Instruction::GetElementPtr:
00572       Out << "(&(";
00573       printIndexingExpression(CE->getOperand(0), gep_type_begin(CPV),
00574                               gep_type_end(CPV));
00575       Out << "))";
00576       return;
00577     case Instruction::Select:
00578       Out << '(';
00579       printConstant(CE->getOperand(0));
00580       Out << '?';
00581       printConstant(CE->getOperand(1));
00582       Out << ':';
00583       printConstant(CE->getOperand(2));
00584       Out << ')';
00585       return;
00586     case Instruction::Add:
00587     case Instruction::Sub:
00588     case Instruction::Mul:
00589     case Instruction::Div:
00590     case Instruction::Rem:
00591     case Instruction::And:
00592     case Instruction::Or:
00593     case Instruction::Xor:
00594     case Instruction::SetEQ:
00595     case Instruction::SetNE:
00596     case Instruction::SetLT:
00597     case Instruction::SetLE:
00598     case Instruction::SetGT:
00599     case Instruction::SetGE:
00600     case Instruction::Shl:
00601     case Instruction::Shr:
00602       Out << '(';
00603       printConstant(CE->getOperand(0));
00604       switch (CE->getOpcode()) {
00605       case Instruction::Add: Out << " + "; break;
00606       case Instruction::Sub: Out << " - "; break;
00607       case Instruction::Mul: Out << " * "; break;
00608       case Instruction::Div: Out << " / "; break;
00609       case Instruction::Rem: Out << " % "; break;
00610       case Instruction::And: Out << " & "; break;
00611       case Instruction::Or:  Out << " | "; break;
00612       case Instruction::Xor: Out << " ^ "; break;
00613       case Instruction::SetEQ: Out << " == "; break;
00614       case Instruction::SetNE: Out << " != "; break;
00615       case Instruction::SetLT: Out << " < "; break;
00616       case Instruction::SetLE: Out << " <= "; break;
00617       case Instruction::SetGT: Out << " > "; break;
00618       case Instruction::SetGE: Out << " >= "; break;
00619       case Instruction::Shl: Out << " << "; break;
00620       case Instruction::Shr: Out << " >> "; break;
00621       default: assert(0 && "Illegal opcode here!");
00622       }
00623       printConstant(CE->getOperand(1));
00624       Out << ')';
00625       return;
00626 
00627     default:
00628       std::cerr << "CWriter Error: Unhandled constant expression: "
00629                 << *CE << "\n";
00630       abort();
00631     }
00632   } else if (isa<UndefValue>(CPV) && CPV->getType()->isFirstClassType()) {
00633     Out << "((";
00634     printType(Out, CPV->getType());
00635     Out << ")/*UNDEF*/0)";
00636     return;
00637   }
00638 
00639   switch (CPV->getType()->getTypeID()) {
00640   case Type::BoolTyID:
00641     Out << (CPV == ConstantBool::False ? '0' : '1'); break;
00642   case Type::SByteTyID:
00643   case Type::ShortTyID:
00644     Out << cast<ConstantSInt>(CPV)->getValue(); break;
00645   case Type::IntTyID:
00646     if ((int)cast<ConstantSInt>(CPV)->getValue() == (int)0x80000000)
00647       Out << "((int)0x80000000U)";   // Handle MININT specially to avoid warning
00648     else
00649       Out << cast<ConstantSInt>(CPV)->getValue();
00650     break;
00651 
00652   case Type::LongTyID:
00653     if (cast<ConstantSInt>(CPV)->isMinValue())
00654       Out << "(/*INT64_MIN*/(-9223372036854775807LL)-1)";
00655     else
00656       Out << cast<ConstantSInt>(CPV)->getValue() << "ll"; break;
00657 
00658   case Type::UByteTyID:
00659   case Type::UShortTyID:
00660     Out << cast<ConstantUInt>(CPV)->getValue(); break;
00661   case Type::UIntTyID:
00662     Out << cast<ConstantUInt>(CPV)->getValue() << 'u'; break;
00663   case Type::ULongTyID:
00664     Out << cast<ConstantUInt>(CPV)->getValue() << "ull"; break;
00665 
00666   case Type::FloatTyID:
00667   case Type::DoubleTyID: {
00668     ConstantFP *FPC = cast<ConstantFP>(CPV);
00669     std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
00670     if (I != FPConstantMap.end()) {
00671       // Because of FP precision problems we must load from a stack allocated
00672       // value that holds the value in hex.
00673       Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
00674           << "*)&FPConstant" << I->second << ')';
00675     } else {
00676       if (IsNAN(FPC->getValue())) {
00677         // The value is NaN
00678 
00679         // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
00680         // it's 0x7ff4.
00681         const unsigned long QuietNaN = 0x7ff8UL;
00682         const unsigned long SignalNaN = 0x7ff4UL;
00683 
00684         // We need to grab the first part of the FP #
00685         char Buffer[100];
00686 
00687         uint64_t ll = DoubleToBits(FPC->getValue());
00688         sprintf(Buffer, "0x%llx", static_cast<long long>(ll));
00689 
00690         std::string Num(&Buffer[0], &Buffer[6]);
00691         unsigned long Val = strtoul(Num.c_str(), 0, 16);
00692 
00693         if (FPC->getType() == Type::FloatTy)
00694           Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
00695               << Buffer << "\") /*nan*/ ";
00696         else
00697           Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
00698               << Buffer << "\") /*nan*/ ";
00699       } else if (IsInf(FPC->getValue())) {
00700         // The value is Inf
00701         if (FPC->getValue() < 0) Out << '-';
00702         Out << "LLVM_INF" << (FPC->getType() == Type::FloatTy ? "F" : "")
00703             << " /*inf*/ ";
00704       } else {
00705         std::string Num;
00706 #if HAVE_PRINTF_A
00707         // Print out the constant as a floating point number.
00708         char Buffer[100];
00709         sprintf(Buffer, "%a", FPC->getValue());
00710         Num = Buffer;
00711 #else
00712         Num = ftostr(FPC->getValue());
00713 #endif
00714         Out << Num;
00715       }
00716     }
00717     break;
00718   }
00719 
00720   case Type::ArrayTyID:
00721     if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
00722       const ArrayType *AT = cast<ArrayType>(CPV->getType());
00723       Out << '{';
00724       if (AT->getNumElements()) {
00725         Out << ' ';
00726         Constant *CZ = Constant::getNullValue(AT->getElementType());
00727         printConstant(CZ);
00728         for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
00729           Out << ", ";
00730           printConstant(CZ);
00731         }
00732       }
00733       Out << " }";
00734     } else {
00735       printConstantArray(cast<ConstantArray>(CPV));
00736     }
00737     break;
00738 
00739   case Type::PackedTyID:
00740     if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
00741       const PackedType *AT = cast<PackedType>(CPV->getType());
00742       Out << '{';
00743       if (AT->getNumElements()) {
00744         Out << ' ';
00745         Constant *CZ = Constant::getNullValue(AT->getElementType());
00746         printConstant(CZ);
00747         for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
00748           Out << ", ";
00749           printConstant(CZ);
00750         }
00751       }
00752       Out << " }";
00753     } else {
00754       printConstantPacked(cast<ConstantPacked>(CPV));
00755     }
00756     break;
00757 
00758   case Type::StructTyID:
00759     if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
00760       const StructType *ST = cast<StructType>(CPV->getType());
00761       Out << '{';
00762       if (ST->getNumElements()) {
00763         Out << ' ';
00764         printConstant(Constant::getNullValue(ST->getElementType(0)));
00765         for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
00766           Out << ", ";
00767           printConstant(Constant::getNullValue(ST->getElementType(i)));
00768         }
00769       }
00770       Out << " }";
00771     } else {
00772       Out << '{';
00773       if (CPV->getNumOperands()) {
00774         Out << ' ';
00775         printConstant(cast<Constant>(CPV->getOperand(0)));
00776         for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
00777           Out << ", ";
00778           printConstant(cast<Constant>(CPV->getOperand(i)));
00779         }
00780       }
00781       Out << " }";
00782     }
00783     break;
00784 
00785   case Type::PointerTyID:
00786     if (isa<ConstantPointerNull>(CPV)) {
00787       Out << "((";
00788       printType(Out, CPV->getType());
00789       Out << ")/*NULL*/0)";
00790       break;
00791     } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
00792       writeOperand(GV);
00793       break;
00794     }
00795     // FALL THROUGH
00796   default:
00797     std::cerr << "Unknown constant type: " << *CPV << "\n";
00798     abort();
00799   }
00800 }
00801 
00802 void CWriter::writeOperandInternal(Value *Operand) {
00803   if (Instruction *I = dyn_cast<Instruction>(Operand))
00804     if (isInlinableInst(*I) && !isDirectAlloca(I)) {
00805       // Should we inline this instruction to build a tree?
00806       Out << '(';
00807       visit(*I);
00808       Out << ')';
00809       return;
00810     }
00811 
00812   Constant* CPV = dyn_cast<Constant>(Operand);
00813   if (CPV && !isa<GlobalValue>(CPV)) {
00814     printConstant(CPV);
00815   } else {
00816     Out << Mang->getValueName(Operand);
00817   }
00818 }
00819 
00820 void CWriter::writeOperand(Value *Operand) {
00821   if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
00822     Out << "(&";  // Global variables are references as their addresses by llvm
00823 
00824   writeOperandInternal(Operand);
00825 
00826   if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
00827     Out << ')';
00828 }
00829 
00830 // generateCompilerSpecificCode - This is where we add conditional compilation
00831 // directives to cater to specific compilers as need be.
00832 //
00833 static void generateCompilerSpecificCode(std::ostream& Out) {
00834   // Alloca is hard to get, and we don't want to include stdlib.h here.
00835   Out << "/* get a declaration for alloca */\n"
00836       << "#if defined(__CYGWIN__) || defined(__MINGW32__)\n"
00837       << "extern void *_alloca(unsigned long);\n"
00838       << "#define alloca(x) _alloca(x)\n"
00839       << "#elif defined(__APPLE__)\n"
00840       << "extern void *__builtin_alloca(unsigned long);\n"
00841       << "#define alloca(x) __builtin_alloca(x)\n"
00842       << "#elif defined(__sun__)\n"
00843       << "#if defined(__sparcv9)\n"
00844       << "extern void *__builtin_alloca(unsigned long);\n"
00845       << "#else\n"
00846       << "extern void *__builtin_alloca(unsigned int);\n"
00847       << "#endif\n"
00848       << "#define alloca(x) __builtin_alloca(x)\n"
00849       << "#elif defined(__FreeBSD__) || defined(__OpenBSD__)\n"
00850       << "#define alloca(x) __builtin_alloca(x)\n"
00851       << "#elif !defined(_MSC_VER)\n"
00852       << "#include <alloca.h>\n"
00853       << "#endif\n\n";
00854 
00855   // We output GCC specific attributes to preserve 'linkonce'ness on globals.
00856   // If we aren't being compiled with GCC, just drop these attributes.
00857   Out << "#ifndef __GNUC__  /* Can only support \"linkonce\" vars with GCC */\n"
00858       << "#define __attribute__(X)\n"
00859       << "#endif\n\n";
00860 
00861 #if 0
00862   // At some point, we should support "external weak" vs. "weak" linkages.
00863   // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
00864   Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
00865       << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
00866       << "#elif defined(__GNUC__)\n"
00867       << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
00868       << "#else\n"
00869       << "#define __EXTERNAL_WEAK__\n"
00870       << "#endif\n\n";
00871 #endif
00872 
00873   // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
00874   Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
00875       << "#define __ATTRIBUTE_WEAK__\n"
00876       << "#elif defined(__GNUC__)\n"
00877       << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
00878       << "#else\n"
00879       << "#define __ATTRIBUTE_WEAK__\n"
00880       << "#endif\n\n";
00881 
00882   // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
00883   // From the GCC documentation:
00884   //
00885   //   double __builtin_nan (const char *str)
00886   //
00887   // This is an implementation of the ISO C99 function nan.
00888   //
00889   // Since ISO C99 defines this function in terms of strtod, which we do
00890   // not implement, a description of the parsing is in order. The string is
00891   // parsed as by strtol; that is, the base is recognized by leading 0 or
00892   // 0x prefixes. The number parsed is placed in the significand such that
00893   // the least significant bit of the number is at the least significant
00894   // bit of the significand. The number is truncated to fit the significand
00895   // field provided. The significand is forced to be a quiet NaN.
00896   //
00897   // This function, if given a string literal, is evaluated early enough
00898   // that it is considered a compile-time constant.
00899   //
00900   //   float __builtin_nanf (const char *str)
00901   //
00902   // Similar to __builtin_nan, except the return type is float.
00903   //
00904   //   double __builtin_inf (void)
00905   //
00906   // Similar to __builtin_huge_val, except a warning is generated if the
00907   // target floating-point format does not support infinities. This
00908   // function is suitable for implementing the ISO C99 macro INFINITY.
00909   //
00910   //   float __builtin_inff (void)
00911   //
00912   // Similar to __builtin_inf, except the return type is float.
00913   Out << "#ifdef __GNUC__\n"
00914       << "#define LLVM_NAN(NanStr)   __builtin_nan(NanStr)   /* Double */\n"
00915       << "#define LLVM_NANF(NanStr)  __builtin_nanf(NanStr)  /* Float */\n"
00916       << "#define LLVM_NANS(NanStr)  __builtin_nans(NanStr)  /* Double */\n"
00917       << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
00918       << "#define LLVM_INF           __builtin_inf()         /* Double */\n"
00919       << "#define LLVM_INFF          __builtin_inff()        /* Float */\n"
00920       << "#define LLVM_PREFETCH(addr,rw,locality) "
00921                               "__builtin_prefetch(addr,rw,locality)\n"
00922       << "#define __ATTRIBUTE_CTOR__ __attribute__((constructor))\n"
00923       << "#define __ATTRIBUTE_DTOR__ __attribute__((destructor))\n"
00924       << "#else\n"
00925       << "#define LLVM_NAN(NanStr)   ((double)0.0)           /* Double */\n"
00926       << "#define LLVM_NANF(NanStr)  0.0F                    /* Float */\n"
00927       << "#define LLVM_NANS(NanStr)  ((double)0.0)           /* Double */\n"
00928       << "#define LLVM_NANSF(NanStr) 0.0F                    /* Float */\n"
00929       << "#define LLVM_INF           ((double)0.0)           /* Double */\n"
00930       << "#define LLVM_INFF          0.0F                    /* Float */\n"
00931       << "#define LLVM_PREFETCH(addr,rw,locality)            /* PREFETCH */\n"
00932       << "#define __ATTRIBUTE_CTOR__\n"
00933       << "#define __ATTRIBUTE_DTOR__\n"
00934       << "#endif\n\n";
00935 
00936   // Output target-specific code that should be inserted into main.
00937   Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
00938   // On X86, set the FP control word to 64-bits of precision instead of 80 bits.
00939   Out << "#if defined(__GNUC__) && !defined(__llvm__)\n"
00940       << "#if defined(i386) || defined(__i386__) || defined(__i386) || "
00941       << "defined(__x86_64__)\n"
00942       << "#undef CODE_FOR_MAIN\n"
00943       << "#define CODE_FOR_MAIN() \\\n"
00944       << "  {short F;__asm__ (\"fnstcw %0\" : \"=m\" (*&F)); \\\n"
00945       << "  F=(F&~0x300)|0x200;__asm__(\"fldcw %0\"::\"m\"(*&F));}\n"
00946       << "#endif\n#endif\n";
00947 
00948 }
00949 
00950 /// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
00951 /// the StaticTors set.
00952 static void FindStaticTors(GlobalVariable *GV, std::set<Function*> &StaticTors){
00953   ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
00954   if (!InitList) return;
00955   
00956   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
00957     if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
00958       if (CS->getNumOperands() != 2) return;  // Not array of 2-element structs.
00959       
00960       if (CS->getOperand(1)->isNullValue())
00961         return;  // Found a null terminator, exit printing.
00962       Constant *FP = CS->getOperand(1);
00963       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
00964         if (CE->getOpcode() == Instruction::Cast)
00965           FP = CE->getOperand(0);
00966       if (Function *F = dyn_cast<Function>(FP))
00967         StaticTors.insert(F);
00968     }
00969 }
00970 
00971 enum SpecialGlobalClass {
00972   NotSpecial = 0,
00973   GlobalCtors, GlobalDtors,
00974   NotPrinted
00975 };
00976 
00977 /// getGlobalVariableClass - If this is a global that is specially recognized
00978 /// by LLVM, return a code that indicates how we should handle it.
00979 static SpecialGlobalClass getGlobalVariableClass(const GlobalVariable *GV) {
00980   // If this is a global ctors/dtors list, handle it now.
00981   if (GV->hasAppendingLinkage() && GV->use_empty()) {
00982     if (GV->getName() == "llvm.global_ctors")
00983       return GlobalCtors;
00984     else if (GV->getName() == "llvm.global_dtors")
00985       return GlobalDtors;
00986   }
00987   
00988   // Otherwise, it it is other metadata, don't print it.  This catches things
00989   // like debug information.
00990   if (GV->getSection() == "llvm.metadata")
00991     return NotPrinted;
00992   
00993   return NotSpecial;
00994 }
00995 
00996 
00997 bool CWriter::doInitialization(Module &M) {
00998   // Initialize
00999   TheModule = &M;
01000 
01001   IL.AddPrototypes(M);
01002 
01003   // Ensure that all structure types have names...
01004   Mang = new Mangler(M);
01005   Mang->markCharUnacceptable('.');
01006 
01007   // Keep track of which functions are static ctors/dtors so they can have
01008   // an attribute added to their prototypes.
01009   std::set<Function*> StaticCtors, StaticDtors;
01010   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
01011        I != E; ++I) {
01012     switch (getGlobalVariableClass(I)) {
01013     default: break;
01014     case GlobalCtors:
01015       FindStaticTors(I, StaticCtors);
01016       break;
01017     case GlobalDtors:
01018       FindStaticTors(I, StaticDtors);
01019       break;
01020     }
01021   }
01022   
01023   // get declaration for alloca
01024   Out << "/* Provide Declarations */\n";
01025   Out << "#include <stdarg.h>\n";      // Varargs support
01026   Out << "#include <setjmp.h>\n";      // Unwind support
01027   generateCompilerSpecificCode(Out);
01028 
01029   // Provide a definition for `bool' if not compiling with a C++ compiler.
01030   Out << "\n"
01031       << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
01032 
01033       << "\n\n/* Support for floating point constants */\n"
01034       << "typedef unsigned long long ConstantDoubleTy;\n"
01035       << "typedef unsigned int        ConstantFloatTy;\n"
01036 
01037       << "\n\n/* Global Declarations */\n";
01038 
01039   // First output all the declarations for the program, because C requires
01040   // Functions & globals to be declared before they are used.
01041   //
01042 
01043   // Loop over the symbol table, emitting all named constants...
01044   printModuleTypes(M.getSymbolTable());
01045 
01046   // Global variable declarations...
01047   if (!M.global_empty()) {
01048     Out << "\n/* External Global Variable Declarations */\n";
01049     for (Module::global_iterator I = M.global_begin(), E = M.global_end();
01050          I != E; ++I) {
01051       if (I->hasExternalLinkage()) {
01052         Out << "extern ";
01053         printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
01054         Out << ";\n";
01055       }
01056     }
01057   }
01058 
01059   // Function declarations
01060   Out << "\n/* Function Declarations */\n";
01061   Out << "double fmod(double, double);\n";   // Support for FP rem
01062   Out << "float fmodf(float, float);\n";
01063   
01064   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
01065     // Don't print declarations for intrinsic functions.
01066     if (!I->getIntrinsicID() &&
01067         I->getName() != "setjmp" && I->getName() != "longjmp") {
01068       printFunctionSignature(I, true);
01069       if (I->hasWeakLinkage() || I->hasLinkOnceLinkage()) 
01070         Out << " __ATTRIBUTE_WEAK__";
01071       if (StaticCtors.count(I))
01072         Out << " __ATTRIBUTE_CTOR__";
01073       if (StaticDtors.count(I))
01074         Out << " __ATTRIBUTE_DTOR__";
01075       Out << ";\n";
01076     }
01077   }
01078 
01079   // Output the global variable declarations
01080   if (!M.global_empty()) {
01081     Out << "\n\n/* Global Variable Declarations */\n";
01082     for (Module::global_iterator I = M.global_begin(), E = M.global_end();
01083          I != E; ++I)
01084       if (!I->isExternal()) {
01085         // Ignore special globals, such as debug info.
01086         if (getGlobalVariableClass(I))
01087           continue;
01088         
01089         if (I->hasInternalLinkage())
01090           Out << "static ";
01091         else
01092           Out << "extern ";
01093         printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
01094 
01095         if (I->hasLinkOnceLinkage())
01096           Out << " __attribute__((common))";
01097         else if (I->hasWeakLinkage())
01098           Out << " __ATTRIBUTE_WEAK__";
01099         Out << ";\n";
01100       }
01101   }
01102 
01103   // Output the global variable definitions and contents...
01104   if (!M.global_empty()) {
01105     Out << "\n\n/* Global Variable Definitions and Initialization */\n";
01106     for (Module::global_iterator I = M.global_begin(), E = M.global_end(); 
01107          I != E; ++I)
01108       if (!I->isExternal()) {
01109         // Ignore special globals, such as debug info.
01110         if (getGlobalVariableClass(I))
01111           continue;
01112         
01113         if (I->hasInternalLinkage())
01114           Out << "static ";
01115         printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
01116         if (I->hasLinkOnceLinkage())
01117           Out << " __attribute__((common))";
01118         else if (I->hasWeakLinkage())
01119           Out << " __ATTRIBUTE_WEAK__";
01120 
01121         // If the initializer is not null, emit the initializer.  If it is null,
01122         // we try to avoid emitting large amounts of zeros.  The problem with
01123         // this, however, occurs when the variable has weak linkage.  In this
01124         // case, the assembler will complain about the variable being both weak
01125         // and common, so we disable this optimization.
01126         if (!I->getInitializer()->isNullValue()) {
01127           Out << " = " ;
01128           writeOperand(I->getInitializer());
01129         } else if (I->hasWeakLinkage()) {
01130           // We have to specify an initializer, but it doesn't have to be
01131           // complete.  If the value is an aggregate, print out { 0 }, and let
01132           // the compiler figure out the rest of the zeros.
01133           Out << " = " ;
01134           if (isa<StructType>(I->getInitializer()->getType()) ||
01135               isa<ArrayType>(I->getInitializer()->getType()) ||
01136               isa<PackedType>(I->getInitializer()->getType())) {
01137             Out << "{ 0 }";
01138           } else {
01139             // Just print it out normally.
01140             writeOperand(I->getInitializer());
01141           }
01142         }
01143         Out << ";\n";
01144       }
01145   }
01146 
01147   if (!M.empty())
01148     Out << "\n\n/* Function Bodies */\n";
01149   return false;
01150 }
01151 
01152 
01153 /// Output all floating point constants that cannot be printed accurately...
01154 void CWriter::printFloatingPointConstants(Function &F) {
01155   // Scan the module for floating point constants.  If any FP constant is used
01156   // in the function, we want to redirect it here so that we do not depend on
01157   // the precision of the printed form, unless the printed form preserves
01158   // precision.
01159   //
01160   static unsigned FPCounter = 0;
01161   for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
01162        I != E; ++I)
01163     if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
01164       if (!isFPCSafeToPrint(FPC) && // Do not put in FPConstantMap if safe.
01165           !FPConstantMap.count(FPC)) {
01166         double Val = FPC->getValue();
01167 
01168         FPConstantMap[FPC] = FPCounter;  // Number the FP constants
01169 
01170         if (FPC->getType() == Type::DoubleTy) {
01171           Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
01172               << " = 0x" << std::hex << DoubleToBits(Val) << std::dec
01173               << "ULL;    /* " << Val << " */\n";
01174         } else if (FPC->getType() == Type::FloatTy) {
01175           Out << "static const ConstantFloatTy FPConstant" << FPCounter++
01176               << " = 0x" << std::hex << FloatToBits(Val) << std::dec
01177               << "U;    /* " << Val << " */\n";
01178         } else
01179           assert(0 && "Unknown float type!");
01180       }
01181 
01182   Out << '\n';
01183 }
01184 
01185 
01186 /// printSymbolTable - Run through symbol table looking for type names.  If a
01187 /// type name is found, emit its declaration...
01188 ///
01189 void CWriter::printModuleTypes(const SymbolTable &ST) {
01190   // We are only interested in the type plane of the symbol table.
01191   SymbolTable::type_const_iterator I   = ST.type_begin();
01192   SymbolTable::type_const_iterator End = ST.type_end();
01193 
01194   // If there are no type names, exit early.
01195   if (I == End) return;
01196 
01197   // Print out forward declarations for structure types before anything else!
01198   Out << "/* Structure forward decls */\n";
01199   for (; I != End; ++I)
01200     if (const Type *STy = dyn_cast<StructType>(I->second)) {
01201       std::string Name = "struct l_" + Mang->makeNameProper(I->first);
01202       Out << Name << ";\n";
01203       TypeNames.insert(std::make_pair(STy, Name));
01204     }
01205 
01206   Out << '\n';
01207 
01208   // Now we can print out typedefs...
01209   Out << "/* Typedefs */\n";
01210   for (I = ST.type_begin(); I != End; ++I) {
01211     const Type *Ty = cast<Type>(I->second);
01212     std::string Name = "l_" + Mang->makeNameProper(I->first);
01213     Out << "typedef ";
01214     printType(Out, Ty, Name);
01215     Out << ";\n";
01216   }
01217 
01218   Out << '\n';
01219 
01220   // Keep track of which structures have been printed so far...
01221   std::set<const StructType *> StructPrinted;
01222 
01223   // Loop over all structures then push them into the stack so they are
01224   // printed in the correct order.
01225   //
01226   Out << "/* Structure contents */\n";
01227   for (I = ST.type_begin(); I != End; ++I)
01228     if (const StructType *STy = dyn_cast<StructType>(I->second))
01229       // Only print out used types!
01230       printContainedStructs(STy, StructPrinted);
01231 }
01232 
01233 // Push the struct onto the stack and recursively push all structs
01234 // this one depends on.
01235 //
01236 // TODO:  Make this work properly with packed types
01237 //
01238 void CWriter::printContainedStructs(const Type *Ty,
01239                                     std::set<const StructType*> &StructPrinted){
01240   // Don't walk through pointers.
01241   if (isa<PointerType>(Ty) || Ty->isPrimitiveType()) return;
01242   
01243   // Print all contained types first.
01244   for (Type::subtype_iterator I = Ty->subtype_begin(),
01245        E = Ty->subtype_end(); I != E; ++I)
01246     printContainedStructs(*I, StructPrinted);
01247   
01248   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
01249     // Check to see if we have already printed this struct.
01250     if (StructPrinted.insert(STy).second) {
01251       // Print structure type out.
01252       std::string Name = TypeNames[STy];
01253       printType(Out, STy, Name, true);
01254       Out << ";\n\n";
01255     }
01256   }
01257 }
01258 
01259 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
01260   /// isCStructReturn - Should this function actually return a struct by-value?
01261   bool isCStructReturn = F->getCallingConv() == CallingConv::CSRet;
01262   
01263   if (F->hasInternalLinkage()) Out << "static ";
01264 
01265   // Loop over the arguments, printing them...
01266   const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
01267 
01268   std::stringstream FunctionInnards;
01269 
01270   // Print out the name...
01271   FunctionInnards << Mang->getValueName(F) << '(';
01272 
01273   bool PrintedArg = false;
01274   if (!F->isExternal()) {
01275     if (!F->arg_empty()) {
01276       Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
01277       
01278       // If this is a struct-return function, don't print the hidden
01279       // struct-return argument.
01280       if (isCStructReturn) {
01281         assert(I != E && "Invalid struct return function!");
01282         ++I;
01283       }
01284       
01285       std::string ArgName;
01286       for (; I != E; ++I) {
01287         if (PrintedArg) FunctionInnards << ", ";
01288         if (I->hasName() || !Prototype)
01289           ArgName = Mang->getValueName(I);
01290         else
01291           ArgName = "";
01292         printType(FunctionInnards, I->getType(), ArgName);
01293         PrintedArg = true;
01294       }
01295     }
01296   } else {
01297     // Loop over the arguments, printing them.
01298     FunctionType::param_iterator I = FT->param_begin(), E = FT->param_end();
01299     
01300     // If this is a struct-return function, don't print the hidden
01301     // struct-return argument.
01302     if (isCStructReturn) {
01303       assert(I != E && "Invalid struct return function!");
01304       ++I;
01305     }
01306     
01307     for (; I != E; ++I) {
01308       if (PrintedArg) FunctionInnards << ", ";
01309       printType(FunctionInnards, *I);
01310       PrintedArg = true;
01311     }
01312   }
01313 
01314   // Finish printing arguments... if this is a vararg function, print the ...,
01315   // unless there are no known types, in which case, we just emit ().
01316   //
01317   if (FT->isVarArg() && PrintedArg) {
01318     if (PrintedArg) FunctionInnards << ", ";
01319     FunctionInnards << "...";  // Output varargs portion of signature!
01320   } else if (!FT->isVarArg() && !PrintedArg) {
01321     FunctionInnards << "void"; // ret() -> ret(void) in C.
01322   }
01323   FunctionInnards << ')';
01324   
01325   // Get the return tpe for the function.
01326   const Type *RetTy;
01327   if (!isCStructReturn)
01328     RetTy = F->getReturnType();
01329   else {
01330     // If this is a struct-return function, print the struct-return type.
01331     RetTy = cast<PointerType>(FT->getParamType(0))->getElementType();
01332   }
01333     
01334   // Print out the return type and the signature built above.
01335   printType(Out, RetTy, FunctionInnards.str());
01336 }
01337 
01338 void CWriter::printFunction(Function &F) {
01339   printFunctionSignature(&F, false);
01340   Out << " {\n";
01341   
01342   // If this is a struct return function, handle the result with magic.
01343   if (F.getCallingConv() == CallingConv::CSRet) {
01344     const Type *StructTy =
01345       cast<PointerType>(F.arg_begin()->getType())->getElementType();
01346     Out << "  ";
01347     printType(Out, StructTy, "StructReturn");
01348     Out << ";  /* Struct return temporary */\n";
01349 
01350     Out << "  ";
01351     printType(Out, F.arg_begin()->getType(), Mang->getValueName(F.arg_begin()));
01352     Out << " = &StructReturn;\n";
01353   }
01354 
01355   bool PrintedVar = false;
01356   
01357   // print local variable information for the function
01358   for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I)
01359     if (const AllocaInst *AI = isDirectAlloca(&*I)) {
01360       Out << "  ";
01361       printType(Out, AI->getAllocatedType(), Mang->getValueName(AI));
01362       Out << ";    /* Address-exposed local */\n";
01363       PrintedVar = true;
01364     } else if (I->getType() != Type::VoidTy && !isInlinableInst(*I)) {
01365       Out << "  ";
01366       printType(Out, I->getType(), Mang->getValueName(&*I));
01367       Out << ";\n";
01368 
01369       if (isa<PHINode>(*I)) {  // Print out PHI node temporaries as well...
01370         Out << "  ";
01371         printType(Out, I->getType(),
01372                   Mang->getValueName(&*I)+"__PHI_TEMPORARY");
01373         Out << ";\n";
01374       }
01375       PrintedVar = true;
01376     }
01377 
01378   if (PrintedVar)
01379     Out << '\n';
01380 
01381   if (F.hasExternalLinkage() && F.getName() == "main")
01382     Out << "  CODE_FOR_MAIN();\n";
01383 
01384   // print the basic blocks
01385   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
01386     if (Loop *L = LI->getLoopFor(BB)) {
01387       if (L->getHeader() == BB && L->getParentLoop() == 0)
01388         printLoop(L);
01389     } else {
01390       printBasicBlock(BB);
01391     }
01392   }
01393 
01394   Out << "}\n\n";
01395 }
01396 
01397 void CWriter::printLoop(Loop *L) {
01398   Out << "  do {     /* Syntactic loop '" << L->getHeader()->getName()
01399       << "' to make GCC happy */\n";
01400   for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
01401     BasicBlock *BB = L->getBlocks()[i];
01402     Loop *BBLoop = LI->getLoopFor(BB);
01403     if (BBLoop == L)
01404       printBasicBlock(BB);
01405     else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
01406       printLoop(BBLoop);
01407   }
01408   Out << "  } while (1); /* end of syntactic loop '"
01409       << L->getHeader()->getName() << "' */\n";
01410 }
01411 
01412 void CWriter::printBasicBlock(BasicBlock *BB) {
01413 
01414   // Don't print the label for the basic block if there are no uses, or if
01415   // the only terminator use is the predecessor basic block's terminator.
01416   // We have to scan the use list because PHI nodes use basic blocks too but
01417   // do not require a label to be generated.
01418   //
01419   bool NeedsLabel = false;
01420   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
01421     if (isGotoCodeNecessary(*PI, BB)) {
01422       NeedsLabel = true;
01423       break;
01424     }
01425 
01426   if (NeedsLabel) Out << Mang->getValueName(BB) << ":\n";
01427 
01428   // Output all of the instructions in the basic block...
01429   for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
01430        ++II) {
01431     if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
01432       if (II->getType() != Type::VoidTy)
01433         outputLValue(II);
01434       else
01435         Out << "  ";
01436       visit(*II);
01437       Out << ";\n";
01438     }
01439   }
01440 
01441   // Don't emit prefix or suffix for the terminator...
01442   visit(*BB->getTerminator());
01443 }
01444 
01445 
01446 // Specific Instruction type classes... note that all of the casts are
01447 // necessary because we use the instruction classes as opaque types...
01448 //
01449 void CWriter::visitReturnInst(ReturnInst &I) {
01450   // If this is a struct return function, return the temporary struct.
01451   if (I.getParent()->getParent()->getCallingConv() == CallingConv::CSRet) {
01452     Out << "  return StructReturn;\n";
01453     return;
01454   }
01455   
01456   // Don't output a void return if this is the last basic block in the function
01457   if (I.getNumOperands() == 0 &&
01458       &*--I.getParent()->getParent()->end() == I.getParent() &&
01459       !I.getParent()->size() == 1) {
01460     return;
01461   }
01462 
01463   Out << "  return";
01464   if (I.getNumOperands()) {
01465     Out << ' ';
01466     writeOperand(I.getOperand(0));
01467   }
01468   Out << ";\n";
01469 }
01470 
01471 void CWriter::visitSwitchInst(SwitchInst &SI) {
01472 
01473   Out << "  switch (";
01474   writeOperand(SI.getOperand(0));
01475   Out << ") {\n  default:\n";
01476   printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
01477   printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
01478   Out << ";\n";
01479   for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
01480     Out << "  case ";
01481     writeOperand(SI.getOperand(i));
01482     Out << ":\n";
01483     BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
01484     printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
01485     printBranchToBlock(SI.getParent(), Succ, 2);
01486     if (Function::iterator(Succ) == next(Function::iterator(SI.getParent())))
01487       Out << "    break;\n";
01488   }
01489   Out << "  }\n";
01490 }
01491 
01492 void CWriter::visitUnreachableInst(UnreachableInst &I) {
01493   Out << "  /*UNREACHABLE*/;\n";
01494 }
01495 
01496 bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
01497   /// FIXME: This should be reenabled, but loop reordering safe!!
01498   return true;
01499 
01500   if (next(Function::iterator(From)) != Function::iterator(To))
01501     return true;  // Not the direct successor, we need a goto.
01502 
01503   //isa<SwitchInst>(From->getTerminator())
01504 
01505   if (LI->getLoopFor(From) != LI->getLoopFor(To))
01506     return true;
01507   return false;
01508 }
01509 
01510 void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
01511                                           BasicBlock *Successor,
01512                                           unsigned Indent) {
01513   for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
01514     PHINode *PN = cast<PHINode>(I);
01515     // Now we have to do the printing.
01516     Value *IV = PN->getIncomingValueForBlock(CurBlock);
01517     if (!isa<UndefValue>(IV)) {
01518       Out << std::string(Indent, ' ');
01519       Out << "  " << Mang->getValueName(I) << "__PHI_TEMPORARY = ";
01520       writeOperand(IV);
01521       Out << ";   /* for PHI node */\n";
01522     }
01523   }
01524 }
01525 
01526 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
01527                                  unsigned Indent) {
01528   if (isGotoCodeNecessary(CurBB, Succ)) {
01529     Out << std::string(Indent, ' ') << "  goto ";
01530     writeOperand(Succ);
01531     Out << ";\n";
01532   }
01533 }
01534 
01535 // Branch instruction printing - Avoid printing out a branch to a basic block
01536 // that immediately succeeds the current one.
01537 //
01538 void CWriter::visitBranchInst(BranchInst &I) {
01539 
01540   if (I.isConditional()) {
01541     if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
01542       Out << "  if (";
01543       writeOperand(I.getCondition());
01544       Out << ") {\n";
01545 
01546       printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
01547       printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
01548 
01549       if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
01550         Out << "  } else {\n";
01551         printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
01552         printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
01553       }
01554     } else {
01555       // First goto not necessary, assume second one is...
01556       Out << "  if (!";
01557       writeOperand(I.getCondition());
01558       Out << ") {\n";
01559 
01560       printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
01561       printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
01562     }
01563 
01564     Out << "  }\n";
01565   } else {
01566     printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
01567     printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
01568   }
01569   Out << "\n";
01570 }
01571 
01572 // PHI nodes get copied into temporary values at the end of predecessor basic
01573 // blocks.  We now need to copy these temporary values into the REAL value for
01574 // the PHI.
01575 void CWriter::visitPHINode(PHINode &I) {
01576   writeOperand(&I);
01577   Out << "__PHI_TEMPORARY";
01578 }
01579 
01580 
01581 void CWriter::visitBinaryOperator(Instruction &I) {
01582   // binary instructions, shift instructions, setCond instructions.
01583   assert(!isa<PointerType>(I.getType()));
01584 
01585   // We must cast the results of binary operations which might be promoted.
01586   bool needsCast = false;
01587   if ((I.getType() == Type::UByteTy) || (I.getType() == Type::SByteTy)
01588       || (I.getType() == Type::UShortTy) || (I.getType() == Type::ShortTy)
01589       || (I.getType() == Type::FloatTy)) {
01590     needsCast = true;
01591     Out << "((";
01592     printType(Out, I.getType());
01593     Out << ")(";
01594   }
01595 
01596   // If this is a negation operation, print it out as such.  For FP, we don't
01597   // want to print "-0.0 - X".
01598   if (BinaryOperator::isNeg(&I)) {
01599     Out << "-(";
01600     writeOperand(BinaryOperator::getNegArgument(cast<BinaryOperator>(&I)));
01601     Out << ")";
01602   } else if (I.getOpcode() == Instruction::Rem && 
01603              I.getType()->isFloatingPoint()) {
01604     // Output a call to fmod/fmodf instead of emitting a%b
01605     if (I.getType() == Type::FloatTy)
01606       Out << "fmodf(";
01607     else
01608       Out << "fmod(";
01609     writeOperand(I.getOperand(0));
01610     Out << ", ";
01611     writeOperand(I.getOperand(1));
01612     Out << ")";
01613   } else {
01614     writeOperand(I.getOperand(0));
01615 
01616     switch (I.getOpcode()) {
01617     case Instruction::Add: Out << " + "; break;
01618     case Instruction::Sub: Out << " - "; break;
01619     case Instruction::Mul: Out << '*'; break;
01620     case Instruction::Div: Out << '/'; break;
01621     case Instruction::Rem: Out << '%'; break;
01622     case Instruction::And: Out << " & "; break;
01623     case Instruction::Or: Out << " | "; break;
01624     case Instruction::Xor: Out << " ^ "; break;
01625     case Instruction::SetEQ: Out << " == "; break;
01626     case Instruction::SetNE: Out << " != "; break;
01627     case Instruction::SetLE: Out << " <= "; break;
01628     case Instruction::SetGE: Out << " >= "; break;
01629     case Instruction::SetLT: Out << " < "; break;
01630     case Instruction::SetGT: Out << " > "; break;
01631     case Instruction::Shl : Out << " << "; break;
01632     case Instruction::Shr : Out << " >> "; break;
01633     default: std::cerr << "Invalid operator type!" << I; abort();
01634     }
01635 
01636     writeOperand(I.getOperand(1));
01637   }
01638 
01639   if (needsCast) {
01640     Out << "))";
01641   }
01642 }
01643 
01644 void CWriter::visitCastInst(CastInst &I) {
01645   if (I.getType() == Type::BoolTy) {
01646     Out << '(';
01647     writeOperand(I.getOperand(0));
01648     Out << " != 0)";
01649     return;
01650   }
01651   Out << '(';
01652   printType(Out, I.getType());
01653   Out << ')';
01654   if (isa<PointerType>(I.getType())&&I.getOperand(0)->getType()->isIntegral() ||
01655       isa<PointerType>(I.getOperand(0)->getType())&&I.getType()->isIntegral()) {
01656     // Avoid "cast to pointer from integer of different size" warnings
01657     Out << "(long)";
01658   }
01659 
01660   writeOperand(I.getOperand(0));
01661 }
01662 
01663 void CWriter::visitSelectInst(SelectInst &I) {
01664   Out << "((";
01665   writeOperand(I.getCondition());
01666   Out << ") ? (";
01667   writeOperand(I.getTrueValue());
01668   Out << ") : (";
01669   writeOperand(I.getFalseValue());
01670   Out << "))";
01671 }
01672 
01673 
01674 void CWriter::lowerIntrinsics(Function &F) {
01675   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
01676     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
01677       if (CallInst *CI = dyn_cast<CallInst>(I++))
01678         if (Function *F = CI->getCalledFunction())
01679           switch (F->getIntrinsicID()) {
01680           case Intrinsic::not_intrinsic:
01681           case Intrinsic::vastart:
01682           case Intrinsic::vacopy:
01683           case Intrinsic::vaend:
01684           case Intrinsic::returnaddress:
01685           case Intrinsic::frameaddress:
01686           case Intrinsic::setjmp:
01687           case Intrinsic::longjmp:
01688           case Intrinsic::prefetch:
01689           case Intrinsic::dbg_stoppoint:
01690             // We directly implement these intrinsics
01691             break;
01692           default:
01693             // If this is an intrinsic that directly corresponds to a GCC
01694             // builtin, we handle it.
01695             const char *BuiltinName = "";
01696 #define GET_GCC_BUILTIN_NAME
01697 #include "llvm/Intrinsics.gen"
01698 #undef GET_GCC_BUILTIN_NAME
01699             // If we handle it, don't lower it.
01700             if (BuiltinName[0]) break;
01701             
01702             // All other intrinsic calls we must lower.
01703             Instruction *Before = 0;
01704             if (CI != &BB->front())
01705               Before = prior(BasicBlock::iterator(CI));
01706 
01707             IL.LowerIntrinsicCall(CI);
01708             if (Before) {        // Move iterator to instruction after call
01709               I = Before; ++I;
01710             } else {
01711               I = BB->begin();
01712             }
01713             break;
01714           }
01715 }
01716 
01717 
01718 
01719 void CWriter::visitCallInst(CallInst &I) {
01720   bool WroteCallee = false;
01721 
01722   // Handle intrinsic function calls first...
01723   if (Function *F = I.getCalledFunction())
01724     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
01725       switch (ID) {
01726       default: {
01727         // If this is an intrinsic that directly corresponds to a GCC
01728         // builtin, we emit it here.
01729         const char *BuiltinName = "";
01730 #define GET_GCC_BUILTIN_NAME
01731 #include "llvm/Intrinsics.gen"
01732 #undef GET_GCC_BUILTIN_NAME
01733         assert(BuiltinName[0] && "Unknown LLVM intrinsic!");
01734 
01735         Out << BuiltinName;
01736         WroteCallee = true;
01737         break;
01738       }
01739       case Intrinsic::vastart:
01740         Out << "0; ";
01741 
01742         Out << "va_start(*(va_list*)";
01743         writeOperand(I.getOperand(1));
01744         Out << ", ";
01745         // Output the last argument to the enclosing function...
01746         if (I.getParent()->getParent()->arg_empty()) {
01747           std::cerr << "The C backend does not currently support zero "
01748                     << "argument varargs functions, such as '"
01749                     << I.getParent()->getParent()->getName() << "'!\n";
01750           abort();
01751         }
01752         writeOperand(--I.getParent()->getParent()->arg_end());
01753         Out << ')';
01754         return;
01755       case Intrinsic::vaend:
01756         if (!isa<ConstantPointerNull>(I.getOperand(1))) {
01757           Out << "0; va_end(*(va_list*)";
01758           writeOperand(I.getOperand(1));
01759           Out << ')';
01760         } else {
01761           Out << "va_end(*(va_list*)0)";
01762         }
01763         return;
01764       case Intrinsic::vacopy:
01765         Out << "0; ";
01766         Out << "va_copy(*(va_list*)";
01767         writeOperand(I.getOperand(1));
01768         Out << ", *(va_list*)";
01769         writeOperand(I.getOperand(2));
01770         Out << ')';
01771         return;
01772       case Intrinsic::returnaddress:
01773         Out << "__builtin_return_address(";
01774         writeOperand(I.getOperand(1));
01775         Out << ')';
01776         return;
01777       case Intrinsic::frameaddress:
01778         Out << "__builtin_frame_address(";
01779         writeOperand(I.getOperand(1));
01780         Out << ')';
01781         return;
01782       case Intrinsic::setjmp:
01783 #if defined(HAVE__SETJMP) && defined(HAVE__LONGJMP)
01784         Out << "_";  // Use _setjmp on systems that support it!
01785 #endif
01786         Out << "setjmp(*(jmp_buf*)";
01787         writeOperand(I.getOperand(1));
01788         Out << ')';
01789         return;
01790       case Intrinsic::longjmp:
01791 #if defined(HAVE__SETJMP) && defined(HAVE__LONGJMP)
01792         Out << "_";  // Use _longjmp on systems that support it!
01793 #endif
01794         Out << "longjmp(*(jmp_buf*)";
01795         writeOperand(I.getOperand(1));
01796         Out << ", ";
01797         writeOperand(I.getOperand(2));
01798         Out << ')';
01799         return;
01800       case Intrinsic::prefetch:
01801         Out << "LLVM_PREFETCH((const void *)";
01802         writeOperand(I.getOperand(1));
01803         Out << ", ";
01804         writeOperand(I.getOperand(2));
01805         Out << ", ";
01806         writeOperand(I.getOperand(3));
01807         Out << ")";
01808         return;
01809       case Intrinsic::dbg_stoppoint: {
01810         // If we use writeOperand directly we get a "u" suffix which is rejected
01811         // by gcc.
01812         DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
01813 
01814         Out << "\n#line "
01815             << SPI.getLine()
01816             << " \"" << SPI.getDirectory()
01817             << SPI.getFileName() << "\"\n";
01818         return;
01819       }
01820       }
01821     }
01822 
01823   Value *Callee = I.getCalledValue();
01824 
01825   // If this is a call to a struct-return function, assign to the first
01826   // parameter instead of passing it to the call.
01827   bool isStructRet = I.getCallingConv() == CallingConv::CSRet;
01828   if (isStructRet) {
01829     Out << "*(";
01830     writeOperand(I.getOperand(1));
01831     Out << ") = ";
01832   }
01833   
01834   if (I.isTailCall()) Out << " /*tail*/ ";
01835 
01836   const PointerType  *PTy   = cast<PointerType>(Callee->getType());
01837   const FunctionType *FTy   = cast<FunctionType>(PTy->getElementType());
01838   
01839   if (!WroteCallee) {
01840     // If this is an indirect call to a struct return function, we need to cast
01841     // the pointer.
01842     bool NeedsCast = isStructRet && !isa<Function>(Callee);
01843 
01844     // GCC is a real PITA.  It does not permit codegening casts of functions to
01845     // function pointers if they are in a call (it generates a trap instruction
01846     // instead!).  We work around this by inserting a cast to void* in between
01847     // the function and the function pointer cast.  Unfortunately, we can't just
01848     // form the constant expression here, because the folder will immediately
01849     // nuke it.
01850     //
01851     // Note finally, that this is completely unsafe.  ANSI C does not guarantee
01852     // that void* and function pointers have the same size. :( To deal with this
01853     // in the common case, we handle casts where the number of arguments passed
01854     // match exactly.
01855     //
01856     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee))
01857       if (CE->getOpcode() == Instruction::Cast)
01858         if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) {
01859           NeedsCast = true;
01860           Callee = RF;
01861         }
01862   
01863     if (NeedsCast) {
01864       // Ok, just cast the pointer type.
01865       Out << "((";
01866       if (!isStructRet)
01867         printType(Out, I.getCalledValue()->getType());
01868       else
01869         printStructReturnPointerFunctionType(Out, 
01870                              cast<PointerType>(I.getCalledValue()->getType()));
01871       Out << ")(void*)";
01872     }
01873     writeOperand(Callee);
01874     if (NeedsCast) Out << ')';
01875   }
01876 
01877   Out << '(';
01878 
01879   unsigned NumDeclaredParams = FTy->getNumParams();
01880 
01881   CallSite::arg_iterator AI = I.op_begin()+1, AE = I.op_end();
01882   unsigned ArgNo = 0;
01883   if (isStructRet) {   // Skip struct return argument.
01884     ++AI;
01885     ++ArgNo;
01886   }
01887       
01888   bool PrintedArg = false;
01889   for (; AI != AE; ++AI, ++ArgNo) {
01890     if (PrintedArg) Out << ", ";
01891     if (ArgNo < NumDeclaredParams &&
01892         (*AI)->getType() != FTy->getParamType(ArgNo)) {
01893       Out << '(';
01894       printType(Out, FTy->getParamType(ArgNo));
01895       Out << ')';
01896     }
01897     writeOperand(*AI);
01898     PrintedArg = true;
01899   }
01900   Out << ')';
01901 }
01902 
01903 void CWriter::visitMallocInst(MallocInst &I) {
01904   assert(0 && "lowerallocations pass didn't work!");
01905 }
01906 
01907 void CWriter::visitAllocaInst(AllocaInst &I) {
01908   Out << '(';
01909   printType(Out, I.getType());
01910   Out << ") alloca(sizeof(";
01911   printType(Out, I.getType()->getElementType());
01912   Out << ')';
01913   if (I.isArrayAllocation()) {
01914     Out << " * " ;
01915     writeOperand(I.getOperand(0));
01916   }
01917   Out << ')';
01918 }
01919 
01920 void CWriter::visitFreeInst(FreeInst &I) {
01921   assert(0 && "lowerallocations pass didn't work!");
01922 }
01923 
01924 void CWriter::printIndexingExpression(Value *Ptr, gep_type_iterator I,
01925                                       gep_type_iterator E) {
01926   bool HasImplicitAddress = false;
01927   // If accessing a global value with no indexing, avoid *(&GV) syndrome
01928   if (GlobalValue *V = dyn_cast<GlobalValue>(Ptr)) {
01929     HasImplicitAddress = true;
01930   } else if (isDirectAlloca(Ptr)) {
01931     HasImplicitAddress = true;
01932   }
01933 
01934   if (I == E) {
01935     if (!HasImplicitAddress)
01936       Out << '*';  // Implicit zero first argument: '*x' is equivalent to 'x[0]'
01937 
01938     writeOperandInternal(Ptr);
01939     return;
01940   }
01941 
01942   const Constant *CI = dyn_cast<Constant>(I.getOperand());
01943   if (HasImplicitAddress && (!CI || !CI->isNullValue()))
01944     Out << "(&";
01945 
01946   writeOperandInternal(Ptr);
01947 
01948   if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
01949     Out << ')';
01950     HasImplicitAddress = false;  // HIA is only true if we haven't addressed yet
01951   }
01952 
01953   assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
01954          "Can only have implicit address with direct accessing");
01955 
01956   if (HasImplicitAddress) {
01957     ++I;
01958   } else if (CI && CI->isNullValue()) {
01959     gep_type_iterator TmpI = I; ++TmpI;
01960 
01961     // Print out the -> operator if possible...
01962     if (TmpI != E && isa<StructType>(*TmpI)) {
01963       Out << (HasImplicitAddress ? "." : "->");
01964       Out << "field" << cast<ConstantUInt>(TmpI.getOperand())->getValue();
01965       I = ++TmpI;
01966     }
01967   }
01968 
01969   for (; I != E; ++I)
01970     if (isa<StructType>(*I)) {
01971       Out << ".field" << cast<ConstantUInt>(I.getOperand())->getValue();
01972     } else {
01973       Out << '[';
01974       writeOperand(I.getOperand());
01975       Out << ']';
01976     }
01977 }
01978 
01979 void CWriter::visitLoadInst(LoadInst &I) {
01980   Out << '*';
01981   if (I.isVolatile()) {
01982     Out << "((";
01983     printType(Out, I.getType(), "volatile*");
01984     Out << ")";
01985   }
01986 
01987   writeOperand(I.getOperand(0));
01988 
01989   if (I.isVolatile())
01990     Out << ')';
01991 }
01992 
01993 void CWriter::visitStoreInst(StoreInst &I) {
01994   Out << '*';
01995   if (I.isVolatile()) {
01996     Out << "((";
01997     printType(Out, I.getOperand(0)->getType(), " volatile*");
01998     Out << ")";
01999   }
02000   writeOperand(I.getPointerOperand());
02001   if (I.isVolatile()) Out << ')';
02002   Out << " = ";
02003   writeOperand(I.getOperand(0));
02004 }
02005 
02006 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
02007   Out << '&';
02008   printIndexingExpression(I.getPointerOperand(), gep_type_begin(I),
02009                           gep_type_end(I));
02010 }
02011 
02012 void CWriter::visitVAArgInst(VAArgInst &I) {
02013   Out << "va_arg(*(va_list*)";
02014   writeOperand(I.getOperand(0));
02015   Out << ", ";
02016   printType(Out, I.getType());
02017   Out << ");\n ";
02018 }
02019 
02020 //===----------------------------------------------------------------------===//
02021 //                       External Interface declaration
02022 //===----------------------------------------------------------------------===//
02023 
02024 bool CTargetMachine::addPassesToEmitFile(PassManager &PM, std::ostream &o,
02025                                          CodeGenFileType FileType, bool Fast) {
02026   if (FileType != TargetMachine::AssemblyFile) return true;
02027 
02028   PM.add(createLowerGCPass());
02029   PM.add(createLowerAllocationsPass(true));
02030   PM.add(createLowerInvokePass());
02031   PM.add(createCFGSimplificationPass());   // clean up after lower invoke.
02032   PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
02033   PM.add(new CWriter(o));
02034   return false;
02035 }