Optimization suggested by Matthijs Kooijman.
[oota-llvm.git] / lib / Analysis / IPA / CallGraph.cpp
index e3a60248895251e5f9b69d12fed651a5a705cbd4..1a65179c5aac56972a9a8cb0a42939d9a0c93f95 100644 (file)
 //===- CallGraph.cpp - Build a Module's call graph ------------------------===//
-// 
+//
 //                     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 file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
 //===----------------------------------------------------------------------===//
 //
-//  This file implements the CallGraph class.
+// This file implements the CallGraph class and provides the BasicCallGraph
+// default implementation.
 //
 //===----------------------------------------------------------------------===//
 
 #include "llvm/Analysis/CallGraph.h"
-#include "llvm/Constants.h"     // Remove when ConstantPointerRefs are gone
 #include "llvm/Module.h"
 #include "llvm/Instructions.h"
 #include "llvm/Support/CallSite.h"
-#include "llvm/ADT/STLExtras.h"
-#include <iostream>
+#include "llvm/Support/Compiler.h"
+#include "llvm/Support/Streams.h"
+#include <ostream>
 using namespace llvm;
 
-static RegisterAnalysis<CallGraph> X("callgraph", "Call Graph Construction");
+namespace {
 
-// getNodeFor - Return the node for the specified function or create one if it
-// does not already exist.
+//===----------------------------------------------------------------------===//
+// BasicCallGraph class definition
 //
-CallGraphNode *CallGraph::getNodeFor(Function *F) {
-  CallGraphNode *&CGN = FunctionMap[F];
-  if (CGN) return CGN;
+class VISIBILITY_HIDDEN BasicCallGraph : public CallGraph, public ModulePass {
+  // Root is root of the call graph, or the external node if a 'main' function
+  // couldn't be found.
+  //
+  CallGraphNode *Root;
 
-  assert((!F || F->getParent() == Mod) && "Function not in current module!");
-  return CGN = new CallGraphNode(F);
-}
+  // ExternalCallingNode - This node has edges to all external functions and
+  // those internal functions that have their address taken.
+  CallGraphNode *ExternalCallingNode;
 
-static bool isOnlyADirectCall(Function *F, CallSite CS) {
-  if (!CS.getInstruction()) return false;
-  for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); I != E; ++I)
-    if (*I == F) return false;
-  return true;
-}
+  // CallsExternalNode - This node has edges to it from all functions making
+  // indirect calls or calling an external function.
+  CallGraphNode *CallsExternalNode;
 
-// addToCallGraph - Add a function to the call graph, and link the node to all
-// of the functions that it calls.
-//
-void CallGraph::addToCallGraph(Function *F) {
-  CallGraphNode *Node = getNodeFor(F);
-
-  // If this function has external linkage, anything could call it...
-  if (!F->hasInternalLinkage()) {
-    ExternalCallingNode->addCalledFunction(Node);
-
-    // Found the entry point?
-    if (F->getName() == "main") {
-      if (Root)    // Found multiple external mains?  Don't pick one.
-        Root = ExternalCallingNode;
-      else
-        Root = Node;          // Found a main, keep track of it!
-    }
+public:
+  static char ID; // Class identification, replacement for typeinfo
+  BasicCallGraph() : ModulePass(&ID), Root(0), 
+    ExternalCallingNode(0), CallsExternalNode(0) {}
+
+  // runOnModule - Compute the call graph for the specified module.
+  virtual bool runOnModule(Module &M) {
+    CallGraph::initialize(M);
+    
+    ExternalCallingNode = getOrInsertFunction(0);
+    CallsExternalNode = new CallGraphNode(0);
+    Root = 0;
+  
+    // Add every function to the call graph...
+    for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
+      addToCallGraph(I);
+  
+    // If we didn't find a main function, use the external call graph node
+    if (Root == 0) Root = ExternalCallingNode;
+    
+    return false;
+  }
+
+  virtual void getAnalysisUsage(AnalysisUsage &AU) const {
+    AU.setPreservesAll();
+  }
+
+  void print(std::ostream *o, const Module *M) const {
+    if (o) print(*o, M);
+  }
+
+  virtual void print(std::ostream &o, const Module *M) const {
+    o << "CallGraph Root is: ";
+    if (Function *F = getRoot()->getFunction())
+      o << F->getName() << "\n";
+    else
+      o << "<<null function: 0x" << getRoot() << ">>\n";
+    
+    CallGraph::print(o, M);
+  }
+
+  virtual void releaseMemory() {
+    destroy();
   }
   
-  // If this function is not defined in this translation unit, it could call
-  // anything.
-  if (F->isExternal() && !F->getIntrinsicID())
-    Node->addCalledFunction(CallsExternalNode);
+  /// dump - Print out this call graph.
+  ///
+  inline void dump() const {
+    print(cerr, Mod);
+  }
+
+  CallGraphNode* getExternalCallingNode() const { return ExternalCallingNode; }
+  CallGraphNode* getCallsExternalNode()   const { return CallsExternalNode; }
 
-  // Loop over all of the users of the function... looking for callers...
+  // getRoot - Return the root of the call graph, which is either main, or if
+  // main cannot be found, the external node.
   //
-  bool isUsedExternally = false;
-  for (Value::use_iterator I = F->use_begin(), E = F->use_end(); I != E; ++I) {
-    if (Instruction *Inst = dyn_cast<Instruction>(*I)) {
-      if (isOnlyADirectCall(F, CallSite::get(Inst)))
-        getNodeFor(Inst->getParent()->getParent())->addCalledFunction(Node);
-      else
+  CallGraphNode *getRoot()             { return Root; }
+  const CallGraphNode *getRoot() const { return Root; }
+
+private:
+  //===---------------------------------------------------------------------
+  // Implementation of CallGraph construction
+  //
+
+  // addToCallGraph - Add a function to the call graph, and link the node to all
+  // of the functions that it calls.
+  //
+  void addToCallGraph(Function *F) {
+    CallGraphNode *Node = getOrInsertFunction(F);
+
+    // If this function has external linkage, anything could call it.
+    if (!F->hasInternalLinkage()) {
+      ExternalCallingNode->addCalledFunction(CallSite(), Node);
+
+      // Found the entry point?
+      if (F->getName() == "main") {
+        if (Root)    // Found multiple external mains?  Don't pick one.
+          Root = ExternalCallingNode;
+        else
+          Root = Node;          // Found a main, keep track of it!
+      }
+    }
+
+    // If this function is not defined in this translation unit, it could call
+    // anything.
+    if (F->isDeclaration() && !F->isIntrinsic())
+      Node->addCalledFunction(CallSite(), CallsExternalNode);
+
+    // Loop over all of the users of the function, looking for non-call uses.
+    bool isUsedExternally = false;
+    for (Value::use_iterator I = F->use_begin(), E = F->use_end();
+         I != E && !isUsedExternally; ++I) {
+      if (Instruction *Inst = dyn_cast<Instruction>(*I)) {
+        CallSite CS = CallSite::get(Inst);
+        // Not a call?  Or F being passed as a parameter not as the callee?
+        isUsedExternally = !CS.getInstruction() || I.getOperandNo();
+      } else {                        // User is not a direct call!
         isUsedExternally = true;
-    } else if (GlobalValue *GV = dyn_cast<GlobalValue>(*I)) {
-      for (Value::use_iterator I = GV->use_begin(), E = GV->use_end();
-           I != E; ++I)
-        if (Instruction *Inst = dyn_cast<Instruction>(*I)) {
-          if (isOnlyADirectCall(F, CallSite::get(Inst)))
-            getNodeFor(Inst->getParent()->getParent())->addCalledFunction(Node);
+      }
+    }
+    if (isUsedExternally)
+      ExternalCallingNode->addCalledFunction(CallSite(), Node);
+
+    // Look for calls by this function.
+    for (Function::iterator BB = F->begin(), BBE = F->end(); BB != BBE; ++BB)
+      for (BasicBlock::iterator II = BB->begin(), IE = BB->end();
+           II != IE; ++II) {
+        CallSite CS = CallSite::get(II);
+        if (CS.getInstruction()) {
+          const Function *Callee = CS.getCalledFunction();
+          if (Callee)
+            Node->addCalledFunction(CS, getOrInsertFunction(Callee));
           else
-            isUsedExternally = true;
-        } else {
-          isUsedExternally = true;
+            Node->addCalledFunction(CS, CallsExternalNode);
         }
-    } else {                        // Can't classify the user!
-      isUsedExternally = true;
-    }
+      }
   }
-  if (isUsedExternally)
-    ExternalCallingNode->addCalledFunction(Node);
-
-  // Look for an indirect function call...
-  for (Function::iterator BB = F->begin(), BBE = F->end(); BB != BBE; ++BB)
-    for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE; ++II){
-      CallSite CS = CallSite::get(II);
-      if (CS.getInstruction() && !CS.getCalledFunction())
-        Node->addCalledFunction(CallsExternalNode);
-    }
-}
 
-bool CallGraph::run(Module &M) {
-  destroy();
+  //
+  // destroy - Release memory for the call graph
+  virtual void destroy() {
+    /// CallsExternalNode is not in the function map, delete it explicitly.
+    delete CallsExternalNode;
+    CallsExternalNode = 0;
+    CallGraph::destroy();
+  }
+};
 
-  Mod = &M;
-  ExternalCallingNode = getNodeFor(0);
-  CallsExternalNode = new CallGraphNode(0);
-  Root = 0;
+} //End anonymous namespace
 
-  // Add every function to the call graph...
-  for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
-    addToCallGraph(I);
+static RegisterAnalysisGroup<CallGraph> X("Call Graph");
+static RegisterPass<BasicCallGraph>
+Y("basiccg", "Basic CallGraph Construction", false, true);
+static RegisterAnalysisGroup<CallGraph, true> Z(Y);
 
-  // If we didn't find a main function, use the external call graph node
-  if (Root == 0) Root = ExternalCallingNode;
-  
-  return false;
-}
+char CallGraph::ID = 0;
+char BasicCallGraph::ID = 0;
 
-void CallGraph::destroy() {
-  for (FunctionMapTy::iterator I = FunctionMap.begin(), E = FunctionMap.end();
-       I != E; ++I)
-    delete I->second;
-  FunctionMap.clear();
-  delete CallsExternalNode;
-  CallsExternalNode = 0;
+void CallGraph::initialize(Module &M) {
+  Mod = &M;
 }
 
-void CallGraphNode::print(std::ostream &OS) const {
-  if (Function *F = getFunction())
-    OS << "Call graph node for function: '" << F->getName() <<"'\n";
-  else
-    OS << "Call graph node <<null function: 0x" << this << ">>:\n";
-
-  for (const_iterator I = begin(), E = end(); I != E; ++I)
-    if ((*I)->getFunction())
-      OS << "  Calls function '" << (*I)->getFunction()->getName() << "'\n";
-    else
-      OS << "  Calls external node\n";
-  OS << "\n";
+void CallGraph::destroy() {
+  if (!FunctionMap.empty()) {
+    for (FunctionMapTy::iterator I = FunctionMap.begin(), E = FunctionMap.end();
+        I != E; ++I)
+      delete I->second;
+    FunctionMap.clear();
+  }
 }
 
-void CallGraphNode::dump() const { print(std::cerr); }
-
 void CallGraph::print(std::ostream &OS, const Module *M) const {
-  OS << "CallGraph Root is: ";
-  if (Function *F = getRoot()->getFunction())
-    OS << F->getName() << "\n";
-  else
-    OS << "<<null function: 0x" << getRoot() << ">>\n";
-  
   for (CallGraph::const_iterator I = begin(), E = end(); I != E; ++I)
     I->second->print(OS);
 }
 
 void CallGraph::dump() const {
-  print(std::cerr, 0);
+  print(cerr, 0);
 }
 
-
 //===----------------------------------------------------------------------===//
 // Implementations of public modification methods
 //
@@ -194,27 +236,71 @@ void CallGraph::changeFunction(Function *OldF, Function *NewF) {
   FunctionMap.erase(I);
 }
 
+// getOrInsertFunction - This method is identical to calling operator[], but
+// it will insert a new CallGraphNode for the specified function if one does
+// not already exist.
+CallGraphNode *CallGraph::getOrInsertFunction(const Function *F) {
+  CallGraphNode *&CGN = FunctionMap[F];
+  if (CGN) return CGN;
+  
+  assert((!F || F->getParent() == Mod) && "Function not in current module!");
+  return CGN = new CallGraphNode(const_cast<Function*>(F));
+}
+
+void CallGraphNode::print(std::ostream &OS) const {
+  if (Function *F = getFunction())
+    OS << "Call graph node for function: '" << F->getName() <<"'\n";
+  else
+    OS << "Call graph node <<null function: 0x" << this << ">>:\n";
 
-void CallGraph::stub() {}
+  for (const_iterator I = begin(), E = end(); I != E; ++I)
+    if (I->second->getFunction())
+      OS << "  Calls function '" << I->second->getFunction()->getName() <<"'\n";
+  else
+    OS << "  Calls external node\n";
+  OS << "\n";
+}
+
+void CallGraphNode::dump() const { print(cerr); }
 
-void CallGraphNode::removeCallEdgeTo(CallGraphNode *Callee) {
+/// removeCallEdgeFor - This method removes the edge in the node for the
+/// specified call site.  Note that this method takes linear time, so it
+/// should be used sparingly.
+void CallGraphNode::removeCallEdgeFor(CallSite CS) {
   for (unsigned i = CalledFunctions.size(); ; --i) {
-    assert(i && "Cannot find callee to remove!");
-    if (CalledFunctions[i-1] == Callee) {
+    assert(i && "Cannot find callsite to remove!");
+    if (CalledFunctions[i-1].first == CS) {
       CalledFunctions.erase(CalledFunctions.begin()+i-1);
       return;
     }
   }
 }
 
+
 // removeAnyCallEdgeTo - This method removes any call edges from this node to
 // the specified callee function.  This takes more time to execute than
 // removeCallEdgeTo, so it should not be used unless necessary.
 void CallGraphNode::removeAnyCallEdgeTo(CallGraphNode *Callee) {
-  for (std::vector<CallGraphNode*>::iterator I = CalledFunctions.begin(),
-         E = CalledFunctions.end(); I != E; ++I)
-    if (*I == Callee) {
-      CalledFunctions.erase(I);
-      E = CalledFunctions.end();
+  for (unsigned i = 0, e = CalledFunctions.size(); i != e; ++i)
+    if (CalledFunctions[i].second == Callee) {
+      CalledFunctions[i] = CalledFunctions.back();
+      CalledFunctions.pop_back();
+      --i; --e;
+    }
+}
+
+/// replaceCallSite - Make the edge in the node for Old CallSite be for
+/// New CallSite instead.  Note that this method takes linear time, so it
+/// should be used sparingly.
+void CallGraphNode::replaceCallSite(CallSite Old, CallSite New) {
+  for (unsigned i = CalledFunctions.size(); ; --i) {
+    assert(i && "Cannot find callsite to replace!");
+    if (CalledFunctions[i-1].first == Old) {
+      CalledFunctions[i-1].first = New;
+      return;
     }
+  }
 }
+
+// Enuse that users of CallGraph.h also link with this file
+DEFINING_FILE_FOR(CallGraph)