1 //===- DataStructure.cpp - Implement the core data structure analysis -----===//
3 // This file implements the core data structure functionality.
5 //===----------------------------------------------------------------------===//
7 #include "llvm/Analysis/DSGraph.h"
8 #include "llvm/Function.h"
9 #include "llvm/DerivedTypes.h"
10 #include "Support/STLExtras.h"
11 #include "Support/Statistic.h"
12 #include "llvm/Target/TargetData.h"
19 namespace DataStructureAnalysis {
20 // isPointerType - Return true if this first class type is big enough to hold
23 bool isPointerType(const Type *Ty);
26 using namespace DataStructureAnalysis;
28 //===----------------------------------------------------------------------===//
29 // DSNode Implementation
30 //===----------------------------------------------------------------------===//
32 DSNode::DSNode(enum NodeTy NT, const Type *T) : NodeType(NT) {
33 // If this node is big enough to have pointer fields, add space for them now.
34 if (T != Type::VoidTy && !isa<FunctionType>(T)) // Avoid TargetData assert's
35 LinkIndex.resize(TD.getTypeSize(T), -1);
37 TypeEntries.push_back(std::make_pair(T, 0));
40 // DSNode copy constructor... do not copy over the referrers list!
41 DSNode::DSNode(const DSNode &N)
42 : Links(N.Links), LinkIndex(N.LinkIndex),
43 TypeEntries(N.TypeEntries), Globals(N.Globals), NodeType(N.NodeType) {
46 void DSNode::removeReferrer(DSNodeHandle *H) {
47 // Search backwards, because we depopulate the list from the back for
48 // efficiency (because it's a vector).
49 vector<DSNodeHandle*>::reverse_iterator I =
50 std::find(Referrers.rbegin(), Referrers.rend(), H);
51 assert(I != Referrers.rend() && "Referrer not pointing to node!");
52 Referrers.erase(I.base()-1);
55 // addGlobal - Add an entry for a global value to the Globals list. This also
56 // marks the node with the 'G' flag if it does not already have it.
58 void DSNode::addGlobal(GlobalValue *GV) {
59 // Keep the list sorted.
60 vector<GlobalValue*>::iterator I =
61 std::lower_bound(Globals.begin(), Globals.end(), GV);
63 if (I == Globals.end() || *I != GV) {
64 //assert(GV->getType()->getElementType() == Ty);
65 Globals.insert(I, GV);
66 NodeType |= GlobalNode;
71 // addEdgeTo - Add an edge from the current node to the specified node. This
72 // can cause merging of nodes in the graph.
74 void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
75 assert(Offset < LinkIndex.size() && "Offset out of range!");
76 if (NH.getNode() == 0) return; // Nothing to do
78 if (LinkIndex[Offset] == -1) { // No merging to perform...
79 LinkIndex[Offset] = Links.size(); // Allocate a new link...
84 unsigned Idx = (unsigned)LinkIndex[Offset];
85 if (!Links[Idx].getNode()) { // No merging to perform
90 // Merge the two nodes...
91 Links[Idx].mergeWith(NH);
95 // MergeSortedVectors - Efficiently merge a vector into another vector where
96 // duplicates are not allowed and both are sorted. This assumes that 'T's are
97 // efficiently copyable and have sane comparison semantics.
100 void MergeSortedVectors(vector<T> &Dest, const vector<T> &Src) {
101 // By far, the most common cases will be the simple ones. In these cases,
102 // avoid having to allocate a temporary vector...
104 if (Src.empty()) { // Nothing to merge in...
106 } else if (Dest.empty()) { // Just copy the result in...
108 } else if (Src.size() == 1) { // Insert a single element...
110 typename vector<T>::iterator I =
111 std::lower_bound(Dest.begin(), Dest.end(), V);
112 if (I == Dest.end() || *I != Src[0]) // If not already contained...
113 Dest.insert(I, Src[0]);
114 } else if (Dest.size() == 1) {
115 T Tmp = Dest[0]; // Save value in temporary...
116 Dest = Src; // Copy over list...
117 typename vector<T>::iterator I =
118 std::lower_bound(Dest.begin(), Dest.end(),Tmp);
119 if (I == Dest.end() || *I != Src[0]) // If not already contained...
120 Dest.insert(I, Src[0]);
123 // Make a copy to the side of Dest...
126 // Make space for all of the type entries now...
127 Dest.resize(Dest.size()+Src.size());
129 // Merge the two sorted ranges together... into Dest.
130 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
132 // Now erase any duplicate entries that may have accumulated into the
133 // vectors (because they were in both of the input sets)
134 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
139 // mergeWith - Merge this node and the specified node, moving all links to and
140 // from the argument node into the current node, deleting the node argument.
141 // Offset indicates what offset the specified node is to be merged into the
144 // The specified node may be a null pointer (in which case, nothing happens).
146 void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
147 DSNode *N = NH.getNode();
148 if (N == 0 || (N == this && NH.getOffset() == Offset))
151 assert(NH.getNode() != this &&
152 "Cannot merge two portions of the same node yet!");
154 // If both nodes are not at offset 0, make sure that we are merging the node
155 // at an later offset into the node with the zero offset.
157 if (Offset > NH.getOffset()) {
158 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
163 std::cerr << "\n\nMerging:\n";
164 N->print(std::cerr, 0);
165 std::cerr << " and:\n";
169 // Now we know that Offset <= NH.Offset, so convert it so our "Offset" (with
170 // respect to NH.Offset) is now zero.
172 unsigned NOffset = NH.getOffset()-Offset;
174 // Remove all edges pointing at N, causing them to point to 'this' instead.
175 // Make sure to adjust their offset, not just the node pointer.
177 while (!N->Referrers.empty()) {
178 DSNodeHandle &Ref = *N->Referrers.back();
179 Ref = DSNodeHandle(this, NOffset+Ref.getOffset());
182 // Make all of the outgoing links of N now be outgoing links of this. This
183 // can cause recursive merging!
185 for (unsigned i = 0, e = N->LinkIndex.size(); i != e; ++i)
186 if (N->LinkIndex[i] != -1) {
187 addEdgeTo(i+NOffset, N->Links[N->LinkIndex[i]]);
188 N->LinkIndex[i] = -1; // Reduce unneccesary edges in graph. N is dead
191 // Now that there are no outgoing edges, all of the Links are dead.
194 // Merge the node types
195 NodeType |= N->NodeType;
196 N->NodeType = 0; // N is now a dead node.
198 // If this merging into node has more than just void nodes in it, merge!
199 assert(!N->TypeEntries.empty() && "TypeEntries is empty for a node?");
200 if (N->TypeEntries.size() != 1 || N->TypeEntries[0].first != Type::VoidTy) {
201 // If the current node just has a Void entry in it, remove it.
202 if (TypeEntries.size() == 1 && TypeEntries[0].first == Type::VoidTy)
205 // Adjust all of the type entries we are merging in by the offset... and add
206 // them to the TypeEntries list.
208 if (NOffset != 0) { // This case is common enough to optimize for
209 // Offset all of the TypeEntries in N with their new offset
210 for (unsigned i = 0, e = N->TypeEntries.size(); i != e; ++i)
211 N->TypeEntries[i].second += NOffset;
214 MergeSortedVectors(TypeEntries, N->TypeEntries);
216 N->TypeEntries.clear();
219 // Merge the globals list...
220 if (!N->Globals.empty()) {
221 MergeSortedVectors(Globals, N->Globals);
223 // Delete the globals from the old node...
228 //===----------------------------------------------------------------------===//
229 // DSGraph Implementation
230 //===----------------------------------------------------------------------===//
232 DSGraph::DSGraph(const DSGraph &G) : Func(G.Func) {
233 std::map<const DSNode*, DSNode*> NodeMap;
234 RetNode = cloneInto(G, ValueMap, NodeMap);
237 DSGraph::~DSGraph() {
238 FunctionCalls.clear();
243 // Drop all intra-node references, so that assertions don't fail...
244 std::for_each(Nodes.begin(), Nodes.end(),
245 std::mem_fun(&DSNode::dropAllReferences));
248 // Delete all of the nodes themselves...
249 std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
252 // dump - Allow inspection of graph in a debugger.
253 void DSGraph::dump() const { print(std::cerr); }
255 // Helper function used to clone a function list.
257 static void CopyFunctionCallsList(const vector<vector<DSNodeHandle> >&fromCalls,
258 vector<vector<DSNodeHandle> > &toCalls,
259 std::map<const DSNode*, DSNode*> &NodeMap) {
261 unsigned FC = toCalls.size(); // FirstCall
262 toCalls.reserve(FC+fromCalls.size());
263 for (unsigned i = 0, ei = fromCalls.size(); i != ei; ++i) {
264 toCalls.push_back(vector<DSNodeHandle>());
266 const vector<DSNodeHandle> &CurCall = fromCalls[i];
267 toCalls.back().reserve(CurCall.size());
268 for (unsigned j = 0, ej = fromCalls[i].size(); j != ej; ++j)
269 toCalls[FC+i].push_back(DSNodeHandle(NodeMap[CurCall[j].getNode()],
270 CurCall[j].getOffset()));
274 /// remapLinks - Change all of the Links in the current node according to the
275 /// specified mapping.
276 void DSNode::remapLinks(std::map<const DSNode*, DSNode*> &OldNodeMap) {
277 for (unsigned i = 0, e = Links.size(); i != e; ++i)
278 Links[i].setNode(OldNodeMap[Links[i].getNode()]);
281 // cloneInto - Clone the specified DSGraph into the current graph, returning the
282 // Return node of the graph. The translated ValueMap for the old function is
283 // filled into the OldValMap member. If StripLocals is set to true, Scalar and
284 // Alloca markers are removed from the graph, as the graph is being cloned into
285 // a calling function's graph.
287 DSNodeHandle DSGraph::cloneInto(const DSGraph &G,
288 std::map<Value*, DSNodeHandle> &OldValMap,
289 std::map<const DSNode*, DSNode*> &OldNodeMap,
290 bool StripScalars, bool StripAllocas,
291 bool CopyCallers, bool CopyOrigCalls) {
292 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
294 unsigned FN = Nodes.size(); // First new node...
296 // Duplicate all of the nodes, populating the node map...
297 Nodes.reserve(FN+G.Nodes.size());
298 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
299 DSNode *Old = G.Nodes[i];
300 DSNode *New = new DSNode(*Old);
301 Nodes.push_back(New);
302 OldNodeMap[Old] = New;
305 // Rewrite the links in the new nodes to point into the current graph now.
306 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
307 Nodes[i]->remapLinks(OldNodeMap);
309 // Remove local markers as specified
310 unsigned char StripBits = (StripScalars ? DSNode::ScalarNode : 0) |
311 (StripAllocas ? DSNode::AllocaNode : 0);
313 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
314 Nodes[i]->NodeType &= ~StripBits;
316 // Copy the value map...
317 for (std::map<Value*, DSNodeHandle>::const_iterator I = G.ValueMap.begin(),
318 E = G.ValueMap.end(); I != E; ++I)
319 OldValMap[I->first] = DSNodeHandle(OldNodeMap[I->second.getNode()],
320 I->second.getOffset());
321 // Copy the function calls list...
322 CopyFunctionCallsList(G.FunctionCalls, FunctionCalls, OldNodeMap);
326 CopyFunctionCallsList(G.OrigFunctionCalls, OrigFunctionCalls, OldNodeMap);
328 // Copy the list of unresolved callers
330 PendingCallers.insert(G.PendingCallers.begin(), G.PendingCallers.end());
333 // Return the returned node pointer...
334 return DSNodeHandle(OldNodeMap[G.RetNode.getNode()], G.RetNode.getOffset());
338 // cloneGlobalInto - Clone the given global node and all its target links
339 // (and all their llinks, recursively).
341 DSNode *DSGraph::cloneGlobalInto(const DSNode *GNode) {
342 if (GNode == 0 || GNode->getGlobals().size() == 0) return 0;
344 // If a clone has already been created for GNode, return it.
345 DSNodeHandle& ValMapEntry = ValueMap[GNode->getGlobals()[0]];
346 if (ValMapEntry != 0)
349 // Clone the node and update the ValMap.
350 DSNode* NewNode = new DSNode(*GNode);
351 ValMapEntry = NewNode; // j=0 case of loop below!
352 Nodes.push_back(NewNode);
353 for (unsigned j = 1, N = NewNode->getGlobals().size(); j < N; ++j)
354 ValueMap[NewNode->getGlobals()[j]] = NewNode;
356 // Rewrite the links in the new node to point into the current graph.
357 for (unsigned j = 0, e = GNode->getNumLinks(); j != e; ++j)
358 NewNode->setLink(j, cloneGlobalInto(GNode->getLink(j)));
365 // markIncompleteNodes - Mark the specified node as having contents that are not
366 // known with the current analysis we have performed. Because a node makes all
367 // of the nodes it can reach imcomplete if the node itself is incomplete, we
368 // must recursively traverse the data structure graph, marking all reachable
369 // nodes as incomplete.
371 static void markIncompleteNode(DSNode *N) {
372 // Stop recursion if no node, or if node already marked...
373 if (N == 0 || (N->NodeType & DSNode::Incomplete)) return;
375 // Actually mark the node
376 N->NodeType |= DSNode::Incomplete;
378 // Recusively process children...
379 for (unsigned i = 0, e = N->getSize(); i != e; ++i)
380 if (DSNodeHandle *DSNH = N->getLink(i))
381 markIncompleteNode(DSNH->getNode());
385 // markIncompleteNodes - Traverse the graph, identifying nodes that may be
386 // modified by other functions that have not been resolved yet. This marks
387 // nodes that are reachable through three sources of "unknownness":
389 // Global Variables, Function Calls, and Incoming Arguments
391 // For any node that may have unknown components (because something outside the
392 // scope of current analysis may have modified it), the 'Incomplete' flag is
393 // added to the NodeType.
395 void DSGraph::markIncompleteNodes(bool markFormalArgs) {
396 // Mark any incoming arguments as incomplete...
397 if (markFormalArgs && Func)
398 for (Function::aiterator I = Func->abegin(), E = Func->aend(); I != E; ++I)
399 if (isPointerType(I->getType()) && ValueMap.find(I) != ValueMap.end()) {
400 DSNodeHandle &INH = ValueMap[I];
401 if (INH.getNode() && INH.hasLink(0))
402 markIncompleteNode(ValueMap[I].getLink(0)->getNode());
405 // Mark stuff passed into functions calls as being incomplete...
406 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
407 vector<DSNodeHandle> &Args = FunctionCalls[i];
408 // Then the return value is certainly incomplete!
409 markIncompleteNode(Args[0].getNode());
411 // The call does not make the function argument incomplete...
413 // All arguments to the function call are incomplete though!
414 for (unsigned i = 2, e = Args.size(); i != e; ++i)
415 markIncompleteNode(Args[i].getNode());
418 // Mark all of the nodes pointed to by global or cast nodes as incomplete...
419 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
420 if (Nodes[i]->NodeType & DSNode::GlobalNode) {
421 DSNode *N = Nodes[i];
422 for (unsigned i = 0, e = N->getSize(); i != e; ++i)
423 if (DSNodeHandle *DSNH = N->getLink(i))
424 markIncompleteNode(DSNH->getNode());
428 // removeRefsToGlobal - Helper function that removes globals from the
429 // ValueMap so that the referrer count will go down to zero.
430 static void removeRefsToGlobal(DSNode* N,
431 std::map<Value*, DSNodeHandle> &ValueMap) {
432 while (!N->getGlobals().empty()) {
433 GlobalValue *GV = N->getGlobals().back();
434 N->getGlobals().pop_back();
440 // isNodeDead - This method checks to see if a node is dead, and if it isn't, it
441 // checks to see if there are simple transformations that it can do to make it
444 bool DSGraph::isNodeDead(DSNode *N) {
445 // Is it a trivially dead shadow node...
446 if (N->getReferrers().empty() && N->NodeType == 0)
449 // Is it a function node or some other trivially unused global?
450 if (N->NodeType != 0 &&
451 (N->NodeType & ~DSNode::GlobalNode) == 0 &&
453 N->getReferrers().size() == N->getGlobals().size()) {
455 // Remove the globals from the valuemap, so that the referrer count will go
457 removeRefsToGlobal(N, ValueMap);
458 assert(N->getReferrers().empty() && "Referrers should all be gone now!");
465 static void removeIdenticalCalls(vector<vector<DSNodeHandle> > &Calls,
466 const std::string &where) {
467 // Remove trivially identical function calls
468 unsigned NumFns = Calls.size();
469 std::sort(Calls.begin(), Calls.end());
470 Calls.erase(std::unique(Calls.begin(), Calls.end()),
473 DEBUG(if (NumFns != Calls.size())
474 std::cerr << "Merged " << (NumFns-Calls.size())
475 << " call nodes in " << where << "\n";);
478 // removeTriviallyDeadNodes - After the graph has been constructed, this method
479 // removes all unreachable nodes that are created because they got merged with
480 // other nodes in the graph. These nodes will all be trivially unreachable, so
481 // we don't have to perform any non-trivial analysis here.
483 void DSGraph::removeTriviallyDeadNodes(bool KeepAllGlobals) {
484 for (unsigned i = 0; i != Nodes.size(); ++i)
485 if (! KeepAllGlobals || ! (Nodes[i]->NodeType & DSNode::GlobalNode))
486 if (isNodeDead(Nodes[i])) { // This node is dead!
487 delete Nodes[i]; // Free memory...
488 Nodes.erase(Nodes.begin()+i--); // Remove from node list...
491 removeIdenticalCalls(FunctionCalls, Func ? Func->getName() : "");
495 // markAlive - Simple graph walker that recursively traverses the graph, marking
496 // stuff to be alive.
498 static void markAlive(DSNode *N, std::set<DSNode*> &Alive) {
502 for (unsigned i = 0, e = N->getSize(); i != e; ++i)
503 if (DSNodeHandle *DSNH = N->getLink(i))
504 if (!Alive.count(DSNH->getNode()))
505 markAlive(DSNH->getNode(), Alive);
508 static bool checkGlobalAlive(DSNode *N, std::set<DSNode*> &Alive,
509 std::set<DSNode*> &Visiting) {
510 if (N == 0) return false;
512 if (Visiting.count(N)) return false; // terminate recursion on a cycle
515 // If any immediate successor is alive, N is alive
516 for (unsigned i = 0, e = N->getSize(); i != e; ++i)
517 if (DSNodeHandle *DSNH = N->getLink(i))
518 if (Alive.count(DSNH->getNode())) {
523 // Else if any successor reaches a live node, N is alive
524 for (unsigned i = 0, e = N->getSize(); i != e; ++i)
525 if (DSNodeHandle *DSNH = N->getLink(i))
526 if (checkGlobalAlive(DSNH->getNode(), Alive, Visiting)) {
527 Visiting.erase(N); return true;
535 // markGlobalsIteration - Recursive helper function for markGlobalsAlive().
536 // This would be unnecessary if function calls were real nodes! In that case,
537 // the simple iterative loop in the first few lines below suffice.
539 static void markGlobalsIteration(std::set<DSNode*>& GlobalNodes,
540 vector<vector<DSNodeHandle> > &Calls,
541 std::set<DSNode*> &Alive,
544 // Iterate, marking globals or cast nodes alive until no new live nodes
545 // are added to Alive
546 std::set<DSNode*> Visiting; // Used to identify cycles
547 std::set<DSNode*>::iterator I=GlobalNodes.begin(), E=GlobalNodes.end();
548 for (size_t liveCount = 0; liveCount < Alive.size(); ) {
549 liveCount = Alive.size();
551 if (Alive.count(*I) == 0) {
553 if (checkGlobalAlive(*I, Alive, Visiting))
554 markAlive(*I, Alive);
558 // Find function calls with some dead and some live nodes.
559 // Since all call nodes must be live if any one is live, we have to mark
560 // all nodes of the call as live and continue the iteration (via recursion).
562 bool recurse = false;
563 for (int i = 0, ei = Calls.size(); i < ei; ++i) {
564 bool CallIsDead = true, CallHasDeadArg = false;
565 for (unsigned j = 0, ej = Calls[i].size(); j != ej; ++j) {
566 bool argIsDead = Calls[i][j].getNode() == 0 ||
567 Alive.count(Calls[i][j].getNode()) == 0;
568 CallHasDeadArg |= (Calls[i][j].getNode() != 0 && argIsDead);
569 CallIsDead &= argIsDead;
571 if (!CallIsDead && CallHasDeadArg) {
572 // Some node in this call is live and another is dead.
573 // Mark all nodes of call as live and iterate once more.
575 for (unsigned j = 0, ej = Calls[i].size(); j != ej; ++j)
576 markAlive(Calls[i][j].getNode(), Alive);
580 markGlobalsIteration(GlobalNodes, Calls, Alive, FilterCalls);
585 // markGlobalsAlive - Mark global nodes and cast nodes alive if they
586 // can reach any other live node. Since this can produce new live nodes,
587 // we use a simple iterative algorithm.
589 static void markGlobalsAlive(DSGraph &G, std::set<DSNode*> &Alive,
591 // Add global and cast nodes to a set so we don't walk all nodes every time
592 std::set<DSNode*> GlobalNodes;
593 for (unsigned i = 0, e = G.getNodes().size(); i != e; ++i)
594 if (G.getNodes()[i]->NodeType & DSNode::GlobalNode)
595 GlobalNodes.insert(G.getNodes()[i]);
597 // Add all call nodes to the same set
598 vector<vector<DSNodeHandle> > &Calls = G.getFunctionCalls();
600 for (unsigned i = 0, e = Calls.size(); i != e; ++i)
601 for (unsigned j = 0, e = Calls[i].size(); j != e; ++j)
602 if (Calls[i][j].getNode())
603 GlobalNodes.insert(Calls[i][j].getNode());
606 // Iterate and recurse until no new live node are discovered.
607 // This would be a simple iterative loop if function calls were real nodes!
608 markGlobalsIteration(GlobalNodes, Calls, Alive, FilterCalls);
610 // Free up references to dead globals from the ValueMap
611 std::set<DSNode*>::iterator I=GlobalNodes.begin(), E=GlobalNodes.end();
613 if (Alive.count(*I) == 0)
614 removeRefsToGlobal(*I, G.getValueMap());
616 // Delete dead function calls
618 for (int ei = Calls.size(), i = ei-1; i >= 0; --i) {
619 bool CallIsDead = true;
620 for (unsigned j = 0, ej = Calls[i].size(); CallIsDead && j != ej; ++j)
621 CallIsDead = Alive.count(Calls[i][j].getNode()) == 0;
623 Calls.erase(Calls.begin() + i); // remove the call entirely
627 // removeDeadNodes - Use a more powerful reachability analysis to eliminate
628 // subgraphs that are unreachable. This often occurs because the data
629 // structure doesn't "escape" into it's caller, and thus should be eliminated
630 // from the caller's graph entirely. This is only appropriate to use when
633 void DSGraph::removeDeadNodes(bool KeepAllGlobals, bool KeepCalls) {
634 assert((!KeepAllGlobals || KeepCalls) &&
635 "KeepAllGlobals without KeepCalls is meaningless");
637 // Reduce the amount of work we have to do...
638 removeTriviallyDeadNodes(KeepAllGlobals);
640 // FIXME: Merge nontrivially identical call nodes...
642 // Alive - a set that holds all nodes found to be reachable/alive.
643 std::set<DSNode*> Alive;
645 // If KeepCalls, mark all nodes reachable by call nodes as alive...
647 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
648 for (unsigned j = 0, e = FunctionCalls[i].size(); j != e; ++j)
649 markAlive(FunctionCalls[i][j].getNode(), Alive);
652 for (unsigned i = 0, e = OrigFunctionCalls.size(); i != e; ++i)
653 for (unsigned j = 0, e = OrigFunctionCalls[i].size(); j != e; ++j)
654 markAlive(OrigFunctionCalls[i][j].getNode(), Alive);
657 // Mark all nodes reachable by scalar nodes (and global nodes, if
658 // keeping them was specified) as alive...
659 unsigned char keepBits = DSNode::ScalarNode |
660 (KeepAllGlobals ? DSNode::GlobalNode : 0);
661 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
662 if (Nodes[i]->NodeType & keepBits)
663 markAlive(Nodes[i], Alive);
665 // The return value is alive as well...
666 markAlive(RetNode.getNode(), Alive);
668 // Mark all globals or cast nodes that can reach a live node as alive.
669 // This also marks all nodes reachable from such nodes as alive.
670 // Of course, if KeepAllGlobals is specified, they would be live already.
671 if (! KeepAllGlobals)
672 markGlobalsAlive(*this, Alive, ! KeepCalls);
674 // Loop over all unreachable nodes, dropping their references...
675 vector<DSNode*> DeadNodes;
676 DeadNodes.reserve(Nodes.size()); // Only one allocation is allowed.
677 for (unsigned i = 0; i != Nodes.size(); ++i)
678 if (!Alive.count(Nodes[i])) {
679 DSNode *N = Nodes[i];
680 Nodes.erase(Nodes.begin()+i--); // Erase node from alive list.
681 DeadNodes.push_back(N); // Add node to our list of dead nodes
682 N->dropAllReferences(); // Drop all outgoing edges
685 // Delete all dead nodes...
686 std::for_each(DeadNodes.begin(), DeadNodes.end(), deleter<DSNode>);
691 // maskNodeTypes - Apply a mask to all of the node types in the graph. This
692 // is useful for clearing out markers like Scalar or Incomplete.
694 void DSGraph::maskNodeTypes(unsigned char Mask) {
695 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
696 Nodes[i]->NodeType &= Mask;
701 //===----------------------------------------------------------------------===//
702 // GlobalDSGraph Implementation
703 //===----------------------------------------------------------------------===//
705 GlobalDSGraph::GlobalDSGraph() : DSGraph(*(Function*)0, this) {
708 GlobalDSGraph::~GlobalDSGraph() {
709 assert(Referrers.size() == 0 &&
710 "Deleting global graph while references from other graphs exist");
713 void GlobalDSGraph::addReference(const DSGraph* referrer) {
714 if (referrer != this)
715 Referrers.insert(referrer);
718 void GlobalDSGraph::removeReference(const DSGraph* referrer) {
719 if (referrer != this) {
720 assert(Referrers.find(referrer) != Referrers.end() && "This is very bad!");
721 Referrers.erase(referrer);
722 if (Referrers.size() == 0)
727 // Bits used in the next function
728 static const char ExternalTypeBits = DSNode::GlobalNode | DSNode::NewNode;
731 // GlobalDSGraph::cloneNodeInto - Clone a global node and all its externally
732 // visible target links (and recursively their such links) into this graph.
733 // NodeCache maps the node being cloned to its clone in the Globals graph,
734 // in order to track cycles.
735 // GlobalsAreFinal is a flag that says whether it is safe to assume that
736 // an existing global node is complete. This is important to avoid
737 // reinserting all globals when inserting Calls to functions.
738 // This is a helper function for cloneGlobals and cloneCalls.
740 DSNode* GlobalDSGraph::cloneNodeInto(DSNode *OldNode,
741 std::map<const DSNode*, DSNode*> &NodeCache,
742 bool GlobalsAreFinal) {
743 if (OldNode == 0) return 0;
745 // The caller should check this is an external node. Just more efficient...
746 assert((OldNode->NodeType & ExternalTypeBits) && "Non-external node");
748 // If a clone has already been created for OldNode, return it.
749 DSNode*& CacheEntry = NodeCache[OldNode];
753 // The result value...
756 // If nodes already exist for any of the globals of OldNode,
757 // merge all such nodes together since they are merged in OldNode.
758 // If ValueCacheIsFinal==true, look for an existing node that has
759 // an identical list of globals and return it if it exists.
761 for (unsigned j = 0, N = OldNode->getGlobals().size(); j != N; ++j)
762 if (DSNode *PrevNode = ValueMap[OldNode->getGlobals()[j]].getNode()) {
764 NewNode = PrevNode; // first existing node found
765 if (GlobalsAreFinal && j == 0)
766 if (OldNode->getGlobals() == PrevNode->getGlobals()) {
767 CacheEntry = NewNode;
771 else if (NewNode != PrevNode) { // found another, different from prev
772 // update ValMap *before* merging PrevNode into NewNode
773 for (unsigned k = 0, NK = PrevNode->getGlobals().size(); k < NK; ++k)
774 ValueMap[PrevNode->getGlobals()[k]] = NewNode;
775 NewNode->mergeWith(PrevNode);
777 } else if (NewNode != 0) {
778 ValueMap[OldNode->getGlobals()[j]] = NewNode; // add the merged node
781 // If no existing node was found, clone the node and update the ValMap.
783 NewNode = new DSNode(*OldNode);
784 Nodes.push_back(NewNode);
785 for (unsigned j = 0, e = NewNode->getNumLinks(); j != e; ++j)
786 NewNode->setLink(j, 0);
787 for (unsigned j = 0, N = NewNode->getGlobals().size(); j < N; ++j)
788 ValueMap[NewNode->getGlobals()[j]] = NewNode;
791 NewNode->NodeType |= OldNode->NodeType; // Markers may be different!
793 // Add the entry to NodeCache
794 CacheEntry = NewNode;
796 // Rewrite the links in the new node to point into the current graph,
797 // but only for links to external nodes. Set other links to NULL.
798 for (unsigned j = 0, e = OldNode->getNumLinks(); j != e; ++j) {
799 DSNode* OldTarget = OldNode->getLink(j);
800 if (OldTarget && (OldTarget->NodeType & ExternalTypeBits)) {
801 DSNode* NewLink = this->cloneNodeInto(OldTarget, NodeCache);
802 if (NewNode->getLink(j))
803 NewNode->getLink(j)->mergeWith(NewLink);
805 NewNode->setLink(j, NewLink);
809 // Remove all local markers
810 NewNode->NodeType &= ~(DSNode::AllocaNode | DSNode::ScalarNode);
816 // GlobalDSGraph::cloneGlobals - Clone global nodes and all their externally
817 // visible target links (and recursively their such links) into this graph.
819 void GlobalDSGraph::cloneGlobals(DSGraph& Graph, bool CloneCalls) {
820 std::map<const DSNode*, DSNode*> NodeCache;
822 for (unsigned i = 0, N = Graph.Nodes.size(); i < N; ++i)
823 if (Graph.Nodes[i]->NodeType & DSNode::GlobalNode)
824 GlobalsGraph->cloneNodeInto(Graph.Nodes[i], NodeCache, false);
826 GlobalsGraph->cloneCalls(Graph);
828 GlobalsGraph->removeDeadNodes(/*KeepAllGlobals*/ true, /*KeepCalls*/ true);
833 // GlobalDSGraph::cloneCalls - Clone function calls and their visible target
834 // links (and recursively their such links) into this graph.
836 void GlobalDSGraph::cloneCalls(DSGraph& Graph) {
837 std::map<const DSNode*, DSNode*> NodeCache;
838 vector<vector<DSNodeHandle> >& FromCalls =Graph.FunctionCalls;
840 FunctionCalls.reserve(FunctionCalls.size() + FromCalls.size());
842 for (int i = 0, ei = FromCalls.size(); i < ei; ++i) {
843 FunctionCalls.push_back(vector<DSNodeHandle>());
844 FunctionCalls.back().reserve(FromCalls[i].size());
845 for (unsigned j = 0, ej = FromCalls[i].size(); j != ej; ++j)
846 FunctionCalls.back().push_back
847 ((FromCalls[i][j] && (FromCalls[i][j]->NodeType & ExternalTypeBits))
848 ? cloneNodeInto(FromCalls[i][j], NodeCache, true)
852 // remove trivially identical function calls
853 removeIdenticalCalls(FunctionCalls, "Globals Graph");