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"
14 #include "Support/Timer.h"
21 Statistic<> NumFolds ("dsnode", "Number of nodes completely folded");
22 Statistic<> NumCallNodesMerged("dsnode", "Number of call nodes merged");
25 namespace DS { // TODO: FIXME
30 //===----------------------------------------------------------------------===//
31 // DSNode Implementation
32 //===----------------------------------------------------------------------===//
34 DSNode::DSNode(enum NodeTy NT, const Type *T)
35 : Ty(Type::VoidTy), Size(0), NodeType(NT) {
36 // Add the type entry if it is specified...
37 if (T) mergeTypeInfo(T, 0);
40 // DSNode copy constructor... do not copy over the referrers list!
41 DSNode::DSNode(const DSNode &N)
42 : Links(N.Links), Globals(N.Globals), Ty(N.Ty), Size(N.Size),
43 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;
70 /// foldNodeCompletely - If we determine that this node has some funny
71 /// behavior happening to it that we cannot represent, we fold it down to a
72 /// single, completely pessimistic, node. This node is represented as a
73 /// single byte with a single TypeEntry of "void".
75 void DSNode::foldNodeCompletely() {
76 if (isNodeCompletelyFolded()) return;
80 // We are no longer typed at all...
85 // Loop over all of our referrers, making them point to our zero bytes of
87 for (vector<DSNodeHandle*>::iterator I = Referrers.begin(), E=Referrers.end();
91 // If we have links, merge all of our outgoing links together...
92 for (unsigned i = 1, e = Links.size(); i < e; ++i)
93 Links[0].mergeWith(Links[i]);
97 /// isNodeCompletelyFolded - Return true if this node has been completely
98 /// folded down to something that can never be expanded, effectively losing
99 /// all of the field sensitivity that may be present in the node.
101 bool DSNode::isNodeCompletelyFolded() const {
102 return getSize() == 1 && Ty == Type::VoidTy && isArray();
106 /// mergeTypeInfo - This method merges the specified type into the current node
107 /// at the specified offset. This may update the current node's type record if
108 /// this gives more information to the node, it may do nothing to the node if
109 /// this information is already known, or it may merge the node completely (and
110 /// return true) if the information is incompatible with what is already known.
112 /// This method returns true if the node is completely folded, otherwise false.
114 bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset) {
115 // Check to make sure the Size member is up-to-date. Size can be one of the
117 // Size = 0, Ty = Void: Nothing is known about this node.
118 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
119 // Size = 1, Ty = Void, Array = 1: The node is collapsed
120 // Otherwise, sizeof(Ty) = Size
122 assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
123 (Size == 0 && !Ty->isSized() && !isArray()) ||
124 (Size == 1 && Ty == Type::VoidTy && isArray()) ||
125 (Size == 0 && !Ty->isSized() && !isArray()) ||
126 (TD.getTypeSize(Ty) == Size)) &&
127 "Size member of DSNode doesn't match the type structure!");
128 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
130 if (Offset == 0 && NewTy == Ty)
131 return false; // This should be a common case, handle it efficiently
133 // Return true immediately if the node is completely folded.
134 if (isNodeCompletelyFolded()) return true;
136 // If this is an array type, eliminate the outside arrays because they won't
137 // be used anyway. This greatly reduces the size of large static arrays used
138 // as global variables, for example.
140 bool WillBeArray = false;
141 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
142 // FIXME: we might want to keep small arrays, but must be careful about
143 // things like: [2 x [10000 x int*]]
144 NewTy = AT->getElementType();
148 // Figure out how big the new type we're merging in is...
149 unsigned NewTySize = NewTy->isSized() ? TD.getTypeSize(NewTy) : 0;
151 // Otherwise check to see if we can fold this type into the current node. If
152 // we can't, we fold the node completely, if we can, we potentially update our
155 if (Ty == Type::VoidTy) {
156 // If this is the first type that this node has seen, just accept it without
158 assert(Offset == 0 && "Cannot have an offset into a void node!");
159 assert(!isArray() && "This shouldn't happen!");
162 if (WillBeArray) NodeType |= Array;
165 // Calculate the number of outgoing links from this node.
166 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
170 // Handle node expansion case here...
171 if (Offset+NewTySize > Size) {
172 // It is illegal to grow this node if we have treated it as an array of
175 foldNodeCompletely();
179 if (Offset) { // We could handle this case, but we don't for now...
180 DEBUG(std::cerr << "UNIMP: Trying to merge a growth type into "
181 << "offset != 0: Collapsing!\n");
182 foldNodeCompletely();
186 // Okay, the situation is nice and simple, we are trying to merge a type in
187 // at offset 0 that is bigger than our current type. Implement this by
188 // switching to the new type and then merge in the smaller one, which should
189 // hit the other code path here. If the other code path decides it's not
190 // ok, it will collapse the node as appropriate.
192 const Type *OldTy = Ty;
195 if (WillBeArray) NodeType |= Array;
198 // Must grow links to be the appropriate size...
199 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
201 // Merge in the old type now... which is guaranteed to be smaller than the
203 return mergeTypeInfo(OldTy, 0);
206 assert(Offset <= Size &&
207 "Cannot merge something into a part of our type that doesn't exist!");
209 // Find the section of Ty that NewTy overlaps with... first we find the
210 // type that starts at offset Offset.
213 const Type *SubType = Ty;
215 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
217 switch (SubType->getPrimitiveID()) {
218 case Type::StructTyID: {
219 const StructType *STy = cast<StructType>(SubType);
220 const StructLayout &SL = *TD.getStructLayout(STy);
222 unsigned i = 0, e = SL.MemberOffsets.size();
223 for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
226 // The offset we are looking for must be in the i'th element...
227 SubType = STy->getElementTypes()[i];
228 O += SL.MemberOffsets[i];
231 case Type::ArrayTyID: {
232 SubType = cast<ArrayType>(SubType)->getElementType();
233 unsigned ElSize = TD.getTypeSize(SubType);
234 unsigned Remainder = (Offset-O) % ElSize;
235 O = Offset-Remainder;
239 assert(0 && "Unknown type!");
243 assert(O == Offset && "Could not achieve the correct offset!");
245 // If we found our type exactly, early exit
246 if (SubType == NewTy) return false;
248 // Okay, so we found the leader type at the offset requested. Search the list
249 // of types that starts at this offset. If SubType is currently an array or
250 // structure, the type desired may actually be the first element of the
253 unsigned SubTypeSize = SubType->isSized() ? TD.getTypeSize(SubType) : 0;
254 unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
255 while (SubType != NewTy) {
256 const Type *NextSubType = 0;
257 unsigned NextSubTypeSize = 0;
258 unsigned NextPadSize = 0;
259 switch (SubType->getPrimitiveID()) {
260 case Type::StructTyID: {
261 const StructType *STy = cast<StructType>(SubType);
262 const StructLayout &SL = *TD.getStructLayout(STy);
263 if (SL.MemberOffsets.size() > 1)
264 NextPadSize = SL.MemberOffsets[1];
266 NextPadSize = SubTypeSize;
267 NextSubType = STy->getElementTypes()[0];
268 NextSubTypeSize = TD.getTypeSize(NextSubType);
271 case Type::ArrayTyID:
272 NextSubType = cast<ArrayType>(SubType)->getElementType();
273 NextSubTypeSize = TD.getTypeSize(NextSubType);
274 NextPadSize = NextSubTypeSize;
280 if (NextSubType == 0)
281 break; // In the default case, break out of the loop
283 if (NextPadSize < NewTySize)
284 break; // Don't allow shrinking to a smaller type than NewTySize
285 SubType = NextSubType;
286 SubTypeSize = NextSubTypeSize;
287 PadSize = NextPadSize;
290 // If we found the type exactly, return it...
291 if (SubType == NewTy)
294 // Check to see if we have a compatible, but different type...
295 if (NewTySize == SubTypeSize) {
296 // Check to see if this type is obviously convertable... int -> uint f.e.
297 if (NewTy->isLosslesslyConvertableTo(SubType))
300 // Check to see if we have a pointer & integer mismatch going on here,
301 // loading a pointer as a long, for example.
303 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
304 NewTy->isInteger() && isa<PointerType>(SubType))
306 } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
307 // We are accessing the field, plus some structure padding. Ignore the
308 // structure padding.
313 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: " << Ty
314 << "\n due to:" << NewTy << " @ " << Offset << "!\n"
315 << "SubType: " << SubType << "\n\n");
317 foldNodeCompletely();
323 // addEdgeTo - Add an edge from the current node to the specified node. This
324 // can cause merging of nodes in the graph.
326 void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
327 if (NH.getNode() == 0) return; // Nothing to do
329 DSNodeHandle &ExistingEdge = getLink(Offset);
330 if (ExistingEdge.getNode()) {
331 // Merge the two nodes...
332 ExistingEdge.mergeWith(NH);
333 } else { // No merging to perform...
334 setLink(Offset, NH); // Just force a link in there...
339 // MergeSortedVectors - Efficiently merge a vector into another vector where
340 // duplicates are not allowed and both are sorted. This assumes that 'T's are
341 // efficiently copyable and have sane comparison semantics.
343 static void MergeSortedVectors(vector<GlobalValue*> &Dest,
344 const vector<GlobalValue*> &Src) {
345 // By far, the most common cases will be the simple ones. In these cases,
346 // avoid having to allocate a temporary vector...
348 if (Src.empty()) { // Nothing to merge in...
350 } else if (Dest.empty()) { // Just copy the result in...
352 } else if (Src.size() == 1) { // Insert a single element...
353 const GlobalValue *V = Src[0];
354 vector<GlobalValue*>::iterator I =
355 std::lower_bound(Dest.begin(), Dest.end(), V);
356 if (I == Dest.end() || *I != Src[0]) // If not already contained...
357 Dest.insert(I, Src[0]);
358 } else if (Dest.size() == 1) {
359 GlobalValue *Tmp = Dest[0]; // Save value in temporary...
360 Dest = Src; // Copy over list...
361 vector<GlobalValue*>::iterator I =
362 std::lower_bound(Dest.begin(), Dest.end(), Tmp);
363 if (I == Dest.end() || *I != Tmp) // If not already contained...
367 // Make a copy to the side of Dest...
368 vector<GlobalValue*> Old(Dest);
370 // Make space for all of the type entries now...
371 Dest.resize(Dest.size()+Src.size());
373 // Merge the two sorted ranges together... into Dest.
374 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
376 // Now erase any duplicate entries that may have accumulated into the
377 // vectors (because they were in both of the input sets)
378 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
383 // mergeWith - Merge this node and the specified node, moving all links to and
384 // from the argument node into the current node, deleting the node argument.
385 // Offset indicates what offset the specified node is to be merged into the
388 // The specified node may be a null pointer (in which case, nothing happens).
390 void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
391 DSNode *N = NH.getNode();
392 if (N == 0 || (N == this && NH.getOffset() == Offset))
395 assert((N->NodeType & DSNode::DEAD) == 0);
396 assert((NodeType & DSNode::DEAD) == 0);
397 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
400 // We cannot merge two pieces of the same node together, collapse the node
402 DEBUG(std::cerr << "Attempting to merge two chunks of"
403 << " the same node together!\n");
404 foldNodeCompletely();
408 // If both nodes are not at offset 0, make sure that we are merging the node
409 // at an later offset into the node with the zero offset.
411 if (Offset < NH.getOffset()) {
412 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
414 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
415 // If the offsets are the same, merge the smaller node into the bigger node
416 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
420 // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
421 // respect to NH.Offset) is now zero. NOffset is the distance from the base
422 // of our object that N starts from.
424 unsigned NOffset = Offset-NH.getOffset();
425 unsigned NSize = N->getSize();
427 // Merge the type entries of the two nodes together...
428 if (N->Ty != Type::VoidTy) {
429 mergeTypeInfo(N->Ty, NOffset);
431 // mergeTypeInfo can cause collapsing, which can cause this node to become
433 if (hasNoReferrers()) return;
435 assert((NodeType & DSNode::DEAD) == 0);
437 // If we are merging a node with a completely folded node, then both nodes are
438 // now completely folded.
440 if (isNodeCompletelyFolded()) {
441 if (!N->isNodeCompletelyFolded()) {
442 N->foldNodeCompletely();
443 if (hasNoReferrers()) return;
444 NSize = N->getSize();
446 } else if (N->isNodeCompletelyFolded()) {
447 foldNodeCompletely();
448 if (hasNoReferrers()) return;
450 NOffset = NH.getOffset();
451 NSize = N->getSize();
454 if (this == N || N == 0) return;
455 assert((NodeType & DSNode::DEAD) == 0);
458 std::cerr << "\n\nMerging:\n";
459 N->print(std::cerr, 0);
460 std::cerr << " and:\n";
464 // Remove all edges pointing at N, causing them to point to 'this' instead.
465 // Make sure to adjust their offset, not just the node pointer.
467 while (!N->Referrers.empty()) {
468 DSNodeHandle &Ref = *N->Referrers.back();
469 Ref = DSNodeHandle(this, NOffset+Ref.getOffset());
471 assert((NodeType & DSNode::DEAD) == 0);
473 // Make all of the outgoing links of N now be outgoing links of this. This
474 // can cause recursive merging!
476 for (unsigned i = 0; i < NSize; i += DS::PointerSize) {
477 DSNodeHandle &Link = N->getLink(i);
478 if (Link.getNode()) {
479 addEdgeTo((i+NOffset) % getSize(), Link);
481 // It's possible that after adding the new edge that some recursive
482 // merging just occured, causing THIS node to get merged into oblivion.
483 // If that happens, we must not try to merge any more edges into it!
486 return; // Node is now dead
488 break; // Node got collapsed
492 // Now that there are no outgoing edges, all of the Links are dead.
495 N->Ty = Type::VoidTy;
497 // Merge the node types
498 NodeType |= N->NodeType;
499 N->NodeType = DEAD; // N is now a dead node.
501 // Merge the globals list...
502 if (!N->Globals.empty()) {
503 MergeSortedVectors(Globals, N->Globals);
505 // Delete the globals from the old node...
510 //===----------------------------------------------------------------------===//
511 // DSCallSite Implementation
512 //===----------------------------------------------------------------------===//
514 // Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
515 Function &DSCallSite::getCaller() const {
516 return *Inst->getParent()->getParent();
520 //===----------------------------------------------------------------------===//
521 // DSGraph Implementation
522 //===----------------------------------------------------------------------===//
524 DSGraph::DSGraph(const DSGraph &G) : Func(G.Func), GlobalsGraph(0) {
525 PrintAuxCalls = false;
526 std::map<const DSNode*, DSNodeHandle> NodeMap;
527 RetNode = cloneInto(G, ScalarMap, NodeMap);
530 DSGraph::DSGraph(const DSGraph &G,
531 std::map<const DSNode*, DSNodeHandle> &NodeMap)
532 : Func(G.Func), GlobalsGraph(0) {
533 PrintAuxCalls = false;
534 RetNode = cloneInto(G, ScalarMap, NodeMap);
537 DSGraph::~DSGraph() {
538 FunctionCalls.clear();
539 AuxFunctionCalls.clear();
543 // Drop all intra-node references, so that assertions don't fail...
544 std::for_each(Nodes.begin(), Nodes.end(),
545 std::mem_fun(&DSNode::dropAllReferences));
547 // Delete all of the nodes themselves...
548 std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
551 // dump - Allow inspection of graph in a debugger.
552 void DSGraph::dump() const { print(std::cerr); }
555 /// remapLinks - Change all of the Links in the current node according to the
556 /// specified mapping.
558 void DSNode::remapLinks(std::map<const DSNode*, DSNodeHandle> &OldNodeMap) {
559 for (unsigned i = 0, e = Links.size(); i != e; ++i) {
560 DSNodeHandle &H = OldNodeMap[Links[i].getNode()];
561 Links[i].setNode(H.getNode());
562 Links[i].setOffset(Links[i].getOffset()+H.getOffset());
567 // cloneInto - Clone the specified DSGraph into the current graph, returning the
568 // Return node of the graph. The translated ScalarMap for the old function is
569 // filled into the OldValMap member. If StripAllocas is set to true, Alloca
570 // markers are removed from the graph, as the graph is being cloned into a
571 // calling function's graph.
573 DSNodeHandle DSGraph::cloneInto(const DSGraph &G,
574 std::map<Value*, DSNodeHandle> &OldValMap,
575 std::map<const DSNode*, DSNodeHandle> &OldNodeMap,
576 unsigned CloneFlags) {
577 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
578 assert(&G != this && "Cannot clone graph into itself!");
580 unsigned FN = Nodes.size(); // First new node...
582 // Duplicate all of the nodes, populating the node map...
583 Nodes.reserve(FN+G.Nodes.size());
584 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
585 DSNode *Old = G.Nodes[i];
586 DSNode *New = new DSNode(*Old);
587 New->NodeType &= ~DSNode::DEAD; // Clear dead flag...
588 Nodes.push_back(New);
589 OldNodeMap[Old] = New;
593 Timer::addPeakMemoryMeasurement();
596 // Rewrite the links in the new nodes to point into the current graph now.
597 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
598 Nodes[i]->remapLinks(OldNodeMap);
600 // Remove alloca markers as specified
601 if (CloneFlags & StripAllocaBit)
602 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
603 Nodes[i]->NodeType &= ~DSNode::AllocaNode;
605 // Copy the value map... and merge all of the global nodes...
606 for (std::map<Value*, DSNodeHandle>::const_iterator I = G.ScalarMap.begin(),
607 E = G.ScalarMap.end(); I != E; ++I) {
608 DSNodeHandle &H = OldValMap[I->first];
609 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
610 H.setNode(MappedNode.getNode());
611 H.setOffset(I->second.getOffset()+MappedNode.getOffset());
613 if (isa<GlobalValue>(I->first)) { // Is this a global?
614 std::map<Value*, DSNodeHandle>::iterator GVI = ScalarMap.find(I->first);
615 if (GVI != ScalarMap.end()) { // Is the global value in this fn already?
616 GVI->second.mergeWith(H);
618 ScalarMap[I->first] = H; // Add global pointer to this graph
623 if (!(CloneFlags & DontCloneCallNodes)) {
624 // Copy the function calls list...
625 unsigned FC = FunctionCalls.size(); // FirstCall
626 FunctionCalls.reserve(FC+G.FunctionCalls.size());
627 for (unsigned i = 0, ei = G.FunctionCalls.size(); i != ei; ++i)
628 FunctionCalls.push_back(DSCallSite(G.FunctionCalls[i], OldNodeMap));
631 if (!(CloneFlags & DontCloneAuxCallNodes)) {
632 // Copy the auxillary function calls list...
633 unsigned FC = AuxFunctionCalls.size(); // FirstCall
634 AuxFunctionCalls.reserve(FC+G.AuxFunctionCalls.size());
635 for (unsigned i = 0, ei = G.AuxFunctionCalls.size(); i != ei; ++i)
636 AuxFunctionCalls.push_back(DSCallSite(G.AuxFunctionCalls[i], OldNodeMap));
639 // Return the returned node pointer...
640 DSNodeHandle &MappedRet = OldNodeMap[G.RetNode.getNode()];
641 return DSNodeHandle(MappedRet.getNode(),
642 MappedRet.getOffset()+G.RetNode.getOffset());
645 /// mergeInGraph - The method is used for merging graphs together. If the
646 /// argument graph is not *this, it makes a clone of the specified graph, then
647 /// merges the nodes specified in the call site with the formal arguments in the
650 void DSGraph::mergeInGraph(DSCallSite &CS, const DSGraph &Graph,
651 unsigned CloneFlags) {
652 std::map<Value*, DSNodeHandle> OldValMap;
654 std::map<Value*, DSNodeHandle> *ScalarMap = &OldValMap;
656 // If this is not a recursive call, clone the graph into this graph...
657 if (&Graph != this) {
658 // Clone the callee's graph into the current graph, keeping
659 // track of where scalars in the old graph _used_ to point,
660 // and of the new nodes matching nodes of the old graph.
661 std::map<const DSNode*, DSNodeHandle> OldNodeMap;
663 // The clone call may invalidate any of the vectors in the data
664 // structure graph. Strip locals and don't copy the list of callers
665 RetVal = cloneInto(Graph, OldValMap, OldNodeMap, CloneFlags);
666 ScalarMap = &OldValMap;
668 RetVal = getRetNode();
669 ScalarMap = &getScalarMap();
672 // Merge the return value with the return value of the context...
673 RetVal.mergeWith(CS.getRetVal());
675 // Resolve all of the function arguments...
676 Function &F = Graph.getFunction();
677 Function::aiterator AI = F.abegin();
678 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
679 // Advance the argument iterator to the first pointer argument...
680 while (!isPointerType(AI->getType())) {
684 std::cerr << "Bad call to Function: " << F.getName() << "\n";
686 assert(AI != F.aend() && "# Args provided is not # Args required!");
689 // Add the link from the argument scalar to the provided value
690 DSNodeHandle &NH = (*ScalarMap)[AI];
691 assert(NH.getNode() && "Pointer argument without scalarmap entry?");
692 NH.mergeWith(CS.getPtrArg(i));
697 // cloneGlobalInto - Clone the given global node and all its target links
698 // (and all their llinks, recursively).
700 DSNode *DSGraph::cloneGlobalInto(const DSNode *GNode) {
701 if (GNode == 0 || GNode->getGlobals().size() == 0) return 0;
703 // If a clone has already been created for GNode, return it.
704 DSNodeHandle& ValMapEntry = ScalarMap[GNode->getGlobals()[0]];
705 if (ValMapEntry != 0)
708 // Clone the node and update the ValMap.
709 DSNode* NewNode = new DSNode(*GNode);
710 ValMapEntry = NewNode; // j=0 case of loop below!
711 Nodes.push_back(NewNode);
712 for (unsigned j = 1, N = NewNode->getGlobals().size(); j < N; ++j)
713 ScalarMap[NewNode->getGlobals()[j]] = NewNode;
715 // Rewrite the links in the new node to point into the current graph.
716 for (unsigned j = 0, e = GNode->getNumLinks(); j != e; ++j)
717 NewNode->setLink(j, cloneGlobalInto(GNode->getLink(j)));
724 // markIncompleteNodes - Mark the specified node as having contents that are not
725 // known with the current analysis we have performed. Because a node makes all
726 // of the nodes it can reach imcomplete if the node itself is incomplete, we
727 // must recursively traverse the data structure graph, marking all reachable
728 // nodes as incomplete.
730 static void markIncompleteNode(DSNode *N) {
731 // Stop recursion if no node, or if node already marked...
732 if (N == 0 || (N->NodeType & DSNode::Incomplete)) return;
734 // Actually mark the node
735 N->NodeType |= DSNode::Incomplete;
737 // Recusively process children...
738 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
739 if (DSNode *DSN = N->getLink(i).getNode())
740 markIncompleteNode(DSN);
743 static void markIncomplete(DSCallSite &Call) {
744 // Then the return value is certainly incomplete!
745 markIncompleteNode(Call.getRetVal().getNode());
747 // All objects pointed to by function arguments are incomplete!
748 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
749 markIncompleteNode(Call.getPtrArg(i).getNode());
752 // markIncompleteNodes - Traverse the graph, identifying nodes that may be
753 // modified by other functions that have not been resolved yet. This marks
754 // nodes that are reachable through three sources of "unknownness":
756 // Global Variables, Function Calls, and Incoming Arguments
758 // For any node that may have unknown components (because something outside the
759 // scope of current analysis may have modified it), the 'Incomplete' flag is
760 // added to the NodeType.
762 void DSGraph::markIncompleteNodes(bool markFormalArgs) {
763 // Mark any incoming arguments as incomplete...
764 if (markFormalArgs && Func)
765 for (Function::aiterator I = Func->abegin(), E = Func->aend(); I != E; ++I)
766 if (isPointerType(I->getType()) && ScalarMap.find(I) != ScalarMap.end())
767 markIncompleteNode(ScalarMap[I].getNode());
769 // Mark stuff passed into functions calls as being incomplete...
770 if (!shouldPrintAuxCalls())
771 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
772 markIncomplete(FunctionCalls[i]);
774 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
775 markIncomplete(AuxFunctionCalls[i]);
778 // Mark all of the nodes pointed to by global nodes as incomplete...
779 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
780 if (Nodes[i]->NodeType & DSNode::GlobalNode) {
781 DSNode *N = Nodes[i];
782 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
783 if (DSNode *DSN = N->getLink(i).getNode())
784 markIncompleteNode(DSN);
788 // removeRefsToGlobal - Helper function that removes globals from the
789 // ScalarMap so that the referrer count will go down to zero.
790 static void removeRefsToGlobal(DSNode* N,
791 std::map<Value*, DSNodeHandle> &ScalarMap) {
792 while (!N->getGlobals().empty()) {
793 GlobalValue *GV = N->getGlobals().back();
794 N->getGlobals().pop_back();
800 // isNodeDead - This method checks to see if a node is dead, and if it isn't, it
801 // checks to see if there are simple transformations that it can do to make it
804 bool DSGraph::isNodeDead(DSNode *N) {
805 // Is it a trivially dead shadow node?
806 return N->getReferrers().empty() && (N->NodeType & ~DSNode::DEAD) == 0;
809 static inline void killIfUselessEdge(DSNodeHandle &Edge) {
810 if (DSNode *N = Edge.getNode()) // Is there an edge?
811 if (N->getReferrers().size() == 1) // Does it point to a lonely node?
812 if ((N->NodeType & ~DSNode::Incomplete) == 0 && // No interesting info?
813 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
814 Edge.setNode(0); // Kill the edge!
817 static inline bool nodeContainsExternalFunction(const DSNode *N) {
818 const std::vector<GlobalValue*> &Globals = N->getGlobals();
819 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
820 if (Globals[i]->isExternal())
825 static void removeIdenticalCalls(vector<DSCallSite> &Calls,
826 const std::string &where) {
827 // Remove trivially identical function calls
828 unsigned NumFns = Calls.size();
829 std::sort(Calls.begin(), Calls.end()); // Sort by callee as primary key!
831 // Scan the call list cleaning it up as necessary...
832 DSNode *LastCalleeNode = 0;
833 unsigned NumDuplicateCalls = 0;
834 bool LastCalleeContainsExternalFunction = false;
835 for (unsigned i = 0; i != Calls.size(); ++i) {
836 DSCallSite &CS = Calls[i];
838 // If the Callee is a useless edge, this must be an unreachable call site,
840 killIfUselessEdge(CS.getCallee());
841 if (CS.getCallee().getNode() == 0) {
842 CS.swap(Calls.back());
846 // If the return value or any arguments point to a void node with no
847 // information at all in it, and the call node is the only node to point
848 // to it, remove the edge to the node (killing the node).
850 killIfUselessEdge(CS.getRetVal());
851 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
852 killIfUselessEdge(CS.getPtrArg(a));
854 // If this call site calls the same function as the last call site, and if
855 // the function pointer contains an external function, this node will
856 // never be resolved. Merge the arguments of the call node because no
857 // information will be lost.
859 if (CS.getCallee().getNode() == LastCalleeNode) {
861 if (NumDuplicateCalls == 1) {
862 LastCalleeContainsExternalFunction =
863 nodeContainsExternalFunction(LastCalleeNode);
866 if (LastCalleeContainsExternalFunction ||
867 // This should be more than enough context sensitivity!
868 // FIXME: Evaluate how many times this is tripped!
869 NumDuplicateCalls > 20) {
870 DSCallSite &OCS = Calls[i-1];
873 // The node will now be eliminated as a duplicate!
874 if (CS.getNumPtrArgs() < OCS.getNumPtrArgs())
876 else if (CS.getNumPtrArgs() > OCS.getNumPtrArgs())
880 LastCalleeNode = CS.getCallee().getNode();
881 NumDuplicateCalls = 0;
886 Calls.erase(std::unique(Calls.begin(), Calls.end()),
889 // Track the number of call nodes merged away...
890 NumCallNodesMerged += NumFns-Calls.size();
892 DEBUG(if (NumFns != Calls.size())
893 std::cerr << "Merged " << (NumFns-Calls.size())
894 << " call nodes in " << where << "\n";);
898 // removeTriviallyDeadNodes - After the graph has been constructed, this method
899 // removes all unreachable nodes that are created because they got merged with
900 // other nodes in the graph. These nodes will all be trivially unreachable, so
901 // we don't have to perform any non-trivial analysis here.
903 void DSGraph::removeTriviallyDeadNodes() {
904 removeIdenticalCalls(FunctionCalls, Func ? Func->getName() : "");
905 removeIdenticalCalls(AuxFunctionCalls, Func ? Func->getName() : "");
907 for (unsigned i = 0; i != Nodes.size(); ++i)
908 if (isNodeDead(Nodes[i])) { // This node is dead!
909 delete Nodes[i]; // Free memory...
910 Nodes.erase(Nodes.begin()+i--); // Remove from node list...
915 // markAlive - Simple graph walker that recursively traverses the graph, marking
916 // stuff to be alive.
918 static void markAlive(DSNode *N, std::set<DSNode*> &Alive) {
920 std::set<DSNode*>::iterator I = Alive.lower_bound(N);
921 if (I != Alive.end() && *I == N) return; // Already marked alive
922 Alive.insert(I, N); // Is alive now
924 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
925 markAlive(N->getLink(i).getNode(), Alive);
928 // markAliveIfCanReachAlive - Simple graph walker that recursively traverses the
929 // graph looking for a node that is marked alive. If the node is marked alive,
930 // the recursive unwind marks node alive that can point to the alive node. This
931 // is basically just a post-order traversal.
933 // This function returns true if the specified node is alive.
935 static bool markAliveIfCanReachAlive(DSNode *N, std::set<DSNode*> &Alive,
936 std::set<DSNode*> &Visited) {
937 if (N == 0) return false;
939 // If we know that this node is alive, return so!
940 if (Alive.count(N)) return true;
942 // Otherwise, we don't think the node is alive yet, check for infinite
944 std::set<DSNode*>::iterator VI = Visited.lower_bound(N);
945 if (VI != Visited.end() && *VI == N) return false; // Found a cycle
946 // No recursion, insert into Visited...
947 Visited.insert(VI, N);
949 if (N->NodeType & DSNode::GlobalNode)
950 return false; // Global nodes will be marked on their own
952 bool ChildrenAreAlive = false;
954 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
955 ChildrenAreAlive |= markAliveIfCanReachAlive(N->getLink(i).getNode(),
957 if (ChildrenAreAlive)
959 return ChildrenAreAlive;
962 static bool CallSiteUsesAliveArgs(DSCallSite &CS, std::set<DSNode*> &Alive,
963 std::set<DSNode*> &Visited) {
964 if (markAliveIfCanReachAlive(CS.getRetVal().getNode(), Alive, Visited) ||
965 markAliveIfCanReachAlive(CS.getCallee().getNode(), Alive, Visited))
967 for (unsigned j = 0, e = CS.getNumPtrArgs(); j != e; ++j)
968 if (markAliveIfCanReachAlive(CS.getPtrArg(j).getNode(), Alive, Visited))
973 static void markAlive(DSCallSite &CS, std::set<DSNode*> &Alive) {
974 markAlive(CS.getRetVal().getNode(), Alive);
975 markAlive(CS.getCallee().getNode(), Alive);
977 for (unsigned j = 0, e = CS.getNumPtrArgs(); j != e; ++j)
978 markAlive(CS.getPtrArg(j).getNode(), Alive);
981 // removeDeadNodes - Use a more powerful reachability analysis to eliminate
982 // subgraphs that are unreachable. This often occurs because the data
983 // structure doesn't "escape" into it's caller, and thus should be eliminated
984 // from the caller's graph entirely. This is only appropriate to use when
987 void DSGraph::removeDeadNodes() {
988 // Reduce the amount of work we have to do...
989 removeTriviallyDeadNodes();
991 // FIXME: Merge nontrivially identical call nodes...
993 // Alive - a set that holds all nodes found to be reachable/alive.
994 std::set<DSNode*> Alive;
995 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
997 // Mark all nodes reachable by (non-global) scalar nodes as alive...
998 for (std::map<Value*, DSNodeHandle>::iterator I = ScalarMap.begin(),
999 E = ScalarMap.end(); I != E; ++I)
1000 if (!isa<GlobalValue>(I->first)) // Don't mark globals!
1001 markAlive(I->second.getNode(), Alive);
1002 else // Keep track of global nodes
1003 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
1005 // The return value is alive as well...
1006 markAlive(RetNode.getNode(), Alive);
1008 // If any global nodes points to a non-global that is "alive", the global is
1009 // "alive" as well...
1011 std::set<DSNode*> Visited;
1012 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
1013 markAliveIfCanReachAlive(GlobalNodes[i].second, Alive, Visited);
1015 std::vector<bool> FCallsAlive(FunctionCalls.size());
1016 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1017 if (CallSiteUsesAliveArgs(FunctionCalls[i], Alive, Visited)) {
1018 markAlive(FunctionCalls[i], Alive);
1019 FCallsAlive[i] = true;
1022 std::vector<bool> AuxFCallsAlive(AuxFunctionCalls.size());
1023 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1024 if (CallSiteUsesAliveArgs(AuxFunctionCalls[i], Alive, Visited)) {
1025 markAlive(AuxFunctionCalls[i], Alive);
1026 AuxFCallsAlive[i] = true;
1029 // Remove all dead function calls...
1030 unsigned CurIdx = 0;
1031 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1033 FunctionCalls[CurIdx++].swap(FunctionCalls[i]);
1034 // Crop all the bad ones out...
1035 FunctionCalls.erase(FunctionCalls.begin()+CurIdx, FunctionCalls.end());
1037 // Remove all dead aux function calls...
1039 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1040 if (AuxFCallsAlive[i])
1041 AuxFunctionCalls[CurIdx++].swap(AuxFunctionCalls[i]);
1042 // Crop all the bad ones out...
1043 AuxFunctionCalls.erase(AuxFunctionCalls.begin()+CurIdx,
1044 AuxFunctionCalls.end());
1047 // Remove all unreachable globals from the ScalarMap
1048 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
1049 if (!Alive.count(GlobalNodes[i].second))
1050 ScalarMap.erase(GlobalNodes[i].first);
1052 // Loop over all unreachable nodes, dropping their references...
1053 vector<DSNode*> DeadNodes;
1054 DeadNodes.reserve(Nodes.size()); // Only one allocation is allowed.
1055 for (unsigned i = 0; i != Nodes.size(); ++i)
1056 if (!Alive.count(Nodes[i])) {
1057 DSNode *N = Nodes[i];
1058 Nodes.erase(Nodes.begin()+i--); // Erase node from alive list.
1059 DeadNodes.push_back(N); // Add node to our list of dead nodes
1060 N->dropAllReferences(); // Drop all outgoing edges
1063 // Delete all dead nodes...
1064 std::for_each(DeadNodes.begin(), DeadNodes.end(), deleter<DSNode>);
1068 //===----------------------------------------------------------------------===//
1069 // GlobalDSGraph Implementation
1070 //===----------------------------------------------------------------------===//
1073 // Bits used in the next function
1074 static const char ExternalTypeBits = DSNode::GlobalNode | DSNode::HeapNode;
1077 // GlobalDSGraph::cloneNodeInto - Clone a global node and all its externally
1078 // visible target links (and recursively their such links) into this graph.
1079 // NodeCache maps the node being cloned to its clone in the Globals graph,
1080 // in order to track cycles.
1081 // GlobalsAreFinal is a flag that says whether it is safe to assume that
1082 // an existing global node is complete. This is important to avoid
1083 // reinserting all globals when inserting Calls to functions.
1084 // This is a helper function for cloneGlobals and cloneCalls.
1086 DSNode* GlobalDSGraph::cloneNodeInto(DSNode *OldNode,
1087 std::map<const DSNode*, DSNode*> &NodeCache,
1088 bool GlobalsAreFinal) {
1089 if (OldNode == 0) return 0;
1091 // The caller should check this is an external node. Just more efficient...
1092 assert((OldNode->NodeType & ExternalTypeBits) && "Non-external node");
1094 // If a clone has already been created for OldNode, return it.
1095 DSNode*& CacheEntry = NodeCache[OldNode];
1096 if (CacheEntry != 0)
1099 // The result value...
1100 DSNode* NewNode = 0;
1102 // If nodes already exist for any of the globals of OldNode,
1103 // merge all such nodes together since they are merged in OldNode.
1104 // If ValueCacheIsFinal==true, look for an existing node that has
1105 // an identical list of globals and return it if it exists.
1107 for (unsigned j = 0, N = OldNode->getGlobals().size(); j != N; ++j)
1108 if (DSNode *PrevNode = ScalarMap[OldNode->getGlobals()[j]].getNode()) {
1110 NewNode = PrevNode; // first existing node found
1111 if (GlobalsAreFinal && j == 0)
1112 if (OldNode->getGlobals() == PrevNode->getGlobals()) {
1113 CacheEntry = NewNode;
1117 else if (NewNode != PrevNode) { // found another, different from prev
1118 // update ValMap *before* merging PrevNode into NewNode
1119 for (unsigned k = 0, NK = PrevNode->getGlobals().size(); k < NK; ++k)
1120 ScalarMap[PrevNode->getGlobals()[k]] = NewNode;
1121 NewNode->mergeWith(PrevNode);
1123 } else if (NewNode != 0) {
1124 ScalarMap[OldNode->getGlobals()[j]] = NewNode; // add the merged node
1127 // If no existing node was found, clone the node and update the ValMap.
1129 NewNode = new DSNode(*OldNode);
1130 Nodes.push_back(NewNode);
1131 for (unsigned j = 0, e = NewNode->getNumLinks(); j != e; ++j)
1132 NewNode->setLink(j, 0);
1133 for (unsigned j = 0, N = NewNode->getGlobals().size(); j < N; ++j)
1134 ScalarMap[NewNode->getGlobals()[j]] = NewNode;
1137 NewNode->NodeType |= OldNode->NodeType; // Markers may be different!
1139 // Add the entry to NodeCache
1140 CacheEntry = NewNode;
1142 // Rewrite the links in the new node to point into the current graph,
1143 // but only for links to external nodes. Set other links to NULL.
1144 for (unsigned j = 0, e = OldNode->getNumLinks(); j != e; ++j) {
1145 DSNode* OldTarget = OldNode->getLink(j);
1146 if (OldTarget && (OldTarget->NodeType & ExternalTypeBits)) {
1147 DSNode* NewLink = this->cloneNodeInto(OldTarget, NodeCache);
1148 if (NewNode->getLink(j))
1149 NewNode->getLink(j)->mergeWith(NewLink);
1151 NewNode->setLink(j, NewLink);
1155 // Remove all local markers
1156 NewNode->NodeType &= ~(DSNode::AllocaNode | DSNode::ScalarNode);
1162 // GlobalDSGraph::cloneCalls - Clone function calls and their visible target
1163 // links (and recursively their such links) into this graph.
1165 void GlobalDSGraph::cloneCalls(DSGraph& Graph) {
1166 std::map<const DSNode*, DSNode*> NodeCache;
1167 vector<DSCallSite >& FromCalls =Graph.FunctionCalls;
1169 FunctionCalls.reserve(FunctionCalls.size() + FromCalls.size());
1171 for (int i = 0, ei = FromCalls.size(); i < ei; ++i) {
1172 DSCallSite& callCopy = FunctionCalls.back();
1173 callCopy.reserve(FromCalls[i].size());
1174 for (unsigned j = 0, ej = FromCalls[i].size(); j != ej; ++j)
1176 ((FromCalls[i][j] && (FromCalls[i][j]->NodeType & ExternalTypeBits))
1177 ? cloneNodeInto(FromCalls[i][j], NodeCache, true)
1181 // remove trivially identical function calls
1182 removeIdenticalCalls(FunctionCalls, "Globals Graph");