1 //===- DataStructure.cpp - Implement the core data structure analysis -----===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the core data structure functionality.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Analysis/DSGraph.h"
15 #include "llvm/Function.h"
16 #include "llvm/iOther.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Target/TargetData.h"
19 #include "llvm/Assembly/Writer.h"
20 #include "Support/CommandLine.h"
21 #include "Support/Debug.h"
22 #include "Support/STLExtras.h"
23 #include "Support/Statistic.h"
24 #include "Support/Timer.h"
29 Statistic<> NumFolds ("dsa", "Number of nodes completely folded");
30 Statistic<> NumCallNodesMerged("dsa", "Number of call nodes merged");
31 Statistic<> NumNodeAllocated ("dsa", "Number of nodes allocated");
32 Statistic<> NumDNE ("dsa", "Number of nodes removed by reachability");
35 EnableDSNodeGlobalRootsHack("enable-dsa-globalrootshack", cl::Hidden,
36 cl::desc("Make DSA less aggressive when cloning graphs"));
40 #define TIME_REGION(VARNAME, DESC) \
41 NamedRegionTimer VARNAME(DESC)
43 #define TIME_REGION(VARNAME, DESC)
48 DSNode *DSNodeHandle::HandleForwarding() const {
49 assert(!N->ForwardNH.isNull() && "Can only be invoked if forwarding!");
51 // Handle node forwarding here!
52 DSNode *Next = N->ForwardNH.getNode(); // Cause recursive shrinkage
53 Offset += N->ForwardNH.getOffset();
55 if (--N->NumReferrers == 0) {
56 // Removing the last referrer to the node, sever the forwarding link
62 if (N->Size <= Offset) {
63 assert(N->Size <= 1 && "Forwarded to shrunk but not collapsed node?");
69 //===----------------------------------------------------------------------===//
70 // DSNode Implementation
71 //===----------------------------------------------------------------------===//
73 DSNode::DSNode(const Type *T, DSGraph *G)
74 : NumReferrers(0), Size(0), ParentGraph(G), Ty(Type::VoidTy), NodeType(0) {
75 // Add the type entry if it is specified...
76 if (T) mergeTypeInfo(T, 0);
81 // DSNode copy constructor... do not copy over the referrers list!
82 DSNode::DSNode(const DSNode &N, DSGraph *G, bool NullLinks)
83 : NumReferrers(0), Size(N.Size), ParentGraph(G),
84 Ty(N.Ty), Globals(N.Globals), NodeType(N.NodeType) {
88 Links.resize(N.Links.size()); // Create the appropriate number of null links
93 /// getTargetData - Get the target data object used to construct this node.
95 const TargetData &DSNode::getTargetData() const {
96 return ParentGraph->getTargetData();
99 void DSNode::assertOK() const {
100 assert((Ty != Type::VoidTy ||
101 Ty == Type::VoidTy && (Size == 0 ||
102 (NodeType & DSNode::Array))) &&
105 assert(ParentGraph && "Node has no parent?");
106 const DSScalarMap &SM = ParentGraph->getScalarMap();
107 for (unsigned i = 0, e = Globals.size(); i != e; ++i) {
108 assert(SM.count(Globals[i]));
109 assert(SM.find(Globals[i])->second.getNode() == this);
113 /// forwardNode - Mark this node as being obsolete, and all references to it
114 /// should be forwarded to the specified node and offset.
116 void DSNode::forwardNode(DSNode *To, unsigned Offset) {
117 assert(this != To && "Cannot forward a node to itself!");
118 assert(ForwardNH.isNull() && "Already forwarding from this node!");
119 if (To->Size <= 1) Offset = 0;
120 assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
121 "Forwarded offset is wrong!");
122 ForwardNH.setNode(To);
123 ForwardNH.setOffset(Offset);
129 // addGlobal - Add an entry for a global value to the Globals list. This also
130 // marks the node with the 'G' flag if it does not already have it.
132 void DSNode::addGlobal(GlobalValue *GV) {
133 // Keep the list sorted.
134 std::vector<GlobalValue*>::iterator I =
135 std::lower_bound(Globals.begin(), Globals.end(), GV);
137 if (I == Globals.end() || *I != GV) {
138 //assert(GV->getType()->getElementType() == Ty);
139 Globals.insert(I, GV);
140 NodeType |= GlobalNode;
144 /// foldNodeCompletely - If we determine that this node has some funny
145 /// behavior happening to it that we cannot represent, we fold it down to a
146 /// single, completely pessimistic, node. This node is represented as a
147 /// single byte with a single TypeEntry of "void".
149 void DSNode::foldNodeCompletely() {
150 if (isNodeCompletelyFolded()) return; // If this node is already folded...
154 // If this node has a size that is <= 1, we don't need to create a forwarding
156 if (getSize() <= 1) {
157 NodeType |= DSNode::Array;
160 assert(Links.size() <= 1 && "Size is 1, but has more links?");
163 // Create the node we are going to forward to. This is required because
164 // some referrers may have an offset that is > 0. By forcing them to
165 // forward, the forwarder has the opportunity to correct the offset.
166 DSNode *DestNode = new DSNode(0, ParentGraph);
167 DestNode->NodeType = NodeType|DSNode::Array;
168 DestNode->Ty = Type::VoidTy;
170 DestNode->Globals.swap(Globals);
172 // Start forwarding to the destination node...
173 forwardNode(DestNode, 0);
175 if (!Links.empty()) {
176 DestNode->Links.reserve(1);
178 DSNodeHandle NH(DestNode);
179 DestNode->Links.push_back(Links[0]);
181 // If we have links, merge all of our outgoing links together...
182 for (unsigned i = Links.size()-1; i != 0; --i)
183 NH.getNode()->Links[0].mergeWith(Links[i]);
186 DestNode->Links.resize(1);
191 /// isNodeCompletelyFolded - Return true if this node has been completely
192 /// folded down to something that can never be expanded, effectively losing
193 /// all of the field sensitivity that may be present in the node.
195 bool DSNode::isNodeCompletelyFolded() const {
196 return getSize() == 1 && Ty == Type::VoidTy && isArray();
200 /// TypeElementWalker Class - Used for implementation of physical subtyping...
202 class TypeElementWalker {
207 StackState(const Type *T, unsigned Off = 0)
208 : Ty(T), Offset(Off), Idx(0) {}
211 std::vector<StackState> Stack;
212 const TargetData &TD;
214 TypeElementWalker(const Type *T, const TargetData &td) : TD(td) {
219 bool isDone() const { return Stack.empty(); }
220 const Type *getCurrentType() const { return Stack.back().Ty; }
221 unsigned getCurrentOffset() const { return Stack.back().Offset; }
223 void StepToNextType() {
224 PopStackAndAdvance();
229 /// PopStackAndAdvance - Pop the current element off of the stack and
230 /// advance the underlying element to the next contained member.
231 void PopStackAndAdvance() {
232 assert(!Stack.empty() && "Cannot pop an empty stack!");
234 while (!Stack.empty()) {
235 StackState &SS = Stack.back();
236 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
238 if (SS.Idx != ST->getElementTypes().size()) {
239 const StructLayout *SL = TD.getStructLayout(ST);
240 SS.Offset += SL->MemberOffsets[SS.Idx]-SL->MemberOffsets[SS.Idx-1];
243 Stack.pop_back(); // At the end of the structure
245 const ArrayType *AT = cast<ArrayType>(SS.Ty);
247 if (SS.Idx != AT->getNumElements()) {
248 SS.Offset += TD.getTypeSize(AT->getElementType());
251 Stack.pop_back(); // At the end of the array
256 /// StepToLeaf - Used by physical subtyping to move to the first leaf node
257 /// on the type stack.
259 if (Stack.empty()) return;
260 while (!Stack.empty() && !Stack.back().Ty->isFirstClassType()) {
261 StackState &SS = Stack.back();
262 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
263 if (ST->getElementTypes().empty()) {
265 PopStackAndAdvance();
267 // Step into the structure...
268 assert(SS.Idx < ST->getElementTypes().size());
269 const StructLayout *SL = TD.getStructLayout(ST);
270 Stack.push_back(StackState(ST->getElementTypes()[SS.Idx],
271 SS.Offset+SL->MemberOffsets[SS.Idx]));
274 const ArrayType *AT = cast<ArrayType>(SS.Ty);
275 if (AT->getNumElements() == 0) {
277 PopStackAndAdvance();
279 // Step into the array...
280 assert(SS.Idx < AT->getNumElements());
281 Stack.push_back(StackState(AT->getElementType(),
283 TD.getTypeSize(AT->getElementType())));
289 } // end anonymous namespace
291 /// ElementTypesAreCompatible - Check to see if the specified types are
292 /// "physically" compatible. If so, return true, else return false. We only
293 /// have to check the fields in T1: T2 may be larger than T1. If AllowLargerT1
294 /// is true, then we also allow a larger T1.
296 static bool ElementTypesAreCompatible(const Type *T1, const Type *T2,
297 bool AllowLargerT1, const TargetData &TD){
298 TypeElementWalker T1W(T1, TD), T2W(T2, TD);
300 while (!T1W.isDone() && !T2W.isDone()) {
301 if (T1W.getCurrentOffset() != T2W.getCurrentOffset())
304 const Type *T1 = T1W.getCurrentType();
305 const Type *T2 = T2W.getCurrentType();
306 if (T1 != T2 && !T1->isLosslesslyConvertibleTo(T2))
309 T1W.StepToNextType();
310 T2W.StepToNextType();
313 return AllowLargerT1 || T1W.isDone();
317 /// mergeTypeInfo - This method merges the specified type into the current node
318 /// at the specified offset. This may update the current node's type record if
319 /// this gives more information to the node, it may do nothing to the node if
320 /// this information is already known, or it may merge the node completely (and
321 /// return true) if the information is incompatible with what is already known.
323 /// This method returns true if the node is completely folded, otherwise false.
325 bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset,
326 bool FoldIfIncompatible) {
327 const TargetData &TD = getTargetData();
328 // Check to make sure the Size member is up-to-date. Size can be one of the
330 // Size = 0, Ty = Void: Nothing is known about this node.
331 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
332 // Size = 1, Ty = Void, Array = 1: The node is collapsed
333 // Otherwise, sizeof(Ty) = Size
335 assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
336 (Size == 0 && !Ty->isSized() && !isArray()) ||
337 (Size == 1 && Ty == Type::VoidTy && isArray()) ||
338 (Size == 0 && !Ty->isSized() && !isArray()) ||
339 (TD.getTypeSize(Ty) == Size)) &&
340 "Size member of DSNode doesn't match the type structure!");
341 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
343 if (Offset == 0 && NewTy == Ty)
344 return false; // This should be a common case, handle it efficiently
346 // Return true immediately if the node is completely folded.
347 if (isNodeCompletelyFolded()) return true;
349 // If this is an array type, eliminate the outside arrays because they won't
350 // be used anyway. This greatly reduces the size of large static arrays used
351 // as global variables, for example.
353 bool WillBeArray = false;
354 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
355 // FIXME: we might want to keep small arrays, but must be careful about
356 // things like: [2 x [10000 x int*]]
357 NewTy = AT->getElementType();
361 // Figure out how big the new type we're merging in is...
362 unsigned NewTySize = NewTy->isSized() ? TD.getTypeSize(NewTy) : 0;
364 // Otherwise check to see if we can fold this type into the current node. If
365 // we can't, we fold the node completely, if we can, we potentially update our
368 if (Ty == Type::VoidTy) {
369 // If this is the first type that this node has seen, just accept it without
371 assert(Offset == 0 && !isArray() &&
372 "Cannot have an offset into a void node!");
375 if (WillBeArray) NodeType |= Array;
378 // Calculate the number of outgoing links from this node.
379 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
383 // Handle node expansion case here...
384 if (Offset+NewTySize > Size) {
385 // It is illegal to grow this node if we have treated it as an array of
388 if (FoldIfIncompatible) foldNodeCompletely();
392 if (Offset) { // We could handle this case, but we don't for now...
393 std::cerr << "UNIMP: Trying to merge a growth type into "
394 << "offset != 0: Collapsing!\n";
395 if (FoldIfIncompatible) foldNodeCompletely();
399 // Okay, the situation is nice and simple, we are trying to merge a type in
400 // at offset 0 that is bigger than our current type. Implement this by
401 // switching to the new type and then merge in the smaller one, which should
402 // hit the other code path here. If the other code path decides it's not
403 // ok, it will collapse the node as appropriate.
405 const Type *OldTy = Ty;
408 if (WillBeArray) NodeType |= Array;
411 // Must grow links to be the appropriate size...
412 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
414 // Merge in the old type now... which is guaranteed to be smaller than the
416 return mergeTypeInfo(OldTy, 0);
419 assert(Offset <= Size &&
420 "Cannot merge something into a part of our type that doesn't exist!");
422 // Find the section of Ty that NewTy overlaps with... first we find the
423 // type that starts at offset Offset.
426 const Type *SubType = Ty;
428 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
430 switch (SubType->getPrimitiveID()) {
431 case Type::StructTyID: {
432 const StructType *STy = cast<StructType>(SubType);
433 const StructLayout &SL = *TD.getStructLayout(STy);
435 unsigned i = 0, e = SL.MemberOffsets.size();
436 for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
439 // The offset we are looking for must be in the i'th element...
440 SubType = STy->getElementTypes()[i];
441 O += SL.MemberOffsets[i];
444 case Type::ArrayTyID: {
445 SubType = cast<ArrayType>(SubType)->getElementType();
446 unsigned ElSize = TD.getTypeSize(SubType);
447 unsigned Remainder = (Offset-O) % ElSize;
448 O = Offset-Remainder;
452 if (FoldIfIncompatible) foldNodeCompletely();
457 assert(O == Offset && "Could not achieve the correct offset!");
459 // If we found our type exactly, early exit
460 if (SubType == NewTy) return false;
462 // Differing function types don't require us to merge. They are not values anyway.
463 if (isa<FunctionType>(SubType) &&
464 isa<FunctionType>(NewTy)) return false;
466 unsigned SubTypeSize = SubType->isSized() ? TD.getTypeSize(SubType) : 0;
468 // Ok, we are getting desperate now. Check for physical subtyping, where we
469 // just require each element in the node to be compatible.
470 if (NewTySize <= SubTypeSize && NewTySize && NewTySize < 256 &&
471 SubTypeSize && SubTypeSize < 256 &&
472 ElementTypesAreCompatible(NewTy, SubType, !isArray(), TD))
475 // Okay, so we found the leader type at the offset requested. Search the list
476 // of types that starts at this offset. If SubType is currently an array or
477 // structure, the type desired may actually be the first element of the
480 unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
481 while (SubType != NewTy) {
482 const Type *NextSubType = 0;
483 unsigned NextSubTypeSize = 0;
484 unsigned NextPadSize = 0;
485 switch (SubType->getPrimitiveID()) {
486 case Type::StructTyID: {
487 const StructType *STy = cast<StructType>(SubType);
488 const StructLayout &SL = *TD.getStructLayout(STy);
489 if (SL.MemberOffsets.size() > 1)
490 NextPadSize = SL.MemberOffsets[1];
492 NextPadSize = SubTypeSize;
493 NextSubType = STy->getElementTypes()[0];
494 NextSubTypeSize = TD.getTypeSize(NextSubType);
497 case Type::ArrayTyID:
498 NextSubType = cast<ArrayType>(SubType)->getElementType();
499 NextSubTypeSize = TD.getTypeSize(NextSubType);
500 NextPadSize = NextSubTypeSize;
506 if (NextSubType == 0)
507 break; // In the default case, break out of the loop
509 if (NextPadSize < NewTySize)
510 break; // Don't allow shrinking to a smaller type than NewTySize
511 SubType = NextSubType;
512 SubTypeSize = NextSubTypeSize;
513 PadSize = NextPadSize;
516 // If we found the type exactly, return it...
517 if (SubType == NewTy)
520 // Check to see if we have a compatible, but different type...
521 if (NewTySize == SubTypeSize) {
522 // Check to see if this type is obviously convertible... int -> uint f.e.
523 if (NewTy->isLosslesslyConvertibleTo(SubType))
526 // Check to see if we have a pointer & integer mismatch going on here,
527 // loading a pointer as a long, for example.
529 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
530 NewTy->isInteger() && isa<PointerType>(SubType))
532 } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
533 // We are accessing the field, plus some structure padding. Ignore the
534 // structure padding.
539 if (getParentGraph()->getReturnNodes().size())
540 M = getParentGraph()->getReturnNodes().begin()->first->getParent();
541 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: ";
542 WriteTypeSymbolic(std::cerr, Ty, M) << "\n due to:";
543 WriteTypeSymbolic(std::cerr, NewTy, M) << " @ " << Offset << "!\n"
545 WriteTypeSymbolic(std::cerr, SubType, M) << "\n\n");
547 if (FoldIfIncompatible) foldNodeCompletely();
553 // addEdgeTo - Add an edge from the current node to the specified node. This
554 // can cause merging of nodes in the graph.
556 void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
557 if (NH.isNull()) return; // Nothing to do
559 DSNodeHandle &ExistingEdge = getLink(Offset);
560 if (!ExistingEdge.isNull()) {
561 // Merge the two nodes...
562 ExistingEdge.mergeWith(NH);
563 } else { // No merging to perform...
564 setLink(Offset, NH); // Just force a link in there...
569 // MergeSortedVectors - Efficiently merge a vector into another vector where
570 // duplicates are not allowed and both are sorted. This assumes that 'T's are
571 // efficiently copyable and have sane comparison semantics.
573 static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
574 const std::vector<GlobalValue*> &Src) {
575 // By far, the most common cases will be the simple ones. In these cases,
576 // avoid having to allocate a temporary vector...
578 if (Src.empty()) { // Nothing to merge in...
580 } else if (Dest.empty()) { // Just copy the result in...
582 } else if (Src.size() == 1) { // Insert a single element...
583 const GlobalValue *V = Src[0];
584 std::vector<GlobalValue*>::iterator I =
585 std::lower_bound(Dest.begin(), Dest.end(), V);
586 if (I == Dest.end() || *I != Src[0]) // If not already contained...
587 Dest.insert(I, Src[0]);
588 } else if (Dest.size() == 1) {
589 GlobalValue *Tmp = Dest[0]; // Save value in temporary...
590 Dest = Src; // Copy over list...
591 std::vector<GlobalValue*>::iterator I =
592 std::lower_bound(Dest.begin(), Dest.end(), Tmp);
593 if (I == Dest.end() || *I != Tmp) // If not already contained...
597 // Make a copy to the side of Dest...
598 std::vector<GlobalValue*> Old(Dest);
600 // Make space for all of the type entries now...
601 Dest.resize(Dest.size()+Src.size());
603 // Merge the two sorted ranges together... into Dest.
604 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
606 // Now erase any duplicate entries that may have accumulated into the
607 // vectors (because they were in both of the input sets)
608 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
612 void DSNode::mergeGlobals(const std::vector<GlobalValue*> &RHS) {
613 MergeSortedVectors(Globals, RHS);
616 // MergeNodes - Helper function for DSNode::mergeWith().
617 // This function does the hard work of merging two nodes, CurNodeH
618 // and NH after filtering out trivial cases and making sure that
619 // CurNodeH.offset >= NH.offset.
622 // Since merging may cause either node to go away, we must always
623 // use the node-handles to refer to the nodes. These node handles are
624 // automatically updated during merging, so will always provide access
625 // to the correct node after a merge.
627 void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
628 assert(CurNodeH.getOffset() >= NH.getOffset() &&
629 "This should have been enforced in the caller.");
631 // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
632 // respect to NH.Offset) is now zero. NOffset is the distance from the base
633 // of our object that N starts from.
635 unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
636 unsigned NSize = NH.getNode()->getSize();
638 // If the two nodes are of different size, and the smaller node has the array
639 // bit set, collapse!
640 if (NSize != CurNodeH.getNode()->getSize()) {
641 if (NSize < CurNodeH.getNode()->getSize()) {
642 if (NH.getNode()->isArray())
643 NH.getNode()->foldNodeCompletely();
644 } else if (CurNodeH.getNode()->isArray()) {
645 NH.getNode()->foldNodeCompletely();
649 // Merge the type entries of the two nodes together...
650 if (NH.getNode()->Ty != Type::VoidTy)
651 CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
652 assert(!CurNodeH.getNode()->isDeadNode());
654 // If we are merging a node with a completely folded node, then both nodes are
655 // now completely folded.
657 if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
658 if (!NH.getNode()->isNodeCompletelyFolded()) {
659 NH.getNode()->foldNodeCompletely();
660 assert(NH.getNode() && NH.getOffset() == 0 &&
661 "folding did not make offset 0?");
662 NOffset = NH.getOffset();
663 NSize = NH.getNode()->getSize();
664 assert(NOffset == 0 && NSize == 1);
666 } else if (NH.getNode()->isNodeCompletelyFolded()) {
667 CurNodeH.getNode()->foldNodeCompletely();
668 assert(CurNodeH.getNode() && CurNodeH.getOffset() == 0 &&
669 "folding did not make offset 0?");
670 NOffset = NH.getOffset();
671 NSize = NH.getNode()->getSize();
672 assert(NOffset == 0 && NSize == 1);
675 DSNode *N = NH.getNode();
676 if (CurNodeH.getNode() == N || N == 0) return;
677 assert(!CurNodeH.getNode()->isDeadNode());
679 // Merge the NodeType information.
680 CurNodeH.getNode()->NodeType |= N->NodeType;
682 // Start forwarding to the new node!
683 N->forwardNode(CurNodeH.getNode(), NOffset);
684 assert(!CurNodeH.getNode()->isDeadNode());
686 // Make all of the outgoing links of N now be outgoing links of CurNodeH.
688 for (unsigned i = 0; i < N->getNumLinks(); ++i) {
689 DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
690 if (Link.getNode()) {
691 // Compute the offset into the current node at which to
692 // merge this link. In the common case, this is a linear
693 // relation to the offset in the original node (with
694 // wrapping), but if the current node gets collapsed due to
695 // recursive merging, we must make sure to merge in all remaining
696 // links at offset zero.
697 unsigned MergeOffset = 0;
698 DSNode *CN = CurNodeH.getNode();
700 MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
701 CN->addEdgeTo(MergeOffset, Link);
705 // Now that there are no outgoing edges, all of the Links are dead.
708 // Merge the globals list...
709 if (!N->Globals.empty()) {
710 CurNodeH.getNode()->mergeGlobals(N->Globals);
712 // Delete the globals from the old node...
713 std::vector<GlobalValue*>().swap(N->Globals);
718 // mergeWith - Merge this node and the specified node, moving all links to and
719 // from the argument node into the current node, deleting the node argument.
720 // Offset indicates what offset the specified node is to be merged into the
723 // The specified node may be a null pointer (in which case, we update it to
724 // point to this node).
726 void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
727 DSNode *N = NH.getNode();
728 if (N == this && NH.getOffset() == Offset)
731 // If the RHS is a null node, make it point to this node!
733 NH.mergeWith(DSNodeHandle(this, Offset));
737 assert(!N->isDeadNode() && !isDeadNode());
738 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
741 // We cannot merge two pieces of the same node together, collapse the node
743 DEBUG(std::cerr << "Attempting to merge two chunks of"
744 << " the same node together!\n");
745 foldNodeCompletely();
749 // If both nodes are not at offset 0, make sure that we are merging the node
750 // at an later offset into the node with the zero offset.
752 if (Offset < NH.getOffset()) {
753 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
755 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
756 // If the offsets are the same, merge the smaller node into the bigger node
757 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
761 // Ok, now we can merge the two nodes. Use a static helper that works with
762 // two node handles, since "this" may get merged away at intermediate steps.
763 DSNodeHandle CurNodeH(this, Offset);
764 DSNodeHandle NHCopy(NH);
765 DSNode::MergeNodes(CurNodeH, NHCopy);
769 //===----------------------------------------------------------------------===//
770 // ReachabilityCloner Implementation
771 //===----------------------------------------------------------------------===//
773 DSNodeHandle ReachabilityCloner::getClonedNH(const DSNodeHandle &SrcNH) {
774 if (SrcNH.isNull()) return DSNodeHandle();
775 const DSNode *SN = SrcNH.getNode();
777 DSNodeHandle &NH = NodeMap[SN];
778 if (!NH.isNull()) // Node already mapped?
779 return DSNodeHandle(NH.getNode(), NH.getOffset()+SrcNH.getOffset());
781 DSNode *DN = new DSNode(*SN, &Dest, true /* Null out all links */);
782 DN->maskNodeTypes(BitsToKeep);
785 // Next, recursively clone all outgoing links as necessary. Note that
786 // adding these links can cause the node to collapse itself at any time, and
787 // the current node may be merged with arbitrary other nodes. For this
788 // reason, we must always go through NH.
790 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
791 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
792 if (!SrcEdge.isNull()) {
793 const DSNodeHandle &DestEdge = getClonedNH(SrcEdge);
794 // Compute the offset into the current node at which to
795 // merge this link. In the common case, this is a linear
796 // relation to the offset in the original node (with
797 // wrapping), but if the current node gets collapsed due to
798 // recursive merging, we must make sure to merge in all remaining
799 // links at offset zero.
800 unsigned MergeOffset = 0;
801 DSNode *CN = NH.getNode();
802 if (CN->getSize() != 1)
803 MergeOffset = ((i << DS::PointerShift)+NH.getOffset()
804 - SrcNH.getOffset()) %CN->getSize();
805 CN->addEdgeTo(MergeOffset, DestEdge);
809 // If this node contains any globals, make sure they end up in the scalar
810 // map with the correct offset.
811 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
813 GlobalValue *GV = *I;
814 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
815 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
816 assert(DestGNH.getNode() == NH.getNode() &&"Global mapping inconsistent");
817 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
818 DestGNH.getOffset()+SrcGNH.getOffset()));
820 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
821 Dest.getInlinedGlobals().insert(GV);
824 return DSNodeHandle(NH.getNode(), NH.getOffset()+SrcNH.getOffset());
827 void ReachabilityCloner::merge(const DSNodeHandle &NH,
828 const DSNodeHandle &SrcNH) {
829 if (SrcNH.isNull()) return; // Noop
831 // If there is no destination node, just clone the source and assign the
832 // destination node to be it.
833 NH.mergeWith(getClonedNH(SrcNH));
837 // Okay, at this point, we know that we have both a destination and a source
838 // node that need to be merged. Check to see if the source node has already
840 const DSNode *SN = SrcNH.getNode();
841 DSNodeHandle &SCNH = NodeMap[SN]; // SourceClonedNodeHandle
842 if (SCNH.getNode()) { // Node already cloned?
843 NH.mergeWith(DSNodeHandle(SCNH.getNode(),
844 SCNH.getOffset()+SrcNH.getOffset()));
846 return; // Nothing to do!
849 // Okay, so the source node has not already been cloned. Instead of creating
850 // a new DSNode, only to merge it into the one we already have, try to perform
851 // the merge in-place. The only case we cannot handle here is when the offset
852 // into the existing node is less than the offset into the virtual node we are
853 // merging in. In this case, we have to extend the existing node, which
854 // requires an allocation anyway.
855 DSNode *DN = NH.getNode(); // Make sure the Offset is up-to-date
856 if (NH.getOffset() >= SrcNH.getOffset()) {
857 if (!DN->isNodeCompletelyFolded()) {
858 // Make sure the destination node is folded if the source node is folded.
859 if (SN->isNodeCompletelyFolded()) {
860 DN->foldNodeCompletely();
862 } else if (SN->getSize() != DN->getSize()) {
863 // If the two nodes are of different size, and the smaller node has the
864 // array bit set, collapse!
865 if (SN->getSize() < DN->getSize()) {
867 DN->foldNodeCompletely();
870 } else if (DN->isArray()) {
871 DN->foldNodeCompletely();
876 // Merge the type entries of the two nodes together...
877 if (SN->getType() != Type::VoidTy && !DN->isNodeCompletelyFolded()) {
878 DN->mergeTypeInfo(SN->getType(), NH.getOffset()-SrcNH.getOffset());
883 assert(!DN->isDeadNode());
885 // Merge the NodeType information.
886 DN->mergeNodeFlags(SN->getNodeFlags() & BitsToKeep);
888 // Before we start merging outgoing links and updating the scalar map, make
889 // sure it is known that this is the representative node for the src node.
890 SCNH = DSNodeHandle(DN, NH.getOffset()-SrcNH.getOffset());
892 // If the source node contains any globals, make sure they end up in the
893 // scalar map with the correct offset.
894 if (SN->global_begin() != SN->global_end()) {
895 // Update the globals in the destination node itself.
896 DN->mergeGlobals(SN->getGlobals());
898 // Update the scalar map for the graph we are merging the source node
900 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
902 GlobalValue *GV = *I;
903 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
904 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
905 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
906 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
907 DestGNH.getOffset()+SrcGNH.getOffset()));
909 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
910 Dest.getInlinedGlobals().insert(GV);
914 // We cannot handle this case without allocating a temporary node. Fall
915 // back on being simple.
916 DSNode *NewDN = new DSNode(*SN, &Dest, true /* Null out all links */);
917 NewDN->maskNodeTypes(BitsToKeep);
919 unsigned NHOffset = NH.getOffset();
920 NH.mergeWith(DSNodeHandle(NewDN, SrcNH.getOffset()));
922 assert(NH.getNode() &&
923 (NH.getOffset() > NHOffset ||
924 (NH.getOffset() == 0 && NH.getNode()->isNodeCompletelyFolded())) &&
925 "Merging did not adjust the offset!");
927 // Before we start merging outgoing links and updating the scalar map, make
928 // sure it is known that this is the representative node for the src node.
929 SCNH = DSNodeHandle(NH.getNode(), NH.getOffset()-SrcNH.getOffset());
931 // If the source node contained any globals, make sure to create entries
932 // in the scalar map for them!
933 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
935 GlobalValue *GV = *I;
936 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
937 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
938 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
939 assert(SrcGNH.getNode() == SN && "Global mapping inconsistent");
940 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
941 DestGNH.getOffset()+SrcGNH.getOffset()));
943 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
944 Dest.getInlinedGlobals().insert(GV);
949 // Next, recursively merge all outgoing links as necessary. Note that
950 // adding these links can cause the destination node to collapse itself at
951 // any time, and the current node may be merged with arbitrary other nodes.
952 // For this reason, we must always go through NH.
954 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
955 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
956 if (!SrcEdge.isNull()) {
957 // Compute the offset into the current node at which to
958 // merge this link. In the common case, this is a linear
959 // relation to the offset in the original node (with
960 // wrapping), but if the current node gets collapsed due to
961 // recursive merging, we must make sure to merge in all remaining
962 // links at offset zero.
963 unsigned MergeOffset = 0;
964 DSNode *CN = SCNH.getNode();
965 if (CN->getSize() != 1)
966 MergeOffset = ((i << DS::PointerShift)+SCNH.getOffset()) %CN->getSize();
968 // Perform the recursive merging. Make sure to create a temporary NH,
969 // because the Link can disappear in the process of recursive merging.
970 DSNodeHandle Tmp = CN->getLink(MergeOffset);
976 /// mergeCallSite - Merge the nodes reachable from the specified src call
977 /// site into the nodes reachable from DestCS.
978 void ReachabilityCloner::mergeCallSite(const DSCallSite &DestCS,
979 const DSCallSite &SrcCS) {
980 merge(DestCS.getRetVal(), SrcCS.getRetVal());
981 unsigned MinArgs = DestCS.getNumPtrArgs();
982 if (SrcCS.getNumPtrArgs() < MinArgs) MinArgs = SrcCS.getNumPtrArgs();
984 for (unsigned a = 0; a != MinArgs; ++a)
985 merge(DestCS.getPtrArg(a), SrcCS.getPtrArg(a));
989 //===----------------------------------------------------------------------===//
990 // DSCallSite Implementation
991 //===----------------------------------------------------------------------===//
993 // Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
994 Function &DSCallSite::getCaller() const {
995 return *Site.getInstruction()->getParent()->getParent();
998 void DSCallSite::InitNH(DSNodeHandle &NH, const DSNodeHandle &Src,
999 ReachabilityCloner &RC) {
1000 NH = RC.getClonedNH(Src);
1003 //===----------------------------------------------------------------------===//
1004 // DSGraph Implementation
1005 //===----------------------------------------------------------------------===//
1007 /// getFunctionNames - Return a space separated list of the name of the
1008 /// functions in this graph (if any)
1009 std::string DSGraph::getFunctionNames() const {
1010 switch (getReturnNodes().size()) {
1011 case 0: return "Globals graph";
1012 case 1: return getReturnNodes().begin()->first->getName();
1015 for (DSGraph::ReturnNodesTy::const_iterator I = getReturnNodes().begin();
1016 I != getReturnNodes().end(); ++I)
1017 Return += I->first->getName() + " ";
1018 Return.erase(Return.end()-1, Return.end()); // Remove last space character
1024 DSGraph::DSGraph(const DSGraph &G) : GlobalsGraph(0), TD(G.TD) {
1025 PrintAuxCalls = false;
1027 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
1030 DSGraph::DSGraph(const DSGraph &G, NodeMapTy &NodeMap)
1031 : GlobalsGraph(0), TD(G.TD) {
1032 PrintAuxCalls = false;
1033 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
1036 DSGraph::~DSGraph() {
1037 FunctionCalls.clear();
1038 AuxFunctionCalls.clear();
1039 InlinedGlobals.clear();
1041 ReturnNodes.clear();
1043 // Drop all intra-node references, so that assertions don't fail...
1044 std::for_each(Nodes.begin(), Nodes.end(),
1045 std::mem_fun(&DSNode::dropAllReferences));
1047 // Delete all of the nodes themselves...
1048 std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
1051 // dump - Allow inspection of graph in a debugger.
1052 void DSGraph::dump() const { print(std::cerr); }
1055 /// remapLinks - Change all of the Links in the current node according to the
1056 /// specified mapping.
1058 void DSNode::remapLinks(DSGraph::NodeMapTy &OldNodeMap) {
1059 for (unsigned i = 0, e = Links.size(); i != e; ++i)
1060 if (DSNode *N = Links[i].getNode()) {
1061 DSGraph::NodeMapTy::const_iterator ONMI = OldNodeMap.find(N);
1062 if (ONMI != OldNodeMap.end()) {
1063 Links[i].setNode(ONMI->second.getNode());
1064 Links[i].setOffset(Links[i].getOffset()+ONMI->second.getOffset());
1069 /// updateFromGlobalGraph - This function rematerializes global nodes and
1070 /// nodes reachable from them from the globals graph into the current graph.
1071 /// It uses the vector InlinedGlobals to avoid cloning and merging globals that
1072 /// are already up-to-date in the current graph. In practice, in the TD pass,
1073 /// this is likely to be a large fraction of the live global nodes in each
1074 /// function (since most live nodes are likely to have been brought up-to-date
1075 /// in at _some_ caller or callee).
1077 void DSGraph::updateFromGlobalGraph() {
1078 TIME_REGION(X, "updateFromGlobalGraph");
1079 ReachabilityCloner RC(*this, *GlobalsGraph, 0);
1081 // Clone the non-up-to-date global nodes into this graph.
1082 for (DSScalarMap::global_iterator I = getScalarMap().global_begin(),
1083 E = getScalarMap().global_end(); I != E; ++I)
1084 if (InlinedGlobals.count(*I) == 0) { // GNode is not up-to-date
1085 DSScalarMap::iterator It = GlobalsGraph->ScalarMap.find(*I);
1086 if (It != GlobalsGraph->ScalarMap.end())
1087 RC.merge(getNodeForValue(*I), It->second);
1091 /// cloneInto - Clone the specified DSGraph into the current graph. The
1092 /// translated ScalarMap for the old function is filled into the OldValMap
1093 /// member, and the translated ReturnNodes map is returned into ReturnNodes.
1095 /// The CloneFlags member controls various aspects of the cloning process.
1097 void DSGraph::cloneInto(const DSGraph &G, DSScalarMap &OldValMap,
1098 ReturnNodesTy &OldReturnNodes, NodeMapTy &OldNodeMap,
1099 unsigned CloneFlags) {
1100 TIME_REGION(X, "cloneInto");
1101 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
1102 assert(&G != this && "Cannot clone graph into itself!");
1104 unsigned FN = Nodes.size(); // First new node...
1106 // Duplicate all of the nodes, populating the node map...
1107 Nodes.reserve(FN+G.Nodes.size());
1109 // Remove alloca or mod/ref bits as specified...
1110 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
1111 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
1112 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
1113 BitsToClear |= DSNode::DEAD; // Clear dead flag...
1114 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
1115 DSNode *Old = G.Nodes[i];
1116 if (!Old->isForwarding()) {
1117 DSNode *New = new DSNode(*Old, this);
1118 New->maskNodeTypes(~BitsToClear);
1119 OldNodeMap[Old] = New;
1123 Timer::addPeakMemoryMeasurement();
1126 // Rewrite the links in the new nodes to point into the current graph now.
1127 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
1128 Nodes[i]->remapLinks(OldNodeMap);
1130 // Copy the scalar map... merging all of the global nodes...
1131 for (DSScalarMap::const_iterator I = G.ScalarMap.begin(),
1132 E = G.ScalarMap.end(); I != E; ++I) {
1133 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
1134 DSNodeHandle &H = OldValMap[I->first];
1135 H.mergeWith(DSNodeHandle(MappedNode.getNode(),
1136 I->second.getOffset()+MappedNode.getOffset()));
1138 // If this is a global, add the global to this fn or merge if already exists
1139 if (GlobalValue* GV = dyn_cast<GlobalValue>(I->first)) {
1140 ScalarMap[GV].mergeWith(H);
1141 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
1142 InlinedGlobals.insert(GV);
1146 if (!(CloneFlags & DontCloneCallNodes)) {
1147 // Copy the function calls list...
1148 unsigned FC = FunctionCalls.size(); // FirstCall
1149 FunctionCalls.reserve(FC+G.FunctionCalls.size());
1150 for (unsigned i = 0, ei = G.FunctionCalls.size(); i != ei; ++i)
1151 FunctionCalls.push_back(DSCallSite(G.FunctionCalls[i], OldNodeMap));
1154 if (!(CloneFlags & DontCloneAuxCallNodes)) {
1155 // Copy the auxiliary function calls list...
1156 unsigned FC = AuxFunctionCalls.size(); // FirstCall
1157 AuxFunctionCalls.reserve(FC+G.AuxFunctionCalls.size());
1158 for (unsigned i = 0, ei = G.AuxFunctionCalls.size(); i != ei; ++i)
1159 AuxFunctionCalls.push_back(DSCallSite(G.AuxFunctionCalls[i], OldNodeMap));
1162 // Map the return node pointers over...
1163 for (ReturnNodesTy::const_iterator I = G.getReturnNodes().begin(),
1164 E = G.getReturnNodes().end(); I != E; ++I) {
1165 const DSNodeHandle &Ret = I->second;
1166 DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
1167 OldReturnNodes.insert(std::make_pair(I->first,
1168 DSNodeHandle(MappedRet.getNode(),
1169 MappedRet.getOffset()+Ret.getOffset())));
1174 /// mergeInGraph - The method is used for merging graphs together. If the
1175 /// argument graph is not *this, it makes a clone of the specified graph, then
1176 /// merges the nodes specified in the call site with the formal arguments in the
1179 void DSGraph::mergeInGraph(const DSCallSite &CS, Function &F,
1180 const DSGraph &Graph, unsigned CloneFlags) {
1181 TIME_REGION(X, "mergeInGraph");
1183 // If this is not a recursive call, clone the graph into this graph...
1184 if (&Graph != this) {
1185 // Clone the callee's graph into the current graph, keeping track of where
1186 // scalars in the old graph _used_ to point, and of the new nodes matching
1187 // nodes of the old graph.
1188 ReachabilityCloner RC(*this, Graph, CloneFlags);
1190 // Set up argument bindings
1191 Function::aiterator AI = F.abegin();
1192 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
1193 // Advance the argument iterator to the first pointer argument...
1194 while (AI != F.aend() && !isPointerType(AI->getType())) {
1196 #ifndef NDEBUG // FIXME: We should merge vararg arguments!
1197 if (AI == F.aend() && !F.getFunctionType()->isVarArg())
1198 std::cerr << "Bad call to Function: " << F.getName() << "\n";
1201 if (AI == F.aend()) break;
1203 // Add the link from the argument scalar to the provided value.
1204 RC.merge(CS.getPtrArg(i), Graph.getNodeForValue(AI));
1207 // Map the return node pointer over.
1208 if (CS.getRetVal().getNode())
1209 RC.merge(CS.getRetVal(), Graph.getReturnNodeFor(F));
1211 // If requested, copy the calls or aux-calls lists.
1212 if (!(CloneFlags & DontCloneCallNodes)) {
1213 // Copy the function calls list...
1214 FunctionCalls.reserve(FunctionCalls.size()+Graph.FunctionCalls.size());
1215 for (unsigned i = 0, ei = Graph.FunctionCalls.size(); i != ei; ++i)
1216 FunctionCalls.push_back(DSCallSite(Graph.FunctionCalls[i], RC));
1219 if (!(CloneFlags & DontCloneAuxCallNodes)) {
1220 // Copy the auxiliary function calls list...
1221 AuxFunctionCalls.reserve(AuxFunctionCalls.size()+
1222 Graph.AuxFunctionCalls.size());
1223 for (unsigned i = 0, ei = Graph.AuxFunctionCalls.size(); i != ei; ++i)
1224 AuxFunctionCalls.push_back(DSCallSite(Graph.AuxFunctionCalls[i], RC));
1227 // If the user requested it, add the nodes that we need to clone to the
1229 if (!EnableDSNodeGlobalRootsHack)
1230 for (unsigned i = 0, e = Graph.Nodes.size(); i != e; ++i)
1231 if (!Graph.Nodes[i]->getGlobals().empty())
1232 RC.getClonedNH(Graph.Nodes[i]);
1235 DSNodeHandle RetVal = getReturnNodeFor(F);
1237 // Merge the return value with the return value of the context...
1238 RetVal.mergeWith(CS.getRetVal());
1240 // Resolve all of the function arguments...
1241 Function::aiterator AI = F.abegin();
1243 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
1244 // Advance the argument iterator to the first pointer argument...
1245 while (AI != F.aend() && !isPointerType(AI->getType())) {
1247 #ifndef NDEBUG // FIXME: We should merge varargs arguments!!
1248 if (AI == F.aend() && !F.getFunctionType()->isVarArg())
1249 std::cerr << "Bad call to Function: " << F.getName() << "\n";
1252 if (AI == F.aend()) break;
1254 // Add the link from the argument scalar to the provided value
1255 DSNodeHandle &NH = getNodeForValue(AI);
1256 assert(NH.getNode() && "Pointer argument without scalarmap entry?");
1257 NH.mergeWith(CS.getPtrArg(i));
1262 /// getCallSiteForArguments - Get the arguments and return value bindings for
1263 /// the specified function in the current graph.
1265 DSCallSite DSGraph::getCallSiteForArguments(Function &F) const {
1266 std::vector<DSNodeHandle> Args;
1268 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
1269 if (isPointerType(I->getType()))
1270 Args.push_back(getNodeForValue(I));
1272 return DSCallSite(CallSite(), getReturnNodeFor(F), &F, Args);
1277 // markIncompleteNodes - Mark the specified node as having contents that are not
1278 // known with the current analysis we have performed. Because a node makes all
1279 // of the nodes it can reach incomplete if the node itself is incomplete, we
1280 // must recursively traverse the data structure graph, marking all reachable
1281 // nodes as incomplete.
1283 static void markIncompleteNode(DSNode *N) {
1284 // Stop recursion if no node, or if node already marked...
1285 if (N == 0 || N->isIncomplete()) return;
1287 // Actually mark the node
1288 N->setIncompleteMarker();
1290 // Recursively process children...
1291 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
1292 if (DSNode *DSN = N->getLink(i).getNode())
1293 markIncompleteNode(DSN);
1296 static void markIncomplete(DSCallSite &Call) {
1297 // Then the return value is certainly incomplete!
1298 markIncompleteNode(Call.getRetVal().getNode());
1300 // All objects pointed to by function arguments are incomplete!
1301 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
1302 markIncompleteNode(Call.getPtrArg(i).getNode());
1305 // markIncompleteNodes - Traverse the graph, identifying nodes that may be
1306 // modified by other functions that have not been resolved yet. This marks
1307 // nodes that are reachable through three sources of "unknownness":
1309 // Global Variables, Function Calls, and Incoming Arguments
1311 // For any node that may have unknown components (because something outside the
1312 // scope of current analysis may have modified it), the 'Incomplete' flag is
1313 // added to the NodeType.
1315 void DSGraph::markIncompleteNodes(unsigned Flags) {
1316 // Mark any incoming arguments as incomplete...
1317 if (Flags & DSGraph::MarkFormalArgs)
1318 for (ReturnNodesTy::iterator FI = ReturnNodes.begin(), E =ReturnNodes.end();
1320 Function &F = *FI->first;
1321 if (F.getName() != "main")
1322 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
1323 if (isPointerType(I->getType()))
1324 markIncompleteNode(getNodeForValue(I).getNode());
1327 // Mark stuff passed into functions calls as being incomplete...
1328 if (!shouldPrintAuxCalls())
1329 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1330 markIncomplete(FunctionCalls[i]);
1332 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1333 markIncomplete(AuxFunctionCalls[i]);
1336 // Mark all global nodes as incomplete...
1337 if ((Flags & DSGraph::IgnoreGlobals) == 0)
1338 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
1339 if (Nodes[i]->isGlobalNode() && Nodes[i]->getNumLinks())
1340 markIncompleteNode(Nodes[i]);
1343 static inline void killIfUselessEdge(DSNodeHandle &Edge) {
1344 if (DSNode *N = Edge.getNode()) // Is there an edge?
1345 if (N->getNumReferrers() == 1) // Does it point to a lonely node?
1346 // No interesting info?
1347 if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
1348 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
1349 Edge.setNode(0); // Kill the edge!
1352 static inline bool nodeContainsExternalFunction(const DSNode *N) {
1353 const std::vector<GlobalValue*> &Globals = N->getGlobals();
1354 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
1355 if (Globals[i]->isExternal())
1360 static void removeIdenticalCalls(std::vector<DSCallSite> &Calls) {
1361 // Remove trivially identical function calls
1362 unsigned NumFns = Calls.size();
1363 std::sort(Calls.begin(), Calls.end()); // Sort by callee as primary key!
1366 // Scan the call list cleaning it up as necessary...
1367 DSNode *LastCalleeNode = 0;
1368 Function *LastCalleeFunc = 0;
1369 unsigned NumDuplicateCalls = 0;
1370 bool LastCalleeContainsExternalFunction = false;
1371 for (unsigned i = 0; i != Calls.size(); ++i) {
1372 DSCallSite &CS = Calls[i];
1374 // If the Callee is a useless edge, this must be an unreachable call site,
1376 if (CS.isIndirectCall() && CS.getCalleeNode()->getNumReferrers() == 1 &&
1377 CS.getCalleeNode()->getNodeFlags() == 0) { // No useful info?
1379 std::cerr << "WARNING: Useless call site found??\n";
1381 CS.swap(Calls.back());
1385 // If the return value or any arguments point to a void node with no
1386 // information at all in it, and the call node is the only node to point
1387 // to it, remove the edge to the node (killing the node).
1389 killIfUselessEdge(CS.getRetVal());
1390 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
1391 killIfUselessEdge(CS.getPtrArg(a));
1393 // If this call site calls the same function as the last call site, and if
1394 // the function pointer contains an external function, this node will
1395 // never be resolved. Merge the arguments of the call node because no
1396 // information will be lost.
1398 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
1399 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
1400 ++NumDuplicateCalls;
1401 if (NumDuplicateCalls == 1) {
1403 LastCalleeContainsExternalFunction =
1404 nodeContainsExternalFunction(LastCalleeNode);
1406 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
1409 // It is not clear why, but enabling this code makes DSA really
1410 // sensitive to node forwarding. Basically, with this enabled, DSA
1411 // performs different number of inlinings based on which nodes are
1412 // forwarding or not. This is clearly a problem, so this code is
1413 // disabled until this can be resolved.
1415 if (LastCalleeContainsExternalFunction
1418 // This should be more than enough context sensitivity!
1419 // FIXME: Evaluate how many times this is tripped!
1420 NumDuplicateCalls > 20
1423 DSCallSite &OCS = Calls[i-1];
1426 // The node will now be eliminated as a duplicate!
1427 if (CS.getNumPtrArgs() < OCS.getNumPtrArgs())
1429 else if (CS.getNumPtrArgs() > OCS.getNumPtrArgs())
1434 if (CS.isDirectCall()) {
1435 LastCalleeFunc = CS.getCalleeFunc();
1438 LastCalleeNode = CS.getCalleeNode();
1441 NumDuplicateCalls = 0;
1446 Calls.erase(std::unique(Calls.begin(), Calls.end()), Calls.end());
1448 // Track the number of call nodes merged away...
1449 NumCallNodesMerged += NumFns-Calls.size();
1451 DEBUG(if (NumFns != Calls.size())
1452 std::cerr << "Merged " << (NumFns-Calls.size()) << " call nodes.\n";);
1456 // removeTriviallyDeadNodes - After the graph has been constructed, this method
1457 // removes all unreachable nodes that are created because they got merged with
1458 // other nodes in the graph. These nodes will all be trivially unreachable, so
1459 // we don't have to perform any non-trivial analysis here.
1461 void DSGraph::removeTriviallyDeadNodes() {
1462 TIME_REGION(X, "removeTriviallyDeadNodes");
1463 removeIdenticalCalls(FunctionCalls);
1464 removeIdenticalCalls(AuxFunctionCalls);
1466 // Loop over all of the nodes in the graph, calling getNode on each field.
1467 // This will cause all nodes to update their forwarding edges, causing
1468 // forwarded nodes to be delete-able.
1469 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1470 DSNode *N = Nodes[i];
1471 for (unsigned l = 0, e = N->getNumLinks(); l != e; ++l)
1472 N->getLink(l*N->getPointerSize()).getNode();
1475 // NOTE: This code is disabled. Though it should, in theory, allow us to
1476 // remove more nodes down below, the scan of the scalar map is incredibly
1477 // expensive for certain programs (with large SCCs). In the future, if we can
1478 // make the scalar map scan more efficient, then we can reenable this.
1480 { TIME_REGION(X, "removeTriviallyDeadNodes:scalarmap");
1482 // Likewise, forward any edges from the scalar nodes. While we are at it,
1483 // clean house a bit.
1484 for (DSScalarMap::iterator I = ScalarMap.begin(),E = ScalarMap.end();I != E;){
1485 I->second.getNode();
1490 bool isGlobalsGraph = !GlobalsGraph;
1492 for (unsigned i = 0; i != Nodes.size(); ++i) {
1493 DSNode *Node = Nodes[i];
1495 // Do not remove *any* global nodes in the globals graph.
1496 // This is a special case because such nodes may not have I, M, R flags set.
1497 if (Node->isGlobalNode() && isGlobalsGraph)
1500 if (Node->isComplete() && !Node->isModified() && !Node->isRead()) {
1501 // This is a useless node if it has no mod/ref info (checked above),
1502 // outgoing edges (which it cannot, as it is not modified in this
1503 // context), and it has no incoming edges. If it is a global node it may
1504 // have all of these properties and still have incoming edges, due to the
1505 // scalar map, so we check those now.
1507 if (Node->getNumReferrers() == Node->getGlobals().size()) {
1508 const std::vector<GlobalValue*> &Globals = Node->getGlobals();
1510 // Loop through and make sure all of the globals are referring directly
1512 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1513 DSNode *N = getNodeForValue(Globals[j]).getNode();
1514 assert(N == Node && "ScalarMap doesn't match globals list!");
1517 // Make sure NumReferrers still agrees, if so, the node is truly dead.
1518 if (Node->getNumReferrers() == Globals.size()) {
1519 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1520 ScalarMap.erase(Globals[j]);
1521 Node->makeNodeDead();
1526 if (Node->getNodeFlags() == 0 && Node->hasNoReferrers()) {
1527 // This node is dead!
1528 delete Node; // Free memory...
1529 Nodes[i--] = Nodes.back();
1530 Nodes.pop_back(); // Remove from node list...
1536 /// markReachableNodes - This method recursively traverses the specified
1537 /// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
1538 /// to the set, which allows it to only traverse visited nodes once.
1540 void DSNode::markReachableNodes(hash_set<DSNode*> &ReachableNodes) {
1541 if (this == 0) return;
1542 assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
1543 if (ReachableNodes.insert(this).second) // Is newly reachable?
1544 for (unsigned i = 0, e = getSize(); i < e; i += DS::PointerSize)
1545 getLink(i).getNode()->markReachableNodes(ReachableNodes);
1548 void DSCallSite::markReachableNodes(hash_set<DSNode*> &Nodes) {
1549 getRetVal().getNode()->markReachableNodes(Nodes);
1550 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
1552 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
1553 getPtrArg(i).getNode()->markReachableNodes(Nodes);
1556 // CanReachAliveNodes - Simple graph walker that recursively traverses the graph
1557 // looking for a node that is marked alive. If an alive node is found, return
1558 // true, otherwise return false. If an alive node is reachable, this node is
1559 // marked as alive...
1561 static bool CanReachAliveNodes(DSNode *N, hash_set<DSNode*> &Alive,
1562 hash_set<DSNode*> &Visited,
1563 bool IgnoreGlobals) {
1564 if (N == 0) return false;
1565 assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
1567 // If this is a global node, it will end up in the globals graph anyway, so we
1568 // don't need to worry about it.
1569 if (IgnoreGlobals && N->isGlobalNode()) return false;
1571 // If we know that this node is alive, return so!
1572 if (Alive.count(N)) return true;
1574 // Otherwise, we don't think the node is alive yet, check for infinite
1576 if (Visited.count(N)) return false; // Found a cycle
1577 Visited.insert(N); // No recursion, insert into Visited...
1579 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
1580 if (CanReachAliveNodes(N->getLink(i).getNode(), Alive, Visited,
1582 N->markReachableNodes(Alive);
1588 // CallSiteUsesAliveArgs - Return true if the specified call site can reach any
1591 static bool CallSiteUsesAliveArgs(DSCallSite &CS, hash_set<DSNode*> &Alive,
1592 hash_set<DSNode*> &Visited,
1593 bool IgnoreGlobals) {
1594 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited,
1597 if (CS.isIndirectCall() &&
1598 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited, IgnoreGlobals))
1600 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
1601 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited,
1607 // removeDeadNodes - Use a more powerful reachability analysis to eliminate
1608 // subgraphs that are unreachable. This often occurs because the data
1609 // structure doesn't "escape" into it's caller, and thus should be eliminated
1610 // from the caller's graph entirely. This is only appropriate to use when
1613 void DSGraph::removeDeadNodes(unsigned Flags) {
1614 DEBUG(AssertGraphOK(); if (GlobalsGraph) GlobalsGraph->AssertGraphOK());
1616 // Reduce the amount of work we have to do... remove dummy nodes left over by
1618 removeTriviallyDeadNodes();
1620 TIME_REGION(X, "removeDeadNodes");
1622 // FIXME: Merge non-trivially identical call nodes...
1624 // Alive - a set that holds all nodes found to be reachable/alive.
1625 hash_set<DSNode*> Alive;
1626 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
1628 // Copy and merge all information about globals to the GlobalsGraph if this is
1629 // not a final pass (where unreachable globals are removed).
1631 // Strip all alloca bits since the current function is only for the BU pass.
1632 // Strip all incomplete bits since they are short-lived properties and they
1633 // will be correctly computed when rematerializing nodes into the functions.
1635 ReachabilityCloner GGCloner(*GlobalsGraph, *this, DSGraph::StripAllocaBit |
1636 DSGraph::StripIncompleteBit);
1638 // Mark all nodes reachable by (non-global) scalar nodes as alive...
1639 { TIME_REGION(Y, "removeDeadNodes:scalarscan");
1640 for (DSScalarMap::iterator I = ScalarMap.begin(), E = ScalarMap.end(); I !=E;)
1641 if (isa<GlobalValue>(I->first)) { // Keep track of global nodes
1642 assert(I->second.getNode() && "Null global node?");
1643 assert(I->second.getNode()->isGlobalNode() && "Should be a global node!");
1644 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
1646 // Make sure that all globals are cloned over as roots.
1647 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
1648 DSGraph::ScalarMapTy::iterator SMI =
1649 GlobalsGraph->getScalarMap().find(I->first);
1650 if (SMI != GlobalsGraph->getScalarMap().end())
1651 GGCloner.merge(SMI->second, I->second);
1653 GGCloner.getClonedNH(I->second);
1657 DSNode *N = I->second.getNode();
1659 // Check to see if this is a worthless node generated for non-pointer
1660 // values, such as integers. Consider an addition of long types: A+B.
1661 // Assuming we can track all uses of the value in this context, and it is
1662 // NOT used as a pointer, we can delete the node. We will be able to
1663 // detect this situation if the node pointed to ONLY has Unknown bit set
1664 // in the node. In this case, the node is not incomplete, does not point
1665 // to any other nodes (no mod/ref bits set), and is therefore
1666 // uninteresting for data structure analysis. If we run across one of
1667 // these, prune the scalar pointing to it.
1669 if (N->getNodeFlags() == DSNode::UnknownNode && !isa<Argument>(I->first))
1670 ScalarMap.erase(I++);
1673 N->markReachableNodes(Alive);
1679 // The return values are alive as well.
1680 for (ReturnNodesTy::iterator I = ReturnNodes.begin(), E = ReturnNodes.end();
1682 I->second.getNode()->markReachableNodes(Alive);
1684 // Mark any nodes reachable by primary calls as alive...
1685 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1686 FunctionCalls[i].markReachableNodes(Alive);
1689 // Now find globals and aux call nodes that are already live or reach a live
1690 // value (which makes them live in turn), and continue till no more are found.
1693 hash_set<DSNode*> Visited;
1694 std::vector<unsigned char> AuxFCallsAlive(AuxFunctionCalls.size());
1697 // If any global node points to a non-global that is "alive", the global is
1698 // "alive" as well... Remove it from the GlobalNodes list so we only have
1699 // unreachable globals in the list.
1702 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
1703 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
1704 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited,
1705 Flags & DSGraph::RemoveUnreachableGlobals)) {
1706 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to...
1707 GlobalNodes.pop_back(); // erase efficiently
1711 // Mark only unresolvable call nodes for moving to the GlobalsGraph since
1712 // call nodes that get resolved will be difficult to remove from that graph.
1713 // The final unresolved call nodes must be handled specially at the end of
1714 // the BU pass (i.e., in main or other roots of the call graph).
1715 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1716 if (!AuxFCallsAlive[i] &&
1717 (AuxFunctionCalls[i].isIndirectCall()
1718 || CallSiteUsesAliveArgs(AuxFunctionCalls[i], Alive, Visited,
1719 Flags & DSGraph::RemoveUnreachableGlobals))) {
1720 AuxFunctionCalls[i].markReachableNodes(Alive);
1721 AuxFCallsAlive[i] = true;
1726 // Move dead aux function calls to the end of the list
1727 unsigned CurIdx = 0;
1728 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1729 if (AuxFCallsAlive[i])
1730 AuxFunctionCalls[CurIdx++].swap(AuxFunctionCalls[i]);
1732 // Copy and merge all global nodes and dead aux call nodes into the
1733 // GlobalsGraph, and all nodes reachable from those nodes
1735 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
1736 // Copy the unreachable call nodes to the globals graph, updating their
1737 // target pointers using the GGCloner
1738 for (unsigned i = CurIdx, e = AuxFunctionCalls.size(); i != e; ++i)
1739 GlobalsGraph->AuxFunctionCalls.push_back(DSCallSite(AuxFunctionCalls[i],
1742 // Crop all the useless ones out...
1743 AuxFunctionCalls.erase(AuxFunctionCalls.begin()+CurIdx,
1744 AuxFunctionCalls.end());
1746 // We are finally done with the GGCloner so we can clear it and then get rid
1747 // of unused nodes in the GlobalsGraph produced by merging.
1748 if (GGCloner.clonedNode()) {
1750 GlobalsGraph->removeTriviallyDeadNodes();
1753 // At this point, any nodes which are visited, but not alive, are nodes
1754 // which can be removed. Loop over all nodes, eliminating completely
1755 // unreachable nodes.
1757 std::vector<DSNode*> DeadNodes;
1758 DeadNodes.reserve(Nodes.size());
1759 for (unsigned i = 0; i != Nodes.size(); ++i)
1760 if (!Alive.count(Nodes[i])) {
1762 DSNode *N = Nodes[i];
1763 Nodes[i--] = Nodes.back(); // move node to end of vector
1764 Nodes.pop_back(); // Erase node from alive list.
1765 DeadNodes.push_back(N);
1766 N->dropAllReferences();
1768 assert(Nodes[i]->getForwardNode() == 0 && "Alive forwarded node?");
1771 // Remove all unreachable globals from the ScalarMap.
1772 // If flag RemoveUnreachableGlobals is set, GlobalNodes has only dead nodes.
1773 // In either case, the dead nodes will not be in the set Alive.
1774 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
1775 if (!Alive.count(GlobalNodes[i].second))
1776 ScalarMap.erase(GlobalNodes[i].first);
1778 assert((Flags & DSGraph::RemoveUnreachableGlobals) && "non-dead global");
1780 // Delete all dead nodes now since their referrer counts are zero.
1781 for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
1782 delete DeadNodes[i];
1784 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
1787 void DSGraph::AssertGraphOK() const {
1788 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
1789 Nodes[i]->assertOK();
1791 for (ScalarMapTy::const_iterator I = ScalarMap.begin(),
1792 E = ScalarMap.end(); I != E; ++I) {
1793 assert(I->second.getNode() && "Null node in scalarmap!");
1794 AssertNodeInGraph(I->second.getNode());
1795 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
1796 assert(I->second.getNode()->isGlobalNode() &&
1797 "Global points to node, but node isn't global?");
1798 AssertNodeContainsGlobal(I->second.getNode(), GV);
1801 AssertCallNodesInGraph();
1802 AssertAuxCallNodesInGraph();
1805 /// computeNodeMapping - Given roots in two different DSGraphs, traverse the
1806 /// nodes reachable from the two graphs, computing the mapping of nodes from
1807 /// the first to the second graph.
1809 void DSGraph::computeNodeMapping(const DSNodeHandle &NH1,
1810 const DSNodeHandle &NH2, NodeMapTy &NodeMap,
1811 bool StrictChecking) {
1812 DSNode *N1 = NH1.getNode(), *N2 = NH2.getNode();
1813 if (N1 == 0 || N2 == 0) return;
1815 DSNodeHandle &Entry = NodeMap[N1];
1816 if (Entry.getNode()) {
1817 // Termination of recursion!
1818 assert(!StrictChecking ||
1819 (Entry.getNode() == N2 &&
1820 Entry.getOffset() == (NH2.getOffset()-NH1.getOffset())) &&
1821 "Inconsistent mapping detected!");
1826 Entry.setOffset(NH2.getOffset()-NH1.getOffset());
1828 // Loop over all of the fields that N1 and N2 have in common, recursively
1829 // mapping the edges together now.
1830 int N2Idx = NH2.getOffset()-NH1.getOffset();
1831 unsigned N2Size = N2->getSize();
1832 for (unsigned i = 0, e = N1->getSize(); i < e; i += DS::PointerSize)
1833 if (unsigned(N2Idx)+i < N2Size)
1834 computeNodeMapping(N1->getLink(i), N2->getLink(N2Idx+i), NodeMap);