llvm.isnan doesn't access memory
[oota-llvm.git] / lib / Analysis / BasicAliasAnalysis.cpp
index e928a265ff091da20634fd413205ee51f10996a3..efaa7beb89baad1a845673c507152aa0b355d9be 100644 (file)
 //===----------------------------------------------------------------------===//
 
 #include "llvm/Analysis/AliasAnalysis.h"
-#include "llvm/Pass.h"
-#include "llvm/Argument.h"
-#include "llvm/iOther.h"
-#include "llvm/iMemory.h"
 #include "llvm/Constants.h"
-#include "llvm/GlobalVariable.h"
 #include "llvm/DerivedTypes.h"
+#include "llvm/Function.h"
+#include "llvm/GlobalVariable.h"
+#include "llvm/iOther.h"
+#include "llvm/iMemory.h"
+#include "llvm/Pass.h"
 #include "llvm/Target/TargetData.h"
 #include "llvm/Support/GetElementPtrTypeIterator.h"
 using namespace llvm;
@@ -36,23 +36,72 @@ using namespace llvm;
 void llvm::BasicAAStub() {}
 
 namespace {
-  struct BasicAliasAnalysis : public ImmutablePass, public AliasAnalysis {
-    
+  /// NoAA - This class implements the -no-aa pass, which always returns "I
+  /// don't know" for alias queries.  NoAA is unlike other alias analysis
+  /// implementations, in that it does not chain to a previous analysis.  As
+  /// such it doesn't follow many of the rules that other alias analyses must.
+  ///
+  struct NoAA : public ImmutablePass, public AliasAnalysis {
+    virtual AliasResult alias(const Value *V1, unsigned V1Size,
+                              const Value *V2, unsigned V2Size) {
+      return MayAlias;
+    }
+
+    virtual void getMustAliases(Value *P, std::vector<Value*> &RetVals) { }
+    virtual bool pointsToConstantMemory(const Value *P) { return false; }
+    virtual bool doesNotAccessMemory(Function *F) { return false; }
+    virtual bool onlyReadsMemory(Function *F) { return false; }
+    virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size) {
+      return ModRef;
+    }
+    virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2) {
+      return ModRef;
+    }
+    virtual bool hasNoModRefInfoForCalls() const { return true; }
+
+    virtual void deleteValue(Value *V) {}
+    virtual void copyValue(Value *From, Value *To) {}
+    virtual void getAnalysisUsage(AnalysisUsage &AU) const {}
+  };
+  // Register this pass...
+  RegisterOpt<NoAA>
+  U("no-aa", "No Alias Analysis (always returns 'may' alias)");
+
+  // Declare that we implement the AliasAnalysis interface
+  RegisterAnalysisGroup<AliasAnalysis, NoAA> V;
+}  // End of anonymous namespace
+
+
+namespace {
+  /// BasicAliasAnalysis - This is the default alias analysis implementation.
+  /// Because it doesn't chain to a previous alias analysis (like -no-aa), it
+  /// derives from the NoAA class.
+  struct BasicAliasAnalysis : public NoAA {
     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
-      AliasAnalysis::getAnalysisUsage(AU);
+      AU.addRequired<TargetData>();
     }
     
-    virtual void initializePass();
+    virtual void initializePass() {
+      TD = &getAnalysis<TargetData>();
+    }
 
     AliasResult alias(const Value *V1, unsigned V1Size,
                       const Value *V2, unsigned V2Size);
 
     ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
 
+    /// hasNoModRefInfoForCalls - We have no way to test one call against
+    /// another, unless they are pure or const.
+    virtual bool hasNoModRefInfoForCalls() const { return true; }
+
     /// pointsToConstantMemory - Chase pointers until we find a (constant
     /// global) or not.
     bool pointsToConstantMemory(const Value *P);
 
+    virtual bool doesNotAccessMemory(Function *F);
+    virtual bool onlyReadsMemory(Function *F);
+
   private:
     // CheckGEPInstructions - Check two GEP instructions with known
     // must-aliasing base pointers.  This checks to see if the index expressions
@@ -72,10 +121,6 @@ namespace {
   RegisterAnalysisGroup<AliasAnalysis, BasicAliasAnalysis, true> Y;
 }  // End of anonymous namespace
 
-void BasicAliasAnalysis::initializePass() {
-  InitializeAliasAnalysis(this);
-}
-
 // hasUniqueAddress - Return true if the specified value points to something
 // with a unique, discernable, address.
 static inline bool hasUniqueAddress(const Value *V) {
@@ -183,9 +228,8 @@ BasicAliasAnalysis::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
         return NoModRef;
     }
 
-  // If P points to a constant memory location, the call definitely could not
-  // modify the memory location.
-  return pointsToConstantMemory(P) ? Ref : ModRef;
+  // The AliasAnalysis base class has some smarts, lets use them.
+  return AliasAnalysis::getModRefInfo(CS, P, Size);
 }
 
 // alias - Provide a bunch of ad-hoc rules to disambiguate in common cases, such
@@ -351,6 +395,19 @@ BasicAliasAnalysis::alias(const Value *V1, unsigned V1Size,
   return MayAlias;
 }
 
+static bool ValuesEqual(Value *V1, Value *V2) {
+  if (V1->getType() == V2->getType())
+    return V1 == V2;
+  if (Constant *C1 = dyn_cast<Constant>(V1))
+    if (Constant *C2 = dyn_cast<Constant>(V2)) {
+      // Sign extend the constants to long types.
+      C1 = ConstantExpr::getSignExtend(C1, Type::LongTy);
+      C2 = ConstantExpr::getSignExtend(C2, Type::LongTy);
+      return C1 == C2;
+    }
+  return false;
+}
+
 /// CheckGEPInstructions - Check two GEP instructions with known must-aliasing
 /// base pointers.  This checks to see if the index expressions preclude the
 /// pointers from aliasing...
@@ -374,7 +431,7 @@ CheckGEPInstructions(const Type* BasePtr1Ty, std::vector<Value*> &GEP1Ops,
   unsigned MaxOperands = std::max(NumGEP1Operands, NumGEP2Operands);
   unsigned UnequalOper = 0;
   while (UnequalOper != MinOperands &&
-         GEP1Ops[UnequalOper] == GEP2Ops[UnequalOper]) {
+         ValuesEqual(GEP1Ops[UnequalOper], GEP2Ops[UnequalOper])) {
     // Advance through the type as we go...
     ++UnequalOper;
     if (const CompositeType *CT = dyn_cast<CompositeType>(BasePtr1Ty))
@@ -416,7 +473,7 @@ CheckGEPInstructions(const Type* BasePtr1Ty, std::vector<Value*> &GEP1Ops,
   if (SizeMax == ~0U) return MayAlias; // Avoid frivolous work...
 
   // Scan for the first operand that is constant and unequal in the
-  // two getelemenptrs...
+  // two getelementptrs...
   unsigned FirstConstantOper = UnequalOper;
   for (; FirstConstantOper != MinOperands; ++FirstConstantOper) {
     const Value *G1Oper = GEP1Ops[FirstConstantOper];
@@ -425,13 +482,23 @@ CheckGEPInstructions(const Type* BasePtr1Ty, std::vector<Value*> &GEP1Ops,
     if (G1Oper != G2Oper)   // Found non-equal constant indexes...
       if (Constant *G1OC = dyn_cast<Constant>(const_cast<Value*>(G1Oper)))
         if (Constant *G2OC = dyn_cast<Constant>(const_cast<Value*>(G2Oper))) {
-          // Make sure they are comparable (ie, not constant expressions)...
-          // and make sure the GEP with the smaller leading constant is GEP1.
-          Constant *Compare = ConstantExpr::get(Instruction::SetGT, G1OC, G2OC);
-          if (ConstantBool *CV = dyn_cast<ConstantBool>(Compare)) {
-            if (CV->getValue())   // If they are comparable and G2 > G1
-              std::swap(GEP1Ops, GEP2Ops);  // Make GEP1 < GEP2
-            break;
+          if (G1OC->getType() != G2OC->getType()) {
+            // Sign extend both operands to long.
+            G1OC = ConstantExpr::getSignExtend(G1OC, Type::LongTy);
+            G2OC = ConstantExpr::getSignExtend(G2OC, Type::LongTy);
+            GEP1Ops[FirstConstantOper] = G1OC;
+            GEP2Ops[FirstConstantOper] = G2OC;
+          }
+
+          if (G1OC != G2OC) {
+            // Make sure they are comparable (ie, not constant expressions)...
+            // and make sure the GEP with the smaller leading constant is GEP1.
+            Constant *Compare = ConstantExpr::getSetGT(G1OC, G2OC);
+            if (ConstantBool *CV = dyn_cast<ConstantBool>(Compare)) {
+              if (CV->getValue())   // If they are comparable and G2 > G1
+                std::swap(GEP1Ops, GEP2Ops);  // Make GEP1 < GEP2
+              break;
+            }
           }
         }
     BasePtr1Ty = cast<CompositeType>(BasePtr1Ty)->getTypeAtIndex(G1Oper);
@@ -441,7 +508,7 @@ CheckGEPInstructions(const Type* BasePtr1Ty, std::vector<Value*> &GEP1Ops,
   // point, the GEP instructions have run through all of their operands, and we
   // haven't found evidence that there are any deltas between the GEP's.
   // However, one GEP may have more operands than the other.  If this is the
-  // case, there may still be hope.  This this now.
+  // case, there may still be hope.  Check this now.
   if (FirstConstantOper == MinOperands) {
     // Make GEP1Ops be the longer one if there is a longer one.
     if (GEP1Ops.size() < GEP2Ops.size())
@@ -492,10 +559,8 @@ CheckGEPInstructions(const Type* BasePtr1Ty, std::vector<Value*> &GEP1Ops,
   // initial equal sequence of variables into constant zeros to start with.
   for (unsigned i = 0; i != FirstConstantOper; ++i) {
     if (!isa<Constant>(GEP1Ops[i]) || isa<ConstantExpr>(GEP1Ops[i]) ||
-        !isa<Constant>(GEP2Ops[i]) || isa<ConstantExpr>(GEP2Ops[i])) {
-      GEP1Ops[i] = Constant::getNullValue(GEP1Ops[i]->getType());
-      GEP2Ops[i] = Constant::getNullValue(GEP2Ops[i]->getType());
-    }
+        !isa<Constant>(GEP2Ops[i]) || isa<ConstantExpr>(GEP2Ops[i]))
+      GEP1Ops[i] = GEP2Ops[i] = Constant::getNullValue(Type::UIntTy);
   }
 
   // We know that GEP1Ops[FirstConstantOper] & GEP2Ops[FirstConstantOper] are ok
@@ -572,3 +637,124 @@ CheckGEPInstructions(const Type* BasePtr1Ty, std::vector<Value*> &GEP1Ops,
   return MayAlias;
 }
 
+namespace {
+  struct StringCompare {
+    bool operator()(const char *LHS, const char *RHS) {
+      return strcmp(LHS, RHS) < 0;
+    }
+  };
+}
+
+// Note that this list cannot contain libm functions (such as acos and sqrt)
+// that set errno on a domain or other error.
+static const char *DoesntAccessMemoryTable[] = {
+  // LLVM intrinsics:
+  "llvm.frameaddress", "llvm.returnaddress", "llvm.readport", "llvm.isnan",
+
+  "abs", "labs", "llabs", "imaxabs", "fabs", "fabsf", "fabsl",
+  "trunc", "truncf", "truncl", "ldexp",
+  
+  "atan", "atanf", "atanl",   "atan2", "atan2f", "atan2l",
+  "cbrt",
+  "cos", "cosf", "cosl",      "cosh", "coshf", "coshl",
+  "exp", "expf", "expl", 
+  "hypot",
+  "sin", "sinf", "sinl",      "sinh", "sinhf", "sinhl",
+  "tan", "tanf", "tanl",      "tanh", "tanhf", "tanhl",
+
+  // ctype.h
+  "isalnum", "isalpha", "iscntrl", "isdigit", "isgraph", "islower", "isprint"
+  "ispunct", "isspace", "isupper", "isxdigit", "tolower", "toupper",
+
+  // wctype.h"
+  "iswalnum", "iswalpha", "iswcntrl", "iswdigit", "iswgraph", "iswlower",
+  "iswprint", "iswpunct", "iswspace", "iswupper", "iswxdigit",
+
+  "iswctype", "towctrans", "towlower", "towupper", 
+
+  "btowc", "wctob", 
+
+  "isinf", "isnan", "finite",
+
+  // C99 math functions
+  "copysign", "copysignf", "copysignd",
+  "nexttoward", "nexttowardf", "nexttowardd",
+  "nextafter", "nextafterf", "nextafterd",
+
+  // glibc functions:
+  "__fpclassify", "__fpclassifyf", "__fpclassifyl",
+  "__signbit", "__signbitf", "__signbitl",
+};
+
+static const unsigned DAMTableSize =
+    sizeof(DoesntAccessMemoryTable)/sizeof(DoesntAccessMemoryTable[0]);
+
+/// doesNotAccessMemory - Return true if we know that the function does not
+/// access memory at all.  Since basicaa does no analysis, we can only do simple
+/// things here.  In particular, if we have an external function with the name
+/// of a standard C library function, we are allowed to assume it will be
+/// resolved by libc, so we can hardcode some entries in here.
+bool BasicAliasAnalysis::doesNotAccessMemory(Function *F) {
+  if (!F->isExternal()) return false;
+
+  static bool Initialized = false;
+  if (!Initialized) {
+    // Sort the table the first time through.
+    std::sort(DoesntAccessMemoryTable, DoesntAccessMemoryTable+DAMTableSize,
+              StringCompare());
+    Initialized = true;
+  }
+
+  const char **Ptr = std::lower_bound(DoesntAccessMemoryTable,
+                                      DoesntAccessMemoryTable+DAMTableSize,
+                                      F->getName().c_str(), StringCompare());
+  return Ptr != DoesntAccessMemoryTable+DAMTableSize && *Ptr == F->getName();
+}
+
+
+static const char *OnlyReadsMemoryTable[] = {
+  "atoi", "atol", "atof", "atoll", "atoq", "a64l",
+  "bcmp", "memcmp", "memchr", "memrchr", "wmemcmp", "wmemchr", 
+
+  // Strings
+  "strcmp", "strcasecmp", "strcoll", "strncmp", "strncasecmp",
+  "strchr", "strcspn", "strlen", "strpbrk", "strrchr", "strspn", "strstr", 
+  "index", "rindex",
+
+  // Wide char strings
+  "wcschr", "wcscmp", "wcscoll", "wcscspn", "wcslen", "wcsncmp", "wcspbrk",
+  "wcsrchr", "wcsspn", "wcsstr", 
+
+  // glibc
+  "alphasort", "alphasort64", "versionsort", "versionsort64",
+
+  // C99
+  "nan", "nanf", "nand",
+
+  // File I/O
+  "feof", "ferror", "fileno",
+  "feof_unlocked", "ferror_unlocked", "fileno_unlocked"
+};
+
+static const unsigned ORMTableSize =
+    sizeof(OnlyReadsMemoryTable)/sizeof(OnlyReadsMemoryTable[0]);
+
+bool BasicAliasAnalysis::onlyReadsMemory(Function *F) {
+  if (doesNotAccessMemory(F)) return true;
+  if (!F->isExternal()) return false;
+
+  static bool Initialized = false;
+  if (!Initialized) {
+    // Sort the table the first time through.
+    std::sort(OnlyReadsMemoryTable, OnlyReadsMemoryTable+ORMTableSize,
+              StringCompare());
+    Initialized = true;
+  }
+
+  const char **Ptr = std::lower_bound(OnlyReadsMemoryTable,
+                                      OnlyReadsMemoryTable+ORMTableSize,
+                                      F->getName().c_str(), StringCompare());
+  return Ptr != OnlyReadsMemoryTable+ORMTableSize && *Ptr == F->getName();
+}
+
+