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"
33 #define COLLAPSE_ARRAYS_AGGRESSIVELY 0
36 Statistic<> NumFolds ("dsa", "Number of nodes completely folded");
37 Statistic<> NumCallNodesMerged("dsa", "Number of call nodes merged");
38 Statistic<> NumNodeAllocated ("dsa", "Number of nodes allocated");
39 Statistic<> NumDNE ("dsa", "Number of nodes removed by reachability");
40 Statistic<> NumTrivialDNE ("dsa", "Number of nodes trivially removed");
41 Statistic<> NumTrivialGlobalDNE("dsa", "Number of globals trivially removed");
42 static cl::opt<unsigned>
43 DSAFieldLimit("dsa-field-limit", cl::Hidden,
44 cl::desc("Number of fields to track before collapsing a node"),
49 #define TIME_REGION(VARNAME, DESC) \
50 NamedRegionTimer VARNAME(DESC)
52 #define TIME_REGION(VARNAME, DESC)
57 /// isForwarding - Return true if this NodeHandle is forwarding to another
59 bool DSNodeHandle::isForwarding() const {
60 return N && N->isForwarding();
63 DSNode *DSNodeHandle::HandleForwarding() const {
64 assert(N->isForwarding() && "Can only be invoked if forwarding!");
66 // Handle node forwarding here!
67 DSNode *Next = N->ForwardNH.getNode(); // Cause recursive shrinkage
68 Offset += N->ForwardNH.getOffset();
70 if (--N->NumReferrers == 0) {
71 // Removing the last referrer to the node, sever the forwarding link
77 if (N->Size <= Offset) {
78 assert(N->Size <= 1 && "Forwarded to shrunk but not collapsed node?");
84 //===----------------------------------------------------------------------===//
85 // DSScalarMap Implementation
86 //===----------------------------------------------------------------------===//
88 DSNodeHandle &DSScalarMap::AddGlobal(GlobalValue *GV) {
89 assert(ValueMap.count(GV) == 0 && "GV already exists!");
91 // If the node doesn't exist, check to see if it's a global that is
92 // equated to another global in the program.
93 EquivalenceClasses<GlobalValue*>::iterator ECI = GlobalECs.findValue(GV);
94 if (ECI != GlobalECs.end()) {
95 GlobalValue *Leader = *GlobalECs.findLeader(ECI);
98 iterator I = ValueMap.find(GV);
99 if (I != ValueMap.end())
104 // Okay, this is either not an equivalenced global or it is the leader, it
105 // will be inserted into the scalar map now.
106 GlobalSet.insert(GV);
108 return ValueMap.insert(std::make_pair(GV, DSNodeHandle())).first->second;
112 //===----------------------------------------------------------------------===//
113 // DSNode Implementation
114 //===----------------------------------------------------------------------===//
116 DSNode::DSNode(const Type *T, DSGraph *G)
117 : NumReferrers(0), Size(0), ParentGraph(G), Ty(Type::VoidTy), NodeType(0) {
118 // Add the type entry if it is specified...
119 if (T) mergeTypeInfo(T, 0);
120 if (G) G->addNode(this);
124 // DSNode copy constructor... do not copy over the referrers list!
125 DSNode::DSNode(const DSNode &N, DSGraph *G, bool NullLinks)
126 : NumReferrers(0), Size(N.Size), ParentGraph(G),
127 Ty(N.Ty), Globals(N.Globals), NodeType(N.NodeType) {
131 Links.resize(N.Links.size()); // Create the appropriate number of null links
136 /// getTargetData - Get the target data object used to construct this node.
138 const TargetData &DSNode::getTargetData() const {
139 return ParentGraph->getTargetData();
142 void DSNode::assertOK() const {
143 assert((Ty != Type::VoidTy ||
144 Ty == Type::VoidTy && (Size == 0 ||
145 (NodeType & DSNode::Array))) &&
148 assert(ParentGraph && "Node has no parent?");
149 const DSScalarMap &SM = ParentGraph->getScalarMap();
150 for (unsigned i = 0, e = Globals.size(); i != e; ++i) {
151 assert(SM.global_count(Globals[i]));
152 assert(SM.find(Globals[i])->second.getNode() == this);
156 /// forwardNode - Mark this node as being obsolete, and all references to it
157 /// should be forwarded to the specified node and offset.
159 void DSNode::forwardNode(DSNode *To, unsigned Offset) {
160 assert(this != To && "Cannot forward a node to itself!");
161 assert(ForwardNH.isNull() && "Already forwarding from this node!");
162 if (To->Size <= 1) Offset = 0;
163 assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
164 "Forwarded offset is wrong!");
165 ForwardNH.setTo(To, Offset);
170 // Remove this node from the parent graph's Nodes list.
171 ParentGraph->unlinkNode(this);
175 // addGlobal - Add an entry for a global value to the Globals list. This also
176 // marks the node with the 'G' flag if it does not already have it.
178 void DSNode::addGlobal(GlobalValue *GV) {
179 // First, check to make sure this is the leader if the global is in an
180 // equivalence class.
181 GV = getParentGraph()->getScalarMap().getLeaderForGlobal(GV);
183 // Keep the list sorted.
184 std::vector<GlobalValue*>::iterator I =
185 std::lower_bound(Globals.begin(), Globals.end(), GV);
187 if (I == Globals.end() || *I != GV) {
188 Globals.insert(I, GV);
189 NodeType |= GlobalNode;
193 // removeGlobal - Remove the specified global that is explicitly in the globals
195 void DSNode::removeGlobal(GlobalValue *GV) {
196 std::vector<GlobalValue*>::iterator I =
197 std::lower_bound(Globals.begin(), Globals.end(), GV);
198 assert(I != Globals.end() && *I == GV && "Global not in node!");
202 /// foldNodeCompletely - If we determine that this node has some funny
203 /// behavior happening to it that we cannot represent, we fold it down to a
204 /// single, completely pessimistic, node. This node is represented as a
205 /// single byte with a single TypeEntry of "void".
207 void DSNode::foldNodeCompletely() {
208 if (isNodeCompletelyFolded()) return; // If this node is already folded...
212 // If this node has a size that is <= 1, we don't need to create a forwarding
214 if (getSize() <= 1) {
215 NodeType |= DSNode::Array;
218 assert(Links.size() <= 1 && "Size is 1, but has more links?");
221 // Create the node we are going to forward to. This is required because
222 // some referrers may have an offset that is > 0. By forcing them to
223 // forward, the forwarder has the opportunity to correct the offset.
224 DSNode *DestNode = new DSNode(0, ParentGraph);
225 DestNode->NodeType = NodeType|DSNode::Array;
226 DestNode->Ty = Type::VoidTy;
228 DestNode->Globals.swap(Globals);
230 // Start forwarding to the destination node...
231 forwardNode(DestNode, 0);
233 if (!Links.empty()) {
234 DestNode->Links.reserve(1);
236 DSNodeHandle NH(DestNode);
237 DestNode->Links.push_back(Links[0]);
239 // If we have links, merge all of our outgoing links together...
240 for (unsigned i = Links.size()-1; i != 0; --i)
241 NH.getNode()->Links[0].mergeWith(Links[i]);
244 DestNode->Links.resize(1);
249 /// isNodeCompletelyFolded - Return true if this node has been completely
250 /// folded down to something that can never be expanded, effectively losing
251 /// all of the field sensitivity that may be present in the node.
253 bool DSNode::isNodeCompletelyFolded() const {
254 return getSize() == 1 && Ty == Type::VoidTy && isArray();
257 /// addFullGlobalsList - Compute the full set of global values that are
258 /// represented by this node. Unlike getGlobalsList(), this requires fair
259 /// amount of work to compute, so don't treat this method call as free.
260 void DSNode::addFullGlobalsList(std::vector<GlobalValue*> &List) const {
261 if (globals_begin() == globals_end()) return;
263 EquivalenceClasses<GlobalValue*> &EC = getParentGraph()->getGlobalECs();
265 for (globals_iterator I = globals_begin(), E = globals_end(); I != E; ++I) {
266 EquivalenceClasses<GlobalValue*>::iterator ECI = EC.findValue(*I);
270 List.insert(List.end(), EC.member_begin(ECI), EC.member_end());
274 /// addFullFunctionList - Identical to addFullGlobalsList, but only return the
275 /// functions in the full list.
276 void DSNode::addFullFunctionList(std::vector<Function*> &List) const {
277 if (globals_begin() == globals_end()) return;
279 EquivalenceClasses<GlobalValue*> &EC = getParentGraph()->getGlobalECs();
281 for (globals_iterator I = globals_begin(), E = globals_end(); I != E; ++I) {
282 EquivalenceClasses<GlobalValue*>::iterator ECI = EC.findValue(*I);
283 if (ECI == EC.end()) {
284 if (Function *F = dyn_cast<Function>(*I))
287 for (EquivalenceClasses<GlobalValue*>::member_iterator MI =
288 EC.member_begin(ECI), E = EC.member_end(); MI != E; ++MI)
289 if (Function *F = dyn_cast<Function>(*MI))
296 /// TypeElementWalker Class - Used for implementation of physical subtyping...
298 class TypeElementWalker {
303 StackState(const Type *T, unsigned Off = 0)
304 : Ty(T), Offset(Off), Idx(0) {}
307 std::vector<StackState> Stack;
308 const TargetData &TD;
310 TypeElementWalker(const Type *T, const TargetData &td) : TD(td) {
315 bool isDone() const { return Stack.empty(); }
316 const Type *getCurrentType() const { return Stack.back().Ty; }
317 unsigned getCurrentOffset() const { return Stack.back().Offset; }
319 void StepToNextType() {
320 PopStackAndAdvance();
325 /// PopStackAndAdvance - Pop the current element off of the stack and
326 /// advance the underlying element to the next contained member.
327 void PopStackAndAdvance() {
328 assert(!Stack.empty() && "Cannot pop an empty stack!");
330 while (!Stack.empty()) {
331 StackState &SS = Stack.back();
332 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
334 if (SS.Idx != ST->getNumElements()) {
335 const StructLayout *SL = TD.getStructLayout(ST);
337 unsigned(SL->MemberOffsets[SS.Idx]-SL->MemberOffsets[SS.Idx-1]);
340 Stack.pop_back(); // At the end of the structure
342 const ArrayType *AT = cast<ArrayType>(SS.Ty);
344 if (SS.Idx != AT->getNumElements()) {
345 SS.Offset += unsigned(TD.getTypeSize(AT->getElementType()));
348 Stack.pop_back(); // At the end of the array
353 /// StepToLeaf - Used by physical subtyping to move to the first leaf node
354 /// on the type stack.
356 if (Stack.empty()) return;
357 while (!Stack.empty() && !Stack.back().Ty->isFirstClassType()) {
358 StackState &SS = Stack.back();
359 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
360 if (ST->getNumElements() == 0) {
362 PopStackAndAdvance();
364 // Step into the structure...
365 assert(SS.Idx < ST->getNumElements());
366 const StructLayout *SL = TD.getStructLayout(ST);
367 Stack.push_back(StackState(ST->getElementType(SS.Idx),
368 SS.Offset+unsigned(SL->MemberOffsets[SS.Idx])));
371 const ArrayType *AT = cast<ArrayType>(SS.Ty);
372 if (AT->getNumElements() == 0) {
374 PopStackAndAdvance();
376 // Step into the array...
377 assert(SS.Idx < AT->getNumElements());
378 Stack.push_back(StackState(AT->getElementType(),
380 unsigned(TD.getTypeSize(AT->getElementType()))));
386 } // end anonymous namespace
388 /// ElementTypesAreCompatible - Check to see if the specified types are
389 /// "physically" compatible. If so, return true, else return false. We only
390 /// have to check the fields in T1: T2 may be larger than T1. If AllowLargerT1
391 /// is true, then we also allow a larger T1.
393 static bool ElementTypesAreCompatible(const Type *T1, const Type *T2,
394 bool AllowLargerT1, const TargetData &TD){
395 TypeElementWalker T1W(T1, TD), T2W(T2, TD);
397 while (!T1W.isDone() && !T2W.isDone()) {
398 if (T1W.getCurrentOffset() != T2W.getCurrentOffset())
401 const Type *T1 = T1W.getCurrentType();
402 const Type *T2 = T2W.getCurrentType();
403 if (T1 != T2 && !T1->isLosslesslyConvertibleTo(T2))
406 T1W.StepToNextType();
407 T2W.StepToNextType();
410 return AllowLargerT1 || T1W.isDone();
414 /// mergeTypeInfo - This method merges the specified type into the current node
415 /// at the specified offset. This may update the current node's type record if
416 /// this gives more information to the node, it may do nothing to the node if
417 /// this information is already known, or it may merge the node completely (and
418 /// return true) if the information is incompatible with what is already known.
420 /// This method returns true if the node is completely folded, otherwise false.
422 bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset,
423 bool FoldIfIncompatible) {
424 const TargetData &TD = getTargetData();
425 // Check to make sure the Size member is up-to-date. Size can be one of the
427 // Size = 0, Ty = Void: Nothing is known about this node.
428 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
429 // Size = 1, Ty = Void, Array = 1: The node is collapsed
430 // Otherwise, sizeof(Ty) = Size
432 assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
433 (Size == 0 && !Ty->isSized() && !isArray()) ||
434 (Size == 1 && Ty == Type::VoidTy && isArray()) ||
435 (Size == 0 && !Ty->isSized() && !isArray()) ||
436 (TD.getTypeSize(Ty) == Size)) &&
437 "Size member of DSNode doesn't match the type structure!");
438 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
440 if (Offset == 0 && NewTy == Ty)
441 return false; // This should be a common case, handle it efficiently
443 // Return true immediately if the node is completely folded.
444 if (isNodeCompletelyFolded()) return true;
446 // If this is an array type, eliminate the outside arrays because they won't
447 // be used anyway. This greatly reduces the size of large static arrays used
448 // as global variables, for example.
450 bool WillBeArray = false;
451 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
452 // FIXME: we might want to keep small arrays, but must be careful about
453 // things like: [2 x [10000 x int*]]
454 NewTy = AT->getElementType();
458 // Figure out how big the new type we're merging in is...
459 unsigned NewTySize = NewTy->isSized() ? (unsigned)TD.getTypeSize(NewTy) : 0;
461 // Otherwise check to see if we can fold this type into the current node. If
462 // we can't, we fold the node completely, if we can, we potentially update our
465 if (Ty == Type::VoidTy) {
466 // If this is the first type that this node has seen, just accept it without
468 assert(Offset == 0 && !isArray() &&
469 "Cannot have an offset into a void node!");
471 // If this node would have to have an unreasonable number of fields, just
472 // collapse it. This can occur for fortran common blocks, which have stupid
473 // things like { [100000000 x double], [1000000 x double] }.
474 unsigned NumFields = (NewTySize+DS::PointerSize-1) >> DS::PointerShift;
475 if (NumFields > DSAFieldLimit) {
476 foldNodeCompletely();
482 if (WillBeArray) NodeType |= Array;
485 // Calculate the number of outgoing links from this node.
486 Links.resize(NumFields);
490 // Handle node expansion case here...
491 if (Offset+NewTySize > Size) {
492 // It is illegal to grow this node if we have treated it as an array of
495 if (FoldIfIncompatible) foldNodeCompletely();
499 // If this node would have to have an unreasonable number of fields, just
500 // collapse it. This can occur for fortran common blocks, which have stupid
501 // things like { [100000000 x double], [1000000 x double] }.
502 unsigned NumFields = (NewTySize+Offset+DS::PointerSize-1) >> DS::PointerShift;
503 if (NumFields > DSAFieldLimit) {
504 foldNodeCompletely();
509 //handle some common cases:
510 // Ty: struct { t1, t2, t3, t4, ..., tn}
511 // NewTy: struct { offset, stuff...}
512 // try merge with NewTy: struct {t1, t2, stuff...} if offset lands exactly on a field in Ty
513 if (isa<StructType>(NewTy) && isa<StructType>(Ty)) {
514 DEBUG(std::cerr << "Ty: " << *Ty << "\nNewTy: " << *NewTy << "@" << Offset << "\n");
516 const StructType *STy = cast<StructType>(Ty);
517 const StructLayout &SL = *TD.getStructLayout(STy);
518 unsigned i = SL.getElementContainingOffset(Offset);
519 //Either we hit it exactly or give up
520 if (SL.MemberOffsets[i] != Offset) {
521 if (FoldIfIncompatible) foldNodeCompletely();
524 std::vector<const Type*> nt;
525 for (unsigned x = 0; x < i; ++x)
526 nt.push_back(STy->getElementType(x));
527 STy = cast<StructType>(NewTy);
528 nt.insert(nt.end(), STy->element_begin(), STy->element_end());
530 STy = StructType::get(nt);
531 DEBUG(std::cerr << "Trying with: " << *STy << "\n");
532 return mergeTypeInfo(STy, 0);
535 //Ty: struct { t1, t2, t3 ... tn}
537 //try merge with NewTy: struct : {t1, t2, T} if offset lands on a field in Ty
538 if (isa<StructType>(Ty)) {
539 DEBUG(std::cerr << "Ty: " << *Ty << "\nNewTy: " << *NewTy << "@" << Offset << "\n");
541 const StructType *STy = cast<StructType>(Ty);
542 const StructLayout &SL = *TD.getStructLayout(STy);
543 unsigned i = SL.getElementContainingOffset(Offset);
544 //Either we hit it exactly or give up
545 if (SL.MemberOffsets[i] != Offset) {
546 if (FoldIfIncompatible) foldNodeCompletely();
549 std::vector<const Type*> nt;
550 for (unsigned x = 0; x < i; ++x)
551 nt.push_back(STy->getElementType(x));
554 STy = StructType::get(nt);
555 DEBUG(std::cerr << "Trying with: " << *STy << "\n");
556 return mergeTypeInfo(STy, 0);
559 std::cerr << "UNIMP: Trying to merge a growth type into "
560 << "offset != 0: Collapsing!\n";
562 if (FoldIfIncompatible) foldNodeCompletely();
568 // Okay, the situation is nice and simple, we are trying to merge a type in
569 // at offset 0 that is bigger than our current type. Implement this by
570 // switching to the new type and then merge in the smaller one, which should
571 // hit the other code path here. If the other code path decides it's not
572 // ok, it will collapse the node as appropriate.
575 const Type *OldTy = Ty;
578 if (WillBeArray) NodeType |= Array;
581 // Must grow links to be the appropriate size...
582 Links.resize(NumFields);
584 // Merge in the old type now... which is guaranteed to be smaller than the
586 return mergeTypeInfo(OldTy, 0);
589 assert(Offset <= Size &&
590 "Cannot merge something into a part of our type that doesn't exist!");
592 // Find the section of Ty that NewTy overlaps with... first we find the
593 // type that starts at offset Offset.
596 const Type *SubType = Ty;
598 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
600 switch (SubType->getTypeID()) {
601 case Type::StructTyID: {
602 const StructType *STy = cast<StructType>(SubType);
603 const StructLayout &SL = *TD.getStructLayout(STy);
604 unsigned i = SL.getElementContainingOffset(Offset-O);
606 // The offset we are looking for must be in the i'th element...
607 SubType = STy->getElementType(i);
608 O += (unsigned)SL.MemberOffsets[i];
611 case Type::ArrayTyID: {
612 SubType = cast<ArrayType>(SubType)->getElementType();
613 unsigned ElSize = (unsigned)TD.getTypeSize(SubType);
614 unsigned Remainder = (Offset-O) % ElSize;
615 O = Offset-Remainder;
619 if (FoldIfIncompatible) foldNodeCompletely();
624 assert(O == Offset && "Could not achieve the correct offset!");
626 // If we found our type exactly, early exit
627 if (SubType == NewTy) return false;
629 // Differing function types don't require us to merge. They are not values
631 if (isa<FunctionType>(SubType) &&
632 isa<FunctionType>(NewTy)) return false;
634 unsigned SubTypeSize = SubType->isSized() ?
635 (unsigned)TD.getTypeSize(SubType) : 0;
637 // Ok, we are getting desperate now. Check for physical subtyping, where we
638 // just require each element in the node to be compatible.
639 if (NewTySize <= SubTypeSize && NewTySize && NewTySize < 256 &&
640 SubTypeSize && SubTypeSize < 256 &&
641 ElementTypesAreCompatible(NewTy, SubType, !isArray(), TD))
644 // Okay, so we found the leader type at the offset requested. Search the list
645 // of types that starts at this offset. If SubType is currently an array or
646 // structure, the type desired may actually be the first element of the
649 unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
650 while (SubType != NewTy) {
651 const Type *NextSubType = 0;
652 unsigned NextSubTypeSize = 0;
653 unsigned NextPadSize = 0;
654 switch (SubType->getTypeID()) {
655 case Type::StructTyID: {
656 const StructType *STy = cast<StructType>(SubType);
657 const StructLayout &SL = *TD.getStructLayout(STy);
658 if (SL.MemberOffsets.size() > 1)
659 NextPadSize = (unsigned)SL.MemberOffsets[1];
661 NextPadSize = SubTypeSize;
662 NextSubType = STy->getElementType(0);
663 NextSubTypeSize = (unsigned)TD.getTypeSize(NextSubType);
666 case Type::ArrayTyID:
667 NextSubType = cast<ArrayType>(SubType)->getElementType();
668 NextSubTypeSize = (unsigned)TD.getTypeSize(NextSubType);
669 NextPadSize = NextSubTypeSize;
675 if (NextSubType == 0)
676 break; // In the default case, break out of the loop
678 if (NextPadSize < NewTySize)
679 break; // Don't allow shrinking to a smaller type than NewTySize
680 SubType = NextSubType;
681 SubTypeSize = NextSubTypeSize;
682 PadSize = NextPadSize;
685 // If we found the type exactly, return it...
686 if (SubType == NewTy)
689 // Check to see if we have a compatible, but different type...
690 if (NewTySize == SubTypeSize) {
691 // Check to see if this type is obviously convertible... int -> uint f.e.
692 if (NewTy->isLosslesslyConvertibleTo(SubType))
695 // Check to see if we have a pointer & integer mismatch going on here,
696 // loading a pointer as a long, for example.
698 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
699 NewTy->isInteger() && isa<PointerType>(SubType))
701 } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
702 // We are accessing the field, plus some structure padding. Ignore the
703 // structure padding.
708 if (getParentGraph()->retnodes_begin() != getParentGraph()->retnodes_end())
709 M = getParentGraph()->retnodes_begin()->first->getParent();
710 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: ";
711 WriteTypeSymbolic(std::cerr, Ty, M) << "\n due to:";
712 WriteTypeSymbolic(std::cerr, NewTy, M) << " @ " << Offset << "!\n"
714 WriteTypeSymbolic(std::cerr, SubType, M) << "\n\n");
716 if (FoldIfIncompatible) foldNodeCompletely();
722 /// addEdgeTo - Add an edge from the current node to the specified node. This
723 /// can cause merging of nodes in the graph.
725 void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
726 if (NH.isNull()) return; // Nothing to do
728 if (isNodeCompletelyFolded())
731 DSNodeHandle &ExistingEdge = getLink(Offset);
732 if (!ExistingEdge.isNull()) {
733 // Merge the two nodes...
734 ExistingEdge.mergeWith(NH);
735 } else { // No merging to perform...
736 setLink(Offset, NH); // Just force a link in there...
741 /// MergeSortedVectors - Efficiently merge a vector into another vector where
742 /// duplicates are not allowed and both are sorted. This assumes that 'T's are
743 /// efficiently copyable and have sane comparison semantics.
745 static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
746 const std::vector<GlobalValue*> &Src) {
747 // By far, the most common cases will be the simple ones. In these cases,
748 // avoid having to allocate a temporary vector...
750 if (Src.empty()) { // Nothing to merge in...
752 } else if (Dest.empty()) { // Just copy the result in...
754 } else if (Src.size() == 1) { // Insert a single element...
755 const GlobalValue *V = Src[0];
756 std::vector<GlobalValue*>::iterator I =
757 std::lower_bound(Dest.begin(), Dest.end(), V);
758 if (I == Dest.end() || *I != Src[0]) // If not already contained...
759 Dest.insert(I, Src[0]);
760 } else if (Dest.size() == 1) {
761 GlobalValue *Tmp = Dest[0]; // Save value in temporary...
762 Dest = Src; // Copy over list...
763 std::vector<GlobalValue*>::iterator I =
764 std::lower_bound(Dest.begin(), Dest.end(), Tmp);
765 if (I == Dest.end() || *I != Tmp) // If not already contained...
769 // Make a copy to the side of Dest...
770 std::vector<GlobalValue*> Old(Dest);
772 // Make space for all of the type entries now...
773 Dest.resize(Dest.size()+Src.size());
775 // Merge the two sorted ranges together... into Dest.
776 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
778 // Now erase any duplicate entries that may have accumulated into the
779 // vectors (because they were in both of the input sets)
780 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
784 void DSNode::mergeGlobals(const std::vector<GlobalValue*> &RHS) {
785 MergeSortedVectors(Globals, RHS);
788 // MergeNodes - Helper function for DSNode::mergeWith().
789 // This function does the hard work of merging two nodes, CurNodeH
790 // and NH after filtering out trivial cases and making sure that
791 // CurNodeH.offset >= NH.offset.
794 // Since merging may cause either node to go away, we must always
795 // use the node-handles to refer to the nodes. These node handles are
796 // automatically updated during merging, so will always provide access
797 // to the correct node after a merge.
799 void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
800 assert(CurNodeH.getOffset() >= NH.getOffset() &&
801 "This should have been enforced in the caller.");
802 assert(CurNodeH.getNode()->getParentGraph()==NH.getNode()->getParentGraph() &&
803 "Cannot merge two nodes that are not in the same graph!");
805 // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
806 // respect to NH.Offset) is now zero. NOffset is the distance from the base
807 // of our object that N starts from.
809 unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
810 unsigned NSize = NH.getNode()->getSize();
812 // If the two nodes are of different size, and the smaller node has the array
813 // bit set, collapse!
814 if (NSize != CurNodeH.getNode()->getSize()) {
815 #if COLLAPSE_ARRAYS_AGGRESSIVELY
816 if (NSize < CurNodeH.getNode()->getSize()) {
817 if (NH.getNode()->isArray())
818 NH.getNode()->foldNodeCompletely();
819 } else if (CurNodeH.getNode()->isArray()) {
820 NH.getNode()->foldNodeCompletely();
825 // Merge the type entries of the two nodes together...
826 if (NH.getNode()->Ty != Type::VoidTy)
827 CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
828 assert(!CurNodeH.getNode()->isDeadNode());
830 // If we are merging a node with a completely folded node, then both nodes are
831 // now completely folded.
833 if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
834 if (!NH.getNode()->isNodeCompletelyFolded()) {
835 NH.getNode()->foldNodeCompletely();
836 assert(NH.getNode() && NH.getOffset() == 0 &&
837 "folding did not make offset 0?");
838 NOffset = NH.getOffset();
839 NSize = NH.getNode()->getSize();
840 assert(NOffset == 0 && NSize == 1);
842 } else if (NH.getNode()->isNodeCompletelyFolded()) {
843 CurNodeH.getNode()->foldNodeCompletely();
844 assert(CurNodeH.getNode() && CurNodeH.getOffset() == 0 &&
845 "folding did not make offset 0?");
846 NSize = NH.getNode()->getSize();
847 NOffset = NH.getOffset();
848 assert(NOffset == 0 && NSize == 1);
851 DSNode *N = NH.getNode();
852 if (CurNodeH.getNode() == N || N == 0) return;
853 assert(!CurNodeH.getNode()->isDeadNode());
855 // Merge the NodeType information.
856 CurNodeH.getNode()->NodeType |= N->NodeType;
858 // Start forwarding to the new node!
859 N->forwardNode(CurNodeH.getNode(), NOffset);
860 assert(!CurNodeH.getNode()->isDeadNode());
862 // Make all of the outgoing links of N now be outgoing links of CurNodeH.
864 for (unsigned i = 0; i < N->getNumLinks(); ++i) {
865 DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
866 if (Link.getNode()) {
867 // Compute the offset into the current node at which to
868 // merge this link. In the common case, this is a linear
869 // relation to the offset in the original node (with
870 // wrapping), but if the current node gets collapsed due to
871 // recursive merging, we must make sure to merge in all remaining
872 // links at offset zero.
873 unsigned MergeOffset = 0;
874 DSNode *CN = CurNodeH.getNode();
876 MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
877 CN->addEdgeTo(MergeOffset, Link);
881 // Now that there are no outgoing edges, all of the Links are dead.
884 // Merge the globals list...
885 if (!N->Globals.empty()) {
886 CurNodeH.getNode()->mergeGlobals(N->Globals);
888 // Delete the globals from the old node...
889 std::vector<GlobalValue*>().swap(N->Globals);
894 /// mergeWith - Merge this node and the specified node, moving all links to and
895 /// from the argument node into the current node, deleting the node argument.
896 /// Offset indicates what offset the specified node is to be merged into the
899 /// The specified node may be a null pointer (in which case, we update it to
900 /// point to this node).
902 void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
903 DSNode *N = NH.getNode();
904 if (N == this && NH.getOffset() == Offset)
907 // If the RHS is a null node, make it point to this node!
909 NH.mergeWith(DSNodeHandle(this, Offset));
913 assert(!N->isDeadNode() && !isDeadNode());
914 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
917 // We cannot merge two pieces of the same node together, collapse the node
919 DEBUG(std::cerr << "Attempting to merge two chunks of"
920 << " the same node together!\n");
921 foldNodeCompletely();
925 // If both nodes are not at offset 0, make sure that we are merging the node
926 // at an later offset into the node with the zero offset.
928 if (Offset < NH.getOffset()) {
929 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
931 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
932 // If the offsets are the same, merge the smaller node into the bigger node
933 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
937 // Ok, now we can merge the two nodes. Use a static helper that works with
938 // two node handles, since "this" may get merged away at intermediate steps.
939 DSNodeHandle CurNodeH(this, Offset);
940 DSNodeHandle NHCopy(NH);
941 if (CurNodeH.getOffset() >= NHCopy.getOffset())
942 DSNode::MergeNodes(CurNodeH, NHCopy);
944 DSNode::MergeNodes(NHCopy, CurNodeH);
948 //===----------------------------------------------------------------------===//
949 // ReachabilityCloner Implementation
950 //===----------------------------------------------------------------------===//
952 DSNodeHandle ReachabilityCloner::getClonedNH(const DSNodeHandle &SrcNH) {
953 if (SrcNH.isNull()) return DSNodeHandle();
954 const DSNode *SN = SrcNH.getNode();
956 DSNodeHandle &NH = NodeMap[SN];
957 if (!NH.isNull()) { // Node already mapped?
958 DSNode *NHN = NH.getNode();
959 return DSNodeHandle(NHN, NH.getOffset()+SrcNH.getOffset());
962 // If SrcNH has globals and the destination graph has one of the same globals,
963 // merge this node with the destination node, which is much more efficient.
964 if (SN->globals_begin() != SN->globals_end()) {
965 DSScalarMap &DestSM = Dest.getScalarMap();
966 for (DSNode::globals_iterator I = SN->globals_begin(),E = SN->globals_end();
968 GlobalValue *GV = *I;
969 DSScalarMap::iterator GI = DestSM.find(GV);
970 if (GI != DestSM.end() && !GI->second.isNull()) {
971 // We found one, use merge instead!
972 merge(GI->second, Src.getNodeForValue(GV));
973 assert(!NH.isNull() && "Didn't merge node!");
974 DSNode *NHN = NH.getNode();
975 return DSNodeHandle(NHN, NH.getOffset()+SrcNH.getOffset());
980 DSNode *DN = new DSNode(*SN, &Dest, true /* Null out all links */);
981 DN->maskNodeTypes(BitsToKeep);
984 // Next, recursively clone all outgoing links as necessary. Note that
985 // adding these links can cause the node to collapse itself at any time, and
986 // the current node may be merged with arbitrary other nodes. For this
987 // reason, we must always go through NH.
989 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
990 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
991 if (!SrcEdge.isNull()) {
992 const DSNodeHandle &DestEdge = getClonedNH(SrcEdge);
993 // Compute the offset into the current node at which to
994 // merge this link. In the common case, this is a linear
995 // relation to the offset in the original node (with
996 // wrapping), but if the current node gets collapsed due to
997 // recursive merging, we must make sure to merge in all remaining
998 // links at offset zero.
999 unsigned MergeOffset = 0;
1000 DSNode *CN = NH.getNode();
1001 if (CN->getSize() != 1)
1002 MergeOffset = ((i << DS::PointerShift)+NH.getOffset()) % CN->getSize();
1003 CN->addEdgeTo(MergeOffset, DestEdge);
1007 // If this node contains any globals, make sure they end up in the scalar
1008 // map with the correct offset.
1009 for (DSNode::globals_iterator I = SN->globals_begin(), E = SN->globals_end();
1011 GlobalValue *GV = *I;
1012 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
1013 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
1014 assert(DestGNH.getNode() == NH.getNode() &&"Global mapping inconsistent");
1015 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
1016 DestGNH.getOffset()+SrcGNH.getOffset()));
1018 NH.getNode()->mergeGlobals(SN->getGlobalsList());
1020 return DSNodeHandle(NH.getNode(), NH.getOffset()+SrcNH.getOffset());
1023 void ReachabilityCloner::merge(const DSNodeHandle &NH,
1024 const DSNodeHandle &SrcNH) {
1025 if (SrcNH.isNull()) return; // Noop
1027 // If there is no destination node, just clone the source and assign the
1028 // destination node to be it.
1029 NH.mergeWith(getClonedNH(SrcNH));
1033 // Okay, at this point, we know that we have both a destination and a source
1034 // node that need to be merged. Check to see if the source node has already
1036 const DSNode *SN = SrcNH.getNode();
1037 DSNodeHandle &SCNH = NodeMap[SN]; // SourceClonedNodeHandle
1038 if (!SCNH.isNull()) { // Node already cloned?
1039 DSNode *SCNHN = SCNH.getNode();
1040 NH.mergeWith(DSNodeHandle(SCNHN,
1041 SCNH.getOffset()+SrcNH.getOffset()));
1042 return; // Nothing to do!
1045 // Okay, so the source node has not already been cloned. Instead of creating
1046 // a new DSNode, only to merge it into the one we already have, try to perform
1047 // the merge in-place. The only case we cannot handle here is when the offset
1048 // into the existing node is less than the offset into the virtual node we are
1049 // merging in. In this case, we have to extend the existing node, which
1050 // requires an allocation anyway.
1051 DSNode *DN = NH.getNode(); // Make sure the Offset is up-to-date
1052 if (NH.getOffset() >= SrcNH.getOffset()) {
1053 if (!DN->isNodeCompletelyFolded()) {
1054 // Make sure the destination node is folded if the source node is folded.
1055 if (SN->isNodeCompletelyFolded()) {
1056 DN->foldNodeCompletely();
1058 } else if (SN->getSize() != DN->getSize()) {
1059 // If the two nodes are of different size, and the smaller node has the
1060 // array bit set, collapse!
1061 #if COLLAPSE_ARRAYS_AGGRESSIVELY
1062 if (SN->getSize() < DN->getSize()) {
1063 if (SN->isArray()) {
1064 DN->foldNodeCompletely();
1067 } else if (DN->isArray()) {
1068 DN->foldNodeCompletely();
1074 // Merge the type entries of the two nodes together...
1075 if (SN->getType() != Type::VoidTy && !DN->isNodeCompletelyFolded()) {
1076 DN->mergeTypeInfo(SN->getType(), NH.getOffset()-SrcNH.getOffset());
1081 assert(!DN->isDeadNode());
1083 // Merge the NodeType information.
1084 DN->mergeNodeFlags(SN->getNodeFlags() & BitsToKeep);
1086 // Before we start merging outgoing links and updating the scalar map, make
1087 // sure it is known that this is the representative node for the src node.
1088 SCNH = DSNodeHandle(DN, NH.getOffset()-SrcNH.getOffset());
1090 // If the source node contains any globals, make sure they end up in the
1091 // scalar map with the correct offset.
1092 if (SN->globals_begin() != SN->globals_end()) {
1093 // Update the globals in the destination node itself.
1094 DN->mergeGlobals(SN->getGlobalsList());
1096 // Update the scalar map for the graph we are merging the source node
1098 for (DSNode::globals_iterator I = SN->globals_begin(),
1099 E = SN->globals_end(); I != E; ++I) {
1100 GlobalValue *GV = *I;
1101 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
1102 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
1103 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
1104 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
1105 DestGNH.getOffset()+SrcGNH.getOffset()));
1107 NH.getNode()->mergeGlobals(SN->getGlobalsList());
1110 // We cannot handle this case without allocating a temporary node. Fall
1111 // back on being simple.
1112 DSNode *NewDN = new DSNode(*SN, &Dest, true /* Null out all links */);
1113 NewDN->maskNodeTypes(BitsToKeep);
1115 unsigned NHOffset = NH.getOffset();
1116 NH.mergeWith(DSNodeHandle(NewDN, SrcNH.getOffset()));
1118 assert(NH.getNode() &&
1119 (NH.getOffset() > NHOffset ||
1120 (NH.getOffset() == 0 && NH.getNode()->isNodeCompletelyFolded())) &&
1121 "Merging did not adjust the offset!");
1123 // Before we start merging outgoing links and updating the scalar map, make
1124 // sure it is known that this is the representative node for the src node.
1125 SCNH = DSNodeHandle(NH.getNode(), NH.getOffset()-SrcNH.getOffset());
1127 // If the source node contained any globals, make sure to create entries
1128 // in the scalar map for them!
1129 for (DSNode::globals_iterator I = SN->globals_begin(),
1130 E = SN->globals_end(); I != E; ++I) {
1131 GlobalValue *GV = *I;
1132 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
1133 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
1134 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
1135 assert(SrcGNH.getNode() == SN && "Global mapping inconsistent");
1136 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
1137 DestGNH.getOffset()+SrcGNH.getOffset()));
1142 // Next, recursively merge all outgoing links as necessary. Note that
1143 // adding these links can cause the destination node to collapse itself at
1144 // any time, and the current node may be merged with arbitrary other nodes.
1145 // For this reason, we must always go through NH.
1147 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
1148 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
1149 if (!SrcEdge.isNull()) {
1150 // Compute the offset into the current node at which to
1151 // merge this link. In the common case, this is a linear
1152 // relation to the offset in the original node (with
1153 // wrapping), but if the current node gets collapsed due to
1154 // recursive merging, we must make sure to merge in all remaining
1155 // links at offset zero.
1156 DSNode *CN = SCNH.getNode();
1157 unsigned MergeOffset =
1158 ((i << DS::PointerShift)+SCNH.getOffset()) % CN->getSize();
1160 DSNodeHandle Tmp = CN->getLink(MergeOffset);
1161 if (!Tmp.isNull()) {
1162 // Perform the recursive merging. Make sure to create a temporary NH,
1163 // because the Link can disappear in the process of recursive merging.
1164 merge(Tmp, SrcEdge);
1166 Tmp.mergeWith(getClonedNH(SrcEdge));
1167 // Merging this could cause all kinds of recursive things to happen,
1168 // culminating in the current node being eliminated. Since this is
1169 // possible, make sure to reaquire the link from 'CN'.
1171 unsigned MergeOffset = 0;
1172 CN = SCNH.getNode();
1173 MergeOffset = ((i << DS::PointerShift)+SCNH.getOffset()) %CN->getSize();
1174 CN->getLink(MergeOffset).mergeWith(Tmp);
1180 /// mergeCallSite - Merge the nodes reachable from the specified src call
1181 /// site into the nodes reachable from DestCS.
1182 void ReachabilityCloner::mergeCallSite(DSCallSite &DestCS,
1183 const DSCallSite &SrcCS) {
1184 merge(DestCS.getRetVal(), SrcCS.getRetVal());
1185 unsigned MinArgs = DestCS.getNumPtrArgs();
1186 if (SrcCS.getNumPtrArgs() < MinArgs) MinArgs = SrcCS.getNumPtrArgs();
1188 for (unsigned a = 0; a != MinArgs; ++a)
1189 merge(DestCS.getPtrArg(a), SrcCS.getPtrArg(a));
1191 for (unsigned a = MinArgs, e = SrcCS.getNumPtrArgs(); a != e; ++a)
1192 DestCS.addPtrArg(getClonedNH(SrcCS.getPtrArg(a)));
1196 //===----------------------------------------------------------------------===//
1197 // DSCallSite Implementation
1198 //===----------------------------------------------------------------------===//
1200 // Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
1201 Function &DSCallSite::getCaller() const {
1202 return *Site.getInstruction()->getParent()->getParent();
1205 void DSCallSite::InitNH(DSNodeHandle &NH, const DSNodeHandle &Src,
1206 ReachabilityCloner &RC) {
1207 NH = RC.getClonedNH(Src);
1210 //===----------------------------------------------------------------------===//
1211 // DSGraph Implementation
1212 //===----------------------------------------------------------------------===//
1214 /// getFunctionNames - Return a space separated list of the name of the
1215 /// functions in this graph (if any)
1216 std::string DSGraph::getFunctionNames() const {
1217 switch (getReturnNodes().size()) {
1218 case 0: return "Globals graph";
1219 case 1: return retnodes_begin()->first->getName();
1222 for (DSGraph::retnodes_iterator I = retnodes_begin();
1223 I != retnodes_end(); ++I)
1224 Return += I->first->getName() + " ";
1225 Return.erase(Return.end()-1, Return.end()); // Remove last space character
1231 DSGraph::DSGraph(const DSGraph &G, EquivalenceClasses<GlobalValue*> &ECs,
1232 unsigned CloneFlags)
1233 : GlobalsGraph(0), ScalarMap(ECs), TD(G.TD) {
1234 PrintAuxCalls = false;
1235 cloneInto(G, CloneFlags);
1238 DSGraph::~DSGraph() {
1239 FunctionCalls.clear();
1240 AuxFunctionCalls.clear();
1242 ReturnNodes.clear();
1244 // Drop all intra-node references, so that assertions don't fail...
1245 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
1246 NI->dropAllReferences();
1248 // Free all of the nodes.
1252 // dump - Allow inspection of graph in a debugger.
1253 void DSGraph::dump() const { print(std::cerr); }
1256 /// remapLinks - Change all of the Links in the current node according to the
1257 /// specified mapping.
1259 void DSNode::remapLinks(DSGraph::NodeMapTy &OldNodeMap) {
1260 for (unsigned i = 0, e = Links.size(); i != e; ++i)
1261 if (DSNode *N = Links[i].getNode()) {
1262 DSGraph::NodeMapTy::const_iterator ONMI = OldNodeMap.find(N);
1263 if (ONMI != OldNodeMap.end()) {
1264 DSNode *ONMIN = ONMI->second.getNode();
1265 Links[i].setTo(ONMIN, Links[i].getOffset()+ONMI->second.getOffset());
1270 /// addObjectToGraph - This method can be used to add global, stack, and heap
1271 /// objects to the graph. This can be used when updating DSGraphs due to the
1272 /// introduction of new temporary objects. The new object is not pointed to
1273 /// and does not point to any other objects in the graph.
1274 DSNode *DSGraph::addObjectToGraph(Value *Ptr, bool UseDeclaredType) {
1275 assert(isa<PointerType>(Ptr->getType()) && "Ptr is not a pointer!");
1276 const Type *Ty = cast<PointerType>(Ptr->getType())->getElementType();
1277 DSNode *N = new DSNode(UseDeclaredType ? Ty : 0, this);
1278 assert(ScalarMap[Ptr].isNull() && "Object already in this graph!");
1281 if (GlobalValue *GV = dyn_cast<GlobalValue>(Ptr)) {
1283 } else if (MallocInst *MI = dyn_cast<MallocInst>(Ptr)) {
1284 N->setHeapNodeMarker();
1285 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(Ptr)) {
1286 N->setAllocaNodeMarker();
1288 assert(0 && "Illegal memory object input!");
1294 /// cloneInto - Clone the specified DSGraph into the current graph. The
1295 /// translated ScalarMap for the old function is filled into the ScalarMap
1296 /// for the graph, and the translated ReturnNodes map is returned into
1299 /// The CloneFlags member controls various aspects of the cloning process.
1301 void DSGraph::cloneInto(const DSGraph &G, unsigned CloneFlags) {
1302 TIME_REGION(X, "cloneInto");
1303 assert(&G != this && "Cannot clone graph into itself!");
1305 NodeMapTy OldNodeMap;
1307 // Remove alloca or mod/ref bits as specified...
1308 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
1309 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
1310 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
1311 BitsToClear |= DSNode::DEAD; // Clear dead flag...
1313 for (node_const_iterator I = G.node_begin(), E = G.node_end(); I != E; ++I) {
1314 assert(!I->isForwarding() &&
1315 "Forward nodes shouldn't be in node list!");
1316 DSNode *New = new DSNode(*I, this);
1317 New->maskNodeTypes(~BitsToClear);
1318 OldNodeMap[I] = New;
1322 Timer::addPeakMemoryMeasurement();
1325 // Rewrite the links in the new nodes to point into the current graph now.
1326 // Note that we don't loop over the node's list to do this. The problem is
1327 // that remaping links can cause recursive merging to happen, which means
1328 // that node_iterator's can get easily invalidated! Because of this, we
1329 // loop over the OldNodeMap, which contains all of the new nodes as the
1330 // .second element of the map elements. Also note that if we remap a node
1331 // more than once, we won't break anything.
1332 for (NodeMapTy::iterator I = OldNodeMap.begin(), E = OldNodeMap.end();
1334 I->second.getNode()->remapLinks(OldNodeMap);
1336 // Copy the scalar map... merging all of the global nodes...
1337 for (DSScalarMap::const_iterator I = G.ScalarMap.begin(),
1338 E = G.ScalarMap.end(); I != E; ++I) {
1339 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
1340 DSNodeHandle &H = ScalarMap.getRawEntryRef(I->first);
1341 DSNode *MappedNodeN = MappedNode.getNode();
1342 H.mergeWith(DSNodeHandle(MappedNodeN,
1343 I->second.getOffset()+MappedNode.getOffset()));
1346 if (!(CloneFlags & DontCloneCallNodes)) {
1347 // Copy the function calls list.
1348 for (fc_iterator I = G.fc_begin(), E = G.fc_end(); I != E; ++I)
1349 FunctionCalls.push_back(DSCallSite(*I, OldNodeMap));
1352 if (!(CloneFlags & DontCloneAuxCallNodes)) {
1353 // Copy the auxiliary function calls list.
1354 for (afc_iterator I = G.afc_begin(), E = G.afc_end(); I != E; ++I)
1355 AuxFunctionCalls.push_back(DSCallSite(*I, OldNodeMap));
1358 // Map the return node pointers over...
1359 for (retnodes_iterator I = G.retnodes_begin(),
1360 E = G.retnodes_end(); I != E; ++I) {
1361 const DSNodeHandle &Ret = I->second;
1362 DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
1363 DSNode *MappedRetN = MappedRet.getNode();
1364 ReturnNodes.insert(std::make_pair(I->first,
1365 DSNodeHandle(MappedRetN,
1366 MappedRet.getOffset()+Ret.getOffset())));
1370 /// spliceFrom - Logically perform the operation of cloning the RHS graph into
1371 /// this graph, then clearing the RHS graph. Instead of performing this as
1372 /// two seperate operations, do it as a single, much faster, one.
1374 void DSGraph::spliceFrom(DSGraph &RHS) {
1375 // Change all of the nodes in RHS to think we are their parent.
1376 for (NodeListTy::iterator I = RHS.Nodes.begin(), E = RHS.Nodes.end();
1378 I->setParentGraph(this);
1379 // Take all of the nodes.
1380 Nodes.splice(Nodes.end(), RHS.Nodes);
1382 // Take all of the calls.
1383 FunctionCalls.splice(FunctionCalls.end(), RHS.FunctionCalls);
1384 AuxFunctionCalls.splice(AuxFunctionCalls.end(), RHS.AuxFunctionCalls);
1386 // Take all of the return nodes.
1387 if (ReturnNodes.empty()) {
1388 ReturnNodes.swap(RHS.ReturnNodes);
1390 ReturnNodes.insert(RHS.ReturnNodes.begin(), RHS.ReturnNodes.end());
1391 RHS.ReturnNodes.clear();
1394 // Merge the scalar map in.
1395 ScalarMap.spliceFrom(RHS.ScalarMap);
1398 /// spliceFrom - Copy all entries from RHS, then clear RHS.
1400 void DSScalarMap::spliceFrom(DSScalarMap &RHS) {
1401 // Special case if this is empty.
1402 if (ValueMap.empty()) {
1403 ValueMap.swap(RHS.ValueMap);
1404 GlobalSet.swap(RHS.GlobalSet);
1406 GlobalSet.insert(RHS.GlobalSet.begin(), RHS.GlobalSet.end());
1407 for (ValueMapTy::iterator I = RHS.ValueMap.begin(), E = RHS.ValueMap.end();
1409 ValueMap[I->first].mergeWith(I->second);
1410 RHS.ValueMap.clear();
1415 /// getFunctionArgumentsForCall - Given a function that is currently in this
1416 /// graph, return the DSNodeHandles that correspond to the pointer-compatible
1417 /// function arguments. The vector is filled in with the return value (or
1418 /// null if it is not pointer compatible), followed by all of the
1419 /// pointer-compatible arguments.
1420 void DSGraph::getFunctionArgumentsForCall(Function *F,
1421 std::vector<DSNodeHandle> &Args) const {
1422 Args.push_back(getReturnNodeFor(*F));
1423 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1425 if (isPointerType(AI->getType())) {
1426 Args.push_back(getNodeForValue(AI));
1427 assert(!Args.back().isNull() && "Pointer argument w/o scalarmap entry!?");
1432 // HackedGraphSCCFinder - This is used to find nodes that have a path from the
1433 // node to a node cloned by the ReachabilityCloner object contained. To be
1434 // extra obnoxious it ignores edges from nodes that are globals, and truncates
1435 // search at RC marked nodes. This is designed as an object so that
1436 // intermediate results can be memoized across invocations of
1437 // PathExistsToClonedNode.
1438 struct HackedGraphSCCFinder {
1439 ReachabilityCloner &RC;
1441 std::vector<const DSNode*> SCCStack;
1442 std::map<const DSNode*, std::pair<unsigned, bool> > NodeInfo;
1444 HackedGraphSCCFinder(ReachabilityCloner &rc) : RC(rc), CurNodeId(1) {
1445 // Remove null pointer as a special case.
1446 NodeInfo[0] = std::make_pair(0, false);
1449 std::pair<unsigned, bool> &VisitForSCCs(const DSNode *N);
1451 bool PathExistsToClonedNode(const DSNode *N) {
1452 return VisitForSCCs(N).second;
1455 bool PathExistsToClonedNode(const DSCallSite &CS) {
1456 if (PathExistsToClonedNode(CS.getRetVal().getNode()))
1458 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
1459 if (PathExistsToClonedNode(CS.getPtrArg(i).getNode()))
1466 std::pair<unsigned, bool> &HackedGraphSCCFinder::
1467 VisitForSCCs(const DSNode *N) {
1468 std::map<const DSNode*, std::pair<unsigned, bool> >::iterator
1469 NodeInfoIt = NodeInfo.lower_bound(N);
1470 if (NodeInfoIt != NodeInfo.end() && NodeInfoIt->first == N)
1471 return NodeInfoIt->second;
1473 unsigned Min = CurNodeId++;
1474 unsigned MyId = Min;
1475 std::pair<unsigned, bool> &ThisNodeInfo =
1476 NodeInfo.insert(NodeInfoIt,
1477 std::make_pair(N, std::make_pair(MyId, false)))->second;
1479 // Base case: if we find a global, this doesn't reach the cloned graph
1481 if (N->isGlobalNode()) {
1482 ThisNodeInfo.second = false;
1483 return ThisNodeInfo;
1486 // Base case: if this does reach the cloned graph portion... it does. :)
1487 if (RC.hasClonedNode(N)) {
1488 ThisNodeInfo.second = true;
1489 return ThisNodeInfo;
1492 SCCStack.push_back(N);
1494 // Otherwise, check all successors.
1495 bool AnyDirectSuccessorsReachClonedNodes = false;
1496 for (DSNode::const_edge_iterator EI = N->edge_begin(), EE = N->edge_end();
1498 if (DSNode *Succ = EI->getNode()) {
1499 std::pair<unsigned, bool> &SuccInfo = VisitForSCCs(Succ);
1500 if (SuccInfo.first < Min) Min = SuccInfo.first;
1501 AnyDirectSuccessorsReachClonedNodes |= SuccInfo.second;
1505 return ThisNodeInfo; // Part of a large SCC. Leave self on stack.
1507 if (SCCStack.back() == N) { // Special case single node SCC.
1508 SCCStack.pop_back();
1509 ThisNodeInfo.second = AnyDirectSuccessorsReachClonedNodes;
1510 return ThisNodeInfo;
1513 // Find out if any direct successors of any node reach cloned nodes.
1514 if (!AnyDirectSuccessorsReachClonedNodes)
1515 for (unsigned i = SCCStack.size()-1; SCCStack[i] != N; --i)
1516 for (DSNode::const_edge_iterator EI = N->edge_begin(), EE = N->edge_end();
1518 if (DSNode *N = EI->getNode())
1519 if (NodeInfo[N].second) {
1520 AnyDirectSuccessorsReachClonedNodes = true;
1524 // If any successor reaches a cloned node, mark all nodes in this SCC as
1525 // reaching the cloned node.
1526 if (AnyDirectSuccessorsReachClonedNodes)
1527 while (SCCStack.back() != N) {
1528 NodeInfo[SCCStack.back()].second = true;
1529 SCCStack.pop_back();
1531 SCCStack.pop_back();
1532 ThisNodeInfo.second = true;
1533 return ThisNodeInfo;
1536 /// mergeInCallFromOtherGraph - This graph merges in the minimal number of
1537 /// nodes from G2 into 'this' graph, merging the bindings specified by the
1538 /// call site (in this graph) with the bindings specified by the vector in G2.
1539 /// The two DSGraphs must be different.
1541 void DSGraph::mergeInGraph(const DSCallSite &CS,
1542 std::vector<DSNodeHandle> &Args,
1543 const DSGraph &Graph, unsigned CloneFlags) {
1544 TIME_REGION(X, "mergeInGraph");
1546 assert((CloneFlags & DontCloneCallNodes) &&
1547 "Doesn't support copying of call nodes!");
1549 // If this is not a recursive call, clone the graph into this graph...
1550 if (&Graph == this) {
1551 // Merge the return value with the return value of the context.
1552 Args[0].mergeWith(CS.getRetVal());
1554 // Resolve all of the function arguments.
1555 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i) {
1556 if (i == Args.size()-1)
1559 // Add the link from the argument scalar to the provided value.
1560 Args[i+1].mergeWith(CS.getPtrArg(i));
1565 // Clone the callee's graph into the current graph, keeping track of where
1566 // scalars in the old graph _used_ to point, and of the new nodes matching
1567 // nodes of the old graph.
1568 ReachabilityCloner RC(*this, Graph, CloneFlags);
1570 // Map the return node pointer over.
1571 if (!CS.getRetVal().isNull())
1572 RC.merge(CS.getRetVal(), Args[0]);
1574 // Map over all of the arguments.
1575 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i) {
1576 if (i == Args.size()-1)
1579 // Add the link from the argument scalar to the provided value.
1580 RC.merge(CS.getPtrArg(i), Args[i+1]);
1583 // We generally don't want to copy global nodes or aux calls from the callee
1584 // graph to the caller graph. However, we have to copy them if there is a
1585 // path from the node to a node we have already copied which does not go
1586 // through another global. Compute the set of node that can reach globals and
1587 // aux call nodes to copy over, then do it.
1588 std::vector<const DSCallSite*> AuxCallToCopy;
1589 std::vector<GlobalValue*> GlobalsToCopy;
1591 // NodesReachCopiedNodes - Memoize results for efficiency. Contains a
1592 // true/false value for every visited node that reaches a copied node without
1593 // going through a global.
1594 HackedGraphSCCFinder SCCFinder(RC);
1596 if (!(CloneFlags & DontCloneAuxCallNodes))
1597 for (afc_iterator I = Graph.afc_begin(), E = Graph.afc_end(); I!=E; ++I)
1598 if (SCCFinder.PathExistsToClonedNode(*I))
1599 AuxCallToCopy.push_back(&*I);
1600 else if (I->isIndirectCall()){
1601 //If the call node doesn't have any callees, clone it
1602 std::vector< Function *> List;
1603 I->getCalleeNode()->addFullFunctionList(List);
1605 AuxCallToCopy.push_back(&*I);
1608 const DSScalarMap &GSM = Graph.getScalarMap();
1609 for (DSScalarMap::global_iterator GI = GSM.global_begin(),
1610 E = GSM.global_end(); GI != E; ++GI) {
1611 DSNode *GlobalNode = Graph.getNodeForValue(*GI).getNode();
1612 for (DSNode::edge_iterator EI = GlobalNode->edge_begin(),
1613 EE = GlobalNode->edge_end(); EI != EE; ++EI)
1614 if (SCCFinder.PathExistsToClonedNode(EI->getNode())) {
1615 GlobalsToCopy.push_back(*GI);
1620 // Copy aux calls that are needed.
1621 for (unsigned i = 0, e = AuxCallToCopy.size(); i != e; ++i)
1622 AuxFunctionCalls.push_back(DSCallSite(*AuxCallToCopy[i], RC));
1624 // Copy globals that are needed.
1625 for (unsigned i = 0, e = GlobalsToCopy.size(); i != e; ++i)
1626 RC.getClonedNH(Graph.getNodeForValue(GlobalsToCopy[i]));
1631 /// mergeInGraph - The method is used for merging graphs together. If the
1632 /// argument graph is not *this, it makes a clone of the specified graph, then
1633 /// merges the nodes specified in the call site with the formal arguments in the
1636 void DSGraph::mergeInGraph(const DSCallSite &CS, Function &F,
1637 const DSGraph &Graph, unsigned CloneFlags) {
1638 // Set up argument bindings.
1639 std::vector<DSNodeHandle> Args;
1640 Graph.getFunctionArgumentsForCall(&F, Args);
1642 mergeInGraph(CS, Args, Graph, CloneFlags);
1645 /// getCallSiteForArguments - Get the arguments and return value bindings for
1646 /// the specified function in the current graph.
1648 DSCallSite DSGraph::getCallSiteForArguments(Function &F) const {
1649 std::vector<DSNodeHandle> Args;
1651 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I)
1652 if (isPointerType(I->getType()))
1653 Args.push_back(getNodeForValue(I));
1655 return DSCallSite(CallSite(), getReturnNodeFor(F), &F, Args);
1658 /// getDSCallSiteForCallSite - Given an LLVM CallSite object that is live in
1659 /// the context of this graph, return the DSCallSite for it.
1660 DSCallSite DSGraph::getDSCallSiteForCallSite(CallSite CS) const {
1661 DSNodeHandle RetVal;
1662 Instruction *I = CS.getInstruction();
1663 if (isPointerType(I->getType()))
1664 RetVal = getNodeForValue(I);
1666 std::vector<DSNodeHandle> Args;
1667 Args.reserve(CS.arg_end()-CS.arg_begin());
1669 // Calculate the arguments vector...
1670 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); I != E; ++I)
1671 if (isPointerType((*I)->getType()))
1672 if (isa<ConstantPointerNull>(*I))
1673 Args.push_back(DSNodeHandle());
1675 Args.push_back(getNodeForValue(*I));
1677 // Add a new function call entry...
1678 if (Function *F = CS.getCalledFunction())
1679 return DSCallSite(CS, RetVal, F, Args);
1681 return DSCallSite(CS, RetVal,
1682 getNodeForValue(CS.getCalledValue()).getNode(), Args);
1687 // markIncompleteNodes - Mark the specified node as having contents that are not
1688 // known with the current analysis we have performed. Because a node makes all
1689 // of the nodes it can reach incomplete if the node itself is incomplete, we
1690 // must recursively traverse the data structure graph, marking all reachable
1691 // nodes as incomplete.
1693 static void markIncompleteNode(DSNode *N) {
1694 // Stop recursion if no node, or if node already marked...
1695 if (N == 0 || N->isIncomplete()) return;
1697 // Actually mark the node
1698 N->setIncompleteMarker();
1700 // Recursively process children...
1701 for (DSNode::edge_iterator I = N->edge_begin(),E = N->edge_end(); I != E; ++I)
1702 if (DSNode *DSN = I->getNode())
1703 markIncompleteNode(DSN);
1706 static void markIncomplete(DSCallSite &Call) {
1707 // Then the return value is certainly incomplete!
1708 markIncompleteNode(Call.getRetVal().getNode());
1710 // All objects pointed to by function arguments are incomplete!
1711 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
1712 markIncompleteNode(Call.getPtrArg(i).getNode());
1715 // markIncompleteNodes - Traverse the graph, identifying nodes that may be
1716 // modified by other functions that have not been resolved yet. This marks
1717 // nodes that are reachable through three sources of "unknownness":
1719 // Global Variables, Function Calls, and Incoming Arguments
1721 // For any node that may have unknown components (because something outside the
1722 // scope of current analysis may have modified it), the 'Incomplete' flag is
1723 // added to the NodeType.
1725 void DSGraph::markIncompleteNodes(unsigned Flags) {
1726 // Mark any incoming arguments as incomplete.
1727 if (Flags & DSGraph::MarkFormalArgs)
1728 for (ReturnNodesTy::iterator FI = ReturnNodes.begin(), E =ReturnNodes.end();
1730 Function &F = *FI->first;
1731 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
1733 if (isPointerType(I->getType()))
1734 markIncompleteNode(getNodeForValue(I).getNode());
1735 markIncompleteNode(FI->second.getNode());
1738 // Mark stuff passed into functions calls as being incomplete.
1739 if (!shouldPrintAuxCalls())
1740 for (std::list<DSCallSite>::iterator I = FunctionCalls.begin(),
1741 E = FunctionCalls.end(); I != E; ++I)
1744 for (std::list<DSCallSite>::iterator I = AuxFunctionCalls.begin(),
1745 E = AuxFunctionCalls.end(); I != E; ++I)
1748 // Mark all global nodes as incomplete.
1749 for (DSScalarMap::global_iterator I = ScalarMap.global_begin(),
1750 E = ScalarMap.global_end(); I != E; ++I)
1751 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I))
1752 if (!GV->hasInitializer() || // Always mark external globals incomp.
1753 (!GV->isConstant() && (Flags & DSGraph::IgnoreGlobals) == 0))
1754 markIncompleteNode(ScalarMap[GV].getNode());
1757 static inline void killIfUselessEdge(DSNodeHandle &Edge) {
1758 if (DSNode *N = Edge.getNode()) // Is there an edge?
1759 if (N->getNumReferrers() == 1) // Does it point to a lonely node?
1760 // No interesting info?
1761 if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
1762 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
1763 Edge.setTo(0, 0); // Kill the edge!
1766 static inline bool nodeContainsExternalFunction(const DSNode *N) {
1767 std::vector<Function*> Funcs;
1768 N->addFullFunctionList(Funcs);
1769 for (unsigned i = 0, e = Funcs.size(); i != e; ++i)
1770 if (Funcs[i]->isExternal()) return true;
1774 static void removeIdenticalCalls(std::list<DSCallSite> &Calls) {
1775 // Remove trivially identical function calls
1776 Calls.sort(); // Sort by callee as primary key!
1778 // Scan the call list cleaning it up as necessary...
1779 DSNodeHandle LastCalleeNode;
1780 Function *LastCalleeFunc = 0;
1781 unsigned NumDuplicateCalls = 0;
1782 bool LastCalleeContainsExternalFunction = false;
1784 unsigned NumDeleted = 0;
1785 for (std::list<DSCallSite>::iterator I = Calls.begin(), E = Calls.end();
1787 DSCallSite &CS = *I;
1788 std::list<DSCallSite>::iterator OldIt = I++;
1790 if (!CS.isIndirectCall()) {
1793 DSNode *Callee = CS.getCalleeNode();
1795 // If the Callee is a useless edge, this must be an unreachable call site,
1797 if (Callee->getNumReferrers() == 1 && Callee->isComplete() &&
1798 Callee->getGlobalsList().empty()) { // No useful info?
1800 std::cerr << "WARNING: Useless call site found.\n";
1807 // If the last call site in the list has the same callee as this one, and
1808 // if the callee contains an external function, it will never be
1809 // resolvable, just merge the call sites.
1810 if (!LastCalleeNode.isNull() && LastCalleeNode.getNode() == Callee) {
1811 LastCalleeContainsExternalFunction =
1812 nodeContainsExternalFunction(Callee);
1814 std::list<DSCallSite>::iterator PrevIt = OldIt;
1816 PrevIt->mergeWith(CS);
1818 // No need to keep this call anymore.
1823 LastCalleeNode = Callee;
1827 // If the return value or any arguments point to a void node with no
1828 // information at all in it, and the call node is the only node to point
1829 // to it, remove the edge to the node (killing the node).
1831 killIfUselessEdge(CS.getRetVal());
1832 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
1833 killIfUselessEdge(CS.getPtrArg(a));
1836 // If this call site calls the same function as the last call site, and if
1837 // the function pointer contains an external function, this node will
1838 // never be resolved. Merge the arguments of the call node because no
1839 // information will be lost.
1841 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
1842 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
1843 ++NumDuplicateCalls;
1844 if (NumDuplicateCalls == 1) {
1846 LastCalleeContainsExternalFunction =
1847 nodeContainsExternalFunction(LastCalleeNode);
1849 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
1852 // It is not clear why, but enabling this code makes DSA really
1853 // sensitive to node forwarding. Basically, with this enabled, DSA
1854 // performs different number of inlinings based on which nodes are
1855 // forwarding or not. This is clearly a problem, so this code is
1856 // disabled until this can be resolved.
1858 if (LastCalleeContainsExternalFunction
1861 // This should be more than enough context sensitivity!
1862 // FIXME: Evaluate how many times this is tripped!
1863 NumDuplicateCalls > 20
1867 std::list<DSCallSite>::iterator PrevIt = OldIt;
1869 PrevIt->mergeWith(CS);
1871 // No need to keep this call anymore.
1878 if (CS.isDirectCall()) {
1879 LastCalleeFunc = CS.getCalleeFunc();
1882 LastCalleeNode = CS.getCalleeNode();
1885 NumDuplicateCalls = 0;
1889 if (I != Calls.end() && CS == *I) {
1897 // Resort now that we simplified things.
1900 // Now that we are in sorted order, eliminate duplicates.
1901 std::list<DSCallSite>::iterator CI = Calls.begin(), CE = Calls.end();
1904 std::list<DSCallSite>::iterator OldIt = CI++;
1905 if (CI == CE) break;
1907 // If this call site is now the same as the previous one, we can delete it
1909 if (*OldIt == *CI) {
1916 //Calls.erase(std::unique(Calls.begin(), Calls.end()), Calls.end());
1918 // Track the number of call nodes merged away...
1919 NumCallNodesMerged += NumDeleted;
1921 DEBUG(if (NumDeleted)
1922 std::cerr << "Merged " << NumDeleted << " call nodes.\n";);
1926 // removeTriviallyDeadNodes - After the graph has been constructed, this method
1927 // removes all unreachable nodes that are created because they got merged with
1928 // other nodes in the graph. These nodes will all be trivially unreachable, so
1929 // we don't have to perform any non-trivial analysis here.
1931 void DSGraph::removeTriviallyDeadNodes() {
1932 TIME_REGION(X, "removeTriviallyDeadNodes");
1935 /// NOTE: This code is disabled. This slows down DSA on 177.mesa
1938 // Loop over all of the nodes in the graph, calling getNode on each field.
1939 // This will cause all nodes to update their forwarding edges, causing
1940 // forwarded nodes to be delete-able.
1941 { TIME_REGION(X, "removeTriviallyDeadNodes:node_iterate");
1942 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI) {
1944 for (unsigned l = 0, e = N.getNumLinks(); l != e; ++l)
1945 N.getLink(l*N.getPointerSize()).getNode();
1949 // NOTE: This code is disabled. Though it should, in theory, allow us to
1950 // remove more nodes down below, the scan of the scalar map is incredibly
1951 // expensive for certain programs (with large SCCs). In the future, if we can
1952 // make the scalar map scan more efficient, then we can reenable this.
1953 { TIME_REGION(X, "removeTriviallyDeadNodes:scalarmap");
1955 // Likewise, forward any edges from the scalar nodes. While we are at it,
1956 // clean house a bit.
1957 for (DSScalarMap::iterator I = ScalarMap.begin(),E = ScalarMap.end();I != E;){
1958 I->second.getNode();
1963 bool isGlobalsGraph = !GlobalsGraph;
1965 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E; ) {
1968 // Do not remove *any* global nodes in the globals graph.
1969 // This is a special case because such nodes may not have I, M, R flags set.
1970 if (Node.isGlobalNode() && isGlobalsGraph) {
1975 if (Node.isComplete() && !Node.isModified() && !Node.isRead()) {
1976 // This is a useless node if it has no mod/ref info (checked above),
1977 // outgoing edges (which it cannot, as it is not modified in this
1978 // context), and it has no incoming edges. If it is a global node it may
1979 // have all of these properties and still have incoming edges, due to the
1980 // scalar map, so we check those now.
1982 if (Node.getNumReferrers() == Node.getGlobalsList().size()) {
1983 const std::vector<GlobalValue*> &Globals = Node.getGlobalsList();
1985 // Loop through and make sure all of the globals are referring directly
1987 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1988 DSNode *N = getNodeForValue(Globals[j]).getNode();
1989 assert(N == &Node && "ScalarMap doesn't match globals list!");
1992 // Make sure NumReferrers still agrees, if so, the node is truly dead.
1993 if (Node.getNumReferrers() == Globals.size()) {
1994 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1995 ScalarMap.erase(Globals[j]);
1996 Node.makeNodeDead();
1997 ++NumTrivialGlobalDNE;
2002 if (Node.getNodeFlags() == 0 && Node.hasNoReferrers()) {
2003 // This node is dead!
2004 NI = Nodes.erase(NI); // Erase & remove from node list.
2011 removeIdenticalCalls(FunctionCalls);
2012 removeIdenticalCalls(AuxFunctionCalls);
2016 /// markReachableNodes - This method recursively traverses the specified
2017 /// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
2018 /// to the set, which allows it to only traverse visited nodes once.
2020 void DSNode::markReachableNodes(hash_set<const DSNode*> &ReachableNodes) const {
2021 if (this == 0) return;
2022 assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
2023 if (ReachableNodes.insert(this).second) // Is newly reachable?
2024 for (DSNode::const_edge_iterator I = edge_begin(), E = edge_end();
2026 I->getNode()->markReachableNodes(ReachableNodes);
2029 void DSCallSite::markReachableNodes(hash_set<const DSNode*> &Nodes) const {
2030 getRetVal().getNode()->markReachableNodes(Nodes);
2031 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
2033 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
2034 getPtrArg(i).getNode()->markReachableNodes(Nodes);
2037 // CanReachAliveNodes - Simple graph walker that recursively traverses the graph
2038 // looking for a node that is marked alive. If an alive node is found, return
2039 // true, otherwise return false. If an alive node is reachable, this node is
2040 // marked as alive...
2042 static bool CanReachAliveNodes(DSNode *N, hash_set<const DSNode*> &Alive,
2043 hash_set<const DSNode*> &Visited,
2044 bool IgnoreGlobals) {
2045 if (N == 0) return false;
2046 assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
2048 // If this is a global node, it will end up in the globals graph anyway, so we
2049 // don't need to worry about it.
2050 if (IgnoreGlobals && N->isGlobalNode()) return false;
2052 // If we know that this node is alive, return so!
2053 if (Alive.count(N)) return true;
2055 // Otherwise, we don't think the node is alive yet, check for infinite
2057 if (Visited.count(N)) return false; // Found a cycle
2058 Visited.insert(N); // No recursion, insert into Visited...
2060 for (DSNode::edge_iterator I = N->edge_begin(),E = N->edge_end(); I != E; ++I)
2061 if (CanReachAliveNodes(I->getNode(), Alive, Visited, IgnoreGlobals)) {
2062 N->markReachableNodes(Alive);
2068 // CallSiteUsesAliveArgs - Return true if the specified call site can reach any
2071 static bool CallSiteUsesAliveArgs(const DSCallSite &CS,
2072 hash_set<const DSNode*> &Alive,
2073 hash_set<const DSNode*> &Visited,
2074 bool IgnoreGlobals) {
2075 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited,
2078 if (CS.isIndirectCall() &&
2079 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited, IgnoreGlobals))
2081 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
2082 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited,
2088 // removeDeadNodes - Use a more powerful reachability analysis to eliminate
2089 // subgraphs that are unreachable. This often occurs because the data
2090 // structure doesn't "escape" into it's caller, and thus should be eliminated
2091 // from the caller's graph entirely. This is only appropriate to use when
2094 void DSGraph::removeDeadNodes(unsigned Flags) {
2095 DEBUG(AssertGraphOK(); if (GlobalsGraph) GlobalsGraph->AssertGraphOK());
2097 // Reduce the amount of work we have to do... remove dummy nodes left over by
2099 removeTriviallyDeadNodes();
2101 TIME_REGION(X, "removeDeadNodes");
2103 // FIXME: Merge non-trivially identical call nodes...
2105 // Alive - a set that holds all nodes found to be reachable/alive.
2106 hash_set<const DSNode*> Alive;
2107 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
2109 // Copy and merge all information about globals to the GlobalsGraph if this is
2110 // not a final pass (where unreachable globals are removed).
2112 // Strip all alloca bits since the current function is only for the BU pass.
2113 // Strip all incomplete bits since they are short-lived properties and they
2114 // will be correctly computed when rematerializing nodes into the functions.
2116 ReachabilityCloner GGCloner(*GlobalsGraph, *this, DSGraph::StripAllocaBit |
2117 DSGraph::StripIncompleteBit);
2119 // Mark all nodes reachable by (non-global) scalar nodes as alive...
2120 { TIME_REGION(Y, "removeDeadNodes:scalarscan");
2121 for (DSScalarMap::iterator I = ScalarMap.begin(), E = ScalarMap.end();
2123 if (isa<GlobalValue>(I->first)) { // Keep track of global nodes
2124 assert(!I->second.isNull() && "Null global node?");
2125 assert(I->second.getNode()->isGlobalNode() && "Should be a global node!");
2126 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
2128 // Make sure that all globals are cloned over as roots.
2129 if (!(Flags & DSGraph::RemoveUnreachableGlobals) && GlobalsGraph) {
2130 DSGraph::ScalarMapTy::iterator SMI =
2131 GlobalsGraph->getScalarMap().find(I->first);
2132 if (SMI != GlobalsGraph->getScalarMap().end())
2133 GGCloner.merge(SMI->second, I->second);
2135 GGCloner.getClonedNH(I->second);
2138 I->second.getNode()->markReachableNodes(Alive);
2142 // The return values are alive as well.
2143 for (ReturnNodesTy::iterator I = ReturnNodes.begin(), E = ReturnNodes.end();
2145 I->second.getNode()->markReachableNodes(Alive);
2147 // Mark any nodes reachable by primary calls as alive...
2148 for (fc_iterator I = fc_begin(), E = fc_end(); I != E; ++I)
2149 I->markReachableNodes(Alive);
2152 // Now find globals and aux call nodes that are already live or reach a live
2153 // value (which makes them live in turn), and continue till no more are found.
2156 hash_set<const DSNode*> Visited;
2157 hash_set<const DSCallSite*> AuxFCallsAlive;
2160 // If any global node points to a non-global that is "alive", the global is
2161 // "alive" as well... Remove it from the GlobalNodes list so we only have
2162 // unreachable globals in the list.
2165 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
2166 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
2167 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited,
2168 Flags & DSGraph::RemoveUnreachableGlobals)) {
2169 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to...
2170 GlobalNodes.pop_back(); // erase efficiently
2174 // Mark only unresolvable call nodes for moving to the GlobalsGraph since
2175 // call nodes that get resolved will be difficult to remove from that graph.
2176 // The final unresolved call nodes must be handled specially at the end of
2177 // the BU pass (i.e., in main or other roots of the call graph).
2178 for (afc_iterator CI = afc_begin(), E = afc_end(); CI != E; ++CI)
2179 if (!AuxFCallsAlive.count(&*CI) &&
2180 (CI->isIndirectCall()
2181 || CallSiteUsesAliveArgs(*CI, Alive, Visited,
2182 Flags & DSGraph::RemoveUnreachableGlobals))) {
2183 CI->markReachableNodes(Alive);
2184 AuxFCallsAlive.insert(&*CI);
2189 // Move dead aux function calls to the end of the list
2190 unsigned CurIdx = 0;
2191 for (std::list<DSCallSite>::iterator CI = AuxFunctionCalls.begin(),
2192 E = AuxFunctionCalls.end(); CI != E; )
2193 if (AuxFCallsAlive.count(&*CI))
2196 // Copy and merge global nodes and dead aux call nodes into the
2197 // GlobalsGraph, and all nodes reachable from those nodes. Update their
2198 // target pointers using the GGCloner.
2200 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
2201 GlobalsGraph->AuxFunctionCalls.push_back(DSCallSite(*CI, GGCloner));
2203 AuxFunctionCalls.erase(CI++);
2206 // We are finally done with the GGCloner so we can destroy it.
2209 // At this point, any nodes which are visited, but not alive, are nodes
2210 // which can be removed. Loop over all nodes, eliminating completely
2211 // unreachable nodes.
2213 std::vector<DSNode*> DeadNodes;
2214 DeadNodes.reserve(Nodes.size());
2215 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E;) {
2217 assert(!N->isForwarding() && "Forwarded node in nodes list?");
2219 if (!Alive.count(N)) {
2221 assert(!N->isForwarding() && "Cannot remove a forwarding node!");
2222 DeadNodes.push_back(N);
2223 N->dropAllReferences();
2228 // Remove all unreachable globals from the ScalarMap.
2229 // If flag RemoveUnreachableGlobals is set, GlobalNodes has only dead nodes.
2230 // In either case, the dead nodes will not be in the set Alive.
2231 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
2232 if (!Alive.count(GlobalNodes[i].second))
2233 ScalarMap.erase(GlobalNodes[i].first);
2235 assert((Flags & DSGraph::RemoveUnreachableGlobals) && "non-dead global");
2237 // Delete all dead nodes now since their referrer counts are zero.
2238 for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
2239 delete DeadNodes[i];
2241 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
2244 void DSGraph::AssertNodeContainsGlobal(const DSNode *N, GlobalValue *GV) const {
2245 assert(std::find(N->globals_begin(),N->globals_end(), GV) !=
2246 N->globals_end() && "Global value not in node!");
2249 void DSGraph::AssertCallSiteInGraph(const DSCallSite &CS) const {
2250 if (CS.isIndirectCall()) {
2251 AssertNodeInGraph(CS.getCalleeNode());
2253 if (CS.getNumPtrArgs() && CS.getCalleeNode() == CS.getPtrArg(0).getNode() &&
2254 CS.getCalleeNode() && CS.getCalleeNode()->getGlobals().empty())
2255 std::cerr << "WARNING: WEIRD CALL SITE FOUND!\n";
2258 AssertNodeInGraph(CS.getRetVal().getNode());
2259 for (unsigned j = 0, e = CS.getNumPtrArgs(); j != e; ++j)
2260 AssertNodeInGraph(CS.getPtrArg(j).getNode());
2263 void DSGraph::AssertCallNodesInGraph() const {
2264 for (fc_iterator I = fc_begin(), E = fc_end(); I != E; ++I)
2265 AssertCallSiteInGraph(*I);
2267 void DSGraph::AssertAuxCallNodesInGraph() const {
2268 for (afc_iterator I = afc_begin(), E = afc_end(); I != E; ++I)
2269 AssertCallSiteInGraph(*I);
2272 void DSGraph::AssertGraphOK() const {
2273 for (node_const_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
2276 for (ScalarMapTy::const_iterator I = ScalarMap.begin(),
2277 E = ScalarMap.end(); I != E; ++I) {
2278 assert(!I->second.isNull() && "Null node in scalarmap!");
2279 AssertNodeInGraph(I->second.getNode());
2280 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
2281 assert(I->second.getNode()->isGlobalNode() &&
2282 "Global points to node, but node isn't global?");
2283 AssertNodeContainsGlobal(I->second.getNode(), GV);
2286 AssertCallNodesInGraph();
2287 AssertAuxCallNodesInGraph();
2289 // Check that all pointer arguments to any functions in this graph have
2291 for (ReturnNodesTy::const_iterator RI = ReturnNodes.begin(),
2292 E = ReturnNodes.end();
2294 Function &F = *RI->first;
2295 for (Function::arg_iterator AI = F.arg_begin(); AI != F.arg_end(); ++AI)
2296 if (isPointerType(AI->getType()))
2297 assert(!getNodeForValue(AI).isNull() &&
2298 "Pointer argument must be in the scalar map!");
2302 /// computeNodeMapping - Given roots in two different DSGraphs, traverse the
2303 /// nodes reachable from the two graphs, computing the mapping of nodes from the
2304 /// first to the second graph. This mapping may be many-to-one (i.e. the first
2305 /// graph may have multiple nodes representing one node in the second graph),
2306 /// but it will not work if there is a one-to-many or many-to-many mapping.
2308 void DSGraph::computeNodeMapping(const DSNodeHandle &NH1,
2309 const DSNodeHandle &NH2, NodeMapTy &NodeMap,
2310 bool StrictChecking) {
2311 DSNode *N1 = NH1.getNode(), *N2 = NH2.getNode();
2312 if (N1 == 0 || N2 == 0) return;
2314 DSNodeHandle &Entry = NodeMap[N1];
2315 if (!Entry.isNull()) {
2316 // Termination of recursion!
2317 if (StrictChecking) {
2318 assert(Entry.getNode() == N2 && "Inconsistent mapping detected!");
2319 assert((Entry.getOffset() == (NH2.getOffset()-NH1.getOffset()) ||
2320 Entry.getNode()->isNodeCompletelyFolded()) &&
2321 "Inconsistent mapping detected!");
2326 Entry.setTo(N2, NH2.getOffset()-NH1.getOffset());
2328 // Loop over all of the fields that N1 and N2 have in common, recursively
2329 // mapping the edges together now.
2330 int N2Idx = NH2.getOffset()-NH1.getOffset();
2331 unsigned N2Size = N2->getSize();
2332 if (N2Size == 0) return; // No edges to map to.
2334 for (unsigned i = 0, e = N1->getSize(); i < e; i += DS::PointerSize) {
2335 const DSNodeHandle &N1NH = N1->getLink(i);
2336 // Don't call N2->getLink if not needed (avoiding crash if N2Idx is not
2338 if (!N1NH.isNull()) {
2339 if (unsigned(N2Idx)+i < N2Size)
2340 computeNodeMapping(N1NH, N2->getLink(N2Idx+i), NodeMap);
2342 computeNodeMapping(N1NH,
2343 N2->getLink(unsigned(N2Idx+i) % N2Size), NodeMap);
2349 /// computeGToGGMapping - Compute the mapping of nodes in the global graph to
2350 /// nodes in this graph.
2351 void DSGraph::computeGToGGMapping(NodeMapTy &NodeMap) {
2352 DSGraph &GG = *getGlobalsGraph();
2354 DSScalarMap &SM = getScalarMap();
2355 for (DSScalarMap::global_iterator I = SM.global_begin(),
2356 E = SM.global_end(); I != E; ++I)
2357 DSGraph::computeNodeMapping(SM[*I], GG.getNodeForValue(*I), NodeMap);
2360 /// computeGGToGMapping - Compute the mapping of nodes in the global graph to
2361 /// nodes in this graph. Note that any uses of this method are probably bugs,
2362 /// unless it is known that the globals graph has been merged into this graph!
2363 void DSGraph::computeGGToGMapping(InvNodeMapTy &InvNodeMap) {
2365 computeGToGGMapping(NodeMap);
2367 while (!NodeMap.empty()) {
2368 InvNodeMap.insert(std::make_pair(NodeMap.begin()->second,
2369 NodeMap.begin()->first));
2370 NodeMap.erase(NodeMap.begin());
2375 /// computeCalleeCallerMapping - Given a call from a function in the current
2376 /// graph to the 'Callee' function (which lives in 'CalleeGraph'), compute the
2377 /// mapping of nodes from the callee to nodes in the caller.
2378 void DSGraph::computeCalleeCallerMapping(DSCallSite CS, const Function &Callee,
2379 DSGraph &CalleeGraph,
2380 NodeMapTy &NodeMap) {
2382 DSCallSite CalleeArgs =
2383 CalleeGraph.getCallSiteForArguments(const_cast<Function&>(Callee));
2385 computeNodeMapping(CalleeArgs.getRetVal(), CS.getRetVal(), NodeMap);
2387 unsigned NumArgs = CS.getNumPtrArgs();
2388 if (NumArgs > CalleeArgs.getNumPtrArgs())
2389 NumArgs = CalleeArgs.getNumPtrArgs();
2391 for (unsigned i = 0; i != NumArgs; ++i)
2392 computeNodeMapping(CalleeArgs.getPtrArg(i), CS.getPtrArg(i), NodeMap);
2394 // Map the nodes that are pointed to by globals.
2395 DSScalarMap &CalleeSM = CalleeGraph.getScalarMap();
2396 DSScalarMap &CallerSM = getScalarMap();
2398 if (CalleeSM.global_size() >= CallerSM.global_size()) {
2399 for (DSScalarMap::global_iterator GI = CallerSM.global_begin(),
2400 E = CallerSM.global_end(); GI != E; ++GI)
2401 if (CalleeSM.global_count(*GI))
2402 computeNodeMapping(CalleeSM[*GI], CallerSM[*GI], NodeMap);
2404 for (DSScalarMap::global_iterator GI = CalleeSM.global_begin(),
2405 E = CalleeSM.global_end(); GI != E; ++GI)
2406 if (CallerSM.global_count(*GI))
2407 computeNodeMapping(CalleeSM[*GI], CallerSM[*GI], NodeMap);
2411 /// updateFromGlobalGraph - This function rematerializes global nodes and
2412 /// nodes reachable from them from the globals graph into the current graph.
2414 void DSGraph::updateFromGlobalGraph() {
2415 TIME_REGION(X, "updateFromGlobalGraph");
2416 ReachabilityCloner RC(*this, *GlobalsGraph, 0);
2418 // Clone the non-up-to-date global nodes into this graph.
2419 for (DSScalarMap::global_iterator I = getScalarMap().global_begin(),
2420 E = getScalarMap().global_end(); I != E; ++I) {
2421 DSScalarMap::iterator It = GlobalsGraph->ScalarMap.find(*I);
2422 if (It != GlobalsGraph->ScalarMap.end())
2423 RC.merge(getNodeForValue(*I), It->second);