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 { //assert not looping
68 std::set<DSNode*> seen;
69 while(NH && NH->isForwarding()) {
70 assert(seen.find(NH) == seen.end() && "Loop detected");
76 // Handle node forwarding here!
77 DSNode *Next = N->ForwardNH.getNode(); // Cause recursive shrinkage
78 Offset += N->ForwardNH.getOffset();
80 if (--N->NumReferrers == 0) {
81 // Removing the last referrer to the node, sever the forwarding link
87 if (N->Size <= Offset) {
88 assert(N->Size <= 1 && "Forwarded to shrunk but not collapsed node?");
94 //===----------------------------------------------------------------------===//
95 // DSScalarMap Implementation
96 //===----------------------------------------------------------------------===//
98 DSNodeHandle &DSScalarMap::AddGlobal(GlobalValue *GV) {
99 assert(ValueMap.count(GV) == 0 && "GV already exists!");
101 // If the node doesn't exist, check to see if it's a global that is
102 // equated to another global in the program.
103 EquivalenceClasses<GlobalValue*>::iterator ECI = GlobalECs.findValue(GV);
104 if (ECI != GlobalECs.end()) {
105 GlobalValue *Leader = *GlobalECs.findLeader(ECI);
108 iterator I = ValueMap.find(GV);
109 if (I != ValueMap.end())
114 // Okay, this is either not an equivalenced global or it is the leader, it
115 // will be inserted into the scalar map now.
116 GlobalSet.insert(GV);
118 return ValueMap.insert(std::make_pair(GV, DSNodeHandle())).first->second;
122 //===----------------------------------------------------------------------===//
123 // DSNode Implementation
124 //===----------------------------------------------------------------------===//
126 DSNode::DSNode(const Type *T, DSGraph *G)
127 : NumReferrers(0), Size(0), ParentGraph(G), Ty(Type::VoidTy), NodeType(0) {
128 // Add the type entry if it is specified...
129 if (T) mergeTypeInfo(T, 0);
130 if (G) G->addNode(this);
134 // DSNode copy constructor... do not copy over the referrers list!
135 DSNode::DSNode(const DSNode &N, DSGraph *G, bool NullLinks)
136 : NumReferrers(0), Size(N.Size), ParentGraph(G),
137 Ty(N.Ty), Globals(N.Globals), NodeType(N.NodeType) {
141 Links.resize(N.Links.size()); // Create the appropriate number of null links
146 /// getTargetData - Get the target data object used to construct this node.
148 const TargetData &DSNode::getTargetData() const {
149 return ParentGraph->getTargetData();
152 void DSNode::assertOK() const {
153 assert((Ty != Type::VoidTy ||
154 Ty == Type::VoidTy && (Size == 0 ||
155 (NodeType & DSNode::Array))) &&
158 assert(ParentGraph && "Node has no parent?");
159 const DSScalarMap &SM = ParentGraph->getScalarMap();
160 for (unsigned i = 0, e = Globals.size(); i != e; ++i) {
161 assert(SM.global_count(Globals[i]));
162 assert(SM.find(Globals[i])->second.getNode() == this);
166 /// forwardNode - Mark this node as being obsolete, and all references to it
167 /// should be forwarded to the specified node and offset.
169 void DSNode::forwardNode(DSNode *To, unsigned Offset) {
170 assert(this != To && "Cannot forward a node to itself!");
171 assert(ForwardNH.isNull() && "Already forwarding from this node!");
172 if (To->Size <= 1) Offset = 0;
173 assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
174 "Forwarded offset is wrong!");
175 ForwardNH.setTo(To, Offset);
180 // Remove this node from the parent graph's Nodes list.
181 ParentGraph->unlinkNode(this);
185 // addGlobal - Add an entry for a global value to the Globals list. This also
186 // marks the node with the 'G' flag if it does not already have it.
188 void DSNode::addGlobal(GlobalValue *GV) {
189 // First, check to make sure this is the leader if the global is in an
190 // equivalence class.
191 GV = getParentGraph()->getScalarMap().getLeaderForGlobal(GV);
193 // Keep the list sorted.
194 std::vector<GlobalValue*>::iterator I =
195 std::lower_bound(Globals.begin(), Globals.end(), GV);
197 if (I == Globals.end() || *I != GV) {
198 Globals.insert(I, GV);
199 NodeType |= GlobalNode;
203 // removeGlobal - Remove the specified global that is explicitly in the globals
205 void DSNode::removeGlobal(GlobalValue *GV) {
206 std::vector<GlobalValue*>::iterator I =
207 std::lower_bound(Globals.begin(), Globals.end(), GV);
208 assert(I != Globals.end() && *I == GV && "Global not in node!");
212 /// foldNodeCompletely - If we determine that this node has some funny
213 /// behavior happening to it that we cannot represent, we fold it down to a
214 /// single, completely pessimistic, node. This node is represented as a
215 /// single byte with a single TypeEntry of "void".
217 void DSNode::foldNodeCompletely() {
218 if (isNodeCompletelyFolded()) return; // If this node is already folded...
222 // If this node has a size that is <= 1, we don't need to create a forwarding
224 if (getSize() <= 1) {
225 NodeType |= DSNode::Array;
228 assert(Links.size() <= 1 && "Size is 1, but has more links?");
231 // Create the node we are going to forward to. This is required because
232 // some referrers may have an offset that is > 0. By forcing them to
233 // forward, the forwarder has the opportunity to correct the offset.
234 DSNode *DestNode = new DSNode(0, ParentGraph);
235 DestNode->NodeType = NodeType|DSNode::Array;
236 DestNode->Ty = Type::VoidTy;
238 DestNode->Globals.swap(Globals);
240 // Start forwarding to the destination node...
241 forwardNode(DestNode, 0);
243 if (!Links.empty()) {
244 DestNode->Links.reserve(1);
246 DSNodeHandle NH(DestNode);
247 DestNode->Links.push_back(Links[0]);
249 // If we have links, merge all of our outgoing links together...
250 for (unsigned i = Links.size()-1; i != 0; --i)
251 NH.getNode()->Links[0].mergeWith(Links[i]);
254 DestNode->Links.resize(1);
259 /// isNodeCompletelyFolded - Return true if this node has been completely
260 /// folded down to something that can never be expanded, effectively losing
261 /// all of the field sensitivity that may be present in the node.
263 bool DSNode::isNodeCompletelyFolded() const {
264 return getSize() == 1 && Ty == Type::VoidTy && isArray();
267 /// addFullGlobalsList - Compute the full set of global values that are
268 /// represented by this node. Unlike getGlobalsList(), this requires fair
269 /// amount of work to compute, so don't treat this method call as free.
270 void DSNode::addFullGlobalsList(std::vector<GlobalValue*> &List) const {
271 if (globals_begin() == globals_end()) return;
273 EquivalenceClasses<GlobalValue*> &EC = getParentGraph()->getGlobalECs();
275 for (globals_iterator I = globals_begin(), E = globals_end(); I != E; ++I) {
276 EquivalenceClasses<GlobalValue*>::iterator ECI = EC.findValue(*I);
280 List.insert(List.end(), EC.member_begin(ECI), EC.member_end());
284 /// addFullFunctionList - Identical to addFullGlobalsList, but only return the
285 /// functions in the full list.
286 void DSNode::addFullFunctionList(std::vector<Function*> &List) const {
287 if (globals_begin() == globals_end()) return;
289 EquivalenceClasses<GlobalValue*> &EC = getParentGraph()->getGlobalECs();
291 for (globals_iterator I = globals_begin(), E = globals_end(); I != E; ++I) {
292 EquivalenceClasses<GlobalValue*>::iterator ECI = EC.findValue(*I);
293 if (ECI == EC.end()) {
294 if (Function *F = dyn_cast<Function>(*I))
297 for (EquivalenceClasses<GlobalValue*>::member_iterator MI =
298 EC.member_begin(ECI), E = EC.member_end(); MI != E; ++MI)
299 if (Function *F = dyn_cast<Function>(*MI))
306 /// TypeElementWalker Class - Used for implementation of physical subtyping...
308 class TypeElementWalker {
313 StackState(const Type *T, unsigned Off = 0)
314 : Ty(T), Offset(Off), Idx(0) {}
317 std::vector<StackState> Stack;
318 const TargetData &TD;
320 TypeElementWalker(const Type *T, const TargetData &td) : TD(td) {
325 bool isDone() const { return Stack.empty(); }
326 const Type *getCurrentType() const { return Stack.back().Ty; }
327 unsigned getCurrentOffset() const { return Stack.back().Offset; }
329 void StepToNextType() {
330 PopStackAndAdvance();
335 /// PopStackAndAdvance - Pop the current element off of the stack and
336 /// advance the underlying element to the next contained member.
337 void PopStackAndAdvance() {
338 assert(!Stack.empty() && "Cannot pop an empty stack!");
340 while (!Stack.empty()) {
341 StackState &SS = Stack.back();
342 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
344 if (SS.Idx != ST->getNumElements()) {
345 const StructLayout *SL = TD.getStructLayout(ST);
347 unsigned(SL->MemberOffsets[SS.Idx]-SL->MemberOffsets[SS.Idx-1]);
350 Stack.pop_back(); // At the end of the structure
352 const ArrayType *AT = cast<ArrayType>(SS.Ty);
354 if (SS.Idx != AT->getNumElements()) {
355 SS.Offset += unsigned(TD.getTypeSize(AT->getElementType()));
358 Stack.pop_back(); // At the end of the array
363 /// StepToLeaf - Used by physical subtyping to move to the first leaf node
364 /// on the type stack.
366 if (Stack.empty()) return;
367 while (!Stack.empty() && !Stack.back().Ty->isFirstClassType()) {
368 StackState &SS = Stack.back();
369 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
370 if (ST->getNumElements() == 0) {
372 PopStackAndAdvance();
374 // Step into the structure...
375 assert(SS.Idx < ST->getNumElements());
376 const StructLayout *SL = TD.getStructLayout(ST);
377 Stack.push_back(StackState(ST->getElementType(SS.Idx),
378 SS.Offset+unsigned(SL->MemberOffsets[SS.Idx])));
381 const ArrayType *AT = cast<ArrayType>(SS.Ty);
382 if (AT->getNumElements() == 0) {
384 PopStackAndAdvance();
386 // Step into the array...
387 assert(SS.Idx < AT->getNumElements());
388 Stack.push_back(StackState(AT->getElementType(),
390 unsigned(TD.getTypeSize(AT->getElementType()))));
396 } // end anonymous namespace
398 /// ElementTypesAreCompatible - Check to see if the specified types are
399 /// "physically" compatible. If so, return true, else return false. We only
400 /// have to check the fields in T1: T2 may be larger than T1. If AllowLargerT1
401 /// is true, then we also allow a larger T1.
403 static bool ElementTypesAreCompatible(const Type *T1, const Type *T2,
404 bool AllowLargerT1, const TargetData &TD){
405 TypeElementWalker T1W(T1, TD), T2W(T2, TD);
407 while (!T1W.isDone() && !T2W.isDone()) {
408 if (T1W.getCurrentOffset() != T2W.getCurrentOffset())
411 const Type *T1 = T1W.getCurrentType();
412 const Type *T2 = T2W.getCurrentType();
413 if (T1 != T2 && !T1->isLosslesslyConvertibleTo(T2))
416 T1W.StepToNextType();
417 T2W.StepToNextType();
420 return AllowLargerT1 || T1W.isDone();
424 /// mergeTypeInfo - This method merges the specified type into the current node
425 /// at the specified offset. This may update the current node's type record if
426 /// this gives more information to the node, it may do nothing to the node if
427 /// this information is already known, or it may merge the node completely (and
428 /// return true) if the information is incompatible with what is already known.
430 /// This method returns true if the node is completely folded, otherwise false.
432 bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset,
433 bool FoldIfIncompatible) {
434 DOUT << "merging " << *NewTy << " at " << Offset << " with " << *Ty << "\n";
435 const TargetData &TD = getTargetData();
436 // Check to make sure the Size member is up-to-date. Size can be one of the
438 // Size = 0, Ty = Void: Nothing is known about this node.
439 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
440 // Size = 1, Ty = Void, Array = 1: The node is collapsed
441 // Otherwise, sizeof(Ty) = Size
443 assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
444 (Size == 0 && !Ty->isSized() && !isArray()) ||
445 (Size == 1 && Ty == Type::VoidTy && isArray()) ||
446 (Size == 0 && !Ty->isSized() && !isArray()) ||
447 (TD.getTypeSize(Ty) == Size)) &&
448 "Size member of DSNode doesn't match the type structure!");
449 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
451 if (Offset == 0 && NewTy == Ty)
452 return false; // This should be a common case, handle it efficiently
454 // Return true immediately if the node is completely folded.
455 if (isNodeCompletelyFolded()) return true;
457 // If this is an array type, eliminate the outside arrays because they won't
458 // be used anyway. This greatly reduces the size of large static arrays used
459 // as global variables, for example.
461 bool WillBeArray = false;
462 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
463 // FIXME: we might want to keep small arrays, but must be careful about
464 // things like: [2 x [10000 x int*]]
465 NewTy = AT->getElementType();
469 // Figure out how big the new type we're merging in is...
470 unsigned NewTySize = NewTy->isSized() ? (unsigned)TD.getTypeSize(NewTy) : 0;
472 // Otherwise check to see if we can fold this type into the current node. If
473 // we can't, we fold the node completely, if we can, we potentially update our
476 if (Ty == Type::VoidTy) {
477 // If this is the first type that this node has seen, just accept it without
479 assert(Offset == 0 && !isArray() &&
480 "Cannot have an offset into a void node!");
482 // If this node would have to have an unreasonable number of fields, just
483 // collapse it. This can occur for fortran common blocks, which have stupid
484 // things like { [100000000 x double], [1000000 x double] }.
485 unsigned NumFields = (NewTySize+DS::PointerSize-1) >> DS::PointerShift;
486 if (NumFields > DSAFieldLimit) {
487 foldNodeCompletely();
493 if (WillBeArray) NodeType |= Array;
496 // Calculate the number of outgoing links from this node.
497 Links.resize(NumFields);
501 // Handle node expansion case here...
502 if (Offset+NewTySize > Size) {
503 // It is illegal to grow this node if we have treated it as an array of
506 if (FoldIfIncompatible) foldNodeCompletely();
510 // If this node would have to have an unreasonable number of fields, just
511 // collapse it. This can occur for fortran common blocks, which have stupid
512 // things like { [100000000 x double], [1000000 x double] }.
513 unsigned NumFields = (NewTySize+Offset+DS::PointerSize-1) >> DS::PointerShift;
514 if (NumFields > DSAFieldLimit) {
515 foldNodeCompletely();
520 //handle some common cases:
521 // Ty: struct { t1, t2, t3, t4, ..., tn}
522 // NewTy: struct { offset, stuff...}
523 // try merge with NewTy: struct {t1, t2, stuff...} if offset lands exactly
525 if (isa<StructType>(NewTy) && isa<StructType>(Ty)) {
526 DOUT << "Ty: " << *Ty << "\nNewTy: " << *NewTy << "@" << Offset << "\n";
527 const StructType *STy = cast<StructType>(Ty);
528 const StructLayout &SL = *TD.getStructLayout(STy);
529 unsigned i = SL.getElementContainingOffset(Offset);
530 //Either we hit it exactly or give up
531 if (SL.MemberOffsets[i] != Offset) {
532 if (FoldIfIncompatible) foldNodeCompletely();
535 std::vector<const Type*> nt;
536 for (unsigned x = 0; x < i; ++x)
537 nt.push_back(STy->getElementType(x));
538 STy = cast<StructType>(NewTy);
539 nt.insert(nt.end(), STy->element_begin(), STy->element_end());
541 STy = StructType::get(nt);
542 DOUT << "Trying with: " << *STy << "\n";
543 return mergeTypeInfo(STy, 0);
546 //Ty: struct { t1, t2, t3 ... tn}
548 //try merge with NewTy: struct : {t1, t2, T} if offset lands on a field
550 if (isa<StructType>(Ty)) {
551 DOUT << "Ty: " << *Ty << "\nNewTy: " << *NewTy << "@" << Offset << "\n";
552 const StructType *STy = cast<StructType>(Ty);
553 const StructLayout &SL = *TD.getStructLayout(STy);
554 unsigned i = SL.getElementContainingOffset(Offset);
555 //Either we hit it exactly or give up
556 if (SL.MemberOffsets[i] != Offset) {
557 if (FoldIfIncompatible) foldNodeCompletely();
560 std::vector<const Type*> nt;
561 for (unsigned x = 0; x < i; ++x)
562 nt.push_back(STy->getElementType(x));
565 STy = StructType::get(nt);
566 DOUT << "Trying with: " << *STy << "\n";
567 return mergeTypeInfo(STy, 0);
571 "UNIMP: Trying to merge a growth type into "
572 "offset != 0: Collapsing!");
574 if (FoldIfIncompatible) foldNodeCompletely();
580 // Okay, the situation is nice and simple, we are trying to merge a type in
581 // at offset 0 that is bigger than our current type. Implement this by
582 // switching to the new type and then merge in the smaller one, which should
583 // hit the other code path here. If the other code path decides it's not
584 // ok, it will collapse the node as appropriate.
587 const Type *OldTy = Ty;
590 if (WillBeArray) NodeType |= Array;
593 // Must grow links to be the appropriate size...
594 Links.resize(NumFields);
596 // Merge in the old type now... which is guaranteed to be smaller than the
598 return mergeTypeInfo(OldTy, 0);
601 assert(Offset <= Size &&
602 "Cannot merge something into a part of our type that doesn't exist!");
604 // Find the section of Ty that NewTy overlaps with... first we find the
605 // type that starts at offset Offset.
608 const Type *SubType = Ty;
610 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
612 switch (SubType->getTypeID()) {
613 case Type::StructTyID: {
614 const StructType *STy = cast<StructType>(SubType);
615 const StructLayout &SL = *TD.getStructLayout(STy);
616 unsigned i = SL.getElementContainingOffset(Offset-O);
618 // The offset we are looking for must be in the i'th element...
619 SubType = STy->getElementType(i);
620 O += (unsigned)SL.MemberOffsets[i];
623 case Type::ArrayTyID: {
624 SubType = cast<ArrayType>(SubType)->getElementType();
625 unsigned ElSize = (unsigned)TD.getTypeSize(SubType);
626 unsigned Remainder = (Offset-O) % ElSize;
627 O = Offset-Remainder;
631 if (FoldIfIncompatible) foldNodeCompletely();
636 assert(O == Offset && "Could not achieve the correct offset!");
638 // If we found our type exactly, early exit
639 if (SubType == NewTy) return false;
641 // Differing function types don't require us to merge. They are not values
643 if (isa<FunctionType>(SubType) &&
644 isa<FunctionType>(NewTy)) return false;
646 unsigned SubTypeSize = SubType->isSized() ?
647 (unsigned)TD.getTypeSize(SubType) : 0;
649 // Ok, we are getting desperate now. Check for physical subtyping, where we
650 // just require each element in the node to be compatible.
651 if (NewTySize <= SubTypeSize && NewTySize && NewTySize < 256 &&
652 SubTypeSize && SubTypeSize < 256 &&
653 ElementTypesAreCompatible(NewTy, SubType, !isArray(), TD))
656 // Okay, so we found the leader type at the offset requested. Search the list
657 // of types that starts at this offset. If SubType is currently an array or
658 // structure, the type desired may actually be the first element of the
661 unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
662 while (SubType != NewTy) {
663 const Type *NextSubType = 0;
664 unsigned NextSubTypeSize = 0;
665 unsigned NextPadSize = 0;
666 switch (SubType->getTypeID()) {
667 case Type::StructTyID: {
668 const StructType *STy = cast<StructType>(SubType);
669 const StructLayout &SL = *TD.getStructLayout(STy);
670 if (SL.MemberOffsets.size() > 1)
671 NextPadSize = (unsigned)SL.MemberOffsets[1];
673 NextPadSize = SubTypeSize;
674 NextSubType = STy->getElementType(0);
675 NextSubTypeSize = (unsigned)TD.getTypeSize(NextSubType);
678 case Type::ArrayTyID:
679 NextSubType = cast<ArrayType>(SubType)->getElementType();
680 NextSubTypeSize = (unsigned)TD.getTypeSize(NextSubType);
681 NextPadSize = NextSubTypeSize;
687 if (NextSubType == 0)
688 break; // In the default case, break out of the loop
690 if (NextPadSize < NewTySize)
691 break; // Don't allow shrinking to a smaller type than NewTySize
692 SubType = NextSubType;
693 SubTypeSize = NextSubTypeSize;
694 PadSize = NextPadSize;
697 // If we found the type exactly, return it...
698 if (SubType == NewTy)
701 // Check to see if we have a compatible, but different type...
702 if (NewTySize == SubTypeSize) {
703 // Check to see if this type is obviously convertible... int -> uint f.e.
704 if (NewTy->isLosslesslyConvertibleTo(SubType))
707 // Check to see if we have a pointer & integer mismatch going on here,
708 // loading a pointer as a long, for example.
710 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
711 NewTy->isInteger() && isa<PointerType>(SubType))
713 } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
714 // We are accessing the field, plus some structure padding. Ignore the
715 // structure padding.
720 if (getParentGraph()->retnodes_begin() != getParentGraph()->retnodes_end())
721 M = getParentGraph()->retnodes_begin()->first->getParent();
723 DOUT << "MergeTypeInfo Folding OrigTy: ";
724 DEBUG(WriteTypeSymbolic(std::cerr, Ty, M) << "\n due to:";
725 WriteTypeSymbolic(std::cerr, NewTy, M) << " @ " << Offset << "!\n"
727 WriteTypeSymbolic(std::cerr, SubType, M) << "\n\n");
729 if (FoldIfIncompatible) foldNodeCompletely();
735 /// addEdgeTo - Add an edge from the current node to the specified node. This
736 /// can cause merging of nodes in the graph.
738 void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
739 if (NH.isNull()) return; // Nothing to do
741 if (isNodeCompletelyFolded())
744 DSNodeHandle &ExistingEdge = getLink(Offset);
745 if (!ExistingEdge.isNull()) {
746 // Merge the two nodes...
747 ExistingEdge.mergeWith(NH);
748 } else { // No merging to perform...
749 setLink(Offset, NH); // Just force a link in there...
754 /// MergeSortedVectors - Efficiently merge a vector into another vector where
755 /// duplicates are not allowed and both are sorted. This assumes that 'T's are
756 /// efficiently copyable and have sane comparison semantics.
758 static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
759 const std::vector<GlobalValue*> &Src) {
760 // By far, the most common cases will be the simple ones. In these cases,
761 // avoid having to allocate a temporary vector...
763 if (Src.empty()) { // Nothing to merge in...
765 } else if (Dest.empty()) { // Just copy the result in...
767 } else if (Src.size() == 1) { // Insert a single element...
768 const GlobalValue *V = Src[0];
769 std::vector<GlobalValue*>::iterator I =
770 std::lower_bound(Dest.begin(), Dest.end(), V);
771 if (I == Dest.end() || *I != Src[0]) // If not already contained...
772 Dest.insert(I, Src[0]);
773 } else if (Dest.size() == 1) {
774 GlobalValue *Tmp = Dest[0]; // Save value in temporary...
775 Dest = Src; // Copy over list...
776 std::vector<GlobalValue*>::iterator I =
777 std::lower_bound(Dest.begin(), Dest.end(), Tmp);
778 if (I == Dest.end() || *I != Tmp) // If not already contained...
782 // Make a copy to the side of Dest...
783 std::vector<GlobalValue*> Old(Dest);
785 // Make space for all of the type entries now...
786 Dest.resize(Dest.size()+Src.size());
788 // Merge the two sorted ranges together... into Dest.
789 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
791 // Now erase any duplicate entries that may have accumulated into the
792 // vectors (because they were in both of the input sets)
793 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
797 void DSNode::mergeGlobals(const std::vector<GlobalValue*> &RHS) {
798 MergeSortedVectors(Globals, RHS);
801 // MergeNodes - Helper function for DSNode::mergeWith().
802 // This function does the hard work of merging two nodes, CurNodeH
803 // and NH after filtering out trivial cases and making sure that
804 // CurNodeH.offset >= NH.offset.
807 // Since merging may cause either node to go away, we must always
808 // use the node-handles to refer to the nodes. These node handles are
809 // automatically updated during merging, so will always provide access
810 // to the correct node after a merge.
812 void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
813 assert(CurNodeH.getOffset() >= NH.getOffset() &&
814 "This should have been enforced in the caller.");
815 assert(CurNodeH.getNode()->getParentGraph()==NH.getNode()->getParentGraph() &&
816 "Cannot merge two nodes that are not in the same graph!");
818 // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
819 // respect to NH.Offset) is now zero. NOffset is the distance from the base
820 // of our object that N starts from.
822 unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
823 unsigned NSize = NH.getNode()->getSize();
825 // If the two nodes are of different size, and the smaller node has the array
826 // bit set, collapse!
827 if (NSize != CurNodeH.getNode()->getSize()) {
828 #if COLLAPSE_ARRAYS_AGGRESSIVELY
829 if (NSize < CurNodeH.getNode()->getSize()) {
830 if (NH.getNode()->isArray())
831 NH.getNode()->foldNodeCompletely();
832 } else if (CurNodeH.getNode()->isArray()) {
833 NH.getNode()->foldNodeCompletely();
838 // Merge the type entries of the two nodes together...
839 if (NH.getNode()->Ty != Type::VoidTy)
840 CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
841 assert(!CurNodeH.getNode()->isDeadNode());
843 // If we are merging a node with a completely folded node, then both nodes are
844 // now completely folded.
846 if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
847 if (!NH.getNode()->isNodeCompletelyFolded()) {
848 NH.getNode()->foldNodeCompletely();
849 assert(NH.getNode() && NH.getOffset() == 0 &&
850 "folding did not make offset 0?");
851 NOffset = NH.getOffset();
852 NSize = NH.getNode()->getSize();
853 assert(NOffset == 0 && NSize == 1);
855 } else if (NH.getNode()->isNodeCompletelyFolded()) {
856 CurNodeH.getNode()->foldNodeCompletely();
857 assert(CurNodeH.getNode() && CurNodeH.getOffset() == 0 &&
858 "folding did not make offset 0?");
859 NSize = NH.getNode()->getSize();
860 NOffset = NH.getOffset();
861 assert(NOffset == 0 && NSize == 1);
864 DSNode *N = NH.getNode();
865 if (CurNodeH.getNode() == N || N == 0) return;
866 assert(!CurNodeH.getNode()->isDeadNode());
868 // Merge the NodeType information.
869 CurNodeH.getNode()->NodeType |= N->NodeType;
871 // Start forwarding to the new node!
872 N->forwardNode(CurNodeH.getNode(), NOffset);
873 assert(!CurNodeH.getNode()->isDeadNode());
875 // Make all of the outgoing links of N now be outgoing links of CurNodeH.
877 for (unsigned i = 0; i < N->getNumLinks(); ++i) {
878 DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
879 if (Link.getNode()) {
880 // Compute the offset into the current node at which to
881 // merge this link. In the common case, this is a linear
882 // relation to the offset in the original node (with
883 // wrapping), but if the current node gets collapsed due to
884 // recursive merging, we must make sure to merge in all remaining
885 // links at offset zero.
886 unsigned MergeOffset = 0;
887 DSNode *CN = CurNodeH.getNode();
889 MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
890 CN->addEdgeTo(MergeOffset, Link);
894 // Now that there are no outgoing edges, all of the Links are dead.
897 // Merge the globals list...
898 if (!N->Globals.empty()) {
899 CurNodeH.getNode()->mergeGlobals(N->Globals);
901 // Delete the globals from the old node...
902 std::vector<GlobalValue*>().swap(N->Globals);
907 /// mergeWith - Merge this node and the specified node, moving all links to and
908 /// from the argument node into the current node, deleting the node argument.
909 /// Offset indicates what offset the specified node is to be merged into the
912 /// The specified node may be a null pointer (in which case, we update it to
913 /// point to this node).
915 void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
916 DSNode *N = NH.getNode();
917 if (N == this && NH.getOffset() == Offset)
920 // If the RHS is a null node, make it point to this node!
922 NH.mergeWith(DSNodeHandle(this, Offset));
926 assert(!N->isDeadNode() && !isDeadNode());
927 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
930 // We cannot merge two pieces of the same node together, collapse the node
932 DOUT << "Attempting to merge two chunks of the same node together!\n";
933 foldNodeCompletely();
937 // If both nodes are not at offset 0, make sure that we are merging the node
938 // at an later offset into the node with the zero offset.
940 if (Offset < NH.getOffset()) {
941 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
943 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
944 // If the offsets are the same, merge the smaller node into the bigger node
945 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
949 // Ok, now we can merge the two nodes. Use a static helper that works with
950 // two node handles, since "this" may get merged away at intermediate steps.
951 DSNodeHandle CurNodeH(this, Offset);
952 DSNodeHandle NHCopy(NH);
953 if (CurNodeH.getOffset() >= NHCopy.getOffset())
954 DSNode::MergeNodes(CurNodeH, NHCopy);
956 DSNode::MergeNodes(NHCopy, CurNodeH);
960 //===----------------------------------------------------------------------===//
961 // ReachabilityCloner Implementation
962 //===----------------------------------------------------------------------===//
964 DSNodeHandle ReachabilityCloner::getClonedNH(const DSNodeHandle &SrcNH) {
965 if (SrcNH.isNull()) return DSNodeHandle();
966 const DSNode *SN = SrcNH.getNode();
968 DSNodeHandle &NH = NodeMap[SN];
969 if (!NH.isNull()) { // Node already mapped?
970 DSNode *NHN = NH.getNode();
971 return DSNodeHandle(NHN, NH.getOffset()+SrcNH.getOffset());
974 // If SrcNH has globals and the destination graph has one of the same globals,
975 // merge this node with the destination node, which is much more efficient.
976 if (SN->globals_begin() != SN->globals_end()) {
977 DSScalarMap &DestSM = Dest.getScalarMap();
978 for (DSNode::globals_iterator I = SN->globals_begin(),E = SN->globals_end();
980 GlobalValue *GV = *I;
981 DSScalarMap::iterator GI = DestSM.find(GV);
982 if (GI != DestSM.end() && !GI->second.isNull()) {
983 // We found one, use merge instead!
984 merge(GI->second, Src.getNodeForValue(GV));
985 assert(!NH.isNull() && "Didn't merge node!");
986 DSNode *NHN = NH.getNode();
987 return DSNodeHandle(NHN, NH.getOffset()+SrcNH.getOffset());
992 DSNode *DN = new DSNode(*SN, &Dest, true /* Null out all links */);
993 DN->maskNodeTypes(BitsToKeep);
996 // Next, recursively clone all outgoing links as necessary. Note that
997 // adding these links can cause the node to collapse itself at any time, and
998 // the current node may be merged with arbitrary other nodes. For this
999 // reason, we must always go through NH.
1001 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
1002 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
1003 if (!SrcEdge.isNull()) {
1004 const DSNodeHandle &DestEdge = getClonedNH(SrcEdge);
1005 // Compute the offset into the current node at which to
1006 // merge this link. In the common case, this is a linear
1007 // relation to the offset in the original node (with
1008 // wrapping), but if the current node gets collapsed due to
1009 // recursive merging, we must make sure to merge in all remaining
1010 // links at offset zero.
1011 unsigned MergeOffset = 0;
1012 DSNode *CN = NH.getNode();
1013 if (CN->getSize() != 1)
1014 MergeOffset = ((i << DS::PointerShift)+NH.getOffset()) % CN->getSize();
1015 CN->addEdgeTo(MergeOffset, DestEdge);
1019 // If this node contains any globals, make sure they end up in the scalar
1020 // map with the correct offset.
1021 for (DSNode::globals_iterator I = SN->globals_begin(), E = SN->globals_end();
1023 GlobalValue *GV = *I;
1024 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
1025 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
1026 assert(DestGNH.getNode() == NH.getNode() &&"Global mapping inconsistent");
1027 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
1028 DestGNH.getOffset()+SrcGNH.getOffset()));
1030 NH.getNode()->mergeGlobals(SN->getGlobalsList());
1032 return DSNodeHandle(NH.getNode(), NH.getOffset()+SrcNH.getOffset());
1035 void ReachabilityCloner::merge(const DSNodeHandle &NH,
1036 const DSNodeHandle &SrcNH) {
1037 if (SrcNH.isNull()) return; // Noop
1039 // If there is no destination node, just clone the source and assign the
1040 // destination node to be it.
1041 NH.mergeWith(getClonedNH(SrcNH));
1045 // Okay, at this point, we know that we have both a destination and a source
1046 // node that need to be merged. Check to see if the source node has already
1048 const DSNode *SN = SrcNH.getNode();
1049 DSNodeHandle &SCNH = NodeMap[SN]; // SourceClonedNodeHandle
1050 if (!SCNH.isNull()) { // Node already cloned?
1051 DSNode *SCNHN = SCNH.getNode();
1052 NH.mergeWith(DSNodeHandle(SCNHN,
1053 SCNH.getOffset()+SrcNH.getOffset()));
1054 return; // Nothing to do!
1057 // Okay, so the source node has not already been cloned. Instead of creating
1058 // a new DSNode, only to merge it into the one we already have, try to perform
1059 // the merge in-place. The only case we cannot handle here is when the offset
1060 // into the existing node is less than the offset into the virtual node we are
1061 // merging in. In this case, we have to extend the existing node, which
1062 // requires an allocation anyway.
1063 DSNode *DN = NH.getNode(); // Make sure the Offset is up-to-date
1064 if (NH.getOffset() >= SrcNH.getOffset()) {
1065 if (!DN->isNodeCompletelyFolded()) {
1066 // Make sure the destination node is folded if the source node is folded.
1067 if (SN->isNodeCompletelyFolded()) {
1068 DN->foldNodeCompletely();
1070 } else if (SN->getSize() != DN->getSize()) {
1071 // If the two nodes are of different size, and the smaller node has the
1072 // array bit set, collapse!
1073 #if COLLAPSE_ARRAYS_AGGRESSIVELY
1074 if (SN->getSize() < DN->getSize()) {
1075 if (SN->isArray()) {
1076 DN->foldNodeCompletely();
1079 } else if (DN->isArray()) {
1080 DN->foldNodeCompletely();
1086 // Merge the type entries of the two nodes together...
1087 if (SN->getType() != Type::VoidTy && !DN->isNodeCompletelyFolded()) {
1088 DN->mergeTypeInfo(SN->getType(), NH.getOffset()-SrcNH.getOffset());
1093 assert(!DN->isDeadNode());
1095 // Merge the NodeType information.
1096 DN->mergeNodeFlags(SN->getNodeFlags() & BitsToKeep);
1098 // Before we start merging outgoing links and updating the scalar map, make
1099 // sure it is known that this is the representative node for the src node.
1100 SCNH = DSNodeHandle(DN, NH.getOffset()-SrcNH.getOffset());
1102 // If the source node contains any globals, make sure they end up in the
1103 // scalar map with the correct offset.
1104 if (SN->globals_begin() != SN->globals_end()) {
1105 // Update the globals in the destination node itself.
1106 DN->mergeGlobals(SN->getGlobalsList());
1108 // Update the scalar map for the graph we are merging the source node
1110 for (DSNode::globals_iterator I = SN->globals_begin(),
1111 E = SN->globals_end(); I != E; ++I) {
1112 GlobalValue *GV = *I;
1113 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
1114 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
1115 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
1116 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
1117 DestGNH.getOffset()+SrcGNH.getOffset()));
1119 NH.getNode()->mergeGlobals(SN->getGlobalsList());
1122 // We cannot handle this case without allocating a temporary node. Fall
1123 // back on being simple.
1124 DSNode *NewDN = new DSNode(*SN, &Dest, true /* Null out all links */);
1125 NewDN->maskNodeTypes(BitsToKeep);
1127 unsigned NHOffset = NH.getOffset();
1128 NH.mergeWith(DSNodeHandle(NewDN, SrcNH.getOffset()));
1130 assert(NH.getNode() &&
1131 (NH.getOffset() > NHOffset ||
1132 (NH.getOffset() == 0 && NH.getNode()->isNodeCompletelyFolded())) &&
1133 "Merging did not adjust the offset!");
1135 // Before we start merging outgoing links and updating the scalar map, make
1136 // sure it is known that this is the representative node for the src node.
1137 SCNH = DSNodeHandle(NH.getNode(), NH.getOffset()-SrcNH.getOffset());
1139 // If the source node contained any globals, make sure to create entries
1140 // in the scalar map for them!
1141 for (DSNode::globals_iterator I = SN->globals_begin(),
1142 E = SN->globals_end(); I != E; ++I) {
1143 GlobalValue *GV = *I;
1144 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
1145 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
1146 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
1147 assert(SrcGNH.getNode() == SN && "Global mapping inconsistent");
1148 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
1149 DestGNH.getOffset()+SrcGNH.getOffset()));
1154 // Next, recursively merge all outgoing links as necessary. Note that
1155 // adding these links can cause the destination node to collapse itself at
1156 // any time, and the current node may be merged with arbitrary other nodes.
1157 // For this reason, we must always go through NH.
1159 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
1160 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
1161 if (!SrcEdge.isNull()) {
1162 // Compute the offset into the current node at which to
1163 // merge this link. In the common case, this is a linear
1164 // relation to the offset in the original node (with
1165 // wrapping), but if the current node gets collapsed due to
1166 // recursive merging, we must make sure to merge in all remaining
1167 // links at offset zero.
1168 DSNode *CN = SCNH.getNode();
1169 unsigned MergeOffset =
1170 ((i << DS::PointerShift)+SCNH.getOffset()) % CN->getSize();
1172 DSNodeHandle Tmp = CN->getLink(MergeOffset);
1173 if (!Tmp.isNull()) {
1174 // Perform the recursive merging. Make sure to create a temporary NH,
1175 // because the Link can disappear in the process of recursive merging.
1176 merge(Tmp, SrcEdge);
1178 Tmp.mergeWith(getClonedNH(SrcEdge));
1179 // Merging this could cause all kinds of recursive things to happen,
1180 // culminating in the current node being eliminated. Since this is
1181 // possible, make sure to reaquire the link from 'CN'.
1183 unsigned MergeOffset = 0;
1184 CN = SCNH.getNode();
1185 MergeOffset = ((i << DS::PointerShift)+SCNH.getOffset()) %CN->getSize();
1186 CN->getLink(MergeOffset).mergeWith(Tmp);
1192 /// mergeCallSite - Merge the nodes reachable from the specified src call
1193 /// site into the nodes reachable from DestCS.
1194 void ReachabilityCloner::mergeCallSite(DSCallSite &DestCS,
1195 const DSCallSite &SrcCS) {
1196 merge(DestCS.getRetVal(), SrcCS.getRetVal());
1197 unsigned MinArgs = DestCS.getNumPtrArgs();
1198 if (SrcCS.getNumPtrArgs() < MinArgs) MinArgs = SrcCS.getNumPtrArgs();
1200 for (unsigned a = 0; a != MinArgs; ++a)
1201 merge(DestCS.getPtrArg(a), SrcCS.getPtrArg(a));
1203 for (unsigned a = MinArgs, e = SrcCS.getNumPtrArgs(); a != e; ++a)
1204 DestCS.addPtrArg(getClonedNH(SrcCS.getPtrArg(a)));
1208 //===----------------------------------------------------------------------===//
1209 // DSCallSite Implementation
1210 //===----------------------------------------------------------------------===//
1212 // Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
1213 Function &DSCallSite::getCaller() const {
1214 return *Site.getInstruction()->getParent()->getParent();
1217 void DSCallSite::InitNH(DSNodeHandle &NH, const DSNodeHandle &Src,
1218 ReachabilityCloner &RC) {
1219 NH = RC.getClonedNH(Src);
1222 //===----------------------------------------------------------------------===//
1223 // DSGraph Implementation
1224 //===----------------------------------------------------------------------===//
1226 /// getFunctionNames - Return a space separated list of the name of the
1227 /// functions in this graph (if any)
1228 std::string DSGraph::getFunctionNames() const {
1229 switch (getReturnNodes().size()) {
1230 case 0: return "Globals graph";
1231 case 1: return retnodes_begin()->first->getName();
1234 for (DSGraph::retnodes_iterator I = retnodes_begin();
1235 I != retnodes_end(); ++I)
1236 Return += I->first->getName() + " ";
1237 Return.erase(Return.end()-1, Return.end()); // Remove last space character
1243 DSGraph::DSGraph(const DSGraph &G, EquivalenceClasses<GlobalValue*> &ECs,
1244 unsigned CloneFlags)
1245 : GlobalsGraph(0), ScalarMap(ECs), TD(G.TD) {
1246 PrintAuxCalls = false;
1247 cloneInto(G, CloneFlags);
1250 DSGraph::~DSGraph() {
1251 FunctionCalls.clear();
1252 AuxFunctionCalls.clear();
1254 ReturnNodes.clear();
1256 // Drop all intra-node references, so that assertions don't fail...
1257 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
1258 NI->dropAllReferences();
1260 // Free all of the nodes.
1264 // dump - Allow inspection of graph in a debugger.
1265 void DSGraph::dump() const { print(std::cerr); }
1268 /// remapLinks - Change all of the Links in the current node according to the
1269 /// specified mapping.
1271 void DSNode::remapLinks(DSGraph::NodeMapTy &OldNodeMap) {
1272 for (unsigned i = 0, e = Links.size(); i != e; ++i)
1273 if (DSNode *N = Links[i].getNode()) {
1274 DSGraph::NodeMapTy::const_iterator ONMI = OldNodeMap.find(N);
1275 if (ONMI != OldNodeMap.end()) {
1276 DSNode *ONMIN = ONMI->second.getNode();
1277 Links[i].setTo(ONMIN, Links[i].getOffset()+ONMI->second.getOffset());
1282 /// addObjectToGraph - This method can be used to add global, stack, and heap
1283 /// objects to the graph. This can be used when updating DSGraphs due to the
1284 /// introduction of new temporary objects. The new object is not pointed to
1285 /// and does not point to any other objects in the graph.
1286 DSNode *DSGraph::addObjectToGraph(Value *Ptr, bool UseDeclaredType) {
1287 assert(isa<PointerType>(Ptr->getType()) && "Ptr is not a pointer!");
1288 const Type *Ty = cast<PointerType>(Ptr->getType())->getElementType();
1289 DSNode *N = new DSNode(UseDeclaredType ? Ty : 0, this);
1290 assert(ScalarMap[Ptr].isNull() && "Object already in this graph!");
1293 if (GlobalValue *GV = dyn_cast<GlobalValue>(Ptr)) {
1295 } else if (isa<MallocInst>(Ptr)) {
1296 N->setHeapNodeMarker();
1297 } else if (isa<AllocaInst>(Ptr)) {
1298 N->setAllocaNodeMarker();
1300 assert(0 && "Illegal memory object input!");
1306 /// cloneInto - Clone the specified DSGraph into the current graph. The
1307 /// translated ScalarMap for the old function is filled into the ScalarMap
1308 /// for the graph, and the translated ReturnNodes map is returned into
1311 /// The CloneFlags member controls various aspects of the cloning process.
1313 void DSGraph::cloneInto(const DSGraph &G, unsigned CloneFlags) {
1314 TIME_REGION(X, "cloneInto");
1315 assert(&G != this && "Cannot clone graph into itself!");
1317 NodeMapTy OldNodeMap;
1319 // Remove alloca or mod/ref bits as specified...
1320 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
1321 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
1322 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
1323 BitsToClear |= DSNode::DEAD; // Clear dead flag...
1325 for (node_const_iterator I = G.node_begin(), E = G.node_end(); I != E; ++I) {
1326 assert(!I->isForwarding() &&
1327 "Forward nodes shouldn't be in node list!");
1328 DSNode *New = new DSNode(*I, this);
1329 New->maskNodeTypes(~BitsToClear);
1330 OldNodeMap[I] = New;
1334 Timer::addPeakMemoryMeasurement();
1337 // Rewrite the links in the new nodes to point into the current graph now.
1338 // Note that we don't loop over the node's list to do this. The problem is
1339 // that remaping links can cause recursive merging to happen, which means
1340 // that node_iterator's can get easily invalidated! Because of this, we
1341 // loop over the OldNodeMap, which contains all of the new nodes as the
1342 // .second element of the map elements. Also note that if we remap a node
1343 // more than once, we won't break anything.
1344 for (NodeMapTy::iterator I = OldNodeMap.begin(), E = OldNodeMap.end();
1346 I->second.getNode()->remapLinks(OldNodeMap);
1348 // Copy the scalar map... merging all of the global nodes...
1349 for (DSScalarMap::const_iterator I = G.ScalarMap.begin(),
1350 E = G.ScalarMap.end(); I != E; ++I) {
1351 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
1352 DSNodeHandle &H = ScalarMap.getRawEntryRef(I->first);
1353 DSNode *MappedNodeN = MappedNode.getNode();
1354 H.mergeWith(DSNodeHandle(MappedNodeN,
1355 I->second.getOffset()+MappedNode.getOffset()));
1358 if (!(CloneFlags & DontCloneCallNodes)) {
1359 // Copy the function calls list.
1360 for (fc_iterator I = G.fc_begin(), E = G.fc_end(); I != E; ++I)
1361 FunctionCalls.push_back(DSCallSite(*I, OldNodeMap));
1364 if (!(CloneFlags & DontCloneAuxCallNodes)) {
1365 // Copy the auxiliary function calls list.
1366 for (afc_iterator I = G.afc_begin(), E = G.afc_end(); I != E; ++I)
1367 AuxFunctionCalls.push_back(DSCallSite(*I, OldNodeMap));
1370 // Map the return node pointers over...
1371 for (retnodes_iterator I = G.retnodes_begin(),
1372 E = G.retnodes_end(); I != E; ++I) {
1373 const DSNodeHandle &Ret = I->second;
1374 DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
1375 DSNode *MappedRetN = MappedRet.getNode();
1376 ReturnNodes.insert(std::make_pair(I->first,
1377 DSNodeHandle(MappedRetN,
1378 MappedRet.getOffset()+Ret.getOffset())));
1382 /// spliceFrom - Logically perform the operation of cloning the RHS graph into
1383 /// this graph, then clearing the RHS graph. Instead of performing this as
1384 /// two seperate operations, do it as a single, much faster, one.
1386 void DSGraph::spliceFrom(DSGraph &RHS) {
1387 // Change all of the nodes in RHS to think we are their parent.
1388 for (NodeListTy::iterator I = RHS.Nodes.begin(), E = RHS.Nodes.end();
1390 I->setParentGraph(this);
1391 // Take all of the nodes.
1392 Nodes.splice(Nodes.end(), RHS.Nodes);
1394 // Take all of the calls.
1395 FunctionCalls.splice(FunctionCalls.end(), RHS.FunctionCalls);
1396 AuxFunctionCalls.splice(AuxFunctionCalls.end(), RHS.AuxFunctionCalls);
1398 // Take all of the return nodes.
1399 if (ReturnNodes.empty()) {
1400 ReturnNodes.swap(RHS.ReturnNodes);
1402 ReturnNodes.insert(RHS.ReturnNodes.begin(), RHS.ReturnNodes.end());
1403 RHS.ReturnNodes.clear();
1406 // Merge the scalar map in.
1407 ScalarMap.spliceFrom(RHS.ScalarMap);
1410 /// spliceFrom - Copy all entries from RHS, then clear RHS.
1412 void DSScalarMap::spliceFrom(DSScalarMap &RHS) {
1413 // Special case if this is empty.
1414 if (ValueMap.empty()) {
1415 ValueMap.swap(RHS.ValueMap);
1416 GlobalSet.swap(RHS.GlobalSet);
1418 GlobalSet.insert(RHS.GlobalSet.begin(), RHS.GlobalSet.end());
1419 for (ValueMapTy::iterator I = RHS.ValueMap.begin(), E = RHS.ValueMap.end();
1421 ValueMap[I->first].mergeWith(I->second);
1422 RHS.ValueMap.clear();
1427 /// getFunctionArgumentsForCall - Given a function that is currently in this
1428 /// graph, return the DSNodeHandles that correspond to the pointer-compatible
1429 /// function arguments. The vector is filled in with the return value (or
1430 /// null if it is not pointer compatible), followed by all of the
1431 /// pointer-compatible arguments.
1432 void DSGraph::getFunctionArgumentsForCall(Function *F,
1433 std::vector<DSNodeHandle> &Args) const {
1434 Args.push_back(getReturnNodeFor(*F));
1435 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1437 if (isPointerType(AI->getType())) {
1438 Args.push_back(getNodeForValue(AI));
1439 assert(!Args.back().isNull() && "Pointer argument w/o scalarmap entry!?");
1444 // HackedGraphSCCFinder - This is used to find nodes that have a path from the
1445 // node to a node cloned by the ReachabilityCloner object contained. To be
1446 // extra obnoxious it ignores edges from nodes that are globals, and truncates
1447 // search at RC marked nodes. This is designed as an object so that
1448 // intermediate results can be memoized across invocations of
1449 // PathExistsToClonedNode.
1450 struct HackedGraphSCCFinder {
1451 ReachabilityCloner &RC;
1453 std::vector<const DSNode*> SCCStack;
1454 std::map<const DSNode*, std::pair<unsigned, bool> > NodeInfo;
1456 HackedGraphSCCFinder(ReachabilityCloner &rc) : RC(rc), CurNodeId(1) {
1457 // Remove null pointer as a special case.
1458 NodeInfo[0] = std::make_pair(0, false);
1461 std::pair<unsigned, bool> &VisitForSCCs(const DSNode *N);
1463 bool PathExistsToClonedNode(const DSNode *N) {
1464 return VisitForSCCs(N).second;
1467 bool PathExistsToClonedNode(const DSCallSite &CS) {
1468 if (PathExistsToClonedNode(CS.getRetVal().getNode()))
1470 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
1471 if (PathExistsToClonedNode(CS.getPtrArg(i).getNode()))
1478 std::pair<unsigned, bool> &HackedGraphSCCFinder::
1479 VisitForSCCs(const DSNode *N) {
1480 std::map<const DSNode*, std::pair<unsigned, bool> >::iterator
1481 NodeInfoIt = NodeInfo.lower_bound(N);
1482 if (NodeInfoIt != NodeInfo.end() && NodeInfoIt->first == N)
1483 return NodeInfoIt->second;
1485 unsigned Min = CurNodeId++;
1486 unsigned MyId = Min;
1487 std::pair<unsigned, bool> &ThisNodeInfo =
1488 NodeInfo.insert(NodeInfoIt,
1489 std::make_pair(N, std::make_pair(MyId, false)))->second;
1491 // Base case: if we find a global, this doesn't reach the cloned graph
1493 if (N->isGlobalNode()) {
1494 ThisNodeInfo.second = false;
1495 return ThisNodeInfo;
1498 // Base case: if this does reach the cloned graph portion... it does. :)
1499 if (RC.hasClonedNode(N)) {
1500 ThisNodeInfo.second = true;
1501 return ThisNodeInfo;
1504 SCCStack.push_back(N);
1506 // Otherwise, check all successors.
1507 bool AnyDirectSuccessorsReachClonedNodes = false;
1508 for (DSNode::const_edge_iterator EI = N->edge_begin(), EE = N->edge_end();
1510 if (DSNode *Succ = EI->getNode()) {
1511 std::pair<unsigned, bool> &SuccInfo = VisitForSCCs(Succ);
1512 if (SuccInfo.first < Min) Min = SuccInfo.first;
1513 AnyDirectSuccessorsReachClonedNodes |= SuccInfo.second;
1517 return ThisNodeInfo; // Part of a large SCC. Leave self on stack.
1519 if (SCCStack.back() == N) { // Special case single node SCC.
1520 SCCStack.pop_back();
1521 ThisNodeInfo.second = AnyDirectSuccessorsReachClonedNodes;
1522 return ThisNodeInfo;
1525 // Find out if any direct successors of any node reach cloned nodes.
1526 if (!AnyDirectSuccessorsReachClonedNodes)
1527 for (unsigned i = SCCStack.size()-1; SCCStack[i] != N; --i)
1528 for (DSNode::const_edge_iterator EI = N->edge_begin(), EE = N->edge_end();
1530 if (DSNode *N = EI->getNode())
1531 if (NodeInfo[N].second) {
1532 AnyDirectSuccessorsReachClonedNodes = true;
1536 // If any successor reaches a cloned node, mark all nodes in this SCC as
1537 // reaching the cloned node.
1538 if (AnyDirectSuccessorsReachClonedNodes)
1539 while (SCCStack.back() != N) {
1540 NodeInfo[SCCStack.back()].second = true;
1541 SCCStack.pop_back();
1543 SCCStack.pop_back();
1544 ThisNodeInfo.second = true;
1545 return ThisNodeInfo;
1548 /// mergeInCallFromOtherGraph - This graph merges in the minimal number of
1549 /// nodes from G2 into 'this' graph, merging the bindings specified by the
1550 /// call site (in this graph) with the bindings specified by the vector in G2.
1551 /// The two DSGraphs must be different.
1553 void DSGraph::mergeInGraph(const DSCallSite &CS,
1554 std::vector<DSNodeHandle> &Args,
1555 const DSGraph &Graph, unsigned CloneFlags) {
1556 TIME_REGION(X, "mergeInGraph");
1558 assert((CloneFlags & DontCloneCallNodes) &&
1559 "Doesn't support copying of call nodes!");
1561 // If this is not a recursive call, clone the graph into this graph...
1562 if (&Graph == this) {
1563 // Merge the return value with the return value of the context.
1564 Args[0].mergeWith(CS.getRetVal());
1566 // Resolve all of the function arguments.
1567 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i) {
1568 if (i == Args.size()-1)
1571 // Add the link from the argument scalar to the provided value.
1572 Args[i+1].mergeWith(CS.getPtrArg(i));
1577 // Clone the callee's graph into the current graph, keeping track of where
1578 // scalars in the old graph _used_ to point, and of the new nodes matching
1579 // nodes of the old graph.
1580 ReachabilityCloner RC(*this, Graph, CloneFlags);
1582 // Map the return node pointer over.
1583 if (!CS.getRetVal().isNull())
1584 RC.merge(CS.getRetVal(), Args[0]);
1586 // Map over all of the arguments.
1587 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i) {
1588 if (i == Args.size()-1)
1591 // Add the link from the argument scalar to the provided value.
1592 RC.merge(CS.getPtrArg(i), Args[i+1]);
1595 // We generally don't want to copy global nodes or aux calls from the callee
1596 // graph to the caller graph. However, we have to copy them if there is a
1597 // path from the node to a node we have already copied which does not go
1598 // through another global. Compute the set of node that can reach globals and
1599 // aux call nodes to copy over, then do it.
1600 std::vector<const DSCallSite*> AuxCallToCopy;
1601 std::vector<GlobalValue*> GlobalsToCopy;
1603 // NodesReachCopiedNodes - Memoize results for efficiency. Contains a
1604 // true/false value for every visited node that reaches a copied node without
1605 // going through a global.
1606 HackedGraphSCCFinder SCCFinder(RC);
1608 if (!(CloneFlags & DontCloneAuxCallNodes))
1609 for (afc_iterator I = Graph.afc_begin(), E = Graph.afc_end(); I!=E; ++I)
1610 if (SCCFinder.PathExistsToClonedNode(*I))
1611 AuxCallToCopy.push_back(&*I);
1612 // else if (I->isIndirectCall()){
1613 // //If the call node doesn't have any callees, clone it
1614 // std::vector< Function *> List;
1615 // I->getCalleeNode()->addFullFunctionList(List);
1616 // if (!List.size())
1617 // AuxCallToCopy.push_back(&*I);
1620 const DSScalarMap &GSM = Graph.getScalarMap();
1621 for (DSScalarMap::global_iterator GI = GSM.global_begin(),
1622 E = GSM.global_end(); GI != E; ++GI) {
1623 DSNode *GlobalNode = Graph.getNodeForValue(*GI).getNode();
1624 for (DSNode::edge_iterator EI = GlobalNode->edge_begin(),
1625 EE = GlobalNode->edge_end(); EI != EE; ++EI)
1626 if (SCCFinder.PathExistsToClonedNode(EI->getNode())) {
1627 GlobalsToCopy.push_back(*GI);
1632 // Copy aux calls that are needed.
1633 for (unsigned i = 0, e = AuxCallToCopy.size(); i != e; ++i)
1634 AuxFunctionCalls.push_back(DSCallSite(*AuxCallToCopy[i], RC));
1636 // Copy globals that are needed.
1637 for (unsigned i = 0, e = GlobalsToCopy.size(); i != e; ++i)
1638 RC.getClonedNH(Graph.getNodeForValue(GlobalsToCopy[i]));
1643 /// mergeInGraph - The method is used for merging graphs together. If the
1644 /// argument graph is not *this, it makes a clone of the specified graph, then
1645 /// merges the nodes specified in the call site with the formal arguments in the
1648 void DSGraph::mergeInGraph(const DSCallSite &CS, Function &F,
1649 const DSGraph &Graph, unsigned CloneFlags) {
1650 // Set up argument bindings.
1651 std::vector<DSNodeHandle> Args;
1652 Graph.getFunctionArgumentsForCall(&F, Args);
1654 mergeInGraph(CS, Args, Graph, CloneFlags);
1657 /// getCallSiteForArguments - Get the arguments and return value bindings for
1658 /// the specified function in the current graph.
1660 DSCallSite DSGraph::getCallSiteForArguments(Function &F) const {
1661 std::vector<DSNodeHandle> Args;
1663 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I)
1664 if (isPointerType(I->getType()))
1665 Args.push_back(getNodeForValue(I));
1667 return DSCallSite(CallSite(), getReturnNodeFor(F), &F, Args);
1670 /// getDSCallSiteForCallSite - Given an LLVM CallSite object that is live in
1671 /// the context of this graph, return the DSCallSite for it.
1672 DSCallSite DSGraph::getDSCallSiteForCallSite(CallSite CS) const {
1673 DSNodeHandle RetVal;
1674 Instruction *I = CS.getInstruction();
1675 if (isPointerType(I->getType()))
1676 RetVal = getNodeForValue(I);
1678 std::vector<DSNodeHandle> Args;
1679 Args.reserve(CS.arg_end()-CS.arg_begin());
1681 // Calculate the arguments vector...
1682 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); I != E; ++I)
1683 if (isPointerType((*I)->getType()))
1684 if (isa<ConstantPointerNull>(*I))
1685 Args.push_back(DSNodeHandle());
1687 Args.push_back(getNodeForValue(*I));
1689 // Add a new function call entry...
1690 if (Function *F = CS.getCalledFunction())
1691 return DSCallSite(CS, RetVal, F, Args);
1693 return DSCallSite(CS, RetVal,
1694 getNodeForValue(CS.getCalledValue()).getNode(), Args);
1699 // markIncompleteNodes - Mark the specified node as having contents that are not
1700 // known with the current analysis we have performed. Because a node makes all
1701 // of the nodes it can reach incomplete if the node itself is incomplete, we
1702 // must recursively traverse the data structure graph, marking all reachable
1703 // nodes as incomplete.
1705 static void markIncompleteNode(DSNode *N) {
1706 // Stop recursion if no node, or if node already marked...
1707 if (N == 0 || N->isIncomplete()) return;
1709 // Actually mark the node
1710 N->setIncompleteMarker();
1712 // Recursively process children...
1713 for (DSNode::edge_iterator I = N->edge_begin(),E = N->edge_end(); I != E; ++I)
1714 if (DSNode *DSN = I->getNode())
1715 markIncompleteNode(DSN);
1718 static void markIncomplete(DSCallSite &Call) {
1719 // Then the return value is certainly incomplete!
1720 markIncompleteNode(Call.getRetVal().getNode());
1722 // All objects pointed to by function arguments are incomplete!
1723 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
1724 markIncompleteNode(Call.getPtrArg(i).getNode());
1727 // markIncompleteNodes - Traverse the graph, identifying nodes that may be
1728 // modified by other functions that have not been resolved yet. This marks
1729 // nodes that are reachable through three sources of "unknownness":
1731 // Global Variables, Function Calls, and Incoming Arguments
1733 // For any node that may have unknown components (because something outside the
1734 // scope of current analysis may have modified it), the 'Incomplete' flag is
1735 // added to the NodeType.
1737 void DSGraph::markIncompleteNodes(unsigned Flags) {
1738 // Mark any incoming arguments as incomplete.
1739 if (Flags & DSGraph::MarkFormalArgs)
1740 for (ReturnNodesTy::iterator FI = ReturnNodes.begin(), E =ReturnNodes.end();
1742 Function &F = *FI->first;
1743 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
1745 if (isPointerType(I->getType()))
1746 markIncompleteNode(getNodeForValue(I).getNode());
1747 markIncompleteNode(FI->second.getNode());
1750 // Mark stuff passed into functions calls as being incomplete.
1751 if (!shouldPrintAuxCalls())
1752 for (std::list<DSCallSite>::iterator I = FunctionCalls.begin(),
1753 E = FunctionCalls.end(); I != E; ++I)
1756 for (std::list<DSCallSite>::iterator I = AuxFunctionCalls.begin(),
1757 E = AuxFunctionCalls.end(); I != E; ++I)
1760 // Mark all global nodes as incomplete.
1761 for (DSScalarMap::global_iterator I = ScalarMap.global_begin(),
1762 E = ScalarMap.global_end(); I != E; ++I)
1763 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I))
1764 if (!GV->hasInitializer() || // Always mark external globals incomp.
1765 (!GV->isConstant() && (Flags & DSGraph::IgnoreGlobals) == 0))
1766 markIncompleteNode(ScalarMap[GV].getNode());
1769 static inline void killIfUselessEdge(DSNodeHandle &Edge) {
1770 if (DSNode *N = Edge.getNode()) // Is there an edge?
1771 if (N->getNumReferrers() == 1) // Does it point to a lonely node?
1772 // No interesting info?
1773 if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
1774 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
1775 Edge.setTo(0, 0); // Kill the edge!
1778 static inline bool nodeContainsExternalFunction(const DSNode *N) {
1779 std::vector<Function*> Funcs;
1780 N->addFullFunctionList(Funcs);
1781 for (unsigned i = 0, e = Funcs.size(); i != e; ++i)
1782 if (Funcs[i]->isExternal()) return true;
1786 static void removeIdenticalCalls(std::list<DSCallSite> &Calls) {
1787 // Remove trivially identical function calls
1788 Calls.sort(); // Sort by callee as primary key!
1790 // Scan the call list cleaning it up as necessary...
1791 DSNodeHandle LastCalleeNode;
1793 Function *LastCalleeFunc = 0;
1794 unsigned NumDuplicateCalls = 0;
1796 bool LastCalleeContainsExternalFunction = false;
1798 unsigned NumDeleted = 0;
1799 for (std::list<DSCallSite>::iterator I = Calls.begin(), E = Calls.end();
1801 DSCallSite &CS = *I;
1802 std::list<DSCallSite>::iterator OldIt = I++;
1804 if (!CS.isIndirectCall()) {
1807 DSNode *Callee = CS.getCalleeNode();
1809 // If the Callee is a useless edge, this must be an unreachable call site,
1811 if (Callee->getNumReferrers() == 1 && Callee->isComplete() &&
1812 Callee->getGlobalsList().empty()) { // No useful info?
1813 DOUT << "WARNING: Useless call site found.\n";
1819 // If the last call site in the list has the same callee as this one, and
1820 // if the callee contains an external function, it will never be
1821 // resolvable, just merge the call sites.
1822 if (!LastCalleeNode.isNull() && LastCalleeNode.getNode() == Callee) {
1823 LastCalleeContainsExternalFunction =
1824 nodeContainsExternalFunction(Callee);
1826 std::list<DSCallSite>::iterator PrevIt = OldIt;
1828 PrevIt->mergeWith(CS);
1830 // No need to keep this call anymore.
1835 LastCalleeNode = Callee;
1839 // If the return value or any arguments point to a void node with no
1840 // information at all in it, and the call node is the only node to point
1841 // to it, remove the edge to the node (killing the node).
1843 killIfUselessEdge(CS.getRetVal());
1844 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
1845 killIfUselessEdge(CS.getPtrArg(a));
1848 // If this call site calls the same function as the last call site, and if
1849 // the function pointer contains an external function, this node will
1850 // never be resolved. Merge the arguments of the call node because no
1851 // information will be lost.
1853 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
1854 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
1855 ++NumDuplicateCalls;
1856 if (NumDuplicateCalls == 1) {
1858 LastCalleeContainsExternalFunction =
1859 nodeContainsExternalFunction(LastCalleeNode);
1861 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
1864 // It is not clear why, but enabling this code makes DSA really
1865 // sensitive to node forwarding. Basically, with this enabled, DSA
1866 // performs different number of inlinings based on which nodes are
1867 // forwarding or not. This is clearly a problem, so this code is
1868 // disabled until this can be resolved.
1870 if (LastCalleeContainsExternalFunction
1873 // This should be more than enough context sensitivity!
1874 // FIXME: Evaluate how many times this is tripped!
1875 NumDuplicateCalls > 20
1879 std::list<DSCallSite>::iterator PrevIt = OldIt;
1881 PrevIt->mergeWith(CS);
1883 // No need to keep this call anymore.
1890 if (CS.isDirectCall()) {
1891 LastCalleeFunc = CS.getCalleeFunc();
1894 LastCalleeNode = CS.getCalleeNode();
1897 NumDuplicateCalls = 0;
1901 if (I != Calls.end() && CS == *I) {
1909 // Resort now that we simplified things.
1912 // Now that we are in sorted order, eliminate duplicates.
1913 std::list<DSCallSite>::iterator CI = Calls.begin(), CE = Calls.end();
1916 std::list<DSCallSite>::iterator OldIt = CI++;
1917 if (CI == CE) break;
1919 // If this call site is now the same as the previous one, we can delete it
1921 if (*OldIt == *CI) {
1928 //Calls.erase(std::unique(Calls.begin(), Calls.end()), Calls.end());
1930 // Track the number of call nodes merged away...
1931 NumCallNodesMerged += NumDeleted;
1934 DOUT << "Merged " << NumDeleted << " call nodes.\n";
1938 // removeTriviallyDeadNodes - After the graph has been constructed, this method
1939 // removes all unreachable nodes that are created because they got merged with
1940 // other nodes in the graph. These nodes will all be trivially unreachable, so
1941 // we don't have to perform any non-trivial analysis here.
1943 void DSGraph::removeTriviallyDeadNodes() {
1944 TIME_REGION(X, "removeTriviallyDeadNodes");
1947 /// NOTE: This code is disabled. This slows down DSA on 177.mesa
1950 // Loop over all of the nodes in the graph, calling getNode on each field.
1951 // This will cause all nodes to update their forwarding edges, causing
1952 // forwarded nodes to be delete-able.
1953 { TIME_REGION(X, "removeTriviallyDeadNodes:node_iterate");
1954 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI) {
1956 for (unsigned l = 0, e = N.getNumLinks(); l != e; ++l)
1957 N.getLink(l*N.getPointerSize()).getNode();
1961 // NOTE: This code is disabled. Though it should, in theory, allow us to
1962 // remove more nodes down below, the scan of the scalar map is incredibly
1963 // expensive for certain programs (with large SCCs). In the future, if we can
1964 // make the scalar map scan more efficient, then we can reenable this.
1965 { TIME_REGION(X, "removeTriviallyDeadNodes:scalarmap");
1967 // Likewise, forward any edges from the scalar nodes. While we are at it,
1968 // clean house a bit.
1969 for (DSScalarMap::iterator I = ScalarMap.begin(),E = ScalarMap.end();I != E;){
1970 I->second.getNode();
1975 bool isGlobalsGraph = !GlobalsGraph;
1977 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E; ) {
1980 // Do not remove *any* global nodes in the globals graph.
1981 // This is a special case because such nodes may not have I, M, R flags set.
1982 if (Node.isGlobalNode() && isGlobalsGraph) {
1987 if (Node.isComplete() && !Node.isModified() && !Node.isRead()) {
1988 // This is a useless node if it has no mod/ref info (checked above),
1989 // outgoing edges (which it cannot, as it is not modified in this
1990 // context), and it has no incoming edges. If it is a global node it may
1991 // have all of these properties and still have incoming edges, due to the
1992 // scalar map, so we check those now.
1994 if (Node.getNumReferrers() == Node.getGlobalsList().size()) {
1995 const std::vector<GlobalValue*> &Globals = Node.getGlobalsList();
1997 // Loop through and make sure all of the globals are referring directly
1999 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
2000 DSNode *N = getNodeForValue(Globals[j]).getNode();
2001 assert(N == &Node && "ScalarMap doesn't match globals list!");
2004 // Make sure NumReferrers still agrees, if so, the node is truly dead.
2005 if (Node.getNumReferrers() == Globals.size()) {
2006 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
2007 ScalarMap.erase(Globals[j]);
2008 Node.makeNodeDead();
2009 ++NumTrivialGlobalDNE;
2014 if (Node.getNodeFlags() == 0 && Node.hasNoReferrers()) {
2015 // This node is dead!
2016 NI = Nodes.erase(NI); // Erase & remove from node list.
2023 removeIdenticalCalls(FunctionCalls);
2024 removeIdenticalCalls(AuxFunctionCalls);
2028 /// markReachableNodes - This method recursively traverses the specified
2029 /// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
2030 /// to the set, which allows it to only traverse visited nodes once.
2032 void DSNode::markReachableNodes(hash_set<const DSNode*> &ReachableNodes) const {
2033 if (this == 0) return;
2034 assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
2035 if (ReachableNodes.insert(this).second) // Is newly reachable?
2036 for (DSNode::const_edge_iterator I = edge_begin(), E = edge_end();
2038 I->getNode()->markReachableNodes(ReachableNodes);
2041 void DSCallSite::markReachableNodes(hash_set<const DSNode*> &Nodes) const {
2042 getRetVal().getNode()->markReachableNodes(Nodes);
2043 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
2045 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
2046 getPtrArg(i).getNode()->markReachableNodes(Nodes);
2049 // CanReachAliveNodes - Simple graph walker that recursively traverses the graph
2050 // looking for a node that is marked alive. If an alive node is found, return
2051 // true, otherwise return false. If an alive node is reachable, this node is
2052 // marked as alive...
2054 static bool CanReachAliveNodes(DSNode *N, hash_set<const DSNode*> &Alive,
2055 hash_set<const DSNode*> &Visited,
2056 bool IgnoreGlobals) {
2057 if (N == 0) return false;
2058 assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
2060 // If this is a global node, it will end up in the globals graph anyway, so we
2061 // don't need to worry about it.
2062 if (IgnoreGlobals && N->isGlobalNode()) return false;
2064 // If we know that this node is alive, return so!
2065 if (Alive.count(N)) return true;
2067 // Otherwise, we don't think the node is alive yet, check for infinite
2069 if (Visited.count(N)) return false; // Found a cycle
2070 Visited.insert(N); // No recursion, insert into Visited...
2072 for (DSNode::edge_iterator I = N->edge_begin(),E = N->edge_end(); I != E; ++I)
2073 if (CanReachAliveNodes(I->getNode(), Alive, Visited, IgnoreGlobals)) {
2074 N->markReachableNodes(Alive);
2080 // CallSiteUsesAliveArgs - Return true if the specified call site can reach any
2083 static bool CallSiteUsesAliveArgs(const DSCallSite &CS,
2084 hash_set<const DSNode*> &Alive,
2085 hash_set<const DSNode*> &Visited,
2086 bool IgnoreGlobals) {
2087 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited,
2090 if (CS.isIndirectCall() &&
2091 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited, IgnoreGlobals))
2093 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
2094 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited,
2100 // removeDeadNodes - Use a more powerful reachability analysis to eliminate
2101 // subgraphs that are unreachable. This often occurs because the data
2102 // structure doesn't "escape" into it's caller, and thus should be eliminated
2103 // from the caller's graph entirely. This is only appropriate to use when
2106 void DSGraph::removeDeadNodes(unsigned Flags) {
2107 DEBUG(AssertGraphOK(); if (GlobalsGraph) GlobalsGraph->AssertGraphOK());
2109 // Reduce the amount of work we have to do... remove dummy nodes left over by
2111 removeTriviallyDeadNodes();
2113 TIME_REGION(X, "removeDeadNodes");
2115 // FIXME: Merge non-trivially identical call nodes...
2117 // Alive - a set that holds all nodes found to be reachable/alive.
2118 hash_set<const DSNode*> Alive;
2119 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
2121 // Copy and merge all information about globals to the GlobalsGraph if this is
2122 // not a final pass (where unreachable globals are removed).
2124 // Strip all alloca bits since the current function is only for the BU pass.
2125 // Strip all incomplete bits since they are short-lived properties and they
2126 // will be correctly computed when rematerializing nodes into the functions.
2128 ReachabilityCloner GGCloner(*GlobalsGraph, *this, DSGraph::StripAllocaBit |
2129 DSGraph::StripIncompleteBit);
2131 // Mark all nodes reachable by (non-global) scalar nodes as alive...
2132 { TIME_REGION(Y, "removeDeadNodes:scalarscan");
2133 for (DSScalarMap::iterator I = ScalarMap.begin(), E = ScalarMap.end();
2135 if (isa<GlobalValue>(I->first)) { // Keep track of global nodes
2136 assert(!I->second.isNull() && "Null global node?");
2137 assert(I->second.getNode()->isGlobalNode() && "Should be a global node!");
2138 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
2140 // Make sure that all globals are cloned over as roots.
2141 if (!(Flags & DSGraph::RemoveUnreachableGlobals) && GlobalsGraph) {
2142 DSGraph::ScalarMapTy::iterator SMI =
2143 GlobalsGraph->getScalarMap().find(I->first);
2144 if (SMI != GlobalsGraph->getScalarMap().end())
2145 GGCloner.merge(SMI->second, I->second);
2147 GGCloner.getClonedNH(I->second);
2150 I->second.getNode()->markReachableNodes(Alive);
2154 // The return values are alive as well.
2155 for (ReturnNodesTy::iterator I = ReturnNodes.begin(), E = ReturnNodes.end();
2157 I->second.getNode()->markReachableNodes(Alive);
2159 // Mark any nodes reachable by primary calls as alive...
2160 for (fc_iterator I = fc_begin(), E = fc_end(); I != E; ++I)
2161 I->markReachableNodes(Alive);
2164 // Now find globals and aux call nodes that are already live or reach a live
2165 // value (which makes them live in turn), and continue till no more are found.
2168 hash_set<const DSNode*> Visited;
2169 hash_set<const DSCallSite*> AuxFCallsAlive;
2172 // If any global node points to a non-global that is "alive", the global is
2173 // "alive" as well... Remove it from the GlobalNodes list so we only have
2174 // unreachable globals in the list.
2177 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
2178 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
2179 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited,
2180 Flags & DSGraph::RemoveUnreachableGlobals)) {
2181 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to...
2182 GlobalNodes.pop_back(); // erase efficiently
2186 // Mark only unresolvable call nodes for moving to the GlobalsGraph since
2187 // call nodes that get resolved will be difficult to remove from that graph.
2188 // The final unresolved call nodes must be handled specially at the end of
2189 // the BU pass (i.e., in main or other roots of the call graph).
2190 for (afc_iterator CI = afc_begin(), E = afc_end(); CI != E; ++CI)
2191 if (!AuxFCallsAlive.count(&*CI) &&
2192 (CI->isIndirectCall()
2193 || CallSiteUsesAliveArgs(*CI, Alive, Visited,
2194 Flags & DSGraph::RemoveUnreachableGlobals))) {
2195 CI->markReachableNodes(Alive);
2196 AuxFCallsAlive.insert(&*CI);
2201 // Move dead aux function calls to the end of the list
2202 for (std::list<DSCallSite>::iterator CI = AuxFunctionCalls.begin(),
2203 E = AuxFunctionCalls.end(); CI != E; )
2204 if (AuxFCallsAlive.count(&*CI))
2207 // Copy and merge global nodes and dead aux call nodes into the
2208 // GlobalsGraph, and all nodes reachable from those nodes. Update their
2209 // target pointers using the GGCloner.
2211 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
2212 GlobalsGraph->AuxFunctionCalls.push_back(DSCallSite(*CI, GGCloner));
2214 AuxFunctionCalls.erase(CI++);
2217 // We are finally done with the GGCloner so we can destroy it.
2220 // At this point, any nodes which are visited, but not alive, are nodes
2221 // which can be removed. Loop over all nodes, eliminating completely
2222 // unreachable nodes.
2224 std::vector<DSNode*> DeadNodes;
2225 DeadNodes.reserve(Nodes.size());
2226 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E;) {
2228 assert(!N->isForwarding() && "Forwarded node in nodes list?");
2230 if (!Alive.count(N)) {
2232 assert(!N->isForwarding() && "Cannot remove a forwarding node!");
2233 DeadNodes.push_back(N);
2234 N->dropAllReferences();
2239 // Remove all unreachable globals from the ScalarMap.
2240 // If flag RemoveUnreachableGlobals is set, GlobalNodes has only dead nodes.
2241 // In either case, the dead nodes will not be in the set Alive.
2242 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
2243 if (!Alive.count(GlobalNodes[i].second))
2244 ScalarMap.erase(GlobalNodes[i].first);
2246 assert((Flags & DSGraph::RemoveUnreachableGlobals) && "non-dead global");
2248 // Delete all dead nodes now since their referrer counts are zero.
2249 for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
2250 delete DeadNodes[i];
2252 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
2255 void DSGraph::AssertNodeContainsGlobal(const DSNode *N, GlobalValue *GV) const {
2256 assert(std::find(N->globals_begin(),N->globals_end(), GV) !=
2257 N->globals_end() && "Global value not in node!");
2260 void DSGraph::AssertCallSiteInGraph(const DSCallSite &CS) const {
2261 if (CS.isIndirectCall()) {
2262 AssertNodeInGraph(CS.getCalleeNode());
2264 if (CS.getNumPtrArgs() && CS.getCalleeNode() == CS.getPtrArg(0).getNode() &&
2265 CS.getCalleeNode() && CS.getCalleeNode()->getGlobals().empty())
2266 DOUT << "WARNING: WEIRD CALL SITE FOUND!\n";
2269 AssertNodeInGraph(CS.getRetVal().getNode());
2270 for (unsigned j = 0, e = CS.getNumPtrArgs(); j != e; ++j)
2271 AssertNodeInGraph(CS.getPtrArg(j).getNode());
2274 void DSGraph::AssertCallNodesInGraph() const {
2275 for (fc_iterator I = fc_begin(), E = fc_end(); I != E; ++I)
2276 AssertCallSiteInGraph(*I);
2278 void DSGraph::AssertAuxCallNodesInGraph() const {
2279 for (afc_iterator I = afc_begin(), E = afc_end(); I != E; ++I)
2280 AssertCallSiteInGraph(*I);
2283 void DSGraph::AssertGraphOK() const {
2284 for (node_const_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
2287 for (ScalarMapTy::const_iterator I = ScalarMap.begin(),
2288 E = ScalarMap.end(); I != E; ++I) {
2289 assert(!I->second.isNull() && "Null node in scalarmap!");
2290 AssertNodeInGraph(I->second.getNode());
2291 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
2292 assert(I->second.getNode()->isGlobalNode() &&
2293 "Global points to node, but node isn't global?");
2294 AssertNodeContainsGlobal(I->second.getNode(), GV);
2297 AssertCallNodesInGraph();
2298 AssertAuxCallNodesInGraph();
2300 // Check that all pointer arguments to any functions in this graph have
2302 for (ReturnNodesTy::const_iterator RI = ReturnNodes.begin(),
2303 E = ReturnNodes.end();
2305 Function &F = *RI->first;
2306 for (Function::arg_iterator AI = F.arg_begin(); AI != F.arg_end(); ++AI)
2307 if (isPointerType(AI->getType()))
2308 assert(!getNodeForValue(AI).isNull() &&
2309 "Pointer argument must be in the scalar map!");
2313 /// computeNodeMapping - Given roots in two different DSGraphs, traverse the
2314 /// nodes reachable from the two graphs, computing the mapping of nodes from the
2315 /// first to the second graph. This mapping may be many-to-one (i.e. the first
2316 /// graph may have multiple nodes representing one node in the second graph),
2317 /// but it will not work if there is a one-to-many or many-to-many mapping.
2319 void DSGraph::computeNodeMapping(const DSNodeHandle &NH1,
2320 const DSNodeHandle &NH2, NodeMapTy &NodeMap,
2321 bool StrictChecking) {
2322 DSNode *N1 = NH1.getNode(), *N2 = NH2.getNode();
2323 if (N1 == 0 || N2 == 0) return;
2325 DSNodeHandle &Entry = NodeMap[N1];
2326 if (!Entry.isNull()) {
2327 // Termination of recursion!
2328 if (StrictChecking) {
2329 assert(Entry.getNode() == N2 && "Inconsistent mapping detected!");
2330 assert((Entry.getOffset() == (NH2.getOffset()-NH1.getOffset()) ||
2331 Entry.getNode()->isNodeCompletelyFolded()) &&
2332 "Inconsistent mapping detected!");
2337 Entry.setTo(N2, NH2.getOffset()-NH1.getOffset());
2339 // Loop over all of the fields that N1 and N2 have in common, recursively
2340 // mapping the edges together now.
2341 int N2Idx = NH2.getOffset()-NH1.getOffset();
2342 unsigned N2Size = N2->getSize();
2343 if (N2Size == 0) return; // No edges to map to.
2345 for (unsigned i = 0, e = N1->getSize(); i < e; i += DS::PointerSize) {
2346 const DSNodeHandle &N1NH = N1->getLink(i);
2347 // Don't call N2->getLink if not needed (avoiding crash if N2Idx is not
2349 if (!N1NH.isNull()) {
2350 if (unsigned(N2Idx)+i < N2Size)
2351 computeNodeMapping(N1NH, N2->getLink(N2Idx+i), NodeMap);
2353 computeNodeMapping(N1NH,
2354 N2->getLink(unsigned(N2Idx+i) % N2Size), NodeMap);
2360 /// computeGToGGMapping - Compute the mapping of nodes in the global graph to
2361 /// nodes in this graph.
2362 void DSGraph::computeGToGGMapping(NodeMapTy &NodeMap) {
2363 DSGraph &GG = *getGlobalsGraph();
2365 DSScalarMap &SM = getScalarMap();
2366 for (DSScalarMap::global_iterator I = SM.global_begin(),
2367 E = SM.global_end(); I != E; ++I)
2368 DSGraph::computeNodeMapping(SM[*I], GG.getNodeForValue(*I), NodeMap);
2371 /// computeGGToGMapping - Compute the mapping of nodes in the global graph to
2372 /// nodes in this graph. Note that any uses of this method are probably bugs,
2373 /// unless it is known that the globals graph has been merged into this graph!
2374 void DSGraph::computeGGToGMapping(InvNodeMapTy &InvNodeMap) {
2376 computeGToGGMapping(NodeMap);
2378 while (!NodeMap.empty()) {
2379 InvNodeMap.insert(std::make_pair(NodeMap.begin()->second,
2380 NodeMap.begin()->first));
2381 NodeMap.erase(NodeMap.begin());
2386 /// computeCalleeCallerMapping - Given a call from a function in the current
2387 /// graph to the 'Callee' function (which lives in 'CalleeGraph'), compute the
2388 /// mapping of nodes from the callee to nodes in the caller.
2389 void DSGraph::computeCalleeCallerMapping(DSCallSite CS, const Function &Callee,
2390 DSGraph &CalleeGraph,
2391 NodeMapTy &NodeMap) {
2393 DSCallSite CalleeArgs =
2394 CalleeGraph.getCallSiteForArguments(const_cast<Function&>(Callee));
2396 computeNodeMapping(CalleeArgs.getRetVal(), CS.getRetVal(), NodeMap);
2398 unsigned NumArgs = CS.getNumPtrArgs();
2399 if (NumArgs > CalleeArgs.getNumPtrArgs())
2400 NumArgs = CalleeArgs.getNumPtrArgs();
2402 for (unsigned i = 0; i != NumArgs; ++i)
2403 computeNodeMapping(CalleeArgs.getPtrArg(i), CS.getPtrArg(i), NodeMap);
2405 // Map the nodes that are pointed to by globals.
2406 DSScalarMap &CalleeSM = CalleeGraph.getScalarMap();
2407 DSScalarMap &CallerSM = getScalarMap();
2409 if (CalleeSM.global_size() >= CallerSM.global_size()) {
2410 for (DSScalarMap::global_iterator GI = CallerSM.global_begin(),
2411 E = CallerSM.global_end(); GI != E; ++GI)
2412 if (CalleeSM.global_count(*GI))
2413 computeNodeMapping(CalleeSM[*GI], CallerSM[*GI], NodeMap);
2415 for (DSScalarMap::global_iterator GI = CalleeSM.global_begin(),
2416 E = CalleeSM.global_end(); GI != E; ++GI)
2417 if (CallerSM.global_count(*GI))
2418 computeNodeMapping(CalleeSM[*GI], CallerSM[*GI], NodeMap);
2422 /// updateFromGlobalGraph - This function rematerializes global nodes and
2423 /// nodes reachable from them from the globals graph into the current graph.
2425 void DSGraph::updateFromGlobalGraph() {
2426 TIME_REGION(X, "updateFromGlobalGraph");
2427 ReachabilityCloner RC(*this, *GlobalsGraph, 0);
2429 // Clone the non-up-to-date global nodes into this graph.
2430 for (DSScalarMap::global_iterator I = getScalarMap().global_begin(),
2431 E = getScalarMap().global_end(); I != E; ++I) {
2432 DSScalarMap::iterator It = GlobalsGraph->ScalarMap.find(*I);
2433 if (It != GlobalsGraph->ScalarMap.end())
2434 RC.merge(getNodeForValue(*I), It->second);