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 "llvm/Target/TargetData.h"
11 #include "Support/STLExtras.h"
12 #include "Support/Statistic.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 MergeMap.resize(TD.getTypeSize(T));
37 // Assign unique values to all of the elements of MergeMap
38 if (MergeMap.size() < 128) {
39 // Handle the common case of reasonable size structures...
40 for (unsigned i = 0, e = MergeMap.size(); i != e; ++i)
41 MergeMap[i] = -1-i; // Assign -1, -2, -3, ...
43 // It's possible that we have something really big here. In this case,
44 // divide the object into chunks until it will fit into 128 elements.
45 unsigned Multiple = MergeMap.size()/128;
47 // It's probably an array, and probably some power of two in size.
48 // Because of this, find the biggest power of two that is bigger than
49 // multiple to use as our real Multiple.
50 unsigned RealMultiple = 2;
51 while (RealMultiple <= Multiple) RealMultiple <<= 1;
53 unsigned RealBound = MergeMap.size()/RealMultiple;
54 assert(RealBound <= 128 && "Math didn't work out right");
56 // Now go through and assign indexes that are between -1 and -128
59 for (unsigned i = 0, e = MergeMap.size(); i != e; ++i)
60 MergeMap[i] = -1-(i % RealBound); // Assign -1, -2, -3...
64 TypeEntries.push_back(std::make_pair(T, 0));
67 // DSNode copy constructor... do not copy over the referrers list!
68 DSNode::DSNode(const DSNode &N)
69 : Links(N.Links), MergeMap(N.MergeMap),
70 TypeEntries(N.TypeEntries), Globals(N.Globals), NodeType(N.NodeType) {
73 void DSNode::removeReferrer(DSNodeHandle *H) {
74 // Search backwards, because we depopulate the list from the back for
75 // efficiency (because it's a vector).
76 vector<DSNodeHandle*>::reverse_iterator I =
77 std::find(Referrers.rbegin(), Referrers.rend(), H);
78 assert(I != Referrers.rend() && "Referrer not pointing to node!");
79 Referrers.erase(I.base()-1);
82 // addGlobal - Add an entry for a global value to the Globals list. This also
83 // marks the node with the 'G' flag if it does not already have it.
85 void DSNode::addGlobal(GlobalValue *GV) {
86 // Keep the list sorted.
87 vector<GlobalValue*>::iterator I =
88 std::lower_bound(Globals.begin(), Globals.end(), GV);
90 if (I == Globals.end() || *I != GV) {
91 //assert(GV->getType()->getElementType() == Ty);
92 Globals.insert(I, GV);
93 NodeType |= GlobalNode;
98 /// setLink - Set the link at the specified offset to the specified
99 /// NodeHandle, replacing what was there. It is uncommon to use this method,
100 /// instead one of the higher level methods should be used, below.
102 void DSNode::setLink(unsigned i, const DSNodeHandle &NH) {
103 // Create a new entry in the Links vector to hold a new element for offset.
105 signed char NewIdx = Links.size();
106 // Check to see if we allocate more than 128 distinct links for this node.
107 // If so, just merge with the last one. This really shouldn't ever happen,
108 // but it should work regardless of whether it does or not.
111 Links.push_back(NH); // Allocate space: common case
112 } else { // Wrap around? Too many links?
113 NewIdx--; // Merge with whatever happened last
114 assert(NewIdx > 0 && "Should wrap back around");
115 std::cerr << "\n*** DSNode found that requires more than 128 "
116 << "active links at once!\n\n";
119 signed char OldIdx = MergeMap[i];
120 assert (OldIdx < 0 && "Shouldn't contain link!");
122 // Make sure that anything aliasing this field gets updated to point to the
124 rewriteMergeMap(OldIdx, NewIdx);
125 assert(MergeMap[i] == NewIdx && "Field not replaced!");
127 Links[MergeMap[i]] = NH;
131 // addEdgeTo - Add an edge from the current node to the specified node. This
132 // can cause merging of nodes in the graph.
134 void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
135 assert(Offset < getSize() && "Offset out of range!");
136 if (NH.getNode() == 0) return; // Nothing to do
138 if (DSNodeHandle *ExistingNH = getLink(Offset)) {
139 // Merge the two nodes...
140 ExistingNH->mergeWith(NH);
141 } else { // No merging to perform...
142 setLink(Offset, NH); // Just force a link in there...
146 /// mergeMappedValues - This is the higher level form of rewriteMergeMap. It is
147 /// fully capable of merging links together if neccesary as well as simply
148 /// rewriting the map entries.
150 void DSNode::mergeMappedValues(signed char V1, signed char V2) {
151 assert(V1 != V2 && "Cannot merge two identical mapped values!");
153 if (V1 < 0) { // If there is no outgoing link from V1, merge it with V2
154 if (V2 < 0 && V1 > V2)
155 // If both are not linked, merge to the field closer to 0
156 rewriteMergeMap(V2, V1);
158 rewriteMergeMap(V1, V2);
159 } else if (V2 < 0) { // Is V2 < 0 && V1 >= 0?
160 rewriteMergeMap(V2, V1); // Merge into the one with the link...
161 } else { // Otherwise, links exist at both locations
162 // Merge Links[V1] with Links[V2] so they point to the same place now...
163 Links[V1].mergeWith(Links[V2]);
165 // Merge the V2 link into V1 so that we reduce the overall value of the
166 // links are reduced...
168 if (V2 < V1) std::swap(V1, V2); // Ensure V1 < V2
169 rewriteMergeMap(V2, V1); // After this, V2 is "dead"
171 // Change the user of the last link to use V2 instead
172 if ((unsigned)V2 != Links.size()-1) {
173 rewriteMergeMap(Links.size()-1, V2); // Point to V2 instead of last el...
174 // Make sure V2 points the right DSNode
175 Links[V2] = Links.back();
178 // Reduce the number of distinct outgoing links...
184 // MergeSortedVectors - Efficiently merge a vector into another vector where
185 // duplicates are not allowed and both are sorted. This assumes that 'T's are
186 // efficiently copyable and have sane comparison semantics.
189 void MergeSortedVectors(vector<T> &Dest, const vector<T> &Src) {
190 // By far, the most common cases will be the simple ones. In these cases,
191 // avoid having to allocate a temporary vector...
193 if (Src.empty()) { // Nothing to merge in...
195 } else if (Dest.empty()) { // Just copy the result in...
197 } else if (Src.size() == 1) { // Insert a single element...
199 typename vector<T>::iterator I =
200 std::lower_bound(Dest.begin(), Dest.end(), V);
201 if (I == Dest.end() || *I != Src[0]) // If not already contained...
202 Dest.insert(I, Src[0]);
203 } else if (Dest.size() == 1) {
204 T Tmp = Dest[0]; // Save value in temporary...
205 Dest = Src; // Copy over list...
206 typename vector<T>::iterator I =
207 std::lower_bound(Dest.begin(), Dest.end(),Tmp);
208 if (I == Dest.end() || *I != Src[0]) // If not already contained...
209 Dest.insert(I, Src[0]);
212 // Make a copy to the side of Dest...
215 // Make space for all of the type entries now...
216 Dest.resize(Dest.size()+Src.size());
218 // Merge the two sorted ranges together... into Dest.
219 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
221 // Now erase any duplicate entries that may have accumulated into the
222 // vectors (because they were in both of the input sets)
223 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
228 // mergeWith - Merge this node and the specified node, moving all links to and
229 // from the argument node into the current node, deleting the node argument.
230 // Offset indicates what offset the specified node is to be merged into the
233 // The specified node may be a null pointer (in which case, nothing happens).
235 void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
236 DSNode *N = NH.getNode();
237 if (N == 0 || (N == this && NH.getOffset() == Offset))
240 assert(NH.getNode() != this &&
241 "Cannot merge two portions of the same node yet!");
243 // If both nodes are not at offset 0, make sure that we are merging the node
244 // at an later offset into the node with the zero offset.
246 if (Offset > NH.getOffset()) {
247 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
252 std::cerr << "\n\nMerging:\n";
253 N->print(std::cerr, 0);
254 std::cerr << " and:\n";
258 // Now we know that Offset <= NH.Offset, so convert it so our "Offset" (with
259 // respect to NH.Offset) is now zero.
261 unsigned NOffset = NH.getOffset()-Offset;
263 unsigned NSize = N->getSize();
264 assert(NSize+NOffset <= getSize() &&
265 "Don't know how to merge extend a merged nodes size yet!");
267 // Remove all edges pointing at N, causing them to point to 'this' instead.
268 // Make sure to adjust their offset, not just the node pointer.
270 while (!N->Referrers.empty()) {
271 DSNodeHandle &Ref = *N->Referrers.back();
272 Ref = DSNodeHandle(this, NOffset+Ref.getOffset());
275 // We must merge fields in this node due to nodes merged in the source node.
276 // In order to handle this we build a map that converts from the source node's
277 // MergeMap values to our MergeMap values. This map is indexed by the
278 // expression: MergeMap[SMM+SourceNodeSize] so we need to allocate at least
279 // 2*SourceNodeSize elements of space for the mapping. We can do this because
280 // we know that there are at most SourceNodeSize outgoing links in the node
281 // (thus that many positive values) and at most SourceNodeSize distinct fields
282 // (thus that many negative values).
284 std::vector<signed char> MergeMapMap(NSize*2, 127);
286 // Loop through the structures, merging them together...
287 for (unsigned i = 0, e = NSize; i != e; ++i) {
288 // Get what this byte of N maps to...
289 signed char NElement = N->MergeMap[i];
291 // Get what we map this byte to...
292 signed char Element = MergeMap[i+NOffset];
293 // We use 127 as a sentinal and don't check for it's existence yet...
294 assert(Element != 127 && "MergeMapMap doesn't permit 127 values yet!");
296 signed char CurMappedVal = MergeMapMap[NElement+NSize];
297 if (CurMappedVal == 127) { // Haven't seen this NElement yet?
298 MergeMapMap[NElement+NSize] = Element; // Map the two together...
299 } else if (CurMappedVal != Element) {
300 // If we are mapping two different fields together this means that we need
301 // to merge fields in the current node due to merging in the source node.
303 mergeMappedValues(CurMappedVal, Element);
304 MergeMapMap[NElement+NSize] = MergeMap[i+NOffset];
308 // Make all of the outgoing links of N now be outgoing links of this. This
309 // can cause recursive merging!
311 for (unsigned i = 0, e = NSize; i != e; ++i)
312 if (DSNodeHandle *Link = N->getLink(i)) {
313 addEdgeTo(i+NOffset, *Link);
314 N->MergeMap[i] = -1; // Kill outgoing edge
317 // Now that there are no outgoing edges, all of the Links are dead.
320 // Merge the node types
321 NodeType |= N->NodeType;
322 N->NodeType = 0; // N is now a dead node.
324 // If this merging into node has more than just void nodes in it, merge!
325 assert(!N->TypeEntries.empty() && "TypeEntries is empty for a node?");
326 if (N->TypeEntries.size() != 1 || N->TypeEntries[0].first != Type::VoidTy) {
327 // If the current node just has a Void entry in it, remove it.
328 if (TypeEntries.size() == 1 && TypeEntries[0].first == Type::VoidTy)
331 // Adjust all of the type entries we are merging in by the offset... and add
332 // them to the TypeEntries list.
334 if (NOffset != 0) { // This case is common enough to optimize for
335 // Offset all of the TypeEntries in N with their new offset
336 for (unsigned i = 0, e = N->TypeEntries.size(); i != e; ++i)
337 N->TypeEntries[i].second += NOffset;
340 MergeSortedVectors(TypeEntries, N->TypeEntries);
342 N->TypeEntries.clear();
345 // Merge the globals list...
346 if (!N->Globals.empty()) {
347 MergeSortedVectors(Globals, N->Globals);
349 // Delete the globals from the old node...
354 //===----------------------------------------------------------------------===//
355 // DSGraph Implementation
356 //===----------------------------------------------------------------------===//
358 DSGraph::DSGraph(const DSGraph &G) : Func(G.Func) {
359 std::map<const DSNode*, DSNode*> NodeMap;
360 RetNode = cloneInto(G, ValueMap, NodeMap);
363 DSGraph::~DSGraph() {
364 FunctionCalls.clear();
369 // Drop all intra-node references, so that assertions don't fail...
370 std::for_each(Nodes.begin(), Nodes.end(),
371 std::mem_fun(&DSNode::dropAllReferences));
374 // Delete all of the nodes themselves...
375 std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
378 // dump - Allow inspection of graph in a debugger.
379 void DSGraph::dump() const { print(std::cerr); }
381 // Helper function used to clone a function list.
383 static void CopyFunctionCallsList(const vector<vector<DSNodeHandle> >&fromCalls,
384 vector<vector<DSNodeHandle> > &toCalls,
385 std::map<const DSNode*, DSNode*> &NodeMap) {
387 unsigned FC = toCalls.size(); // FirstCall
388 toCalls.reserve(FC+fromCalls.size());
389 for (unsigned i = 0, ei = fromCalls.size(); i != ei; ++i) {
390 toCalls.push_back(vector<DSNodeHandle>());
392 const vector<DSNodeHandle> &CurCall = fromCalls[i];
393 toCalls.back().reserve(CurCall.size());
394 for (unsigned j = 0, ej = fromCalls[i].size(); j != ej; ++j)
395 toCalls[FC+i].push_back(DSNodeHandle(NodeMap[CurCall[j].getNode()],
396 CurCall[j].getOffset()));
400 /// remapLinks - Change all of the Links in the current node according to the
401 /// specified mapping.
402 void DSNode::remapLinks(std::map<const DSNode*, DSNode*> &OldNodeMap) {
403 for (unsigned i = 0, e = Links.size(); i != e; ++i)
404 Links[i].setNode(OldNodeMap[Links[i].getNode()]);
407 // cloneInto - Clone the specified DSGraph into the current graph, returning the
408 // Return node of the graph. The translated ValueMap for the old function is
409 // filled into the OldValMap member. If StripLocals is set to true, Scalar and
410 // Alloca markers are removed from the graph, as the graph is being cloned into
411 // a calling function's graph.
413 DSNodeHandle DSGraph::cloneInto(const DSGraph &G,
414 std::map<Value*, DSNodeHandle> &OldValMap,
415 std::map<const DSNode*, DSNode*> &OldNodeMap,
416 bool StripScalars, bool StripAllocas,
417 bool CopyCallers, bool CopyOrigCalls) {
418 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
420 unsigned FN = Nodes.size(); // First new node...
422 // Duplicate all of the nodes, populating the node map...
423 Nodes.reserve(FN+G.Nodes.size());
424 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
425 DSNode *Old = G.Nodes[i];
426 DSNode *New = new DSNode(*Old);
427 Nodes.push_back(New);
428 OldNodeMap[Old] = New;
431 // Rewrite the links in the new nodes to point into the current graph now.
432 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
433 Nodes[i]->remapLinks(OldNodeMap);
435 // Remove local markers as specified
436 unsigned char StripBits = (StripScalars ? DSNode::ScalarNode : 0) |
437 (StripAllocas ? DSNode::AllocaNode : 0);
439 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
440 Nodes[i]->NodeType &= ~StripBits;
442 // Copy the value map...
443 for (std::map<Value*, DSNodeHandle>::const_iterator I = G.ValueMap.begin(),
444 E = G.ValueMap.end(); I != E; ++I)
445 OldValMap[I->first] = DSNodeHandle(OldNodeMap[I->second.getNode()],
446 I->second.getOffset());
447 // Copy the function calls list...
448 CopyFunctionCallsList(G.FunctionCalls, FunctionCalls, OldNodeMap);
450 // Return the returned node pointer...
451 return DSNodeHandle(OldNodeMap[G.RetNode.getNode()], G.RetNode.getOffset());
455 // cloneGlobalInto - Clone the given global node and all its target links
456 // (and all their llinks, recursively).
458 DSNode *DSGraph::cloneGlobalInto(const DSNode *GNode) {
459 if (GNode == 0 || GNode->getGlobals().size() == 0) return 0;
461 // If a clone has already been created for GNode, return it.
462 DSNodeHandle& ValMapEntry = ValueMap[GNode->getGlobals()[0]];
463 if (ValMapEntry != 0)
466 // Clone the node and update the ValMap.
467 DSNode* NewNode = new DSNode(*GNode);
468 ValMapEntry = NewNode; // j=0 case of loop below!
469 Nodes.push_back(NewNode);
470 for (unsigned j = 1, N = NewNode->getGlobals().size(); j < N; ++j)
471 ValueMap[NewNode->getGlobals()[j]] = NewNode;
473 // Rewrite the links in the new node to point into the current graph.
474 for (unsigned j = 0, e = GNode->getNumLinks(); j != e; ++j)
475 NewNode->setLink(j, cloneGlobalInto(GNode->getLink(j)));
482 // markIncompleteNodes - Mark the specified node as having contents that are not
483 // known with the current analysis we have performed. Because a node makes all
484 // of the nodes it can reach imcomplete if the node itself is incomplete, we
485 // must recursively traverse the data structure graph, marking all reachable
486 // nodes as incomplete.
488 static void markIncompleteNode(DSNode *N) {
489 // Stop recursion if no node, or if node already marked...
490 if (N == 0 || (N->NodeType & DSNode::Incomplete)) return;
492 // Actually mark the node
493 N->NodeType |= DSNode::Incomplete;
495 // Recusively process children...
496 for (unsigned i = 0, e = N->getSize(); i != e; ++i)
497 if (DSNodeHandle *DSNH = N->getLink(i))
498 markIncompleteNode(DSNH->getNode());
502 // markIncompleteNodes - Traverse the graph, identifying nodes that may be
503 // modified by other functions that have not been resolved yet. This marks
504 // nodes that are reachable through three sources of "unknownness":
506 // Global Variables, Function Calls, and Incoming Arguments
508 // For any node that may have unknown components (because something outside the
509 // scope of current analysis may have modified it), the 'Incomplete' flag is
510 // added to the NodeType.
512 void DSGraph::markIncompleteNodes(bool markFormalArgs) {
513 // Mark any incoming arguments as incomplete...
514 if (markFormalArgs && Func)
515 for (Function::aiterator I = Func->abegin(), E = Func->aend(); I != E; ++I)
516 if (isPointerType(I->getType()) && ValueMap.find(I) != ValueMap.end()) {
517 DSNodeHandle &INH = ValueMap[I];
518 if (INH.getNode() && INH.hasLink(0))
519 markIncompleteNode(ValueMap[I].getLink(0)->getNode());
522 // Mark stuff passed into functions calls as being incomplete...
523 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
524 vector<DSNodeHandle> &Args = FunctionCalls[i];
525 // Then the return value is certainly incomplete!
526 markIncompleteNode(Args[0].getNode());
528 // The call does not make the function argument incomplete...
530 // All arguments to the function call are incomplete though!
531 for (unsigned i = 2, e = Args.size(); i != e; ++i)
532 markIncompleteNode(Args[i].getNode());
535 // Mark all of the nodes pointed to by global or cast nodes as incomplete...
536 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
537 if (Nodes[i]->NodeType & DSNode::GlobalNode) {
538 DSNode *N = Nodes[i];
539 for (unsigned i = 0, e = N->getSize(); i != e; ++i)
540 if (DSNodeHandle *DSNH = N->getLink(i))
541 markIncompleteNode(DSNH->getNode());
545 // removeRefsToGlobal - Helper function that removes globals from the
546 // ValueMap so that the referrer count will go down to zero.
547 static void removeRefsToGlobal(DSNode* N,
548 std::map<Value*, DSNodeHandle> &ValueMap) {
549 while (!N->getGlobals().empty()) {
550 GlobalValue *GV = N->getGlobals().back();
551 N->getGlobals().pop_back();
557 // isNodeDead - This method checks to see if a node is dead, and if it isn't, it
558 // checks to see if there are simple transformations that it can do to make it
561 bool DSGraph::isNodeDead(DSNode *N) {
562 // Is it a trivially dead shadow node...
563 if (N->getReferrers().empty() && N->NodeType == 0)
566 // Is it a function node or some other trivially unused global?
567 if (N->NodeType != 0 &&
568 (N->NodeType & ~DSNode::GlobalNode) == 0 &&
570 N->getReferrers().size() == N->getGlobals().size()) {
572 // Remove the globals from the ValueMap, so that the referrer count will go
574 removeRefsToGlobal(N, ValueMap);
575 assert(N->getReferrers().empty() && "Referrers should all be gone now!");
582 static void removeIdenticalCalls(vector<vector<DSNodeHandle> > &Calls,
583 const std::string &where) {
584 // Remove trivially identical function calls
585 unsigned NumFns = Calls.size();
586 std::sort(Calls.begin(), Calls.end());
587 Calls.erase(std::unique(Calls.begin(), Calls.end()),
590 DEBUG(if (NumFns != Calls.size())
591 std::cerr << "Merged " << (NumFns-Calls.size())
592 << " call nodes in " << where << "\n";);
595 // removeTriviallyDeadNodes - After the graph has been constructed, this method
596 // removes all unreachable nodes that are created because they got merged with
597 // other nodes in the graph. These nodes will all be trivially unreachable, so
598 // we don't have to perform any non-trivial analysis here.
600 void DSGraph::removeTriviallyDeadNodes(bool KeepAllGlobals) {
601 for (unsigned i = 0; i != Nodes.size(); ++i)
602 if (!KeepAllGlobals || !(Nodes[i]->NodeType & DSNode::GlobalNode))
603 if (isNodeDead(Nodes[i])) { // This node is dead!
604 delete Nodes[i]; // Free memory...
605 Nodes.erase(Nodes.begin()+i--); // Remove from node list...
608 removeIdenticalCalls(FunctionCalls, Func ? Func->getName() : "");
612 // markAlive - Simple graph walker that recursively traverses the graph, marking
613 // stuff to be alive.
615 static void markAlive(DSNode *N, std::set<DSNode*> &Alive) {
619 for (unsigned i = 0, e = N->getSize(); i != e; ++i)
620 if (DSNodeHandle *DSNH = N->getLink(i))
621 if (!Alive.count(DSNH->getNode()))
622 markAlive(DSNH->getNode(), Alive);
625 static bool checkGlobalAlive(DSNode *N, std::set<DSNode*> &Alive,
626 std::set<DSNode*> &Visiting) {
627 if (N == 0) return false;
629 if (Visiting.count(N)) return false; // terminate recursion on a cycle
632 // If any immediate successor is alive, N is alive
633 for (unsigned i = 0, e = N->getSize(); i != e; ++i)
634 if (DSNodeHandle *DSNH = N->getLink(i))
635 if (Alive.count(DSNH->getNode())) {
640 // Else if any successor reaches a live node, N is alive
641 for (unsigned i = 0, e = N->getSize(); i != e; ++i)
642 if (DSNodeHandle *DSNH = N->getLink(i))
643 if (checkGlobalAlive(DSNH->getNode(), Alive, Visiting)) {
644 Visiting.erase(N); return true;
652 // markGlobalsIteration - Recursive helper function for markGlobalsAlive().
653 // This would be unnecessary if function calls were real nodes! In that case,
654 // the simple iterative loop in the first few lines below suffice.
656 static void markGlobalsIteration(std::set<DSNode*>& GlobalNodes,
657 vector<vector<DSNodeHandle> > &Calls,
658 std::set<DSNode*> &Alive,
661 // Iterate, marking globals or cast nodes alive until no new live nodes
662 // are added to Alive
663 std::set<DSNode*> Visiting; // Used to identify cycles
664 std::set<DSNode*>::iterator I=GlobalNodes.begin(), E=GlobalNodes.end();
665 for (size_t liveCount = 0; liveCount < Alive.size(); ) {
666 liveCount = Alive.size();
668 if (Alive.count(*I) == 0) {
670 if (checkGlobalAlive(*I, Alive, Visiting))
671 markAlive(*I, Alive);
675 // Find function calls with some dead and some live nodes.
676 // Since all call nodes must be live if any one is live, we have to mark
677 // all nodes of the call as live and continue the iteration (via recursion).
679 bool recurse = false;
680 for (int i = 0, ei = Calls.size(); i < ei; ++i) {
681 bool CallIsDead = true, CallHasDeadArg = false;
682 for (unsigned j = 0, ej = Calls[i].size(); j != ej; ++j) {
683 bool argIsDead = Calls[i][j].getNode() == 0 ||
684 Alive.count(Calls[i][j].getNode()) == 0;
685 CallHasDeadArg |= (Calls[i][j].getNode() != 0 && argIsDead);
686 CallIsDead &= argIsDead;
688 if (!CallIsDead && CallHasDeadArg) {
689 // Some node in this call is live and another is dead.
690 // Mark all nodes of call as live and iterate once more.
692 for (unsigned j = 0, ej = Calls[i].size(); j != ej; ++j)
693 markAlive(Calls[i][j].getNode(), Alive);
697 markGlobalsIteration(GlobalNodes, Calls, Alive, FilterCalls);
702 // markGlobalsAlive - Mark global nodes and cast nodes alive if they
703 // can reach any other live node. Since this can produce new live nodes,
704 // we use a simple iterative algorithm.
706 static void markGlobalsAlive(DSGraph &G, std::set<DSNode*> &Alive,
708 // Add global and cast nodes to a set so we don't walk all nodes every time
709 std::set<DSNode*> GlobalNodes;
710 for (unsigned i = 0, e = G.getNodes().size(); i != e; ++i)
711 if (G.getNodes()[i]->NodeType & DSNode::GlobalNode)
712 GlobalNodes.insert(G.getNodes()[i]);
714 // Add all call nodes to the same set
715 vector<vector<DSNodeHandle> > &Calls = G.getFunctionCalls();
717 for (unsigned i = 0, e = Calls.size(); i != e; ++i)
718 for (unsigned j = 0, e = Calls[i].size(); j != e; ++j)
719 if (Calls[i][j].getNode())
720 GlobalNodes.insert(Calls[i][j].getNode());
723 // Iterate and recurse until no new live node are discovered.
724 // This would be a simple iterative loop if function calls were real nodes!
725 markGlobalsIteration(GlobalNodes, Calls, Alive, FilterCalls);
727 // Free up references to dead globals from the ValueMap
728 std::set<DSNode*>::iterator I=GlobalNodes.begin(), E=GlobalNodes.end();
730 if (Alive.count(*I) == 0)
731 removeRefsToGlobal(*I, G.getValueMap());
733 // Delete dead function calls
735 for (int ei = Calls.size(), i = ei-1; i >= 0; --i) {
736 bool CallIsDead = true;
737 for (unsigned j = 0, ej = Calls[i].size(); CallIsDead && j != ej; ++j)
738 CallIsDead = Alive.count(Calls[i][j].getNode()) == 0;
740 Calls.erase(Calls.begin() + i); // remove the call entirely
744 // removeDeadNodes - Use a more powerful reachability analysis to eliminate
745 // subgraphs that are unreachable. This often occurs because the data
746 // structure doesn't "escape" into it's caller, and thus should be eliminated
747 // from the caller's graph entirely. This is only appropriate to use when
750 void DSGraph::removeDeadNodes(bool KeepAllGlobals, bool KeepCalls) {
751 assert((!KeepAllGlobals || KeepCalls) &&
752 "KeepAllGlobals without KeepCalls is meaningless");
754 // Reduce the amount of work we have to do...
755 removeTriviallyDeadNodes(KeepAllGlobals);
757 // FIXME: Merge nontrivially identical call nodes...
759 // Alive - a set that holds all nodes found to be reachable/alive.
760 std::set<DSNode*> Alive;
762 // If KeepCalls, mark all nodes reachable by call nodes as alive...
764 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
765 for (unsigned j = 0, e = FunctionCalls[i].size(); j != e; ++j)
766 markAlive(FunctionCalls[i][j].getNode(), Alive);
769 for (unsigned i = 0, e = OrigFunctionCalls.size(); i != e; ++i)
770 for (unsigned j = 0, e = OrigFunctionCalls[i].size(); j != e; ++j)
771 markAlive(OrigFunctionCalls[i][j].getNode(), Alive);
774 // Mark all nodes reachable by scalar nodes (and global nodes, if
775 // keeping them was specified) as alive...
776 unsigned char keepBits = DSNode::ScalarNode |
777 (KeepAllGlobals ? DSNode::GlobalNode : 0);
778 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
779 if (Nodes[i]->NodeType & keepBits)
780 markAlive(Nodes[i], Alive);
782 // The return value is alive as well...
783 markAlive(RetNode.getNode(), Alive);
785 // Mark all globals or cast nodes that can reach a live node as alive.
786 // This also marks all nodes reachable from such nodes as alive.
787 // Of course, if KeepAllGlobals is specified, they would be live already.
788 if (! KeepAllGlobals)
789 markGlobalsAlive(*this, Alive, ! KeepCalls);
791 // Loop over all unreachable nodes, dropping their references...
792 vector<DSNode*> DeadNodes;
793 DeadNodes.reserve(Nodes.size()); // Only one allocation is allowed.
794 for (unsigned i = 0; i != Nodes.size(); ++i)
795 if (!Alive.count(Nodes[i])) {
796 DSNode *N = Nodes[i];
797 Nodes.erase(Nodes.begin()+i--); // Erase node from alive list.
798 DeadNodes.push_back(N); // Add node to our list of dead nodes
799 N->dropAllReferences(); // Drop all outgoing edges
802 // Delete all dead nodes...
803 std::for_each(DeadNodes.begin(), DeadNodes.end(), deleter<DSNode>);
808 // maskNodeTypes - Apply a mask to all of the node types in the graph. This
809 // is useful for clearing out markers like Scalar or Incomplete.
811 void DSGraph::maskNodeTypes(unsigned char Mask) {
812 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
813 Nodes[i]->NodeType &= Mask;
818 //===----------------------------------------------------------------------===//
819 // GlobalDSGraph Implementation
820 //===----------------------------------------------------------------------===//
822 GlobalDSGraph::GlobalDSGraph() : DSGraph(*(Function*)0, this) {
825 GlobalDSGraph::~GlobalDSGraph() {
826 assert(Referrers.size() == 0 &&
827 "Deleting global graph while references from other graphs exist");
830 void GlobalDSGraph::addReference(const DSGraph* referrer) {
831 if (referrer != this)
832 Referrers.insert(referrer);
835 void GlobalDSGraph::removeReference(const DSGraph* referrer) {
836 if (referrer != this) {
837 assert(Referrers.find(referrer) != Referrers.end() && "This is very bad!");
838 Referrers.erase(referrer);
839 if (Referrers.size() == 0)
844 // Bits used in the next function
845 static const char ExternalTypeBits = DSNode::GlobalNode | DSNode::NewNode;
848 // GlobalDSGraph::cloneNodeInto - Clone a global node and all its externally
849 // visible target links (and recursively their such links) into this graph.
850 // NodeCache maps the node being cloned to its clone in the Globals graph,
851 // in order to track cycles.
852 // GlobalsAreFinal is a flag that says whether it is safe to assume that
853 // an existing global node is complete. This is important to avoid
854 // reinserting all globals when inserting Calls to functions.
855 // This is a helper function for cloneGlobals and cloneCalls.
857 DSNode* GlobalDSGraph::cloneNodeInto(DSNode *OldNode,
858 std::map<const DSNode*, DSNode*> &NodeCache,
859 bool GlobalsAreFinal) {
860 if (OldNode == 0) return 0;
862 // The caller should check this is an external node. Just more efficient...
863 assert((OldNode->NodeType & ExternalTypeBits) && "Non-external node");
865 // If a clone has already been created for OldNode, return it.
866 DSNode*& CacheEntry = NodeCache[OldNode];
870 // The result value...
873 // If nodes already exist for any of the globals of OldNode,
874 // merge all such nodes together since they are merged in OldNode.
875 // If ValueCacheIsFinal==true, look for an existing node that has
876 // an identical list of globals and return it if it exists.
878 for (unsigned j = 0, N = OldNode->getGlobals().size(); j != N; ++j)
879 if (DSNode *PrevNode = ValueMap[OldNode->getGlobals()[j]].getNode()) {
881 NewNode = PrevNode; // first existing node found
882 if (GlobalsAreFinal && j == 0)
883 if (OldNode->getGlobals() == PrevNode->getGlobals()) {
884 CacheEntry = NewNode;
888 else if (NewNode != PrevNode) { // found another, different from prev
889 // update ValMap *before* merging PrevNode into NewNode
890 for (unsigned k = 0, NK = PrevNode->getGlobals().size(); k < NK; ++k)
891 ValueMap[PrevNode->getGlobals()[k]] = NewNode;
892 NewNode->mergeWith(PrevNode);
894 } else if (NewNode != 0) {
895 ValueMap[OldNode->getGlobals()[j]] = NewNode; // add the merged node
898 // If no existing node was found, clone the node and update the ValMap.
900 NewNode = new DSNode(*OldNode);
901 Nodes.push_back(NewNode);
902 for (unsigned j = 0, e = NewNode->getNumLinks(); j != e; ++j)
903 NewNode->setLink(j, 0);
904 for (unsigned j = 0, N = NewNode->getGlobals().size(); j < N; ++j)
905 ValueMap[NewNode->getGlobals()[j]] = NewNode;
908 NewNode->NodeType |= OldNode->NodeType; // Markers may be different!
910 // Add the entry to NodeCache
911 CacheEntry = NewNode;
913 // Rewrite the links in the new node to point into the current graph,
914 // but only for links to external nodes. Set other links to NULL.
915 for (unsigned j = 0, e = OldNode->getNumLinks(); j != e; ++j) {
916 DSNode* OldTarget = OldNode->getLink(j);
917 if (OldTarget && (OldTarget->NodeType & ExternalTypeBits)) {
918 DSNode* NewLink = this->cloneNodeInto(OldTarget, NodeCache);
919 if (NewNode->getLink(j))
920 NewNode->getLink(j)->mergeWith(NewLink);
922 NewNode->setLink(j, NewLink);
926 // Remove all local markers
927 NewNode->NodeType &= ~(DSNode::AllocaNode | DSNode::ScalarNode);
933 // GlobalDSGraph::cloneGlobals - Clone global nodes and all their externally
934 // visible target links (and recursively their such links) into this graph.
936 void GlobalDSGraph::cloneGlobals(DSGraph& Graph, bool CloneCalls) {
937 std::map<const DSNode*, DSNode*> NodeCache;
939 for (unsigned i = 0, N = Graph.Nodes.size(); i < N; ++i)
940 if (Graph.Nodes[i]->NodeType & DSNode::GlobalNode)
941 GlobalsGraph->cloneNodeInto(Graph.Nodes[i], NodeCache, false);
943 GlobalsGraph->cloneCalls(Graph);
945 GlobalsGraph->removeDeadNodes(/*KeepAllGlobals*/ true, /*KeepCalls*/ true);
950 // GlobalDSGraph::cloneCalls - Clone function calls and their visible target
951 // links (and recursively their such links) into this graph.
953 void GlobalDSGraph::cloneCalls(DSGraph& Graph) {
954 std::map<const DSNode*, DSNode*> NodeCache;
955 vector<vector<DSNodeHandle> >& FromCalls =Graph.FunctionCalls;
957 FunctionCalls.reserve(FunctionCalls.size() + FromCalls.size());
959 for (int i = 0, ei = FromCalls.size(); i < ei; ++i) {
960 FunctionCalls.push_back(vector<DSNodeHandle>());
961 FunctionCalls.back().reserve(FromCalls[i].size());
962 for (unsigned j = 0, ej = FromCalls[i].size(); j != ej; ++j)
963 FunctionCalls.back().push_back
964 ((FromCalls[i][j] && (FromCalls[i][j]->NodeType & ExternalTypeBits))
965 ? cloneNodeInto(FromCalls[i][j], NodeCache, true)
969 // remove trivially identical function calls
970 removeIdenticalCalls(FunctionCalls, "Globals Graph");