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/DataStructure/DSGraphTraits.h"
15 #include "llvm/Constants.h"
16 #include "llvm/Function.h"
17 #include "llvm/GlobalVariable.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Target/TargetData.h"
21 #include "llvm/Assembly/Writer.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/ADT/DepthFirstIterator.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SCCIterator.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/Support/Timer.h"
32 #define COLLAPSE_ARRAYS_AGGRESSIVELY 0
35 Statistic<> NumFolds ("dsa", "Number of nodes completely folded");
36 Statistic<> NumCallNodesMerged("dsa", "Number of call nodes merged");
37 Statistic<> NumNodeAllocated ("dsa", "Number of nodes allocated");
38 Statistic<> NumDNE ("dsa", "Number of nodes removed by reachability");
39 Statistic<> NumTrivialDNE ("dsa", "Number of nodes trivially removed");
40 Statistic<> NumTrivialGlobalDNE("dsa", "Number of globals trivially removed");
44 #define TIME_REGION(VARNAME, DESC) \
45 NamedRegionTimer VARNAME(DESC)
47 #define TIME_REGION(VARNAME, DESC)
52 /// isForwarding - Return true if this NodeHandle is forwarding to another
54 bool DSNodeHandle::isForwarding() const {
55 return N && N->isForwarding();
58 DSNode *DSNodeHandle::HandleForwarding() const {
59 assert(N->isForwarding() && "Can only be invoked if forwarding!");
61 // Handle node forwarding here!
62 DSNode *Next = N->ForwardNH.getNode(); // Cause recursive shrinkage
63 Offset += N->ForwardNH.getOffset();
65 if (--N->NumReferrers == 0) {
66 // Removing the last referrer to the node, sever the forwarding link
72 if (N->Size <= Offset) {
73 assert(N->Size <= 1 && "Forwarded to shrunk but not collapsed node?");
79 //===----------------------------------------------------------------------===//
80 // DSScalarMap Implementation
81 //===----------------------------------------------------------------------===//
83 DSNodeHandle &DSScalarMap::AddGlobal(GlobalValue *GV) {
84 assert(ValueMap.count(GV) == 0 && "GV already exists!");
86 // If the node doesn't exist, check to see if it's a global that is
87 // equated to another global in the program.
88 EquivalenceClasses<GlobalValue*>::iterator ECI = GlobalECs.findValue(GV);
89 if (ECI != GlobalECs.end()) {
90 GlobalValue *Leader = *GlobalECs.findLeader(ECI);
93 iterator I = ValueMap.find(GV);
94 if (I != ValueMap.end())
99 // Okay, this is either not an equivalenced global or it is the leader, it
100 // will be inserted into the scalar map now.
101 GlobalSet.insert(GV);
103 return ValueMap.insert(std::make_pair(GV, DSNodeHandle())).first->second;
107 //===----------------------------------------------------------------------===//
108 // DSNode Implementation
109 //===----------------------------------------------------------------------===//
111 DSNode::DSNode(const Type *T, DSGraph *G)
112 : NumReferrers(0), Size(0), ParentGraph(G), Ty(Type::VoidTy), NodeType(0) {
113 // Add the type entry if it is specified...
114 if (T) mergeTypeInfo(T, 0);
115 if (G) G->addNode(this);
119 // DSNode copy constructor... do not copy over the referrers list!
120 DSNode::DSNode(const DSNode &N, DSGraph *G, bool NullLinks)
121 : NumReferrers(0), Size(N.Size), ParentGraph(G),
122 Ty(N.Ty), NodeType(N.NodeType) {
127 Links.resize(N.Links.size()); // Create the appropriate number of null links
132 /// getTargetData - Get the target data object used to construct this node.
134 const TargetData &DSNode::getTargetData() const {
135 return ParentGraph->getTargetData();
138 void DSNode::assertOK() const {
139 assert((Ty != Type::VoidTy ||
140 Ty == Type::VoidTy && (Size == 0 ||
141 (NodeType & DSNode::Array))) &&
144 assert(ParentGraph && "Node has no parent?");
145 const DSScalarMap &SM = ParentGraph->getScalarMap();
146 for (unsigned i = 0, e = Globals.size(); i != e; ++i) {
147 assert(SM.global_count(Globals[i]));
148 assert(SM.find(Globals[i])->second.getNode() == this);
152 /// forwardNode - Mark this node as being obsolete, and all references to it
153 /// should be forwarded to the specified node and offset.
155 void DSNode::forwardNode(DSNode *To, unsigned Offset) {
156 assert(this != To && "Cannot forward a node to itself!");
157 assert(ForwardNH.isNull() && "Already forwarding from this node!");
158 if (To->Size <= 1) Offset = 0;
159 assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
160 "Forwarded offset is wrong!");
161 ForwardNH.setTo(To, Offset);
166 // Remove this node from the parent graph's Nodes list.
167 ParentGraph->unlinkNode(this);
171 // addGlobal - Add an entry for a global value to the Globals list. This also
172 // marks the node with the 'G' flag if it does not already have it.
174 void DSNode::addGlobal(GlobalValue *GV) {
175 // First, check to make sure this is the leader if the global is in an
176 // equivalence class.
177 GV = getParentGraph()->getScalarMap().getLeaderForGlobal(GV);
179 // Keep the list sorted.
180 std::vector<GlobalValue*>::iterator I =
181 std::lower_bound(Globals.begin(), Globals.end(), GV);
183 if (I == Globals.end() || *I != GV) {
184 Globals.insert(I, GV);
185 NodeType |= GlobalNode;
189 // removeGlobal - Remove the specified global that is explicitly in the globals
191 void DSNode::removeGlobal(GlobalValue *GV) {
192 std::vector<GlobalValue*>::iterator I =
193 std::lower_bound(Globals.begin(), Globals.end(), GV);
194 assert(I != Globals.end() && *I == GV && "Global not in node!");
198 /// foldNodeCompletely - If we determine that this node has some funny
199 /// behavior happening to it that we cannot represent, we fold it down to a
200 /// single, completely pessimistic, node. This node is represented as a
201 /// single byte with a single TypeEntry of "void".
203 void DSNode::foldNodeCompletely() {
204 if (isNodeCompletelyFolded()) return; // If this node is already folded...
208 // If this node has a size that is <= 1, we don't need to create a forwarding
210 if (getSize() <= 1) {
211 NodeType |= DSNode::Array;
214 assert(Links.size() <= 1 && "Size is 1, but has more links?");
217 // Create the node we are going to forward to. This is required because
218 // some referrers may have an offset that is > 0. By forcing them to
219 // forward, the forwarder has the opportunity to correct the offset.
220 DSNode *DestNode = new DSNode(0, ParentGraph);
221 DestNode->NodeType = NodeType|DSNode::Array;
222 DestNode->Ty = Type::VoidTy;
224 DestNode->Globals.swap(Globals);
226 // Start forwarding to the destination node...
227 forwardNode(DestNode, 0);
229 if (!Links.empty()) {
230 DestNode->Links.reserve(1);
232 DSNodeHandle NH(DestNode);
233 DestNode->Links.push_back(Links[0]);
235 // If we have links, merge all of our outgoing links together...
236 for (unsigned i = Links.size()-1; i != 0; --i)
237 NH.getNode()->Links[0].mergeWith(Links[i]);
240 DestNode->Links.resize(1);
245 /// isNodeCompletelyFolded - Return true if this node has been completely
246 /// folded down to something that can never be expanded, effectively losing
247 /// all of the field sensitivity that may be present in the node.
249 bool DSNode::isNodeCompletelyFolded() const {
250 return getSize() == 1 && Ty == Type::VoidTy && isArray();
253 /// addFullGlobalsList - Compute the full set of global values that are
254 /// represented by this node. Unlike getGlobalsList(), this requires fair
255 /// amount of work to compute, so don't treat this method call as free.
256 void DSNode::addFullGlobalsList(std::vector<GlobalValue*> &List) const {
257 if (globals_begin() == globals_end()) return;
259 EquivalenceClasses<GlobalValue*> &EC = getParentGraph()->getGlobalECs();
261 for (globals_iterator I = globals_begin(), E = globals_end(); I != E; ++I) {
262 EquivalenceClasses<GlobalValue*>::iterator ECI = EC.findValue(*I);
266 List.insert(List.end(), EC.member_begin(ECI), EC.member_end());
270 /// addFullFunctionList - Identical to addFullGlobalsList, but only return the
271 /// functions in the full list.
272 void DSNode::addFullFunctionList(std::vector<Function*> &List) const {
273 if (globals_begin() == globals_end()) return;
275 EquivalenceClasses<GlobalValue*> &EC = getParentGraph()->getGlobalECs();
277 for (globals_iterator I = globals_begin(), E = globals_end(); I != E; ++I) {
278 EquivalenceClasses<GlobalValue*>::iterator ECI = EC.findValue(*I);
279 if (ECI == EC.end()) {
280 if (Function *F = dyn_cast<Function>(*I))
283 for (EquivalenceClasses<GlobalValue*>::member_iterator MI =
284 EC.member_begin(ECI), E = EC.member_end(); MI != E; ++MI)
285 if (Function *F = dyn_cast<Function>(*MI))
292 /// TypeElementWalker Class - Used for implementation of physical subtyping...
294 class TypeElementWalker {
299 StackState(const Type *T, unsigned Off = 0)
300 : Ty(T), Offset(Off), Idx(0) {}
303 std::vector<StackState> Stack;
304 const TargetData &TD;
306 TypeElementWalker(const Type *T, const TargetData &td) : TD(td) {
311 bool isDone() const { return Stack.empty(); }
312 const Type *getCurrentType() const { return Stack.back().Ty; }
313 unsigned getCurrentOffset() const { return Stack.back().Offset; }
315 void StepToNextType() {
316 PopStackAndAdvance();
321 /// PopStackAndAdvance - Pop the current element off of the stack and
322 /// advance the underlying element to the next contained member.
323 void PopStackAndAdvance() {
324 assert(!Stack.empty() && "Cannot pop an empty stack!");
326 while (!Stack.empty()) {
327 StackState &SS = Stack.back();
328 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
330 if (SS.Idx != ST->getNumElements()) {
331 const StructLayout *SL = TD.getStructLayout(ST);
333 unsigned(SL->MemberOffsets[SS.Idx]-SL->MemberOffsets[SS.Idx-1]);
336 Stack.pop_back(); // At the end of the structure
338 const ArrayType *AT = cast<ArrayType>(SS.Ty);
340 if (SS.Idx != AT->getNumElements()) {
341 SS.Offset += unsigned(TD.getTypeSize(AT->getElementType()));
344 Stack.pop_back(); // At the end of the array
349 /// StepToLeaf - Used by physical subtyping to move to the first leaf node
350 /// on the type stack.
352 if (Stack.empty()) return;
353 while (!Stack.empty() && !Stack.back().Ty->isFirstClassType()) {
354 StackState &SS = Stack.back();
355 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
356 if (ST->getNumElements() == 0) {
358 PopStackAndAdvance();
360 // Step into the structure...
361 assert(SS.Idx < ST->getNumElements());
362 const StructLayout *SL = TD.getStructLayout(ST);
363 Stack.push_back(StackState(ST->getElementType(SS.Idx),
364 SS.Offset+unsigned(SL->MemberOffsets[SS.Idx])));
367 const ArrayType *AT = cast<ArrayType>(SS.Ty);
368 if (AT->getNumElements() == 0) {
370 PopStackAndAdvance();
372 // Step into the array...
373 assert(SS.Idx < AT->getNumElements());
374 Stack.push_back(StackState(AT->getElementType(),
376 unsigned(TD.getTypeSize(AT->getElementType()))));
382 } // end anonymous namespace
384 /// ElementTypesAreCompatible - Check to see if the specified types are
385 /// "physically" compatible. If so, return true, else return false. We only
386 /// have to check the fields in T1: T2 may be larger than T1. If AllowLargerT1
387 /// is true, then we also allow a larger T1.
389 static bool ElementTypesAreCompatible(const Type *T1, const Type *T2,
390 bool AllowLargerT1, const TargetData &TD){
391 TypeElementWalker T1W(T1, TD), T2W(T2, TD);
393 while (!T1W.isDone() && !T2W.isDone()) {
394 if (T1W.getCurrentOffset() != T2W.getCurrentOffset())
397 const Type *T1 = T1W.getCurrentType();
398 const Type *T2 = T2W.getCurrentType();
399 if (T1 != T2 && !T1->isLosslesslyConvertibleTo(T2))
402 T1W.StepToNextType();
403 T2W.StepToNextType();
406 return AllowLargerT1 || T1W.isDone();
410 /// mergeTypeInfo - This method merges the specified type into the current node
411 /// at the specified offset. This may update the current node's type record if
412 /// this gives more information to the node, it may do nothing to the node if
413 /// this information is already known, or it may merge the node completely (and
414 /// return true) if the information is incompatible with what is already known.
416 /// This method returns true if the node is completely folded, otherwise false.
418 bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset,
419 bool FoldIfIncompatible) {
420 const TargetData &TD = getTargetData();
421 // Check to make sure the Size member is up-to-date. Size can be one of the
423 // Size = 0, Ty = Void: Nothing is known about this node.
424 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
425 // Size = 1, Ty = Void, Array = 1: The node is collapsed
426 // Otherwise, sizeof(Ty) = Size
428 assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
429 (Size == 0 && !Ty->isSized() && !isArray()) ||
430 (Size == 1 && Ty == Type::VoidTy && isArray()) ||
431 (Size == 0 && !Ty->isSized() && !isArray()) ||
432 (TD.getTypeSize(Ty) == Size)) &&
433 "Size member of DSNode doesn't match the type structure!");
434 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
436 if (Offset == 0 && NewTy == Ty)
437 return false; // This should be a common case, handle it efficiently
439 // Return true immediately if the node is completely folded.
440 if (isNodeCompletelyFolded()) return true;
442 // If this is an array type, eliminate the outside arrays because they won't
443 // be used anyway. This greatly reduces the size of large static arrays used
444 // as global variables, for example.
446 bool WillBeArray = false;
447 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
448 // FIXME: we might want to keep small arrays, but must be careful about
449 // things like: [2 x [10000 x int*]]
450 NewTy = AT->getElementType();
454 // Figure out how big the new type we're merging in is...
455 unsigned NewTySize = NewTy->isSized() ? (unsigned)TD.getTypeSize(NewTy) : 0;
457 // Otherwise check to see if we can fold this type into the current node. If
458 // we can't, we fold the node completely, if we can, we potentially update our
461 if (Ty == Type::VoidTy) {
462 // If this is the first type that this node has seen, just accept it without
464 assert(Offset == 0 && !isArray() &&
465 "Cannot have an offset into a void node!");
467 // If this node would have to have an unreasonable number of fields, just
468 // collapse it. This can occur for fortran common blocks, which have stupid
469 // things like { [100000000 x double], [1000000 x double] }.
470 unsigned NumFields = (NewTySize+DS::PointerSize-1) >> DS::PointerShift;
471 if (NumFields > 256) {
472 foldNodeCompletely();
478 if (WillBeArray) NodeType |= Array;
481 // Calculate the number of outgoing links from this node.
482 Links.resize(NumFields);
486 // Handle node expansion case here...
487 if (Offset+NewTySize > Size) {
488 // It is illegal to grow this node if we have treated it as an array of
491 if (FoldIfIncompatible) foldNodeCompletely();
495 if (Offset) { // We could handle this case, but we don't for now...
496 std::cerr << "UNIMP: Trying to merge a growth type into "
497 << "offset != 0: Collapsing!\n";
498 if (FoldIfIncompatible) foldNodeCompletely();
502 // Okay, the situation is nice and simple, we are trying to merge a type in
503 // at offset 0 that is bigger than our current type. Implement this by
504 // switching to the new type and then merge in the smaller one, which should
505 // hit the other code path here. If the other code path decides it's not
506 // ok, it will collapse the node as appropriate.
509 // If this node would have to have an unreasonable number of fields, just
510 // collapse it. This can occur for fortran common blocks, which have stupid
511 // things like { [100000000 x double], [1000000 x double] }.
512 unsigned NumFields = (NewTySize+DS::PointerSize-1) >> DS::PointerShift;
513 if (NumFields > 256) {
514 foldNodeCompletely();
518 const Type *OldTy = Ty;
521 if (WillBeArray) NodeType |= Array;
524 // Must grow links to be the appropriate size...
525 Links.resize(NumFields);
527 // Merge in the old type now... which is guaranteed to be smaller than the
529 return mergeTypeInfo(OldTy, 0);
532 assert(Offset <= Size &&
533 "Cannot merge something into a part of our type that doesn't exist!");
535 // Find the section of Ty that NewTy overlaps with... first we find the
536 // type that starts at offset Offset.
539 const Type *SubType = Ty;
541 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
543 switch (SubType->getTypeID()) {
544 case Type::StructTyID: {
545 const StructType *STy = cast<StructType>(SubType);
546 const StructLayout &SL = *TD.getStructLayout(STy);
547 unsigned i = SL.getElementContainingOffset(Offset-O);
549 // The offset we are looking for must be in the i'th element...
550 SubType = STy->getElementType(i);
551 O += (unsigned)SL.MemberOffsets[i];
554 case Type::ArrayTyID: {
555 SubType = cast<ArrayType>(SubType)->getElementType();
556 unsigned ElSize = (unsigned)TD.getTypeSize(SubType);
557 unsigned Remainder = (Offset-O) % ElSize;
558 O = Offset-Remainder;
562 if (FoldIfIncompatible) foldNodeCompletely();
567 assert(O == Offset && "Could not achieve the correct offset!");
569 // If we found our type exactly, early exit
570 if (SubType == NewTy) return false;
572 // Differing function types don't require us to merge. They are not values
574 if (isa<FunctionType>(SubType) &&
575 isa<FunctionType>(NewTy)) return false;
577 unsigned SubTypeSize = SubType->isSized() ?
578 (unsigned)TD.getTypeSize(SubType) : 0;
580 // Ok, we are getting desperate now. Check for physical subtyping, where we
581 // just require each element in the node to be compatible.
582 if (NewTySize <= SubTypeSize && NewTySize && NewTySize < 256 &&
583 SubTypeSize && SubTypeSize < 256 &&
584 ElementTypesAreCompatible(NewTy, SubType, !isArray(), TD))
587 // Okay, so we found the leader type at the offset requested. Search the list
588 // of types that starts at this offset. If SubType is currently an array or
589 // structure, the type desired may actually be the first element of the
592 unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
593 while (SubType != NewTy) {
594 const Type *NextSubType = 0;
595 unsigned NextSubTypeSize = 0;
596 unsigned NextPadSize = 0;
597 switch (SubType->getTypeID()) {
598 case Type::StructTyID: {
599 const StructType *STy = cast<StructType>(SubType);
600 const StructLayout &SL = *TD.getStructLayout(STy);
601 if (SL.MemberOffsets.size() > 1)
602 NextPadSize = (unsigned)SL.MemberOffsets[1];
604 NextPadSize = SubTypeSize;
605 NextSubType = STy->getElementType(0);
606 NextSubTypeSize = (unsigned)TD.getTypeSize(NextSubType);
609 case Type::ArrayTyID:
610 NextSubType = cast<ArrayType>(SubType)->getElementType();
611 NextSubTypeSize = (unsigned)TD.getTypeSize(NextSubType);
612 NextPadSize = NextSubTypeSize;
618 if (NextSubType == 0)
619 break; // In the default case, break out of the loop
621 if (NextPadSize < NewTySize)
622 break; // Don't allow shrinking to a smaller type than NewTySize
623 SubType = NextSubType;
624 SubTypeSize = NextSubTypeSize;
625 PadSize = NextPadSize;
628 // If we found the type exactly, return it...
629 if (SubType == NewTy)
632 // Check to see if we have a compatible, but different type...
633 if (NewTySize == SubTypeSize) {
634 // Check to see if this type is obviously convertible... int -> uint f.e.
635 if (NewTy->isLosslesslyConvertibleTo(SubType))
638 // Check to see if we have a pointer & integer mismatch going on here,
639 // loading a pointer as a long, for example.
641 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
642 NewTy->isInteger() && isa<PointerType>(SubType))
644 } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
645 // We are accessing the field, plus some structure padding. Ignore the
646 // structure padding.
651 if (getParentGraph()->retnodes_begin() != getParentGraph()->retnodes_end())
652 M = getParentGraph()->retnodes_begin()->first->getParent();
653 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: ";
654 WriteTypeSymbolic(std::cerr, Ty, M) << "\n due to:";
655 WriteTypeSymbolic(std::cerr, NewTy, M) << " @ " << Offset << "!\n"
657 WriteTypeSymbolic(std::cerr, SubType, M) << "\n\n");
659 if (FoldIfIncompatible) foldNodeCompletely();
665 /// addEdgeTo - Add an edge from the current node to the specified node. This
666 /// can cause merging of nodes in the graph.
668 void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
669 if (NH.isNull()) return; // Nothing to do
671 DSNodeHandle &ExistingEdge = getLink(Offset);
672 if (!ExistingEdge.isNull()) {
673 // Merge the two nodes...
674 ExistingEdge.mergeWith(NH);
675 } else { // No merging to perform...
676 setLink(Offset, NH); // Just force a link in there...
681 /// MergeSortedVectors - Efficiently merge a vector into another vector where
682 /// duplicates are not allowed and both are sorted. This assumes that 'T's are
683 /// efficiently copyable and have sane comparison semantics.
685 static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
686 const std::vector<GlobalValue*> &Src) {
687 // By far, the most common cases will be the simple ones. In these cases,
688 // avoid having to allocate a temporary vector...
690 if (Src.empty()) { // Nothing to merge in...
692 } else if (Dest.empty()) { // Just copy the result in...
694 } else if (Src.size() == 1) { // Insert a single element...
695 const GlobalValue *V = Src[0];
696 std::vector<GlobalValue*>::iterator I =
697 std::lower_bound(Dest.begin(), Dest.end(), V);
698 if (I == Dest.end() || *I != Src[0]) // If not already contained...
699 Dest.insert(I, Src[0]);
700 } else if (Dest.size() == 1) {
701 GlobalValue *Tmp = Dest[0]; // Save value in temporary...
702 Dest = Src; // Copy over list...
703 std::vector<GlobalValue*>::iterator I =
704 std::lower_bound(Dest.begin(), Dest.end(), Tmp);
705 if (I == Dest.end() || *I != Tmp) // If not already contained...
709 // Make a copy to the side of Dest...
710 std::vector<GlobalValue*> Old(Dest);
712 // Make space for all of the type entries now...
713 Dest.resize(Dest.size()+Src.size());
715 // Merge the two sorted ranges together... into Dest.
716 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
718 // Now erase any duplicate entries that may have accumulated into the
719 // vectors (because they were in both of the input sets)
720 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
724 void DSNode::mergeGlobals(const std::vector<GlobalValue*> &RHS) {
725 MergeSortedVectors(Globals, RHS);
728 // MergeNodes - Helper function for DSNode::mergeWith().
729 // This function does the hard work of merging two nodes, CurNodeH
730 // and NH after filtering out trivial cases and making sure that
731 // CurNodeH.offset >= NH.offset.
734 // Since merging may cause either node to go away, we must always
735 // use the node-handles to refer to the nodes. These node handles are
736 // automatically updated during merging, so will always provide access
737 // to the correct node after a merge.
739 void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
740 assert(CurNodeH.getOffset() >= NH.getOffset() &&
741 "This should have been enforced in the caller.");
742 assert(CurNodeH.getNode()->getParentGraph()==NH.getNode()->getParentGraph() &&
743 "Cannot merge two nodes that are not in the same graph!");
745 // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
746 // respect to NH.Offset) is now zero. NOffset is the distance from the base
747 // of our object that N starts from.
749 unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
750 unsigned NSize = NH.getNode()->getSize();
752 // If the two nodes are of different size, and the smaller node has the array
753 // bit set, collapse!
754 if (NSize != CurNodeH.getNode()->getSize()) {
755 #if COLLAPSE_ARRAYS_AGGRESSIVELY
756 if (NSize < CurNodeH.getNode()->getSize()) {
757 if (NH.getNode()->isArray())
758 NH.getNode()->foldNodeCompletely();
759 } else if (CurNodeH.getNode()->isArray()) {
760 NH.getNode()->foldNodeCompletely();
765 // Merge the type entries of the two nodes together...
766 if (NH.getNode()->Ty != Type::VoidTy)
767 CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
768 assert(!CurNodeH.getNode()->isDeadNode());
770 // If we are merging a node with a completely folded node, then both nodes are
771 // now completely folded.
773 if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
774 if (!NH.getNode()->isNodeCompletelyFolded()) {
775 NH.getNode()->foldNodeCompletely();
776 assert(NH.getNode() && NH.getOffset() == 0 &&
777 "folding did not make offset 0?");
778 NOffset = NH.getOffset();
779 NSize = NH.getNode()->getSize();
780 assert(NOffset == 0 && NSize == 1);
782 } else if (NH.getNode()->isNodeCompletelyFolded()) {
783 CurNodeH.getNode()->foldNodeCompletely();
784 assert(CurNodeH.getNode() && CurNodeH.getOffset() == 0 &&
785 "folding did not make offset 0?");
786 NSize = NH.getNode()->getSize();
787 NOffset = NH.getOffset();
788 assert(NOffset == 0 && NSize == 1);
791 DSNode *N = NH.getNode();
792 if (CurNodeH.getNode() == N || N == 0) return;
793 assert(!CurNodeH.getNode()->isDeadNode());
795 // Merge the NodeType information.
796 CurNodeH.getNode()->NodeType |= N->NodeType;
798 // Start forwarding to the new node!
799 N->forwardNode(CurNodeH.getNode(), NOffset);
800 assert(!CurNodeH.getNode()->isDeadNode());
802 // Make all of the outgoing links of N now be outgoing links of CurNodeH.
804 for (unsigned i = 0; i < N->getNumLinks(); ++i) {
805 DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
806 if (Link.getNode()) {
807 // Compute the offset into the current node at which to
808 // merge this link. In the common case, this is a linear
809 // relation to the offset in the original node (with
810 // wrapping), but if the current node gets collapsed due to
811 // recursive merging, we must make sure to merge in all remaining
812 // links at offset zero.
813 unsigned MergeOffset = 0;
814 DSNode *CN = CurNodeH.getNode();
816 MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
817 CN->addEdgeTo(MergeOffset, Link);
821 // Now that there are no outgoing edges, all of the Links are dead.
824 // Merge the globals list...
825 if (!N->Globals.empty()) {
826 CurNodeH.getNode()->mergeGlobals(N->Globals);
828 // Delete the globals from the old node...
829 std::vector<GlobalValue*>().swap(N->Globals);
834 /// mergeWith - Merge this node and the specified node, moving all links to and
835 /// from the argument node into the current node, deleting the node argument.
836 /// Offset indicates what offset the specified node is to be merged into the
839 /// The specified node may be a null pointer (in which case, we update it to
840 /// point to this node).
842 void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
843 DSNode *N = NH.getNode();
844 if (N == this && NH.getOffset() == Offset)
847 // If the RHS is a null node, make it point to this node!
849 NH.mergeWith(DSNodeHandle(this, Offset));
853 assert(!N->isDeadNode() && !isDeadNode());
854 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
857 // We cannot merge two pieces of the same node together, collapse the node
859 DEBUG(std::cerr << "Attempting to merge two chunks of"
860 << " the same node together!\n");
861 foldNodeCompletely();
865 // If both nodes are not at offset 0, make sure that we are merging the node
866 // at an later offset into the node with the zero offset.
868 if (Offset < NH.getOffset()) {
869 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
871 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
872 // If the offsets are the same, merge the smaller node into the bigger node
873 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
877 // Ok, now we can merge the two nodes. Use a static helper that works with
878 // two node handles, since "this" may get merged away at intermediate steps.
879 DSNodeHandle CurNodeH(this, Offset);
880 DSNodeHandle NHCopy(NH);
881 DSNode::MergeNodes(CurNodeH, NHCopy);
885 //===----------------------------------------------------------------------===//
886 // ReachabilityCloner Implementation
887 //===----------------------------------------------------------------------===//
889 DSNodeHandle ReachabilityCloner::getClonedNH(const DSNodeHandle &SrcNH) {
890 if (SrcNH.isNull()) return DSNodeHandle();
891 const DSNode *SN = SrcNH.getNode();
893 DSNodeHandle &NH = NodeMap[SN];
894 if (!NH.isNull()) { // Node already mapped?
895 DSNode *NHN = NH.getNode();
896 return DSNodeHandle(NHN, NH.getOffset()+SrcNH.getOffset());
899 // If SrcNH has globals and the destination graph has one of the same globals,
900 // merge this node with the destination node, which is much more efficient.
901 if (SN->globals_begin() != SN->globals_end()) {
902 DSScalarMap &DestSM = Dest.getScalarMap();
903 for (DSNode::globals_iterator I = SN->globals_begin(),E = SN->globals_end();
905 GlobalValue *GV = *I;
906 DSScalarMap::iterator GI = DestSM.find(GV);
907 if (GI != DestSM.end() && !GI->second.isNull()) {
908 // We found one, use merge instead!
909 merge(GI->second, Src.getNodeForValue(GV));
910 assert(!NH.isNull() && "Didn't merge node!");
911 DSNode *NHN = NH.getNode();
912 return DSNodeHandle(NHN, NH.getOffset()+SrcNH.getOffset());
917 DSNode *DN = new DSNode(*SN, &Dest, true /* Null out all links */);
918 DN->maskNodeTypes(BitsToKeep);
921 // Next, recursively clone all outgoing links as necessary. Note that
922 // adding these links can cause the node to collapse itself at any time, and
923 // the current node may be merged with arbitrary other nodes. For this
924 // reason, we must always go through NH.
926 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
927 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
928 if (!SrcEdge.isNull()) {
929 const DSNodeHandle &DestEdge = getClonedNH(SrcEdge);
930 // Compute the offset into the current node at which to
931 // merge this link. In the common case, this is a linear
932 // relation to the offset in the original node (with
933 // wrapping), but if the current node gets collapsed due to
934 // recursive merging, we must make sure to merge in all remaining
935 // links at offset zero.
936 unsigned MergeOffset = 0;
937 DSNode *CN = NH.getNode();
938 if (CN->getSize() != 1)
939 MergeOffset = ((i << DS::PointerShift)+NH.getOffset()) % CN->getSize();
940 CN->addEdgeTo(MergeOffset, DestEdge);
944 // If this node contains any globals, make sure they end up in the scalar
945 // map with the correct offset.
946 for (DSNode::globals_iterator I = SN->globals_begin(), E = SN->globals_end();
948 GlobalValue *GV = *I;
949 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
950 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
951 assert(DestGNH.getNode() == NH.getNode() &&"Global mapping inconsistent");
952 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
953 DestGNH.getOffset()+SrcGNH.getOffset()));
955 NH.getNode()->mergeGlobals(SN->getGlobalsList());
957 return DSNodeHandle(NH.getNode(), NH.getOffset()+SrcNH.getOffset());
960 void ReachabilityCloner::merge(const DSNodeHandle &NH,
961 const DSNodeHandle &SrcNH) {
962 if (SrcNH.isNull()) return; // Noop
964 // If there is no destination node, just clone the source and assign the
965 // destination node to be it.
966 NH.mergeWith(getClonedNH(SrcNH));
970 // Okay, at this point, we know that we have both a destination and a source
971 // node that need to be merged. Check to see if the source node has already
973 const DSNode *SN = SrcNH.getNode();
974 DSNodeHandle &SCNH = NodeMap[SN]; // SourceClonedNodeHandle
975 if (!SCNH.isNull()) { // Node already cloned?
976 DSNode *SCNHN = SCNH.getNode();
977 NH.mergeWith(DSNodeHandle(SCNHN,
978 SCNH.getOffset()+SrcNH.getOffset()));
979 return; // Nothing to do!
982 // Okay, so the source node has not already been cloned. Instead of creating
983 // a new DSNode, only to merge it into the one we already have, try to perform
984 // the merge in-place. The only case we cannot handle here is when the offset
985 // into the existing node is less than the offset into the virtual node we are
986 // merging in. In this case, we have to extend the existing node, which
987 // requires an allocation anyway.
988 DSNode *DN = NH.getNode(); // Make sure the Offset is up-to-date
989 if (NH.getOffset() >= SrcNH.getOffset()) {
990 if (!DN->isNodeCompletelyFolded()) {
991 // Make sure the destination node is folded if the source node is folded.
992 if (SN->isNodeCompletelyFolded()) {
993 DN->foldNodeCompletely();
995 } else if (SN->getSize() != DN->getSize()) {
996 // If the two nodes are of different size, and the smaller node has the
997 // array bit set, collapse!
998 #if COLLAPSE_ARRAYS_AGGRESSIVELY
999 if (SN->getSize() < DN->getSize()) {
1000 if (SN->isArray()) {
1001 DN->foldNodeCompletely();
1004 } else if (DN->isArray()) {
1005 DN->foldNodeCompletely();
1011 // Merge the type entries of the two nodes together...
1012 if (SN->getType() != Type::VoidTy && !DN->isNodeCompletelyFolded()) {
1013 DN->mergeTypeInfo(SN->getType(), NH.getOffset()-SrcNH.getOffset());
1018 assert(!DN->isDeadNode());
1020 // Merge the NodeType information.
1021 DN->mergeNodeFlags(SN->getNodeFlags() & BitsToKeep);
1023 // Before we start merging outgoing links and updating the scalar map, make
1024 // sure it is known that this is the representative node for the src node.
1025 SCNH = DSNodeHandle(DN, NH.getOffset()-SrcNH.getOffset());
1027 // If the source node contains any globals, make sure they end up in the
1028 // scalar map with the correct offset.
1029 if (SN->globals_begin() != SN->globals_end()) {
1030 // Update the globals in the destination node itself.
1031 DN->mergeGlobals(SN->getGlobalsList());
1033 // Update the scalar map for the graph we are merging the source node
1035 for (DSNode::globals_iterator I = SN->globals_begin(),
1036 E = SN->globals_end(); I != E; ++I) {
1037 GlobalValue *GV = *I;
1038 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
1039 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
1040 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
1041 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
1042 DestGNH.getOffset()+SrcGNH.getOffset()));
1044 NH.getNode()->mergeGlobals(SN->getGlobalsList());
1047 // We cannot handle this case without allocating a temporary node. Fall
1048 // back on being simple.
1049 DSNode *NewDN = new DSNode(*SN, &Dest, true /* Null out all links */);
1050 NewDN->maskNodeTypes(BitsToKeep);
1052 unsigned NHOffset = NH.getOffset();
1053 NH.mergeWith(DSNodeHandle(NewDN, SrcNH.getOffset()));
1055 assert(NH.getNode() &&
1056 (NH.getOffset() > NHOffset ||
1057 (NH.getOffset() == 0 && NH.getNode()->isNodeCompletelyFolded())) &&
1058 "Merging did not adjust the offset!");
1060 // Before we start merging outgoing links and updating the scalar map, make
1061 // sure it is known that this is the representative node for the src node.
1062 SCNH = DSNodeHandle(NH.getNode(), NH.getOffset()-SrcNH.getOffset());
1064 // If the source node contained any globals, make sure to create entries
1065 // in the scalar map for them!
1066 for (DSNode::globals_iterator I = SN->globals_begin(),
1067 E = SN->globals_end(); I != E; ++I) {
1068 GlobalValue *GV = *I;
1069 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
1070 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
1071 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
1072 assert(SrcGNH.getNode() == SN && "Global mapping inconsistent");
1073 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
1074 DestGNH.getOffset()+SrcGNH.getOffset()));
1079 // Next, recursively merge all outgoing links as necessary. Note that
1080 // adding these links can cause the destination node to collapse itself at
1081 // any time, and the current node may be merged with arbitrary other nodes.
1082 // For this reason, we must always go through NH.
1084 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
1085 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
1086 if (!SrcEdge.isNull()) {
1087 // Compute the offset into the current node at which to
1088 // merge this link. In the common case, this is a linear
1089 // relation to the offset in the original node (with
1090 // wrapping), but if the current node gets collapsed due to
1091 // recursive merging, we must make sure to merge in all remaining
1092 // links at offset zero.
1093 DSNode *CN = SCNH.getNode();
1094 unsigned MergeOffset =
1095 ((i << DS::PointerShift)+SCNH.getOffset()) % CN->getSize();
1097 DSNodeHandle Tmp = CN->getLink(MergeOffset);
1098 if (!Tmp.isNull()) {
1099 // Perform the recursive merging. Make sure to create a temporary NH,
1100 // because the Link can disappear in the process of recursive merging.
1101 merge(Tmp, SrcEdge);
1103 Tmp.mergeWith(getClonedNH(SrcEdge));
1104 // Merging this could cause all kinds of recursive things to happen,
1105 // culminating in the current node being eliminated. Since this is
1106 // possible, make sure to reaquire the link from 'CN'.
1108 unsigned MergeOffset = 0;
1109 CN = SCNH.getNode();
1110 MergeOffset = ((i << DS::PointerShift)+SCNH.getOffset()) %CN->getSize();
1111 CN->getLink(MergeOffset).mergeWith(Tmp);
1117 /// mergeCallSite - Merge the nodes reachable from the specified src call
1118 /// site into the nodes reachable from DestCS.
1119 void ReachabilityCloner::mergeCallSite(DSCallSite &DestCS,
1120 const DSCallSite &SrcCS) {
1121 merge(DestCS.getRetVal(), SrcCS.getRetVal());
1122 unsigned MinArgs = DestCS.getNumPtrArgs();
1123 if (SrcCS.getNumPtrArgs() < MinArgs) MinArgs = SrcCS.getNumPtrArgs();
1125 for (unsigned a = 0; a != MinArgs; ++a)
1126 merge(DestCS.getPtrArg(a), SrcCS.getPtrArg(a));
1128 for (unsigned a = MinArgs, e = SrcCS.getNumPtrArgs(); a != e; ++a)
1129 DestCS.addPtrArg(getClonedNH(SrcCS.getPtrArg(a)));
1133 //===----------------------------------------------------------------------===//
1134 // DSCallSite Implementation
1135 //===----------------------------------------------------------------------===//
1137 // Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
1138 Function &DSCallSite::getCaller() const {
1139 return *Site.getInstruction()->getParent()->getParent();
1142 void DSCallSite::InitNH(DSNodeHandle &NH, const DSNodeHandle &Src,
1143 ReachabilityCloner &RC) {
1144 NH = RC.getClonedNH(Src);
1147 //===----------------------------------------------------------------------===//
1148 // DSGraph Implementation
1149 //===----------------------------------------------------------------------===//
1151 /// getFunctionNames - Return a space separated list of the name of the
1152 /// functions in this graph (if any)
1153 std::string DSGraph::getFunctionNames() const {
1154 switch (getReturnNodes().size()) {
1155 case 0: return "Globals graph";
1156 case 1: return retnodes_begin()->first->getName();
1159 for (DSGraph::retnodes_iterator I = retnodes_begin();
1160 I != retnodes_end(); ++I)
1161 Return += I->first->getName() + " ";
1162 Return.erase(Return.end()-1, Return.end()); // Remove last space character
1168 DSGraph::DSGraph(const DSGraph &G, EquivalenceClasses<GlobalValue*> &ECs,
1169 unsigned CloneFlags)
1170 : GlobalsGraph(0), ScalarMap(ECs), TD(G.TD) {
1171 PrintAuxCalls = false;
1172 cloneInto(G, CloneFlags);
1175 DSGraph::~DSGraph() {
1176 FunctionCalls.clear();
1177 AuxFunctionCalls.clear();
1179 ReturnNodes.clear();
1181 // Drop all intra-node references, so that assertions don't fail...
1182 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
1183 NI->dropAllReferences();
1185 // Free all of the nodes.
1189 // dump - Allow inspection of graph in a debugger.
1190 void DSGraph::dump() const { print(std::cerr); }
1193 /// remapLinks - Change all of the Links in the current node according to the
1194 /// specified mapping.
1196 void DSNode::remapLinks(DSGraph::NodeMapTy &OldNodeMap) {
1197 for (unsigned i = 0, e = Links.size(); i != e; ++i)
1198 if (DSNode *N = Links[i].getNode()) {
1199 DSGraph::NodeMapTy::const_iterator ONMI = OldNodeMap.find(N);
1200 if (ONMI != OldNodeMap.end()) {
1201 DSNode *ONMIN = ONMI->second.getNode();
1202 Links[i].setTo(ONMIN, Links[i].getOffset()+ONMI->second.getOffset());
1207 /// addObjectToGraph - This method can be used to add global, stack, and heap
1208 /// objects to the graph. This can be used when updating DSGraphs due to the
1209 /// introduction of new temporary objects. The new object is not pointed to
1210 /// and does not point to any other objects in the graph.
1211 DSNode *DSGraph::addObjectToGraph(Value *Ptr, bool UseDeclaredType) {
1212 assert(isa<PointerType>(Ptr->getType()) && "Ptr is not a pointer!");
1213 const Type *Ty = cast<PointerType>(Ptr->getType())->getElementType();
1214 DSNode *N = new DSNode(UseDeclaredType ? Ty : 0, this);
1215 assert(ScalarMap[Ptr].isNull() && "Object already in this graph!");
1218 if (GlobalValue *GV = dyn_cast<GlobalValue>(Ptr)) {
1220 } else if (MallocInst *MI = dyn_cast<MallocInst>(Ptr)) {
1221 N->setHeapNodeMarker();
1222 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(Ptr)) {
1223 N->setAllocaNodeMarker();
1225 assert(0 && "Illegal memory object input!");
1231 /// cloneInto - Clone the specified DSGraph into the current graph. The
1232 /// translated ScalarMap for the old function is filled into the ScalarMap
1233 /// for the graph, and the translated ReturnNodes map is returned into
1236 /// The CloneFlags member controls various aspects of the cloning process.
1238 void DSGraph::cloneInto(const DSGraph &G, unsigned CloneFlags) {
1239 TIME_REGION(X, "cloneInto");
1240 assert(&G != this && "Cannot clone graph into itself!");
1242 NodeMapTy OldNodeMap;
1244 // Remove alloca or mod/ref bits as specified...
1245 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
1246 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
1247 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
1248 BitsToClear |= DSNode::DEAD; // Clear dead flag...
1250 for (node_const_iterator I = G.node_begin(), E = G.node_end(); I != E; ++I) {
1251 assert(!I->isForwarding() &&
1252 "Forward nodes shouldn't be in node list!");
1253 DSNode *New = new DSNode(*I, this);
1254 New->maskNodeTypes(~BitsToClear);
1255 OldNodeMap[I] = New;
1259 Timer::addPeakMemoryMeasurement();
1262 // Rewrite the links in the new nodes to point into the current graph now.
1263 // Note that we don't loop over the node's list to do this. The problem is
1264 // that remaping links can cause recursive merging to happen, which means
1265 // that node_iterator's can get easily invalidated! Because of this, we
1266 // loop over the OldNodeMap, which contains all of the new nodes as the
1267 // .second element of the map elements. Also note that if we remap a node
1268 // more than once, we won't break anything.
1269 for (NodeMapTy::iterator I = OldNodeMap.begin(), E = OldNodeMap.end();
1271 I->second.getNode()->remapLinks(OldNodeMap);
1273 // Copy the scalar map... merging all of the global nodes...
1274 for (DSScalarMap::const_iterator I = G.ScalarMap.begin(),
1275 E = G.ScalarMap.end(); I != E; ++I) {
1276 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
1277 DSNodeHandle &H = ScalarMap.getRawEntryRef(I->first);
1278 DSNode *MappedNodeN = MappedNode.getNode();
1279 H.mergeWith(DSNodeHandle(MappedNodeN,
1280 I->second.getOffset()+MappedNode.getOffset()));
1283 if (!(CloneFlags & DontCloneCallNodes)) {
1284 // Copy the function calls list.
1285 for (fc_iterator I = G.fc_begin(), E = G.fc_end(); I != E; ++I)
1286 FunctionCalls.push_back(DSCallSite(*I, OldNodeMap));
1289 if (!(CloneFlags & DontCloneAuxCallNodes)) {
1290 // Copy the auxiliary function calls list.
1291 for (afc_iterator I = G.afc_begin(), E = G.afc_end(); I != E; ++I)
1292 AuxFunctionCalls.push_back(DSCallSite(*I, OldNodeMap));
1295 // Map the return node pointers over...
1296 for (retnodes_iterator I = G.retnodes_begin(),
1297 E = G.retnodes_end(); I != E; ++I) {
1298 const DSNodeHandle &Ret = I->second;
1299 DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
1300 DSNode *MappedRetN = MappedRet.getNode();
1301 ReturnNodes.insert(std::make_pair(I->first,
1302 DSNodeHandle(MappedRetN,
1303 MappedRet.getOffset()+Ret.getOffset())));
1307 /// spliceFrom - Logically perform the operation of cloning the RHS graph into
1308 /// this graph, then clearing the RHS graph. Instead of performing this as
1309 /// two seperate operations, do it as a single, much faster, one.
1311 void DSGraph::spliceFrom(DSGraph &RHS) {
1312 // Change all of the nodes in RHS to think we are their parent.
1313 for (NodeListTy::iterator I = RHS.Nodes.begin(), E = RHS.Nodes.end();
1315 I->setParentGraph(this);
1316 // Take all of the nodes.
1317 Nodes.splice(Nodes.end(), RHS.Nodes);
1319 // Take all of the calls.
1320 FunctionCalls.splice(FunctionCalls.end(), RHS.FunctionCalls);
1321 AuxFunctionCalls.splice(AuxFunctionCalls.end(), RHS.AuxFunctionCalls);
1323 // Take all of the return nodes.
1324 ReturnNodes.insert(RHS.ReturnNodes.begin(), RHS.ReturnNodes.end());
1325 RHS.ReturnNodes.clear();
1327 // Merge the scalar map in.
1328 ScalarMap.spliceFrom(RHS.ScalarMap);
1331 /// spliceFrom - Copy all entries from RHS, then clear RHS.
1333 void DSScalarMap::spliceFrom(DSScalarMap &RHS) {
1334 // Special case if this is empty.
1335 if (ValueMap.empty()) {
1336 ValueMap.swap(RHS.ValueMap);
1337 GlobalSet.swap(RHS.GlobalSet);
1339 GlobalSet.insert(RHS.GlobalSet.begin(), RHS.GlobalSet.end());
1340 for (ValueMapTy::iterator I = RHS.ValueMap.begin(), E = RHS.ValueMap.end();
1342 ValueMap[I->first].mergeWith(I->second);
1343 RHS.ValueMap.clear();
1348 /// getFunctionArgumentsForCall - Given a function that is currently in this
1349 /// graph, return the DSNodeHandles that correspond to the pointer-compatible
1350 /// function arguments. The vector is filled in with the return value (or
1351 /// null if it is not pointer compatible), followed by all of the
1352 /// pointer-compatible arguments.
1353 void DSGraph::getFunctionArgumentsForCall(Function *F,
1354 std::vector<DSNodeHandle> &Args) const {
1355 Args.push_back(getReturnNodeFor(*F));
1356 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1358 if (isPointerType(AI->getType())) {
1359 Args.push_back(getNodeForValue(AI));
1360 assert(!Args.back().isNull() && "Pointer argument w/o scalarmap entry!?");
1365 // HackedGraphSCCFinder - This is used to find nodes that have a path from the
1366 // node to a node cloned by the ReachabilityCloner object contained. To be
1367 // extra obnoxious it ignores edges from nodes that are globals, and truncates
1368 // search at RC marked nodes. This is designed as an object so that
1369 // intermediate results can be memoized across invocations of
1370 // PathExistsToClonedNode.
1371 struct HackedGraphSCCFinder {
1372 ReachabilityCloner &RC;
1374 std::vector<const DSNode*> SCCStack;
1375 std::map<const DSNode*, std::pair<unsigned, bool> > NodeInfo;
1377 HackedGraphSCCFinder(ReachabilityCloner &rc) : RC(rc), CurNodeId(1) {
1378 // Remove null pointer as a special case.
1379 NodeInfo[0] = std::make_pair(0, false);
1382 std::pair<unsigned, bool> &VisitForSCCs(const DSNode *N);
1384 bool PathExistsToClonedNode(const DSNode *N) {
1385 return VisitForSCCs(N).second;
1388 bool PathExistsToClonedNode(const DSCallSite &CS) {
1389 if (PathExistsToClonedNode(CS.getRetVal().getNode()))
1391 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
1392 if (PathExistsToClonedNode(CS.getPtrArg(i).getNode()))
1399 std::pair<unsigned, bool> &HackedGraphSCCFinder::
1400 VisitForSCCs(const DSNode *N) {
1401 std::map<const DSNode*, std::pair<unsigned, bool> >::iterator
1402 NodeInfoIt = NodeInfo.lower_bound(N);
1403 if (NodeInfoIt != NodeInfo.end() && NodeInfoIt->first == N)
1404 return NodeInfoIt->second;
1406 unsigned Min = CurNodeId++;
1407 unsigned MyId = Min;
1408 std::pair<unsigned, bool> &ThisNodeInfo =
1409 NodeInfo.insert(NodeInfoIt,
1410 std::make_pair(N, std::make_pair(MyId, false)))->second;
1412 // Base case: if we find a global, this doesn't reach the cloned graph
1414 if (N->isGlobalNode()) {
1415 ThisNodeInfo.second = false;
1416 return ThisNodeInfo;
1419 // Base case: if this does reach the cloned graph portion... it does. :)
1420 if (RC.hasClonedNode(N)) {
1421 ThisNodeInfo.second = true;
1422 return ThisNodeInfo;
1425 SCCStack.push_back(N);
1427 // Otherwise, check all successors.
1428 bool AnyDirectSuccessorsReachClonedNodes = false;
1429 for (DSNode::const_edge_iterator EI = N->edge_begin(), EE = N->edge_end();
1431 std::pair<unsigned, bool> &SuccInfo = VisitForSCCs(EI->getNode());
1432 if (SuccInfo.first < Min) Min = SuccInfo.first;
1433 AnyDirectSuccessorsReachClonedNodes |= SuccInfo.second;
1437 return ThisNodeInfo; // Part of a large SCC. Leave self on stack.
1439 if (SCCStack.back() == N) { // Special case single node SCC.
1440 SCCStack.pop_back();
1441 ThisNodeInfo.second = AnyDirectSuccessorsReachClonedNodes;
1442 return ThisNodeInfo;
1445 // Find out if any direct successors of any node reach cloned nodes.
1446 if (!AnyDirectSuccessorsReachClonedNodes)
1447 for (unsigned i = SCCStack.size()-1; SCCStack[i] != N; --i)
1448 for (DSNode::const_edge_iterator EI = N->edge_begin(), EE = N->edge_end();
1450 if (DSNode *N = EI->getNode())
1451 if (NodeInfo[N].second) {
1452 AnyDirectSuccessorsReachClonedNodes = true;
1456 // If any successor reaches a cloned node, mark all nodes in this SCC as
1457 // reaching the cloned node.
1458 if (AnyDirectSuccessorsReachClonedNodes)
1459 while (SCCStack.back() != N) {
1460 NodeInfo[SCCStack.back()].second = true;
1461 SCCStack.pop_back();
1463 SCCStack.pop_back();
1464 ThisNodeInfo.second = true;
1465 return ThisNodeInfo;
1468 /// mergeInCallFromOtherGraph - This graph merges in the minimal number of
1469 /// nodes from G2 into 'this' graph, merging the bindings specified by the
1470 /// call site (in this graph) with the bindings specified by the vector in G2.
1471 /// The two DSGraphs must be different.
1473 void DSGraph::mergeInGraph(const DSCallSite &CS,
1474 std::vector<DSNodeHandle> &Args,
1475 const DSGraph &Graph, unsigned CloneFlags) {
1476 TIME_REGION(X, "mergeInGraph");
1478 assert((CloneFlags & DontCloneCallNodes) &&
1479 "Doesn't support copying of call nodes!");
1481 // If this is not a recursive call, clone the graph into this graph...
1482 if (&Graph == this) {
1483 // Merge the return value with the return value of the context.
1484 Args[0].mergeWith(CS.getRetVal());
1486 // Resolve all of the function arguments.
1487 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i) {
1488 if (i == Args.size()-1)
1491 // Add the link from the argument scalar to the provided value.
1492 Args[i+1].mergeWith(CS.getPtrArg(i));
1497 // Clone the callee's graph into the current graph, keeping track of where
1498 // scalars in the old graph _used_ to point, and of the new nodes matching
1499 // nodes of the old graph.
1500 ReachabilityCloner RC(*this, Graph, CloneFlags);
1502 // Map the return node pointer over.
1503 if (!CS.getRetVal().isNull())
1504 RC.merge(CS.getRetVal(), Args[0]);
1506 // Map over all of the arguments.
1507 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i) {
1508 if (i == Args.size()-1)
1511 // Add the link from the argument scalar to the provided value.
1512 RC.merge(CS.getPtrArg(i), Args[i+1]);
1515 // We generally don't want to copy global nodes or aux calls from the callee
1516 // graph to the caller graph. However, we have to copy them if there is a
1517 // path from the node to a node we have already copied which does not go
1518 // through another global. Compute the set of node that can reach globals and
1519 // aux call nodes to copy over, then do it.
1520 std::vector<const DSCallSite*> AuxCallToCopy;
1521 std::vector<GlobalValue*> GlobalsToCopy;
1523 // NodesReachCopiedNodes - Memoize results for efficiency. Contains a
1524 // true/false value for every visited node that reaches a copied node without
1525 // going through a global.
1526 HackedGraphSCCFinder SCCFinder(RC);
1528 if (!(CloneFlags & DontCloneAuxCallNodes))
1529 for (afc_iterator I = Graph.afc_begin(), E = Graph.afc_end(); I!=E; ++I)
1530 if (SCCFinder.PathExistsToClonedNode(*I))
1531 AuxCallToCopy.push_back(&*I);
1533 const DSScalarMap &GSM = Graph.getScalarMap();
1534 for (DSScalarMap::global_iterator GI = GSM.global_begin(),
1535 E = GSM.global_end(); GI != E; ++GI) {
1536 DSNode *GlobalNode = Graph.getNodeForValue(*GI).getNode();
1537 for (DSNode::edge_iterator EI = GlobalNode->edge_begin(),
1538 EE = GlobalNode->edge_end(); EI != EE; ++EI)
1539 if (SCCFinder.PathExistsToClonedNode(EI->getNode())) {
1540 GlobalsToCopy.push_back(*GI);
1545 // Copy aux calls that are needed.
1546 for (unsigned i = 0, e = AuxCallToCopy.size(); i != e; ++i)
1547 AuxFunctionCalls.push_back(DSCallSite(*AuxCallToCopy[i], RC));
1549 // Copy globals that are needed.
1550 for (unsigned i = 0, e = GlobalsToCopy.size(); i != e; ++i)
1551 RC.getClonedNH(Graph.getNodeForValue(GlobalsToCopy[i]));
1556 /// mergeInGraph - The method is used for merging graphs together. If the
1557 /// argument graph is not *this, it makes a clone of the specified graph, then
1558 /// merges the nodes specified in the call site with the formal arguments in the
1561 void DSGraph::mergeInGraph(const DSCallSite &CS, Function &F,
1562 const DSGraph &Graph, unsigned CloneFlags) {
1563 // Set up argument bindings.
1564 std::vector<DSNodeHandle> Args;
1565 Graph.getFunctionArgumentsForCall(&F, Args);
1567 mergeInGraph(CS, Args, Graph, CloneFlags);
1570 /// getCallSiteForArguments - Get the arguments and return value bindings for
1571 /// the specified function in the current graph.
1573 DSCallSite DSGraph::getCallSiteForArguments(Function &F) const {
1574 std::vector<DSNodeHandle> Args;
1576 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I)
1577 if (isPointerType(I->getType()))
1578 Args.push_back(getNodeForValue(I));
1580 return DSCallSite(CallSite(), getReturnNodeFor(F), &F, Args);
1583 /// getDSCallSiteForCallSite - Given an LLVM CallSite object that is live in
1584 /// the context of this graph, return the DSCallSite for it.
1585 DSCallSite DSGraph::getDSCallSiteForCallSite(CallSite CS) const {
1586 DSNodeHandle RetVal;
1587 Instruction *I = CS.getInstruction();
1588 if (isPointerType(I->getType()))
1589 RetVal = getNodeForValue(I);
1591 std::vector<DSNodeHandle> Args;
1592 Args.reserve(CS.arg_end()-CS.arg_begin());
1594 // Calculate the arguments vector...
1595 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); I != E; ++I)
1596 if (isPointerType((*I)->getType()))
1597 if (isa<ConstantPointerNull>(*I))
1598 Args.push_back(DSNodeHandle());
1600 Args.push_back(getNodeForValue(*I));
1602 // Add a new function call entry...
1603 if (Function *F = CS.getCalledFunction())
1604 return DSCallSite(CS, RetVal, F, Args);
1606 return DSCallSite(CS, RetVal,
1607 getNodeForValue(CS.getCalledValue()).getNode(), Args);
1612 // markIncompleteNodes - Mark the specified node as having contents that are not
1613 // known with the current analysis we have performed. Because a node makes all
1614 // of the nodes it can reach incomplete if the node itself is incomplete, we
1615 // must recursively traverse the data structure graph, marking all reachable
1616 // nodes as incomplete.
1618 static void markIncompleteNode(DSNode *N) {
1619 // Stop recursion if no node, or if node already marked...
1620 if (N == 0 || N->isIncomplete()) return;
1622 // Actually mark the node
1623 N->setIncompleteMarker();
1625 // Recursively process children...
1626 for (DSNode::edge_iterator I = N->edge_begin(),E = N->edge_end(); I != E; ++I)
1627 if (DSNode *DSN = I->getNode())
1628 markIncompleteNode(DSN);
1631 static void markIncomplete(DSCallSite &Call) {
1632 // Then the return value is certainly incomplete!
1633 markIncompleteNode(Call.getRetVal().getNode());
1635 // All objects pointed to by function arguments are incomplete!
1636 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
1637 markIncompleteNode(Call.getPtrArg(i).getNode());
1640 // markIncompleteNodes - Traverse the graph, identifying nodes that may be
1641 // modified by other functions that have not been resolved yet. This marks
1642 // nodes that are reachable through three sources of "unknownness":
1644 // Global Variables, Function Calls, and Incoming Arguments
1646 // For any node that may have unknown components (because something outside the
1647 // scope of current analysis may have modified it), the 'Incomplete' flag is
1648 // added to the NodeType.
1650 void DSGraph::markIncompleteNodes(unsigned Flags) {
1651 // Mark any incoming arguments as incomplete.
1652 if (Flags & DSGraph::MarkFormalArgs)
1653 for (ReturnNodesTy::iterator FI = ReturnNodes.begin(), E =ReturnNodes.end();
1655 Function &F = *FI->first;
1656 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I)
1657 if (isPointerType(I->getType()))
1658 markIncompleteNode(getNodeForValue(I).getNode());
1659 markIncompleteNode(FI->second.getNode());
1662 // Mark stuff passed into functions calls as being incomplete.
1663 if (!shouldPrintAuxCalls())
1664 for (std::list<DSCallSite>::iterator I = FunctionCalls.begin(),
1665 E = FunctionCalls.end(); I != E; ++I)
1668 for (std::list<DSCallSite>::iterator I = AuxFunctionCalls.begin(),
1669 E = AuxFunctionCalls.end(); I != E; ++I)
1672 // Mark all global nodes as incomplete.
1673 for (DSScalarMap::global_iterator I = ScalarMap.global_begin(),
1674 E = ScalarMap.global_end(); I != E; ++I)
1675 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I))
1676 if (!GV->hasInitializer() || // Always mark external globals incomp.
1677 (!GV->isConstant() && (Flags & DSGraph::IgnoreGlobals) == 0))
1678 markIncompleteNode(ScalarMap[GV].getNode());
1681 static inline void killIfUselessEdge(DSNodeHandle &Edge) {
1682 if (DSNode *N = Edge.getNode()) // Is there an edge?
1683 if (N->getNumReferrers() == 1) // Does it point to a lonely node?
1684 // No interesting info?
1685 if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
1686 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
1687 Edge.setTo(0, 0); // Kill the edge!
1690 static inline bool nodeContainsExternalFunction(const DSNode *N) {
1691 std::vector<Function*> Funcs;
1692 N->addFullFunctionList(Funcs);
1693 for (unsigned i = 0, e = Funcs.size(); i != e; ++i)
1694 if (Funcs[i]->isExternal()) return true;
1698 static void removeIdenticalCalls(std::list<DSCallSite> &Calls) {
1699 // Remove trivially identical function calls
1700 Calls.sort(); // Sort by callee as primary key!
1702 // Scan the call list cleaning it up as necessary...
1703 DSNodeHandle LastCalleeNode;
1704 Function *LastCalleeFunc = 0;
1705 unsigned NumDuplicateCalls = 0;
1706 bool LastCalleeContainsExternalFunction = false;
1708 unsigned NumDeleted = 0;
1709 for (std::list<DSCallSite>::iterator I = Calls.begin(), E = Calls.end();
1711 DSCallSite &CS = *I;
1712 std::list<DSCallSite>::iterator OldIt = I++;
1714 if (!CS.isIndirectCall()) {
1717 DSNode *Callee = CS.getCalleeNode();
1719 // If the Callee is a useless edge, this must be an unreachable call site,
1721 if (Callee->getNumReferrers() == 1 && Callee->isComplete() &&
1722 Callee->getGlobalsList().empty()) { // No useful info?
1724 std::cerr << "WARNING: Useless call site found.\n";
1731 // If the last call site in the list has the same callee as this one, and
1732 // if the callee contains an external function, it will never be
1733 // resolvable, just merge the call sites.
1734 if (!LastCalleeNode.isNull() && LastCalleeNode.getNode() == Callee) {
1735 LastCalleeContainsExternalFunction =
1736 nodeContainsExternalFunction(Callee);
1738 std::list<DSCallSite>::iterator PrevIt = OldIt;
1740 PrevIt->mergeWith(CS);
1742 // No need to keep this call anymore.
1747 LastCalleeNode = Callee;
1751 // If the return value or any arguments point to a void node with no
1752 // information at all in it, and the call node is the only node to point
1753 // to it, remove the edge to the node (killing the node).
1755 killIfUselessEdge(CS.getRetVal());
1756 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
1757 killIfUselessEdge(CS.getPtrArg(a));
1760 // If this call site calls the same function as the last call site, and if
1761 // the function pointer contains an external function, this node will
1762 // never be resolved. Merge the arguments of the call node because no
1763 // information will be lost.
1765 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
1766 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
1767 ++NumDuplicateCalls;
1768 if (NumDuplicateCalls == 1) {
1770 LastCalleeContainsExternalFunction =
1771 nodeContainsExternalFunction(LastCalleeNode);
1773 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
1776 // It is not clear why, but enabling this code makes DSA really
1777 // sensitive to node forwarding. Basically, with this enabled, DSA
1778 // performs different number of inlinings based on which nodes are
1779 // forwarding or not. This is clearly a problem, so this code is
1780 // disabled until this can be resolved.
1782 if (LastCalleeContainsExternalFunction
1785 // This should be more than enough context sensitivity!
1786 // FIXME: Evaluate how many times this is tripped!
1787 NumDuplicateCalls > 20
1791 std::list<DSCallSite>::iterator PrevIt = OldIt;
1793 PrevIt->mergeWith(CS);
1795 // No need to keep this call anymore.
1802 if (CS.isDirectCall()) {
1803 LastCalleeFunc = CS.getCalleeFunc();
1806 LastCalleeNode = CS.getCalleeNode();
1809 NumDuplicateCalls = 0;
1813 if (I != Calls.end() && CS == *I) {
1821 // Resort now that we simplified things.
1824 // Now that we are in sorted order, eliminate duplicates.
1825 std::list<DSCallSite>::iterator CI = Calls.begin(), CE = Calls.end();
1828 std::list<DSCallSite>::iterator OldIt = CI++;
1829 if (CI == CE) break;
1831 // If this call site is now the same as the previous one, we can delete it
1833 if (*OldIt == *CI) {
1840 //Calls.erase(std::unique(Calls.begin(), Calls.end()), Calls.end());
1842 // Track the number of call nodes merged away...
1843 NumCallNodesMerged += NumDeleted;
1845 DEBUG(if (NumDeleted)
1846 std::cerr << "Merged " << NumDeleted << " call nodes.\n";);
1850 // removeTriviallyDeadNodes - After the graph has been constructed, this method
1851 // removes all unreachable nodes that are created because they got merged with
1852 // other nodes in the graph. These nodes will all be trivially unreachable, so
1853 // we don't have to perform any non-trivial analysis here.
1855 void DSGraph::removeTriviallyDeadNodes() {
1856 TIME_REGION(X, "removeTriviallyDeadNodes");
1859 /// NOTE: This code is disabled. This slows down DSA on 177.mesa
1862 // Loop over all of the nodes in the graph, calling getNode on each field.
1863 // This will cause all nodes to update their forwarding edges, causing
1864 // forwarded nodes to be delete-able.
1865 { TIME_REGION(X, "removeTriviallyDeadNodes:node_iterate");
1866 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI) {
1868 for (unsigned l = 0, e = N.getNumLinks(); l != e; ++l)
1869 N.getLink(l*N.getPointerSize()).getNode();
1873 // NOTE: This code is disabled. Though it should, in theory, allow us to
1874 // remove more nodes down below, the scan of the scalar map is incredibly
1875 // expensive for certain programs (with large SCCs). In the future, if we can
1876 // make the scalar map scan more efficient, then we can reenable this.
1877 { TIME_REGION(X, "removeTriviallyDeadNodes:scalarmap");
1879 // Likewise, forward any edges from the scalar nodes. While we are at it,
1880 // clean house a bit.
1881 for (DSScalarMap::iterator I = ScalarMap.begin(),E = ScalarMap.end();I != E;){
1882 I->second.getNode();
1887 bool isGlobalsGraph = !GlobalsGraph;
1889 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E; ) {
1892 // Do not remove *any* global nodes in the globals graph.
1893 // This is a special case because such nodes may not have I, M, R flags set.
1894 if (Node.isGlobalNode() && isGlobalsGraph) {
1899 if (Node.isComplete() && !Node.isModified() && !Node.isRead()) {
1900 // This is a useless node if it has no mod/ref info (checked above),
1901 // outgoing edges (which it cannot, as it is not modified in this
1902 // context), and it has no incoming edges. If it is a global node it may
1903 // have all of these properties and still have incoming edges, due to the
1904 // scalar map, so we check those now.
1906 if (Node.getNumReferrers() == Node.getGlobalsList().size()) {
1907 const std::vector<GlobalValue*> &Globals = Node.getGlobalsList();
1909 // Loop through and make sure all of the globals are referring directly
1911 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1912 DSNode *N = getNodeForValue(Globals[j]).getNode();
1913 assert(N == &Node && "ScalarMap doesn't match globals list!");
1916 // Make sure NumReferrers still agrees, if so, the node is truly dead.
1917 if (Node.getNumReferrers() == Globals.size()) {
1918 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1919 ScalarMap.erase(Globals[j]);
1920 Node.makeNodeDead();
1921 ++NumTrivialGlobalDNE;
1926 if (Node.getNodeFlags() == 0 && Node.hasNoReferrers()) {
1927 // This node is dead!
1928 NI = Nodes.erase(NI); // Erase & remove from node list.
1935 removeIdenticalCalls(FunctionCalls);
1936 removeIdenticalCalls(AuxFunctionCalls);
1940 /// markReachableNodes - This method recursively traverses the specified
1941 /// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
1942 /// to the set, which allows it to only traverse visited nodes once.
1944 void DSNode::markReachableNodes(hash_set<const DSNode*> &ReachableNodes) const {
1945 if (this == 0) return;
1946 assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
1947 if (ReachableNodes.insert(this).second) // Is newly reachable?
1948 for (DSNode::const_edge_iterator I = edge_begin(), E = edge_end();
1950 I->getNode()->markReachableNodes(ReachableNodes);
1953 void DSCallSite::markReachableNodes(hash_set<const DSNode*> &Nodes) const {
1954 getRetVal().getNode()->markReachableNodes(Nodes);
1955 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
1957 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
1958 getPtrArg(i).getNode()->markReachableNodes(Nodes);
1961 // CanReachAliveNodes - Simple graph walker that recursively traverses the graph
1962 // looking for a node that is marked alive. If an alive node is found, return
1963 // true, otherwise return false. If an alive node is reachable, this node is
1964 // marked as alive...
1966 static bool CanReachAliveNodes(DSNode *N, hash_set<const DSNode*> &Alive,
1967 hash_set<const DSNode*> &Visited,
1968 bool IgnoreGlobals) {
1969 if (N == 0) return false;
1970 assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
1972 // If this is a global node, it will end up in the globals graph anyway, so we
1973 // don't need to worry about it.
1974 if (IgnoreGlobals && N->isGlobalNode()) return false;
1976 // If we know that this node is alive, return so!
1977 if (Alive.count(N)) return true;
1979 // Otherwise, we don't think the node is alive yet, check for infinite
1981 if (Visited.count(N)) return false; // Found a cycle
1982 Visited.insert(N); // No recursion, insert into Visited...
1984 for (DSNode::edge_iterator I = N->edge_begin(),E = N->edge_end(); I != E; ++I)
1985 if (CanReachAliveNodes(I->getNode(), Alive, Visited, IgnoreGlobals)) {
1986 N->markReachableNodes(Alive);
1992 // CallSiteUsesAliveArgs - Return true if the specified call site can reach any
1995 static bool CallSiteUsesAliveArgs(const DSCallSite &CS,
1996 hash_set<const DSNode*> &Alive,
1997 hash_set<const DSNode*> &Visited,
1998 bool IgnoreGlobals) {
1999 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited,
2002 if (CS.isIndirectCall() &&
2003 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited, IgnoreGlobals))
2005 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
2006 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited,
2012 // removeDeadNodes - Use a more powerful reachability analysis to eliminate
2013 // subgraphs that are unreachable. This often occurs because the data
2014 // structure doesn't "escape" into it's caller, and thus should be eliminated
2015 // from the caller's graph entirely. This is only appropriate to use when
2018 void DSGraph::removeDeadNodes(unsigned Flags) {
2019 DEBUG(AssertGraphOK(); if (GlobalsGraph) GlobalsGraph->AssertGraphOK());
2021 // Reduce the amount of work we have to do... remove dummy nodes left over by
2023 removeTriviallyDeadNodes();
2025 TIME_REGION(X, "removeDeadNodes");
2027 // FIXME: Merge non-trivially identical call nodes...
2029 // Alive - a set that holds all nodes found to be reachable/alive.
2030 hash_set<const DSNode*> Alive;
2031 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
2033 // Copy and merge all information about globals to the GlobalsGraph if this is
2034 // not a final pass (where unreachable globals are removed).
2036 // Strip all alloca bits since the current function is only for the BU pass.
2037 // Strip all incomplete bits since they are short-lived properties and they
2038 // will be correctly computed when rematerializing nodes into the functions.
2040 ReachabilityCloner GGCloner(*GlobalsGraph, *this, DSGraph::StripAllocaBit |
2041 DSGraph::StripIncompleteBit);
2043 // Mark all nodes reachable by (non-global) scalar nodes as alive...
2044 { TIME_REGION(Y, "removeDeadNodes:scalarscan");
2045 for (DSScalarMap::iterator I = ScalarMap.begin(), E = ScalarMap.end();
2047 if (isa<GlobalValue>(I->first)) { // Keep track of global nodes
2048 assert(!I->second.isNull() && "Null global node?");
2049 assert(I->second.getNode()->isGlobalNode() && "Should be a global node!");
2050 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
2052 // Make sure that all globals are cloned over as roots.
2053 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
2054 DSGraph::ScalarMapTy::iterator SMI =
2055 GlobalsGraph->getScalarMap().find(I->first);
2056 if (SMI != GlobalsGraph->getScalarMap().end())
2057 GGCloner.merge(SMI->second, I->second);
2059 GGCloner.getClonedNH(I->second);
2062 I->second.getNode()->markReachableNodes(Alive);
2066 // The return values are alive as well.
2067 for (ReturnNodesTy::iterator I = ReturnNodes.begin(), E = ReturnNodes.end();
2069 I->second.getNode()->markReachableNodes(Alive);
2071 // Mark any nodes reachable by primary calls as alive...
2072 for (fc_iterator I = fc_begin(), E = fc_end(); I != E; ++I)
2073 I->markReachableNodes(Alive);
2076 // Now find globals and aux call nodes that are already live or reach a live
2077 // value (which makes them live in turn), and continue till no more are found.
2080 hash_set<const DSNode*> Visited;
2081 hash_set<const DSCallSite*> AuxFCallsAlive;
2084 // If any global node points to a non-global that is "alive", the global is
2085 // "alive" as well... Remove it from the GlobalNodes list so we only have
2086 // unreachable globals in the list.
2089 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
2090 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
2091 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited,
2092 Flags & DSGraph::RemoveUnreachableGlobals)) {
2093 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to...
2094 GlobalNodes.pop_back(); // erase efficiently
2098 // Mark only unresolvable call nodes for moving to the GlobalsGraph since
2099 // call nodes that get resolved will be difficult to remove from that graph.
2100 // The final unresolved call nodes must be handled specially at the end of
2101 // the BU pass (i.e., in main or other roots of the call graph).
2102 for (afc_iterator CI = afc_begin(), E = afc_end(); CI != E; ++CI)
2103 if (!AuxFCallsAlive.count(&*CI) &&
2104 (CI->isIndirectCall()
2105 || CallSiteUsesAliveArgs(*CI, Alive, Visited,
2106 Flags & DSGraph::RemoveUnreachableGlobals))) {
2107 CI->markReachableNodes(Alive);
2108 AuxFCallsAlive.insert(&*CI);
2113 // Move dead aux function calls to the end of the list
2114 unsigned CurIdx = 0;
2115 for (std::list<DSCallSite>::iterator CI = AuxFunctionCalls.begin(),
2116 E = AuxFunctionCalls.end(); CI != E; )
2117 if (AuxFCallsAlive.count(&*CI))
2120 // Copy and merge global nodes and dead aux call nodes into the
2121 // GlobalsGraph, and all nodes reachable from those nodes. Update their
2122 // target pointers using the GGCloner.
2124 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
2125 GlobalsGraph->AuxFunctionCalls.push_back(DSCallSite(*CI, GGCloner));
2127 AuxFunctionCalls.erase(CI++);
2130 // We are finally done with the GGCloner so we can destroy it.
2133 // At this point, any nodes which are visited, but not alive, are nodes
2134 // which can be removed. Loop over all nodes, eliminating completely
2135 // unreachable nodes.
2137 std::vector<DSNode*> DeadNodes;
2138 DeadNodes.reserve(Nodes.size());
2139 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E;) {
2141 assert(!N->isForwarding() && "Forwarded node in nodes list?");
2143 if (!Alive.count(N)) {
2145 assert(!N->isForwarding() && "Cannot remove a forwarding node!");
2146 DeadNodes.push_back(N);
2147 N->dropAllReferences();
2152 // Remove all unreachable globals from the ScalarMap.
2153 // If flag RemoveUnreachableGlobals is set, GlobalNodes has only dead nodes.
2154 // In either case, the dead nodes will not be in the set Alive.
2155 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
2156 if (!Alive.count(GlobalNodes[i].second))
2157 ScalarMap.erase(GlobalNodes[i].first);
2159 assert((Flags & DSGraph::RemoveUnreachableGlobals) && "non-dead global");
2161 // Delete all dead nodes now since their referrer counts are zero.
2162 for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
2163 delete DeadNodes[i];
2165 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
2168 void DSGraph::AssertNodeContainsGlobal(const DSNode *N, GlobalValue *GV) const {
2169 assert(std::find(N->globals_begin(),N->globals_end(), GV) !=
2170 N->globals_end() && "Global value not in node!");
2173 void DSGraph::AssertCallSiteInGraph(const DSCallSite &CS) const {
2174 if (CS.isIndirectCall()) {
2175 AssertNodeInGraph(CS.getCalleeNode());
2177 if (CS.getNumPtrArgs() && CS.getCalleeNode() == CS.getPtrArg(0).getNode() &&
2178 CS.getCalleeNode() && CS.getCalleeNode()->getGlobals().empty())
2179 std::cerr << "WARNING: WEIRD CALL SITE FOUND!\n";
2182 AssertNodeInGraph(CS.getRetVal().getNode());
2183 for (unsigned j = 0, e = CS.getNumPtrArgs(); j != e; ++j)
2184 AssertNodeInGraph(CS.getPtrArg(j).getNode());
2187 void DSGraph::AssertCallNodesInGraph() const {
2188 for (fc_iterator I = fc_begin(), E = fc_end(); I != E; ++I)
2189 AssertCallSiteInGraph(*I);
2191 void DSGraph::AssertAuxCallNodesInGraph() const {
2192 for (afc_iterator I = afc_begin(), E = afc_end(); I != E; ++I)
2193 AssertCallSiteInGraph(*I);
2196 void DSGraph::AssertGraphOK() const {
2197 for (node_const_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
2200 for (ScalarMapTy::const_iterator I = ScalarMap.begin(),
2201 E = ScalarMap.end(); I != E; ++I) {
2202 assert(!I->second.isNull() && "Null node in scalarmap!");
2203 AssertNodeInGraph(I->second.getNode());
2204 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
2205 assert(I->second.getNode()->isGlobalNode() &&
2206 "Global points to node, but node isn't global?");
2207 AssertNodeContainsGlobal(I->second.getNode(), GV);
2210 AssertCallNodesInGraph();
2211 AssertAuxCallNodesInGraph();
2213 // Check that all pointer arguments to any functions in this graph have
2215 for (ReturnNodesTy::const_iterator RI = ReturnNodes.begin(),
2216 E = ReturnNodes.end();
2218 Function &F = *RI->first;
2219 for (Function::arg_iterator AI = F.arg_begin(); AI != F.arg_end(); ++AI)
2220 if (isPointerType(AI->getType()))
2221 assert(!getNodeForValue(AI).isNull() &&
2222 "Pointer argument must be in the scalar map!");
2226 /// computeNodeMapping - Given roots in two different DSGraphs, traverse the
2227 /// nodes reachable from the two graphs, computing the mapping of nodes from the
2228 /// first to the second graph. This mapping may be many-to-one (i.e. the first
2229 /// graph may have multiple nodes representing one node in the second graph),
2230 /// but it will not work if there is a one-to-many or many-to-many mapping.
2232 void DSGraph::computeNodeMapping(const DSNodeHandle &NH1,
2233 const DSNodeHandle &NH2, NodeMapTy &NodeMap,
2234 bool StrictChecking) {
2235 DSNode *N1 = NH1.getNode(), *N2 = NH2.getNode();
2236 if (N1 == 0 || N2 == 0) return;
2238 DSNodeHandle &Entry = NodeMap[N1];
2239 if (!Entry.isNull()) {
2240 // Termination of recursion!
2241 if (StrictChecking) {
2242 assert(Entry.getNode() == N2 && "Inconsistent mapping detected!");
2243 assert((Entry.getOffset() == (NH2.getOffset()-NH1.getOffset()) ||
2244 Entry.getNode()->isNodeCompletelyFolded()) &&
2245 "Inconsistent mapping detected!");
2250 Entry.setTo(N2, NH2.getOffset()-NH1.getOffset());
2252 // Loop over all of the fields that N1 and N2 have in common, recursively
2253 // mapping the edges together now.
2254 int N2Idx = NH2.getOffset()-NH1.getOffset();
2255 unsigned N2Size = N2->getSize();
2256 if (N2Size == 0) return; // No edges to map to.
2258 for (unsigned i = 0, e = N1->getSize(); i < e; i += DS::PointerSize) {
2259 const DSNodeHandle &N1NH = N1->getLink(i);
2260 // Don't call N2->getLink if not needed (avoiding crash if N2Idx is not
2262 if (!N1NH.isNull()) {
2263 if (unsigned(N2Idx)+i < N2Size)
2264 computeNodeMapping(N1NH, N2->getLink(N2Idx+i), NodeMap);
2266 computeNodeMapping(N1NH,
2267 N2->getLink(unsigned(N2Idx+i) % N2Size), NodeMap);
2273 /// computeGToGGMapping - Compute the mapping of nodes in the global graph to
2274 /// nodes in this graph.
2275 void DSGraph::computeGToGGMapping(NodeMapTy &NodeMap) {
2276 DSGraph &GG = *getGlobalsGraph();
2278 DSScalarMap &SM = getScalarMap();
2279 for (DSScalarMap::global_iterator I = SM.global_begin(),
2280 E = SM.global_end(); I != E; ++I)
2281 DSGraph::computeNodeMapping(SM[*I], GG.getNodeForValue(*I), NodeMap);
2284 /// computeGGToGMapping - Compute the mapping of nodes in the global graph to
2285 /// nodes in this graph. Note that any uses of this method are probably bugs,
2286 /// unless it is known that the globals graph has been merged into this graph!
2287 void DSGraph::computeGGToGMapping(InvNodeMapTy &InvNodeMap) {
2289 computeGToGGMapping(NodeMap);
2291 while (!NodeMap.empty()) {
2292 InvNodeMap.insert(std::make_pair(NodeMap.begin()->second,
2293 NodeMap.begin()->first));
2294 NodeMap.erase(NodeMap.begin());
2299 /// computeCalleeCallerMapping - Given a call from a function in the current
2300 /// graph to the 'Callee' function (which lives in 'CalleeGraph'), compute the
2301 /// mapping of nodes from the callee to nodes in the caller.
2302 void DSGraph::computeCalleeCallerMapping(DSCallSite CS, const Function &Callee,
2303 DSGraph &CalleeGraph,
2304 NodeMapTy &NodeMap) {
2306 DSCallSite CalleeArgs =
2307 CalleeGraph.getCallSiteForArguments(const_cast<Function&>(Callee));
2309 computeNodeMapping(CalleeArgs.getRetVal(), CS.getRetVal(), NodeMap);
2311 unsigned NumArgs = CS.getNumPtrArgs();
2312 if (NumArgs > CalleeArgs.getNumPtrArgs())
2313 NumArgs = CalleeArgs.getNumPtrArgs();
2315 for (unsigned i = 0; i != NumArgs; ++i)
2316 computeNodeMapping(CalleeArgs.getPtrArg(i), CS.getPtrArg(i), NodeMap);
2318 // Map the nodes that are pointed to by globals.
2319 DSScalarMap &CalleeSM = CalleeGraph.getScalarMap();
2320 DSScalarMap &CallerSM = getScalarMap();
2322 if (CalleeSM.global_size() >= CallerSM.global_size()) {
2323 for (DSScalarMap::global_iterator GI = CallerSM.global_begin(),
2324 E = CallerSM.global_end(); GI != E; ++GI)
2325 if (CalleeSM.global_count(*GI))
2326 computeNodeMapping(CalleeSM[*GI], CallerSM[*GI], NodeMap);
2328 for (DSScalarMap::global_iterator GI = CalleeSM.global_begin(),
2329 E = CalleeSM.global_end(); GI != E; ++GI)
2330 if (CallerSM.global_count(*GI))
2331 computeNodeMapping(CalleeSM[*GI], CallerSM[*GI], NodeMap);