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/iOther.h"
10 #include "llvm/DerivedTypes.h"
11 #include "llvm/Target/TargetData.h"
12 #include "Support/STLExtras.h"
13 #include "Support/Statistic.h"
20 Statistic<> NumFolds("dsnode", "Number of nodes completely folded");
23 namespace DS { // TODO: FIXME
28 //===----------------------------------------------------------------------===//
29 // DSNode Implementation
30 //===----------------------------------------------------------------------===//
32 DSNode::DSNode(enum NodeTy NT, const Type *T)
33 : Ty(Type::VoidTy), Size(0), NodeType(NT) {
34 // Add the type entry if it is specified...
35 if (T) mergeTypeInfo(T, 0);
38 // DSNode copy constructor... do not copy over the referrers list!
39 DSNode::DSNode(const DSNode &N)
40 : Links(N.Links), Globals(N.Globals), Ty(N.Ty), Size(N.Size),
41 NodeType(N.NodeType) {
44 void DSNode::removeReferrer(DSNodeHandle *H) {
45 // Search backwards, because we depopulate the list from the back for
46 // efficiency (because it's a vector).
47 vector<DSNodeHandle*>::reverse_iterator I =
48 std::find(Referrers.rbegin(), Referrers.rend(), H);
49 assert(I != Referrers.rend() && "Referrer not pointing to node!");
50 Referrers.erase(I.base()-1);
53 // addGlobal - Add an entry for a global value to the Globals list. This also
54 // marks the node with the 'G' flag if it does not already have it.
56 void DSNode::addGlobal(GlobalValue *GV) {
57 // Keep the list sorted.
58 vector<GlobalValue*>::iterator I =
59 std::lower_bound(Globals.begin(), Globals.end(), GV);
61 if (I == Globals.end() || *I != GV) {
62 //assert(GV->getType()->getElementType() == Ty);
63 Globals.insert(I, GV);
64 NodeType |= GlobalNode;
68 /// foldNodeCompletely - If we determine that this node has some funny
69 /// behavior happening to it that we cannot represent, we fold it down to a
70 /// single, completely pessimistic, node. This node is represented as a
71 /// single byte with a single TypeEntry of "void".
73 void DSNode::foldNodeCompletely() {
74 if (isNodeCompletelyFolded()) return;
78 // We are no longer typed at all...
79 Ty = DSTypeRec(Type::VoidTy, true);
82 // Loop over all of our referrers, making them point to our zero bytes of
84 for (vector<DSNodeHandle*>::iterator I = Referrers.begin(), E=Referrers.end();
88 // If we have links, merge all of our outgoing links together...
89 for (unsigned i = 1, e = Links.size(); i < e; ++i)
90 Links[0].mergeWith(Links[i]);
94 /// isNodeCompletelyFolded - Return true if this node has been completely
95 /// folded down to something that can never be expanded, effectively losing
96 /// all of the field sensitivity that may be present in the node.
98 bool DSNode::isNodeCompletelyFolded() const {
99 return getSize() == 1 && Ty.Ty == Type::VoidTy && Ty.isArray;
103 /// mergeTypeInfo - This method merges the specified type into the current node
104 /// at the specified offset. This may update the current node's type record if
105 /// this gives more information to the node, it may do nothing to the node if
106 /// this information is already known, or it may merge the node completely (and
107 /// return true) if the information is incompatible with what is already known.
109 /// This method returns true if the node is completely folded, otherwise false.
111 bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset) {
112 // Check to make sure the Size member is up-to-date. Size can be one of the
114 // Size = 0, Ty = Void: Nothing is known about this node.
115 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
116 // Size = 1, Ty = Void, Array = 1: The node is collapsed
117 // Otherwise, sizeof(Ty) = Size
119 assert(((Size == 0 && Ty.Ty == Type::VoidTy && !Ty.isArray) ||
120 (Size == 0 && !Ty.Ty->isSized() && !Ty.isArray) ||
121 (Size == 1 && Ty.Ty == Type::VoidTy && Ty.isArray) ||
122 (Size == 0 && !Ty.Ty->isSized() && !Ty.isArray) ||
123 (TD.getTypeSize(Ty.Ty) == Size)) &&
124 "Size member of DSNode doesn't match the type structure!");
125 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
127 if (Offset == 0 && NewTy == Ty.Ty)
128 return false; // This should be a common case, handle it efficiently
130 // Return true immediately if the node is completely folded.
131 if (isNodeCompletelyFolded()) return true;
133 // Figure out how big the new type we're merging in is...
134 unsigned NewTySize = NewTy->isSized() ? TD.getTypeSize(NewTy) : 0;
136 // Otherwise check to see if we can fold this type into the current node. If
137 // we can't, we fold the node completely, if we can, we potentially update our
140 if (Ty.Ty == Type::VoidTy) {
141 // If this is the first type that this node has seen, just accept it without
143 assert(Offset == 0 && "Cannot have an offset into a void node!");
144 assert(Ty.isArray == false && "This shouldn't happen!");
148 // Calculate the number of outgoing links from this node.
149 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
153 // Handle node expansion case here...
154 if (Offset+NewTySize > Size) {
155 // It is illegal to grow this node if we have treated it as an array of
158 foldNodeCompletely();
162 if (Offset) { // We could handle this case, but we don't for now...
163 DEBUG(std::cerr << "UNIMP: Trying to merge a growth type into "
164 << "offset != 0: Collapsing!\n");
165 foldNodeCompletely();
169 // Okay, the situation is nice and simple, we are trying to merge a type in
170 // at offset 0 that is bigger than our current type. Implement this by
171 // switching to the new type and then merge in the smaller one, which should
172 // hit the other code path here. If the other code path decides it's not
173 // ok, it will collapse the node as appropriate.
175 const Type *OldTy = Ty.Ty;
179 // Must grow links to be the appropriate size...
180 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
182 // Merge in the old type now... which is guaranteed to be smaller than the
184 return mergeTypeInfo(OldTy, 0);
187 assert(Offset <= Size &&
188 "Cannot merge something into a part of our type that doesn't exist!");
190 // Find the section of Ty.Ty that NewTy overlaps with... first we find the
191 // type that starts at offset Offset.
194 const Type *SubType = Ty.Ty;
196 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
198 switch (SubType->getPrimitiveID()) {
199 case Type::StructTyID: {
200 const StructType *STy = cast<StructType>(SubType);
201 const StructLayout &SL = *TD.getStructLayout(STy);
203 unsigned i = 0, e = SL.MemberOffsets.size();
204 for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
207 // The offset we are looking for must be in the i'th element...
208 SubType = STy->getElementTypes()[i];
209 O += SL.MemberOffsets[i];
212 case Type::ArrayTyID: {
213 SubType = cast<ArrayType>(SubType)->getElementType();
214 unsigned ElSize = TD.getTypeSize(SubType);
215 unsigned Remainder = (Offset-O) % ElSize;
216 O = Offset-Remainder;
220 assert(0 && "Unknown type!");
224 assert(O == Offset && "Could not achieve the correct offset!");
226 // If we found our type exactly, early exit
227 if (SubType == NewTy) return false;
229 // Okay, so we found the leader type at the offset requested. Search the list
230 // of types that starts at this offset. If SubType is currently an array or
231 // structure, the type desired may actually be the first element of the
234 unsigned SubTypeSize = SubType->isSized() ? TD.getTypeSize(SubType) : 0;
235 while (SubType != NewTy) {
236 const Type *NextSubType = 0;
237 unsigned NextSubTypeSize;
238 switch (SubType->getPrimitiveID()) {
239 case Type::StructTyID:
240 NextSubType = cast<StructType>(SubType)->getElementTypes()[0];
241 NextSubTypeSize = TD.getTypeSize(SubType);
243 case Type::ArrayTyID:
244 NextSubType = cast<ArrayType>(SubType)->getElementType();
245 NextSubTypeSize = TD.getTypeSize(SubType);
251 if (NextSubType == 0)
252 break; // In the default case, break out of the loop
254 if (NextSubTypeSize < NewTySize)
255 break; // Don't allow shrinking to a smaller type than NewTySize
256 SubType = NextSubType;
257 SubTypeSize = NextSubTypeSize;
260 // If we found the type exactly, return it...
261 if (SubType == NewTy)
264 // Check to see if we have a compatible, but different type...
265 if (NewTySize == SubTypeSize) {
266 // Check to see if this type is obviously convertable... int -> uint f.e.
267 if (NewTy->isLosslesslyConvertableTo(SubType))
270 // Check to see if we have a pointer & integer mismatch going on here,
271 // loading a pointer as a long, for example.
273 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
274 NewTy->isInteger() && isa<PointerType>(SubType))
280 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: " << Ty.Ty
281 << "\n due to:" << NewTy << " @ " << Offset << "!\n"
282 << "SubType: " << SubType << "\n\n");
284 foldNodeCompletely();
290 // addEdgeTo - Add an edge from the current node to the specified node. This
291 // can cause merging of nodes in the graph.
293 void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
294 if (NH.getNode() == 0) return; // Nothing to do
296 DSNodeHandle &ExistingEdge = getLink(Offset);
297 if (ExistingEdge.getNode()) {
298 // Merge the two nodes...
299 ExistingEdge.mergeWith(NH);
300 } else { // No merging to perform...
301 setLink(Offset, NH); // Just force a link in there...
306 // MergeSortedVectors - Efficiently merge a vector into another vector where
307 // duplicates are not allowed and both are sorted. This assumes that 'T's are
308 // efficiently copyable and have sane comparison semantics.
311 void MergeSortedVectors(vector<T> &Dest, const vector<T> &Src) {
312 // By far, the most common cases will be the simple ones. In these cases,
313 // avoid having to allocate a temporary vector...
315 if (Src.empty()) { // Nothing to merge in...
317 } else if (Dest.empty()) { // Just copy the result in...
319 } else if (Src.size() == 1) { // Insert a single element...
321 typename vector<T>::iterator I =
322 std::lower_bound(Dest.begin(), Dest.end(), V);
323 if (I == Dest.end() || *I != Src[0]) // If not already contained...
324 Dest.insert(I, Src[0]);
325 } else if (Dest.size() == 1) {
326 T Tmp = Dest[0]; // Save value in temporary...
327 Dest = Src; // Copy over list...
328 typename vector<T>::iterator I =
329 std::lower_bound(Dest.begin(), Dest.end(),Tmp);
330 if (I == Dest.end() || *I != Src[0]) // If not already contained...
331 Dest.insert(I, Src[0]);
334 // Make a copy to the side of Dest...
337 // Make space for all of the type entries now...
338 Dest.resize(Dest.size()+Src.size());
340 // Merge the two sorted ranges together... into Dest.
341 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
343 // Now erase any duplicate entries that may have accumulated into the
344 // vectors (because they were in both of the input sets)
345 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
350 // mergeWith - Merge this node and the specified node, moving all links to and
351 // from the argument node into the current node, deleting the node argument.
352 // Offset indicates what offset the specified node is to be merged into the
355 // The specified node may be a null pointer (in which case, nothing happens).
357 void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
358 DSNode *N = NH.getNode();
359 if (N == 0 || (N == this && NH.getOffset() == Offset))
363 // We cannot merge two pieces of the same node together, collapse the node
365 DEBUG(std::cerr << "Attempting to merge two chunks of"
366 << " the same node together!\n");
367 foldNodeCompletely();
371 // Merge the type entries of the two nodes together...
372 if (N->Ty.Ty != Type::VoidTy)
373 mergeTypeInfo(N->Ty.Ty, Offset);
375 // If we are merging a node with a completely folded node, then both nodes are
376 // now completely folded.
378 if (isNodeCompletelyFolded()) {
379 if (!N->isNodeCompletelyFolded())
380 N->foldNodeCompletely();
381 } else if (N->isNodeCompletelyFolded()) {
382 foldNodeCompletely();
387 if (this == N || N == 0) return;
389 // If both nodes are not at offset 0, make sure that we are merging the node
390 // at an later offset into the node with the zero offset.
392 if (Offset > NH.getOffset()) {
393 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
395 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
396 // If the offsets are the same, merge the smaller node into the bigger node
397 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
402 std::cerr << "\n\nMerging:\n";
403 N->print(std::cerr, 0);
404 std::cerr << " and:\n";
408 // Now we know that Offset <= NH.Offset, so convert it so our "Offset" (with
409 // respect to NH.Offset) is now zero.
411 unsigned NOffset = NH.getOffset()-Offset;
412 unsigned NSize = N->getSize();
414 // Remove all edges pointing at N, causing them to point to 'this' instead.
415 // Make sure to adjust their offset, not just the node pointer.
417 while (!N->Referrers.empty()) {
418 DSNodeHandle &Ref = *N->Referrers.back();
419 Ref = DSNodeHandle(this, NOffset+Ref.getOffset());
422 // Make all of the outgoing links of N now be outgoing links of this. This
423 // can cause recursive merging!
425 for (unsigned i = 0; i < NSize; i += DS::PointerSize) {
426 DSNodeHandle &Link = N->getLink(i);
427 if (Link.getNode()) {
428 addEdgeTo((i+NOffset) % getSize(), Link);
430 // It's possible that after adding the new edge that some recursive
431 // merging just occured, causing THIS node to get merged into oblivion.
432 // If that happens, we must not try to merge any more edges into it!
434 if (Size == 0) return;
438 // Now that there are no outgoing edges, all of the Links are dead.
441 N->Ty.Ty = Type::VoidTy;
442 N->Ty.isArray = false;
444 // Merge the node types
445 NodeType |= N->NodeType;
446 N->NodeType = 0; // N is now a dead node.
448 // Merge the globals list...
449 if (!N->Globals.empty()) {
450 MergeSortedVectors(Globals, N->Globals);
452 // Delete the globals from the old node...
457 //===----------------------------------------------------------------------===//
458 // DSCallSite Implementation
459 //===----------------------------------------------------------------------===//
461 // Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
462 Function &DSCallSite::getCaller() const {
463 return *Inst->getParent()->getParent();
467 //===----------------------------------------------------------------------===//
468 // DSGraph Implementation
469 //===----------------------------------------------------------------------===//
471 DSGraph::DSGraph(const DSGraph &G) : Func(G.Func) {
472 std::map<const DSNode*, DSNode*> NodeMap;
473 RetNode = cloneInto(G, ScalarMap, NodeMap);
476 DSGraph::DSGraph(const DSGraph &G, std::map<const DSNode*, DSNode*> &NodeMap)
478 RetNode = cloneInto(G, ScalarMap, NodeMap);
481 DSGraph::~DSGraph() {
482 FunctionCalls.clear();
487 // Drop all intra-node references, so that assertions don't fail...
488 std::for_each(Nodes.begin(), Nodes.end(),
489 std::mem_fun(&DSNode::dropAllReferences));
492 // Delete all of the nodes themselves...
493 std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
496 // dump - Allow inspection of graph in a debugger.
497 void DSGraph::dump() const { print(std::cerr); }
500 // Helper function used to clone a function list.
502 static void CopyFunctionCallsList(const vector<DSCallSite>& fromCalls,
503 vector<DSCallSite> &toCalls,
504 std::map<const DSNode*, DSNode*> &NodeMap) {
505 unsigned FC = toCalls.size(); // FirstCall
506 toCalls.reserve(FC+fromCalls.size());
507 for (unsigned i = 0, ei = fromCalls.size(); i != ei; ++i)
508 toCalls.push_back(DSCallSite(fromCalls[i], NodeMap));
511 /// remapLinks - Change all of the Links in the current node according to the
512 /// specified mapping.
514 void DSNode::remapLinks(std::map<const DSNode*, DSNode*> &OldNodeMap) {
515 for (unsigned i = 0, e = Links.size(); i != e; ++i)
516 Links[i].setNode(OldNodeMap[Links[i].getNode()]);
520 // cloneInto - Clone the specified DSGraph into the current graph, returning the
521 // Return node of the graph. The translated ScalarMap for the old function is
522 // filled into the OldValMap member. If StripAllocas is set to true, Alloca
523 // markers are removed from the graph, as the graph is being cloned into a
524 // calling function's graph.
526 DSNodeHandle DSGraph::cloneInto(const DSGraph &G,
527 std::map<Value*, DSNodeHandle> &OldValMap,
528 std::map<const DSNode*, DSNode*> &OldNodeMap,
530 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
532 unsigned FN = Nodes.size(); // First new node...
534 // Duplicate all of the nodes, populating the node map...
535 Nodes.reserve(FN+G.Nodes.size());
536 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
537 DSNode *Old = G.Nodes[i];
538 DSNode *New = new DSNode(*Old);
539 Nodes.push_back(New);
540 OldNodeMap[Old] = New;
543 // Rewrite the links in the new nodes to point into the current graph now.
544 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
545 Nodes[i]->remapLinks(OldNodeMap);
547 // Remove local markers as specified
548 unsigned char StripBits = StripAllocas ? DSNode::AllocaNode : 0;
550 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
551 Nodes[i]->NodeType &= ~StripBits;
553 // Copy the value map... and merge all of the global nodes...
554 for (std::map<Value*, DSNodeHandle>::const_iterator I = G.ScalarMap.begin(),
555 E = G.ScalarMap.end(); I != E; ++I) {
556 DSNodeHandle &H = OldValMap[I->first];
557 H.setNode(OldNodeMap[I->second.getNode()]);
558 H.setOffset(I->second.getOffset());
560 if (isa<GlobalValue>(I->first)) { // Is this a global?
561 std::map<Value*, DSNodeHandle>::iterator GVI = ScalarMap.find(I->first);
562 if (GVI != ScalarMap.end()) { // Is the global value in this fn already?
563 GVI->second.mergeWith(H);
565 ScalarMap[I->first] = H; // Add global pointer to this graph
569 // Copy the function calls list...
570 CopyFunctionCallsList(G.FunctionCalls, FunctionCalls, OldNodeMap);
573 // Return the returned node pointer...
574 return DSNodeHandle(OldNodeMap[G.RetNode.getNode()], G.RetNode.getOffset());
577 /// mergeInGraph - The method is used for merging graphs together. If the
578 /// argument graph is not *this, it makes a clone of the specified graph, then
579 /// merges the nodes specified in the call site with the formal arguments in the
582 void DSGraph::mergeInGraph(DSCallSite &CS, const DSGraph &Graph,
584 std::map<Value*, DSNodeHandle> OldValMap;
586 std::map<Value*, DSNodeHandle> *ScalarMap = &OldValMap;
588 // If this is not a recursive call, clone the graph into this graph...
589 if (&Graph != this) {
590 // Clone the callee's graph into the current graph, keeping
591 // track of where scalars in the old graph _used_ to point,
592 // and of the new nodes matching nodes of the old graph.
593 std::map<const DSNode*, DSNode*> OldNodeMap;
595 // The clone call may invalidate any of the vectors in the data
596 // structure graph. Strip locals and don't copy the list of callers
597 RetVal = cloneInto(Graph, OldValMap, OldNodeMap, StripAllocas);
598 ScalarMap = &OldValMap;
600 RetVal = getRetNode();
601 ScalarMap = &getScalarMap();
604 // Merge the return value with the return value of the context...
605 RetVal.mergeWith(CS.getRetVal());
607 // Resolve all of the function arguments...
608 Function &F = Graph.getFunction();
609 Function::aiterator AI = F.abegin();
610 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
611 // Advance the argument iterator to the first pointer argument...
612 while (!isPointerType(AI->getType())) {
616 std::cerr << "Bad call to Function: " << F.getName() << "\n";
618 assert(AI != F.aend() && "# Args provided is not # Args required!");
621 // Add the link from the argument scalar to the provided value
622 DSNodeHandle &NH = (*ScalarMap)[AI];
623 assert(NH.getNode() && "Pointer argument without scalarmap entry?");
624 NH.mergeWith(CS.getPtrArg(i));
629 // cloneGlobalInto - Clone the given global node and all its target links
630 // (and all their llinks, recursively).
632 DSNode *DSGraph::cloneGlobalInto(const DSNode *GNode) {
633 if (GNode == 0 || GNode->getGlobals().size() == 0) return 0;
635 // If a clone has already been created for GNode, return it.
636 DSNodeHandle& ValMapEntry = ScalarMap[GNode->getGlobals()[0]];
637 if (ValMapEntry != 0)
640 // Clone the node and update the ValMap.
641 DSNode* NewNode = new DSNode(*GNode);
642 ValMapEntry = NewNode; // j=0 case of loop below!
643 Nodes.push_back(NewNode);
644 for (unsigned j = 1, N = NewNode->getGlobals().size(); j < N; ++j)
645 ScalarMap[NewNode->getGlobals()[j]] = NewNode;
647 // Rewrite the links in the new node to point into the current graph.
648 for (unsigned j = 0, e = GNode->getNumLinks(); j != e; ++j)
649 NewNode->setLink(j, cloneGlobalInto(GNode->getLink(j)));
656 // markIncompleteNodes - Mark the specified node as having contents that are not
657 // known with the current analysis we have performed. Because a node makes all
658 // of the nodes it can reach imcomplete if the node itself is incomplete, we
659 // must recursively traverse the data structure graph, marking all reachable
660 // nodes as incomplete.
662 static void markIncompleteNode(DSNode *N) {
663 // Stop recursion if no node, or if node already marked...
664 if (N == 0 || (N->NodeType & DSNode::Incomplete)) return;
666 // Actually mark the node
667 N->NodeType |= DSNode::Incomplete;
669 // Recusively process children...
670 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
671 if (DSNode *DSN = N->getLink(i).getNode())
672 markIncompleteNode(DSN);
676 // markIncompleteNodes - Traverse the graph, identifying nodes that may be
677 // modified by other functions that have not been resolved yet. This marks
678 // nodes that are reachable through three sources of "unknownness":
680 // Global Variables, Function Calls, and Incoming Arguments
682 // For any node that may have unknown components (because something outside the
683 // scope of current analysis may have modified it), the 'Incomplete' flag is
684 // added to the NodeType.
686 void DSGraph::markIncompleteNodes(bool markFormalArgs) {
687 // Mark any incoming arguments as incomplete...
688 if (markFormalArgs && Func)
689 for (Function::aiterator I = Func->abegin(), E = Func->aend(); I != E; ++I)
690 if (isPointerType(I->getType()) && ScalarMap.find(I) != ScalarMap.end())
691 markIncompleteNode(ScalarMap[I].getNode());
693 // Mark stuff passed into functions calls as being incomplete...
694 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
695 DSCallSite &Call = FunctionCalls[i];
696 // Then the return value is certainly incomplete!
697 markIncompleteNode(Call.getRetVal().getNode());
699 // All objects pointed to by function arguments are incomplete though!
700 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
701 markIncompleteNode(Call.getPtrArg(i).getNode());
704 // Mark all of the nodes pointed to by global nodes as incomplete...
705 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
706 if (Nodes[i]->NodeType & DSNode::GlobalNode) {
707 DSNode *N = Nodes[i];
708 // FIXME: Make more efficient by looking over Links directly
709 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
710 if (DSNode *DSN = N->getLink(i).getNode())
711 markIncompleteNode(DSN);
715 // removeRefsToGlobal - Helper function that removes globals from the
716 // ScalarMap so that the referrer count will go down to zero.
717 static void removeRefsToGlobal(DSNode* N,
718 std::map<Value*, DSNodeHandle> &ScalarMap) {
719 while (!N->getGlobals().empty()) {
720 GlobalValue *GV = N->getGlobals().back();
721 N->getGlobals().pop_back();
727 // isNodeDead - This method checks to see if a node is dead, and if it isn't, it
728 // checks to see if there are simple transformations that it can do to make it
731 bool DSGraph::isNodeDead(DSNode *N) {
732 // Is it a trivially dead shadow node...
733 if (N->getReferrers().empty() && N->NodeType == 0)
736 // Is it a function node or some other trivially unused global?
737 if ((N->NodeType & ~DSNode::GlobalNode) == 0 && N->getSize() == 0 &&
738 N->getReferrers().size() == N->getGlobals().size()) {
740 // Remove the globals from the ScalarMap, so that the referrer count will go
742 removeRefsToGlobal(N, ScalarMap);
743 assert(N->getReferrers().empty() && "Referrers should all be gone now!");
750 static void removeIdenticalCalls(vector<DSCallSite> &Calls,
751 const std::string &where) {
752 // Remove trivially identical function calls
753 unsigned NumFns = Calls.size();
754 std::sort(Calls.begin(), Calls.end());
755 Calls.erase(std::unique(Calls.begin(), Calls.end()),
758 DEBUG(if (NumFns != Calls.size())
759 std::cerr << "Merged " << (NumFns-Calls.size())
760 << " call nodes in " << where << "\n";);
763 // removeTriviallyDeadNodes - After the graph has been constructed, this method
764 // removes all unreachable nodes that are created because they got merged with
765 // other nodes in the graph. These nodes will all be trivially unreachable, so
766 // we don't have to perform any non-trivial analysis here.
768 void DSGraph::removeTriviallyDeadNodes(bool KeepAllGlobals) {
769 for (unsigned i = 0; i != Nodes.size(); ++i)
770 if (!KeepAllGlobals || !(Nodes[i]->NodeType & DSNode::GlobalNode))
771 if (isNodeDead(Nodes[i])) { // This node is dead!
772 delete Nodes[i]; // Free memory...
773 Nodes.erase(Nodes.begin()+i--); // Remove from node list...
776 removeIdenticalCalls(FunctionCalls, Func ? Func->getName() : "");
780 // markAlive - Simple graph walker that recursively traverses the graph, marking
781 // stuff to be alive.
783 static void markAlive(DSNode *N, std::set<DSNode*> &Alive) {
787 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
788 if (DSNode *DSN = N->getLink(i).getNode())
789 if (!Alive.count(DSN))
790 markAlive(DSN, Alive);
793 static bool checkGlobalAlive(DSNode *N, std::set<DSNode*> &Alive,
794 std::set<DSNode*> &Visiting) {
795 if (N == 0) return false;
797 if (Visiting.count(N)) return false; // terminate recursion on a cycle
800 // If any immediate successor is alive, N is alive
801 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
802 if (DSNode *DSN = N->getLink(i).getNode())
803 if (Alive.count(DSN)) {
808 // Else if any successor reaches a live node, N is alive
809 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
810 if (DSNode *DSN = N->getLink(i).getNode())
811 if (checkGlobalAlive(DSN, Alive, Visiting)) {
812 Visiting.erase(N); return true;
820 // markGlobalsIteration - Recursive helper function for markGlobalsAlive().
821 // This would be unnecessary if function calls were real nodes! In that case,
822 // the simple iterative loop in the first few lines below suffice.
824 static void markGlobalsIteration(std::set<DSNode*>& GlobalNodes,
825 vector<DSCallSite> &Calls,
826 std::set<DSNode*> &Alive,
829 // Iterate, marking globals or cast nodes alive until no new live nodes
830 // are added to Alive
831 std::set<DSNode*> Visiting; // Used to identify cycles
832 std::set<DSNode*>::iterator I = GlobalNodes.begin(), E = GlobalNodes.end();
833 for (size_t liveCount = 0; liveCount < Alive.size(); ) {
834 liveCount = Alive.size();
836 if (Alive.count(*I) == 0) {
838 if (checkGlobalAlive(*I, Alive, Visiting))
839 markAlive(*I, Alive);
843 // Find function calls with some dead and some live nodes.
844 // Since all call nodes must be live if any one is live, we have to mark
845 // all nodes of the call as live and continue the iteration (via recursion).
847 bool Recurse = false;
848 for (unsigned i = 0, ei = Calls.size(); i < ei; ++i) {
849 bool CallIsDead = true, CallHasDeadArg = false;
850 DSCallSite &CS = Calls[i];
851 for (unsigned j = 0, ej = CS.getNumPtrArgs(); j != ej; ++j)
852 if (DSNode *N = CS.getPtrArg(j).getNode()) {
853 bool ArgIsDead = !Alive.count(N);
854 CallHasDeadArg |= ArgIsDead;
855 CallIsDead &= ArgIsDead;
858 if (DSNode *N = CS.getRetVal().getNode()) {
859 bool RetIsDead = !Alive.count(N);
860 CallHasDeadArg |= RetIsDead;
861 CallIsDead &= RetIsDead;
864 DSNode *N = CS.getCallee().getNode();
865 bool FnIsDead = !Alive.count(N);
866 CallHasDeadArg |= FnIsDead;
867 CallIsDead &= FnIsDead;
869 if (!CallIsDead && CallHasDeadArg) {
870 // Some node in this call is live and another is dead.
871 // Mark all nodes of call as live and iterate once more.
873 for (unsigned j = 0, ej = CS.getNumPtrArgs(); j != ej; ++j)
874 markAlive(CS.getPtrArg(j).getNode(), Alive);
875 markAlive(CS.getRetVal().getNode(), Alive);
876 markAlive(CS.getCallee().getNode(), Alive);
880 markGlobalsIteration(GlobalNodes, Calls, Alive, FilterCalls);
885 // markGlobalsAlive - Mark global nodes and cast nodes alive if they
886 // can reach any other live node. Since this can produce new live nodes,
887 // we use a simple iterative algorithm.
889 static void markGlobalsAlive(DSGraph &G, std::set<DSNode*> &Alive,
891 // Add global and cast nodes to a set so we don't walk all nodes every time
892 std::set<DSNode*> GlobalNodes;
893 for (unsigned i = 0, e = G.getNodes().size(); i != e; ++i)
894 if (G.getNodes()[i]->NodeType & DSNode::GlobalNode)
895 GlobalNodes.insert(G.getNodes()[i]);
897 // Add all call nodes to the same set
898 vector<DSCallSite> &Calls = G.getFunctionCalls();
900 for (unsigned i = 0, e = Calls.size(); i != e; ++i) {
901 for (unsigned j = 0, e = Calls[i].getNumPtrArgs(); j != e; ++j)
902 if (DSNode *N = Calls[i].getPtrArg(j).getNode())
903 GlobalNodes.insert(N);
904 if (DSNode *N = Calls[i].getRetVal().getNode())
905 GlobalNodes.insert(N);
906 if (DSNode *N = Calls[i].getCallee().getNode())
907 GlobalNodes.insert(N);
911 // Iterate and recurse until no new live node are discovered.
912 // This would be a simple iterative loop if function calls were real nodes!
913 markGlobalsIteration(GlobalNodes, Calls, Alive, FilterCalls);
915 // Free up references to dead globals from the ScalarMap
916 std::set<DSNode*>::iterator I = GlobalNodes.begin(), E = GlobalNodes.end();
918 if (Alive.count(*I) == 0)
919 removeRefsToGlobal(*I, G.getScalarMap());
921 // Delete dead function calls
923 for (int ei = Calls.size(), i = ei-1; i >= 0; --i) {
924 bool CallIsDead = true;
925 for (unsigned j = 0, ej = Calls[i].getNumPtrArgs();
926 CallIsDead && j != ej; ++j)
927 CallIsDead = Alive.count(Calls[i].getPtrArg(j).getNode()) == 0;
929 Calls.erase(Calls.begin() + i); // remove the call entirely
933 // removeDeadNodes - Use a more powerful reachability analysis to eliminate
934 // subgraphs that are unreachable. This often occurs because the data
935 // structure doesn't "escape" into it's caller, and thus should be eliminated
936 // from the caller's graph entirely. This is only appropriate to use when
939 void DSGraph::removeDeadNodes(bool KeepAllGlobals, bool KeepCalls) {
940 assert((!KeepAllGlobals || KeepCalls) &&
941 "KeepAllGlobals without KeepCalls is meaningless");
943 // Reduce the amount of work we have to do...
944 removeTriviallyDeadNodes(KeepAllGlobals);
946 // FIXME: Merge nontrivially identical call nodes...
948 // Alive - a set that holds all nodes found to be reachable/alive.
949 std::set<DSNode*> Alive;
951 // If KeepCalls, mark all nodes reachable by call nodes as alive...
953 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
954 for (unsigned j = 0, e = FunctionCalls[i].getNumPtrArgs(); j != e; ++j)
955 markAlive(FunctionCalls[i].getPtrArg(j).getNode(), Alive);
956 markAlive(FunctionCalls[i].getRetVal().getNode(), Alive);
957 markAlive(FunctionCalls[i].getCallee().getNode(), Alive);
960 // Mark all nodes reachable by scalar nodes as alive...
961 for (std::map<Value*, DSNodeHandle>::iterator I = ScalarMap.begin(),
962 E = ScalarMap.end(); I != E; ++I)
963 markAlive(I->second.getNode(), Alive);
966 // Marge all nodes reachable by global nodes, as alive. Isn't this covered by
970 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
971 if (Nodes[i]->NodeType & DSNode::GlobalNode)
972 markAlive(Nodes[i], Alive);
975 // The return value is alive as well...
976 markAlive(RetNode.getNode(), Alive);
978 // Mark all globals or cast nodes that can reach a live node as alive.
979 // This also marks all nodes reachable from such nodes as alive.
980 // Of course, if KeepAllGlobals is specified, they would be live already.
982 markGlobalsAlive(*this, Alive, !KeepCalls);
984 // Loop over all unreachable nodes, dropping their references...
985 vector<DSNode*> DeadNodes;
986 DeadNodes.reserve(Nodes.size()); // Only one allocation is allowed.
987 for (unsigned i = 0; i != Nodes.size(); ++i)
988 if (!Alive.count(Nodes[i])) {
989 DSNode *N = Nodes[i];
990 Nodes.erase(Nodes.begin()+i--); // Erase node from alive list.
991 DeadNodes.push_back(N); // Add node to our list of dead nodes
992 N->dropAllReferences(); // Drop all outgoing edges
995 // Delete all dead nodes...
996 std::for_each(DeadNodes.begin(), DeadNodes.end(), deleter<DSNode>);
1001 // maskNodeTypes - Apply a mask to all of the node types in the graph. This
1002 // is useful for clearing out markers like Scalar or Incomplete.
1004 void DSGraph::maskNodeTypes(unsigned char Mask) {
1005 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
1006 Nodes[i]->NodeType &= Mask;
1011 //===----------------------------------------------------------------------===//
1012 // GlobalDSGraph Implementation
1013 //===----------------------------------------------------------------------===//
1015 GlobalDSGraph::GlobalDSGraph() : DSGraph(*(Function*)0, this) {
1018 GlobalDSGraph::~GlobalDSGraph() {
1019 assert(Referrers.size() == 0 &&
1020 "Deleting global graph while references from other graphs exist");
1023 void GlobalDSGraph::addReference(const DSGraph* referrer) {
1024 if (referrer != this)
1025 Referrers.insert(referrer);
1028 void GlobalDSGraph::removeReference(const DSGraph* referrer) {
1029 if (referrer != this) {
1030 assert(Referrers.find(referrer) != Referrers.end() && "This is very bad!");
1031 Referrers.erase(referrer);
1032 if (Referrers.size() == 0)
1038 // Bits used in the next function
1039 static const char ExternalTypeBits = DSNode::GlobalNode | DSNode::HeapNode;
1042 // GlobalDSGraph::cloneNodeInto - Clone a global node and all its externally
1043 // visible target links (and recursively their such links) into this graph.
1044 // NodeCache maps the node being cloned to its clone in the Globals graph,
1045 // in order to track cycles.
1046 // GlobalsAreFinal is a flag that says whether it is safe to assume that
1047 // an existing global node is complete. This is important to avoid
1048 // reinserting all globals when inserting Calls to functions.
1049 // This is a helper function for cloneGlobals and cloneCalls.
1051 DSNode* GlobalDSGraph::cloneNodeInto(DSNode *OldNode,
1052 std::map<const DSNode*, DSNode*> &NodeCache,
1053 bool GlobalsAreFinal) {
1054 if (OldNode == 0) return 0;
1056 // The caller should check this is an external node. Just more efficient...
1057 assert((OldNode->NodeType & ExternalTypeBits) && "Non-external node");
1059 // If a clone has already been created for OldNode, return it.
1060 DSNode*& CacheEntry = NodeCache[OldNode];
1061 if (CacheEntry != 0)
1064 // The result value...
1065 DSNode* NewNode = 0;
1067 // If nodes already exist for any of the globals of OldNode,
1068 // merge all such nodes together since they are merged in OldNode.
1069 // If ValueCacheIsFinal==true, look for an existing node that has
1070 // an identical list of globals and return it if it exists.
1072 for (unsigned j = 0, N = OldNode->getGlobals().size(); j != N; ++j)
1073 if (DSNode *PrevNode = ScalarMap[OldNode->getGlobals()[j]].getNode()) {
1075 NewNode = PrevNode; // first existing node found
1076 if (GlobalsAreFinal && j == 0)
1077 if (OldNode->getGlobals() == PrevNode->getGlobals()) {
1078 CacheEntry = NewNode;
1082 else if (NewNode != PrevNode) { // found another, different from prev
1083 // update ValMap *before* merging PrevNode into NewNode
1084 for (unsigned k = 0, NK = PrevNode->getGlobals().size(); k < NK; ++k)
1085 ScalarMap[PrevNode->getGlobals()[k]] = NewNode;
1086 NewNode->mergeWith(PrevNode);
1088 } else if (NewNode != 0) {
1089 ScalarMap[OldNode->getGlobals()[j]] = NewNode; // add the merged node
1092 // If no existing node was found, clone the node and update the ValMap.
1094 NewNode = new DSNode(*OldNode);
1095 Nodes.push_back(NewNode);
1096 for (unsigned j = 0, e = NewNode->getNumLinks(); j != e; ++j)
1097 NewNode->setLink(j, 0);
1098 for (unsigned j = 0, N = NewNode->getGlobals().size(); j < N; ++j)
1099 ScalarMap[NewNode->getGlobals()[j]] = NewNode;
1102 NewNode->NodeType |= OldNode->NodeType; // Markers may be different!
1104 // Add the entry to NodeCache
1105 CacheEntry = NewNode;
1107 // Rewrite the links in the new node to point into the current graph,
1108 // but only for links to external nodes. Set other links to NULL.
1109 for (unsigned j = 0, e = OldNode->getNumLinks(); j != e; ++j) {
1110 DSNode* OldTarget = OldNode->getLink(j);
1111 if (OldTarget && (OldTarget->NodeType & ExternalTypeBits)) {
1112 DSNode* NewLink = this->cloneNodeInto(OldTarget, NodeCache);
1113 if (NewNode->getLink(j))
1114 NewNode->getLink(j)->mergeWith(NewLink);
1116 NewNode->setLink(j, NewLink);
1120 // Remove all local markers
1121 NewNode->NodeType &= ~(DSNode::AllocaNode | DSNode::ScalarNode);
1127 // GlobalDSGraph::cloneGlobals - Clone global nodes and all their externally
1128 // visible target links (and recursively their such links) into this graph.
1130 void GlobalDSGraph::cloneGlobals(DSGraph& Graph, bool CloneCalls) {
1131 std::map<const DSNode*, DSNode*> NodeCache;
1133 for (unsigned i = 0, N = Graph.Nodes.size(); i < N; ++i)
1134 if (Graph.Nodes[i]->NodeType & DSNode::GlobalNode)
1135 GlobalsGraph->cloneNodeInto(Graph.Nodes[i], NodeCache, false);
1137 GlobalsGraph->cloneCalls(Graph);
1139 GlobalsGraph->removeDeadNodes(/*KeepAllGlobals*/ true, /*KeepCalls*/ true);
1144 // GlobalDSGraph::cloneCalls - Clone function calls and their visible target
1145 // links (and recursively their such links) into this graph.
1147 void GlobalDSGraph::cloneCalls(DSGraph& Graph) {
1148 std::map<const DSNode*, DSNode*> NodeCache;
1149 vector<DSCallSite >& FromCalls =Graph.FunctionCalls;
1151 FunctionCalls.reserve(FunctionCalls.size() + FromCalls.size());
1153 for (int i = 0, ei = FromCalls.size(); i < ei; ++i) {
1154 DSCallSite& callCopy = FunctionCalls.back();
1155 callCopy.reserve(FromCalls[i].size());
1156 for (unsigned j = 0, ej = FromCalls[i].size(); j != ej; ++j)
1158 ((FromCalls[i][j] && (FromCalls[i][j]->NodeType & ExternalTypeBits))
1159 ? cloneNodeInto(FromCalls[i][j], NodeCache, true)
1163 // remove trivially identical function calls
1164 removeIdenticalCalls(FunctionCalls, "Globals Graph");