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"
27 Statistic<> NumFolds ("dsnode", "Number of nodes completely folded");
28 Statistic<> NumCallNodesMerged("dsnode", "Number of call nodes merged");
33 DSNode *DSNodeHandle::HandleForwarding() const {
34 assert(!N->ForwardNH.isNull() && "Can only be invoked if forwarding!");
36 // Handle node forwarding here!
37 DSNode *Next = N->ForwardNH.getNode(); // Cause recursive shrinkage
38 Offset += N->ForwardNH.getOffset();
40 if (--N->NumReferrers == 0) {
41 // Removing the last referrer to the node, sever the forwarding link
47 if (N->Size <= Offset) {
48 assert(N->Size <= 1 && "Forwarded to shrunk but not collapsed node?");
54 //===----------------------------------------------------------------------===//
55 // DSNode Implementation
56 //===----------------------------------------------------------------------===//
58 DSNode::DSNode(const Type *T, DSGraph *G)
59 : NumReferrers(0), Size(0), ParentGraph(G), Ty(Type::VoidTy), NodeType(0) {
60 // Add the type entry if it is specified...
61 if (T) mergeTypeInfo(T, 0);
62 G->getNodes().push_back(this);
65 // DSNode copy constructor... do not copy over the referrers list!
66 DSNode::DSNode(const DSNode &N, DSGraph *G)
67 : NumReferrers(0), Size(N.Size), ParentGraph(G),
68 Ty(N.Ty), Links(N.Links), Globals(N.Globals), NodeType(N.NodeType) {
69 G->getNodes().push_back(this);
72 /// getTargetData - Get the target data object used to construct this node.
74 const TargetData &DSNode::getTargetData() const {
75 return ParentGraph->getTargetData();
78 void DSNode::assertOK() const {
79 assert((Ty != Type::VoidTy ||
80 Ty == Type::VoidTy && (Size == 0 ||
81 (NodeType & DSNode::Array))) &&
84 assert(ParentGraph && "Node has no parent?");
85 const DSGraph::ScalarMapTy &SM = ParentGraph->getScalarMap();
86 for (unsigned i = 0, e = Globals.size(); i != e; ++i) {
87 assert(SM.find(Globals[i]) != SM.end());
88 assert(SM.find(Globals[i])->second.getNode() == this);
92 /// forwardNode - Mark this node as being obsolete, and all references to it
93 /// should be forwarded to the specified node and offset.
95 void DSNode::forwardNode(DSNode *To, unsigned Offset) {
96 assert(this != To && "Cannot forward a node to itself!");
97 assert(ForwardNH.isNull() && "Already forwarding from this node!");
98 if (To->Size <= 1) Offset = 0;
99 assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
100 "Forwarded offset is wrong!");
101 ForwardNH.setNode(To);
102 ForwardNH.setOffset(Offset);
108 // addGlobal - Add an entry for a global value to the Globals list. This also
109 // marks the node with the 'G' flag if it does not already have it.
111 void DSNode::addGlobal(GlobalValue *GV) {
112 // Keep the list sorted.
113 std::vector<GlobalValue*>::iterator I =
114 std::lower_bound(Globals.begin(), Globals.end(), GV);
116 if (I == Globals.end() || *I != GV) {
117 //assert(GV->getType()->getElementType() == Ty);
118 Globals.insert(I, GV);
119 NodeType |= GlobalNode;
123 /// foldNodeCompletely - If we determine that this node has some funny
124 /// behavior happening to it that we cannot represent, we fold it down to a
125 /// single, completely pessimistic, node. This node is represented as a
126 /// single byte with a single TypeEntry of "void".
128 void DSNode::foldNodeCompletely() {
129 if (isNodeCompletelyFolded()) return; // If this node is already folded...
133 // Create the node we are going to forward to...
134 DSNode *DestNode = new DSNode(0, ParentGraph);
135 DestNode->NodeType = NodeType|DSNode::Array;
136 DestNode->Ty = Type::VoidTy;
138 DestNode->Globals.swap(Globals);
140 // Start forwarding to the destination node...
141 forwardNode(DestNode, 0);
144 DestNode->Links.push_back(Links[0]);
145 DSNodeHandle NH(DestNode);
147 // If we have links, merge all of our outgoing links together...
148 for (unsigned i = Links.size()-1; i != 0; --i)
149 NH.getNode()->Links[0].mergeWith(Links[i]);
152 DestNode->Links.resize(1);
156 /// isNodeCompletelyFolded - Return true if this node has been completely
157 /// folded down to something that can never be expanded, effectively losing
158 /// all of the field sensitivity that may be present in the node.
160 bool DSNode::isNodeCompletelyFolded() const {
161 return getSize() == 1 && Ty == Type::VoidTy && isArray();
166 /// TypeElementWalker Class - Used for implementation of physical subtyping...
168 class TypeElementWalker {
173 StackState(const Type *T, unsigned Off = 0)
174 : Ty(T), Offset(Off), Idx(0) {}
177 std::vector<StackState> Stack;
178 const TargetData &TD;
180 TypeElementWalker(const Type *T, const TargetData &td) : TD(td) {
185 bool isDone() const { return Stack.empty(); }
186 const Type *getCurrentType() const { return Stack.back().Ty; }
187 unsigned getCurrentOffset() const { return Stack.back().Offset; }
189 void StepToNextType() {
190 PopStackAndAdvance();
195 /// PopStackAndAdvance - Pop the current element off of the stack and
196 /// advance the underlying element to the next contained member.
197 void PopStackAndAdvance() {
198 assert(!Stack.empty() && "Cannot pop an empty stack!");
200 while (!Stack.empty()) {
201 StackState &SS = Stack.back();
202 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
204 if (SS.Idx != ST->getElementTypes().size()) {
205 const StructLayout *SL = TD.getStructLayout(ST);
206 SS.Offset += SL->MemberOffsets[SS.Idx]-SL->MemberOffsets[SS.Idx-1];
209 Stack.pop_back(); // At the end of the structure
211 const ArrayType *AT = cast<ArrayType>(SS.Ty);
213 if (SS.Idx != AT->getNumElements()) {
214 SS.Offset += TD.getTypeSize(AT->getElementType());
217 Stack.pop_back(); // At the end of the array
222 /// StepToLeaf - Used by physical subtyping to move to the first leaf node
223 /// on the type stack.
225 if (Stack.empty()) return;
226 while (!Stack.empty() && !Stack.back().Ty->isFirstClassType()) {
227 StackState &SS = Stack.back();
228 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
229 if (ST->getElementTypes().empty()) {
231 PopStackAndAdvance();
233 // Step into the structure...
234 assert(SS.Idx < ST->getElementTypes().size());
235 const StructLayout *SL = TD.getStructLayout(ST);
236 Stack.push_back(StackState(ST->getElementTypes()[SS.Idx],
237 SS.Offset+SL->MemberOffsets[SS.Idx]));
240 const ArrayType *AT = cast<ArrayType>(SS.Ty);
241 if (AT->getNumElements() == 0) {
243 PopStackAndAdvance();
245 // Step into the array...
246 assert(SS.Idx < AT->getNumElements());
247 Stack.push_back(StackState(AT->getElementType(),
249 TD.getTypeSize(AT->getElementType())));
257 /// ElementTypesAreCompatible - Check to see if the specified types are
258 /// "physically" compatible. If so, return true, else return false. We only
259 /// have to check the fields in T1: T2 may be larger than T1. If AllowLargerT1
260 /// is true, then we also allow a larger T1.
262 static bool ElementTypesAreCompatible(const Type *T1, const Type *T2,
263 bool AllowLargerT1, const TargetData &TD){
264 TypeElementWalker T1W(T1, TD), T2W(T2, TD);
266 while (!T1W.isDone() && !T2W.isDone()) {
267 if (T1W.getCurrentOffset() != T2W.getCurrentOffset())
270 const Type *T1 = T1W.getCurrentType();
271 const Type *T2 = T2W.getCurrentType();
272 if (T1 != T2 && !T1->isLosslesslyConvertibleTo(T2))
275 T1W.StepToNextType();
276 T2W.StepToNextType();
279 return AllowLargerT1 || T1W.isDone();
283 /// mergeTypeInfo - This method merges the specified type into the current node
284 /// at the specified offset. This may update the current node's type record if
285 /// this gives more information to the node, it may do nothing to the node if
286 /// this information is already known, or it may merge the node completely (and
287 /// return true) if the information is incompatible with what is already known.
289 /// This method returns true if the node is completely folded, otherwise false.
291 bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset,
292 bool FoldIfIncompatible) {
293 const TargetData &TD = getTargetData();
294 // Check to make sure the Size member is up-to-date. Size can be one of the
296 // Size = 0, Ty = Void: Nothing is known about this node.
297 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
298 // Size = 1, Ty = Void, Array = 1: The node is collapsed
299 // Otherwise, sizeof(Ty) = Size
301 assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
302 (Size == 0 && !Ty->isSized() && !isArray()) ||
303 (Size == 1 && Ty == Type::VoidTy && isArray()) ||
304 (Size == 0 && !Ty->isSized() && !isArray()) ||
305 (TD.getTypeSize(Ty) == Size)) &&
306 "Size member of DSNode doesn't match the type structure!");
307 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
309 if (Offset == 0 && NewTy == Ty)
310 return false; // This should be a common case, handle it efficiently
312 // Return true immediately if the node is completely folded.
313 if (isNodeCompletelyFolded()) return true;
315 // If this is an array type, eliminate the outside arrays because they won't
316 // be used anyway. This greatly reduces the size of large static arrays used
317 // as global variables, for example.
319 bool WillBeArray = false;
320 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
321 // FIXME: we might want to keep small arrays, but must be careful about
322 // things like: [2 x [10000 x int*]]
323 NewTy = AT->getElementType();
327 // Figure out how big the new type we're merging in is...
328 unsigned NewTySize = NewTy->isSized() ? TD.getTypeSize(NewTy) : 0;
330 // Otherwise check to see if we can fold this type into the current node. If
331 // we can't, we fold the node completely, if we can, we potentially update our
334 if (Ty == Type::VoidTy) {
335 // If this is the first type that this node has seen, just accept it without
337 assert(Offset == 0 && !isArray() &&
338 "Cannot have an offset into a void node!");
341 if (WillBeArray) NodeType |= Array;
344 // Calculate the number of outgoing links from this node.
345 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
349 // Handle node expansion case here...
350 if (Offset+NewTySize > Size) {
351 // It is illegal to grow this node if we have treated it as an array of
354 if (FoldIfIncompatible) foldNodeCompletely();
358 if (Offset) { // We could handle this case, but we don't for now...
359 std::cerr << "UNIMP: Trying to merge a growth type into "
360 << "offset != 0: Collapsing!\n";
361 if (FoldIfIncompatible) foldNodeCompletely();
365 // Okay, the situation is nice and simple, we are trying to merge a type in
366 // at offset 0 that is bigger than our current type. Implement this by
367 // switching to the new type and then merge in the smaller one, which should
368 // hit the other code path here. If the other code path decides it's not
369 // ok, it will collapse the node as appropriate.
371 const Type *OldTy = Ty;
374 if (WillBeArray) NodeType |= Array;
377 // Must grow links to be the appropriate size...
378 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
380 // Merge in the old type now... which is guaranteed to be smaller than the
382 return mergeTypeInfo(OldTy, 0);
385 assert(Offset <= Size &&
386 "Cannot merge something into a part of our type that doesn't exist!");
388 // Find the section of Ty that NewTy overlaps with... first we find the
389 // type that starts at offset Offset.
392 const Type *SubType = Ty;
394 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
396 switch (SubType->getPrimitiveID()) {
397 case Type::StructTyID: {
398 const StructType *STy = cast<StructType>(SubType);
399 const StructLayout &SL = *TD.getStructLayout(STy);
401 unsigned i = 0, e = SL.MemberOffsets.size();
402 for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
405 // The offset we are looking for must be in the i'th element...
406 SubType = STy->getElementTypes()[i];
407 O += SL.MemberOffsets[i];
410 case Type::ArrayTyID: {
411 SubType = cast<ArrayType>(SubType)->getElementType();
412 unsigned ElSize = TD.getTypeSize(SubType);
413 unsigned Remainder = (Offset-O) % ElSize;
414 O = Offset-Remainder;
418 if (FoldIfIncompatible) foldNodeCompletely();
423 assert(O == Offset && "Could not achieve the correct offset!");
425 // If we found our type exactly, early exit
426 if (SubType == NewTy) return false;
428 unsigned SubTypeSize = SubType->isSized() ? TD.getTypeSize(SubType) : 0;
430 // Ok, we are getting desperate now. Check for physical subtyping, where we
431 // just require each element in the node to be compatible.
432 if (NewTySize <= SubTypeSize && NewTySize && NewTySize < 256 &&
433 SubTypeSize && SubTypeSize < 256 &&
434 ElementTypesAreCompatible(NewTy, SubType, !isArray(), TD))
437 // Okay, so we found the leader type at the offset requested. Search the list
438 // of types that starts at this offset. If SubType is currently an array or
439 // structure, the type desired may actually be the first element of the
442 unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
443 while (SubType != NewTy) {
444 const Type *NextSubType = 0;
445 unsigned NextSubTypeSize = 0;
446 unsigned NextPadSize = 0;
447 switch (SubType->getPrimitiveID()) {
448 case Type::StructTyID: {
449 const StructType *STy = cast<StructType>(SubType);
450 const StructLayout &SL = *TD.getStructLayout(STy);
451 if (SL.MemberOffsets.size() > 1)
452 NextPadSize = SL.MemberOffsets[1];
454 NextPadSize = SubTypeSize;
455 NextSubType = STy->getElementTypes()[0];
456 NextSubTypeSize = TD.getTypeSize(NextSubType);
459 case Type::ArrayTyID:
460 NextSubType = cast<ArrayType>(SubType)->getElementType();
461 NextSubTypeSize = TD.getTypeSize(NextSubType);
462 NextPadSize = NextSubTypeSize;
468 if (NextSubType == 0)
469 break; // In the default case, break out of the loop
471 if (NextPadSize < NewTySize)
472 break; // Don't allow shrinking to a smaller type than NewTySize
473 SubType = NextSubType;
474 SubTypeSize = NextSubTypeSize;
475 PadSize = NextPadSize;
478 // If we found the type exactly, return it...
479 if (SubType == NewTy)
482 // Check to see if we have a compatible, but different type...
483 if (NewTySize == SubTypeSize) {
484 // Check to see if this type is obviously convertible... int -> uint f.e.
485 if (NewTy->isLosslesslyConvertibleTo(SubType))
488 // Check to see if we have a pointer & integer mismatch going on here,
489 // loading a pointer as a long, for example.
491 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
492 NewTy->isInteger() && isa<PointerType>(SubType))
494 } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
495 // We are accessing the field, plus some structure padding. Ignore the
496 // structure padding.
501 if (getParentGraph()->getReturnNodes().size())
502 M = getParentGraph()->getReturnNodes().begin()->first->getParent();
503 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: ";
504 WriteTypeSymbolic(std::cerr, Ty, M) << "\n due to:";
505 WriteTypeSymbolic(std::cerr, NewTy, M) << " @ " << Offset << "!\n"
507 WriteTypeSymbolic(std::cerr, SubType, M) << "\n\n");
509 if (FoldIfIncompatible) foldNodeCompletely();
515 // addEdgeTo - Add an edge from the current node to the specified node. This
516 // can cause merging of nodes in the graph.
518 void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
519 if (NH.getNode() == 0) return; // Nothing to do
521 DSNodeHandle &ExistingEdge = getLink(Offset);
522 if (ExistingEdge.getNode()) {
523 // Merge the two nodes...
524 ExistingEdge.mergeWith(NH);
525 } else { // No merging to perform...
526 setLink(Offset, NH); // Just force a link in there...
531 // MergeSortedVectors - Efficiently merge a vector into another vector where
532 // duplicates are not allowed and both are sorted. This assumes that 'T's are
533 // efficiently copyable and have sane comparison semantics.
535 static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
536 const std::vector<GlobalValue*> &Src) {
537 // By far, the most common cases will be the simple ones. In these cases,
538 // avoid having to allocate a temporary vector...
540 if (Src.empty()) { // Nothing to merge in...
542 } else if (Dest.empty()) { // Just copy the result in...
544 } else if (Src.size() == 1) { // Insert a single element...
545 const GlobalValue *V = Src[0];
546 std::vector<GlobalValue*>::iterator I =
547 std::lower_bound(Dest.begin(), Dest.end(), V);
548 if (I == Dest.end() || *I != Src[0]) // If not already contained...
549 Dest.insert(I, Src[0]);
550 } else if (Dest.size() == 1) {
551 GlobalValue *Tmp = Dest[0]; // Save value in temporary...
552 Dest = Src; // Copy over list...
553 std::vector<GlobalValue*>::iterator I =
554 std::lower_bound(Dest.begin(), Dest.end(), Tmp);
555 if (I == Dest.end() || *I != Tmp) // If not already contained...
559 // Make a copy to the side of Dest...
560 std::vector<GlobalValue*> Old(Dest);
562 // Make space for all of the type entries now...
563 Dest.resize(Dest.size()+Src.size());
565 // Merge the two sorted ranges together... into Dest.
566 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
568 // Now erase any duplicate entries that may have accumulated into the
569 // vectors (because they were in both of the input sets)
570 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
575 // MergeNodes() - Helper function for DSNode::mergeWith().
576 // This function does the hard work of merging two nodes, CurNodeH
577 // and NH after filtering out trivial cases and making sure that
578 // CurNodeH.offset >= NH.offset.
581 // Since merging may cause either node to go away, we must always
582 // use the node-handles to refer to the nodes. These node handles are
583 // automatically updated during merging, so will always provide access
584 // to the correct node after a merge.
586 void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
587 assert(CurNodeH.getOffset() >= NH.getOffset() &&
588 "This should have been enforced in the caller.");
590 // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
591 // respect to NH.Offset) is now zero. NOffset is the distance from the base
592 // of our object that N starts from.
594 unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
595 unsigned NSize = NH.getNode()->getSize();
597 // If the two nodes are of different size, and the smaller node has the array
598 // bit set, collapse!
599 if (NSize != CurNodeH.getNode()->getSize()) {
600 if (NSize < CurNodeH.getNode()->getSize()) {
601 if (NH.getNode()->isArray())
602 NH.getNode()->foldNodeCompletely();
603 } else if (CurNodeH.getNode()->isArray()) {
604 NH.getNode()->foldNodeCompletely();
608 // Merge the type entries of the two nodes together...
609 if (NH.getNode()->Ty != Type::VoidTy)
610 CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
611 assert(!CurNodeH.getNode()->isDeadNode());
613 // If we are merging a node with a completely folded node, then both nodes are
614 // now completely folded.
616 if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
617 if (!NH.getNode()->isNodeCompletelyFolded()) {
618 NH.getNode()->foldNodeCompletely();
619 assert(NH.getNode() && NH.getOffset() == 0 &&
620 "folding did not make offset 0?");
621 NOffset = NH.getOffset();
622 NSize = NH.getNode()->getSize();
623 assert(NOffset == 0 && NSize == 1);
625 } else if (NH.getNode()->isNodeCompletelyFolded()) {
626 CurNodeH.getNode()->foldNodeCompletely();
627 assert(CurNodeH.getNode() && CurNodeH.getOffset() == 0 &&
628 "folding did not make offset 0?");
629 NOffset = NH.getOffset();
630 NSize = NH.getNode()->getSize();
631 assert(NOffset == 0 && NSize == 1);
634 DSNode *N = NH.getNode();
635 if (CurNodeH.getNode() == N || N == 0) return;
636 assert(!CurNodeH.getNode()->isDeadNode());
638 // Merge the NodeType information...
639 CurNodeH.getNode()->NodeType |= N->NodeType;
641 // Start forwarding to the new node!
642 N->forwardNode(CurNodeH.getNode(), NOffset);
643 assert(!CurNodeH.getNode()->isDeadNode());
645 // Make all of the outgoing links of N now be outgoing links of CurNodeH.
647 for (unsigned i = 0; i < N->getNumLinks(); ++i) {
648 DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
649 if (Link.getNode()) {
650 // Compute the offset into the current node at which to
651 // merge this link. In the common case, this is a linear
652 // relation to the offset in the original node (with
653 // wrapping), but if the current node gets collapsed due to
654 // recursive merging, we must make sure to merge in all remaining
655 // links at offset zero.
656 unsigned MergeOffset = 0;
657 DSNode *CN = CurNodeH.getNode();
659 MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
660 CN->addEdgeTo(MergeOffset, Link);
664 // Now that there are no outgoing edges, all of the Links are dead.
667 // Merge the globals list...
668 if (!N->Globals.empty()) {
669 MergeSortedVectors(CurNodeH.getNode()->Globals, N->Globals);
671 // Delete the globals from the old node...
672 std::vector<GlobalValue*>().swap(N->Globals);
677 // mergeWith - Merge this node and the specified node, moving all links to and
678 // from the argument node into the current node, deleting the node argument.
679 // Offset indicates what offset the specified node is to be merged into the
682 // The specified node may be a null pointer (in which case, nothing happens).
684 void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
685 DSNode *N = NH.getNode();
686 if (N == 0 || (N == this && NH.getOffset() == Offset))
689 assert(!N->isDeadNode() && !isDeadNode());
690 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
693 // We cannot merge two pieces of the same node together, collapse the node
695 DEBUG(std::cerr << "Attempting to merge two chunks of"
696 << " the same node together!\n");
697 foldNodeCompletely();
701 // If both nodes are not at offset 0, make sure that we are merging the node
702 // at an later offset into the node with the zero offset.
704 if (Offset < NH.getOffset()) {
705 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
707 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
708 // If the offsets are the same, merge the smaller node into the bigger node
709 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
713 // Ok, now we can merge the two nodes. Use a static helper that works with
714 // two node handles, since "this" may get merged away at intermediate steps.
715 DSNodeHandle CurNodeH(this, Offset);
716 DSNodeHandle NHCopy(NH);
717 DSNode::MergeNodes(CurNodeH, NHCopy);
720 //===----------------------------------------------------------------------===//
721 // DSCallSite Implementation
722 //===----------------------------------------------------------------------===//
724 // Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
725 Function &DSCallSite::getCaller() const {
726 return *Site.getInstruction()->getParent()->getParent();
730 //===----------------------------------------------------------------------===//
731 // DSGraph Implementation
732 //===----------------------------------------------------------------------===//
734 /// getFunctionNames - Return a space separated list of the name of the
735 /// functions in this graph (if any)
736 std::string DSGraph::getFunctionNames() const {
737 switch (getReturnNodes().size()) {
738 case 0: return "Globals graph";
739 case 1: return getReturnNodes().begin()->first->getName();
742 for (DSGraph::ReturnNodesTy::const_iterator I = getReturnNodes().begin();
743 I != getReturnNodes().end(); ++I)
744 Return += I->first->getName() + " ";
745 Return.erase(Return.end()-1, Return.end()); // Remove last space character
751 DSGraph::DSGraph(const DSGraph &G) : GlobalsGraph(0), TD(G.TD) {
752 PrintAuxCalls = false;
754 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
755 InlinedGlobals.clear(); // clear set of "up-to-date" globals
758 DSGraph::DSGraph(const DSGraph &G, NodeMapTy &NodeMap)
759 : GlobalsGraph(0), TD(G.TD) {
760 PrintAuxCalls = false;
761 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
762 InlinedGlobals.clear(); // clear set of "up-to-date" globals
765 DSGraph::~DSGraph() {
766 FunctionCalls.clear();
767 AuxFunctionCalls.clear();
768 InlinedGlobals.clear();
772 // Drop all intra-node references, so that assertions don't fail...
773 std::for_each(Nodes.begin(), Nodes.end(),
774 std::mem_fun(&DSNode::dropAllReferences));
776 // Delete all of the nodes themselves...
777 std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
780 // dump - Allow inspection of graph in a debugger.
781 void DSGraph::dump() const { print(std::cerr); }
784 /// remapLinks - Change all of the Links in the current node according to the
785 /// specified mapping.
787 void DSNode::remapLinks(DSGraph::NodeMapTy &OldNodeMap) {
788 for (unsigned i = 0, e = Links.size(); i != e; ++i) {
789 DSNodeHandle &H = OldNodeMap[Links[i].getNode()];
790 Links[i].setNode(H.getNode());
791 Links[i].setOffset(Links[i].getOffset()+H.getOffset());
796 /// cloneReachableNodes - Clone all reachable nodes from *Node into the
797 /// current graph. This is a recursive function. The map OldNodeMap is a
798 /// map from the original nodes to their clones.
800 void DSGraph::cloneReachableNodes(const DSNode* Node,
801 unsigned BitsToClear,
802 NodeMapTy& OldNodeMap,
803 NodeMapTy& CompletedNodeMap) {
804 if (CompletedNodeMap.find(Node) != CompletedNodeMap.end())
807 DSNodeHandle& NH = OldNodeMap[Node];
808 if (NH.getNode() != NULL)
811 // else Node has not yet been cloned: clone it and clear the specified bits
812 NH = new DSNode(*Node, this); // enters in OldNodeMap
813 NH.getNode()->maskNodeTypes(~BitsToClear);
815 // now recursively clone nodes pointed to by this node
816 for (unsigned i = 0, e = Node->getNumLinks(); i != e; ++i) {
817 const DSNodeHandle &Link = Node->getLink(i << DS::PointerShift);
818 if (const DSNode* nextNode = Link.getNode())
819 cloneReachableNodes(nextNode, BitsToClear, OldNodeMap, CompletedNodeMap);
823 void DSGraph::cloneReachableSubgraph(const DSGraph& G,
824 const hash_set<const DSNode*>& RootNodes,
825 NodeMapTy& OldNodeMap,
826 NodeMapTy& CompletedNodeMap,
827 unsigned CloneFlags) {
828 if (RootNodes.empty())
831 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
832 assert(&G != this && "Cannot clone graph into itself!");
833 assert((*RootNodes.begin())->getParentGraph() == &G &&
834 "Root nodes do not belong to this graph!");
836 // Remove alloca or mod/ref bits as specified...
837 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
838 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
839 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
840 BitsToClear |= DSNode::DEAD; // Clear dead flag...
842 // Clone all nodes reachable from each root node, using a recursive helper
843 for (hash_set<const DSNode*>::const_iterator I = RootNodes.begin(),
844 E = RootNodes.end(); I != E; ++I)
845 cloneReachableNodes(*I, BitsToClear, OldNodeMap, CompletedNodeMap);
847 // Merge the map entries in OldNodeMap and CompletedNodeMap to remap links
848 NodeMapTy MergedMap(OldNodeMap);
849 MergedMap.insert(CompletedNodeMap.begin(), CompletedNodeMap.end());
851 // Rewrite the links in the newly created nodes (the nodes in OldNodeMap)
852 // to point into the current graph. MergedMap gives the full mapping.
853 for (NodeMapTy::iterator I=OldNodeMap.begin(), E=OldNodeMap.end(); I!= E; ++I)
854 I->second.getNode()->remapLinks(MergedMap);
856 // Now merge cloned global nodes with their copies in the current graph
857 // Just look through OldNodeMap to find such nodes!
858 for (NodeMapTy::iterator I=OldNodeMap.begin(), E=OldNodeMap.end(); I!= E; ++I)
859 if (I->first->isGlobalNode()) {
860 DSNodeHandle &GClone = I->second;
861 assert(GClone.getNode() != NULL && "NULL node in OldNodeMap?");
862 const std::vector<GlobalValue*> &Globals = I->first->getGlobals();
863 for (unsigned gi = 0, ge = Globals.size(); gi != ge; ++gi) {
864 DSNodeHandle &GH = ScalarMap[Globals[gi]];
865 GH.mergeWith(GClone);
871 /// updateFromGlobalGraph - This function rematerializes global nodes and
872 /// nodes reachable from them from the globals graph into the current graph.
873 /// It invokes cloneReachableSubgraph, using the globals in the current graph
874 /// as the roots. It also uses the vector InlinedGlobals to avoid cloning and
875 /// merging globals that are already up-to-date in the current graph. In
876 /// practice, in the TD pass, this is likely to be a large fraction of the
877 /// live global nodes in each function (since most live nodes are likely to
878 /// have been brought up-to-date in at _some_ caller or callee).
880 void DSGraph::updateFromGlobalGraph() {
882 // Use a map to keep track of the mapping between nodes in the globals graph
883 // and this graph for up-to-date global nodes, which do not need to be cloned.
884 NodeMapTy CompletedMap;
886 // Put the live, non-up-to-date global nodes into a set and the up-to-date
887 // ones in the map above, mapping node in GlobalsGraph to the up-to-date node.
888 hash_set<const DSNode*> GlobalNodeSet;
889 for (ScalarMapTy::const_iterator I = getScalarMap().begin(),
890 E = getScalarMap().end(); I != E; ++I)
891 if (GlobalValue* GV = dyn_cast<GlobalValue>(I->first)) {
892 DSNode* GNode = I->second.getNode();
893 assert(GNode && "No node for live global in current Graph?");
894 if (const DSNode* GGNode = GlobalsGraph->ScalarMap[GV].getNode())
895 if (InlinedGlobals.count(GV) == 0) // GNode is not up-to-date
896 GlobalNodeSet.insert(GGNode);
897 else { // GNode is up-to-date
898 CompletedMap[GGNode] = I->second;
899 assert(GGNode->getNumLinks() == GNode->getNumLinks() &&
900 "Links dont match in a node that is supposed to be up-to-date?"
901 "\nremapLinks() will not work if the links don't match!");
905 // Clone the subgraph reachable from the vector of nodes in GlobalNodes
906 // and merge the cloned global nodes with the corresponding ones, if any.
907 NodeMapTy OldNodeMap;
908 cloneReachableSubgraph(*GlobalsGraph, GlobalNodeSet, OldNodeMap,CompletedMap);
910 // Merging global nodes leaves behind unused nodes: get rid of them now.
911 OldNodeMap.clear(); // remove references before dead node cleanup
912 CompletedMap.clear(); // remove references before dead node cleanup
913 removeTriviallyDeadNodes();
916 /// cloneInto - Clone the specified DSGraph into the current graph. The
917 /// translated ScalarMap for the old function is filled into the OldValMap
918 /// member, and the translated ReturnNodes map is returned into ReturnNodes.
920 /// The CloneFlags member controls various aspects of the cloning process.
922 void DSGraph::cloneInto(const DSGraph &G, ScalarMapTy &OldValMap,
923 ReturnNodesTy &OldReturnNodes, NodeMapTy &OldNodeMap,
924 unsigned CloneFlags) {
925 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
926 assert(&G != this && "Cannot clone graph into itself!");
928 unsigned FN = Nodes.size(); // First new node...
930 // Duplicate all of the nodes, populating the node map...
931 Nodes.reserve(FN+G.Nodes.size());
933 // Remove alloca or mod/ref bits as specified...
934 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
935 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
936 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
937 BitsToClear |= DSNode::DEAD; // Clear dead flag...
938 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
939 DSNode *Old = G.Nodes[i];
940 DSNode *New = new DSNode(*Old, this);
941 New->maskNodeTypes(~BitsToClear);
942 OldNodeMap[Old] = New;
946 Timer::addPeakMemoryMeasurement();
949 // Rewrite the links in the new nodes to point into the current graph now.
950 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
951 Nodes[i]->remapLinks(OldNodeMap);
953 // Copy the scalar map... merging all of the global nodes...
954 for (ScalarMapTy::const_iterator I = G.ScalarMap.begin(),
955 E = G.ScalarMap.end(); I != E; ++I) {
956 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
957 DSNodeHandle &H = OldValMap[I->first];
958 H.mergeWith(DSNodeHandle(MappedNode.getNode(),
959 I->second.getOffset()+MappedNode.getOffset()));
961 // If this is a global, add the global to this fn or merge if already exists
962 if (GlobalValue* GV = dyn_cast<GlobalValue>(I->first)) {
963 ScalarMap[GV].mergeWith(H);
964 InlinedGlobals.insert(GV);
968 if (!(CloneFlags & DontCloneCallNodes)) {
969 // Copy the function calls list...
970 unsigned FC = FunctionCalls.size(); // FirstCall
971 FunctionCalls.reserve(FC+G.FunctionCalls.size());
972 for (unsigned i = 0, ei = G.FunctionCalls.size(); i != ei; ++i)
973 FunctionCalls.push_back(DSCallSite(G.FunctionCalls[i], OldNodeMap));
976 if (!(CloneFlags & DontCloneAuxCallNodes)) {
977 // Copy the auxiliary function calls list...
978 unsigned FC = AuxFunctionCalls.size(); // FirstCall
979 AuxFunctionCalls.reserve(FC+G.AuxFunctionCalls.size());
980 for (unsigned i = 0, ei = G.AuxFunctionCalls.size(); i != ei; ++i)
981 AuxFunctionCalls.push_back(DSCallSite(G.AuxFunctionCalls[i], OldNodeMap));
984 // Map the return node pointers over...
985 for (ReturnNodesTy::const_iterator I = G.getReturnNodes().begin(),
986 E = G.getReturnNodes().end(); I != E; ++I) {
987 const DSNodeHandle &Ret = I->second;
988 DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
989 OldReturnNodes.insert(std::make_pair(I->first,
990 DSNodeHandle(MappedRet.getNode(),
991 MappedRet.getOffset()+Ret.getOffset())));
995 /// mergeInGraph - The method is used for merging graphs together. If the
996 /// argument graph is not *this, it makes a clone of the specified graph, then
997 /// merges the nodes specified in the call site with the formal arguments in the
1000 void DSGraph::mergeInGraph(const DSCallSite &CS, Function &F,
1001 const DSGraph &Graph, unsigned CloneFlags) {
1002 ScalarMapTy OldValMap, *ScalarMap;
1003 DSNodeHandle RetVal;
1005 // If this is not a recursive call, clone the graph into this graph...
1006 if (&Graph != this) {
1007 // Clone the callee's graph into the current graph, keeping
1008 // track of where scalars in the old graph _used_ to point,
1009 // and of the new nodes matching nodes of the old graph.
1010 NodeMapTy OldNodeMap;
1012 // The clone call may invalidate any of the vectors in the data
1013 // structure graph. Strip locals and don't copy the list of callers
1014 ReturnNodesTy OldRetNodes;
1015 cloneInto(Graph, OldValMap, OldRetNodes, OldNodeMap, CloneFlags);
1017 // We need to map the arguments for the function to the cloned nodes old
1018 // argument values. Do this now.
1019 RetVal = OldRetNodes[&F];
1020 ScalarMap = &OldValMap;
1022 RetVal = getReturnNodeFor(F);
1023 ScalarMap = &getScalarMap();
1026 // Merge the return value with the return value of the context...
1027 RetVal.mergeWith(CS.getRetVal());
1029 // Resolve all of the function arguments...
1030 Function::aiterator AI = F.abegin();
1032 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
1033 // Advance the argument iterator to the first pointer argument...
1034 while (AI != F.aend() && !isPointerType(AI->getType())) {
1038 std::cerr << "Bad call to Function: " << F.getName() << "\n";
1041 if (AI == F.aend()) break;
1043 // Add the link from the argument scalar to the provided value
1044 assert(ScalarMap->count(AI) && "Argument not in scalar map?");
1045 DSNodeHandle &NH = (*ScalarMap)[AI];
1046 assert(NH.getNode() && "Pointer argument without scalarmap entry?");
1047 NH.mergeWith(CS.getPtrArg(i));
1051 /// getCallSiteForArguments - Get the arguments and return value bindings for
1052 /// the specified function in the current graph.
1054 DSCallSite DSGraph::getCallSiteForArguments(Function &F) const {
1055 std::vector<DSNodeHandle> Args;
1057 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
1058 if (isPointerType(I->getType()))
1059 Args.push_back(getScalarMap().find(I)->second);
1061 return DSCallSite(CallSite(), getReturnNodeFor(F), &F, Args);
1066 // markIncompleteNodes - Mark the specified node as having contents that are not
1067 // known with the current analysis we have performed. Because a node makes all
1068 // of the nodes it can reach incomplete if the node itself is incomplete, we
1069 // must recursively traverse the data structure graph, marking all reachable
1070 // nodes as incomplete.
1072 static void markIncompleteNode(DSNode *N) {
1073 // Stop recursion if no node, or if node already marked...
1074 if (N == 0 || N->isIncomplete()) return;
1076 // Actually mark the node
1077 N->setIncompleteMarker();
1079 // Recursively process children...
1080 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
1081 if (DSNode *DSN = N->getLink(i).getNode())
1082 markIncompleteNode(DSN);
1085 static void markIncomplete(DSCallSite &Call) {
1086 // Then the return value is certainly incomplete!
1087 markIncompleteNode(Call.getRetVal().getNode());
1089 // All objects pointed to by function arguments are incomplete!
1090 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
1091 markIncompleteNode(Call.getPtrArg(i).getNode());
1094 // markIncompleteNodes - Traverse the graph, identifying nodes that may be
1095 // modified by other functions that have not been resolved yet. This marks
1096 // nodes that are reachable through three sources of "unknownness":
1098 // Global Variables, Function Calls, and Incoming Arguments
1100 // For any node that may have unknown components (because something outside the
1101 // scope of current analysis may have modified it), the 'Incomplete' flag is
1102 // added to the NodeType.
1104 void DSGraph::markIncompleteNodes(unsigned Flags) {
1105 // Mark any incoming arguments as incomplete...
1106 if (Flags & DSGraph::MarkFormalArgs)
1107 for (ReturnNodesTy::iterator FI = ReturnNodes.begin(), E =ReturnNodes.end();
1109 Function &F = *FI->first;
1110 if (F.getName() != "main")
1111 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
1112 if (isPointerType(I->getType()) &&
1113 ScalarMap.find(I) != ScalarMap.end())
1114 markIncompleteNode(ScalarMap[I].getNode());
1117 // Mark stuff passed into functions calls as being incomplete...
1118 if (!shouldPrintAuxCalls())
1119 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1120 markIncomplete(FunctionCalls[i]);
1122 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1123 markIncomplete(AuxFunctionCalls[i]);
1126 // Mark all global nodes as incomplete...
1127 if ((Flags & DSGraph::IgnoreGlobals) == 0)
1128 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
1129 if (Nodes[i]->isGlobalNode() && Nodes[i]->getNumLinks())
1130 markIncompleteNode(Nodes[i]);
1133 static inline void killIfUselessEdge(DSNodeHandle &Edge) {
1134 if (DSNode *N = Edge.getNode()) // Is there an edge?
1135 if (N->getNumReferrers() == 1) // Does it point to a lonely node?
1136 // No interesting info?
1137 if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
1138 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
1139 Edge.setNode(0); // Kill the edge!
1142 static inline bool nodeContainsExternalFunction(const DSNode *N) {
1143 const std::vector<GlobalValue*> &Globals = N->getGlobals();
1144 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
1145 if (Globals[i]->isExternal())
1150 static void removeIdenticalCalls(std::vector<DSCallSite> &Calls) {
1152 // Remove trivially identical function calls
1153 unsigned NumFns = Calls.size();
1154 std::sort(Calls.begin(), Calls.end()); // Sort by callee as primary key!
1156 // Scan the call list cleaning it up as necessary...
1157 DSNode *LastCalleeNode = 0;
1158 Function *LastCalleeFunc = 0;
1159 unsigned NumDuplicateCalls = 0;
1160 bool LastCalleeContainsExternalFunction = false;
1161 for (unsigned i = 0; i != Calls.size(); ++i) {
1162 DSCallSite &CS = Calls[i];
1164 // If the Callee is a useless edge, this must be an unreachable call site,
1166 if (CS.isIndirectCall() && CS.getCalleeNode()->getNumReferrers() == 1 &&
1167 CS.getCalleeNode()->getNodeFlags() == 0) { // No useful info?
1168 std::cerr << "WARNING: Useless call site found??\n";
1169 CS.swap(Calls.back());
1173 // If the return value or any arguments point to a void node with no
1174 // information at all in it, and the call node is the only node to point
1175 // to it, remove the edge to the node (killing the node).
1177 killIfUselessEdge(CS.getRetVal());
1178 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
1179 killIfUselessEdge(CS.getPtrArg(a));
1181 // If this call site calls the same function as the last call site, and if
1182 // the function pointer contains an external function, this node will
1183 // never be resolved. Merge the arguments of the call node because no
1184 // information will be lost.
1186 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
1187 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
1188 ++NumDuplicateCalls;
1189 if (NumDuplicateCalls == 1) {
1191 LastCalleeContainsExternalFunction =
1192 nodeContainsExternalFunction(LastCalleeNode);
1194 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
1198 if (LastCalleeContainsExternalFunction ||
1199 // This should be more than enough context sensitivity!
1200 // FIXME: Evaluate how many times this is tripped!
1201 NumDuplicateCalls > 20) {
1202 DSCallSite &OCS = Calls[i-1];
1205 // The node will now be eliminated as a duplicate!
1206 if (CS.getNumPtrArgs() < OCS.getNumPtrArgs())
1208 else if (CS.getNumPtrArgs() > OCS.getNumPtrArgs())
1213 if (CS.isDirectCall()) {
1214 LastCalleeFunc = CS.getCalleeFunc();
1217 LastCalleeNode = CS.getCalleeNode();
1220 NumDuplicateCalls = 0;
1225 Calls.erase(std::unique(Calls.begin(), Calls.end()),
1228 // Track the number of call nodes merged away...
1229 NumCallNodesMerged += NumFns-Calls.size();
1231 DEBUG(if (NumFns != Calls.size())
1232 std::cerr << "Merged " << (NumFns-Calls.size()) << " call nodes.\n";);
1236 // removeTriviallyDeadNodes - After the graph has been constructed, this method
1237 // removes all unreachable nodes that are created because they got merged with
1238 // other nodes in the graph. These nodes will all be trivially unreachable, so
1239 // we don't have to perform any non-trivial analysis here.
1241 void DSGraph::removeTriviallyDeadNodes() {
1242 removeIdenticalCalls(FunctionCalls);
1243 removeIdenticalCalls(AuxFunctionCalls);
1245 // Loop over all of the nodes in the graph, calling getNode on each field.
1246 // This will cause all nodes to update their forwarding edges, causing
1247 // forwarded nodes to be delete-able.
1248 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1249 DSNode *N = Nodes[i];
1250 for (unsigned l = 0, e = N->getNumLinks(); l != e; ++l)
1251 N->getLink(l*N->getPointerSize()).getNode();
1254 // Likewise, forward any edges from the scalar nodes...
1255 for (ScalarMapTy::iterator I = ScalarMap.begin(), E = ScalarMap.end();
1257 I->second.getNode();
1259 bool isGlobalsGraph = !GlobalsGraph;
1261 for (unsigned i = 0; i != Nodes.size(); ++i) {
1262 DSNode *Node = Nodes[i];
1264 // Do not remove *any* global nodes in the globals graph.
1265 // This is a special case because such nodes may not have I, M, R flags set.
1266 if (Node->isGlobalNode() && isGlobalsGraph)
1269 if (Node->isComplete() && !Node->isModified() && !Node->isRead()) {
1270 // This is a useless node if it has no mod/ref info (checked above),
1271 // outgoing edges (which it cannot, as it is not modified in this
1272 // context), and it has no incoming edges. If it is a global node it may
1273 // have all of these properties and still have incoming edges, due to the
1274 // scalar map, so we check those now.
1276 if (Node->getNumReferrers() == Node->getGlobals().size()) {
1277 const std::vector<GlobalValue*> &Globals = Node->getGlobals();
1279 // Loop through and make sure all of the globals are referring directly
1281 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1282 DSNode *N = ScalarMap.find(Globals[j])->second.getNode();
1283 assert(N == Node && "ScalarMap doesn't match globals list!");
1286 // Make sure NumReferrers still agrees, if so, the node is truly dead.
1287 if (Node->getNumReferrers() == Globals.size()) {
1288 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1289 ScalarMap.erase(Globals[j]);
1290 Node->makeNodeDead();
1294 #ifdef SANER_CODE_FOR_CHECKING_IF_ALL_REFERRERS_ARE_FROM_SCALARMAP
1296 // *** It seems to me that we should be able to simply check if
1297 // *** there are fewer or equal #referrers as #globals and make
1298 // *** sure that all those referrers are in the scalar map?
1300 if (Node->getNumReferrers() <= Node->getGlobals().size()) {
1301 const std::vector<GlobalValue*> &Globals = Node->getGlobals();
1304 // Loop through and make sure all of the globals are referring directly
1306 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1307 DSNode *N = ScalarMap.find(Globals[j])->second.getNode();
1308 assert(N == Node && "ScalarMap doesn't match globals list!");
1312 // Make sure NumReferrers still agrees. The node is truly dead.
1313 assert(Node->getNumReferrers() == Globals.size());
1314 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1315 ScalarMap.erase(Globals[j]);
1316 Node->makeNodeDead();
1321 if (Node->getNodeFlags() == 0 && Node->hasNoReferrers()) {
1322 // This node is dead!
1323 delete Node; // Free memory...
1324 Nodes[i--] = Nodes.back();
1325 Nodes.pop_back(); // Remove from node list...
1331 /// markReachableNodes - This method recursively traverses the specified
1332 /// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
1333 /// to the set, which allows it to only traverse visited nodes once.
1335 void DSNode::markReachableNodes(hash_set<DSNode*> &ReachableNodes) {
1336 if (this == 0) return;
1337 assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
1338 if (ReachableNodes.count(this)) return; // Already marked reachable
1339 ReachableNodes.insert(this); // Is reachable now
1341 for (unsigned i = 0, e = getSize(); i < e; i += DS::PointerSize)
1342 getLink(i).getNode()->markReachableNodes(ReachableNodes);
1345 void DSCallSite::markReachableNodes(hash_set<DSNode*> &Nodes) {
1346 getRetVal().getNode()->markReachableNodes(Nodes);
1347 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
1349 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
1350 getPtrArg(i).getNode()->markReachableNodes(Nodes);
1353 // CanReachAliveNodes - Simple graph walker that recursively traverses the graph
1354 // looking for a node that is marked alive. If an alive node is found, return
1355 // true, otherwise return false. If an alive node is reachable, this node is
1356 // marked as alive...
1358 static bool CanReachAliveNodes(DSNode *N, hash_set<DSNode*> &Alive,
1359 hash_set<DSNode*> &Visited,
1360 bool IgnoreGlobals) {
1361 if (N == 0) return false;
1362 assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
1364 // If this is a global node, it will end up in the globals graph anyway, so we
1365 // don't need to worry about it.
1366 if (IgnoreGlobals && N->isGlobalNode()) return false;
1368 // If we know that this node is alive, return so!
1369 if (Alive.count(N)) return true;
1371 // Otherwise, we don't think the node is alive yet, check for infinite
1373 if (Visited.count(N)) return false; // Found a cycle
1374 Visited.insert(N); // No recursion, insert into Visited...
1376 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
1377 if (CanReachAliveNodes(N->getLink(i).getNode(), Alive, Visited,
1379 N->markReachableNodes(Alive);
1385 // CallSiteUsesAliveArgs - Return true if the specified call site can reach any
1388 static bool CallSiteUsesAliveArgs(DSCallSite &CS, hash_set<DSNode*> &Alive,
1389 hash_set<DSNode*> &Visited,
1390 bool IgnoreGlobals) {
1391 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited,
1394 if (CS.isIndirectCall() &&
1395 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited, IgnoreGlobals))
1397 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
1398 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited,
1404 // removeDeadNodes - Use a more powerful reachability analysis to eliminate
1405 // subgraphs that are unreachable. This often occurs because the data
1406 // structure doesn't "escape" into it's caller, and thus should be eliminated
1407 // from the caller's graph entirely. This is only appropriate to use when
1410 void DSGraph::removeDeadNodes(unsigned Flags) {
1411 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
1413 // Reduce the amount of work we have to do... remove dummy nodes left over by
1415 removeTriviallyDeadNodes();
1417 // FIXME: Merge non-trivially identical call nodes...
1419 // Alive - a set that holds all nodes found to be reachable/alive.
1420 hash_set<DSNode*> Alive;
1421 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
1423 // Mark all nodes reachable by (non-global) scalar nodes as alive...
1424 for (ScalarMapTy::iterator I = ScalarMap.begin(), E = ScalarMap.end(); I !=E;)
1425 if (isa<GlobalValue>(I->first)) { // Keep track of global nodes
1426 assert(I->second.getNode() && "Null global node?");
1427 assert(I->second.getNode()->isGlobalNode() && "Should be a global node!");
1428 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
1431 // Check to see if this is a worthless node generated for non-pointer
1432 // values, such as integers. Consider an addition of long types: A+B.
1433 // Assuming we can track all uses of the value in this context, and it is
1434 // NOT used as a pointer, we can delete the node. We will be able to
1435 // detect this situation if the node pointed to ONLY has Unknown bit set
1436 // in the node. In this case, the node is not incomplete, does not point
1437 // to any other nodes (no mod/ref bits set), and is therefore
1438 // uninteresting for data structure analysis. If we run across one of
1439 // these, prune the scalar pointing to it.
1441 DSNode *N = I->second.getNode();
1442 if (N->getNodeFlags() == DSNode::UnknownNode && !isa<Argument>(I->first)){
1443 ScalarMap.erase(I++);
1445 I->second.getNode()->markReachableNodes(Alive);
1450 // The return value is alive as well...
1451 for (ReturnNodesTy::iterator I = ReturnNodes.begin(), E = ReturnNodes.end();
1453 I->second.getNode()->markReachableNodes(Alive);
1455 // Mark any nodes reachable by primary calls as alive...
1456 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1457 FunctionCalls[i].markReachableNodes(Alive);
1459 // Copy and merge all information about globals to the GlobalsGraph
1460 // if this is not a final pass (where unreachable globals are removed)
1461 NodeMapTy GlobalNodeMap;
1462 hash_set<const DSNode*> GlobalNodeSet;
1464 for (std::vector<std::pair<Value*, DSNode*> >::const_iterator
1465 I = GlobalNodes.begin(), E = GlobalNodes.end(); I != E; ++I)
1466 GlobalNodeSet.insert(I->second); // put global nodes into a set
1468 // Now find globals and aux call nodes that are already live or reach a live
1469 // value (which makes them live in turn), and continue till no more are found.
1472 hash_set<DSNode*> Visited;
1473 std::vector<unsigned char> AuxFCallsAlive(AuxFunctionCalls.size());
1476 // If any global node points to a non-global that is "alive", the global is
1477 // "alive" as well... Remove it from the GlobalNodes list so we only have
1478 // unreachable globals in the list.
1481 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
1482 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
1483 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited,
1484 Flags & DSGraph::RemoveUnreachableGlobals)) {
1485 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to...
1486 GlobalNodes.pop_back(); // erase efficiently
1490 // Mark only unresolvable call nodes for moving to the GlobalsGraph since
1491 // call nodes that get resolved will be difficult to remove from that graph.
1492 // The final unresolved call nodes must be handled specially at the end of
1493 // the BU pass (i.e., in main or other roots of the call graph).
1494 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1495 if (!AuxFCallsAlive[i] &&
1496 (AuxFunctionCalls[i].isIndirectCall()
1497 || CallSiteUsesAliveArgs(AuxFunctionCalls[i], Alive, Visited,
1498 Flags & DSGraph::RemoveUnreachableGlobals))) {
1499 AuxFunctionCalls[i].markReachableNodes(Alive);
1500 AuxFCallsAlive[i] = true;
1505 // Move dead aux function calls to the end of the list
1506 unsigned CurIdx = 0;
1507 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1508 if (AuxFCallsAlive[i])
1509 AuxFunctionCalls[CurIdx++].swap(AuxFunctionCalls[i]);
1511 // Copy and merge all global nodes and dead aux call nodes into the
1512 // GlobalsGraph, and all nodes reachable from those nodes
1514 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
1516 // First, add the dead aux call nodes to the set of root nodes for cloning
1517 // -- return value at this call site, if any
1518 // -- actual arguments passed at this call site
1519 // -- callee node at this call site, if this is an indirect call
1520 for (unsigned i = CurIdx, e = AuxFunctionCalls.size(); i != e; ++i) {
1521 if (const DSNode* RetNode = AuxFunctionCalls[i].getRetVal().getNode())
1522 GlobalNodeSet.insert(RetNode);
1523 for (unsigned j=0, N=AuxFunctionCalls[i].getNumPtrArgs(); j < N; ++j)
1524 if (const DSNode* ArgTarget=AuxFunctionCalls[i].getPtrArg(j).getNode())
1525 GlobalNodeSet.insert(ArgTarget);
1526 if (AuxFunctionCalls[i].isIndirectCall())
1527 GlobalNodeSet.insert(AuxFunctionCalls[i].getCalleeNode());
1530 // There are no "pre-completed" nodes so use any empty map for those.
1531 // Strip all alloca bits since the current function is only for the BU pass.
1532 // Strip all incomplete bits since they are short-lived properties and they
1533 // will be correctly computed when rematerializing nodes into the functions.
1535 NodeMapTy CompletedMap;
1536 GlobalsGraph->cloneReachableSubgraph(*this, GlobalNodeSet,
1537 GlobalNodeMap, CompletedMap,
1538 (DSGraph::StripAllocaBit |
1539 DSGraph::StripIncompleteBit));
1542 // Remove all dead aux function calls...
1543 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
1544 assert(GlobalsGraph && "No globals graph available??");
1546 // Copy the unreachable call nodes to the globals graph, updating
1547 // their target pointers using the GlobalNodeMap
1548 for (unsigned i = CurIdx, e = AuxFunctionCalls.size(); i != e; ++i)
1549 GlobalsGraph->AuxFunctionCalls.push_back(DSCallSite(AuxFunctionCalls[i],
1552 // Crop all the useless ones out...
1553 AuxFunctionCalls.erase(AuxFunctionCalls.begin()+CurIdx,
1554 AuxFunctionCalls.end());
1556 // We are finally done with the GlobalNodeMap so we can clear it and
1557 // then get rid of unused nodes in the GlobalsGraph produced by merging.
1558 GlobalNodeMap.clear();
1559 GlobalsGraph->removeTriviallyDeadNodes();
1561 // At this point, any nodes which are visited, but not alive, are nodes
1562 // which can be removed. Loop over all nodes, eliminating completely
1563 // unreachable nodes.
1565 std::vector<DSNode*> DeadNodes;
1566 DeadNodes.reserve(Nodes.size());
1567 for (unsigned i = 0; i != Nodes.size(); ++i)
1568 if (!Alive.count(Nodes[i])) {
1569 DSNode *N = Nodes[i];
1570 Nodes[i--] = Nodes.back(); // move node to end of vector
1571 Nodes.pop_back(); // Erase node from alive list.
1572 DeadNodes.push_back(N);
1573 N->dropAllReferences();
1575 assert(Nodes[i]->getForwardNode() == 0 && "Alive forwarded node?");
1578 // Remove all unreachable globals from the ScalarMap.
1579 // If flag RemoveUnreachableGlobals is set, GlobalNodes has only dead nodes.
1580 // In either case, the dead nodes will not be in the set Alive.
1581 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i) {
1582 assert(((Flags & DSGraph::RemoveUnreachableGlobals) ||
1583 !Alive.count(GlobalNodes[i].second)) && "huh? non-dead global");
1584 if (!Alive.count(GlobalNodes[i].second))
1585 ScalarMap.erase(GlobalNodes[i].first);
1588 // Delete all dead nodes now since their referrer counts are zero.
1589 for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
1590 delete DeadNodes[i];
1592 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
1595 void DSGraph::AssertGraphOK() const {
1596 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
1597 Nodes[i]->assertOK();
1599 for (ScalarMapTy::const_iterator I = ScalarMap.begin(),
1600 E = ScalarMap.end(); I != E; ++I) {
1601 assert(I->second.getNode() && "Null node in scalarmap!");
1602 AssertNodeInGraph(I->second.getNode());
1603 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
1604 assert(I->second.getNode()->isGlobalNode() &&
1605 "Global points to node, but node isn't global?");
1606 AssertNodeContainsGlobal(I->second.getNode(), GV);
1609 AssertCallNodesInGraph();
1610 AssertAuxCallNodesInGraph();
1613 /// mergeInGlobalsGraph - This method is useful for clients to incorporate the
1614 /// globals graph into the DS, BU or TD graph for a function. This code retains
1615 /// all globals, i.e., does not delete unreachable globals after they are
1618 void DSGraph::mergeInGlobalsGraph() {
1619 NodeMapTy GlobalNodeMap;
1620 ScalarMapTy OldValMap;
1621 ReturnNodesTy OldRetNodes;
1622 cloneInto(*GlobalsGraph, OldValMap, OldRetNodes, GlobalNodeMap,
1623 DSGraph::KeepAllocaBit | DSGraph::DontCloneCallNodes |
1624 DSGraph::DontCloneAuxCallNodes);
1626 // Now merge existing global nodes in the GlobalsGraph with their copies
1627 for (ScalarMapTy::iterator I = ScalarMap.begin(), E = ScalarMap.end();
1629 if (isa<GlobalValue>(I->first)) { // Found a global node
1630 DSNodeHandle &GH = I->second;
1631 DSNodeHandle &GGNodeH = GlobalsGraph->getScalarMap()[I->first];
1632 GH.mergeWith(GlobalNodeMap[GGNodeH.getNode()]);
1635 // Merging leaves behind unused nodes: get rid of them now.
1636 GlobalNodeMap.clear();
1638 OldRetNodes.clear();
1639 removeTriviallyDeadNodes();