summaryrefslogtreecommitdiffstats
path: root/llvm/lib/Analysis/DataStructure
diff options
context:
space:
mode:
Diffstat (limited to 'llvm/lib/Analysis/DataStructure')
-rw-r--r--llvm/lib/Analysis/DataStructure/IPModRef.cpp447
-rw-r--r--llvm/lib/Analysis/DataStructure/MemoryDepAnalysis.cpp500
2 files changed, 947 insertions, 0 deletions
diff --git a/llvm/lib/Analysis/DataStructure/IPModRef.cpp b/llvm/lib/Analysis/DataStructure/IPModRef.cpp
new file mode 100644
index 00000000000..5e3652765ba
--- /dev/null
+++ b/llvm/lib/Analysis/DataStructure/IPModRef.cpp
@@ -0,0 +1,447 @@
+//===- IPModRef.cpp - Compute IP Mod/Ref information ------------*- C++ -*-===//
+//
+// 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.
+//
+//===----------------------------------------------------------------------===//
+//
+// See high-level comments in include/llvm/Analysis/IPModRef.h
+//
+//===----------------------------------------------------------------------===//
+
+#include "llvm/Analysis/IPModRef.h"
+#include "llvm/Analysis/DataStructure.h"
+#include "llvm/Analysis/DSGraph.h"
+#include "llvm/Module.h"
+#include "llvm/Function.h"
+#include "llvm/iMemory.h"
+#include "llvm/iOther.h"
+#include "Support/Statistic.h"
+#include "Support/STLExtras.h"
+#include "Support/StringExtras.h"
+#include <vector>
+
+namespace llvm {
+
+//----------------------------------------------------------------------------
+// Private constants and data
+//----------------------------------------------------------------------------
+
+static RegisterAnalysis<IPModRef>
+Z("ipmodref", "Interprocedural mod/ref analysis");
+
+
+//----------------------------------------------------------------------------
+// class ModRefInfo
+//----------------------------------------------------------------------------
+
+void ModRefInfo::print(std::ostream &O,
+ const std::string& sprefix) const
+{
+ O << sprefix << "Modified nodes = " << modNodeSet;
+ O << sprefix << "Referenced nodes = " << refNodeSet;
+}
+
+void ModRefInfo::dump() const
+{
+ print(std::cerr);
+}
+
+//----------------------------------------------------------------------------
+// class FunctionModRefInfo
+//----------------------------------------------------------------------------
+
+
+// This constructor computes a node numbering for the TD graph.
+//
+FunctionModRefInfo::FunctionModRefInfo(const Function& func,
+ IPModRef& ipmro,
+ DSGraph* tdgClone)
+ : F(func), IPModRefObj(ipmro),
+ funcTDGraph(tdgClone),
+ funcModRefInfo(tdgClone->getGraphSize())
+{
+ unsigned i = 0;
+ for (DSGraph::node_iterator NI = funcTDGraph->node_begin(),
+ E = funcTDGraph->node_end(); NI != E; ++NI)
+ NodeIds[*NI] = i++;
+}
+
+
+FunctionModRefInfo::~FunctionModRefInfo()
+{
+ for(std::map<const Instruction*, ModRefInfo*>::iterator
+ I=callSiteModRefInfo.begin(), E=callSiteModRefInfo.end(); I != E; ++I)
+ delete(I->second);
+
+ // Empty map just to make problems easier to track down
+ callSiteModRefInfo.clear();
+
+ delete funcTDGraph;
+}
+
+unsigned FunctionModRefInfo::getNodeId(const Value* value) const {
+ return getNodeId(funcTDGraph->getNodeForValue(const_cast<Value*>(value))
+ .getNode());
+}
+
+
+
+// Compute Mod/Ref bit vectors for the entire function.
+// These are simply copies of the Read/Write flags from the nodes of
+// the top-down DS graph.
+//
+void FunctionModRefInfo::computeModRef(const Function &func)
+{
+ // Mark all nodes in the graph that are marked MOD as being mod
+ // and all those marked REF as being ref.
+ unsigned i = 0;
+ for (DSGraph::node_iterator NI = funcTDGraph->node_begin(),
+ E = funcTDGraph->node_end(); NI != E; ++NI, ++i) {
+ if ((*NI)->isModified()) funcModRefInfo.setNodeIsMod(i);
+ if ((*NI)->isRead()) funcModRefInfo.setNodeIsRef(i);
+ }
+
+ // Compute the Mod/Ref info for all call sites within the function.
+ // The call sites are recorded in the TD graph.
+ const std::vector<DSCallSite>& callSites = funcTDGraph->getFunctionCalls();
+ for (unsigned i = 0, N = callSites.size(); i < N; ++i)
+ computeModRef(callSites[i].getCallSite());
+}
+
+
+// ResolveCallSiteModRefInfo - This method performs the following actions:
+//
+// 1. It clones the top-down graph for the current function
+// 2. It clears all of the mod/ref bits in the cloned graph
+// 3. It then merges the bottom-up graph(s) for the specified call-site into
+// the clone (bringing new mod/ref bits).
+// 4. It returns the clone, and a mapping of nodes from the original TDGraph to
+// the cloned graph with Mod/Ref info for the callsite.
+//
+// NOTE: Because this clones a dsgraph and returns it, the caller is responsible
+// for deleting the returned graph!
+// NOTE: This method may return a null pointer if it is unable to determine the
+// requested information (because the call site calls an external
+// function or we cannot determine the complete set of functions invoked).
+//
+DSGraph* FunctionModRefInfo::ResolveCallSiteModRefInfo(CallSite CS,
+ hash_map<const DSNode*, DSNodeHandle> &NodeMap)
+{
+ // Step #0: Quick check if we are going to fail anyway: avoid
+ // all the graph cloning and map copying in steps #1 and #2.
+ //
+ if (const Function *F = CS.getCalledFunction()) {
+ if (F->isExternal())
+ return 0; // We cannot compute Mod/Ref info for this callsite...
+ } else {
+ // Eventually, should check here if any callee is external.
+ // For now we are not handling this case anyway.
+ std::cerr << "IP Mod/Ref indirect call not implemented yet: "
+ << "Being conservative\n";
+ return 0; // We cannot compute Mod/Ref info for this callsite...
+ }
+
+ // Step #1: Clone the top-down graph...
+ DSGraph *Result = new DSGraph(*funcTDGraph, NodeMap);
+
+ // Step #2: Clear Mod/Ref information...
+ Result->maskNodeTypes(~(DSNode::Modified | DSNode::Read));
+
+ // Step #3: clone the bottom up graphs for the callees into the caller graph
+ if (Function *F = CS.getCalledFunction())
+ {
+ assert(!F->isExternal());
+
+ // Build up a DSCallSite for our invocation point here...
+
+ // If the call returns a value, make sure to merge the nodes...
+ DSNodeHandle RetVal;
+ if (DS::isPointerType(CS.getInstruction()->getType()))
+ RetVal = Result->getNodeForValue(CS.getInstruction());
+
+ // Populate the arguments list...
+ std::vector<DSNodeHandle> Args;
+ for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
+ I != E; ++I)
+ if (DS::isPointerType((*I)->getType()))
+ Args.push_back(Result->getNodeForValue(*I));
+
+ // Build the call site...
+ DSCallSite NCS(CS, RetVal, F, Args);
+
+ // Perform the merging now of the graph for the callee, which will
+ // come with mod/ref bits set...
+ Result->mergeInGraph(NCS, *F, IPModRefObj.getBUDSGraph(*F),
+ DSGraph::StripAllocaBit
+ | DSGraph::DontCloneCallNodes
+ | DSGraph::DontCloneAuxCallNodes);
+ }
+ else
+ assert(0 && "See error message");
+
+ // Remove dead nodes aggressively to match the caller's original graph.
+ Result->removeDeadNodes(DSGraph::KeepUnreachableGlobals);
+
+ // Step #4: Return the clone + the mapping (by ref)
+ return Result;
+}
+
+// Compute Mod/Ref bit vectors for a single call site.
+// These are copies of the Read/Write flags from the nodes of
+// the graph produced by clearing all flags in the caller's TD graph
+// and then inlining the callee's BU graph into the caller's TD graph.
+//
+void
+FunctionModRefInfo::computeModRef(CallSite CS)
+{
+ // Allocate the mod/ref info for the call site. Bits automatically cleared.
+ ModRefInfo* callModRefInfo = new ModRefInfo(funcTDGraph->getGraphSize());
+ callSiteModRefInfo[CS.getInstruction()] = callModRefInfo;
+
+ // Get a copy of the graph for the callee with the callee inlined
+ hash_map<const DSNode*, DSNodeHandle> NodeMap;
+ DSGraph* csgp = ResolveCallSiteModRefInfo(CS, NodeMap);
+ if (!csgp)
+ { // Callee's side effects are unknown: mark all nodes Mod and Ref.
+ // Eventually this should only mark nodes visible to the callee, i.e.,
+ // exclude stack variables not reachable from any outgoing argument
+ // or any global.
+ callModRefInfo->getModSet().set();
+ callModRefInfo->getRefSet().set();
+ return;
+ }
+
+ // For all nodes in the graph, extract the mod/ref information
+ for (DSGraph::node_iterator NI = funcTDGraph->node_begin(),
+ E = funcTDGraph->node_end(); NI != E; ++NI) {
+ DSNode* csgNode = NodeMap[*NI].getNode();
+ assert(csgNode && "Inlined and original graphs do not correspond!");
+ if (csgNode->isModified())
+ callModRefInfo->setNodeIsMod(getNodeId(*NI));
+ if (csgNode->isRead())
+ callModRefInfo->setNodeIsRef(getNodeId(*NI));
+ }
+
+ // Drop nodemap before we delete the graph...
+ NodeMap.clear();
+ delete csgp;
+}
+
+
+class DSGraphPrintHelper {
+ const DSGraph& tdGraph;
+ std::vector<std::vector<const Value*> > knownValues; // identifiable objects
+
+public:
+ /*ctor*/ DSGraphPrintHelper(const FunctionModRefInfo& fmrInfo)
+ : tdGraph(fmrInfo.getFuncGraph())
+ {
+ knownValues.resize(tdGraph.getGraphSize());
+
+ // For every identifiable value, save Value pointer in knownValues[i]
+ for (hash_map<Value*, DSNodeHandle>::const_iterator
+ I = tdGraph.getScalarMap().begin(),
+ E = tdGraph.getScalarMap().end(); I != E; ++I)
+ if (isa<GlobalValue>(I->first) ||
+ isa<Argument>(I->first) ||
+ isa<LoadInst>(I->first) ||
+ isa<AllocaInst>(I->first) ||
+ isa<MallocInst>(I->first))
+ {
+ unsigned nodeId = fmrInfo.getNodeId(I->second.getNode());
+ knownValues[nodeId].push_back(I->first);
+ }
+ }
+
+ void printValuesInBitVec(std::ostream &O, const BitSetVector& bv) const
+ {
+ assert(bv.size() == knownValues.size());
+
+ if (bv.none())
+ { // No bits are set: just say so and return
+ O << "\tNONE.\n";
+ return;
+ }
+
+ if (bv.all())
+ { // All bits are set: just say so and return
+ O << "\tALL GRAPH NODES.\n";
+ return;
+ }
+
+ for (unsigned i=0, N=bv.size(); i < N; ++i)
+ if (bv.test(i))
+ {
+ O << "\tNode# " << i << " : ";
+ if (! knownValues[i].empty())
+ for (unsigned j=0, NV=knownValues[i].size(); j < NV; j++)
+ {
+ const Value* V = knownValues[i][j];
+
+ if (isa<GlobalValue>(V)) O << "(Global) ";
+ else if (isa<Argument>(V)) O << "(Target of FormalParm) ";
+ else if (isa<LoadInst>(V)) O << "(Target of LoadInst ) ";
+ else if (isa<AllocaInst>(V)) O << "(Target of AllocaInst) ";
+ else if (isa<MallocInst>(V)) O << "(Target of MallocInst) ";
+
+ if (V->hasName()) O << V->getName();
+ else if (isa<Instruction>(V)) O << *V;
+ else O << "(Value*) 0x" << (void*) V;
+
+ O << std::string((j < NV-1)? "; " : "\n");
+ }
+#if 0
+ else
+ tdGraph.getNodes()[i]->print(O, /*graph*/ NULL);
+#endif
+ }
+ }
+};
+
+
+// Print the results of the pass.
+// Currently this just prints bit-vectors and is not very readable.
+//
+void FunctionModRefInfo::print(std::ostream &O) const
+{
+ DSGraphPrintHelper DPH(*this);
+
+ O << "========== Mod/ref information for function "
+ << F.getName() << "========== \n\n";
+
+ // First: Print Globals and Locals modified anywhere in the function.
+ //
+ O << " -----Mod/Ref in the body of function " << F.getName()<< ":\n";
+
+ O << " --Objects modified in the function body:\n";
+ DPH.printValuesInBitVec(O, funcModRefInfo.getModSet());
+
+ O << " --Objects referenced in the function body:\n";
+ DPH.printValuesInBitVec(O, funcModRefInfo.getRefSet());
+
+ O << " --Mod and Ref vectors for the nodes listed above:\n";
+ funcModRefInfo.print(O, "\t");
+
+ O << "\n";
+
+ // Second: Print Globals and Locals modified at each call site in function
+ //
+ for (std::map<const Instruction *, ModRefInfo*>::const_iterator
+ CI = callSiteModRefInfo.begin(), CE = callSiteModRefInfo.end();
+ CI != CE; ++CI)
+ {
+ O << " ----Mod/Ref information for call site\n" << CI->first;
+
+ O << " --Objects modified at call site:\n";
+ DPH.printValuesInBitVec(O, CI->second->getModSet());
+
+ O << " --Objects referenced at call site:\n";
+ DPH.printValuesInBitVec(O, CI->second->getRefSet());
+
+ O << " --Mod and Ref vectors for the nodes listed above:\n";
+ CI->second->print(O, "\t");
+
+ O << "\n";
+ }
+
+ O << "\n";
+}
+
+void FunctionModRefInfo::dump() const
+{
+ print(std::cerr);
+}
+
+
+//----------------------------------------------------------------------------
+// class IPModRef: An interprocedural pass that computes IP Mod/Ref info.
+//----------------------------------------------------------------------------
+
+// Free the FunctionModRefInfo objects cached in funcToModRefInfoMap.
+//
+void IPModRef::releaseMemory()
+{
+ for(std::map<const Function*, FunctionModRefInfo*>::iterator
+ I=funcToModRefInfoMap.begin(), E=funcToModRefInfoMap.end(); I != E; ++I)
+ delete(I->second);
+
+ // Clear map so memory is not re-released if we are called again
+ funcToModRefInfoMap.clear();
+}
+
+// Run the "interprocedural" pass on each function. This needs to do
+// NO real interprocedural work because all that has been done the
+// data structure analysis.
+//
+bool IPModRef::run(Module &theModule)
+{
+ M = &theModule;
+
+ for (Module::const_iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI)
+ if (! FI->isExternal())
+ getFuncInfo(*FI, /*computeIfMissing*/ true);
+ return true;
+}
+
+
+FunctionModRefInfo& IPModRef::getFuncInfo(const Function& func,
+ bool computeIfMissing)
+{
+ FunctionModRefInfo*& funcInfo = funcToModRefInfoMap[&func];
+ assert (funcInfo != NULL || computeIfMissing);
+ if (funcInfo == NULL)
+ { // Create a new FunctionModRefInfo object.
+ // Clone the top-down graph and remove any dead nodes first, because
+ // otherwise original and merged graphs will not match.
+ // The memory for this graph clone will be freed by FunctionModRefInfo.
+ DSGraph* funcTDGraph =
+ new DSGraph(getAnalysis<TDDataStructures>().getDSGraph(func));
+ funcTDGraph->removeDeadNodes(DSGraph::KeepUnreachableGlobals);
+
+ funcInfo = new FunctionModRefInfo(func, *this, funcTDGraph); //auto-insert
+ funcInfo->computeModRef(func); // computes the mod/ref info
+ }
+ return *funcInfo;
+}
+
+/// getBUDSGraph - This method returns the BU data structure graph for F through
+/// the use of the BUDataStructures object.
+///
+const DSGraph &IPModRef::getBUDSGraph(const Function &F) {
+ return getAnalysis<BUDataStructures>().getDSGraph(F);
+}
+
+
+// getAnalysisUsage - This pass requires top-down data structure graphs.
+// It modifies nothing.
+//
+void IPModRef::getAnalysisUsage(AnalysisUsage &AU) const {
+ AU.setPreservesAll();
+ AU.addRequired<LocalDataStructures>();
+ AU.addRequired<BUDataStructures>();
+ AU.addRequired<TDDataStructures>();
+}
+
+
+void IPModRef::print(std::ostream &O) const
+{
+ O << "\nRESULTS OF INTERPROCEDURAL MOD/REF ANALYSIS:\n\n";
+
+ for (std::map<const Function*, FunctionModRefInfo*>::const_iterator
+ mapI = funcToModRefInfoMap.begin(), mapE = funcToModRefInfoMap.end();
+ mapI != mapE; ++mapI)
+ mapI->second->print(O);
+
+ O << "\n";
+}
+
+
+void IPModRef::dump() const
+{
+ print(std::cerr);
+}
+
+} // End llvm namespace
diff --git a/llvm/lib/Analysis/DataStructure/MemoryDepAnalysis.cpp b/llvm/lib/Analysis/DataStructure/MemoryDepAnalysis.cpp
new file mode 100644
index 00000000000..97bc9816031
--- /dev/null
+++ b/llvm/lib/Analysis/DataStructure/MemoryDepAnalysis.cpp
@@ -0,0 +1,500 @@
+//===- MemoryDepAnalysis.cpp - Compute dep graph for memory ops -----------===//
+//
+// 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 implements a pass (MemoryDepAnalysis) that computes memory-based
+// data dependences between instructions for each function in a module.
+// Memory-based dependences occur due to load and store operations, but
+// also the side-effects of call instructions.
+//
+// The result of this pass is a DependenceGraph for each function
+// representing the memory-based data dependences between instructions.
+//
+//===----------------------------------------------------------------------===//
+
+#include "llvm/Analysis/MemoryDepAnalysis.h"
+#include "llvm/Module.h"
+#include "llvm/iMemory.h"
+#include "llvm/iOther.h"
+#include "llvm/Analysis/IPModRef.h"
+#include "llvm/Analysis/DataStructure.h"
+#include "llvm/Analysis/DSGraph.h"
+#include "llvm/Support/InstVisitor.h"
+#include "llvm/Support/CFG.h"
+#include "Support/SCCIterator.h"
+#include "Support/Statistic.h"
+#include "Support/STLExtras.h"
+#include "Support/hash_map"
+#include "Support/hash_set"
+
+namespace llvm {
+
+///--------------------------------------------------------------------------
+/// struct ModRefTable:
+///
+/// A data structure that tracks ModRefInfo for instructions:
+/// -- modRefMap is a map of Instruction* -> ModRefInfo for the instr.
+/// -- definers is a vector of instructions that define any node
+/// -- users is a vector of instructions that reference any node
+/// -- numUsersBeforeDef is a vector indicating that the number of users
+/// seen before definers[i] is numUsersBeforeDef[i].
+///
+/// numUsersBeforeDef[] effectively tells us the exact interleaving of
+/// definers and users within the ModRefTable.
+/// This is only maintained when constructing the table for one SCC, and
+/// not copied over from one table to another since it is no longer useful.
+///--------------------------------------------------------------------------
+
+struct ModRefTable {
+ typedef hash_map<Instruction*, ModRefInfo> ModRefMap;
+ typedef ModRefMap::const_iterator const_map_iterator;
+ typedef ModRefMap:: iterator map_iterator;
+ typedef std::vector<Instruction*>::const_iterator const_ref_iterator;
+ typedef std::vector<Instruction*>:: iterator ref_iterator;
+
+ ModRefMap modRefMap;
+ std::vector<Instruction*> definers;
+ std::vector<Instruction*> users;
+ std::vector<unsigned> numUsersBeforeDef;
+
+ // Iterators to enumerate all the defining instructions
+ const_ref_iterator defsBegin() const { return definers.begin(); }
+ ref_iterator defsBegin() { return definers.begin(); }
+ const_ref_iterator defsEnd() const { return definers.end(); }
+ ref_iterator defsEnd() { return definers.end(); }
+
+ // Iterators to enumerate all the user instructions
+ const_ref_iterator usersBegin() const { return users.begin(); }
+ ref_iterator usersBegin() { return users.begin(); }
+ const_ref_iterator usersEnd() const { return users.end(); }
+ ref_iterator usersEnd() { return users.end(); }
+
+ // Iterator identifying the last user that was seen *before* a
+ // specified def. In particular, all users in the half-closed range
+ // [ usersBegin(), usersBeforeDef_End(defPtr) )
+ // were seen *before* the specified def. All users in the half-closed range
+ // [ usersBeforeDef_End(defPtr), usersEnd() )
+ // were seen *after* the specified def.
+ //
+ ref_iterator usersBeforeDef_End(const_ref_iterator defPtr) {
+ unsigned defIndex = (unsigned) (defPtr - defsBegin());
+ assert(defIndex < numUsersBeforeDef.size());
+ assert(usersBegin() + numUsersBeforeDef[defIndex] <= usersEnd());
+ return usersBegin() + numUsersBeforeDef[defIndex];
+ }
+ const_ref_iterator usersBeforeDef_End(const_ref_iterator defPtr) const {
+ return const_cast<ModRefTable*>(this)->usersBeforeDef_End(defPtr);
+ }
+
+ //
+ // Modifier methods
+ //
+ void AddDef(Instruction* D) {
+ definers.push_back(D);
+ numUsersBeforeDef.push_back(users.size());
+ }
+ void AddUse(Instruction* U) {
+ users.push_back(U);
+ }
+ void Insert(const ModRefTable& fromTable) {
+ modRefMap.insert(fromTable.modRefMap.begin(), fromTable.modRefMap.end());
+ definers.insert(definers.end(),
+ fromTable.definers.begin(), fromTable.definers.end());
+ users.insert(users.end(),
+ fromTable.users.begin(), fromTable.users.end());
+ numUsersBeforeDef.clear(); /* fromTable.numUsersBeforeDef is ignored */
+ }
+};
+
+
+///--------------------------------------------------------------------------
+/// class ModRefInfoBuilder:
+///
+/// A simple InstVisitor<> class that retrieves the Mod/Ref info for
+/// Load/Store/Call instructions and inserts this information in
+/// a ModRefTable. It also records all instructions that Mod any node
+/// and all that use any node.
+///--------------------------------------------------------------------------
+
+class ModRefInfoBuilder : public InstVisitor<ModRefInfoBuilder> {
+ const DSGraph& funcGraph;
+ const FunctionModRefInfo& funcModRef;
+ struct ModRefTable& modRefTable;
+
+ ModRefInfoBuilder(); // DO NOT IMPLEMENT
+ ModRefInfoBuilder(const ModRefInfoBuilder&); // DO NOT IMPLEMENT
+ void operator=(const ModRefInfoBuilder&); // DO NOT IMPLEMENT
+
+public:
+ ModRefInfoBuilder(const DSGraph& _funcGraph,
+ const FunctionModRefInfo& _funcModRef,
+ ModRefTable& _modRefTable)
+ : funcGraph(_funcGraph), funcModRef(_funcModRef), modRefTable(_modRefTable)
+ {
+ }
+
+ // At a call instruction, retrieve the ModRefInfo using IPModRef results.
+ // Add the call to the defs list if it modifies any nodes and to the uses
+ // list if it refs any nodes.
+ //
+ void visitCallInst(CallInst& callInst) {
+ ModRefInfo safeModRef(funcGraph.getGraphSize());
+ const ModRefInfo* callModRef = funcModRef.getModRefInfo(callInst);
+ if (callModRef == NULL) {
+ // call to external/unknown function: mark all nodes as Mod and Ref
+ safeModRef.getModSet().set();
+ safeModRef.getRefSet().set();
+ callModRef = &safeModRef;
+ }
+
+ modRefTable.modRefMap.insert(std::make_pair(&callInst,
+ ModRefInfo(*callModRef)));
+ if (callModRef->getModSet().any())
+ modRefTable.AddDef(&callInst);
+ if (callModRef->getRefSet().any())
+ modRefTable.AddUse(&callInst);
+ }
+
+ // At a store instruction, add to the mod set the single node pointed to
+ // by the pointer argument of the store. Interestingly, if there is no
+ // such node, that would be a null pointer reference!
+ void visitStoreInst(StoreInst& storeInst) {
+ const DSNodeHandle& ptrNode =
+ funcGraph.getNodeForValue(storeInst.getPointerOperand());
+ if (const DSNode* target = ptrNode.getNode()) {
+ unsigned nodeId = funcModRef.getNodeId(target);
+ ModRefInfo& minfo =
+ modRefTable.modRefMap.insert(
+ std::make_pair(&storeInst,
+ ModRefInfo(funcGraph.getGraphSize()))).first->second;
+ minfo.setNodeIsMod(nodeId);
+ modRefTable.AddDef(&storeInst);
+ } else
+ std::cerr << "Warning: Uninitialized pointer reference!\n";
+ }
+
+ // At a load instruction, add to the ref set the single node pointed to
+ // by the pointer argument of the load. Interestingly, if there is no
+ // such node, that would be a null pointer reference!
+ void visitLoadInst(LoadInst& loadInst) {
+ const DSNodeHandle& ptrNode =
+ funcGraph.getNodeForValue(loadInst.getPointerOperand());
+ if (const DSNode* target = ptrNode.getNode()) {
+ unsigned nodeId = funcModRef.getNodeId(target);
+ ModRefInfo& minfo =
+ modRefTable.modRefMap.insert(
+ std::make_pair(&loadInst,
+ ModRefInfo(funcGraph.getGraphSize()))).first->second;
+ minfo.setNodeIsRef(nodeId);
+ modRefTable.AddUse(&loadInst);
+ } else
+ std::cerr << "Warning: Uninitialized pointer reference!\n";
+ }
+};
+
+
+//----------------------------------------------------------------------------
+// class MemoryDepAnalysis: A dep. graph for load/store/call instructions
+//----------------------------------------------------------------------------
+
+
+/// getAnalysisUsage - This does not modify anything. It uses the Top-Down DS
+/// Graph and IPModRef.
+///
+void MemoryDepAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
+ AU.setPreservesAll();
+ AU.addRequired<TDDataStructures>();
+ AU.addRequired<IPModRef>();
+}
+
+
+/// Basic dependence gathering algorithm, using scc_iterator on CFG:
+///
+/// for every SCC S in the CFG in PostOrder on the SCC DAG
+/// {
+/// for every basic block BB in S in *postorder*
+/// for every instruction I in BB in reverse
+/// Add (I, ModRef[I]) to ModRefCurrent
+/// if (Mod[I] != NULL)
+/// Add I to DefSetCurrent: { I \in S : Mod[I] != NULL }
+/// if (Ref[I] != NULL)
+/// Add I to UseSetCurrent: { I : Ref[I] != NULL }
+///
+/// for every def D in DefSetCurrent
+///
+/// // NOTE: D comes after itself iff S contains a loop
+/// if (HasLoop(S) && D & D)
+/// Add output-dep: D -> D2
+///
+/// for every def D2 *after* D in DefSetCurrent
+/// // NOTE: D2 comes before D in execution order
+/// if (D & D2)
+/// Add output-dep: D2 -> D
+/// if (HasLoop(S))
+/// Add output-dep: D -> D2
+///
+/// for every use U in UseSetCurrent that was seen *before* D
+/// // NOTE: U comes after D in execution order
+/// if (U & D)
+/// if (U != D || HasLoop(S))
+/// Add true-dep: D -> U
+/// if (HasLoop(S))
+/// Add anti-dep: U -> D
+///
+/// for every use U in UseSetCurrent that was seen *after* D
+/// // NOTE: U comes before D in execution order
+/// if (U & D)
+/// if (U != D || HasLoop(S))
+/// Add anti-dep: U -> D
+/// if (HasLoop(S))
+/// Add true-dep: D -> U
+///
+/// for every def Dnext in DefSetAfter
+/// // NOTE: Dnext comes after D in execution order
+/// if (Dnext & D)
+/// Add output-dep: D -> Dnext
+///
+/// for every use Unext in UseSetAfter
+/// // NOTE: Unext comes after D in execution order
+/// if (Unext & D)
+/// Add true-dep: D -> Unext
+///
+/// for every use U in UseSetCurrent
+/// for every def Dnext in DefSetAfter
+/// // NOTE: Dnext comes after U in execution order
+/// if (Dnext & D)
+/// Add anti-dep: U -> Dnext
+///
+/// Add ModRefCurrent to ModRefAfter: { (I, ModRef[I] ) }
+/// Add DefSetCurrent to DefSetAfter: { I : Mod[I] != NULL }
+/// Add UseSetCurrent to UseSetAfter: { I : Ref[I] != NULL }
+/// }
+///
+///
+void MemoryDepAnalysis::ProcessSCC(std::vector<BasicBlock*> &S,
+ ModRefTable& ModRefAfter, bool hasLoop) {
+ ModRefTable ModRefCurrent;
+ ModRefTable::ModRefMap& mapCurrent = ModRefCurrent.modRefMap;
+ ModRefTable::ModRefMap& mapAfter = ModRefAfter.modRefMap;
+
+ // Builder class fills out a ModRefTable one instruction at a time.
+ // To use it, we just invoke it's visit function for each basic block:
+ //
+ // for each basic block BB in the SCC in *postorder*
+ // for each instruction I in BB in *reverse*
+ // ModRefInfoBuilder::visit(I)
+ // : Add (I, ModRef[I]) to ModRefCurrent.modRefMap
+ // : Add I to ModRefCurrent.definers if it defines any node
+ // : Add I to ModRefCurrent.users if it uses any node
+ //
+ ModRefInfoBuilder builder(*funcGraph, *funcModRef, ModRefCurrent);
+ for (std::vector<BasicBlock*>::iterator BI = S.begin(), BE = S.end();
+ BI != BE; ++BI)
+ // Note: BBs in the SCC<> created by scc_iterator are in postorder.
+ for (BasicBlock::reverse_iterator II=(*BI)->rbegin(), IE=(*BI)->rend();
+ II != IE; ++II)
+ builder.visit(*II);
+
+ /// for every def D in DefSetCurrent
+ ///
+ for (ModRefTable::ref_iterator II=ModRefCurrent.defsBegin(),
+ IE=ModRefCurrent.defsEnd(); II != IE; ++II)
+ {
+ /// // NOTE: D comes after itself iff S contains a loop
+ /// if (HasLoop(S))
+ /// Add output-dep: D -> D2
+ if (hasLoop)
+ funcDepGraph->AddSimpleDependence(**II, **II, OutputDependence);
+
+ /// for every def D2 *after* D in DefSetCurrent
+ /// // NOTE: D2 comes before D in execution order
+ /// if (D2 & D)
+ /// Add output-dep: D2 -> D
+ /// if (HasLoop(S))
+ /// Add output-dep: D -> D2
+ for (ModRefTable::ref_iterator JI=II+1; JI != IE; ++JI)
+ if (!Disjoint(mapCurrent.find(*II)->second.getModSet(),
+ mapCurrent.find(*JI)->second.getModSet()))
+ {
+ funcDepGraph->AddSimpleDependence(**JI, **II, OutputDependence);
+ if (hasLoop)
+ funcDepGraph->AddSimpleDependence(**II, **JI, OutputDependence);
+ }
+
+ /// for every use U in UseSetCurrent that was seen *before* D
+ /// // NOTE: U comes after D in execution order
+ /// if (U & D)
+ /// if (U != D || HasLoop(S))
+ /// Add true-dep: U -> D
+ /// if (HasLoop(S))
+ /// Add anti-dep: D -> U
+ ModRefTable::ref_iterator JI=ModRefCurrent.usersBegin();
+ ModRefTable::ref_iterator JE = ModRefCurrent.usersBeforeDef_End(II);
+ for ( ; JI != JE; ++JI)
+ if (!Disjoint(mapCurrent.find(*II)->second.getModSet(),
+ mapCurrent.find(*JI)->second.getRefSet()))
+ {
+ if (*II != *JI || hasLoop)
+ funcDepGraph->AddSimpleDependence(**II, **JI, TrueDependence);
+ if (hasLoop)
+ funcDepGraph->AddSimpleDependence(**JI, **II, AntiDependence);
+ }
+
+ /// for every use U in UseSetCurrent that was seen *after* D
+ /// // NOTE: U comes before D in execution order
+ /// if (U & D)
+ /// if (U != D || HasLoop(S))
+ /// Add anti-dep: U -> D
+ /// if (HasLoop(S))
+ /// Add true-dep: D -> U
+ for (/*continue JI*/ JE = ModRefCurrent.usersEnd(); JI != JE; ++JI)
+ if (!Disjoint(mapCurrent.find(*II)->second.getModSet(),
+ mapCurrent.find(*JI)->second.getRefSet()))
+ {
+ if (*II != *JI || hasLoop)
+ funcDepGraph->AddSimpleDependence(**JI, **II, AntiDependence);
+ if (hasLoop)
+ funcDepGraph->AddSimpleDependence(**II, **JI, TrueDependence);
+ }
+
+ /// for every def Dnext in DefSetPrev
+ /// // NOTE: Dnext comes after D in execution order
+ /// if (Dnext & D)
+ /// Add output-dep: D -> Dnext
+ for (ModRefTable::ref_iterator JI=ModRefAfter.defsBegin(),
+ JE=ModRefAfter.defsEnd(); JI != JE; ++JI)
+ if (!Disjoint(mapCurrent.find(*II)->second.getModSet(),
+ mapAfter.find(*JI)->second.getModSet()))
+ funcDepGraph->AddSimpleDependence(**II, **JI, OutputDependence);
+
+ /// for every use Unext in UseSetAfter
+ /// // NOTE: Unext comes after D in execution order
+ /// if (Unext & D)
+ /// Add true-dep: D -> Unext
+ for (ModRefTable::ref_iterator JI=ModRefAfter.usersBegin(),
+ JE=ModRefAfter.usersEnd(); JI != JE; ++JI)
+ if (!Disjoint(mapCurrent.find(*II)->second.getModSet(),
+ mapAfter.find(*JI)->second.getRefSet()))
+ funcDepGraph->AddSimpleDependence(**II, **JI, TrueDependence);
+ }
+
+ ///
+ /// for every use U in UseSetCurrent
+ /// for every def Dnext in DefSetAfter
+ /// // NOTE: Dnext comes after U in execution order
+ /// if (Dnext & D)
+ /// Add anti-dep: U -> Dnext
+ for (ModRefTable::ref_iterator II=ModRefCurrent.usersBegin(),
+ IE=ModRefCurrent.usersEnd(); II != IE; ++II)
+ for (ModRefTable::ref_iterator JI=ModRefAfter.defsBegin(),
+ JE=ModRefAfter.defsEnd(); JI != JE; ++JI)
+ if (!Disjoint(mapCurrent.find(*II)->second.getRefSet(),
+ mapAfter.find(*JI)->second.getModSet()))
+ funcDepGraph->AddSimpleDependence(**II, **JI, AntiDependence);
+
+ /// Add ModRefCurrent to ModRefAfter: { (I, ModRef[I] ) }
+ /// Add DefSetCurrent to DefSetAfter: { I : Mod[I] != NULL }
+ /// Add UseSetCurrent to UseSetAfter: { I : Ref[I] != NULL }
+ ModRefAfter.Insert(ModRefCurrent);
+}
+
+
+/// Debugging support methods
+///
+void MemoryDepAnalysis::print(std::ostream &O) const
+{
+ // TEMPORARY LOOP
+ for (hash_map<Function*, DependenceGraph*>::const_iterator
+ I = funcMap.begin(), E = funcMap.end(); I != E; ++I)
+ {
+ Function* func = I->first;
+ DependenceGraph* depGraph = I->second;
+
+ O << "\n================================================================\n";
+ O << "DEPENDENCE GRAPH FOR MEMORY OPERATIONS IN FUNCTION " << func->getName();
+ O << "\n================================================================\n\n";
+ depGraph->print(*func, O);
+
+ }
+}
+
+
+///
+/// Run the pass on a function
+///
+bool MemoryDepAnalysis::runOnFunction(Function &F) {
+ assert(!F.isExternal());
+
+ // Get the FunctionModRefInfo holding IPModRef results for this function.
+ // Use the TD graph recorded within the FunctionModRefInfo object, which
+ // may not be the same as the original TD graph computed by DS analysis.
+ //
+ funcModRef = &getAnalysis<IPModRef>().getFunctionModRefInfo(F);
+ funcGraph = &funcModRef->getFuncGraph();
+
+ // TEMPORARY: ptr to depGraph (later just becomes "this").
+ assert(!funcMap.count(&F) && "Analyzing function twice?");
+ funcDepGraph = funcMap[&F] = new DependenceGraph();
+
+ ModRefTable ModRefAfter;
+
+ for (scc_iterator<Function*> I = scc_begin(&F), E = scc_end(&F); I != E; ++I)
+ ProcessSCC(*I, ModRefAfter, I.hasLoop());
+
+ return true;
+}
+
+
+//-------------------------------------------------------------------------
+// TEMPORARY FUNCTIONS TO MAKE THIS A MODULE PASS ---
+// These functions will go away once this class becomes a FunctionPass.
+//
+
+// Driver function to compute dependence graphs for every function.
+// This is temporary and will go away once this is a FunctionPass.
+//
+bool MemoryDepAnalysis::run(Module& M)
+{
+ for (Module::iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI)
+ if (! FI->isExternal())
+ runOnFunction(*FI); // automatically inserts each depGraph into funcMap
+ return true;
+}
+
+// Release all the dependence graphs in the map.
+void MemoryDepAnalysis::releaseMemory()
+{
+ for (hash_map<Function*, DependenceGraph*>::const_iterator
+ I = funcMap.begin(), E = funcMap.end(); I != E; ++I)
+ delete I->second;
+ funcMap.clear();
+
+ // Clear pointers because the pass constructor will not be invoked again.
+ funcDepGraph = NULL;
+ funcGraph = NULL;
+ funcModRef = NULL;
+}
+
+MemoryDepAnalysis::~MemoryDepAnalysis()
+{
+ releaseMemory();
+}
+
+//----END TEMPORARY FUNCTIONS----------------------------------------------
+
+
+void MemoryDepAnalysis::dump() const
+{
+ this->print(std::cerr);
+}
+
+static RegisterAnalysis<MemoryDepAnalysis>
+Z("memdep", "Memory Dependence Analysis");
+
+
+} // End llvm namespace
OpenPOWER on IntegriCloud