1 //===- DataStructure.cpp - Implement the core data structure analysis -----===//
3 // This file implements the core data structure functionality.
5 //===----------------------------------------------------------------------===//
7 #include "llvm/Module.h"
8 #include "llvm/DerivedTypes.h"
9 #include "Support/STLExtras.h"
10 #include "Support/StatisticReporter.h"
11 #include "Support/STLExtras.h"
14 #include "llvm/Analysis/DataStructure.h"
18 AnalysisID LocalDataStructures::ID(AnalysisID::create<LocalDataStructures>());
20 //===----------------------------------------------------------------------===//
21 // DSNode Implementation
22 //===----------------------------------------------------------------------===//
24 DSNode::DSNode(enum NodeTy NT, const Type *T) : Ty(T), NodeType(NT) {
25 // If this node has any fields, allocate them now, but leave them null.
26 switch (T->getPrimitiveID()) {
27 case Type::PointerTyID: Links.resize(1); break;
28 case Type::ArrayTyID: Links.resize(1); break;
29 case Type::StructTyID:
30 Links.resize(cast<StructType>(T)->getNumContainedTypes());
36 // DSNode copy constructor... do not copy over the referrers list!
37 DSNode::DSNode(const DSNode &N)
38 : Ty(N.Ty), Links(N.Links), Globals(N.Globals), NodeType(N.NodeType) {
41 void DSNode::removeReferrer(DSNodeHandle *H) {
42 // Search backwards, because we depopulate the list from the back for
43 // efficiency (because it's a vector).
44 vector<DSNodeHandle*>::reverse_iterator I =
45 std::find(Referrers.rbegin(), Referrers.rend(), H);
46 assert(I != Referrers.rend() && "Referrer not pointing to node!");
47 Referrers.erase(I.base()-1);
50 // addGlobal - Add an entry for a global value to the Globals list. This also
51 // marks the node with the 'G' flag if it does not already have it.
53 void DSNode::addGlobal(GlobalValue *GV) {
54 // Keep the list sorted.
55 vector<GlobalValue*>::iterator I =
56 std::lower_bound(Globals.begin(), Globals.end(), GV);
58 if (I == Globals.end() || *I != GV) {
59 assert(GV->getType()->getElementType() == Ty);
60 Globals.insert(I, GV);
61 NodeType |= GlobalNode;
66 // addEdgeTo - Add an edge from the current node to the specified node. This
67 // can cause merging of nodes in the graph.
69 void DSNode::addEdgeTo(unsigned LinkNo, DSNode *N) {
70 assert(LinkNo < Links.size() && "LinkNo out of range!");
71 if (N == 0 || Links[LinkNo] == N) return; // Nothing to do
72 if (Links[LinkNo] == 0) { // No merging to perform
77 // Merge the two nodes...
78 Links[LinkNo]->mergeWith(N);
82 // mergeWith - Merge this node into the specified node, moving all links to and
83 // from the argument node into the current node. The specified node may be a
84 // null pointer (in which case, nothing happens).
86 void DSNode::mergeWith(DSNode *N) {
87 if (N == 0 || N == this) return; // Noop
88 assert(N->Ty == Ty && N->Links.size() == Links.size() &&
89 "Cannot merge nodes of two different types!");
91 // Remove all edges pointing at N, causing them to point to 'this' instead.
92 while (!N->Referrers.empty())
93 *N->Referrers.back() = this;
95 // Make all of the outgoing links of N now be outgoing links of this. This
96 // can cause recursive merging!
98 for (unsigned i = 0, e = Links.size(); i != e; ++i) {
99 addEdgeTo(i, N->Links[i]);
100 N->Links[i] = 0; // Reduce unneccesary edges in graph. N is dead
103 // Merge the node types
104 NodeType |= N->NodeType;
105 N->NodeType = 0; // N is now a dead node.
107 // Merge the globals list...
108 if (!N->Globals.empty()) {
109 // Save the current globals off to the side...
110 vector<GlobalValue*> OldGlobals(Globals);
112 // Resize the globals vector to be big enough to hold both of them...
113 Globals.resize(Globals.size()+N->Globals.size());
115 // Merge the two sorted globals lists together...
116 std::merge(OldGlobals.begin(), OldGlobals.end(),
117 N->Globals.begin(), N->Globals.end(), Globals.begin());
119 // Erase duplicate entries from the globals list...
120 Globals.erase(std::unique(Globals.begin(), Globals.end()), Globals.end());
122 // Delete the globals from the old node...
127 //===----------------------------------------------------------------------===//
128 // DSGraph Implementation
129 //===----------------------------------------------------------------------===//
131 DSGraph::DSGraph(const DSGraph &G) : Func(G.Func) {
132 std::map<const DSNode*, DSNode*> NodeMap; // ignored
133 RetNode = cloneInto(G, ValueMap, NodeMap, false);
136 DSGraph::~DSGraph() {
137 FunctionCalls.clear();
138 OrigFunctionCalls.clear();
143 // Drop all intra-node references, so that assertions don't fail...
144 std::for_each(Nodes.begin(), Nodes.end(),
145 std::mem_fun(&DSNode::dropAllReferences));
148 // Delete all of the nodes themselves...
149 std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
152 // dump - Allow inspection of graph in a debugger.
153 void DSGraph::dump() const { print(std::cerr); }
156 // cloneInto - Clone the specified DSGraph into the current graph, returning the
157 // Return node of the graph. The translated ValueMap for the old function is
158 // filled into the OldValMap member. If StripLocals is set to true, Scalar and
159 // Alloca markers are removed from the graph, as the graph is being cloned into
160 // a calling function's graph.
162 DSNode *DSGraph::cloneInto(const DSGraph &G,
163 std::map<Value*, DSNodeHandle> &OldValMap,
164 std::map<const DSNode*, DSNode*> &OldNodeMap,
167 assert(OldNodeMap.size()==0 && "Return argument OldNodeMap should be empty");
169 OldNodeMap[0] = 0; // Null pointer maps to null
171 unsigned FN = Nodes.size(); // FirstNode...
173 // Duplicate all of the nodes, populating the node map...
174 Nodes.reserve(FN+G.Nodes.size());
175 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
176 DSNode *Old = G.Nodes[i], *New = new DSNode(*Old);
177 Nodes.push_back(New);
178 OldNodeMap[Old] = New;
181 // Rewrite the links in the nodes to point into the current graph now.
182 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
183 for (unsigned j = 0, e = Nodes[i]->getNumLinks(); j != e; ++j)
184 Nodes[i]->setLink(j, OldNodeMap[Nodes[i]->getLink(j)]);
186 // If we are inlining this graph into the called function graph, remove local
189 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
190 Nodes[i]->NodeType &= ~(DSNode::AllocaNode | DSNode::ScalarNode);
192 // Copy the value map...
193 for (std::map<Value*, DSNodeHandle>::const_iterator I = G.ValueMap.begin(),
194 E = G.ValueMap.end(); I != E; ++I)
195 OldValMap[I->first] = OldNodeMap[I->second];
197 // Copy the function calls list...
198 unsigned FC = FunctionCalls.size(); // FirstCall
199 FunctionCalls.reserve(FC+G.FunctionCalls.size());
200 for (unsigned i = 0, e = G.FunctionCalls.size(); i != e; ++i) {
201 FunctionCalls.push_back(std::vector<DSNodeHandle>());
202 FunctionCalls[FC+i].reserve(G.FunctionCalls[i].size());
203 for (unsigned j = 0, e = G.FunctionCalls[i].size(); j != e; ++j)
204 FunctionCalls[FC+i].push_back(OldNodeMap[G.FunctionCalls[i][j]]);
207 // Copy the list of unresolved callers
208 PendingCallers.insert(PendingCallers.end(),
209 G.PendingCallers.begin(), G.PendingCallers.end());
211 // Return the returned node pointer...
212 return OldNodeMap[G.RetNode];
216 // markIncompleteNodes - Mark the specified node as having contents that are not
217 // known with the current analysis we have performed. Because a node makes all
218 // of the nodes it can reach imcomplete if the node itself is incomplete, we
219 // must recursively traverse the data structure graph, marking all reachable
220 // nodes as incomplete.
222 static void markIncompleteNode(DSNode *N) {
223 // Stop recursion if no node, or if node already marked...
224 if (N == 0 || (N->NodeType & DSNode::Incomplete)) return;
226 // Actually mark the node
227 N->NodeType |= DSNode::Incomplete;
229 // Recusively process children...
230 for (unsigned i = 0, e = N->getNumLinks(); i != e; ++i)
231 markIncompleteNode(N->getLink(i));
235 // markIncompleteNodes - Traverse the graph, identifying nodes that may be
236 // modified by other functions that have not been resolved yet. This marks
237 // nodes that are reachable through three sources of "unknownness":
239 // Global Variables, Function Calls, and Incoming Arguments
241 // For any node that may have unknown components (because something outside the
242 // scope of current analysis may have modified it), the 'Incomplete' flag is
243 // added to the NodeType.
245 void DSGraph::markIncompleteNodes() {
246 // Mark any incoming arguments as incomplete...
247 for (Function::aiterator I = Func.abegin(), E = Func.aend(); I != E; ++I)
248 if (isa<PointerType>(I->getType()))
249 markIncompleteNode(ValueMap[I]->getLink(0));
251 // Mark stuff passed into functions calls as being incomplete...
252 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
253 vector<DSNodeHandle> &Args = FunctionCalls[i];
254 // Then the return value is certainly incomplete!
255 markIncompleteNode(Args[0]);
257 // The call does not make the function argument incomplete...
259 // All arguments to the function call are incomplete though!
260 for (unsigned i = 2, e = Args.size(); i != e; ++i)
261 markIncompleteNode(Args[i]);
264 // Mark all of the nodes pointed to by global or cast nodes as incomplete...
265 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
266 if (Nodes[i]->NodeType & (DSNode::GlobalNode | DSNode::CastNode)) {
267 DSNode *N = Nodes[i];
268 for (unsigned i = 0, e = N->getNumLinks(); i != e; ++i)
269 markIncompleteNode(N->getLink(i));
273 // isNodeDead - This method checks to see if a node is dead, and if it isn't, it
274 // checks to see if there are simple transformations that it can do to make it
277 bool DSGraph::isNodeDead(DSNode *N) {
278 // Is it a trivially dead shadow node...
279 if (N->getReferrers().empty() && N->NodeType == 0)
282 // Is it a function node or some other trivially unused global?
283 if ((N->NodeType & ~DSNode::GlobalNode) == 0 &&
284 N->getNumLinks() == 0 &&
285 N->getReferrers().size() == N->getGlobals().size()) {
287 // Remove the globals from the valuemap, so that the referrer count will go
289 while (!N->getGlobals().empty()) {
290 GlobalValue *GV = N->getGlobals().back();
291 N->getGlobals().pop_back();
294 assert(N->getReferrers().empty() && "Referrers should all be gone now!");
302 // removeTriviallyDeadNodes - After the graph has been constructed, this method
303 // removes all unreachable nodes that are created because they got merged with
304 // other nodes in the graph. These nodes will all be trivially unreachable, so
305 // we don't have to perform any non-trivial analysis here.
307 void DSGraph::removeTriviallyDeadNodes() {
308 for (unsigned i = 0; i != Nodes.size(); ++i)
309 if (isNodeDead(Nodes[i])) { // This node is dead!
310 delete Nodes[i]; // Free memory...
311 Nodes.erase(Nodes.begin()+i--); // Remove from node list...
314 // Remove trivially identical function calls
315 unsigned NumFns = FunctionCalls.size();
316 std::sort(FunctionCalls.begin(), FunctionCalls.end());
317 FunctionCalls.erase(std::unique(FunctionCalls.begin(), FunctionCalls.end()),
318 FunctionCalls.end());
320 DEBUG(if (NumFns != FunctionCalls.size())
321 std::cerr << "Merged " << (NumFns-FunctionCalls.size())
322 << " call nodes in " << Func.getName() << "\n";);
326 // markAlive - Simple graph traverser that recursively walks the graph marking
327 // stuff to be alive.
329 static void markAlive(DSNode *N, std::set<DSNode*> &Alive) {
330 if (N == 0 || Alive.count(N)) return;
333 for (unsigned i = 0, e = N->getNumLinks(); i != e; ++i)
334 markAlive(N->getLink(i), Alive);
338 // removeDeadNodes - Use a more powerful reachability analysis to eliminate
339 // subgraphs that are unreachable. This often occurs because the data
340 // structure doesn't "escape" into it's caller, and thus should be eliminated
341 // from the caller's graph entirely. This is only appropriate to use when
344 void DSGraph::removeDeadNodes() {
345 // Reduce the amount of work we have to do...
346 removeTriviallyDeadNodes();
348 // FIXME: Merge nontrivially identical call nodes...
350 // Alive - a set that holds all nodes found to be reachable/alive.
351 std::set<DSNode*> Alive;
353 // Mark all nodes reachable by call nodes as alive...
354 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
355 for (unsigned j = 0, e = FunctionCalls[i].size(); j != e; ++j)
356 markAlive(FunctionCalls[i][j], Alive);
358 for (unsigned i = 0, e = OrigFunctionCalls.size(); i != e; ++i)
359 for (unsigned j = 0, e = OrigFunctionCalls[i].size(); j != e; ++j)
360 markAlive(OrigFunctionCalls[i][j], Alive);
362 // Mark all nodes reachable by scalar, global, or incomplete nodes as
364 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
365 if (Nodes[i]->NodeType & (DSNode::ScalarNode | DSNode::GlobalNode))
366 markAlive(Nodes[i], Alive);
368 // Loop over all unreachable nodes, dropping their references...
369 std::vector<DSNode*> DeadNodes;
370 DeadNodes.reserve(Nodes.size()); // Only one allocation is allowed.
371 for (unsigned i = 0; i != Nodes.size(); ++i)
372 if (!Alive.count(Nodes[i])) {
373 DSNode *N = Nodes[i];
374 Nodes.erase(Nodes.begin()+i--); // Erase node from alive list.
375 DeadNodes.push_back(N); // Add node to our list of dead nodes
376 N->dropAllReferences(); // Drop all outgoing edges
379 // The return value is alive as well...
380 markAlive(RetNode, Alive);
382 // Delete all dead nodes...
383 std::for_each(DeadNodes.begin(), DeadNodes.end(), deleter<DSNode>);
388 // maskNodeTypes - Apply a mask to all of the node types in the graph. This
389 // is useful for clearing out markers like Scalar or Incomplete.
391 void DSGraph::maskNodeTypes(unsigned char Mask) {
392 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
393 Nodes[i]->NodeType &= Mask;
397 //===----------------------------------------------------------------------===//
398 // LocalDataStructures Implementation
399 //===----------------------------------------------------------------------===//
401 // releaseMemory - If the pass pipeline is done with this pass, we can release
402 // our memory... here...
404 void LocalDataStructures::releaseMemory() {
405 for (std::map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
406 E = DSInfo.end(); I != E; ++I)
409 // Empty map so next time memory is released, data structures are not
414 bool LocalDataStructures::run(Module &M) {
415 // Calculate all of the graphs...
416 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
417 if (!I->isExternal())
418 DSInfo.insert(std::make_pair(&*I, new DSGraph(*I)));