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/Debug.h"
21 #include "Support/STLExtras.h"
22 #include "Support/Statistic.h"
23 #include "Support/Timer.h"
29 Statistic<> NumFolds ("dsnode", "Number of nodes completely folded");
30 Statistic<> NumCallNodesMerged("dsnode", "Number of call nodes merged");
35 DSNode *DSNodeHandle::HandleForwarding() const {
36 assert(!N->ForwardNH.isNull() && "Can only be invoked if forwarding!");
38 // Handle node forwarding here!
39 DSNode *Next = N->ForwardNH.getNode(); // Cause recursive shrinkage
40 Offset += N->ForwardNH.getOffset();
42 if (--N->NumReferrers == 0) {
43 // Removing the last referrer to the node, sever the forwarding link
49 if (N->Size <= Offset) {
50 assert(N->Size <= 1 && "Forwarded to shrunk but not collapsed node?");
56 //===----------------------------------------------------------------------===//
57 // DSNode Implementation
58 //===----------------------------------------------------------------------===//
60 DSNode::DSNode(const Type *T, DSGraph *G)
61 : NumReferrers(0), Size(0), ParentGraph(G), Ty(Type::VoidTy), NodeType(0) {
62 // Add the type entry if it is specified...
63 if (T) mergeTypeInfo(T, 0);
64 G->getNodes().push_back(this);
67 // DSNode copy constructor... do not copy over the referrers list!
68 DSNode::DSNode(const DSNode &N, DSGraph *G)
69 : NumReferrers(0), Size(N.Size), ParentGraph(G),
70 Ty(N.Ty), Links(N.Links), Globals(N.Globals), NodeType(N.NodeType) {
71 G->getNodes().push_back(this);
74 /// getTargetData - Get the target data object used to construct this node.
76 const TargetData &DSNode::getTargetData() const {
77 return ParentGraph->getTargetData();
80 void DSNode::assertOK() const {
81 assert((Ty != Type::VoidTy ||
82 Ty == Type::VoidTy && (Size == 0 ||
83 (NodeType & DSNode::Array))) &&
86 assert(ParentGraph && "Node has no parent?");
87 const DSGraph::ScalarMapTy &SM = ParentGraph->getScalarMap();
88 for (unsigned i = 0, e = Globals.size(); i != e; ++i) {
89 assert(SM.find(Globals[i]) != SM.end());
90 assert(SM.find(Globals[i])->second.getNode() == this);
94 /// forwardNode - Mark this node as being obsolete, and all references to it
95 /// should be forwarded to the specified node and offset.
97 void DSNode::forwardNode(DSNode *To, unsigned Offset) {
98 assert(this != To && "Cannot forward a node to itself!");
99 assert(ForwardNH.isNull() && "Already forwarding from this node!");
100 if (To->Size <= 1) Offset = 0;
101 assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
102 "Forwarded offset is wrong!");
103 ForwardNH.setNode(To);
104 ForwardNH.setOffset(Offset);
110 // addGlobal - Add an entry for a global value to the Globals list. This also
111 // marks the node with the 'G' flag if it does not already have it.
113 void DSNode::addGlobal(GlobalValue *GV) {
114 // Keep the list sorted.
115 std::vector<GlobalValue*>::iterator I =
116 std::lower_bound(Globals.begin(), Globals.end(), GV);
118 if (I == Globals.end() || *I != GV) {
119 //assert(GV->getType()->getElementType() == Ty);
120 Globals.insert(I, GV);
121 NodeType |= GlobalNode;
125 /// foldNodeCompletely - If we determine that this node has some funny
126 /// behavior happening to it that we cannot represent, we fold it down to a
127 /// single, completely pessimistic, node. This node is represented as a
128 /// single byte with a single TypeEntry of "void".
130 void DSNode::foldNodeCompletely() {
131 if (isNodeCompletelyFolded()) return; // If this node is already folded...
135 // Create the node we are going to forward to...
136 DSNode *DestNode = new DSNode(0, ParentGraph);
137 DestNode->NodeType = NodeType|DSNode::Array;
138 DestNode->Ty = Type::VoidTy;
140 DestNode->Globals.swap(Globals);
142 // Start forwarding to the destination node...
143 forwardNode(DestNode, 0);
146 DestNode->Links.push_back(Links[0]);
147 DSNodeHandle NH(DestNode);
149 // If we have links, merge all of our outgoing links together...
150 for (unsigned i = Links.size()-1; i != 0; --i)
151 NH.getNode()->Links[0].mergeWith(Links[i]);
154 DestNode->Links.resize(1);
158 /// isNodeCompletelyFolded - Return true if this node has been completely
159 /// folded down to something that can never be expanded, effectively losing
160 /// all of the field sensitivity that may be present in the node.
162 bool DSNode::isNodeCompletelyFolded() const {
163 return getSize() == 1 && Ty == Type::VoidTy && isArray();
167 /// TypeElementWalker Class - Used for implementation of physical subtyping...
169 class TypeElementWalker {
174 StackState(const Type *T, unsigned Off = 0)
175 : Ty(T), Offset(Off), Idx(0) {}
178 std::vector<StackState> Stack;
179 const TargetData &TD;
181 TypeElementWalker(const Type *T, const TargetData &td) : TD(td) {
186 bool isDone() const { return Stack.empty(); }
187 const Type *getCurrentType() const { return Stack.back().Ty; }
188 unsigned getCurrentOffset() const { return Stack.back().Offset; }
190 void StepToNextType() {
191 PopStackAndAdvance();
196 /// PopStackAndAdvance - Pop the current element off of the stack and
197 /// advance the underlying element to the next contained member.
198 void PopStackAndAdvance() {
199 assert(!Stack.empty() && "Cannot pop an empty stack!");
201 while (!Stack.empty()) {
202 StackState &SS = Stack.back();
203 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
205 if (SS.Idx != ST->getElementTypes().size()) {
206 const StructLayout *SL = TD.getStructLayout(ST);
207 SS.Offset += SL->MemberOffsets[SS.Idx]-SL->MemberOffsets[SS.Idx-1];
210 Stack.pop_back(); // At the end of the structure
212 const ArrayType *AT = cast<ArrayType>(SS.Ty);
214 if (SS.Idx != AT->getNumElements()) {
215 SS.Offset += TD.getTypeSize(AT->getElementType());
218 Stack.pop_back(); // At the end of the array
223 /// StepToLeaf - Used by physical subtyping to move to the first leaf node
224 /// on the type stack.
226 if (Stack.empty()) return;
227 while (!Stack.empty() && !Stack.back().Ty->isFirstClassType()) {
228 StackState &SS = Stack.back();
229 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
230 if (ST->getElementTypes().empty()) {
232 PopStackAndAdvance();
234 // Step into the structure...
235 assert(SS.Idx < ST->getElementTypes().size());
236 const StructLayout *SL = TD.getStructLayout(ST);
237 Stack.push_back(StackState(ST->getElementTypes()[SS.Idx],
238 SS.Offset+SL->MemberOffsets[SS.Idx]));
241 const ArrayType *AT = cast<ArrayType>(SS.Ty);
242 if (AT->getNumElements() == 0) {
244 PopStackAndAdvance();
246 // Step into the array...
247 assert(SS.Idx < AT->getNumElements());
248 Stack.push_back(StackState(AT->getElementType(),
250 TD.getTypeSize(AT->getElementType())));
256 } // end anonymous namespace
258 /// ElementTypesAreCompatible - Check to see if the specified types are
259 /// "physically" compatible. If so, return true, else return false. We only
260 /// have to check the fields in T1: T2 may be larger than T1. If AllowLargerT1
261 /// is true, then we also allow a larger T1.
263 static bool ElementTypesAreCompatible(const Type *T1, const Type *T2,
264 bool AllowLargerT1, const TargetData &TD){
265 TypeElementWalker T1W(T1, TD), T2W(T2, TD);
267 while (!T1W.isDone() && !T2W.isDone()) {
268 if (T1W.getCurrentOffset() != T2W.getCurrentOffset())
271 const Type *T1 = T1W.getCurrentType();
272 const Type *T2 = T2W.getCurrentType();
273 if (T1 != T2 && !T1->isLosslesslyConvertibleTo(T2))
276 T1W.StepToNextType();
277 T2W.StepToNextType();
280 return AllowLargerT1 || T1W.isDone();
284 /// mergeTypeInfo - This method merges the specified type into the current node
285 /// at the specified offset. This may update the current node's type record if
286 /// this gives more information to the node, it may do nothing to the node if
287 /// this information is already known, or it may merge the node completely (and
288 /// return true) if the information is incompatible with what is already known.
290 /// This method returns true if the node is completely folded, otherwise false.
292 bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset,
293 bool FoldIfIncompatible) {
294 const TargetData &TD = getTargetData();
295 // Check to make sure the Size member is up-to-date. Size can be one of the
297 // Size = 0, Ty = Void: Nothing is known about this node.
298 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
299 // Size = 1, Ty = Void, Array = 1: The node is collapsed
300 // Otherwise, sizeof(Ty) = Size
302 assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
303 (Size == 0 && !Ty->isSized() && !isArray()) ||
304 (Size == 1 && Ty == Type::VoidTy && isArray()) ||
305 (Size == 0 && !Ty->isSized() && !isArray()) ||
306 (TD.getTypeSize(Ty) == Size)) &&
307 "Size member of DSNode doesn't match the type structure!");
308 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
310 if (Offset == 0 && NewTy == Ty)
311 return false; // This should be a common case, handle it efficiently
313 // Return true immediately if the node is completely folded.
314 if (isNodeCompletelyFolded()) return true;
316 // If this is an array type, eliminate the outside arrays because they won't
317 // be used anyway. This greatly reduces the size of large static arrays used
318 // as global variables, for example.
320 bool WillBeArray = false;
321 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
322 // FIXME: we might want to keep small arrays, but must be careful about
323 // things like: [2 x [10000 x int*]]
324 NewTy = AT->getElementType();
328 // Figure out how big the new type we're merging in is...
329 unsigned NewTySize = NewTy->isSized() ? TD.getTypeSize(NewTy) : 0;
331 // Otherwise check to see if we can fold this type into the current node. If
332 // we can't, we fold the node completely, if we can, we potentially update our
335 if (Ty == Type::VoidTy) {
336 // If this is the first type that this node has seen, just accept it without
338 assert(Offset == 0 && !isArray() &&
339 "Cannot have an offset into a void node!");
342 if (WillBeArray) NodeType |= Array;
345 // Calculate the number of outgoing links from this node.
346 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
350 // Handle node expansion case here...
351 if (Offset+NewTySize > Size) {
352 // It is illegal to grow this node if we have treated it as an array of
355 if (FoldIfIncompatible) foldNodeCompletely();
359 if (Offset) { // We could handle this case, but we don't for now...
360 std::cerr << "UNIMP: Trying to merge a growth type into "
361 << "offset != 0: Collapsing!\n";
362 if (FoldIfIncompatible) foldNodeCompletely();
366 // Okay, the situation is nice and simple, we are trying to merge a type in
367 // at offset 0 that is bigger than our current type. Implement this by
368 // switching to the new type and then merge in the smaller one, which should
369 // hit the other code path here. If the other code path decides it's not
370 // ok, it will collapse the node as appropriate.
372 const Type *OldTy = Ty;
375 if (WillBeArray) NodeType |= Array;
378 // Must grow links to be the appropriate size...
379 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
381 // Merge in the old type now... which is guaranteed to be smaller than the
383 return mergeTypeInfo(OldTy, 0);
386 assert(Offset <= Size &&
387 "Cannot merge something into a part of our type that doesn't exist!");
389 // Find the section of Ty that NewTy overlaps with... first we find the
390 // type that starts at offset Offset.
393 const Type *SubType = Ty;
395 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
397 switch (SubType->getPrimitiveID()) {
398 case Type::StructTyID: {
399 const StructType *STy = cast<StructType>(SubType);
400 const StructLayout &SL = *TD.getStructLayout(STy);
402 unsigned i = 0, e = SL.MemberOffsets.size();
403 for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
406 // The offset we are looking for must be in the i'th element...
407 SubType = STy->getElementTypes()[i];
408 O += SL.MemberOffsets[i];
411 case Type::ArrayTyID: {
412 SubType = cast<ArrayType>(SubType)->getElementType();
413 unsigned ElSize = TD.getTypeSize(SubType);
414 unsigned Remainder = (Offset-O) % ElSize;
415 O = Offset-Remainder;
419 if (FoldIfIncompatible) foldNodeCompletely();
424 assert(O == Offset && "Could not achieve the correct offset!");
426 // If we found our type exactly, early exit
427 if (SubType == NewTy) return false;
429 unsigned SubTypeSize = SubType->isSized() ? TD.getTypeSize(SubType) : 0;
431 // Ok, we are getting desperate now. Check for physical subtyping, where we
432 // just require each element in the node to be compatible.
433 if (NewTySize <= SubTypeSize && NewTySize && NewTySize < 256 &&
434 SubTypeSize && SubTypeSize < 256 &&
435 ElementTypesAreCompatible(NewTy, SubType, !isArray(), TD))
438 // Okay, so we found the leader type at the offset requested. Search the list
439 // of types that starts at this offset. If SubType is currently an array or
440 // structure, the type desired may actually be the first element of the
443 unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
444 while (SubType != NewTy) {
445 const Type *NextSubType = 0;
446 unsigned NextSubTypeSize = 0;
447 unsigned NextPadSize = 0;
448 switch (SubType->getPrimitiveID()) {
449 case Type::StructTyID: {
450 const StructType *STy = cast<StructType>(SubType);
451 const StructLayout &SL = *TD.getStructLayout(STy);
452 if (SL.MemberOffsets.size() > 1)
453 NextPadSize = SL.MemberOffsets[1];
455 NextPadSize = SubTypeSize;
456 NextSubType = STy->getElementTypes()[0];
457 NextSubTypeSize = TD.getTypeSize(NextSubType);
460 case Type::ArrayTyID:
461 NextSubType = cast<ArrayType>(SubType)->getElementType();
462 NextSubTypeSize = TD.getTypeSize(NextSubType);
463 NextPadSize = NextSubTypeSize;
469 if (NextSubType == 0)
470 break; // In the default case, break out of the loop
472 if (NextPadSize < NewTySize)
473 break; // Don't allow shrinking to a smaller type than NewTySize
474 SubType = NextSubType;
475 SubTypeSize = NextSubTypeSize;
476 PadSize = NextPadSize;
479 // If we found the type exactly, return it...
480 if (SubType == NewTy)
483 // Check to see if we have a compatible, but different type...
484 if (NewTySize == SubTypeSize) {
485 // Check to see if this type is obviously convertible... int -> uint f.e.
486 if (NewTy->isLosslesslyConvertibleTo(SubType))
489 // Check to see if we have a pointer & integer mismatch going on here,
490 // loading a pointer as a long, for example.
492 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
493 NewTy->isInteger() && isa<PointerType>(SubType))
495 } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
496 // We are accessing the field, plus some structure padding. Ignore the
497 // structure padding.
502 if (getParentGraph()->getReturnNodes().size())
503 M = getParentGraph()->getReturnNodes().begin()->first->getParent();
504 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: ";
505 WriteTypeSymbolic(std::cerr, Ty, M) << "\n due to:";
506 WriteTypeSymbolic(std::cerr, NewTy, M) << " @ " << Offset << "!\n"
508 WriteTypeSymbolic(std::cerr, SubType, M) << "\n\n");
510 if (FoldIfIncompatible) foldNodeCompletely();
516 // addEdgeTo - Add an edge from the current node to the specified node. This
517 // can cause merging of nodes in the graph.
519 void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
520 if (NH.getNode() == 0) return; // Nothing to do
522 DSNodeHandle &ExistingEdge = getLink(Offset);
523 if (ExistingEdge.getNode()) {
524 // Merge the two nodes...
525 ExistingEdge.mergeWith(NH);
526 } else { // No merging to perform...
527 setLink(Offset, NH); // Just force a link in there...
532 // MergeSortedVectors - Efficiently merge a vector into another vector where
533 // duplicates are not allowed and both are sorted. This assumes that 'T's are
534 // efficiently copyable and have sane comparison semantics.
536 static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
537 const std::vector<GlobalValue*> &Src) {
538 // By far, the most common cases will be the simple ones. In these cases,
539 // avoid having to allocate a temporary vector...
541 if (Src.empty()) { // Nothing to merge in...
543 } else if (Dest.empty()) { // Just copy the result in...
545 } else if (Src.size() == 1) { // Insert a single element...
546 const GlobalValue *V = Src[0];
547 std::vector<GlobalValue*>::iterator I =
548 std::lower_bound(Dest.begin(), Dest.end(), V);
549 if (I == Dest.end() || *I != Src[0]) // If not already contained...
550 Dest.insert(I, Src[0]);
551 } else if (Dest.size() == 1) {
552 GlobalValue *Tmp = Dest[0]; // Save value in temporary...
553 Dest = Src; // Copy over list...
554 std::vector<GlobalValue*>::iterator I =
555 std::lower_bound(Dest.begin(), Dest.end(), Tmp);
556 if (I == Dest.end() || *I != Tmp) // If not already contained...
560 // Make a copy to the side of Dest...
561 std::vector<GlobalValue*> Old(Dest);
563 // Make space for all of the type entries now...
564 Dest.resize(Dest.size()+Src.size());
566 // Merge the two sorted ranges together... into Dest.
567 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
569 // Now erase any duplicate entries that may have accumulated into the
570 // vectors (because they were in both of the input sets)
571 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
576 // MergeNodes() - Helper function for DSNode::mergeWith().
577 // This function does the hard work of merging two nodes, CurNodeH
578 // and NH after filtering out trivial cases and making sure that
579 // CurNodeH.offset >= NH.offset.
582 // Since merging may cause either node to go away, we must always
583 // use the node-handles to refer to the nodes. These node handles are
584 // automatically updated during merging, so will always provide access
585 // to the correct node after a merge.
587 void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
588 assert(CurNodeH.getOffset() >= NH.getOffset() &&
589 "This should have been enforced in the caller.");
591 // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
592 // respect to NH.Offset) is now zero. NOffset is the distance from the base
593 // of our object that N starts from.
595 unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
596 unsigned NSize = NH.getNode()->getSize();
598 // If the two nodes are of different size, and the smaller node has the array
599 // bit set, collapse!
600 if (NSize != CurNodeH.getNode()->getSize()) {
601 if (NSize < CurNodeH.getNode()->getSize()) {
602 if (NH.getNode()->isArray())
603 NH.getNode()->foldNodeCompletely();
604 } else if (CurNodeH.getNode()->isArray()) {
605 NH.getNode()->foldNodeCompletely();
609 // Merge the type entries of the two nodes together...
610 if (NH.getNode()->Ty != Type::VoidTy)
611 CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
612 assert(!CurNodeH.getNode()->isDeadNode());
614 // If we are merging a node with a completely folded node, then both nodes are
615 // now completely folded.
617 if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
618 if (!NH.getNode()->isNodeCompletelyFolded()) {
619 NH.getNode()->foldNodeCompletely();
620 assert(NH.getNode() && NH.getOffset() == 0 &&
621 "folding did not make offset 0?");
622 NOffset = NH.getOffset();
623 NSize = NH.getNode()->getSize();
624 assert(NOffset == 0 && NSize == 1);
626 } else if (NH.getNode()->isNodeCompletelyFolded()) {
627 CurNodeH.getNode()->foldNodeCompletely();
628 assert(CurNodeH.getNode() && CurNodeH.getOffset() == 0 &&
629 "folding did not make offset 0?");
630 NOffset = NH.getOffset();
631 NSize = NH.getNode()->getSize();
632 assert(NOffset == 0 && NSize == 1);
635 DSNode *N = NH.getNode();
636 if (CurNodeH.getNode() == N || N == 0) return;
637 assert(!CurNodeH.getNode()->isDeadNode());
639 // Merge the NodeType information...
640 CurNodeH.getNode()->NodeType |= N->NodeType;
642 // Start forwarding to the new node!
643 N->forwardNode(CurNodeH.getNode(), NOffset);
644 assert(!CurNodeH.getNode()->isDeadNode());
646 // Make all of the outgoing links of N now be outgoing links of CurNodeH.
648 for (unsigned i = 0; i < N->getNumLinks(); ++i) {
649 DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
650 if (Link.getNode()) {
651 // Compute the offset into the current node at which to
652 // merge this link. In the common case, this is a linear
653 // relation to the offset in the original node (with
654 // wrapping), but if the current node gets collapsed due to
655 // recursive merging, we must make sure to merge in all remaining
656 // links at offset zero.
657 unsigned MergeOffset = 0;
658 DSNode *CN = CurNodeH.getNode();
660 MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
661 CN->addEdgeTo(MergeOffset, Link);
665 // Now that there are no outgoing edges, all of the Links are dead.
668 // Merge the globals list...
669 if (!N->Globals.empty()) {
670 MergeSortedVectors(CurNodeH.getNode()->Globals, N->Globals);
672 // Delete the globals from the old node...
673 std::vector<GlobalValue*>().swap(N->Globals);
678 // mergeWith - Merge this node and the specified node, moving all links to and
679 // from the argument node into the current node, deleting the node argument.
680 // Offset indicates what offset the specified node is to be merged into the
683 // The specified node may be a null pointer (in which case, nothing happens).
685 void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
686 DSNode *N = NH.getNode();
687 if (N == 0 || (N == this && NH.getOffset() == Offset))
690 assert(!N->isDeadNode() && !isDeadNode());
691 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
694 // We cannot merge two pieces of the same node together, collapse the node
696 DEBUG(std::cerr << "Attempting to merge two chunks of"
697 << " the same node together!\n");
698 foldNodeCompletely();
702 // If both nodes are not at offset 0, make sure that we are merging the node
703 // at an later offset into the node with the zero offset.
705 if (Offset < NH.getOffset()) {
706 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
708 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
709 // If the offsets are the same, merge the smaller node into the bigger node
710 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
714 // Ok, now we can merge the two nodes. Use a static helper that works with
715 // two node handles, since "this" may get merged away at intermediate steps.
716 DSNodeHandle CurNodeH(this, Offset);
717 DSNodeHandle NHCopy(NH);
718 DSNode::MergeNodes(CurNodeH, NHCopy);
721 //===----------------------------------------------------------------------===//
722 // DSCallSite Implementation
723 //===----------------------------------------------------------------------===//
725 // Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
726 Function &DSCallSite::getCaller() const {
727 return *Site.getInstruction()->getParent()->getParent();
731 //===----------------------------------------------------------------------===//
732 // DSGraph Implementation
733 //===----------------------------------------------------------------------===//
735 /// getFunctionNames - Return a space separated list of the name of the
736 /// functions in this graph (if any)
737 std::string DSGraph::getFunctionNames() const {
738 switch (getReturnNodes().size()) {
739 case 0: return "Globals graph";
740 case 1: return getReturnNodes().begin()->first->getName();
743 for (DSGraph::ReturnNodesTy::const_iterator I = getReturnNodes().begin();
744 I != getReturnNodes().end(); ++I)
745 Return += I->first->getName() + " ";
746 Return.erase(Return.end()-1, Return.end()); // Remove last space character
752 DSGraph::DSGraph(const DSGraph &G) : GlobalsGraph(0), TD(G.TD) {
753 PrintAuxCalls = false;
755 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
756 InlinedGlobals.clear(); // clear set of "up-to-date" globals
759 DSGraph::DSGraph(const DSGraph &G, NodeMapTy &NodeMap)
760 : GlobalsGraph(0), TD(G.TD) {
761 PrintAuxCalls = false;
762 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
763 InlinedGlobals.clear(); // clear set of "up-to-date" globals
766 DSGraph::~DSGraph() {
767 FunctionCalls.clear();
768 AuxFunctionCalls.clear();
769 InlinedGlobals.clear();
773 // Drop all intra-node references, so that assertions don't fail...
774 std::for_each(Nodes.begin(), Nodes.end(),
775 std::mem_fun(&DSNode::dropAllReferences));
777 // Delete all of the nodes themselves...
778 std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
781 // dump - Allow inspection of graph in a debugger.
782 void DSGraph::dump() const { print(std::cerr); }
785 /// remapLinks - Change all of the Links in the current node according to the
786 /// specified mapping.
788 void DSNode::remapLinks(DSGraph::NodeMapTy &OldNodeMap) {
789 for (unsigned i = 0, e = Links.size(); i != e; ++i) {
790 DSNodeHandle &H = OldNodeMap[Links[i].getNode()];
791 Links[i].setNode(H.getNode());
792 Links[i].setOffset(Links[i].getOffset()+H.getOffset());
797 /// cloneReachableNodes - Clone all reachable nodes from *Node into the
798 /// current graph. This is a recursive function. The map OldNodeMap is a
799 /// map from the original nodes to their clones.
801 void DSGraph::cloneReachableNodes(const DSNode* Node,
802 unsigned BitsToClear,
803 NodeMapTy& OldNodeMap,
804 NodeMapTy& CompletedNodeMap) {
805 if (CompletedNodeMap.find(Node) != CompletedNodeMap.end())
808 DSNodeHandle& NH = OldNodeMap[Node];
809 if (NH.getNode() != NULL)
812 // else Node has not yet been cloned: clone it and clear the specified bits
813 NH = new DSNode(*Node, this); // enters in OldNodeMap
814 NH.getNode()->maskNodeTypes(~BitsToClear);
816 // now recursively clone nodes pointed to by this node
817 for (unsigned i = 0, e = Node->getNumLinks(); i != e; ++i) {
818 const DSNodeHandle &Link = Node->getLink(i << DS::PointerShift);
819 if (const DSNode* nextNode = Link.getNode())
820 cloneReachableNodes(nextNode, BitsToClear, OldNodeMap, CompletedNodeMap);
824 void DSGraph::cloneReachableSubgraph(const DSGraph& G,
825 const hash_set<const DSNode*>& RootNodes,
826 NodeMapTy& OldNodeMap,
827 NodeMapTy& CompletedNodeMap,
828 unsigned CloneFlags) {
829 if (RootNodes.empty())
832 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
833 assert(&G != this && "Cannot clone graph into itself!");
834 assert((*RootNodes.begin())->getParentGraph() == &G &&
835 "Root nodes do not belong to this graph!");
837 // Remove alloca or mod/ref bits as specified...
838 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
839 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
840 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
841 BitsToClear |= DSNode::DEAD; // Clear dead flag...
843 // Clone all nodes reachable from each root node, using a recursive helper
844 for (hash_set<const DSNode*>::const_iterator I = RootNodes.begin(),
845 E = RootNodes.end(); I != E; ++I)
846 cloneReachableNodes(*I, BitsToClear, OldNodeMap, CompletedNodeMap);
848 // Merge the map entries in OldNodeMap and CompletedNodeMap to remap links
849 NodeMapTy MergedMap(OldNodeMap);
850 MergedMap.insert(CompletedNodeMap.begin(), CompletedNodeMap.end());
852 // Rewrite the links in the newly created nodes (the nodes in OldNodeMap)
853 // to point into the current graph. MergedMap gives the full mapping.
854 for (NodeMapTy::iterator I=OldNodeMap.begin(), E=OldNodeMap.end(); I!= E; ++I)
855 I->second.getNode()->remapLinks(MergedMap);
857 // Now merge cloned global nodes with their copies in the current graph
858 // Just look through OldNodeMap to find such nodes!
859 for (NodeMapTy::iterator I=OldNodeMap.begin(), E=OldNodeMap.end(); I!= E; ++I)
860 if (I->first->isGlobalNode()) {
861 DSNodeHandle &GClone = I->second;
862 assert(GClone.getNode() != NULL && "NULL node in OldNodeMap?");
863 const std::vector<GlobalValue*> &Globals = I->first->getGlobals();
864 for (unsigned gi = 0, ge = Globals.size(); gi != ge; ++gi) {
865 DSNodeHandle &GH = ScalarMap[Globals[gi]];
866 GH.mergeWith(GClone);
872 /// updateFromGlobalGraph - This function rematerializes global nodes and
873 /// nodes reachable from them from the globals graph into the current graph.
874 /// It invokes cloneReachableSubgraph, using the globals in the current graph
875 /// as the roots. It also uses the vector InlinedGlobals to avoid cloning and
876 /// merging globals that are already up-to-date in the current graph. In
877 /// practice, in the TD pass, this is likely to be a large fraction of the
878 /// live global nodes in each function (since most live nodes are likely to
879 /// have been brought up-to-date in at _some_ caller or callee).
881 void DSGraph::updateFromGlobalGraph() {
883 // Use a map to keep track of the mapping between nodes in the globals graph
884 // and this graph for up-to-date global nodes, which do not need to be cloned.
885 NodeMapTy CompletedMap;
887 // Put the live, non-up-to-date global nodes into a set and the up-to-date
888 // ones in the map above, mapping node in GlobalsGraph to the up-to-date node.
889 hash_set<const DSNode*> GlobalNodeSet;
890 for (ScalarMapTy::const_iterator I = getScalarMap().begin(),
891 E = getScalarMap().end(); I != E; ++I)
892 if (GlobalValue* GV = dyn_cast<GlobalValue>(I->first)) {
893 DSNode* GNode = I->second.getNode();
894 assert(GNode && "No node for live global in current Graph?");
895 if (const DSNode* GGNode = GlobalsGraph->ScalarMap[GV].getNode())
896 if (InlinedGlobals.count(GV) == 0) // GNode is not up-to-date
897 GlobalNodeSet.insert(GGNode);
898 else { // GNode is up-to-date
899 CompletedMap[GGNode] = I->second;
900 assert(GGNode->getNumLinks() == GNode->getNumLinks() &&
901 "Links dont match in a node that is supposed to be up-to-date?"
902 "\nremapLinks() will not work if the links don't match!");
906 // Clone the subgraph reachable from the vector of nodes in GlobalNodes
907 // and merge the cloned global nodes with the corresponding ones, if any.
908 NodeMapTy OldNodeMap;
909 cloneReachableSubgraph(*GlobalsGraph, GlobalNodeSet, OldNodeMap,CompletedMap);
911 // Merging global nodes leaves behind unused nodes: get rid of them now.
912 OldNodeMap.clear(); // remove references before dead node cleanup
913 CompletedMap.clear(); // remove references before dead node cleanup
914 removeTriviallyDeadNodes();
917 /// cloneInto - Clone the specified DSGraph into the current graph. The
918 /// translated ScalarMap for the old function is filled into the OldValMap
919 /// member, and the translated ReturnNodes map is returned into ReturnNodes.
921 /// The CloneFlags member controls various aspects of the cloning process.
923 void DSGraph::cloneInto(const DSGraph &G, ScalarMapTy &OldValMap,
924 ReturnNodesTy &OldReturnNodes, NodeMapTy &OldNodeMap,
925 unsigned CloneFlags) {
926 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
927 assert(&G != this && "Cannot clone graph into itself!");
929 unsigned FN = Nodes.size(); // First new node...
931 // Duplicate all of the nodes, populating the node map...
932 Nodes.reserve(FN+G.Nodes.size());
934 // Remove alloca or mod/ref bits as specified...
935 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
936 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
937 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
938 BitsToClear |= DSNode::DEAD; // Clear dead flag...
939 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
940 DSNode *Old = G.Nodes[i];
941 DSNode *New = new DSNode(*Old, this);
942 New->maskNodeTypes(~BitsToClear);
943 OldNodeMap[Old] = New;
947 Timer::addPeakMemoryMeasurement();
950 // Rewrite the links in the new nodes to point into the current graph now.
951 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
952 Nodes[i]->remapLinks(OldNodeMap);
954 // Copy the scalar map... merging all of the global nodes...
955 for (ScalarMapTy::const_iterator I = G.ScalarMap.begin(),
956 E = G.ScalarMap.end(); I != E; ++I) {
957 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
958 DSNodeHandle &H = OldValMap[I->first];
959 H.mergeWith(DSNodeHandle(MappedNode.getNode(),
960 I->second.getOffset()+MappedNode.getOffset()));
962 // If this is a global, add the global to this fn or merge if already exists
963 if (GlobalValue* GV = dyn_cast<GlobalValue>(I->first)) {
964 ScalarMap[GV].mergeWith(H);
965 InlinedGlobals.insert(GV);
969 if (!(CloneFlags & DontCloneCallNodes)) {
970 // Copy the function calls list...
971 unsigned FC = FunctionCalls.size(); // FirstCall
972 FunctionCalls.reserve(FC+G.FunctionCalls.size());
973 for (unsigned i = 0, ei = G.FunctionCalls.size(); i != ei; ++i)
974 FunctionCalls.push_back(DSCallSite(G.FunctionCalls[i], OldNodeMap));
977 if (!(CloneFlags & DontCloneAuxCallNodes)) {
978 // Copy the auxiliary function calls list...
979 unsigned FC = AuxFunctionCalls.size(); // FirstCall
980 AuxFunctionCalls.reserve(FC+G.AuxFunctionCalls.size());
981 for (unsigned i = 0, ei = G.AuxFunctionCalls.size(); i != ei; ++i)
982 AuxFunctionCalls.push_back(DSCallSite(G.AuxFunctionCalls[i], OldNodeMap));
985 // Map the return node pointers over...
986 for (ReturnNodesTy::const_iterator I = G.getReturnNodes().begin(),
987 E = G.getReturnNodes().end(); I != E; ++I) {
988 const DSNodeHandle &Ret = I->second;
989 DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
990 OldReturnNodes.insert(std::make_pair(I->first,
991 DSNodeHandle(MappedRet.getNode(),
992 MappedRet.getOffset()+Ret.getOffset())));
996 /// mergeInGraph - The method is used for merging graphs together. If the
997 /// argument graph is not *this, it makes a clone of the specified graph, then
998 /// merges the nodes specified in the call site with the formal arguments in the
1001 void DSGraph::mergeInGraph(const DSCallSite &CS, Function &F,
1002 const DSGraph &Graph, unsigned CloneFlags) {
1003 ScalarMapTy OldValMap, *ScalarMap;
1004 DSNodeHandle RetVal;
1006 // If this is not a recursive call, clone the graph into this graph...
1007 if (&Graph != this) {
1008 // Clone the callee's graph into the current graph, keeping
1009 // track of where scalars in the old graph _used_ to point,
1010 // and of the new nodes matching nodes of the old graph.
1011 NodeMapTy OldNodeMap;
1013 // The clone call may invalidate any of the vectors in the data
1014 // structure graph. Strip locals and don't copy the list of callers
1015 ReturnNodesTy OldRetNodes;
1016 cloneInto(Graph, OldValMap, OldRetNodes, OldNodeMap, CloneFlags);
1018 // We need to map the arguments for the function to the cloned nodes old
1019 // argument values. Do this now.
1020 RetVal = OldRetNodes[&F];
1021 ScalarMap = &OldValMap;
1023 RetVal = getReturnNodeFor(F);
1024 ScalarMap = &getScalarMap();
1027 // Merge the return value with the return value of the context...
1028 RetVal.mergeWith(CS.getRetVal());
1030 // Resolve all of the function arguments...
1031 Function::aiterator AI = F.abegin();
1033 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
1034 // Advance the argument iterator to the first pointer argument...
1035 while (AI != F.aend() && !isPointerType(AI->getType())) {
1039 std::cerr << "Bad call to Function: " << F.getName() << "\n";
1042 if (AI == F.aend()) break;
1044 // Add the link from the argument scalar to the provided value
1045 assert(ScalarMap->count(AI) && "Argument not in scalar map?");
1046 DSNodeHandle &NH = (*ScalarMap)[AI];
1047 assert(NH.getNode() && "Pointer argument without scalarmap entry?");
1048 NH.mergeWith(CS.getPtrArg(i));
1052 /// getCallSiteForArguments - Get the arguments and return value bindings for
1053 /// the specified function in the current graph.
1055 DSCallSite DSGraph::getCallSiteForArguments(Function &F) const {
1056 std::vector<DSNodeHandle> Args;
1058 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
1059 if (isPointerType(I->getType()))
1060 Args.push_back(getScalarMap().find(I)->second);
1062 return DSCallSite(CallSite(), getReturnNodeFor(F), &F, Args);
1067 // markIncompleteNodes - Mark the specified node as having contents that are not
1068 // known with the current analysis we have performed. Because a node makes all
1069 // of the nodes it can reach incomplete if the node itself is incomplete, we
1070 // must recursively traverse the data structure graph, marking all reachable
1071 // nodes as incomplete.
1073 static void markIncompleteNode(DSNode *N) {
1074 // Stop recursion if no node, or if node already marked...
1075 if (N == 0 || N->isIncomplete()) return;
1077 // Actually mark the node
1078 N->setIncompleteMarker();
1080 // Recursively process children...
1081 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
1082 if (DSNode *DSN = N->getLink(i).getNode())
1083 markIncompleteNode(DSN);
1086 static void markIncomplete(DSCallSite &Call) {
1087 // Then the return value is certainly incomplete!
1088 markIncompleteNode(Call.getRetVal().getNode());
1090 // All objects pointed to by function arguments are incomplete!
1091 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
1092 markIncompleteNode(Call.getPtrArg(i).getNode());
1095 // markIncompleteNodes - Traverse the graph, identifying nodes that may be
1096 // modified by other functions that have not been resolved yet. This marks
1097 // nodes that are reachable through three sources of "unknownness":
1099 // Global Variables, Function Calls, and Incoming Arguments
1101 // For any node that may have unknown components (because something outside the
1102 // scope of current analysis may have modified it), the 'Incomplete' flag is
1103 // added to the NodeType.
1105 void DSGraph::markIncompleteNodes(unsigned Flags) {
1106 // Mark any incoming arguments as incomplete...
1107 if (Flags & DSGraph::MarkFormalArgs)
1108 for (ReturnNodesTy::iterator FI = ReturnNodes.begin(), E =ReturnNodes.end();
1110 Function &F = *FI->first;
1111 if (F.getName() != "main")
1112 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
1113 if (isPointerType(I->getType()) &&
1114 ScalarMap.find(I) != ScalarMap.end())
1115 markIncompleteNode(ScalarMap[I].getNode());
1118 // Mark stuff passed into functions calls as being incomplete...
1119 if (!shouldPrintAuxCalls())
1120 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1121 markIncomplete(FunctionCalls[i]);
1123 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1124 markIncomplete(AuxFunctionCalls[i]);
1127 // Mark all global nodes as incomplete...
1128 if ((Flags & DSGraph::IgnoreGlobals) == 0)
1129 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
1130 if (Nodes[i]->isGlobalNode() && Nodes[i]->getNumLinks())
1131 markIncompleteNode(Nodes[i]);
1134 static inline void killIfUselessEdge(DSNodeHandle &Edge) {
1135 if (DSNode *N = Edge.getNode()) // Is there an edge?
1136 if (N->getNumReferrers() == 1) // Does it point to a lonely node?
1137 // No interesting info?
1138 if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
1139 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
1140 Edge.setNode(0); // Kill the edge!
1143 static inline bool nodeContainsExternalFunction(const DSNode *N) {
1144 const std::vector<GlobalValue*> &Globals = N->getGlobals();
1145 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
1146 if (Globals[i]->isExternal())
1151 static void removeIdenticalCalls(std::vector<DSCallSite> &Calls) {
1153 // Remove trivially identical function calls
1154 unsigned NumFns = Calls.size();
1155 std::sort(Calls.begin(), Calls.end()); // Sort by callee as primary key!
1157 // Scan the call list cleaning it up as necessary...
1158 DSNode *LastCalleeNode = 0;
1159 Function *LastCalleeFunc = 0;
1160 unsigned NumDuplicateCalls = 0;
1161 bool LastCalleeContainsExternalFunction = false;
1162 for (unsigned i = 0; i != Calls.size(); ++i) {
1163 DSCallSite &CS = Calls[i];
1165 // If the Callee is a useless edge, this must be an unreachable call site,
1167 if (CS.isIndirectCall() && CS.getCalleeNode()->getNumReferrers() == 1 &&
1168 CS.getCalleeNode()->getNodeFlags() == 0) { // No useful info?
1169 std::cerr << "WARNING: Useless call site found??\n";
1170 CS.swap(Calls.back());
1174 // If the return value or any arguments point to a void node with no
1175 // information at all in it, and the call node is the only node to point
1176 // to it, remove the edge to the node (killing the node).
1178 killIfUselessEdge(CS.getRetVal());
1179 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
1180 killIfUselessEdge(CS.getPtrArg(a));
1182 // If this call site calls the same function as the last call site, and if
1183 // the function pointer contains an external function, this node will
1184 // never be resolved. Merge the arguments of the call node because no
1185 // information will be lost.
1187 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
1188 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
1189 ++NumDuplicateCalls;
1190 if (NumDuplicateCalls == 1) {
1192 LastCalleeContainsExternalFunction =
1193 nodeContainsExternalFunction(LastCalleeNode);
1195 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
1199 if (LastCalleeContainsExternalFunction ||
1200 // This should be more than enough context sensitivity!
1201 // FIXME: Evaluate how many times this is tripped!
1202 NumDuplicateCalls > 20) {
1203 DSCallSite &OCS = Calls[i-1];
1206 // The node will now be eliminated as a duplicate!
1207 if (CS.getNumPtrArgs() < OCS.getNumPtrArgs())
1209 else if (CS.getNumPtrArgs() > OCS.getNumPtrArgs())
1214 if (CS.isDirectCall()) {
1215 LastCalleeFunc = CS.getCalleeFunc();
1218 LastCalleeNode = CS.getCalleeNode();
1221 NumDuplicateCalls = 0;
1226 Calls.erase(std::unique(Calls.begin(), Calls.end()),
1229 // Track the number of call nodes merged away...
1230 NumCallNodesMerged += NumFns-Calls.size();
1232 DEBUG(if (NumFns != Calls.size())
1233 std::cerr << "Merged " << (NumFns-Calls.size()) << " call nodes.\n";);
1237 // removeTriviallyDeadNodes - After the graph has been constructed, this method
1238 // removes all unreachable nodes that are created because they got merged with
1239 // other nodes in the graph. These nodes will all be trivially unreachable, so
1240 // we don't have to perform any non-trivial analysis here.
1242 void DSGraph::removeTriviallyDeadNodes() {
1243 removeIdenticalCalls(FunctionCalls);
1244 removeIdenticalCalls(AuxFunctionCalls);
1246 // Loop over all of the nodes in the graph, calling getNode on each field.
1247 // This will cause all nodes to update their forwarding edges, causing
1248 // forwarded nodes to be delete-able.
1249 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1250 DSNode *N = Nodes[i];
1251 for (unsigned l = 0, e = N->getNumLinks(); l != e; ++l)
1252 N->getLink(l*N->getPointerSize()).getNode();
1255 // Likewise, forward any edges from the scalar nodes...
1256 for (ScalarMapTy::iterator I = ScalarMap.begin(), E = ScalarMap.end();
1258 I->second.getNode();
1260 bool isGlobalsGraph = !GlobalsGraph;
1262 for (unsigned i = 0; i != Nodes.size(); ++i) {
1263 DSNode *Node = Nodes[i];
1265 // Do not remove *any* global nodes in the globals graph.
1266 // This is a special case because such nodes may not have I, M, R flags set.
1267 if (Node->isGlobalNode() && isGlobalsGraph)
1270 if (Node->isComplete() && !Node->isModified() && !Node->isRead()) {
1271 // This is a useless node if it has no mod/ref info (checked above),
1272 // outgoing edges (which it cannot, as it is not modified in this
1273 // context), and it has no incoming edges. If it is a global node it may
1274 // have all of these properties and still have incoming edges, due to the
1275 // scalar map, so we check those now.
1277 if (Node->getNumReferrers() == Node->getGlobals().size()) {
1278 const std::vector<GlobalValue*> &Globals = Node->getGlobals();
1280 // Loop through and make sure all of the globals are referring directly
1282 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1283 DSNode *N = ScalarMap.find(Globals[j])->second.getNode();
1284 assert(N == Node && "ScalarMap doesn't match globals list!");
1287 // Make sure NumReferrers still agrees, if so, the node is truly dead.
1288 if (Node->getNumReferrers() == Globals.size()) {
1289 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1290 ScalarMap.erase(Globals[j]);
1291 Node->makeNodeDead();
1295 #ifdef SANER_CODE_FOR_CHECKING_IF_ALL_REFERRERS_ARE_FROM_SCALARMAP
1297 // *** It seems to me that we should be able to simply check if
1298 // *** there are fewer or equal #referrers as #globals and make
1299 // *** sure that all those referrers are in the scalar map?
1301 if (Node->getNumReferrers() <= Node->getGlobals().size()) {
1302 const std::vector<GlobalValue*> &Globals = Node->getGlobals();
1305 // Loop through and make sure all of the globals are referring directly
1307 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1308 DSNode *N = ScalarMap.find(Globals[j])->second.getNode();
1309 assert(N == Node && "ScalarMap doesn't match globals list!");
1313 // Make sure NumReferrers still agrees. The node is truly dead.
1314 assert(Node->getNumReferrers() == Globals.size());
1315 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1316 ScalarMap.erase(Globals[j]);
1317 Node->makeNodeDead();
1322 if (Node->getNodeFlags() == 0 && Node->hasNoReferrers()) {
1323 // This node is dead!
1324 delete Node; // Free memory...
1325 Nodes[i--] = Nodes.back();
1326 Nodes.pop_back(); // Remove from node list...
1332 /// markReachableNodes - This method recursively traverses the specified
1333 /// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
1334 /// to the set, which allows it to only traverse visited nodes once.
1336 void DSNode::markReachableNodes(hash_set<DSNode*> &ReachableNodes) {
1337 if (this == 0) return;
1338 assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
1339 if (ReachableNodes.count(this)) return; // Already marked reachable
1340 ReachableNodes.insert(this); // Is reachable now
1342 for (unsigned i = 0, e = getSize(); i < e; i += DS::PointerSize)
1343 getLink(i).getNode()->markReachableNodes(ReachableNodes);
1346 void DSCallSite::markReachableNodes(hash_set<DSNode*> &Nodes) {
1347 getRetVal().getNode()->markReachableNodes(Nodes);
1348 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
1350 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
1351 getPtrArg(i).getNode()->markReachableNodes(Nodes);
1354 // CanReachAliveNodes - Simple graph walker that recursively traverses the graph
1355 // looking for a node that is marked alive. If an alive node is found, return
1356 // true, otherwise return false. If an alive node is reachable, this node is
1357 // marked as alive...
1359 static bool CanReachAliveNodes(DSNode *N, hash_set<DSNode*> &Alive,
1360 hash_set<DSNode*> &Visited,
1361 bool IgnoreGlobals) {
1362 if (N == 0) return false;
1363 assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
1365 // If this is a global node, it will end up in the globals graph anyway, so we
1366 // don't need to worry about it.
1367 if (IgnoreGlobals && N->isGlobalNode()) return false;
1369 // If we know that this node is alive, return so!
1370 if (Alive.count(N)) return true;
1372 // Otherwise, we don't think the node is alive yet, check for infinite
1374 if (Visited.count(N)) return false; // Found a cycle
1375 Visited.insert(N); // No recursion, insert into Visited...
1377 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
1378 if (CanReachAliveNodes(N->getLink(i).getNode(), Alive, Visited,
1380 N->markReachableNodes(Alive);
1386 // CallSiteUsesAliveArgs - Return true if the specified call site can reach any
1389 static bool CallSiteUsesAliveArgs(DSCallSite &CS, hash_set<DSNode*> &Alive,
1390 hash_set<DSNode*> &Visited,
1391 bool IgnoreGlobals) {
1392 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited,
1395 if (CS.isIndirectCall() &&
1396 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited, IgnoreGlobals))
1398 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
1399 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited,
1405 // removeDeadNodes - Use a more powerful reachability analysis to eliminate
1406 // subgraphs that are unreachable. This often occurs because the data
1407 // structure doesn't "escape" into it's caller, and thus should be eliminated
1408 // from the caller's graph entirely. This is only appropriate to use when
1411 void DSGraph::removeDeadNodes(unsigned Flags) {
1412 DEBUG(AssertGraphOK(); if (GlobalsGraph) GlobalsGraph->AssertGraphOK());
1414 // Reduce the amount of work we have to do... remove dummy nodes left over by
1416 removeTriviallyDeadNodes();
1418 // FIXME: Merge non-trivially identical call nodes...
1420 // Alive - a set that holds all nodes found to be reachable/alive.
1421 hash_set<DSNode*> Alive;
1422 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
1424 // Mark all nodes reachable by (non-global) scalar nodes as alive...
1425 for (ScalarMapTy::iterator I = ScalarMap.begin(), E = ScalarMap.end(); I !=E;)
1426 if (isa<GlobalValue>(I->first)) { // Keep track of global nodes
1427 assert(I->second.getNode() && "Null global node?");
1428 assert(I->second.getNode()->isGlobalNode() && "Should be a global node!");
1429 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
1432 // Check to see if this is a worthless node generated for non-pointer
1433 // values, such as integers. Consider an addition of long types: A+B.
1434 // Assuming we can track all uses of the value in this context, and it is
1435 // NOT used as a pointer, we can delete the node. We will be able to
1436 // detect this situation if the node pointed to ONLY has Unknown bit set
1437 // in the node. In this case, the node is not incomplete, does not point
1438 // to any other nodes (no mod/ref bits set), and is therefore
1439 // uninteresting for data structure analysis. If we run across one of
1440 // these, prune the scalar pointing to it.
1442 DSNode *N = I->second.getNode();
1443 if (N->getNodeFlags() == DSNode::UnknownNode && !isa<Argument>(I->first)){
1444 ScalarMap.erase(I++);
1446 I->second.getNode()->markReachableNodes(Alive);
1451 // The return value is alive as well...
1452 for (ReturnNodesTy::iterator I = ReturnNodes.begin(), E = ReturnNodes.end();
1454 I->second.getNode()->markReachableNodes(Alive);
1456 // Mark any nodes reachable by primary calls as alive...
1457 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1458 FunctionCalls[i].markReachableNodes(Alive);
1460 // Copy and merge all information about globals to the GlobalsGraph
1461 // if this is not a final pass (where unreachable globals are removed)
1462 NodeMapTy GlobalNodeMap;
1463 hash_set<const DSNode*> GlobalNodeSet;
1465 for (std::vector<std::pair<Value*, DSNode*> >::const_iterator
1466 I = GlobalNodes.begin(), E = GlobalNodes.end(); I != E; ++I)
1467 GlobalNodeSet.insert(I->second); // put global nodes into a set
1469 // Now find globals and aux call nodes that are already live or reach a live
1470 // value (which makes them live in turn), and continue till no more are found.
1473 hash_set<DSNode*> Visited;
1474 std::vector<unsigned char> AuxFCallsAlive(AuxFunctionCalls.size());
1477 // If any global node points to a non-global that is "alive", the global is
1478 // "alive" as well... Remove it from the GlobalNodes list so we only have
1479 // unreachable globals in the list.
1482 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
1483 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
1484 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited,
1485 Flags & DSGraph::RemoveUnreachableGlobals)) {
1486 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to...
1487 GlobalNodes.pop_back(); // erase efficiently
1491 // Mark only unresolvable call nodes for moving to the GlobalsGraph since
1492 // call nodes that get resolved will be difficult to remove from that graph.
1493 // The final unresolved call nodes must be handled specially at the end of
1494 // the BU pass (i.e., in main or other roots of the call graph).
1495 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1496 if (!AuxFCallsAlive[i] &&
1497 (AuxFunctionCalls[i].isIndirectCall()
1498 || CallSiteUsesAliveArgs(AuxFunctionCalls[i], Alive, Visited,
1499 Flags & DSGraph::RemoveUnreachableGlobals))) {
1500 AuxFunctionCalls[i].markReachableNodes(Alive);
1501 AuxFCallsAlive[i] = true;
1506 // Move dead aux function calls to the end of the list
1507 unsigned CurIdx = 0;
1508 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1509 if (AuxFCallsAlive[i])
1510 AuxFunctionCalls[CurIdx++].swap(AuxFunctionCalls[i]);
1512 // Copy and merge all global nodes and dead aux call nodes into the
1513 // GlobalsGraph, and all nodes reachable from those nodes
1515 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
1517 // First, add the dead aux call nodes to the set of root nodes for cloning
1518 // -- return value at this call site, if any
1519 // -- actual arguments passed at this call site
1520 // -- callee node at this call site, if this is an indirect call
1521 for (unsigned i = CurIdx, e = AuxFunctionCalls.size(); i != e; ++i) {
1522 if (const DSNode* RetNode = AuxFunctionCalls[i].getRetVal().getNode())
1523 GlobalNodeSet.insert(RetNode);
1524 for (unsigned j=0, N=AuxFunctionCalls[i].getNumPtrArgs(); j < N; ++j)
1525 if (const DSNode* ArgTarget=AuxFunctionCalls[i].getPtrArg(j).getNode())
1526 GlobalNodeSet.insert(ArgTarget);
1527 if (AuxFunctionCalls[i].isIndirectCall())
1528 GlobalNodeSet.insert(AuxFunctionCalls[i].getCalleeNode());
1531 // There are no "pre-completed" nodes so use any empty map for those.
1532 // Strip all alloca bits since the current function is only for the BU pass.
1533 // Strip all incomplete bits since they are short-lived properties and they
1534 // will be correctly computed when rematerializing nodes into the functions.
1536 NodeMapTy CompletedMap;
1537 GlobalsGraph->cloneReachableSubgraph(*this, GlobalNodeSet,
1538 GlobalNodeMap, CompletedMap,
1539 (DSGraph::StripAllocaBit |
1540 DSGraph::StripIncompleteBit));
1543 // Remove all dead aux function calls...
1544 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
1545 assert(GlobalsGraph && "No globals graph available??");
1547 // Copy the unreachable call nodes to the globals graph, updating
1548 // their target pointers using the GlobalNodeMap
1549 for (unsigned i = CurIdx, e = AuxFunctionCalls.size(); i != e; ++i)
1550 GlobalsGraph->AuxFunctionCalls.push_back(DSCallSite(AuxFunctionCalls[i],
1553 // Crop all the useless ones out...
1554 AuxFunctionCalls.erase(AuxFunctionCalls.begin()+CurIdx,
1555 AuxFunctionCalls.end());
1557 // We are finally done with the GlobalNodeMap so we can clear it and
1558 // then get rid of unused nodes in the GlobalsGraph produced by merging.
1559 GlobalNodeMap.clear();
1560 GlobalsGraph->removeTriviallyDeadNodes();
1562 // At this point, any nodes which are visited, but not alive, are nodes
1563 // which can be removed. Loop over all nodes, eliminating completely
1564 // unreachable nodes.
1566 std::vector<DSNode*> DeadNodes;
1567 DeadNodes.reserve(Nodes.size());
1568 for (unsigned i = 0; i != Nodes.size(); ++i)
1569 if (!Alive.count(Nodes[i])) {
1570 DSNode *N = Nodes[i];
1571 Nodes[i--] = Nodes.back(); // move node to end of vector
1572 Nodes.pop_back(); // Erase node from alive list.
1573 DeadNodes.push_back(N);
1574 N->dropAllReferences();
1576 assert(Nodes[i]->getForwardNode() == 0 && "Alive forwarded node?");
1579 // Remove all unreachable globals from the ScalarMap.
1580 // If flag RemoveUnreachableGlobals is set, GlobalNodes has only dead nodes.
1581 // In either case, the dead nodes will not be in the set Alive.
1582 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i) {
1583 assert(((Flags & DSGraph::RemoveUnreachableGlobals) ||
1584 !Alive.count(GlobalNodes[i].second)) && "huh? non-dead global");
1585 if (!Alive.count(GlobalNodes[i].second))
1586 ScalarMap.erase(GlobalNodes[i].first);
1589 // Delete all dead nodes now since their referrer counts are zero.
1590 for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
1591 delete DeadNodes[i];
1593 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
1596 void DSGraph::AssertGraphOK() const {
1597 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
1598 Nodes[i]->assertOK();
1600 for (ScalarMapTy::const_iterator I = ScalarMap.begin(),
1601 E = ScalarMap.end(); I != E; ++I) {
1602 assert(I->second.getNode() && "Null node in scalarmap!");
1603 AssertNodeInGraph(I->second.getNode());
1604 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
1605 assert(I->second.getNode()->isGlobalNode() &&
1606 "Global points to node, but node isn't global?");
1607 AssertNodeContainsGlobal(I->second.getNode(), GV);
1610 AssertCallNodesInGraph();
1611 AssertAuxCallNodesInGraph();
1614 /// mergeInGlobalsGraph - This method is useful for clients to incorporate the
1615 /// globals graph into the DS, BU or TD graph for a function. This code retains
1616 /// all globals, i.e., does not delete unreachable globals after they are
1619 void DSGraph::mergeInGlobalsGraph() {
1620 NodeMapTy GlobalNodeMap;
1621 ScalarMapTy OldValMap;
1622 ReturnNodesTy OldRetNodes;
1623 cloneInto(*GlobalsGraph, OldValMap, OldRetNodes, GlobalNodeMap,
1624 DSGraph::KeepAllocaBit | DSGraph::DontCloneCallNodes |
1625 DSGraph::DontCloneAuxCallNodes);
1627 // Now merge existing global nodes in the GlobalsGraph with their copies
1628 for (ScalarMapTy::iterator I = ScalarMap.begin(), E = ScalarMap.end();
1630 if (isa<GlobalValue>(I->first)) { // Found a global node
1631 DSNodeHandle &GH = I->second;
1632 DSNodeHandle &GGNodeH = GlobalsGraph->getScalarMap()[I->first];
1633 GH.mergeWith(GlobalNodeMap[GGNodeH.getNode()]);
1636 // Merging leaves behind unused nodes: get rid of them now.
1637 GlobalNodeMap.clear();
1639 OldRetNodes.clear();
1640 removeTriviallyDeadNodes();
1644 /// computeNodeMapping - Given roots in two different DSGraphs, traverse the
1645 /// nodes reachable from the two graphs, computing the mapping of nodes from
1646 /// the first to the second graph.
1648 void DSGraph::computeNodeMapping(const DSNodeHandle &NH1,
1649 const DSNodeHandle &NH2, NodeMapTy &NodeMap) {
1650 DSNode *N1 = NH1.getNode(), *N2 = NH2.getNode();
1651 if (N1 == 0 || N2 == 0) return;
1653 DSNodeHandle &Entry = NodeMap[N1];
1654 if (Entry.getNode()) {
1655 // Termination of recursion!
1656 assert(Entry.getNode() == N2 &&
1657 Entry.getOffset() == (NH2.getOffset()-NH1.getOffset()) &&
1658 "Inconsistent mapping detected!");
1663 Entry.setOffset(NH2.getOffset()-NH1.getOffset());
1665 // Loop over all of the fields that N1 and N2 have in common, recursively
1666 // mapping the edges together now.
1667 int N2Idx = NH2.getOffset()-NH1.getOffset();
1668 unsigned N2Size = N2->getSize();
1669 for (unsigned i = 0, e = N1->getSize(); i < e; i += DS::PointerSize)
1670 if (unsigned(N2Idx)+i < N2Size)
1671 computeNodeMapping(N1->getLink(i), N2->getLink(N2Idx+i), NodeMap);
1674 } // End llvm namespace