We won't use automake
[oota-llvm.git] / lib / Target / CBackend / CBackend.cpp
index 491b3484119acf839ea4af83ae3c8a27de5b2e3d..7af9bfe4fa6b6d566bc9f8b478d767d781850c95 100644 (file)
@@ -13,7 +13,6 @@
 //===----------------------------------------------------------------------===//
 
 #include "CTargetMachine.h"
-#include "llvm/Target/TargetMachineImpls.h"
 #include "llvm/Constants.h"
 #include "llvm/DerivedTypes.h"
 #include "llvm/Module.h"
 #include "llvm/PassManager.h"
 #include "llvm/SymbolTable.h"
 #include "llvm/Intrinsics.h"
-#include "llvm/IntrinsicLowering.h"
 #include "llvm/Analysis/ConstantsScanner.h"
 #include "llvm/Analysis/FindUsedTypes.h"
 #include "llvm/Analysis/LoopInfo.h"
+#include "llvm/CodeGen/IntrinsicLowering.h"
 #include "llvm/Transforms/Scalar.h"
+#include "llvm/Target/TargetMachineRegistry.h"
 #include "llvm/Support/CallSite.h"
 #include "llvm/Support/CFG.h"
 #include "llvm/Support/GetElementPtrTypeIterator.h"
 #include "llvm/Support/InstVisitor.h"
 #include "llvm/Support/Mangler.h"
-#include "Support/StringExtras.h"
-#include "Config/config.h"
+#include "llvm/ADT/StringExtras.h"
+#include "llvm/Support/MathExtras.h"
+#include "llvm/Config/config.h"
 #include <algorithm>
+#include <iostream>
 #include <sstream>
 using namespace llvm;
 
 namespace {
+  // Register the target.
+  RegisterTarget<CTargetMachine> X("c", "  C backend");
+
   /// NameAllUsedStructs - This pass inserts names for any unnamed structure
   /// types that are used by the program.
   ///
-  class CBackendNameAllUsedStructs : public Pass {
+  class CBackendNameAllUsedStructs : public ModulePass {
     void getAnalysisUsage(AnalysisUsage &AU) const {
       AU.addRequired<FindUsedTypes>();
     }
@@ -51,7 +56,7 @@ namespace {
       return "C backend type canonicalizer";
     }
 
-    virtual bool run(Module &M);
+    virtual bool runOnModule(Module &M);
   };
   
   /// CWriter - This class is the main chunk of code that converts an LLVM
@@ -169,6 +174,7 @@ namespace {
     void visitUnwindInst(UnwindInst &I) {
       assert(0 && "Lowerinvoke pass didn't work!");
     }
+    void visitUnreachableInst(UnreachableInst &I);
 
     void visitPHINode(PHINode &I);
     void visitBinaryOperator(Instruction &I);
@@ -198,6 +204,8 @@ namespace {
     }
 
     bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
+    void printPHICopiesForSuccessor(BasicBlock *CurBlock,
+                                    BasicBlock *Successor, unsigned Indent);
     void printPHICopiesForSuccessors(BasicBlock *CurBlock, 
                                      unsigned Indent);
     void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
@@ -211,7 +219,7 @@ namespace {
 /// the program, and removes names from structure types that are not used by the
 /// program.
 ///
-bool CBackendNameAllUsedStructs::run(Module &M) {
+bool CBackendNameAllUsedStructs::runOnModule(Module &M) {
   // Get a set of types that are used by the program...
   std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
   
@@ -222,11 +230,11 @@ bool CBackendNameAllUsedStructs::run(Module &M) {
   for (SymbolTable::type_iterator TI = MST.type_begin(), TE = MST.type_end();
        TI != TE; ) {
     SymbolTable::type_iterator I = TI++;
-    if (StructType *STy = dyn_cast<StructType>(I->second)) {
+    if (const StructType *STy = dyn_cast<StructType>(I->second)) {
       // If this is not used, remove it from the symbol table.
       std::set<const Type *>::iterator UTI = UT.find(STy);
       if (UTI == UT.end())
-        MST.remove(I->first, (Type*)I->second);
+        MST.remove(I);
       else
         UT.erase(UTI);
     }
@@ -236,10 +244,12 @@ bool CBackendNameAllUsedStructs::run(Module &M) {
   // structure types.
   //
   bool Changed = false;
+  unsigned RenameCounter = 0;
   for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
        I != E; ++I)
     if (const StructType *ST = dyn_cast<StructType>(*I)) {
-      ((Value*)ST)->setName("unnamed", &MST);
+      while (M.addTypeName("unnamed"+utostr(RenameCounter), ST))
+        ++RenameCounter;
       Changed = true;
     }
   return Changed;
@@ -253,7 +263,7 @@ std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
                                  const std::string &NameSoFar,
                                  bool IgnoreName) {
   if (Ty->isPrimitiveType())
-    switch (Ty->getPrimitiveID()) {
+    switch (Ty->getTypeID()) {
     case Type::VoidTyID:   return Out << "void "               << NameSoFar;
     case Type::BoolTyID:   return Out << "bool "               << NameSoFar;
     case Type::UByteTyID:  return Out << "unsigned char "      << NameSoFar;
@@ -267,7 +277,7 @@ std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
     case Type::FloatTyID:  return Out << "float "              << NameSoFar;
     case Type::DoubleTyID: return Out << "double "             << NameSoFar;
     default :
-      std::cerr << "Unknown primitive type: " << Ty << "\n";
+      std::cerr << "Unknown primitive type: " << *Ty << "\n";
       abort();
     }
   
@@ -277,7 +287,7 @@ std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
     if (I != TypeNames.end()) return Out << I->second << " " << NameSoFar;
   }
 
-  switch (Ty->getPrimitiveID()) {
+  switch (Ty->getTypeID()) {
   case Type::FunctionTyID: {
     const FunctionType *MTy = cast<FunctionType>(Ty);
     std::stringstream FunctionInnards; 
@@ -511,12 +521,17 @@ void CWriter::printConstant(Constant *CPV) {
 
     default:
       std::cerr << "CWriter Error: Unhandled constant expression: "
-                << CE << "\n";
+                << *CE << "\n";
       abort();
     }
+  } else if (isa<UndefValue>(CPV) && CPV->getType()->isFirstClassType()) {
+    Out << "((";
+    printType(Out, CPV->getType());
+    Out << ")/*UNDEF*/0)";
+    return;
   }
 
-  switch (CPV->getType()->getPrimitiveID()) {
+  switch (CPV->getType()->getTypeID()) {
   case Type::BoolTyID:
     Out << (CPV == ConstantBool::False ? "0" : "1"); break;
   case Type::SByteTyID:
@@ -550,20 +565,56 @@ void CWriter::printConstant(Constant *CPV) {
       Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
           << "*)&FPConstant" << I->second << ")";
     } else {
+      if (IsNAN(FPC->getValue())) {
+        // The value is NaN
+        // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
+        // it's 0x7ff4.
+        const unsigned long QuietNaN = 0x7ff8UL;
+        const unsigned long SignalNaN = 0x7ff4UL;
+
+        // We need to grab the first part of the FP #
+        union {
+          double   d;
+          uint64_t ll;
+        } DHex;
+        char Buffer[100];
+
+        DHex.d = FPC->getValue();
+        sprintf(Buffer, "0x%llx", (unsigned long long)DHex.ll);
+
+        std::string Num(&Buffer[0], &Buffer[6]);
+        unsigned long Val = strtoul(Num.c_str(), 0, 16);
+
+        if (FPC->getType() == Type::FloatTy)
+          Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
+              << Buffer << "\") /*nan*/ ";
+        else
+          Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
+              << Buffer << "\") /*nan*/ ";
+      } else if (IsInf(FPC->getValue())) {
+        // The value is Inf
+        if (FPC->getValue() < 0) Out << "-";
+        Out << "LLVM_INF" << (FPC->getType() == Type::FloatTy ? "F" : "")
+            << " /*inf*/ ";
+      } else {
+        std::string Num;
 #if HAVE_PRINTF_A
-      // Print out the constant as a floating point number.
-      char Buffer[100];
-      sprintf(Buffer, "%a", FPC->getValue());
-      Out << Buffer << " /*" << FPC->getValue() << "*/ ";
+        // Print out the constant as a floating point number.
+        char Buffer[100];
+        sprintf(Buffer, "%a", FPC->getValue());
+        Num = Buffer;
 #else
-      Out << ftostr(FPC->getValue());
+        Num = ftostr(FPC->getValue());
 #endif
+        Out << Num;
+      }
     }
     break;
   }
 
   case Type::ArrayTyID:
-    if (isa<ConstantAggregateZero>(CPV)) {
+    if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
       const ArrayType *AT = cast<ArrayType>(CPV->getType());
       Out << "{";
       if (AT->getNumElements()) {
@@ -582,7 +633,7 @@ void CWriter::printConstant(Constant *CPV) {
     break;
 
   case Type::StructTyID:
-    if (isa<ConstantAggregateZero>(CPV)) {
+    if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
       const StructType *ST = cast<StructType>(CPV->getType());
       Out << "{";
       if (ST->getNumElements()) {
@@ -614,13 +665,13 @@ void CWriter::printConstant(Constant *CPV) {
       printType(Out, CPV->getType());
       Out << ")/*NULL*/0)";
       break;
-    } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CPV)) {
-      writeOperand(CPR->getValue());
+    } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
+      writeOperand(GV);
       break;
     }
     // FALL THROUGH
   default:
-    std::cerr << "Unknown constant type: " << CPV << "\n";
+    std::cerr << "Unknown constant type: " << *CPV << "\n";
     abort();
   }
 }
@@ -635,7 +686,8 @@ void CWriter::writeOperandInternal(Value *Operand) {
       return;
     }
   
-  if (Constant *CPV = dyn_cast<Constant>(Operand)) {
+  Constant* CPV = dyn_cast<Constant>(Operand);
+  if (CPV && !isa<GlobalValue>(CPV)) {
     printConstant(CPV); 
   } else {
     Out << Mang->getValueName(Operand);
@@ -658,13 +710,13 @@ void CWriter::writeOperand(Value *Operand) {
 static void generateCompilerSpecificCode(std::ostream& Out) {
   // Alloca is hard to get, and we don't want to include stdlib.h here...
   Out << "/* get a declaration for alloca */\n"
-      << "#ifdef sun\n"
+      << "#if defined(sun) || defined(__CYGWIN__) || defined(__APPLE__)\n"
       << "extern void *__builtin_alloca(unsigned long);\n"
       << "#define alloca(x) __builtin_alloca(x)\n"
+      << "#elif defined(__FreeBSD__)\n"
+      << "#define alloca(x) __builtin_alloca(x)\n"
       << "#else\n"
-      << "#ifndef __FreeBSD__\n"
       << "#include <alloca.h>\n"
-      << "#endif\n"
       << "#endif\n\n";
 
   // We output GCC specific attributes to preserve 'linkonce'ness on globals.
@@ -693,6 +745,53 @@ static void generateCompilerSpecificCode(std::ostream& Out) {
       << "#else\n"
       << "#define __ATTRIBUTE_WEAK__\n"
       << "#endif\n\n";
+
+  // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
+  // From the GCC documentation:
+  // 
+  //   double __builtin_nan (const char *str)
+  //
+  // This is an implementation of the ISO C99 function nan.
+  //
+  // Since ISO C99 defines this function in terms of strtod, which we do
+  // not implement, a description of the parsing is in order. The string is
+  // parsed as by strtol; that is, the base is recognized by leading 0 or
+  // 0x prefixes. The number parsed is placed in the significand such that
+  // the least significant bit of the number is at the least significant
+  // bit of the significand. The number is truncated to fit the significand
+  // field provided. The significand is forced to be a quiet NaN.
+  //
+  // This function, if given a string literal, is evaluated early enough
+  // that it is considered a compile-time constant.
+  //
+  //   float __builtin_nanf (const char *str)
+  //
+  // Similar to __builtin_nan, except the return type is float.
+  //
+  //   double __builtin_inf (void)
+  //
+  // Similar to __builtin_huge_val, except a warning is generated if the
+  // target floating-point format does not support infinities. This
+  // function is suitable for implementing the ISO C99 macro INFINITY.
+  //
+  //   float __builtin_inff (void)
+  //
+  // Similar to __builtin_inf, except the return type is float.
+  Out << "#ifdef __GNUC__\n"
+      << "#define LLVM_NAN(NanStr)   __builtin_nan(NanStr)   /* Double */\n"
+      << "#define LLVM_NANF(NanStr)  __builtin_nanf(NanStr)  /* Float */\n"
+      << "#define LLVM_NANS(NanStr)  __builtin_nans(NanStr)  /* Double */\n"
+      << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
+      << "#define LLVM_INF           __builtin_inf()         /* Double */\n"
+      << "#define LLVM_INFF          __builtin_inff()        /* Float */\n"
+      << "#else\n"
+      << "#define LLVM_NAN(NanStr)   ((double)0.0)           /* Double */\n"
+      << "#define LLVM_NANF(NanStr)  0.0F                    /* Float */\n"
+      << "#define LLVM_NANS(NanStr)  ((double)0.0)           /* Double */\n"
+      << "#define LLVM_NANSF(NanStr) 0.0F                    /* Float */\n"
+      << "#define LLVM_INF           ((double)0.0)           /* Double */\n"
+      << "#define LLVM_INFF          0.0F                    /* Float */\n"
+      << "#endif\n";
 }
 
 bool CWriter::doInitialization(Module &M) {
@@ -1114,6 +1213,10 @@ void CWriter::visitSwitchInst(SwitchInst &SI) {
   Out << "  }\n";
 }
 
+void CWriter::visitUnreachableInst(UnreachableInst &I) {
+  Out << "  /*UNREACHABLE*/;\n";
+}
+
 bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
   /// FIXME: This should be reenabled, but loop reordering safe!!
   return true;
@@ -1129,18 +1232,38 @@ bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
   return false;
 }
 
-void CWriter::printPHICopiesForSuccessors(BasicBlock *CurBlock, 
+void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
+                                          BasicBlock *Successor, 
                                           unsigned Indent) {
-  for (succ_iterator SI = succ_begin(CurBlock), E = succ_end(CurBlock);
-       SI != E; ++SI)
-    for (BasicBlock::iterator I = SI->begin();
-         PHINode *PN = dyn_cast<PHINode>(I); ++I) {
-      //  now we have to do the printing
+  for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
+    PHINode *PN = cast<PHINode>(I);
+    // Now we have to do the printing.
+    Value *IV = PN->getIncomingValueForBlock(CurBlock);
+    if (!isa<UndefValue>(IV)) {
       Out << std::string(Indent, ' ');
       Out << "  " << Mang->getValueName(I) << "__PHI_TEMPORARY = ";
-      writeOperand(PN->getIncomingValue(PN->getBasicBlockIndex(CurBlock)));
+      writeOperand(IV);
       Out << ";   /* for PHI node */\n";
     }
+  }
+}
+
+
+void CWriter::printPHICopiesForSuccessors(BasicBlock *CurBlock, 
+                                          unsigned Indent) {
+  for (succ_iterator SI = succ_begin(CurBlock), E = succ_end(CurBlock);
+       SI != E; ++SI)
+    for (BasicBlock::iterator I = SI->begin(); isa<PHINode>(I); ++I) {
+      PHINode *PN = cast<PHINode>(I);
+      // Now we have to do the printing.
+      Value *IV = PN->getIncomingValueForBlock(CurBlock);
+      if (!isa<UndefValue>(IV)) {
+        Out << std::string(Indent, ' ');
+        Out << "  " << Mang->getValueName(I) << "__PHI_TEMPORARY = ";
+        writeOperand(IV);
+        Out << ";   /* for PHI node */\n";
+      }
+    }
 }
 
 
@@ -1157,7 +1280,6 @@ void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
 // that immediately succeeds the current one.
 //
 void CWriter::visitBranchInst(BranchInst &I) {
-  printPHICopiesForSuccessors(I.getParent(), 0);
 
   if (I.isConditional()) {
     if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
@@ -1165,10 +1287,12 @@ void CWriter::visitBranchInst(BranchInst &I) {
       writeOperand(I.getCondition());
       Out << ") {\n";
       
+      printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
       printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
       
       if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
         Out << "  } else {\n";
+        printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
         printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
       }
     } else {
@@ -1177,11 +1301,13 @@ void CWriter::visitBranchInst(BranchInst &I) {
       writeOperand(I.getCondition());
       Out << ") {\n";
 
+      printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
       printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
     }
 
     Out << "  }\n";
   } else {
+    printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
     printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
   }
   Out << "\n";
@@ -1321,9 +1447,13 @@ void CWriter::visitCallInst(CallInst &I) {
         Out << ")";
         return;
       case Intrinsic::vaend:
-        Out << "va_end(*(va_list*)&";
-        writeOperand(I.getOperand(1));
-        Out << ")";
+        if (!isa<ConstantPointerNull>(I.getOperand(1))) {
+          Out << "va_end(*(va_list*)&";
+          writeOperand(I.getOperand(1));
+          Out << ")";
+        } else {
+          Out << "va_end(*(va_list*)0)";
+        }
         return;
       case Intrinsic::vacopy:
         Out << "0;";
@@ -1406,9 +1536,6 @@ void CWriter::printIndexingExpression(Value *Ptr, gep_type_iterator I,
   // If accessing a global value with no indexing, avoid *(&GV) syndrome
   if (GlobalValue *V = dyn_cast<GlobalValue>(Ptr)) {
     HasImplicitAddress = true;
-  } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Ptr)) {
-    HasImplicitAddress = true;
-    Ptr = CPR->getValue();         // Get to the global...
   } else if (isDirectAlloca(Ptr)) {
     HasImplicitAddress = true;
   }
@@ -1505,9 +1632,4 @@ bool CTargetMachine::addPassesToEmitAssembly(PassManager &PM, std::ostream &o) {
   return false;
 }
 
-TargetMachine *llvm::allocateCTargetMachine(const Module &M,
-                                            IntrinsicLowering *IL) {
-  return new CTargetMachine(M, IL);
-}
-
 // vim: sw=2