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");
33 Statistic<> NumTrivialDNE ("dsa", "Number of nodes trivially removed");
34 Statistic<> NumTrivialGlobalDNE("dsa", "Number of globals trivially removed");
37 EnableDSNodeGlobalRootsHack("enable-dsa-globalrootshack", cl::Hidden,
38 cl::desc("Make DSA less aggressive when cloning graphs"));
42 #define TIME_REGION(VARNAME, DESC) \
43 NamedRegionTimer VARNAME(DESC)
45 #define TIME_REGION(VARNAME, DESC)
50 DSNode *DSNodeHandle::HandleForwarding() const {
51 assert(N->isForwarding() && "Can only be invoked if forwarding!");
53 // Handle node forwarding here!
54 DSNode *Next = N->ForwardNH.getNode(); // Cause recursive shrinkage
55 Offset += N->ForwardNH.getOffset();
57 if (--N->NumReferrers == 0) {
58 // Removing the last referrer to the node, sever the forwarding link
64 if (N->Size <= Offset) {
65 assert(N->Size <= 1 && "Forwarded to shrunk but not collapsed node?");
71 //===----------------------------------------------------------------------===//
72 // DSNode Implementation
73 //===----------------------------------------------------------------------===//
75 DSNode::DSNode(const Type *T, DSGraph *G)
76 : NumReferrers(0), Size(0), ParentGraph(G), Ty(Type::VoidTy), NodeType(0) {
77 // Add the type entry if it is specified...
78 if (T) mergeTypeInfo(T, 0);
79 if (G) G->addNode(this);
83 // DSNode copy constructor... do not copy over the referrers list!
84 DSNode::DSNode(const DSNode &N, DSGraph *G, bool NullLinks)
85 : NumReferrers(0), Size(N.Size), ParentGraph(G),
86 Ty(N.Ty), Globals(N.Globals), NodeType(N.NodeType) {
90 Links.resize(N.Links.size()); // Create the appropriate number of null links
95 /// getTargetData - Get the target data object used to construct this node.
97 const TargetData &DSNode::getTargetData() const {
98 return ParentGraph->getTargetData();
101 void DSNode::assertOK() const {
102 assert((Ty != Type::VoidTy ||
103 Ty == Type::VoidTy && (Size == 0 ||
104 (NodeType & DSNode::Array))) &&
107 assert(ParentGraph && "Node has no parent?");
108 const DSScalarMap &SM = ParentGraph->getScalarMap();
109 for (unsigned i = 0, e = Globals.size(); i != e; ++i) {
110 assert(SM.count(Globals[i]));
111 assert(SM.find(Globals[i])->second.getNode() == this);
115 /// forwardNode - Mark this node as being obsolete, and all references to it
116 /// should be forwarded to the specified node and offset.
118 void DSNode::forwardNode(DSNode *To, unsigned Offset) {
119 assert(this != To && "Cannot forward a node to itself!");
120 assert(ForwardNH.isNull() && "Already forwarding from this node!");
121 if (To->Size <= 1) Offset = 0;
122 assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
123 "Forwarded offset is wrong!");
124 ForwardNH.setNode(To);
125 ForwardNH.setOffset(Offset);
130 // Remove this node from the parent graph's Nodes list.
131 ParentGraph->unlinkNode(this);
135 // addGlobal - Add an entry for a global value to the Globals list. This also
136 // marks the node with the 'G' flag if it does not already have it.
138 void DSNode::addGlobal(GlobalValue *GV) {
139 // Keep the list sorted.
140 std::vector<GlobalValue*>::iterator I =
141 std::lower_bound(Globals.begin(), Globals.end(), GV);
143 if (I == Globals.end() || *I != GV) {
144 //assert(GV->getType()->getElementType() == Ty);
145 Globals.insert(I, GV);
146 NodeType |= GlobalNode;
150 /// foldNodeCompletely - If we determine that this node has some funny
151 /// behavior happening to it that we cannot represent, we fold it down to a
152 /// single, completely pessimistic, node. This node is represented as a
153 /// single byte with a single TypeEntry of "void".
155 void DSNode::foldNodeCompletely() {
156 if (isNodeCompletelyFolded()) return; // If this node is already folded...
160 // If this node has a size that is <= 1, we don't need to create a forwarding
162 if (getSize() <= 1) {
163 NodeType |= DSNode::Array;
166 assert(Links.size() <= 1 && "Size is 1, but has more links?");
169 // Create the node we are going to forward to. This is required because
170 // some referrers may have an offset that is > 0. By forcing them to
171 // forward, the forwarder has the opportunity to correct the offset.
172 DSNode *DestNode = new DSNode(0, ParentGraph);
173 DestNode->NodeType = NodeType|DSNode::Array;
174 DestNode->Ty = Type::VoidTy;
176 DestNode->Globals.swap(Globals);
178 // Start forwarding to the destination node...
179 forwardNode(DestNode, 0);
181 if (!Links.empty()) {
182 DestNode->Links.reserve(1);
184 DSNodeHandle NH(DestNode);
185 DestNode->Links.push_back(Links[0]);
187 // If we have links, merge all of our outgoing links together...
188 for (unsigned i = Links.size()-1; i != 0; --i)
189 NH.getNode()->Links[0].mergeWith(Links[i]);
192 DestNode->Links.resize(1);
197 /// isNodeCompletelyFolded - Return true if this node has been completely
198 /// folded down to something that can never be expanded, effectively losing
199 /// all of the field sensitivity that may be present in the node.
201 bool DSNode::isNodeCompletelyFolded() const {
202 return getSize() == 1 && Ty == Type::VoidTy && isArray();
206 /// TypeElementWalker Class - Used for implementation of physical subtyping...
208 class TypeElementWalker {
213 StackState(const Type *T, unsigned Off = 0)
214 : Ty(T), Offset(Off), Idx(0) {}
217 std::vector<StackState> Stack;
218 const TargetData &TD;
220 TypeElementWalker(const Type *T, const TargetData &td) : TD(td) {
225 bool isDone() const { return Stack.empty(); }
226 const Type *getCurrentType() const { return Stack.back().Ty; }
227 unsigned getCurrentOffset() const { return Stack.back().Offset; }
229 void StepToNextType() {
230 PopStackAndAdvance();
235 /// PopStackAndAdvance - Pop the current element off of the stack and
236 /// advance the underlying element to the next contained member.
237 void PopStackAndAdvance() {
238 assert(!Stack.empty() && "Cannot pop an empty stack!");
240 while (!Stack.empty()) {
241 StackState &SS = Stack.back();
242 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
244 if (SS.Idx != ST->getNumElements()) {
245 const StructLayout *SL = TD.getStructLayout(ST);
246 SS.Offset += SL->MemberOffsets[SS.Idx]-SL->MemberOffsets[SS.Idx-1];
249 Stack.pop_back(); // At the end of the structure
251 const ArrayType *AT = cast<ArrayType>(SS.Ty);
253 if (SS.Idx != AT->getNumElements()) {
254 SS.Offset += TD.getTypeSize(AT->getElementType());
257 Stack.pop_back(); // At the end of the array
262 /// StepToLeaf - Used by physical subtyping to move to the first leaf node
263 /// on the type stack.
265 if (Stack.empty()) return;
266 while (!Stack.empty() && !Stack.back().Ty->isFirstClassType()) {
267 StackState &SS = Stack.back();
268 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
269 if (ST->getNumElements() == 0) {
271 PopStackAndAdvance();
273 // Step into the structure...
274 assert(SS.Idx < ST->getNumElements());
275 const StructLayout *SL = TD.getStructLayout(ST);
276 Stack.push_back(StackState(ST->getElementType(SS.Idx),
277 SS.Offset+SL->MemberOffsets[SS.Idx]));
280 const ArrayType *AT = cast<ArrayType>(SS.Ty);
281 if (AT->getNumElements() == 0) {
283 PopStackAndAdvance();
285 // Step into the array...
286 assert(SS.Idx < AT->getNumElements());
287 Stack.push_back(StackState(AT->getElementType(),
289 TD.getTypeSize(AT->getElementType())));
295 } // end anonymous namespace
297 /// ElementTypesAreCompatible - Check to see if the specified types are
298 /// "physically" compatible. If so, return true, else return false. We only
299 /// have to check the fields in T1: T2 may be larger than T1. If AllowLargerT1
300 /// is true, then we also allow a larger T1.
302 static bool ElementTypesAreCompatible(const Type *T1, const Type *T2,
303 bool AllowLargerT1, const TargetData &TD){
304 TypeElementWalker T1W(T1, TD), T2W(T2, TD);
306 while (!T1W.isDone() && !T2W.isDone()) {
307 if (T1W.getCurrentOffset() != T2W.getCurrentOffset())
310 const Type *T1 = T1W.getCurrentType();
311 const Type *T2 = T2W.getCurrentType();
312 if (T1 != T2 && !T1->isLosslesslyConvertibleTo(T2))
315 T1W.StepToNextType();
316 T2W.StepToNextType();
319 return AllowLargerT1 || T1W.isDone();
323 /// mergeTypeInfo - This method merges the specified type into the current node
324 /// at the specified offset. This may update the current node's type record if
325 /// this gives more information to the node, it may do nothing to the node if
326 /// this information is already known, or it may merge the node completely (and
327 /// return true) if the information is incompatible with what is already known.
329 /// This method returns true if the node is completely folded, otherwise false.
331 bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset,
332 bool FoldIfIncompatible) {
333 const TargetData &TD = getTargetData();
334 // Check to make sure the Size member is up-to-date. Size can be one of the
336 // Size = 0, Ty = Void: Nothing is known about this node.
337 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
338 // Size = 1, Ty = Void, Array = 1: The node is collapsed
339 // Otherwise, sizeof(Ty) = Size
341 assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
342 (Size == 0 && !Ty->isSized() && !isArray()) ||
343 (Size == 1 && Ty == Type::VoidTy && isArray()) ||
344 (Size == 0 && !Ty->isSized() && !isArray()) ||
345 (TD.getTypeSize(Ty) == Size)) &&
346 "Size member of DSNode doesn't match the type structure!");
347 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
349 if (Offset == 0 && NewTy == Ty)
350 return false; // This should be a common case, handle it efficiently
352 // Return true immediately if the node is completely folded.
353 if (isNodeCompletelyFolded()) return true;
355 // If this is an array type, eliminate the outside arrays because they won't
356 // be used anyway. This greatly reduces the size of large static arrays used
357 // as global variables, for example.
359 bool WillBeArray = false;
360 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
361 // FIXME: we might want to keep small arrays, but must be careful about
362 // things like: [2 x [10000 x int*]]
363 NewTy = AT->getElementType();
367 // Figure out how big the new type we're merging in is...
368 unsigned NewTySize = NewTy->isSized() ? TD.getTypeSize(NewTy) : 0;
370 // Otherwise check to see if we can fold this type into the current node. If
371 // we can't, we fold the node completely, if we can, we potentially update our
374 if (Ty == Type::VoidTy) {
375 // If this is the first type that this node has seen, just accept it without
377 assert(Offset == 0 && !isArray() &&
378 "Cannot have an offset into a void node!");
381 if (WillBeArray) NodeType |= Array;
384 // Calculate the number of outgoing links from this node.
385 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
389 // Handle node expansion case here...
390 if (Offset+NewTySize > Size) {
391 // It is illegal to grow this node if we have treated it as an array of
394 if (FoldIfIncompatible) foldNodeCompletely();
398 if (Offset) { // We could handle this case, but we don't for now...
399 std::cerr << "UNIMP: Trying to merge a growth type into "
400 << "offset != 0: Collapsing!\n";
401 if (FoldIfIncompatible) foldNodeCompletely();
405 // Okay, the situation is nice and simple, we are trying to merge a type in
406 // at offset 0 that is bigger than our current type. Implement this by
407 // switching to the new type and then merge in the smaller one, which should
408 // hit the other code path here. If the other code path decides it's not
409 // ok, it will collapse the node as appropriate.
411 const Type *OldTy = Ty;
414 if (WillBeArray) NodeType |= Array;
417 // Must grow links to be the appropriate size...
418 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
420 // Merge in the old type now... which is guaranteed to be smaller than the
422 return mergeTypeInfo(OldTy, 0);
425 assert(Offset <= Size &&
426 "Cannot merge something into a part of our type that doesn't exist!");
428 // Find the section of Ty that NewTy overlaps with... first we find the
429 // type that starts at offset Offset.
432 const Type *SubType = Ty;
434 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
436 switch (SubType->getPrimitiveID()) {
437 case Type::StructTyID: {
438 const StructType *STy = cast<StructType>(SubType);
439 const StructLayout &SL = *TD.getStructLayout(STy);
441 unsigned i = 0, e = SL.MemberOffsets.size();
442 for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
445 // The offset we are looking for must be in the i'th element...
446 SubType = STy->getElementType(i);
447 O += SL.MemberOffsets[i];
450 case Type::ArrayTyID: {
451 SubType = cast<ArrayType>(SubType)->getElementType();
452 unsigned ElSize = TD.getTypeSize(SubType);
453 unsigned Remainder = (Offset-O) % ElSize;
454 O = Offset-Remainder;
458 if (FoldIfIncompatible) foldNodeCompletely();
463 assert(O == Offset && "Could not achieve the correct offset!");
465 // If we found our type exactly, early exit
466 if (SubType == NewTy) return false;
468 // Differing function types don't require us to merge. They are not values anyway.
469 if (isa<FunctionType>(SubType) &&
470 isa<FunctionType>(NewTy)) return false;
472 unsigned SubTypeSize = SubType->isSized() ? TD.getTypeSize(SubType) : 0;
474 // Ok, we are getting desperate now. Check for physical subtyping, where we
475 // just require each element in the node to be compatible.
476 if (NewTySize <= SubTypeSize && NewTySize && NewTySize < 256 &&
477 SubTypeSize && SubTypeSize < 256 &&
478 ElementTypesAreCompatible(NewTy, SubType, !isArray(), TD))
481 // Okay, so we found the leader type at the offset requested. Search the list
482 // of types that starts at this offset. If SubType is currently an array or
483 // structure, the type desired may actually be the first element of the
486 unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
487 while (SubType != NewTy) {
488 const Type *NextSubType = 0;
489 unsigned NextSubTypeSize = 0;
490 unsigned NextPadSize = 0;
491 switch (SubType->getPrimitiveID()) {
492 case Type::StructTyID: {
493 const StructType *STy = cast<StructType>(SubType);
494 const StructLayout &SL = *TD.getStructLayout(STy);
495 if (SL.MemberOffsets.size() > 1)
496 NextPadSize = SL.MemberOffsets[1];
498 NextPadSize = SubTypeSize;
499 NextSubType = STy->getElementType(0);
500 NextSubTypeSize = TD.getTypeSize(NextSubType);
503 case Type::ArrayTyID:
504 NextSubType = cast<ArrayType>(SubType)->getElementType();
505 NextSubTypeSize = TD.getTypeSize(NextSubType);
506 NextPadSize = NextSubTypeSize;
512 if (NextSubType == 0)
513 break; // In the default case, break out of the loop
515 if (NextPadSize < NewTySize)
516 break; // Don't allow shrinking to a smaller type than NewTySize
517 SubType = NextSubType;
518 SubTypeSize = NextSubTypeSize;
519 PadSize = NextPadSize;
522 // If we found the type exactly, return it...
523 if (SubType == NewTy)
526 // Check to see if we have a compatible, but different type...
527 if (NewTySize == SubTypeSize) {
528 // Check to see if this type is obviously convertible... int -> uint f.e.
529 if (NewTy->isLosslesslyConvertibleTo(SubType))
532 // Check to see if we have a pointer & integer mismatch going on here,
533 // loading a pointer as a long, for example.
535 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
536 NewTy->isInteger() && isa<PointerType>(SubType))
538 } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
539 // We are accessing the field, plus some structure padding. Ignore the
540 // structure padding.
545 if (getParentGraph()->getReturnNodes().size())
546 M = getParentGraph()->getReturnNodes().begin()->first->getParent();
547 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: ";
548 WriteTypeSymbolic(std::cerr, Ty, M) << "\n due to:";
549 WriteTypeSymbolic(std::cerr, NewTy, M) << " @ " << Offset << "!\n"
551 WriteTypeSymbolic(std::cerr, SubType, M) << "\n\n");
553 if (FoldIfIncompatible) foldNodeCompletely();
559 // addEdgeTo - Add an edge from the current node to the specified node. This
560 // can cause merging of nodes in the graph.
562 void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
563 if (NH.isNull()) return; // Nothing to do
565 DSNodeHandle &ExistingEdge = getLink(Offset);
566 if (!ExistingEdge.isNull()) {
567 // Merge the two nodes...
568 ExistingEdge.mergeWith(NH);
569 } else { // No merging to perform...
570 setLink(Offset, NH); // Just force a link in there...
575 // MergeSortedVectors - Efficiently merge a vector into another vector where
576 // duplicates are not allowed and both are sorted. This assumes that 'T's are
577 // efficiently copyable and have sane comparison semantics.
579 static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
580 const std::vector<GlobalValue*> &Src) {
581 // By far, the most common cases will be the simple ones. In these cases,
582 // avoid having to allocate a temporary vector...
584 if (Src.empty()) { // Nothing to merge in...
586 } else if (Dest.empty()) { // Just copy the result in...
588 } else if (Src.size() == 1) { // Insert a single element...
589 const GlobalValue *V = Src[0];
590 std::vector<GlobalValue*>::iterator I =
591 std::lower_bound(Dest.begin(), Dest.end(), V);
592 if (I == Dest.end() || *I != Src[0]) // If not already contained...
593 Dest.insert(I, Src[0]);
594 } else if (Dest.size() == 1) {
595 GlobalValue *Tmp = Dest[0]; // Save value in temporary...
596 Dest = Src; // Copy over list...
597 std::vector<GlobalValue*>::iterator I =
598 std::lower_bound(Dest.begin(), Dest.end(), Tmp);
599 if (I == Dest.end() || *I != Tmp) // If not already contained...
603 // Make a copy to the side of Dest...
604 std::vector<GlobalValue*> Old(Dest);
606 // Make space for all of the type entries now...
607 Dest.resize(Dest.size()+Src.size());
609 // Merge the two sorted ranges together... into Dest.
610 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
612 // Now erase any duplicate entries that may have accumulated into the
613 // vectors (because they were in both of the input sets)
614 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
618 void DSNode::mergeGlobals(const std::vector<GlobalValue*> &RHS) {
619 MergeSortedVectors(Globals, RHS);
622 // MergeNodes - Helper function for DSNode::mergeWith().
623 // This function does the hard work of merging two nodes, CurNodeH
624 // and NH after filtering out trivial cases and making sure that
625 // CurNodeH.offset >= NH.offset.
628 // Since merging may cause either node to go away, we must always
629 // use the node-handles to refer to the nodes. These node handles are
630 // automatically updated during merging, so will always provide access
631 // to the correct node after a merge.
633 void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
634 assert(CurNodeH.getOffset() >= NH.getOffset() &&
635 "This should have been enforced in the caller.");
637 // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
638 // respect to NH.Offset) is now zero. NOffset is the distance from the base
639 // of our object that N starts from.
641 unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
642 unsigned NSize = NH.getNode()->getSize();
644 // If the two nodes are of different size, and the smaller node has the array
645 // bit set, collapse!
646 if (NSize != CurNodeH.getNode()->getSize()) {
647 if (NSize < CurNodeH.getNode()->getSize()) {
648 if (NH.getNode()->isArray())
649 NH.getNode()->foldNodeCompletely();
650 } else if (CurNodeH.getNode()->isArray()) {
651 NH.getNode()->foldNodeCompletely();
655 // Merge the type entries of the two nodes together...
656 if (NH.getNode()->Ty != Type::VoidTy)
657 CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
658 assert(!CurNodeH.getNode()->isDeadNode());
660 // If we are merging a node with a completely folded node, then both nodes are
661 // now completely folded.
663 if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
664 if (!NH.getNode()->isNodeCompletelyFolded()) {
665 NH.getNode()->foldNodeCompletely();
666 assert(NH.getNode() && NH.getOffset() == 0 &&
667 "folding did not make offset 0?");
668 NOffset = NH.getOffset();
669 NSize = NH.getNode()->getSize();
670 assert(NOffset == 0 && NSize == 1);
672 } else if (NH.getNode()->isNodeCompletelyFolded()) {
673 CurNodeH.getNode()->foldNodeCompletely();
674 assert(CurNodeH.getNode() && CurNodeH.getOffset() == 0 &&
675 "folding did not make offset 0?");
676 NOffset = NH.getOffset();
677 NSize = NH.getNode()->getSize();
678 assert(NOffset == 0 && NSize == 1);
681 DSNode *N = NH.getNode();
682 if (CurNodeH.getNode() == N || N == 0) return;
683 assert(!CurNodeH.getNode()->isDeadNode());
685 // Merge the NodeType information.
686 CurNodeH.getNode()->NodeType |= N->NodeType;
688 // Start forwarding to the new node!
689 N->forwardNode(CurNodeH.getNode(), NOffset);
690 assert(!CurNodeH.getNode()->isDeadNode());
692 // Make all of the outgoing links of N now be outgoing links of CurNodeH.
694 for (unsigned i = 0; i < N->getNumLinks(); ++i) {
695 DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
696 if (Link.getNode()) {
697 // Compute the offset into the current node at which to
698 // merge this link. In the common case, this is a linear
699 // relation to the offset in the original node (with
700 // wrapping), but if the current node gets collapsed due to
701 // recursive merging, we must make sure to merge in all remaining
702 // links at offset zero.
703 unsigned MergeOffset = 0;
704 DSNode *CN = CurNodeH.getNode();
706 MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
707 CN->addEdgeTo(MergeOffset, Link);
711 // Now that there are no outgoing edges, all of the Links are dead.
714 // Merge the globals list...
715 if (!N->Globals.empty()) {
716 CurNodeH.getNode()->mergeGlobals(N->Globals);
718 // Delete the globals from the old node...
719 std::vector<GlobalValue*>().swap(N->Globals);
724 // mergeWith - Merge this node and the specified node, moving all links to and
725 // from the argument node into the current node, deleting the node argument.
726 // Offset indicates what offset the specified node is to be merged into the
729 // The specified node may be a null pointer (in which case, we update it to
730 // point to this node).
732 void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
733 DSNode *N = NH.getNode();
734 if (N == this && NH.getOffset() == Offset)
737 // If the RHS is a null node, make it point to this node!
739 NH.mergeWith(DSNodeHandle(this, Offset));
743 assert(!N->isDeadNode() && !isDeadNode());
744 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
747 // We cannot merge two pieces of the same node together, collapse the node
749 DEBUG(std::cerr << "Attempting to merge two chunks of"
750 << " the same node together!\n");
751 foldNodeCompletely();
755 // If both nodes are not at offset 0, make sure that we are merging the node
756 // at an later offset into the node with the zero offset.
758 if (Offset < NH.getOffset()) {
759 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
761 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
762 // If the offsets are the same, merge the smaller node into the bigger node
763 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
767 // Ok, now we can merge the two nodes. Use a static helper that works with
768 // two node handles, since "this" may get merged away at intermediate steps.
769 DSNodeHandle CurNodeH(this, Offset);
770 DSNodeHandle NHCopy(NH);
771 DSNode::MergeNodes(CurNodeH, NHCopy);
775 //===----------------------------------------------------------------------===//
776 // ReachabilityCloner Implementation
777 //===----------------------------------------------------------------------===//
779 DSNodeHandle ReachabilityCloner::getClonedNH(const DSNodeHandle &SrcNH) {
780 if (SrcNH.isNull()) return DSNodeHandle();
781 const DSNode *SN = SrcNH.getNode();
783 DSNodeHandle &NH = NodeMap[SN];
784 if (!NH.isNull()) // Node already mapped?
785 return DSNodeHandle(NH.getNode(), NH.getOffset()+SrcNH.getOffset());
787 DSNode *DN = new DSNode(*SN, &Dest, true /* Null out all links */);
788 DN->maskNodeTypes(BitsToKeep);
791 // Next, recursively clone all outgoing links as necessary. Note that
792 // adding these links can cause the node to collapse itself at any time, and
793 // the current node may be merged with arbitrary other nodes. For this
794 // reason, we must always go through NH.
796 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
797 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
798 if (!SrcEdge.isNull()) {
799 const DSNodeHandle &DestEdge = getClonedNH(SrcEdge);
800 // Compute the offset into the current node at which to
801 // merge this link. In the common case, this is a linear
802 // relation to the offset in the original node (with
803 // wrapping), but if the current node gets collapsed due to
804 // recursive merging, we must make sure to merge in all remaining
805 // links at offset zero.
806 unsigned MergeOffset = 0;
807 DSNode *CN = NH.getNode();
808 if (CN->getSize() != 1)
809 MergeOffset = ((i << DS::PointerShift)+NH.getOffset()
810 - SrcNH.getOffset()) %CN->getSize();
811 CN->addEdgeTo(MergeOffset, DestEdge);
815 // If this node contains any globals, make sure they end up in the scalar
816 // map with the correct offset.
817 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
819 GlobalValue *GV = *I;
820 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
821 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
822 assert(DestGNH.getNode() == NH.getNode() &&"Global mapping inconsistent");
823 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
824 DestGNH.getOffset()+SrcGNH.getOffset()));
826 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
827 Dest.getInlinedGlobals().insert(GV);
830 return DSNodeHandle(NH.getNode(), NH.getOffset()+SrcNH.getOffset());
833 void ReachabilityCloner::merge(const DSNodeHandle &NH,
834 const DSNodeHandle &SrcNH) {
835 if (SrcNH.isNull()) return; // Noop
837 // If there is no destination node, just clone the source and assign the
838 // destination node to be it.
839 NH.mergeWith(getClonedNH(SrcNH));
843 // Okay, at this point, we know that we have both a destination and a source
844 // node that need to be merged. Check to see if the source node has already
846 const DSNode *SN = SrcNH.getNode();
847 DSNodeHandle &SCNH = NodeMap[SN]; // SourceClonedNodeHandle
848 if (SCNH.getNode()) { // Node already cloned?
849 NH.mergeWith(DSNodeHandle(SCNH.getNode(),
850 SCNH.getOffset()+SrcNH.getOffset()));
852 return; // Nothing to do!
855 // Okay, so the source node has not already been cloned. Instead of creating
856 // a new DSNode, only to merge it into the one we already have, try to perform
857 // the merge in-place. The only case we cannot handle here is when the offset
858 // into the existing node is less than the offset into the virtual node we are
859 // merging in. In this case, we have to extend the existing node, which
860 // requires an allocation anyway.
861 DSNode *DN = NH.getNode(); // Make sure the Offset is up-to-date
862 if (NH.getOffset() >= SrcNH.getOffset()) {
863 if (!DN->isNodeCompletelyFolded()) {
864 // Make sure the destination node is folded if the source node is folded.
865 if (SN->isNodeCompletelyFolded()) {
866 DN->foldNodeCompletely();
868 } else if (SN->getSize() != DN->getSize()) {
869 // If the two nodes are of different size, and the smaller node has the
870 // array bit set, collapse!
871 if (SN->getSize() < DN->getSize()) {
873 DN->foldNodeCompletely();
876 } else if (DN->isArray()) {
877 DN->foldNodeCompletely();
882 // Merge the type entries of the two nodes together...
883 if (SN->getType() != Type::VoidTy && !DN->isNodeCompletelyFolded()) {
884 DN->mergeTypeInfo(SN->getType(), NH.getOffset()-SrcNH.getOffset());
889 assert(!DN->isDeadNode());
891 // Merge the NodeType information.
892 DN->mergeNodeFlags(SN->getNodeFlags() & BitsToKeep);
894 // Before we start merging outgoing links and updating the scalar map, make
895 // sure it is known that this is the representative node for the src node.
896 SCNH = DSNodeHandle(DN, NH.getOffset()-SrcNH.getOffset());
898 // If the source node contains any globals, make sure they end up in the
899 // scalar map with the correct offset.
900 if (SN->global_begin() != SN->global_end()) {
901 // Update the globals in the destination node itself.
902 DN->mergeGlobals(SN->getGlobals());
904 // Update the scalar map for the graph we are merging the source node
906 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
908 GlobalValue *GV = *I;
909 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
910 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
911 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
912 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
913 DestGNH.getOffset()+SrcGNH.getOffset()));
915 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
916 Dest.getInlinedGlobals().insert(GV);
920 // We cannot handle this case without allocating a temporary node. Fall
921 // back on being simple.
922 DSNode *NewDN = new DSNode(*SN, &Dest, true /* Null out all links */);
923 NewDN->maskNodeTypes(BitsToKeep);
925 unsigned NHOffset = NH.getOffset();
926 NH.mergeWith(DSNodeHandle(NewDN, SrcNH.getOffset()));
928 assert(NH.getNode() &&
929 (NH.getOffset() > NHOffset ||
930 (NH.getOffset() == 0 && NH.getNode()->isNodeCompletelyFolded())) &&
931 "Merging did not adjust the offset!");
933 // Before we start merging outgoing links and updating the scalar map, make
934 // sure it is known that this is the representative node for the src node.
935 SCNH = DSNodeHandle(NH.getNode(), NH.getOffset()-SrcNH.getOffset());
937 // If the source node contained any globals, make sure to create entries
938 // in the scalar map for them!
939 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
941 GlobalValue *GV = *I;
942 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
943 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
944 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
945 assert(SrcGNH.getNode() == SN && "Global mapping inconsistent");
946 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
947 DestGNH.getOffset()+SrcGNH.getOffset()));
949 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
950 Dest.getInlinedGlobals().insert(GV);
955 // Next, recursively merge all outgoing links as necessary. Note that
956 // adding these links can cause the destination node to collapse itself at
957 // any time, and the current node may be merged with arbitrary other nodes.
958 // For this reason, we must always go through NH.
960 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
961 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
962 if (!SrcEdge.isNull()) {
963 // Compute the offset into the current node at which to
964 // merge this link. In the common case, this is a linear
965 // relation to the offset in the original node (with
966 // wrapping), but if the current node gets collapsed due to
967 // recursive merging, we must make sure to merge in all remaining
968 // links at offset zero.
969 unsigned MergeOffset = 0;
970 DSNode *CN = SCNH.getNode();
971 if (CN->getSize() != 1)
972 MergeOffset = ((i << DS::PointerShift)+SCNH.getOffset()) %CN->getSize();
974 // Perform the recursive merging. Make sure to create a temporary NH,
975 // because the Link can disappear in the process of recursive merging.
976 DSNodeHandle Tmp = CN->getLink(MergeOffset);
982 /// mergeCallSite - Merge the nodes reachable from the specified src call
983 /// site into the nodes reachable from DestCS.
984 void ReachabilityCloner::mergeCallSite(const DSCallSite &DestCS,
985 const DSCallSite &SrcCS) {
986 merge(DestCS.getRetVal(), SrcCS.getRetVal());
987 unsigned MinArgs = DestCS.getNumPtrArgs();
988 if (SrcCS.getNumPtrArgs() < MinArgs) MinArgs = SrcCS.getNumPtrArgs();
990 for (unsigned a = 0; a != MinArgs; ++a)
991 merge(DestCS.getPtrArg(a), SrcCS.getPtrArg(a));
995 //===----------------------------------------------------------------------===//
996 // DSCallSite Implementation
997 //===----------------------------------------------------------------------===//
999 // Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
1000 Function &DSCallSite::getCaller() const {
1001 return *Site.getInstruction()->getParent()->getParent();
1004 void DSCallSite::InitNH(DSNodeHandle &NH, const DSNodeHandle &Src,
1005 ReachabilityCloner &RC) {
1006 NH = RC.getClonedNH(Src);
1009 //===----------------------------------------------------------------------===//
1010 // DSGraph Implementation
1011 //===----------------------------------------------------------------------===//
1013 /// getFunctionNames - Return a space separated list of the name of the
1014 /// functions in this graph (if any)
1015 std::string DSGraph::getFunctionNames() const {
1016 switch (getReturnNodes().size()) {
1017 case 0: return "Globals graph";
1018 case 1: return getReturnNodes().begin()->first->getName();
1021 for (DSGraph::ReturnNodesTy::const_iterator I = getReturnNodes().begin();
1022 I != getReturnNodes().end(); ++I)
1023 Return += I->first->getName() + " ";
1024 Return.erase(Return.end()-1, Return.end()); // Remove last space character
1030 DSGraph::DSGraph(const DSGraph &G) : GlobalsGraph(0), TD(G.TD) {
1031 PrintAuxCalls = false;
1033 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
1036 DSGraph::DSGraph(const DSGraph &G, NodeMapTy &NodeMap)
1037 : GlobalsGraph(0), TD(G.TD) {
1038 PrintAuxCalls = false;
1039 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
1042 DSGraph::~DSGraph() {
1043 FunctionCalls.clear();
1044 AuxFunctionCalls.clear();
1045 InlinedGlobals.clear();
1047 ReturnNodes.clear();
1049 // Drop all intra-node references, so that assertions don't fail...
1050 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
1051 (*NI)->dropAllReferences();
1053 // Free all of the nodes.
1057 // dump - Allow inspection of graph in a debugger.
1058 void DSGraph::dump() const { print(std::cerr); }
1061 /// remapLinks - Change all of the Links in the current node according to the
1062 /// specified mapping.
1064 void DSNode::remapLinks(DSGraph::NodeMapTy &OldNodeMap) {
1065 for (unsigned i = 0, e = Links.size(); i != e; ++i)
1066 if (DSNode *N = Links[i].getNode()) {
1067 DSGraph::NodeMapTy::const_iterator ONMI = OldNodeMap.find(N);
1068 if (ONMI != OldNodeMap.end()) {
1069 Links[i].setNode(ONMI->second.getNode());
1070 Links[i].setOffset(Links[i].getOffset()+ONMI->second.getOffset());
1075 /// updateFromGlobalGraph - This function rematerializes global nodes and
1076 /// nodes reachable from them from the globals graph into the current graph.
1077 /// It uses the vector InlinedGlobals to avoid cloning and merging globals that
1078 /// are already up-to-date in the current graph. In practice, in the TD pass,
1079 /// this is likely to be a large fraction of the live global nodes in each
1080 /// function (since most live nodes are likely to have been brought up-to-date
1081 /// in at _some_ caller or callee).
1083 void DSGraph::updateFromGlobalGraph() {
1084 TIME_REGION(X, "updateFromGlobalGraph");
1085 ReachabilityCloner RC(*this, *GlobalsGraph, 0);
1087 // Clone the non-up-to-date global nodes into this graph.
1088 for (DSScalarMap::global_iterator I = getScalarMap().global_begin(),
1089 E = getScalarMap().global_end(); I != E; ++I)
1090 if (InlinedGlobals.count(*I) == 0) { // GNode is not up-to-date
1091 DSScalarMap::iterator It = GlobalsGraph->ScalarMap.find(*I);
1092 if (It != GlobalsGraph->ScalarMap.end())
1093 RC.merge(getNodeForValue(*I), It->second);
1097 /// cloneInto - Clone the specified DSGraph into the current graph. The
1098 /// translated ScalarMap for the old function is filled into the OldValMap
1099 /// member, and the translated ReturnNodes map is returned into ReturnNodes.
1101 /// The CloneFlags member controls various aspects of the cloning process.
1103 void DSGraph::cloneInto(const DSGraph &G, DSScalarMap &OldValMap,
1104 ReturnNodesTy &OldReturnNodes, NodeMapTy &OldNodeMap,
1105 unsigned CloneFlags) {
1106 TIME_REGION(X, "cloneInto");
1107 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
1108 assert(&G != this && "Cannot clone graph into itself!");
1110 // Remember the last node that existed before, or node_end() if there are no
1112 node_iterator FN = node_end();
1113 if (FN != node_begin()) --FN;
1115 // Remove alloca or mod/ref bits as specified...
1116 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
1117 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
1118 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
1119 BitsToClear |= DSNode::DEAD; // Clear dead flag...
1120 for (node_iterator I = G.node_begin(), E = G.node_end(); I != E; ++I)
1121 if (!(*I)->isForwarding()) {
1122 DSNode *New = new DSNode(**I, this);
1123 New->maskNodeTypes(~BitsToClear);
1124 OldNodeMap[*I] = New;
1128 Timer::addPeakMemoryMeasurement();
1131 // Move FN to the first newly added node.
1132 if (FN != node_end())
1137 // Rewrite the links in the new nodes to point into the current graph now.
1138 for (; FN != node_end(); ++FN)
1139 (*FN)->remapLinks(OldNodeMap);
1141 // Copy the scalar map... merging all of the global nodes...
1142 for (DSScalarMap::const_iterator I = G.ScalarMap.begin(),
1143 E = G.ScalarMap.end(); I != E; ++I) {
1144 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
1145 DSNodeHandle &H = OldValMap[I->first];
1146 H.mergeWith(DSNodeHandle(MappedNode.getNode(),
1147 I->second.getOffset()+MappedNode.getOffset()));
1149 // If this is a global, add the global to this fn or merge if already exists
1150 if (GlobalValue* GV = dyn_cast<GlobalValue>(I->first)) {
1151 ScalarMap[GV].mergeWith(H);
1152 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
1153 InlinedGlobals.insert(GV);
1157 if (!(CloneFlags & DontCloneCallNodes)) {
1158 // Copy the function calls list...
1159 unsigned FC = FunctionCalls.size(); // FirstCall
1160 FunctionCalls.reserve(FC+G.FunctionCalls.size());
1161 for (unsigned i = 0, ei = G.FunctionCalls.size(); i != ei; ++i)
1162 FunctionCalls.push_back(DSCallSite(G.FunctionCalls[i], OldNodeMap));
1165 if (!(CloneFlags & DontCloneAuxCallNodes)) {
1166 // Copy the auxiliary function calls list...
1167 unsigned FC = AuxFunctionCalls.size(); // FirstCall
1168 AuxFunctionCalls.reserve(FC+G.AuxFunctionCalls.size());
1169 for (unsigned i = 0, ei = G.AuxFunctionCalls.size(); i != ei; ++i)
1170 AuxFunctionCalls.push_back(DSCallSite(G.AuxFunctionCalls[i], OldNodeMap));
1173 // Map the return node pointers over...
1174 for (ReturnNodesTy::const_iterator I = G.getReturnNodes().begin(),
1175 E = G.getReturnNodes().end(); I != E; ++I) {
1176 const DSNodeHandle &Ret = I->second;
1177 DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
1178 OldReturnNodes.insert(std::make_pair(I->first,
1179 DSNodeHandle(MappedRet.getNode(),
1180 MappedRet.getOffset()+Ret.getOffset())));
1185 /// mergeInGraph - The method is used for merging graphs together. If the
1186 /// argument graph is not *this, it makes a clone of the specified graph, then
1187 /// merges the nodes specified in the call site with the formal arguments in the
1190 void DSGraph::mergeInGraph(const DSCallSite &CS, Function &F,
1191 const DSGraph &Graph, unsigned CloneFlags) {
1192 TIME_REGION(X, "mergeInGraph");
1194 // If this is not a recursive call, clone the graph into this graph...
1195 if (&Graph != this) {
1196 // Clone the callee's graph into the current graph, keeping track of where
1197 // scalars in the old graph _used_ to point, and of the new nodes matching
1198 // nodes of the old graph.
1199 ReachabilityCloner RC(*this, Graph, CloneFlags);
1201 // Set up argument bindings
1202 Function::aiterator AI = F.abegin();
1203 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
1204 // Advance the argument iterator to the first pointer argument...
1205 while (AI != F.aend() && !isPointerType(AI->getType())) {
1207 #ifndef NDEBUG // FIXME: We should merge vararg arguments!
1208 if (AI == F.aend() && !F.getFunctionType()->isVarArg())
1209 std::cerr << "Bad call to Function: " << F.getName() << "\n";
1212 if (AI == F.aend()) break;
1214 // Add the link from the argument scalar to the provided value.
1215 RC.merge(CS.getPtrArg(i), Graph.getNodeForValue(AI));
1218 // Map the return node pointer over.
1219 if (CS.getRetVal().getNode())
1220 RC.merge(CS.getRetVal(), Graph.getReturnNodeFor(F));
1222 // If requested, copy the calls or aux-calls lists.
1223 if (!(CloneFlags & DontCloneCallNodes)) {
1224 // Copy the function calls list...
1225 FunctionCalls.reserve(FunctionCalls.size()+Graph.FunctionCalls.size());
1226 for (unsigned i = 0, ei = Graph.FunctionCalls.size(); i != ei; ++i)
1227 FunctionCalls.push_back(DSCallSite(Graph.FunctionCalls[i], RC));
1230 if (!(CloneFlags & DontCloneAuxCallNodes)) {
1231 // Copy the auxiliary function calls list...
1232 AuxFunctionCalls.reserve(AuxFunctionCalls.size()+
1233 Graph.AuxFunctionCalls.size());
1234 for (unsigned i = 0, ei = Graph.AuxFunctionCalls.size(); i != ei; ++i)
1235 AuxFunctionCalls.push_back(DSCallSite(Graph.AuxFunctionCalls[i], RC));
1238 // If the user requested it, add the nodes that we need to clone to the
1240 if (!EnableDSNodeGlobalRootsHack)
1241 for (node_iterator NI = Graph.node_begin(), E = Graph.node_end();
1243 if (!(*NI)->getGlobals().empty())
1244 RC.getClonedNH(*NI);
1247 DSNodeHandle RetVal = getReturnNodeFor(F);
1249 // Merge the return value with the return value of the context...
1250 RetVal.mergeWith(CS.getRetVal());
1252 // Resolve all of the function arguments...
1253 Function::aiterator AI = F.abegin();
1255 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
1256 // Advance the argument iterator to the first pointer argument...
1257 while (AI != F.aend() && !isPointerType(AI->getType())) {
1259 #ifndef NDEBUG // FIXME: We should merge varargs arguments!!
1260 if (AI == F.aend() && !F.getFunctionType()->isVarArg())
1261 std::cerr << "Bad call to Function: " << F.getName() << "\n";
1264 if (AI == F.aend()) break;
1266 // Add the link from the argument scalar to the provided value
1267 DSNodeHandle &NH = getNodeForValue(AI);
1268 assert(NH.getNode() && "Pointer argument without scalarmap entry?");
1269 NH.mergeWith(CS.getPtrArg(i));
1274 /// getCallSiteForArguments - Get the arguments and return value bindings for
1275 /// the specified function in the current graph.
1277 DSCallSite DSGraph::getCallSiteForArguments(Function &F) const {
1278 std::vector<DSNodeHandle> Args;
1280 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
1281 if (isPointerType(I->getType()))
1282 Args.push_back(getNodeForValue(I));
1284 return DSCallSite(CallSite(), getReturnNodeFor(F), &F, Args);
1289 // markIncompleteNodes - Mark the specified node as having contents that are not
1290 // known with the current analysis we have performed. Because a node makes all
1291 // of the nodes it can reach incomplete if the node itself is incomplete, we
1292 // must recursively traverse the data structure graph, marking all reachable
1293 // nodes as incomplete.
1295 static void markIncompleteNode(DSNode *N) {
1296 // Stop recursion if no node, or if node already marked...
1297 if (N == 0 || N->isIncomplete()) return;
1299 // Actually mark the node
1300 N->setIncompleteMarker();
1302 // Recursively process children...
1303 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
1304 if (DSNode *DSN = N->getLink(i).getNode())
1305 markIncompleteNode(DSN);
1308 static void markIncomplete(DSCallSite &Call) {
1309 // Then the return value is certainly incomplete!
1310 markIncompleteNode(Call.getRetVal().getNode());
1312 // All objects pointed to by function arguments are incomplete!
1313 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
1314 markIncompleteNode(Call.getPtrArg(i).getNode());
1317 // markIncompleteNodes - Traverse the graph, identifying nodes that may be
1318 // modified by other functions that have not been resolved yet. This marks
1319 // nodes that are reachable through three sources of "unknownness":
1321 // Global Variables, Function Calls, and Incoming Arguments
1323 // For any node that may have unknown components (because something outside the
1324 // scope of current analysis may have modified it), the 'Incomplete' flag is
1325 // added to the NodeType.
1327 void DSGraph::markIncompleteNodes(unsigned Flags) {
1328 // Mark any incoming arguments as incomplete...
1329 if (Flags & DSGraph::MarkFormalArgs)
1330 for (ReturnNodesTy::iterator FI = ReturnNodes.begin(), E =ReturnNodes.end();
1332 Function &F = *FI->first;
1333 if (F.getName() != "main")
1334 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
1335 if (isPointerType(I->getType()))
1336 markIncompleteNode(getNodeForValue(I).getNode());
1339 // Mark stuff passed into functions calls as being incomplete...
1340 if (!shouldPrintAuxCalls())
1341 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1342 markIncomplete(FunctionCalls[i]);
1344 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1345 markIncomplete(AuxFunctionCalls[i]);
1348 // Mark all global nodes as incomplete...
1349 if ((Flags & DSGraph::IgnoreGlobals) == 0)
1350 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
1351 if ((*NI)->isGlobalNode() && (*NI)->getNumLinks())
1352 markIncompleteNode(*NI);
1355 static inline void killIfUselessEdge(DSNodeHandle &Edge) {
1356 if (DSNode *N = Edge.getNode()) // Is there an edge?
1357 if (N->getNumReferrers() == 1) // Does it point to a lonely node?
1358 // No interesting info?
1359 if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
1360 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
1361 Edge.setNode(0); // Kill the edge!
1364 static inline bool nodeContainsExternalFunction(const DSNode *N) {
1365 const std::vector<GlobalValue*> &Globals = N->getGlobals();
1366 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
1367 if (Globals[i]->isExternal())
1372 static void removeIdenticalCalls(std::vector<DSCallSite> &Calls) {
1373 // Remove trivially identical function calls
1374 unsigned NumFns = Calls.size();
1375 std::sort(Calls.begin(), Calls.end()); // Sort by callee as primary key!
1378 // Scan the call list cleaning it up as necessary...
1379 DSNode *LastCalleeNode = 0;
1380 Function *LastCalleeFunc = 0;
1381 unsigned NumDuplicateCalls = 0;
1382 bool LastCalleeContainsExternalFunction = false;
1383 for (unsigned i = 0; i != Calls.size(); ++i) {
1384 DSCallSite &CS = Calls[i];
1386 // If the Callee is a useless edge, this must be an unreachable call site,
1388 if (CS.isIndirectCall() && CS.getCalleeNode()->getNumReferrers() == 1 &&
1389 CS.getCalleeNode()->getNodeFlags() == 0) { // No useful info?
1391 std::cerr << "WARNING: Useless call site found??\n";
1393 CS.swap(Calls.back());
1397 // If the return value or any arguments point to a void node with no
1398 // information at all in it, and the call node is the only node to point
1399 // to it, remove the edge to the node (killing the node).
1401 killIfUselessEdge(CS.getRetVal());
1402 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
1403 killIfUselessEdge(CS.getPtrArg(a));
1405 // If this call site calls the same function as the last call site, and if
1406 // the function pointer contains an external function, this node will
1407 // never be resolved. Merge the arguments of the call node because no
1408 // information will be lost.
1410 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
1411 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
1412 ++NumDuplicateCalls;
1413 if (NumDuplicateCalls == 1) {
1415 LastCalleeContainsExternalFunction =
1416 nodeContainsExternalFunction(LastCalleeNode);
1418 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
1421 // It is not clear why, but enabling this code makes DSA really
1422 // sensitive to node forwarding. Basically, with this enabled, DSA
1423 // performs different number of inlinings based on which nodes are
1424 // forwarding or not. This is clearly a problem, so this code is
1425 // disabled until this can be resolved.
1427 if (LastCalleeContainsExternalFunction
1430 // This should be more than enough context sensitivity!
1431 // FIXME: Evaluate how many times this is tripped!
1432 NumDuplicateCalls > 20
1435 DSCallSite &OCS = Calls[i-1];
1438 // The node will now be eliminated as a duplicate!
1439 if (CS.getNumPtrArgs() < OCS.getNumPtrArgs())
1441 else if (CS.getNumPtrArgs() > OCS.getNumPtrArgs())
1446 if (CS.isDirectCall()) {
1447 LastCalleeFunc = CS.getCalleeFunc();
1450 LastCalleeNode = CS.getCalleeNode();
1453 NumDuplicateCalls = 0;
1458 Calls.erase(std::unique(Calls.begin(), Calls.end()), Calls.end());
1460 // Track the number of call nodes merged away...
1461 NumCallNodesMerged += NumFns-Calls.size();
1463 DEBUG(if (NumFns != Calls.size())
1464 std::cerr << "Merged " << (NumFns-Calls.size()) << " call nodes.\n";);
1468 // removeTriviallyDeadNodes - After the graph has been constructed, this method
1469 // removes all unreachable nodes that are created because they got merged with
1470 // other nodes in the graph. These nodes will all be trivially unreachable, so
1471 // we don't have to perform any non-trivial analysis here.
1473 void DSGraph::removeTriviallyDeadNodes() {
1474 TIME_REGION(X, "removeTriviallyDeadNodes");
1476 // Loop over all of the nodes in the graph, calling getNode on each field.
1477 // This will cause all nodes to update their forwarding edges, causing
1478 // forwarded nodes to be delete-able.
1479 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI) {
1481 for (unsigned l = 0, e = N->getNumLinks(); l != e; ++l)
1482 N->getLink(l*N->getPointerSize()).getNode();
1485 // NOTE: This code is disabled. Though it should, in theory, allow us to
1486 // remove more nodes down below, the scan of the scalar map is incredibly
1487 // expensive for certain programs (with large SCCs). In the future, if we can
1488 // make the scalar map scan more efficient, then we can reenable this.
1490 { TIME_REGION(X, "removeTriviallyDeadNodes:scalarmap");
1492 // Likewise, forward any edges from the scalar nodes. While we are at it,
1493 // clean house a bit.
1494 for (DSScalarMap::iterator I = ScalarMap.begin(),E = ScalarMap.end();I != E;){
1495 I->second.getNode();
1500 bool isGlobalsGraph = !GlobalsGraph;
1502 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E; ) {
1505 // Do not remove *any* global nodes in the globals graph.
1506 // This is a special case because such nodes may not have I, M, R flags set.
1507 if (Node.isGlobalNode() && isGlobalsGraph) {
1512 if (Node.isComplete() && !Node.isModified() && !Node.isRead()) {
1513 // This is a useless node if it has no mod/ref info (checked above),
1514 // outgoing edges (which it cannot, as it is not modified in this
1515 // context), and it has no incoming edges. If it is a global node it may
1516 // have all of these properties and still have incoming edges, due to the
1517 // scalar map, so we check those now.
1519 if (Node.getNumReferrers() == Node.getGlobals().size()) {
1520 const std::vector<GlobalValue*> &Globals = Node.getGlobals();
1522 // Loop through and make sure all of the globals are referring directly
1524 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1525 DSNode *N = getNodeForValue(Globals[j]).getNode();
1526 assert(N == &Node && "ScalarMap doesn't match globals list!");
1529 // Make sure NumReferrers still agrees, if so, the node is truly dead.
1530 if (Node.getNumReferrers() == Globals.size()) {
1531 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1532 ScalarMap.erase(Globals[j]);
1533 Node.makeNodeDead();
1534 ++NumTrivialGlobalDNE;
1539 if (Node.getNodeFlags() == 0 && Node.hasNoReferrers()) {
1540 // This node is dead!
1541 NI = Nodes.erase(NI); // Erase & remove from node list.
1548 removeIdenticalCalls(FunctionCalls);
1549 removeIdenticalCalls(AuxFunctionCalls);
1553 /// markReachableNodes - This method recursively traverses the specified
1554 /// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
1555 /// to the set, which allows it to only traverse visited nodes once.
1557 void DSNode::markReachableNodes(hash_set<DSNode*> &ReachableNodes) {
1558 if (this == 0) return;
1559 assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
1560 if (ReachableNodes.insert(this).second) // Is newly reachable?
1561 for (unsigned i = 0, e = getSize(); i < e; i += DS::PointerSize)
1562 getLink(i).getNode()->markReachableNodes(ReachableNodes);
1565 void DSCallSite::markReachableNodes(hash_set<DSNode*> &Nodes) {
1566 getRetVal().getNode()->markReachableNodes(Nodes);
1567 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
1569 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
1570 getPtrArg(i).getNode()->markReachableNodes(Nodes);
1573 // CanReachAliveNodes - Simple graph walker that recursively traverses the graph
1574 // looking for a node that is marked alive. If an alive node is found, return
1575 // true, otherwise return false. If an alive node is reachable, this node is
1576 // marked as alive...
1578 static bool CanReachAliveNodes(DSNode *N, hash_set<DSNode*> &Alive,
1579 hash_set<DSNode*> &Visited,
1580 bool IgnoreGlobals) {
1581 if (N == 0) return false;
1582 assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
1584 // If this is a global node, it will end up in the globals graph anyway, so we
1585 // don't need to worry about it.
1586 if (IgnoreGlobals && N->isGlobalNode()) return false;
1588 // If we know that this node is alive, return so!
1589 if (Alive.count(N)) return true;
1591 // Otherwise, we don't think the node is alive yet, check for infinite
1593 if (Visited.count(N)) return false; // Found a cycle
1594 Visited.insert(N); // No recursion, insert into Visited...
1596 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
1597 if (CanReachAliveNodes(N->getLink(i).getNode(), Alive, Visited,
1599 N->markReachableNodes(Alive);
1605 // CallSiteUsesAliveArgs - Return true if the specified call site can reach any
1608 static bool CallSiteUsesAliveArgs(DSCallSite &CS, hash_set<DSNode*> &Alive,
1609 hash_set<DSNode*> &Visited,
1610 bool IgnoreGlobals) {
1611 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited,
1614 if (CS.isIndirectCall() &&
1615 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited, IgnoreGlobals))
1617 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
1618 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited,
1624 // removeDeadNodes - Use a more powerful reachability analysis to eliminate
1625 // subgraphs that are unreachable. This often occurs because the data
1626 // structure doesn't "escape" into it's caller, and thus should be eliminated
1627 // from the caller's graph entirely. This is only appropriate to use when
1630 void DSGraph::removeDeadNodes(unsigned Flags) {
1631 DEBUG(AssertGraphOK(); if (GlobalsGraph) GlobalsGraph->AssertGraphOK());
1633 // Reduce the amount of work we have to do... remove dummy nodes left over by
1635 removeTriviallyDeadNodes();
1637 TIME_REGION(X, "removeDeadNodes");
1639 // FIXME: Merge non-trivially identical call nodes...
1641 // Alive - a set that holds all nodes found to be reachable/alive.
1642 hash_set<DSNode*> Alive;
1643 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
1645 // Copy and merge all information about globals to the GlobalsGraph if this is
1646 // not a final pass (where unreachable globals are removed).
1648 // Strip all alloca bits since the current function is only for the BU pass.
1649 // Strip all incomplete bits since they are short-lived properties and they
1650 // will be correctly computed when rematerializing nodes into the functions.
1652 ReachabilityCloner GGCloner(*GlobalsGraph, *this, DSGraph::StripAllocaBit |
1653 DSGraph::StripIncompleteBit);
1655 // Mark all nodes reachable by (non-global) scalar nodes as alive...
1656 { TIME_REGION(Y, "removeDeadNodes:scalarscan");
1657 for (DSScalarMap::iterator I = ScalarMap.begin(), E = ScalarMap.end(); I !=E;)
1658 if (isa<GlobalValue>(I->first)) { // Keep track of global nodes
1659 assert(I->second.getNode() && "Null global node?");
1660 assert(I->second.getNode()->isGlobalNode() && "Should be a global node!");
1661 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
1663 // Make sure that all globals are cloned over as roots.
1664 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
1665 DSGraph::ScalarMapTy::iterator SMI =
1666 GlobalsGraph->getScalarMap().find(I->first);
1667 if (SMI != GlobalsGraph->getScalarMap().end())
1668 GGCloner.merge(SMI->second, I->second);
1670 GGCloner.getClonedNH(I->second);
1674 DSNode *N = I->second.getNode();
1676 // Check to see if this is a worthless node generated for non-pointer
1677 // values, such as integers. Consider an addition of long types: A+B.
1678 // Assuming we can track all uses of the value in this context, and it is
1679 // NOT used as a pointer, we can delete the node. We will be able to
1680 // detect this situation if the node pointed to ONLY has Unknown bit set
1681 // in the node. In this case, the node is not incomplete, does not point
1682 // to any other nodes (no mod/ref bits set), and is therefore
1683 // uninteresting for data structure analysis. If we run across one of
1684 // these, prune the scalar pointing to it.
1686 if (N->getNodeFlags() == DSNode::UnknownNode && !isa<Argument>(I->first))
1687 ScalarMap.erase(I++);
1690 N->markReachableNodes(Alive);
1696 // The return values are alive as well.
1697 for (ReturnNodesTy::iterator I = ReturnNodes.begin(), E = ReturnNodes.end();
1699 I->second.getNode()->markReachableNodes(Alive);
1701 // Mark any nodes reachable by primary calls as alive...
1702 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1703 FunctionCalls[i].markReachableNodes(Alive);
1706 // Now find globals and aux call nodes that are already live or reach a live
1707 // value (which makes them live in turn), and continue till no more are found.
1710 hash_set<DSNode*> Visited;
1711 std::vector<unsigned char> AuxFCallsAlive(AuxFunctionCalls.size());
1714 // If any global node points to a non-global that is "alive", the global is
1715 // "alive" as well... Remove it from the GlobalNodes list so we only have
1716 // unreachable globals in the list.
1719 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
1720 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
1721 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited,
1722 Flags & DSGraph::RemoveUnreachableGlobals)) {
1723 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to...
1724 GlobalNodes.pop_back(); // erase efficiently
1728 // Mark only unresolvable call nodes for moving to the GlobalsGraph since
1729 // call nodes that get resolved will be difficult to remove from that graph.
1730 // The final unresolved call nodes must be handled specially at the end of
1731 // the BU pass (i.e., in main or other roots of the call graph).
1732 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1733 if (!AuxFCallsAlive[i] &&
1734 (AuxFunctionCalls[i].isIndirectCall()
1735 || CallSiteUsesAliveArgs(AuxFunctionCalls[i], Alive, Visited,
1736 Flags & DSGraph::RemoveUnreachableGlobals))) {
1737 AuxFunctionCalls[i].markReachableNodes(Alive);
1738 AuxFCallsAlive[i] = true;
1743 // Move dead aux function calls to the end of the list
1744 unsigned CurIdx = 0;
1745 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1746 if (AuxFCallsAlive[i])
1747 AuxFunctionCalls[CurIdx++].swap(AuxFunctionCalls[i]);
1749 // Copy and merge all global nodes and dead aux call nodes into the
1750 // GlobalsGraph, and all nodes reachable from those nodes
1752 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
1753 // Copy the unreachable call nodes to the globals graph, updating their
1754 // target pointers using the GGCloner
1755 for (unsigned i = CurIdx, e = AuxFunctionCalls.size(); i != e; ++i)
1756 GlobalsGraph->AuxFunctionCalls.push_back(DSCallSite(AuxFunctionCalls[i],
1759 // Crop all the useless ones out...
1760 AuxFunctionCalls.erase(AuxFunctionCalls.begin()+CurIdx,
1761 AuxFunctionCalls.end());
1763 // We are finally done with the GGCloner so we can destroy it.
1766 // At this point, any nodes which are visited, but not alive, are nodes
1767 // which can be removed. Loop over all nodes, eliminating completely
1768 // unreachable nodes.
1770 std::vector<DSNode*> DeadNodes;
1771 DeadNodes.reserve(Nodes.size());
1772 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E;)
1773 if (!Alive.count(NI)) {
1775 DSNode *N = Nodes.remove(NI++);
1776 DeadNodes.push_back(N);
1777 N->dropAllReferences();
1779 assert(NI->getForwardNode() == 0 && "Alive forwarded node?");
1783 // Remove all unreachable globals from the ScalarMap.
1784 // If flag RemoveUnreachableGlobals is set, GlobalNodes has only dead nodes.
1785 // In either case, the dead nodes will not be in the set Alive.
1786 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
1787 if (!Alive.count(GlobalNodes[i].second))
1788 ScalarMap.erase(GlobalNodes[i].first);
1790 assert((Flags & DSGraph::RemoveUnreachableGlobals) && "non-dead global");
1792 // Delete all dead nodes now since their referrer counts are zero.
1793 for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
1794 delete DeadNodes[i];
1796 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
1799 void DSGraph::AssertGraphOK() const {
1800 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
1803 for (ScalarMapTy::const_iterator I = ScalarMap.begin(),
1804 E = ScalarMap.end(); I != E; ++I) {
1805 assert(I->second.getNode() && "Null node in scalarmap!");
1806 AssertNodeInGraph(I->second.getNode());
1807 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
1808 assert(I->second.getNode()->isGlobalNode() &&
1809 "Global points to node, but node isn't global?");
1810 AssertNodeContainsGlobal(I->second.getNode(), GV);
1813 AssertCallNodesInGraph();
1814 AssertAuxCallNodesInGraph();
1817 /// computeNodeMapping - Given roots in two different DSGraphs, traverse the
1818 /// nodes reachable from the two graphs, computing the mapping of nodes from
1819 /// the first to the second graph.
1821 void DSGraph::computeNodeMapping(const DSNodeHandle &NH1,
1822 const DSNodeHandle &NH2, NodeMapTy &NodeMap,
1823 bool StrictChecking) {
1824 DSNode *N1 = NH1.getNode(), *N2 = NH2.getNode();
1825 if (N1 == 0 || N2 == 0) return;
1827 DSNodeHandle &Entry = NodeMap[N1];
1828 if (Entry.getNode()) {
1829 // Termination of recursion!
1830 assert(!StrictChecking ||
1831 (Entry.getNode() == N2 &&
1832 Entry.getOffset() == (NH2.getOffset()-NH1.getOffset())) &&
1833 "Inconsistent mapping detected!");
1838 Entry.setOffset(NH2.getOffset()-NH1.getOffset());
1840 // Loop over all of the fields that N1 and N2 have in common, recursively
1841 // mapping the edges together now.
1842 int N2Idx = NH2.getOffset()-NH1.getOffset();
1843 unsigned N2Size = N2->getSize();
1844 for (unsigned i = 0, e = N1->getSize(); i < e; i += DS::PointerSize)
1845 if (unsigned(N2Idx)+i < N2Size)
1846 computeNodeMapping(N1->getLink(i), N2->getLink(N2Idx+i), NodeMap);