LLVM API Documentation

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