Fix for PR341
[oota-llvm.git] / lib / Analysis / DataStructure / Steensgaard.cpp
index 24765228001dcc9a1cf67cfd755c4657f2bce6f2..5b055dc345ae828a06598135099f48b030b2a746 100644 (file)
@@ -1,4 +1,11 @@
 //===- Steensgaard.cpp - Context Insensitive Alias Analysis ---------------===//
+// 
+//                     The LLVM Compiler Infrastructure
+//
+// This file was developed by the LLVM research group and is distributed under
+// the University of Illinois Open Source License. See LICENSE.TXT for details.
+// 
+//===----------------------------------------------------------------------===//
 //
 // This pass uses the data structure graphs to implement a simple context
 // insensitive alias analysis.  It does this by computing the local analysis
 //
 //===----------------------------------------------------------------------===//
 
-#include "llvm/Analysis/DataStructure.h"
-#include "llvm/Analysis/DSGraph.h"
+#include "llvm/Analysis/DataStructure/DataStructure.h"
+#include "llvm/Analysis/DataStructure/DSGraph.h"
 #include "llvm/Analysis/AliasAnalysis.h"
 #include "llvm/Module.h"
-#include "Support/Statistic.h"
-
-namespace {
-  Statistic<> NumNoAlias  ("steens", "Number of 'no alias' replies");
-  Statistic<> NumMayAlias ("steens", "Number of 'may alias' replies");
-};
+#include "Support/Debug.h"
+#include <iostream>
+using namespace llvm;
 
 namespace {
   class Steens : public Pass, public AliasAnalysis {
     DSGraph *ResultGraph;
+    DSGraph *GlobalsGraph;  // FIXME: Eliminate globals graph stuff from DNE
   public:
-    Steens() : ResultGraph(0) {}
-    ~Steens() { assert(ResultGraph == 0 && "releaseMemory not called?"); }
+    Steens() : ResultGraph(0), GlobalsGraph(0) {}
+    ~Steens() {
+      releaseMyMemory();
+      assert(ResultGraph == 0 && "releaseMemory not called?");
+    }
 
     //------------------------------------------------
     // Implement the Pass API
@@ -34,12 +42,12 @@ namespace {
     //
     bool run(Module &M);
 
-    virtual void releaseMemory() { delete ResultGraph; ResultGraph = 0; }
+    virtual void releaseMyMemory() { delete ResultGraph; ResultGraph = 0; }
 
     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
+      AliasAnalysis::getAnalysisUsage(AU);
       AU.setPreservesAll();                    // Does not transform code...
       AU.addRequired<LocalDataStructures>();   // Uses local dsgraph
-      AU.addRequired<AliasAnalysis>();         // Chains to another AA impl...
     }
 
     // print - Implement the Pass::print method...
@@ -53,20 +61,9 @@ namespace {
     //  
 
     // alias - This is the only method here that does anything interesting...
-    Result alias(const Value *V1, const Value *V2);
+    AliasResult alias(const Value *V1, unsigned V1Size,
+                      const Value *V2, unsigned V2Size);
     
-    /// canCallModify - Not implemented yet: FIXME
-    ///
-    Result canCallModify(const CallInst &CI, const Value *Ptr) {
-      return MayAlias;
-    }
-    
-    /// canInvokeModify - Not implemented yet: FIXME
-    ///
-    Result canInvokeModify(const InvokeInst &I, const Value *Ptr) {
-      return MayAlias;
-    }
-
   private:
     void ResolveFunctionCall(Function *F, const DSCallSite &Call,
                              DSNodeHandle &RetVal);
@@ -74,22 +71,20 @@ namespace {
 
   // Register the pass...
   RegisterOpt<Steens> X("steens-aa",
-                        "Steensgaard's FlowInsensitive/ConIns alias analysis");
+                        "Steensgaard's alias analysis (DSGraph based)");
 
   // Register as an implementation of AliasAnalysis
   RegisterAnalysisGroup<AliasAnalysis, Steens> Y;
 }
 
-
 /// ResolveFunctionCall - Resolve the actual arguments of a call to function F
 /// with the specified call site descriptor.  This function links the arguments
 /// and the return value for the call site context-insensitively.
 ///
-void Steens::ResolveFunctionCall(Function *F,
-                                 const DSCallSite &Call,
+void Steens::ResolveFunctionCall(Function *F, const DSCallSite &Call,
                                  DSNodeHandle &RetVal) {
   assert(ResultGraph != 0 && "Result graph not allocated!");
-  hash_map<Value*, DSNodeHandle> &ValMap = ResultGraph->getScalarMap();
+  DSGraph::ScalarMapTy &ValMap = ResultGraph->getScalarMap();
 
   // Handle the return value of the function...
   if (Call.getRetVal().getNode() && RetVal.getNode())
@@ -97,13 +92,12 @@ void Steens::ResolveFunctionCall(Function *F,
 
   // Loop over all pointer arguments, resolving them to their provided pointers
   unsigned PtrArgIdx = 0;
-  for (Function::aiterator AI = F->abegin(), AE = F->aend(); AI != AE; ++AI) {
-    hash_map<Value*, DSNodeHandle>::iterator I = ValMap.find(AI);
+  for (Function::aiterator AI = F->abegin(), AE = F->aend();
+       AI != AE && PtrArgIdx < Call.getNumPtrArgs(); ++AI) {
+    DSGraph::ScalarMapTy::iterator I = ValMap.find(AI);
     if (I != ValMap.end())    // If its a pointer argument...
-      I->second.addEdgeTo(Call.getPtrArg(PtrArgIdx++));
+      I->second.mergeWith(Call.getPtrArg(PtrArgIdx++));
   }
-
-  assert(PtrArgIdx == Call.getNumPtrArgs() && "Argument resolution mismatch!");
 }
 
 
@@ -111,48 +105,44 @@ void Steens::ResolveFunctionCall(Function *F,
 /// program.
 ///
 bool Steens::run(Module &M) {
+  InitializeAliasAnalysis(this);
   assert(ResultGraph == 0 && "Result graph already allocated!");
   LocalDataStructures &LDS = getAnalysis<LocalDataStructures>();
 
   // Create a new, empty, graph...
-  ResultGraph = new DSGraph();
+  ResultGraph = new DSGraph(getTargetData());
+  GlobalsGraph = new DSGraph(getTargetData());
+  ResultGraph->setGlobalsGraph(GlobalsGraph);
+  ResultGraph->setPrintAuxCalls();
 
   // RetValMap - Keep track of the return values for all functions that return
   // valid pointers.
   //
-  hash_map<Function*, DSNodeHandle> RetValMap;
+  DSGraph::ReturnNodesTy RetValMap;
 
   // Loop over the rest of the module, merging graphs for non-external functions
   // into this graph.
   //
+  unsigned Count = 0;
   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
     if (!I->isExternal()) {
-      hash_map<Value*, DSNodeHandle> ValMap;
+      DSGraph::ScalarMapTy ValMap;
       {  // Scope to free NodeMap memory ASAP
-        hash_map<const DSNode*, DSNodeHandle> NodeMap;
+        DSGraph::NodeMapTy NodeMap;
         const DSGraph &FDSG = LDS.getDSGraph(*I);
-        DSNodeHandle RetNode = ResultGraph->cloneInto(FDSG, ValMap, NodeMap);
-
-        // Keep track of the return node of the function's graph if it returns a
-        // value...
-        //
-        if (RetNode.getNode())
-          RetValMap[I] = RetNode;
+        ResultGraph->cloneInto(FDSG, ValMap, RetValMap, NodeMap,
+                               DSGraph::UpdateInlinedGlobals);
       }
 
       // Incorporate the inlined Function's ScalarMap into the global
       // ScalarMap...
-      hash_map<Value*, DSNodeHandle> &GVM = ResultGraph->getScalarMap();
-
-      while (!ValMap.empty()) { // Loop over value map, moving entries over...
-        const std::pair<Value*, DSNodeHandle> &DSN = *ValMap.begin();
-        hash_map<Value*, DSNodeHandle>::iterator I = GVM.find(DSN.first);
-        if (I == GVM.end())
-          GVM[DSN.first] = DSN.second;
-        else
-          I->second.mergeWith(DSN.second);
-        ValMap.erase(ValMap.begin());
-      }
+      DSGraph::ScalarMapTy &GVM = ResultGraph->getScalarMap();
+      for (DSGraph::ScalarMapTy::iterator I = ValMap.begin(),
+             E = ValMap.end(); I != E; ++I)
+        GVM[I->first].mergeWith(I->second);
+
+      if ((++Count & 1) == 0)   // Prune nodes out every other time...
+        ResultGraph->removeTriviallyDeadNodes();
     }
 
   // FIXME: Must recalculate and use the Incomplete markers!!
@@ -171,8 +161,12 @@ bool Steens::run(Module &M) {
     DSCallSite &CurCall = Calls[i];
     
     // Loop over the called functions, eliminating as many as possible...
-    std::vector<GlobalValue*> CallTargets =
-      CurCall.getCallee().getNode()->getGlobals();
+    std::vector<GlobalValue*> CallTargets;
+    if (CurCall.isDirectCall())
+      CallTargets.push_back(CurCall.getCalleeFunc());
+    else 
+      CallTargets = CurCall.getCalleeNode()->getGlobals();
+
     for (unsigned c = 0; c != CallTargets.size(); ) {
       // If we can eliminate this function call, do so!
       bool Eliminated = false;
@@ -181,24 +175,29 @@ bool Steens::run(Module &M) {
           ResolveFunctionCall(F, CurCall, RetValMap[F]);
           Eliminated = true;
         }
-      if (Eliminated)
-        CallTargets.erase(CallTargets.begin()+c);
-      else
+      if (Eliminated) {
+        CallTargets[c] = CallTargets.back();
+        CallTargets.pop_back();
+      } else
         ++c;  // Cannot eliminate this call, skip over it...
     }
 
-    if (CallTargets.empty())          // Eliminated all calls?
-      Calls.erase(Calls.begin()+i);   // Remove from call list...
-    else
+    if (CallTargets.empty()) {        // Eliminated all calls?
+      CurCall = Calls.back();         // Remove entry
+      Calls.pop_back();
+    } else
       ++i;                            // Skip this call site...
   }
 
+  RetValMap.clear();
+
   // Update the "incomplete" markers on the nodes, ignoring unknownness due to
   // incoming arguments...
   ResultGraph->maskIncompleteMarkers();
   ResultGraph->markIncompleteNodes(DSGraph::IgnoreFormalArgs);
 
   // Remove any nodes that are dead after all of the merging we have done...
+  // FIXME: We should be able to disable the globals graph for steens!
   ResultGraph->removeDeadNodes(DSGraph::KeepUnreachableGlobals);
 
   DEBUG(print(std::cerr, &M));
@@ -206,23 +205,24 @@ bool Steens::run(Module &M) {
 }
 
 // alias - This is the only method here that does anything interesting...
-AliasAnalysis::Result Steens::alias(const Value *V1, const Value *V2) {
+AliasAnalysis::AliasResult Steens::alias(const Value *V1, unsigned V1Size,
+                                         const Value *V2, unsigned V2Size) {
+  // FIXME: HANDLE Size argument!
   assert(ResultGraph && "Result graph has not been computed yet!");
 
-  hash_map<Value*, DSNodeHandle> &GSM = ResultGraph->getScalarMap();
+  DSGraph::ScalarMapTy &GSM = ResultGraph->getScalarMap();
 
-  hash_map<Value*, DSNodeHandle>::iterator I = GSM.find(const_cast<Value*>(V1));
+  DSGraph::ScalarMapTy::iterator I = GSM.find(const_cast<Value*>(V1));
   if (I != GSM.end() && I->second.getNode()) {
     DSNodeHandle &V1H = I->second;
-    hash_map<Value*, DSNodeHandle>::iterator J=GSM.find(const_cast<Value*>(V2));
+    DSGraph::ScalarMapTy::iterator J=GSM.find(const_cast<Value*>(V2));
     if (J != GSM.end() && J->second.getNode()) {
       DSNodeHandle &V2H = J->second;
       // If the two pointers point to different data structure graph nodes, they
       // cannot alias!
-      if (V1H.getNode() != V2H.getNode()) {  // FIXME: Handle incompleteness!
-        ++NumNoAlias;
+      if (V1H.getNode() != V2H.getNode())    // FIXME: Handle incompleteness!
         return NoAlias;
-      }
+
       // FIXME: If the two pointers point to the same node, and the offsets are
       // different, and the LinkIndex vector doesn't alias the section, then the
       // two pointers do not alias.  We need access size information for the two
@@ -231,11 +231,8 @@ AliasAnalysis::Result Steens::alias(const Value *V1, const Value *V2) {
     }
   }
 
-  // Since Steensgaard cannot do any better, count it as a 'may alias'
-  ++NumMayAlias;
-
   // If we cannot determine alias properties based on our graph, fall back on
   // some other AA implementation.
   //
-  return getAnalysis<AliasAnalysis>().alias(V1, V2);
+  return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
 }