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/GlobalVariable.h"
17 #include "llvm/iOther.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Target/TargetData.h"
20 #include "llvm/Assembly/Writer.h"
21 #include "Support/CommandLine.h"
22 #include "Support/Debug.h"
23 #include "Support/STLExtras.h"
24 #include "Support/Statistic.h"
25 #include "Support/Timer.h"
30 Statistic<> NumFolds ("dsa", "Number of nodes completely folded");
31 Statistic<> NumCallNodesMerged("dsa", "Number of call nodes merged");
32 Statistic<> NumNodeAllocated ("dsa", "Number of nodes allocated");
33 Statistic<> NumDNE ("dsa", "Number of nodes removed by reachability");
34 Statistic<> NumTrivialDNE ("dsa", "Number of nodes trivially removed");
35 Statistic<> NumTrivialGlobalDNE("dsa", "Number of globals trivially removed");
39 #define TIME_REGION(VARNAME, DESC) \
40 NamedRegionTimer VARNAME(DESC)
42 #define TIME_REGION(VARNAME, DESC)
47 DSNode *DSNodeHandle::HandleForwarding() const {
48 assert(N->isForwarding() && "Can only be invoked if forwarding!");
50 // Handle node forwarding here!
51 DSNode *Next = N->ForwardNH.getNode(); // Cause recursive shrinkage
52 Offset += N->ForwardNH.getOffset();
54 if (--N->NumReferrers == 0) {
55 // Removing the last referrer to the node, sever the forwarding link
61 if (N->Size <= Offset) {
62 assert(N->Size <= 1 && "Forwarded to shrunk but not collapsed node?");
68 //===----------------------------------------------------------------------===//
69 // DSNode Implementation
70 //===----------------------------------------------------------------------===//
72 DSNode::DSNode(const Type *T, DSGraph *G)
73 : NumReferrers(0), Size(0), ParentGraph(G), Ty(Type::VoidTy), NodeType(0) {
74 // Add the type entry if it is specified...
75 if (T) mergeTypeInfo(T, 0);
76 if (G) G->addNode(this);
80 // DSNode copy constructor... do not copy over the referrers list!
81 DSNode::DSNode(const DSNode &N, DSGraph *G, bool NullLinks)
82 : NumReferrers(0), Size(N.Size), ParentGraph(G),
83 Ty(N.Ty), Globals(N.Globals), NodeType(N.NodeType) {
87 Links.resize(N.Links.size()); // Create the appropriate number of null links
92 /// getTargetData - Get the target data object used to construct this node.
94 const TargetData &DSNode::getTargetData() const {
95 return ParentGraph->getTargetData();
98 void DSNode::assertOK() const {
99 assert((Ty != Type::VoidTy ||
100 Ty == Type::VoidTy && (Size == 0 ||
101 (NodeType & DSNode::Array))) &&
104 assert(ParentGraph && "Node has no parent?");
105 const DSScalarMap &SM = ParentGraph->getScalarMap();
106 for (unsigned i = 0, e = Globals.size(); i != e; ++i) {
107 assert(SM.count(Globals[i]));
108 assert(SM.find(Globals[i])->second.getNode() == this);
112 /// forwardNode - Mark this node as being obsolete, and all references to it
113 /// should be forwarded to the specified node and offset.
115 void DSNode::forwardNode(DSNode *To, unsigned Offset) {
116 assert(this != To && "Cannot forward a node to itself!");
117 assert(ForwardNH.isNull() && "Already forwarding from this node!");
118 if (To->Size <= 1) Offset = 0;
119 assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
120 "Forwarded offset is wrong!");
121 ForwardNH.setNode(To);
122 ForwardNH.setOffset(Offset);
127 // Remove this node from the parent graph's Nodes list.
128 ParentGraph->unlinkNode(this);
132 // addGlobal - Add an entry for a global value to the Globals list. This also
133 // marks the node with the 'G' flag if it does not already have it.
135 void DSNode::addGlobal(GlobalValue *GV) {
136 // Keep the list sorted.
137 std::vector<GlobalValue*>::iterator I =
138 std::lower_bound(Globals.begin(), Globals.end(), GV);
140 if (I == Globals.end() || *I != GV) {
141 //assert(GV->getType()->getElementType() == Ty);
142 Globals.insert(I, GV);
143 NodeType |= GlobalNode;
147 /// foldNodeCompletely - If we determine that this node has some funny
148 /// behavior happening to it that we cannot represent, we fold it down to a
149 /// single, completely pessimistic, node. This node is represented as a
150 /// single byte with a single TypeEntry of "void".
152 void DSNode::foldNodeCompletely() {
153 if (isNodeCompletelyFolded()) return; // If this node is already folded...
157 // If this node has a size that is <= 1, we don't need to create a forwarding
159 if (getSize() <= 1) {
160 NodeType |= DSNode::Array;
163 assert(Links.size() <= 1 && "Size is 1, but has more links?");
166 // Create the node we are going to forward to. This is required because
167 // some referrers may have an offset that is > 0. By forcing them to
168 // forward, the forwarder has the opportunity to correct the offset.
169 DSNode *DestNode = new DSNode(0, ParentGraph);
170 DestNode->NodeType = NodeType|DSNode::Array;
171 DestNode->Ty = Type::VoidTy;
173 DestNode->Globals.swap(Globals);
175 // Start forwarding to the destination node...
176 forwardNode(DestNode, 0);
178 if (!Links.empty()) {
179 DestNode->Links.reserve(1);
181 DSNodeHandle NH(DestNode);
182 DestNode->Links.push_back(Links[0]);
184 // If we have links, merge all of our outgoing links together...
185 for (unsigned i = Links.size()-1; i != 0; --i)
186 NH.getNode()->Links[0].mergeWith(Links[i]);
189 DestNode->Links.resize(1);
194 /// isNodeCompletelyFolded - Return true if this node has been completely
195 /// folded down to something that can never be expanded, effectively losing
196 /// all of the field sensitivity that may be present in the node.
198 bool DSNode::isNodeCompletelyFolded() const {
199 return getSize() == 1 && Ty == Type::VoidTy && isArray();
203 /// TypeElementWalker Class - Used for implementation of physical subtyping...
205 class TypeElementWalker {
210 StackState(const Type *T, unsigned Off = 0)
211 : Ty(T), Offset(Off), Idx(0) {}
214 std::vector<StackState> Stack;
215 const TargetData &TD;
217 TypeElementWalker(const Type *T, const TargetData &td) : TD(td) {
222 bool isDone() const { return Stack.empty(); }
223 const Type *getCurrentType() const { return Stack.back().Ty; }
224 unsigned getCurrentOffset() const { return Stack.back().Offset; }
226 void StepToNextType() {
227 PopStackAndAdvance();
232 /// PopStackAndAdvance - Pop the current element off of the stack and
233 /// advance the underlying element to the next contained member.
234 void PopStackAndAdvance() {
235 assert(!Stack.empty() && "Cannot pop an empty stack!");
237 while (!Stack.empty()) {
238 StackState &SS = Stack.back();
239 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
241 if (SS.Idx != ST->getNumElements()) {
242 const StructLayout *SL = TD.getStructLayout(ST);
243 SS.Offset += SL->MemberOffsets[SS.Idx]-SL->MemberOffsets[SS.Idx-1];
246 Stack.pop_back(); // At the end of the structure
248 const ArrayType *AT = cast<ArrayType>(SS.Ty);
250 if (SS.Idx != AT->getNumElements()) {
251 SS.Offset += TD.getTypeSize(AT->getElementType());
254 Stack.pop_back(); // At the end of the array
259 /// StepToLeaf - Used by physical subtyping to move to the first leaf node
260 /// on the type stack.
262 if (Stack.empty()) return;
263 while (!Stack.empty() && !Stack.back().Ty->isFirstClassType()) {
264 StackState &SS = Stack.back();
265 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
266 if (ST->getNumElements() == 0) {
268 PopStackAndAdvance();
270 // Step into the structure...
271 assert(SS.Idx < ST->getNumElements());
272 const StructLayout *SL = TD.getStructLayout(ST);
273 Stack.push_back(StackState(ST->getElementType(SS.Idx),
274 SS.Offset+SL->MemberOffsets[SS.Idx]));
277 const ArrayType *AT = cast<ArrayType>(SS.Ty);
278 if (AT->getNumElements() == 0) {
280 PopStackAndAdvance();
282 // Step into the array...
283 assert(SS.Idx < AT->getNumElements());
284 Stack.push_back(StackState(AT->getElementType(),
286 TD.getTypeSize(AT->getElementType())));
292 } // end anonymous namespace
294 /// ElementTypesAreCompatible - Check to see if the specified types are
295 /// "physically" compatible. If so, return true, else return false. We only
296 /// have to check the fields in T1: T2 may be larger than T1. If AllowLargerT1
297 /// is true, then we also allow a larger T1.
299 static bool ElementTypesAreCompatible(const Type *T1, const Type *T2,
300 bool AllowLargerT1, const TargetData &TD){
301 TypeElementWalker T1W(T1, TD), T2W(T2, TD);
303 while (!T1W.isDone() && !T2W.isDone()) {
304 if (T1W.getCurrentOffset() != T2W.getCurrentOffset())
307 const Type *T1 = T1W.getCurrentType();
308 const Type *T2 = T2W.getCurrentType();
309 if (T1 != T2 && !T1->isLosslesslyConvertibleTo(T2))
312 T1W.StepToNextType();
313 T2W.StepToNextType();
316 return AllowLargerT1 || T1W.isDone();
320 /// mergeTypeInfo - This method merges the specified type into the current node
321 /// at the specified offset. This may update the current node's type record if
322 /// this gives more information to the node, it may do nothing to the node if
323 /// this information is already known, or it may merge the node completely (and
324 /// return true) if the information is incompatible with what is already known.
326 /// This method returns true if the node is completely folded, otherwise false.
328 bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset,
329 bool FoldIfIncompatible) {
330 const TargetData &TD = getTargetData();
331 // Check to make sure the Size member is up-to-date. Size can be one of the
333 // Size = 0, Ty = Void: Nothing is known about this node.
334 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
335 // Size = 1, Ty = Void, Array = 1: The node is collapsed
336 // Otherwise, sizeof(Ty) = Size
338 assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
339 (Size == 0 && !Ty->isSized() && !isArray()) ||
340 (Size == 1 && Ty == Type::VoidTy && isArray()) ||
341 (Size == 0 && !Ty->isSized() && !isArray()) ||
342 (TD.getTypeSize(Ty) == Size)) &&
343 "Size member of DSNode doesn't match the type structure!");
344 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
346 if (Offset == 0 && NewTy == Ty)
347 return false; // This should be a common case, handle it efficiently
349 // Return true immediately if the node is completely folded.
350 if (isNodeCompletelyFolded()) return true;
352 // If this is an array type, eliminate the outside arrays because they won't
353 // be used anyway. This greatly reduces the size of large static arrays used
354 // as global variables, for example.
356 bool WillBeArray = false;
357 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
358 // FIXME: we might want to keep small arrays, but must be careful about
359 // things like: [2 x [10000 x int*]]
360 NewTy = AT->getElementType();
364 // Figure out how big the new type we're merging in is...
365 unsigned NewTySize = NewTy->isSized() ? TD.getTypeSize(NewTy) : 0;
367 // Otherwise check to see if we can fold this type into the current node. If
368 // we can't, we fold the node completely, if we can, we potentially update our
371 if (Ty == Type::VoidTy) {
372 // If this is the first type that this node has seen, just accept it without
374 assert(Offset == 0 && !isArray() &&
375 "Cannot have an offset into a void node!");
378 if (WillBeArray) NodeType |= Array;
381 // Calculate the number of outgoing links from this node.
382 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
386 // Handle node expansion case here...
387 if (Offset+NewTySize > Size) {
388 // It is illegal to grow this node if we have treated it as an array of
391 if (FoldIfIncompatible) foldNodeCompletely();
395 if (Offset) { // We could handle this case, but we don't for now...
396 std::cerr << "UNIMP: Trying to merge a growth type into "
397 << "offset != 0: Collapsing!\n";
398 if (FoldIfIncompatible) foldNodeCompletely();
402 // Okay, the situation is nice and simple, we are trying to merge a type in
403 // at offset 0 that is bigger than our current type. Implement this by
404 // switching to the new type and then merge in the smaller one, which should
405 // hit the other code path here. If the other code path decides it's not
406 // ok, it will collapse the node as appropriate.
408 const Type *OldTy = Ty;
411 if (WillBeArray) NodeType |= Array;
414 // Must grow links to be the appropriate size...
415 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
417 // Merge in the old type now... which is guaranteed to be smaller than the
419 return mergeTypeInfo(OldTy, 0);
422 assert(Offset <= Size &&
423 "Cannot merge something into a part of our type that doesn't exist!");
425 // Find the section of Ty that NewTy overlaps with... first we find the
426 // type that starts at offset Offset.
429 const Type *SubType = Ty;
431 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
433 switch (SubType->getPrimitiveID()) {
434 case Type::StructTyID: {
435 const StructType *STy = cast<StructType>(SubType);
436 const StructLayout &SL = *TD.getStructLayout(STy);
438 unsigned i = 0, e = SL.MemberOffsets.size();
439 for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
442 // The offset we are looking for must be in the i'th element...
443 SubType = STy->getElementType(i);
444 O += SL.MemberOffsets[i];
447 case Type::ArrayTyID: {
448 SubType = cast<ArrayType>(SubType)->getElementType();
449 unsigned ElSize = TD.getTypeSize(SubType);
450 unsigned Remainder = (Offset-O) % ElSize;
451 O = Offset-Remainder;
455 if (FoldIfIncompatible) foldNodeCompletely();
460 assert(O == Offset && "Could not achieve the correct offset!");
462 // If we found our type exactly, early exit
463 if (SubType == NewTy) return false;
465 // Differing function types don't require us to merge. They are not values anyway.
466 if (isa<FunctionType>(SubType) &&
467 isa<FunctionType>(NewTy)) return false;
469 unsigned SubTypeSize = SubType->isSized() ? TD.getTypeSize(SubType) : 0;
471 // Ok, we are getting desperate now. Check for physical subtyping, where we
472 // just require each element in the node to be compatible.
473 if (NewTySize <= SubTypeSize && NewTySize && NewTySize < 256 &&
474 SubTypeSize && SubTypeSize < 256 &&
475 ElementTypesAreCompatible(NewTy, SubType, !isArray(), TD))
478 // Okay, so we found the leader type at the offset requested. Search the list
479 // of types that starts at this offset. If SubType is currently an array or
480 // structure, the type desired may actually be the first element of the
483 unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
484 while (SubType != NewTy) {
485 const Type *NextSubType = 0;
486 unsigned NextSubTypeSize = 0;
487 unsigned NextPadSize = 0;
488 switch (SubType->getPrimitiveID()) {
489 case Type::StructTyID: {
490 const StructType *STy = cast<StructType>(SubType);
491 const StructLayout &SL = *TD.getStructLayout(STy);
492 if (SL.MemberOffsets.size() > 1)
493 NextPadSize = SL.MemberOffsets[1];
495 NextPadSize = SubTypeSize;
496 NextSubType = STy->getElementType(0);
497 NextSubTypeSize = TD.getTypeSize(NextSubType);
500 case Type::ArrayTyID:
501 NextSubType = cast<ArrayType>(SubType)->getElementType();
502 NextSubTypeSize = TD.getTypeSize(NextSubType);
503 NextPadSize = NextSubTypeSize;
509 if (NextSubType == 0)
510 break; // In the default case, break out of the loop
512 if (NextPadSize < NewTySize)
513 break; // Don't allow shrinking to a smaller type than NewTySize
514 SubType = NextSubType;
515 SubTypeSize = NextSubTypeSize;
516 PadSize = NextPadSize;
519 // If we found the type exactly, return it...
520 if (SubType == NewTy)
523 // Check to see if we have a compatible, but different type...
524 if (NewTySize == SubTypeSize) {
525 // Check to see if this type is obviously convertible... int -> uint f.e.
526 if (NewTy->isLosslesslyConvertibleTo(SubType))
529 // Check to see if we have a pointer & integer mismatch going on here,
530 // loading a pointer as a long, for example.
532 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
533 NewTy->isInteger() && isa<PointerType>(SubType))
535 } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
536 // We are accessing the field, plus some structure padding. Ignore the
537 // structure padding.
542 if (getParentGraph()->getReturnNodes().size())
543 M = getParentGraph()->getReturnNodes().begin()->first->getParent();
544 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: ";
545 WriteTypeSymbolic(std::cerr, Ty, M) << "\n due to:";
546 WriteTypeSymbolic(std::cerr, NewTy, M) << " @ " << Offset << "!\n"
548 WriteTypeSymbolic(std::cerr, SubType, M) << "\n\n");
550 if (FoldIfIncompatible) foldNodeCompletely();
556 // addEdgeTo - Add an edge from the current node to the specified node. This
557 // can cause merging of nodes in the graph.
559 void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
560 if (NH.isNull()) return; // Nothing to do
562 DSNodeHandle &ExistingEdge = getLink(Offset);
563 if (!ExistingEdge.isNull()) {
564 // Merge the two nodes...
565 ExistingEdge.mergeWith(NH);
566 } else { // No merging to perform...
567 setLink(Offset, NH); // Just force a link in there...
572 // MergeSortedVectors - Efficiently merge a vector into another vector where
573 // duplicates are not allowed and both are sorted. This assumes that 'T's are
574 // efficiently copyable and have sane comparison semantics.
576 static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
577 const std::vector<GlobalValue*> &Src) {
578 // By far, the most common cases will be the simple ones. In these cases,
579 // avoid having to allocate a temporary vector...
581 if (Src.empty()) { // Nothing to merge in...
583 } else if (Dest.empty()) { // Just copy the result in...
585 } else if (Src.size() == 1) { // Insert a single element...
586 const GlobalValue *V = Src[0];
587 std::vector<GlobalValue*>::iterator I =
588 std::lower_bound(Dest.begin(), Dest.end(), V);
589 if (I == Dest.end() || *I != Src[0]) // If not already contained...
590 Dest.insert(I, Src[0]);
591 } else if (Dest.size() == 1) {
592 GlobalValue *Tmp = Dest[0]; // Save value in temporary...
593 Dest = Src; // Copy over list...
594 std::vector<GlobalValue*>::iterator I =
595 std::lower_bound(Dest.begin(), Dest.end(), Tmp);
596 if (I == Dest.end() || *I != Tmp) // If not already contained...
600 // Make a copy to the side of Dest...
601 std::vector<GlobalValue*> Old(Dest);
603 // Make space for all of the type entries now...
604 Dest.resize(Dest.size()+Src.size());
606 // Merge the two sorted ranges together... into Dest.
607 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
609 // Now erase any duplicate entries that may have accumulated into the
610 // vectors (because they were in both of the input sets)
611 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
615 void DSNode::mergeGlobals(const std::vector<GlobalValue*> &RHS) {
616 MergeSortedVectors(Globals, RHS);
619 // MergeNodes - Helper function for DSNode::mergeWith().
620 // This function does the hard work of merging two nodes, CurNodeH
621 // and NH after filtering out trivial cases and making sure that
622 // CurNodeH.offset >= NH.offset.
625 // Since merging may cause either node to go away, we must always
626 // use the node-handles to refer to the nodes. These node handles are
627 // automatically updated during merging, so will always provide access
628 // to the correct node after a merge.
630 void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
631 assert(CurNodeH.getOffset() >= NH.getOffset() &&
632 "This should have been enforced in the caller.");
634 // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
635 // respect to NH.Offset) is now zero. NOffset is the distance from the base
636 // of our object that N starts from.
638 unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
639 unsigned NSize = NH.getNode()->getSize();
641 // If the two nodes are of different size, and the smaller node has the array
642 // bit set, collapse!
643 if (NSize != CurNodeH.getNode()->getSize()) {
644 if (NSize < CurNodeH.getNode()->getSize()) {
645 if (NH.getNode()->isArray())
646 NH.getNode()->foldNodeCompletely();
647 } else if (CurNodeH.getNode()->isArray()) {
648 NH.getNode()->foldNodeCompletely();
652 // Merge the type entries of the two nodes together...
653 if (NH.getNode()->Ty != Type::VoidTy)
654 CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
655 assert(!CurNodeH.getNode()->isDeadNode());
657 // If we are merging a node with a completely folded node, then both nodes are
658 // now completely folded.
660 if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
661 if (!NH.getNode()->isNodeCompletelyFolded()) {
662 NH.getNode()->foldNodeCompletely();
663 assert(NH.getNode() && NH.getOffset() == 0 &&
664 "folding did not make offset 0?");
665 NOffset = NH.getOffset();
666 NSize = NH.getNode()->getSize();
667 assert(NOffset == 0 && NSize == 1);
669 } else if (NH.getNode()->isNodeCompletelyFolded()) {
670 CurNodeH.getNode()->foldNodeCompletely();
671 assert(CurNodeH.getNode() && CurNodeH.getOffset() == 0 &&
672 "folding did not make offset 0?");
673 NOffset = NH.getOffset();
674 NSize = NH.getNode()->getSize();
675 assert(NOffset == 0 && NSize == 1);
678 DSNode *N = NH.getNode();
679 if (CurNodeH.getNode() == N || N == 0) return;
680 assert(!CurNodeH.getNode()->isDeadNode());
682 // Merge the NodeType information.
683 CurNodeH.getNode()->NodeType |= N->NodeType;
685 // Start forwarding to the new node!
686 N->forwardNode(CurNodeH.getNode(), NOffset);
687 assert(!CurNodeH.getNode()->isDeadNode());
689 // Make all of the outgoing links of N now be outgoing links of CurNodeH.
691 for (unsigned i = 0; i < N->getNumLinks(); ++i) {
692 DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
693 if (Link.getNode()) {
694 // Compute the offset into the current node at which to
695 // merge this link. In the common case, this is a linear
696 // relation to the offset in the original node (with
697 // wrapping), but if the current node gets collapsed due to
698 // recursive merging, we must make sure to merge in all remaining
699 // links at offset zero.
700 unsigned MergeOffset = 0;
701 DSNode *CN = CurNodeH.getNode();
703 MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
704 CN->addEdgeTo(MergeOffset, Link);
708 // Now that there are no outgoing edges, all of the Links are dead.
711 // Merge the globals list...
712 if (!N->Globals.empty()) {
713 CurNodeH.getNode()->mergeGlobals(N->Globals);
715 // Delete the globals from the old node...
716 std::vector<GlobalValue*>().swap(N->Globals);
721 // mergeWith - Merge this node and the specified node, moving all links to and
722 // from the argument node into the current node, deleting the node argument.
723 // Offset indicates what offset the specified node is to be merged into the
726 // The specified node may be a null pointer (in which case, we update it to
727 // point to this node).
729 void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
730 DSNode *N = NH.getNode();
731 if (N == this && NH.getOffset() == Offset)
734 // If the RHS is a null node, make it point to this node!
736 NH.mergeWith(DSNodeHandle(this, Offset));
740 assert(!N->isDeadNode() && !isDeadNode());
741 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
744 // We cannot merge two pieces of the same node together, collapse the node
746 DEBUG(std::cerr << "Attempting to merge two chunks of"
747 << " the same node together!\n");
748 foldNodeCompletely();
752 // If both nodes are not at offset 0, make sure that we are merging the node
753 // at an later offset into the node with the zero offset.
755 if (Offset < NH.getOffset()) {
756 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
758 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
759 // If the offsets are the same, merge the smaller node into the bigger node
760 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
764 // Ok, now we can merge the two nodes. Use a static helper that works with
765 // two node handles, since "this" may get merged away at intermediate steps.
766 DSNodeHandle CurNodeH(this, Offset);
767 DSNodeHandle NHCopy(NH);
768 DSNode::MergeNodes(CurNodeH, NHCopy);
772 //===----------------------------------------------------------------------===//
773 // ReachabilityCloner Implementation
774 //===----------------------------------------------------------------------===//
776 DSNodeHandle ReachabilityCloner::getClonedNH(const DSNodeHandle &SrcNH) {
777 if (SrcNH.isNull()) return DSNodeHandle();
778 const DSNode *SN = SrcNH.getNode();
780 DSNodeHandle &NH = NodeMap[SN];
781 if (!NH.isNull()) // Node already mapped?
782 return DSNodeHandle(NH.getNode(), NH.getOffset()+SrcNH.getOffset());
784 DSNode *DN = new DSNode(*SN, &Dest, true /* Null out all links */);
785 DN->maskNodeTypes(BitsToKeep);
788 // Next, recursively clone all outgoing links as necessary. Note that
789 // adding these links can cause the node to collapse itself at any time, and
790 // the current node may be merged with arbitrary other nodes. For this
791 // reason, we must always go through NH.
793 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
794 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
795 if (!SrcEdge.isNull()) {
796 const DSNodeHandle &DestEdge = getClonedNH(SrcEdge);
797 // Compute the offset into the current node at which to
798 // merge this link. In the common case, this is a linear
799 // relation to the offset in the original node (with
800 // wrapping), but if the current node gets collapsed due to
801 // recursive merging, we must make sure to merge in all remaining
802 // links at offset zero.
803 unsigned MergeOffset = 0;
804 DSNode *CN = NH.getNode();
805 if (CN->getSize() != 1)
806 MergeOffset = ((i << DS::PointerShift)+NH.getOffset()
807 - SrcNH.getOffset()) %CN->getSize();
808 CN->addEdgeTo(MergeOffset, DestEdge);
812 // If this node contains any globals, make sure they end up in the scalar
813 // map with the correct offset.
814 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
816 GlobalValue *GV = *I;
817 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
818 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
819 assert(DestGNH.getNode() == NH.getNode() &&"Global mapping inconsistent");
820 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
821 DestGNH.getOffset()+SrcGNH.getOffset()));
823 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
824 Dest.getInlinedGlobals().insert(GV);
827 return DSNodeHandle(NH.getNode(), NH.getOffset()+SrcNH.getOffset());
830 void ReachabilityCloner::merge(const DSNodeHandle &NH,
831 const DSNodeHandle &SrcNH) {
832 if (SrcNH.isNull()) return; // Noop
834 // If there is no destination node, just clone the source and assign the
835 // destination node to be it.
836 NH.mergeWith(getClonedNH(SrcNH));
840 // Okay, at this point, we know that we have both a destination and a source
841 // node that need to be merged. Check to see if the source node has already
843 const DSNode *SN = SrcNH.getNode();
844 DSNodeHandle &SCNH = NodeMap[SN]; // SourceClonedNodeHandle
845 if (!SCNH.isNull()) { // Node already cloned?
846 NH.mergeWith(DSNodeHandle(SCNH.getNode(),
847 SCNH.getOffset()+SrcNH.getOffset()));
849 return; // Nothing to do!
852 // Okay, so the source node has not already been cloned. Instead of creating
853 // a new DSNode, only to merge it into the one we already have, try to perform
854 // the merge in-place. The only case we cannot handle here is when the offset
855 // into the existing node is less than the offset into the virtual node we are
856 // merging in. In this case, we have to extend the existing node, which
857 // requires an allocation anyway.
858 DSNode *DN = NH.getNode(); // Make sure the Offset is up-to-date
859 if (NH.getOffset() >= SrcNH.getOffset()) {
860 if (!DN->isNodeCompletelyFolded()) {
861 // Make sure the destination node is folded if the source node is folded.
862 if (SN->isNodeCompletelyFolded()) {
863 DN->foldNodeCompletely();
865 } else if (SN->getSize() != DN->getSize()) {
866 // If the two nodes are of different size, and the smaller node has the
867 // array bit set, collapse!
868 if (SN->getSize() < DN->getSize()) {
870 DN->foldNodeCompletely();
873 } else if (DN->isArray()) {
874 DN->foldNodeCompletely();
879 // Merge the type entries of the two nodes together...
880 if (SN->getType() != Type::VoidTy && !DN->isNodeCompletelyFolded()) {
881 DN->mergeTypeInfo(SN->getType(), NH.getOffset()-SrcNH.getOffset());
886 assert(!DN->isDeadNode());
888 // Merge the NodeType information.
889 DN->mergeNodeFlags(SN->getNodeFlags() & BitsToKeep);
891 // Before we start merging outgoing links and updating the scalar map, make
892 // sure it is known that this is the representative node for the src node.
893 SCNH = DSNodeHandle(DN, NH.getOffset()-SrcNH.getOffset());
895 // If the source node contains any globals, make sure they end up in the
896 // scalar map with the correct offset.
897 if (SN->global_begin() != SN->global_end()) {
898 // Update the globals in the destination node itself.
899 DN->mergeGlobals(SN->getGlobals());
901 // Update the scalar map for the graph we are merging the source node
903 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
905 GlobalValue *GV = *I;
906 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
907 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
908 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
909 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
910 DestGNH.getOffset()+SrcGNH.getOffset()));
912 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
913 Dest.getInlinedGlobals().insert(GV);
917 // We cannot handle this case without allocating a temporary node. Fall
918 // back on being simple.
919 DSNode *NewDN = new DSNode(*SN, &Dest, true /* Null out all links */);
920 NewDN->maskNodeTypes(BitsToKeep);
922 unsigned NHOffset = NH.getOffset();
923 NH.mergeWith(DSNodeHandle(NewDN, SrcNH.getOffset()));
925 assert(NH.getNode() &&
926 (NH.getOffset() > NHOffset ||
927 (NH.getOffset() == 0 && NH.getNode()->isNodeCompletelyFolded())) &&
928 "Merging did not adjust the offset!");
930 // Before we start merging outgoing links and updating the scalar map, make
931 // sure it is known that this is the representative node for the src node.
932 SCNH = DSNodeHandle(NH.getNode(), NH.getOffset()-SrcNH.getOffset());
934 // If the source node contained any globals, make sure to create entries
935 // in the scalar map for them!
936 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
938 GlobalValue *GV = *I;
939 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
940 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
941 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
942 assert(SrcGNH.getNode() == SN && "Global mapping inconsistent");
943 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
944 DestGNH.getOffset()+SrcGNH.getOffset()));
946 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
947 Dest.getInlinedGlobals().insert(GV);
952 // Next, recursively merge all outgoing links as necessary. Note that
953 // adding these links can cause the destination node to collapse itself at
954 // any time, and the current node may be merged with arbitrary other nodes.
955 // For this reason, we must always go through NH.
957 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
958 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
959 if (!SrcEdge.isNull()) {
960 // Compute the offset into the current node at which to
961 // merge this link. In the common case, this is a linear
962 // relation to the offset in the original node (with
963 // wrapping), but if the current node gets collapsed due to
964 // recursive merging, we must make sure to merge in all remaining
965 // links at offset zero.
966 unsigned MergeOffset = 0;
967 DSNode *CN = SCNH.getNode();
968 if (CN->getSize() != 1)
969 MergeOffset = ((i << DS::PointerShift)+SCNH.getOffset()) %CN->getSize();
971 DSNodeHandle &Link = CN->getLink(MergeOffset);
972 if (!Link.isNull()) {
973 // Perform the recursive merging. Make sure to create a temporary NH,
974 // because the Link can disappear in the process of recursive merging.
975 DSNodeHandle Tmp = Link;
978 merge(Link, SrcEdge);
984 /// mergeCallSite - Merge the nodes reachable from the specified src call
985 /// site into the nodes reachable from DestCS.
986 void ReachabilityCloner::mergeCallSite(const DSCallSite &DestCS,
987 const DSCallSite &SrcCS) {
988 merge(DestCS.getRetVal(), SrcCS.getRetVal());
989 unsigned MinArgs = DestCS.getNumPtrArgs();
990 if (SrcCS.getNumPtrArgs() < MinArgs) MinArgs = SrcCS.getNumPtrArgs();
992 for (unsigned a = 0; a != MinArgs; ++a)
993 merge(DestCS.getPtrArg(a), SrcCS.getPtrArg(a));
997 //===----------------------------------------------------------------------===//
998 // DSCallSite Implementation
999 //===----------------------------------------------------------------------===//
1001 // Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
1002 Function &DSCallSite::getCaller() const {
1003 return *Site.getInstruction()->getParent()->getParent();
1006 void DSCallSite::InitNH(DSNodeHandle &NH, const DSNodeHandle &Src,
1007 ReachabilityCloner &RC) {
1008 NH = RC.getClonedNH(Src);
1011 //===----------------------------------------------------------------------===//
1012 // DSGraph Implementation
1013 //===----------------------------------------------------------------------===//
1015 /// getFunctionNames - Return a space separated list of the name of the
1016 /// functions in this graph (if any)
1017 std::string DSGraph::getFunctionNames() const {
1018 switch (getReturnNodes().size()) {
1019 case 0: return "Globals graph";
1020 case 1: return getReturnNodes().begin()->first->getName();
1023 for (DSGraph::ReturnNodesTy::const_iterator I = getReturnNodes().begin();
1024 I != getReturnNodes().end(); ++I)
1025 Return += I->first->getName() + " ";
1026 Return.erase(Return.end()-1, Return.end()); // Remove last space character
1032 DSGraph::DSGraph(const DSGraph &G) : GlobalsGraph(0), TD(G.TD) {
1033 PrintAuxCalls = false;
1035 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
1038 DSGraph::DSGraph(const DSGraph &G, NodeMapTy &NodeMap)
1039 : GlobalsGraph(0), TD(G.TD) {
1040 PrintAuxCalls = false;
1041 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
1044 DSGraph::~DSGraph() {
1045 FunctionCalls.clear();
1046 AuxFunctionCalls.clear();
1047 InlinedGlobals.clear();
1049 ReturnNodes.clear();
1051 // Drop all intra-node references, so that assertions don't fail...
1052 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
1053 (*NI)->dropAllReferences();
1055 // Free all of the nodes.
1059 // dump - Allow inspection of graph in a debugger.
1060 void DSGraph::dump() const { print(std::cerr); }
1063 /// remapLinks - Change all of the Links in the current node according to the
1064 /// specified mapping.
1066 void DSNode::remapLinks(DSGraph::NodeMapTy &OldNodeMap) {
1067 for (unsigned i = 0, e = Links.size(); i != e; ++i)
1068 if (DSNode *N = Links[i].getNode()) {
1069 DSGraph::NodeMapTy::const_iterator ONMI = OldNodeMap.find(N);
1070 if (ONMI != OldNodeMap.end()) {
1071 Links[i].setNode(ONMI->second.getNode());
1072 Links[i].setOffset(Links[i].getOffset()+ONMI->second.getOffset());
1077 /// updateFromGlobalGraph - This function rematerializes global nodes and
1078 /// nodes reachable from them from the globals graph into the current graph.
1079 /// It uses the vector InlinedGlobals to avoid cloning and merging globals that
1080 /// are already up-to-date in the current graph. In practice, in the TD pass,
1081 /// this is likely to be a large fraction of the live global nodes in each
1082 /// function (since most live nodes are likely to have been brought up-to-date
1083 /// in at _some_ caller or callee).
1085 void DSGraph::updateFromGlobalGraph() {
1086 TIME_REGION(X, "updateFromGlobalGraph");
1087 ReachabilityCloner RC(*this, *GlobalsGraph, 0);
1089 // Clone the non-up-to-date global nodes into this graph.
1090 for (DSScalarMap::global_iterator I = getScalarMap().global_begin(),
1091 E = getScalarMap().global_end(); I != E; ++I)
1092 if (InlinedGlobals.count(*I) == 0) { // GNode is not up-to-date
1093 DSScalarMap::iterator It = GlobalsGraph->ScalarMap.find(*I);
1094 if (It != GlobalsGraph->ScalarMap.end())
1095 RC.merge(getNodeForValue(*I), It->second);
1099 /// cloneInto - Clone the specified DSGraph into the current graph. The
1100 /// translated ScalarMap for the old function is filled into the OldValMap
1101 /// member, and the translated ReturnNodes map is returned into ReturnNodes.
1103 /// The CloneFlags member controls various aspects of the cloning process.
1105 void DSGraph::cloneInto(const DSGraph &G, DSScalarMap &OldValMap,
1106 ReturnNodesTy &OldReturnNodes, NodeMapTy &OldNodeMap,
1107 unsigned CloneFlags) {
1108 TIME_REGION(X, "cloneInto");
1109 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
1110 assert(&G != this && "Cannot clone graph into itself!");
1112 // Remove alloca or mod/ref bits as specified...
1113 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
1114 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
1115 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
1116 BitsToClear |= DSNode::DEAD; // Clear dead flag...
1118 for (node_iterator I = G.node_begin(), E = G.node_end(); I != E; ++I) {
1119 assert(!(*I)->isForwarding() &&
1120 "Forward nodes shouldn't be in node list!");
1121 DSNode *New = new DSNode(**I, this);
1122 New->maskNodeTypes(~BitsToClear);
1123 OldNodeMap[*I] = New;
1127 Timer::addPeakMemoryMeasurement();
1130 // Rewrite the links in the new nodes to point into the current graph now.
1131 // Note that we don't loop over the node's list to do this. The problem is
1132 // that remaping links can cause recursive merging to happen, which means
1133 // that node_iterator's can get easily invalidated! Because of this, we
1134 // loop over the OldNodeMap, which contains all of the new nodes as the
1135 // .second element of the map elements. Also note that if we remap a node
1136 // more than once, we won't break anything.
1137 for (NodeMapTy::iterator I = OldNodeMap.begin(), E = OldNodeMap.end();
1139 I->second.getNode()->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().isNull())
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 // Clone over all globals that appear in the caller and callee graphs.
1239 for (DSScalarMap::global_iterator GI = Graph.getScalarMap().global_begin(),
1240 E = Graph.getScalarMap().global_end(); GI != E; ++GI)
1241 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*GI))
1242 if (ScalarMap.count(GV))
1243 RC.merge(ScalarMap[GV], Graph.getNodeForValue(GV));
1245 DSNodeHandle RetVal = getReturnNodeFor(F);
1247 // Merge the return value with the return value of the context...
1248 RetVal.mergeWith(CS.getRetVal());
1250 // Resolve all of the function arguments...
1251 Function::aiterator AI = F.abegin();
1253 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
1254 // Advance the argument iterator to the first pointer argument...
1255 while (AI != F.aend() && !isPointerType(AI->getType())) {
1257 #ifndef NDEBUG // FIXME: We should merge varargs arguments!!
1258 if (AI == F.aend() && !F.getFunctionType()->isVarArg())
1259 std::cerr << "Bad call to Function: " << F.getName() << "\n";
1262 if (AI == F.aend()) break;
1264 // Add the link from the argument scalar to the provided value
1265 DSNodeHandle &NH = getNodeForValue(AI);
1266 assert(NH.getNode() && "Pointer argument without scalarmap entry?");
1267 NH.mergeWith(CS.getPtrArg(i));
1272 /// getCallSiteForArguments - Get the arguments and return value bindings for
1273 /// the specified function in the current graph.
1275 DSCallSite DSGraph::getCallSiteForArguments(Function &F) const {
1276 std::vector<DSNodeHandle> Args;
1278 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
1279 if (isPointerType(I->getType()))
1280 Args.push_back(getNodeForValue(I));
1282 return DSCallSite(CallSite(), getReturnNodeFor(F), &F, Args);
1287 // markIncompleteNodes - Mark the specified node as having contents that are not
1288 // known with the current analysis we have performed. Because a node makes all
1289 // of the nodes it can reach incomplete if the node itself is incomplete, we
1290 // must recursively traverse the data structure graph, marking all reachable
1291 // nodes as incomplete.
1293 static void markIncompleteNode(DSNode *N) {
1294 // Stop recursion if no node, or if node already marked...
1295 if (N == 0 || N->isIncomplete()) return;
1297 // Actually mark the node
1298 N->setIncompleteMarker();
1300 // Recursively process children...
1301 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
1302 if (DSNode *DSN = N->getLink(i).getNode())
1303 markIncompleteNode(DSN);
1306 static void markIncomplete(DSCallSite &Call) {
1307 // Then the return value is certainly incomplete!
1308 markIncompleteNode(Call.getRetVal().getNode());
1310 // All objects pointed to by function arguments are incomplete!
1311 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
1312 markIncompleteNode(Call.getPtrArg(i).getNode());
1315 // markIncompleteNodes - Traverse the graph, identifying nodes that may be
1316 // modified by other functions that have not been resolved yet. This marks
1317 // nodes that are reachable through three sources of "unknownness":
1319 // Global Variables, Function Calls, and Incoming Arguments
1321 // For any node that may have unknown components (because something outside the
1322 // scope of current analysis may have modified it), the 'Incomplete' flag is
1323 // added to the NodeType.
1325 void DSGraph::markIncompleteNodes(unsigned Flags) {
1326 // Mark any incoming arguments as incomplete...
1327 if (Flags & DSGraph::MarkFormalArgs)
1328 for (ReturnNodesTy::iterator FI = ReturnNodes.begin(), E =ReturnNodes.end();
1330 Function &F = *FI->first;
1331 if (F.getName() != "main")
1332 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
1333 if (isPointerType(I->getType()))
1334 markIncompleteNode(getNodeForValue(I).getNode());
1337 // Mark stuff passed into functions calls as being incomplete...
1338 if (!shouldPrintAuxCalls())
1339 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1340 markIncomplete(FunctionCalls[i]);
1342 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1343 markIncomplete(AuxFunctionCalls[i]);
1346 // Mark all global nodes as incomplete...
1347 if ((Flags & DSGraph::IgnoreGlobals) == 0)
1348 for (DSScalarMap::global_iterator I = ScalarMap.global_begin(),
1349 E = ScalarMap.global_end(); I != E; ++I)
1350 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I))
1351 if (!GV->isConstant())
1352 markIncompleteNode(ScalarMap[GV].getNode());
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()->isComplete() &&
1390 CS.getCalleeNode()->getGlobals().empty()) { // No useful info?
1392 std::cerr << "WARNING: Useless call site found.\n";
1394 CS.swap(Calls.back());
1398 // If the return value or any arguments point to a void node with no
1399 // information at all in it, and the call node is the only node to point
1400 // to it, remove the edge to the node (killing the node).
1402 killIfUselessEdge(CS.getRetVal());
1403 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
1404 killIfUselessEdge(CS.getPtrArg(a));
1406 // If this call site calls the same function as the last call site, and if
1407 // the function pointer contains an external function, this node will
1408 // never be resolved. Merge the arguments of the call node because no
1409 // information will be lost.
1411 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
1412 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
1413 ++NumDuplicateCalls;
1414 if (NumDuplicateCalls == 1) {
1416 LastCalleeContainsExternalFunction =
1417 nodeContainsExternalFunction(LastCalleeNode);
1419 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
1422 // It is not clear why, but enabling this code makes DSA really
1423 // sensitive to node forwarding. Basically, with this enabled, DSA
1424 // performs different number of inlinings based on which nodes are
1425 // forwarding or not. This is clearly a problem, so this code is
1426 // disabled until this can be resolved.
1428 if (LastCalleeContainsExternalFunction
1431 // This should be more than enough context sensitivity!
1432 // FIXME: Evaluate how many times this is tripped!
1433 NumDuplicateCalls > 20
1436 DSCallSite &OCS = Calls[i-1];
1439 // The node will now be eliminated as a duplicate!
1440 if (CS.getNumPtrArgs() < OCS.getNumPtrArgs())
1442 else if (CS.getNumPtrArgs() > OCS.getNumPtrArgs())
1447 if (CS.isDirectCall()) {
1448 LastCalleeFunc = CS.getCalleeFunc();
1451 LastCalleeNode = CS.getCalleeNode();
1454 NumDuplicateCalls = 0;
1459 Calls.erase(std::unique(Calls.begin(), Calls.end()), Calls.end());
1461 // Track the number of call nodes merged away...
1462 NumCallNodesMerged += NumFns-Calls.size();
1464 DEBUG(if (NumFns != Calls.size())
1465 std::cerr << "Merged " << (NumFns-Calls.size()) << " call nodes.\n";);
1469 // removeTriviallyDeadNodes - After the graph has been constructed, this method
1470 // removes all unreachable nodes that are created because they got merged with
1471 // other nodes in the graph. These nodes will all be trivially unreachable, so
1472 // we don't have to perform any non-trivial analysis here.
1474 void DSGraph::removeTriviallyDeadNodes() {
1475 TIME_REGION(X, "removeTriviallyDeadNodes");
1477 // Loop over all of the nodes in the graph, calling getNode on each field.
1478 // This will cause all nodes to update their forwarding edges, causing
1479 // forwarded nodes to be delete-able.
1480 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI) {
1482 for (unsigned l = 0, e = N->getNumLinks(); l != e; ++l)
1483 N->getLink(l*N->getPointerSize()).getNode();
1486 // NOTE: This code is disabled. Though it should, in theory, allow us to
1487 // remove more nodes down below, the scan of the scalar map is incredibly
1488 // expensive for certain programs (with large SCCs). In the future, if we can
1489 // make the scalar map scan more efficient, then we can reenable this.
1491 { TIME_REGION(X, "removeTriviallyDeadNodes:scalarmap");
1493 // Likewise, forward any edges from the scalar nodes. While we are at it,
1494 // clean house a bit.
1495 for (DSScalarMap::iterator I = ScalarMap.begin(),E = ScalarMap.end();I != E;){
1496 I->second.getNode();
1501 bool isGlobalsGraph = !GlobalsGraph;
1503 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E; ) {
1506 // Do not remove *any* global nodes in the globals graph.
1507 // This is a special case because such nodes may not have I, M, R flags set.
1508 if (Node.isGlobalNode() && isGlobalsGraph) {
1513 if (Node.isComplete() && !Node.isModified() && !Node.isRead()) {
1514 // This is a useless node if it has no mod/ref info (checked above),
1515 // outgoing edges (which it cannot, as it is not modified in this
1516 // context), and it has no incoming edges. If it is a global node it may
1517 // have all of these properties and still have incoming edges, due to the
1518 // scalar map, so we check those now.
1520 if (Node.getNumReferrers() == Node.getGlobals().size()) {
1521 const std::vector<GlobalValue*> &Globals = Node.getGlobals();
1523 // Loop through and make sure all of the globals are referring directly
1525 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1526 DSNode *N = getNodeForValue(Globals[j]).getNode();
1527 assert(N == &Node && "ScalarMap doesn't match globals list!");
1530 // Make sure NumReferrers still agrees, if so, the node is truly dead.
1531 if (Node.getNumReferrers() == Globals.size()) {
1532 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1533 ScalarMap.erase(Globals[j]);
1534 Node.makeNodeDead();
1535 ++NumTrivialGlobalDNE;
1540 if (Node.getNodeFlags() == 0 && Node.hasNoReferrers()) {
1541 // This node is dead!
1542 NI = Nodes.erase(NI); // Erase & remove from node list.
1549 removeIdenticalCalls(FunctionCalls);
1550 removeIdenticalCalls(AuxFunctionCalls);
1554 /// markReachableNodes - This method recursively traverses the specified
1555 /// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
1556 /// to the set, which allows it to only traverse visited nodes once.
1558 void DSNode::markReachableNodes(hash_set<DSNode*> &ReachableNodes) {
1559 if (this == 0) return;
1560 assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
1561 if (ReachableNodes.insert(this).second) // Is newly reachable?
1562 for (unsigned i = 0, e = getSize(); i < e; i += DS::PointerSize)
1563 getLink(i).getNode()->markReachableNodes(ReachableNodes);
1566 void DSCallSite::markReachableNodes(hash_set<DSNode*> &Nodes) {
1567 getRetVal().getNode()->markReachableNodes(Nodes);
1568 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
1570 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
1571 getPtrArg(i).getNode()->markReachableNodes(Nodes);
1574 // CanReachAliveNodes - Simple graph walker that recursively traverses the graph
1575 // looking for a node that is marked alive. If an alive node is found, return
1576 // true, otherwise return false. If an alive node is reachable, this node is
1577 // marked as alive...
1579 static bool CanReachAliveNodes(DSNode *N, hash_set<DSNode*> &Alive,
1580 hash_set<DSNode*> &Visited,
1581 bool IgnoreGlobals) {
1582 if (N == 0) return false;
1583 assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
1585 // If this is a global node, it will end up in the globals graph anyway, so we
1586 // don't need to worry about it.
1587 if (IgnoreGlobals && N->isGlobalNode()) return false;
1589 // If we know that this node is alive, return so!
1590 if (Alive.count(N)) return true;
1592 // Otherwise, we don't think the node is alive yet, check for infinite
1594 if (Visited.count(N)) return false; // Found a cycle
1595 Visited.insert(N); // No recursion, insert into Visited...
1597 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
1598 if (CanReachAliveNodes(N->getLink(i).getNode(), Alive, Visited,
1600 N->markReachableNodes(Alive);
1606 // CallSiteUsesAliveArgs - Return true if the specified call site can reach any
1609 static bool CallSiteUsesAliveArgs(DSCallSite &CS, hash_set<DSNode*> &Alive,
1610 hash_set<DSNode*> &Visited,
1611 bool IgnoreGlobals) {
1612 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited,
1615 if (CS.isIndirectCall() &&
1616 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited, IgnoreGlobals))
1618 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
1619 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited,
1625 // removeDeadNodes - Use a more powerful reachability analysis to eliminate
1626 // subgraphs that are unreachable. This often occurs because the data
1627 // structure doesn't "escape" into it's caller, and thus should be eliminated
1628 // from the caller's graph entirely. This is only appropriate to use when
1631 void DSGraph::removeDeadNodes(unsigned Flags) {
1632 DEBUG(AssertGraphOK(); if (GlobalsGraph) GlobalsGraph->AssertGraphOK());
1634 // Reduce the amount of work we have to do... remove dummy nodes left over by
1636 removeTriviallyDeadNodes();
1638 TIME_REGION(X, "removeDeadNodes");
1640 // FIXME: Merge non-trivially identical call nodes...
1642 // Alive - a set that holds all nodes found to be reachable/alive.
1643 hash_set<DSNode*> Alive;
1644 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
1646 // Copy and merge all information about globals to the GlobalsGraph if this is
1647 // not a final pass (where unreachable globals are removed).
1649 // Strip all alloca bits since the current function is only for the BU pass.
1650 // Strip all incomplete bits since they are short-lived properties and they
1651 // will be correctly computed when rematerializing nodes into the functions.
1653 ReachabilityCloner GGCloner(*GlobalsGraph, *this, DSGraph::StripAllocaBit |
1654 DSGraph::StripIncompleteBit);
1656 // Mark all nodes reachable by (non-global) scalar nodes as alive...
1657 { TIME_REGION(Y, "removeDeadNodes:scalarscan");
1658 for (DSScalarMap::iterator I = ScalarMap.begin(), E = ScalarMap.end(); I !=E;)
1659 if (isa<GlobalValue>(I->first)) { // Keep track of global nodes
1660 assert(I->second.getNode() && "Null global node?");
1661 assert(I->second.getNode()->isGlobalNode() && "Should be a global node!");
1662 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
1664 // Make sure that all globals are cloned over as roots.
1665 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
1666 DSGraph::ScalarMapTy::iterator SMI =
1667 GlobalsGraph->getScalarMap().find(I->first);
1668 if (SMI != GlobalsGraph->getScalarMap().end())
1669 GGCloner.merge(SMI->second, I->second);
1671 GGCloner.getClonedNH(I->second);
1675 DSNode *N = I->second.getNode();
1677 // Check to see if this is a worthless node generated for non-pointer
1678 // values, such as integers. Consider an addition of long types: A+B.
1679 // Assuming we can track all uses of the value in this context, and it is
1680 // NOT used as a pointer, we can delete the node. We will be able to
1681 // detect this situation if the node pointed to ONLY has Unknown bit set
1682 // in the node. In this case, the node is not incomplete, does not point
1683 // to any other nodes (no mod/ref bits set), and is therefore
1684 // uninteresting for data structure analysis. If we run across one of
1685 // these, prune the scalar pointing to it.
1687 if (N->getNodeFlags() == DSNode::UnknownNode && !isa<Argument>(I->first))
1688 ScalarMap.erase(I++);
1691 N->markReachableNodes(Alive);
1697 // The return values are alive as well.
1698 for (ReturnNodesTy::iterator I = ReturnNodes.begin(), E = ReturnNodes.end();
1700 I->second.getNode()->markReachableNodes(Alive);
1702 // Mark any nodes reachable by primary calls as alive...
1703 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1704 FunctionCalls[i].markReachableNodes(Alive);
1707 // Now find globals and aux call nodes that are already live or reach a live
1708 // value (which makes them live in turn), and continue till no more are found.
1711 hash_set<DSNode*> Visited;
1712 std::vector<unsigned char> AuxFCallsAlive(AuxFunctionCalls.size());
1715 // If any global node points to a non-global that is "alive", the global is
1716 // "alive" as well... Remove it from the GlobalNodes list so we only have
1717 // unreachable globals in the list.
1720 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
1721 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
1722 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited,
1723 Flags & DSGraph::RemoveUnreachableGlobals)) {
1724 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to...
1725 GlobalNodes.pop_back(); // erase efficiently
1729 // Mark only unresolvable call nodes for moving to the GlobalsGraph since
1730 // call nodes that get resolved will be difficult to remove from that graph.
1731 // The final unresolved call nodes must be handled specially at the end of
1732 // the BU pass (i.e., in main or other roots of the call graph).
1733 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1734 if (!AuxFCallsAlive[i] &&
1735 (AuxFunctionCalls[i].isIndirectCall()
1736 || CallSiteUsesAliveArgs(AuxFunctionCalls[i], Alive, Visited,
1737 Flags & DSGraph::RemoveUnreachableGlobals))) {
1738 AuxFunctionCalls[i].markReachableNodes(Alive);
1739 AuxFCallsAlive[i] = true;
1744 // Move dead aux function calls to the end of the list
1745 unsigned CurIdx = 0;
1746 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1747 if (AuxFCallsAlive[i])
1748 AuxFunctionCalls[CurIdx++].swap(AuxFunctionCalls[i]);
1750 // Copy and merge all global nodes and dead aux call nodes into the
1751 // GlobalsGraph, and all nodes reachable from those nodes
1753 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
1754 // Copy the unreachable call nodes to the globals graph, updating their
1755 // target pointers using the GGCloner
1756 for (unsigned i = CurIdx, e = AuxFunctionCalls.size(); i != e; ++i)
1757 GlobalsGraph->AuxFunctionCalls.push_back(DSCallSite(AuxFunctionCalls[i],
1760 // Crop all the useless ones out...
1761 AuxFunctionCalls.erase(AuxFunctionCalls.begin()+CurIdx,
1762 AuxFunctionCalls.end());
1764 // We are finally done with the GGCloner so we can destroy it.
1767 // At this point, any nodes which are visited, but not alive, are nodes
1768 // which can be removed. Loop over all nodes, eliminating completely
1769 // unreachable nodes.
1771 std::vector<DSNode*> DeadNodes;
1772 DeadNodes.reserve(Nodes.size());
1773 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E;) {
1775 assert(!N->isForwarding() && "Forwarded node in nodes list?");
1777 if (!Alive.count(N)) {
1779 assert(!N->isForwarding() && "Cannot remove a forwarding node!");
1780 DeadNodes.push_back(N);
1781 N->dropAllReferences();
1786 // Remove all unreachable globals from the ScalarMap.
1787 // If flag RemoveUnreachableGlobals is set, GlobalNodes has only dead nodes.
1788 // In either case, the dead nodes will not be in the set Alive.
1789 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
1790 if (!Alive.count(GlobalNodes[i].second))
1791 ScalarMap.erase(GlobalNodes[i].first);
1793 assert((Flags & DSGraph::RemoveUnreachableGlobals) && "non-dead global");
1795 // Delete all dead nodes now since their referrer counts are zero.
1796 for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
1797 delete DeadNodes[i];
1799 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
1802 void DSGraph::AssertGraphOK() const {
1803 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
1806 for (ScalarMapTy::const_iterator I = ScalarMap.begin(),
1807 E = ScalarMap.end(); I != E; ++I) {
1808 assert(I->second.getNode() && "Null node in scalarmap!");
1809 AssertNodeInGraph(I->second.getNode());
1810 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
1811 assert(I->second.getNode()->isGlobalNode() &&
1812 "Global points to node, but node isn't global?");
1813 AssertNodeContainsGlobal(I->second.getNode(), GV);
1816 AssertCallNodesInGraph();
1817 AssertAuxCallNodesInGraph();
1820 /// computeNodeMapping - Given roots in two different DSGraphs, traverse the
1821 /// nodes reachable from the two graphs, computing the mapping of nodes from
1822 /// the first to the second graph.
1824 void DSGraph::computeNodeMapping(const DSNodeHandle &NH1,
1825 const DSNodeHandle &NH2, NodeMapTy &NodeMap,
1826 bool StrictChecking) {
1827 DSNode *N1 = NH1.getNode(), *N2 = NH2.getNode();
1828 if (N1 == 0 || N2 == 0) return;
1830 DSNodeHandle &Entry = NodeMap[N1];
1831 if (Entry.getNode()) {
1832 // Termination of recursion!
1833 assert(!StrictChecking ||
1834 (Entry.getNode() == N2 &&
1835 Entry.getOffset() == (NH2.getOffset()-NH1.getOffset())) &&
1836 "Inconsistent mapping detected!");
1841 Entry.setOffset(NH2.getOffset()-NH1.getOffset());
1843 // Loop over all of the fields that N1 and N2 have in common, recursively
1844 // mapping the edges together now.
1845 int N2Idx = NH2.getOffset()-NH1.getOffset();
1846 unsigned N2Size = N2->getSize();
1847 for (unsigned i = 0, e = N1->getSize(); i < e; i += DS::PointerSize)
1848 if (unsigned(N2Idx)+i < N2Size)
1849 computeNodeMapping(N1->getLink(i), N2->getLink(N2Idx+i), NodeMap);