1 //===- DataStructure.cpp - Implement the core data structure analysis -----===//
3 // This file implements the core data structure functionality.
5 //===----------------------------------------------------------------------===//
7 #include "llvm/Analysis/DSGraph.h"
8 #include "llvm/Function.h"
9 #include "llvm/iOther.h"
10 #include "llvm/DerivedTypes.h"
11 #include "llvm/Target/TargetData.h"
12 #include "Support/STLExtras.h"
13 #include "Support/Statistic.h"
14 #include "Support/Timer.h"
18 Statistic<> NumFolds ("dsnode", "Number of nodes completely folded");
19 Statistic<> NumCallNodesMerged("dsnode", "Number of call nodes merged");
22 namespace DS { // TODO: FIXME
27 DSNode *DSNodeHandle::HandleForwarding() const {
28 assert(!N->ForwardNH.isNull() && "Can only be invoked if forwarding!");
30 // Handle node forwarding here!
31 DSNode *Next = N->ForwardNH.getNode(); // Cause recursive shrinkage
32 Offset += N->ForwardNH.getOffset();
34 if (--N->NumReferrers == 0) {
35 // Removing the last referrer to the node, sever the forwarding link
41 if (N->Size <= Offset) {
42 assert(N->Size <= 1 && "Forwarded to shrunk but not collapsed node?");
48 //===----------------------------------------------------------------------===//
49 // DSNode Implementation
50 //===----------------------------------------------------------------------===//
52 DSNode::DSNode(const Type *T, DSGraph *G)
53 : NumReferrers(0), Size(0), ParentGraph(G), Ty(Type::VoidTy), NodeType(0) {
54 // Add the type entry if it is specified...
55 if (T) mergeTypeInfo(T, 0);
56 G->getNodes().push_back(this);
59 // DSNode copy constructor... do not copy over the referrers list!
60 DSNode::DSNode(const DSNode &N, DSGraph *G)
61 : NumReferrers(0), Size(N.Size), ParentGraph(G), Ty(N.Ty),
62 Links(N.Links), Globals(N.Globals), NodeType(N.NodeType) {
63 G->getNodes().push_back(this);
66 void DSNode::assertOK() const {
67 assert((Ty != Type::VoidTy ||
68 Ty == Type::VoidTy && (Size == 0 ||
69 (NodeType & DSNode::Array))) &&
73 /// forwardNode - Mark this node as being obsolete, and all references to it
74 /// should be forwarded to the specified node and offset.
76 void DSNode::forwardNode(DSNode *To, unsigned Offset) {
77 assert(this != To && "Cannot forward a node to itself!");
78 assert(ForwardNH.isNull() && "Already forwarding from this node!");
79 if (To->Size <= 1) Offset = 0;
80 assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
81 "Forwarded offset is wrong!");
82 ForwardNH.setNode(To);
83 ForwardNH.setOffset(Offset);
89 // addGlobal - Add an entry for a global value to the Globals list. This also
90 // marks the node with the 'G' flag if it does not already have it.
92 void DSNode::addGlobal(GlobalValue *GV) {
93 // Keep the list sorted.
94 std::vector<GlobalValue*>::iterator I =
95 std::lower_bound(Globals.begin(), Globals.end(), GV);
97 if (I == Globals.end() || *I != GV) {
98 //assert(GV->getType()->getElementType() == Ty);
99 Globals.insert(I, GV);
100 NodeType |= GlobalNode;
104 /// foldNodeCompletely - If we determine that this node has some funny
105 /// behavior happening to it that we cannot represent, we fold it down to a
106 /// single, completely pessimistic, node. This node is represented as a
107 /// single byte with a single TypeEntry of "void".
109 void DSNode::foldNodeCompletely() {
110 if (isNodeCompletelyFolded()) return; // If this node is already folded...
114 // Create the node we are going to forward to...
115 DSNode *DestNode = new DSNode(0, ParentGraph);
116 DestNode->NodeType = NodeType|DSNode::Array;
117 DestNode->Ty = Type::VoidTy;
119 DestNode->Globals.swap(Globals);
121 // Start forwarding to the destination node...
122 forwardNode(DestNode, 0);
125 DestNode->Links.push_back(Links[0]);
126 DSNodeHandle NH(DestNode);
128 // If we have links, merge all of our outgoing links together...
129 for (unsigned i = Links.size()-1; i != 0; --i)
130 NH.getNode()->Links[0].mergeWith(Links[i]);
133 DestNode->Links.resize(1);
137 /// isNodeCompletelyFolded - Return true if this node has been completely
138 /// folded down to something that can never be expanded, effectively losing
139 /// all of the field sensitivity that may be present in the node.
141 bool DSNode::isNodeCompletelyFolded() const {
142 return getSize() == 1 && Ty == Type::VoidTy && isArray();
147 /// TypeElementWalker Class - Used for implementation of physical subtyping...
149 class TypeElementWalker {
154 StackState(const Type *T, unsigned Off = 0)
155 : Ty(T), Offset(Off), Idx(0) {}
158 std::vector<StackState> Stack;
160 TypeElementWalker(const Type *T) {
165 bool isDone() const { return Stack.empty(); }
166 const Type *getCurrentType() const { return Stack.back().Ty; }
167 unsigned getCurrentOffset() const { return Stack.back().Offset; }
169 void StepToNextType() {
170 PopStackAndAdvance();
175 /// PopStackAndAdvance - Pop the current element off of the stack and
176 /// advance the underlying element to the next contained member.
177 void PopStackAndAdvance() {
178 assert(!Stack.empty() && "Cannot pop an empty stack!");
180 while (!Stack.empty()) {
181 StackState &SS = Stack.back();
182 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
184 if (SS.Idx != ST->getElementTypes().size()) {
185 const StructLayout *SL = TD.getStructLayout(ST);
186 SS.Offset += SL->MemberOffsets[SS.Idx]-SL->MemberOffsets[SS.Idx-1];
189 Stack.pop_back(); // At the end of the structure
191 const ArrayType *AT = cast<ArrayType>(SS.Ty);
193 if (SS.Idx != AT->getNumElements()) {
194 SS.Offset += TD.getTypeSize(AT->getElementType());
197 Stack.pop_back(); // At the end of the array
202 /// StepToLeaf - Used by physical subtyping to move to the first leaf node
203 /// on the type stack.
205 if (Stack.empty()) return;
206 while (!Stack.empty() && !Stack.back().Ty->isFirstClassType()) {
207 StackState &SS = Stack.back();
208 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
209 if (ST->getElementTypes().empty()) {
211 PopStackAndAdvance();
213 // Step into the structure...
214 assert(SS.Idx < ST->getElementTypes().size());
215 const StructLayout *SL = TD.getStructLayout(ST);
216 Stack.push_back(StackState(ST->getElementTypes()[SS.Idx],
217 SS.Offset+SL->MemberOffsets[SS.Idx]));
220 const ArrayType *AT = cast<ArrayType>(SS.Ty);
221 if (AT->getNumElements() == 0) {
223 PopStackAndAdvance();
225 // Step into the array...
226 assert(SS.Idx < AT->getNumElements());
227 Stack.push_back(StackState(AT->getElementType(),
229 TD.getTypeSize(AT->getElementType())));
237 /// ElementTypesAreCompatible - Check to see if the specified types are
238 /// "physically" compatible. If so, return true, else return false. We only
239 /// have to check the fields in T1: T2 may be larger than T1.
241 static bool ElementTypesAreCompatible(const Type *T1, const Type *T2) {
242 TypeElementWalker T1W(T1), T2W(T2);
244 while (!T1W.isDone() && !T2W.isDone()) {
245 if (T1W.getCurrentOffset() != T2W.getCurrentOffset())
248 const Type *T1 = T1W.getCurrentType();
249 const Type *T2 = T2W.getCurrentType();
250 if (T1 != T2 && !T1->isLosslesslyConvertibleTo(T2))
253 T1W.StepToNextType();
254 T2W.StepToNextType();
261 /// mergeTypeInfo - This method merges the specified type into the current node
262 /// at the specified offset. This may update the current node's type record if
263 /// this gives more information to the node, it may do nothing to the node if
264 /// this information is already known, or it may merge the node completely (and
265 /// return true) if the information is incompatible with what is already known.
267 /// This method returns true if the node is completely folded, otherwise false.
269 bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset,
270 bool FoldIfIncompatible) {
271 // Check to make sure the Size member is up-to-date. Size can be one of the
273 // Size = 0, Ty = Void: Nothing is known about this node.
274 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
275 // Size = 1, Ty = Void, Array = 1: The node is collapsed
276 // Otherwise, sizeof(Ty) = Size
278 assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
279 (Size == 0 && !Ty->isSized() && !isArray()) ||
280 (Size == 1 && Ty == Type::VoidTy && isArray()) ||
281 (Size == 0 && !Ty->isSized() && !isArray()) ||
282 (TD.getTypeSize(Ty) == Size)) &&
283 "Size member of DSNode doesn't match the type structure!");
284 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
286 if (Offset == 0 && NewTy == Ty)
287 return false; // This should be a common case, handle it efficiently
289 // Return true immediately if the node is completely folded.
290 if (isNodeCompletelyFolded()) return true;
292 // If this is an array type, eliminate the outside arrays because they won't
293 // be used anyway. This greatly reduces the size of large static arrays used
294 // as global variables, for example.
296 bool WillBeArray = false;
297 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
298 // FIXME: we might want to keep small arrays, but must be careful about
299 // things like: [2 x [10000 x int*]]
300 NewTy = AT->getElementType();
304 // Figure out how big the new type we're merging in is...
305 unsigned NewTySize = NewTy->isSized() ? TD.getTypeSize(NewTy) : 0;
307 // Otherwise check to see if we can fold this type into the current node. If
308 // we can't, we fold the node completely, if we can, we potentially update our
311 if (Ty == Type::VoidTy) {
312 // If this is the first type that this node has seen, just accept it without
314 assert(Offset == 0 && "Cannot have an offset into a void node!");
315 assert(!isArray() && "This shouldn't happen!");
318 if (WillBeArray) NodeType |= Array;
321 // Calculate the number of outgoing links from this node.
322 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
326 // Handle node expansion case here...
327 if (Offset+NewTySize > Size) {
328 // It is illegal to grow this node if we have treated it as an array of
331 if (FoldIfIncompatible) foldNodeCompletely();
335 if (Offset) { // We could handle this case, but we don't for now...
336 std::cerr << "UNIMP: Trying to merge a growth type into "
337 << "offset != 0: Collapsing!\n";
338 if (FoldIfIncompatible) foldNodeCompletely();
342 // Okay, the situation is nice and simple, we are trying to merge a type in
343 // at offset 0 that is bigger than our current type. Implement this by
344 // switching to the new type and then merge in the smaller one, which should
345 // hit the other code path here. If the other code path decides it's not
346 // ok, it will collapse the node as appropriate.
348 const Type *OldTy = Ty;
351 if (WillBeArray) NodeType |= Array;
354 // Must grow links to be the appropriate size...
355 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
357 // Merge in the old type now... which is guaranteed to be smaller than the
359 return mergeTypeInfo(OldTy, 0);
362 assert(Offset <= Size &&
363 "Cannot merge something into a part of our type that doesn't exist!");
365 // Find the section of Ty that NewTy overlaps with... first we find the
366 // type that starts at offset Offset.
369 const Type *SubType = Ty;
371 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
373 switch (SubType->getPrimitiveID()) {
374 case Type::StructTyID: {
375 const StructType *STy = cast<StructType>(SubType);
376 const StructLayout &SL = *TD.getStructLayout(STy);
378 unsigned i = 0, e = SL.MemberOffsets.size();
379 for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
382 // The offset we are looking for must be in the i'th element...
383 SubType = STy->getElementTypes()[i];
384 O += SL.MemberOffsets[i];
387 case Type::ArrayTyID: {
388 SubType = cast<ArrayType>(SubType)->getElementType();
389 unsigned ElSize = TD.getTypeSize(SubType);
390 unsigned Remainder = (Offset-O) % ElSize;
391 O = Offset-Remainder;
395 if (FoldIfIncompatible) foldNodeCompletely();
400 assert(O == Offset && "Could not achieve the correct offset!");
402 // If we found our type exactly, early exit
403 if (SubType == NewTy) return false;
405 unsigned SubTypeSize = SubType->isSized() ? TD.getTypeSize(SubType) : 0;
407 // Ok, we are getting desperate now. Check for physical subtyping, where we
408 // just require each element in the node to be compatible.
409 assert(NewTySize <= SubTypeSize &&
410 "Expected smaller type merging into this one!");
411 if (NewTySize && NewTySize < 256 &&
412 SubTypeSize && SubTypeSize < 256 &&
413 ElementTypesAreCompatible(NewTy, SubType))
416 // Okay, so we found the leader type at the offset requested. Search the list
417 // of types that starts at this offset. If SubType is currently an array or
418 // structure, the type desired may actually be the first element of the
421 unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
422 while (SubType != NewTy) {
423 const Type *NextSubType = 0;
424 unsigned NextSubTypeSize = 0;
425 unsigned NextPadSize = 0;
426 switch (SubType->getPrimitiveID()) {
427 case Type::StructTyID: {
428 const StructType *STy = cast<StructType>(SubType);
429 const StructLayout &SL = *TD.getStructLayout(STy);
430 if (SL.MemberOffsets.size() > 1)
431 NextPadSize = SL.MemberOffsets[1];
433 NextPadSize = SubTypeSize;
434 NextSubType = STy->getElementTypes()[0];
435 NextSubTypeSize = TD.getTypeSize(NextSubType);
438 case Type::ArrayTyID:
439 NextSubType = cast<ArrayType>(SubType)->getElementType();
440 NextSubTypeSize = TD.getTypeSize(NextSubType);
441 NextPadSize = NextSubTypeSize;
447 if (NextSubType == 0)
448 break; // In the default case, break out of the loop
450 if (NextPadSize < NewTySize)
451 break; // Don't allow shrinking to a smaller type than NewTySize
452 SubType = NextSubType;
453 SubTypeSize = NextSubTypeSize;
454 PadSize = NextPadSize;
457 // If we found the type exactly, return it...
458 if (SubType == NewTy)
461 // Check to see if we have a compatible, but different type...
462 if (NewTySize == SubTypeSize) {
463 // Check to see if this type is obviously convertible... int -> uint f.e.
464 if (NewTy->isLosslesslyConvertibleTo(SubType))
467 // Check to see if we have a pointer & integer mismatch going on here,
468 // loading a pointer as a long, for example.
470 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
471 NewTy->isInteger() && isa<PointerType>(SubType))
473 } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
474 // We are accessing the field, plus some structure padding. Ignore the
475 // structure padding.
479 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: " << Ty
480 << "\n due to:" << NewTy << " @ " << Offset << "!\n"
481 << "SubType: " << SubType << "\n\n");
483 if (FoldIfIncompatible) foldNodeCompletely();
489 // addEdgeTo - Add an edge from the current node to the specified node. This
490 // can cause merging of nodes in the graph.
492 void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
493 if (NH.getNode() == 0) return; // Nothing to do
495 DSNodeHandle &ExistingEdge = getLink(Offset);
496 if (ExistingEdge.getNode()) {
497 // Merge the two nodes...
498 ExistingEdge.mergeWith(NH);
499 } else { // No merging to perform...
500 setLink(Offset, NH); // Just force a link in there...
505 // MergeSortedVectors - Efficiently merge a vector into another vector where
506 // duplicates are not allowed and both are sorted. This assumes that 'T's are
507 // efficiently copyable and have sane comparison semantics.
509 static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
510 const std::vector<GlobalValue*> &Src) {
511 // By far, the most common cases will be the simple ones. In these cases,
512 // avoid having to allocate a temporary vector...
514 if (Src.empty()) { // Nothing to merge in...
516 } else if (Dest.empty()) { // Just copy the result in...
518 } else if (Src.size() == 1) { // Insert a single element...
519 const GlobalValue *V = Src[0];
520 std::vector<GlobalValue*>::iterator I =
521 std::lower_bound(Dest.begin(), Dest.end(), V);
522 if (I == Dest.end() || *I != Src[0]) // If not already contained...
523 Dest.insert(I, Src[0]);
524 } else if (Dest.size() == 1) {
525 GlobalValue *Tmp = Dest[0]; // Save value in temporary...
526 Dest = Src; // Copy over list...
527 std::vector<GlobalValue*>::iterator I =
528 std::lower_bound(Dest.begin(), Dest.end(), Tmp);
529 if (I == Dest.end() || *I != Tmp) // If not already contained...
533 // Make a copy to the side of Dest...
534 std::vector<GlobalValue*> Old(Dest);
536 // Make space for all of the type entries now...
537 Dest.resize(Dest.size()+Src.size());
539 // Merge the two sorted ranges together... into Dest.
540 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
542 // Now erase any duplicate entries that may have accumulated into the
543 // vectors (because they were in both of the input sets)
544 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
549 // MergeNodes() - Helper function for DSNode::mergeWith().
550 // This function does the hard work of merging two nodes, CurNodeH
551 // and NH after filtering out trivial cases and making sure that
552 // CurNodeH.offset >= NH.offset.
555 // Since merging may cause either node to go away, we must always
556 // use the node-handles to refer to the nodes. These node handles are
557 // automatically updated during merging, so will always provide access
558 // to the correct node after a merge.
560 void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
561 assert(CurNodeH.getOffset() >= NH.getOffset() &&
562 "This should have been enforced in the caller.");
564 // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
565 // respect to NH.Offset) is now zero. NOffset is the distance from the base
566 // of our object that N starts from.
568 unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
569 unsigned NSize = NH.getNode()->getSize();
571 // If the two nodes are of different size, and the smaller node has the array
572 // bit set, collapse!
573 if (NSize != CurNodeH.getNode()->getSize()) {
574 if (NSize < CurNodeH.getNode()->getSize()) {
575 if (NH.getNode()->isArray())
576 NH.getNode()->foldNodeCompletely();
577 } else if (CurNodeH.getNode()->isArray()) {
578 NH.getNode()->foldNodeCompletely();
582 // Merge the type entries of the two nodes together...
583 if (NH.getNode()->Ty != Type::VoidTy)
584 CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
585 assert(!CurNodeH.getNode()->isDeadNode());
587 // If we are merging a node with a completely folded node, then both nodes are
588 // now completely folded.
590 if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
591 if (!NH.getNode()->isNodeCompletelyFolded()) {
592 NH.getNode()->foldNodeCompletely();
593 assert(NH.getNode() && NH.getOffset() == 0 &&
594 "folding did not make offset 0?");
595 NOffset = NH.getOffset();
596 NSize = NH.getNode()->getSize();
597 assert(NOffset == 0 && NSize == 1);
599 } else if (NH.getNode()->isNodeCompletelyFolded()) {
600 CurNodeH.getNode()->foldNodeCompletely();
601 assert(CurNodeH.getNode() && CurNodeH.getOffset() == 0 &&
602 "folding did not make offset 0?");
603 NOffset = NH.getOffset();
604 NSize = NH.getNode()->getSize();
605 assert(NOffset == 0 && NSize == 1);
608 DSNode *N = NH.getNode();
609 if (CurNodeH.getNode() == N || N == 0) return;
610 assert(!CurNodeH.getNode()->isDeadNode());
612 // Merge the NodeType information...
613 CurNodeH.getNode()->NodeType |= N->NodeType;
615 // Start forwarding to the new node!
616 N->forwardNode(CurNodeH.getNode(), NOffset);
617 assert(!CurNodeH.getNode()->isDeadNode());
619 // Make all of the outgoing links of N now be outgoing links of CurNodeH.
621 for (unsigned i = 0; i < N->getNumLinks(); ++i) {
622 DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
623 if (Link.getNode()) {
624 // Compute the offset into the current node at which to
625 // merge this link. In the common case, this is a linear
626 // relation to the offset in the original node (with
627 // wrapping), but if the current node gets collapsed due to
628 // recursive merging, we must make sure to merge in all remaining
629 // links at offset zero.
630 unsigned MergeOffset = 0;
631 DSNode *CN = CurNodeH.getNode();
633 MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
634 CN->addEdgeTo(MergeOffset, Link);
638 // Now that there are no outgoing edges, all of the Links are dead.
641 // Merge the globals list...
642 if (!N->Globals.empty()) {
643 MergeSortedVectors(CurNodeH.getNode()->Globals, N->Globals);
645 // Delete the globals from the old node...
646 std::vector<GlobalValue*>().swap(N->Globals);
651 // mergeWith - Merge this node and the specified node, moving all links to and
652 // from the argument node into the current node, deleting the node argument.
653 // Offset indicates what offset the specified node is to be merged into the
656 // The specified node may be a null pointer (in which case, nothing happens).
658 void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
659 DSNode *N = NH.getNode();
660 if (N == 0 || (N == this && NH.getOffset() == Offset))
663 assert(!N->isDeadNode() && !isDeadNode());
664 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
667 // We cannot merge two pieces of the same node together, collapse the node
669 DEBUG(std::cerr << "Attempting to merge two chunks of"
670 << " the same node together!\n");
671 foldNodeCompletely();
675 // If both nodes are not at offset 0, make sure that we are merging the node
676 // at an later offset into the node with the zero offset.
678 if (Offset < NH.getOffset()) {
679 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
681 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
682 // If the offsets are the same, merge the smaller node into the bigger node
683 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
687 // Ok, now we can merge the two nodes. Use a static helper that works with
688 // two node handles, since "this" may get merged away at intermediate steps.
689 DSNodeHandle CurNodeH(this, Offset);
690 DSNodeHandle NHCopy(NH);
691 DSNode::MergeNodes(CurNodeH, NHCopy);
694 //===----------------------------------------------------------------------===//
695 // DSCallSite Implementation
696 //===----------------------------------------------------------------------===//
698 // Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
699 Function &DSCallSite::getCaller() const {
700 return *Inst->getParent()->getParent();
704 //===----------------------------------------------------------------------===//
705 // DSGraph Implementation
706 //===----------------------------------------------------------------------===//
708 DSGraph::DSGraph(const DSGraph &G) : Func(G.Func), GlobalsGraph(0) {
709 PrintAuxCalls = false;
710 hash_map<const DSNode*, DSNodeHandle> NodeMap;
711 RetNode = cloneInto(G, ScalarMap, NodeMap);
714 DSGraph::DSGraph(const DSGraph &G,
715 hash_map<const DSNode*, DSNodeHandle> &NodeMap)
716 : Func(G.Func), GlobalsGraph(0) {
717 PrintAuxCalls = false;
718 RetNode = cloneInto(G, ScalarMap, NodeMap);
721 DSGraph::~DSGraph() {
722 FunctionCalls.clear();
723 AuxFunctionCalls.clear();
727 // Drop all intra-node references, so that assertions don't fail...
728 std::for_each(Nodes.begin(), Nodes.end(),
729 std::mem_fun(&DSNode::dropAllReferences));
731 // Delete all of the nodes themselves...
732 std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
735 // dump - Allow inspection of graph in a debugger.
736 void DSGraph::dump() const { print(std::cerr); }
739 /// remapLinks - Change all of the Links in the current node according to the
740 /// specified mapping.
742 void DSNode::remapLinks(hash_map<const DSNode*, DSNodeHandle> &OldNodeMap) {
743 for (unsigned i = 0, e = Links.size(); i != e; ++i) {
744 DSNodeHandle &H = OldNodeMap[Links[i].getNode()];
745 Links[i].setNode(H.getNode());
746 Links[i].setOffset(Links[i].getOffset()+H.getOffset());
751 // cloneInto - Clone the specified DSGraph into the current graph, returning the
752 // Return node of the graph. The translated ScalarMap for the old function is
753 // filled into the OldValMap member. If StripAllocas is set to true, Alloca
754 // markers are removed from the graph, as the graph is being cloned into a
755 // calling function's graph.
757 DSNodeHandle DSGraph::cloneInto(const DSGraph &G,
758 hash_map<Value*, DSNodeHandle> &OldValMap,
759 hash_map<const DSNode*, DSNodeHandle> &OldNodeMap,
760 unsigned CloneFlags) {
761 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
762 assert(&G != this && "Cannot clone graph into itself!");
764 unsigned FN = Nodes.size(); // First new node...
766 // Duplicate all of the nodes, populating the node map...
767 Nodes.reserve(FN+G.Nodes.size());
769 // Remove alloca or mod/ref bits as specified...
770 unsigned BitsToClear =((CloneFlags & StripAllocaBit) ? DSNode::AllocaNode : 0)
771 | ((CloneFlags & StripModRefBits) ? (DSNode::Modified | DSNode::Read) : 0);
772 BitsToClear |= DSNode::DEAD; // Clear dead flag...
773 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
774 DSNode *Old = G.Nodes[i];
775 DSNode *New = new DSNode(*Old, this);
776 New->maskNodeTypes(~BitsToClear);
777 OldNodeMap[Old] = New;
781 Timer::addPeakMemoryMeasurement();
784 // Rewrite the links in the new nodes to point into the current graph now.
785 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
786 Nodes[i]->remapLinks(OldNodeMap);
788 // Copy the scalar map... merging all of the global nodes...
789 for (hash_map<Value*, DSNodeHandle>::const_iterator I = G.ScalarMap.begin(),
790 E = G.ScalarMap.end(); I != E; ++I) {
791 DSNodeHandle &H = OldValMap[I->first];
792 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
793 H.setOffset(I->second.getOffset()+MappedNode.getOffset());
794 H.setNode(MappedNode.getNode());
796 if (isa<GlobalValue>(I->first)) { // Is this a global?
797 hash_map<Value*, DSNodeHandle>::iterator GVI = ScalarMap.find(I->first);
798 if (GVI != ScalarMap.end()) // Is the global value in this fn already?
799 GVI->second.mergeWith(H);
801 ScalarMap[I->first] = H; // Add global pointer to this graph
805 if (!(CloneFlags & DontCloneCallNodes)) {
806 // Copy the function calls list...
807 unsigned FC = FunctionCalls.size(); // FirstCall
808 FunctionCalls.reserve(FC+G.FunctionCalls.size());
809 for (unsigned i = 0, ei = G.FunctionCalls.size(); i != ei; ++i)
810 FunctionCalls.push_back(DSCallSite(G.FunctionCalls[i], OldNodeMap));
813 if (!(CloneFlags & DontCloneAuxCallNodes)) {
814 // Copy the auxillary function calls list...
815 unsigned FC = AuxFunctionCalls.size(); // FirstCall
816 AuxFunctionCalls.reserve(FC+G.AuxFunctionCalls.size());
817 for (unsigned i = 0, ei = G.AuxFunctionCalls.size(); i != ei; ++i)
818 AuxFunctionCalls.push_back(DSCallSite(G.AuxFunctionCalls[i], OldNodeMap));
821 // Return the returned node pointer...
822 DSNodeHandle &MappedRet = OldNodeMap[G.RetNode.getNode()];
823 return DSNodeHandle(MappedRet.getNode(),
824 MappedRet.getOffset()+G.RetNode.getOffset());
827 /// mergeInGraph - The method is used for merging graphs together. If the
828 /// argument graph is not *this, it makes a clone of the specified graph, then
829 /// merges the nodes specified in the call site with the formal arguments in the
832 void DSGraph::mergeInGraph(DSCallSite &CS, const DSGraph &Graph,
833 unsigned CloneFlags) {
834 hash_map<Value*, DSNodeHandle> OldValMap;
836 hash_map<Value*, DSNodeHandle> *ScalarMap = &OldValMap;
838 // If this is not a recursive call, clone the graph into this graph...
839 if (&Graph != this) {
840 // Clone the callee's graph into the current graph, keeping
841 // track of where scalars in the old graph _used_ to point,
842 // and of the new nodes matching nodes of the old graph.
843 hash_map<const DSNode*, DSNodeHandle> OldNodeMap;
845 // The clone call may invalidate any of the vectors in the data
846 // structure graph. Strip locals and don't copy the list of callers
847 RetVal = cloneInto(Graph, OldValMap, OldNodeMap, CloneFlags);
848 ScalarMap = &OldValMap;
850 RetVal = getRetNode();
851 ScalarMap = &getScalarMap();
854 // Merge the return value with the return value of the context...
855 RetVal.mergeWith(CS.getRetVal());
857 // Resolve all of the function arguments...
858 Function &F = Graph.getFunction();
859 Function::aiterator AI = F.abegin();
861 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
862 // Advance the argument iterator to the first pointer argument...
863 while (AI != F.aend() && !isPointerType(AI->getType())) {
867 std::cerr << "Bad call to Function: " << F.getName() << "\n";
870 if (AI == F.aend()) break;
872 // Add the link from the argument scalar to the provided value
873 assert(ScalarMap->count(AI) && "Argument not in scalar map?");
874 DSNodeHandle &NH = (*ScalarMap)[AI];
875 assert(NH.getNode() && "Pointer argument without scalarmap entry?");
876 NH.mergeWith(CS.getPtrArg(i));
881 // markIncompleteNodes - Mark the specified node as having contents that are not
882 // known with the current analysis we have performed. Because a node makes all
883 // of the nodes it can reach incomplete if the node itself is incomplete, we
884 // must recursively traverse the data structure graph, marking all reachable
885 // nodes as incomplete.
887 static void markIncompleteNode(DSNode *N) {
888 // Stop recursion if no node, or if node already marked...
889 if (N == 0 || N->isIncomplete()) return;
891 // Actually mark the node
892 N->setIncompleteMarker();
894 // Recusively process children...
895 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
896 if (DSNode *DSN = N->getLink(i).getNode())
897 markIncompleteNode(DSN);
900 static void markIncomplete(DSCallSite &Call) {
901 // Then the return value is certainly incomplete!
902 markIncompleteNode(Call.getRetVal().getNode());
904 // All objects pointed to by function arguments are incomplete!
905 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
906 markIncompleteNode(Call.getPtrArg(i).getNode());
909 // markIncompleteNodes - Traverse the graph, identifying nodes that may be
910 // modified by other functions that have not been resolved yet. This marks
911 // nodes that are reachable through three sources of "unknownness":
913 // Global Variables, Function Calls, and Incoming Arguments
915 // For any node that may have unknown components (because something outside the
916 // scope of current analysis may have modified it), the 'Incomplete' flag is
917 // added to the NodeType.
919 void DSGraph::markIncompleteNodes(unsigned Flags) {
920 // Mark any incoming arguments as incomplete...
921 if ((Flags & DSGraph::MarkFormalArgs) && Func && Func->getName() != "main")
922 for (Function::aiterator I = Func->abegin(), E = Func->aend(); I != E; ++I)
923 if (isPointerType(I->getType()) && ScalarMap.find(I) != ScalarMap.end())
924 markIncompleteNode(ScalarMap[I].getNode());
926 // Mark stuff passed into functions calls as being incomplete...
927 if (!shouldPrintAuxCalls())
928 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
929 markIncomplete(FunctionCalls[i]);
931 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
932 markIncomplete(AuxFunctionCalls[i]);
935 // Mark all global nodes as incomplete...
936 if ((Flags & DSGraph::IgnoreGlobals) == 0)
937 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
938 if (Nodes[i]->isGlobalNode() && Nodes[i]->getNumLinks())
939 markIncompleteNode(Nodes[i]);
942 static inline void killIfUselessEdge(DSNodeHandle &Edge) {
943 if (DSNode *N = Edge.getNode()) // Is there an edge?
944 if (N->getNumReferrers() == 1) // Does it point to a lonely node?
945 // No interesting info?
946 if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
947 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
948 Edge.setNode(0); // Kill the edge!
951 static inline bool nodeContainsExternalFunction(const DSNode *N) {
952 const std::vector<GlobalValue*> &Globals = N->getGlobals();
953 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
954 if (Globals[i]->isExternal())
959 static void removeIdenticalCalls(std::vector<DSCallSite> &Calls,
960 const std::string &where) {
961 // Remove trivially identical function calls
962 unsigned NumFns = Calls.size();
963 std::sort(Calls.begin(), Calls.end()); // Sort by callee as primary key!
965 // Scan the call list cleaning it up as necessary...
966 DSNode *LastCalleeNode = 0;
967 Function *LastCalleeFunc = 0;
968 unsigned NumDuplicateCalls = 0;
969 bool LastCalleeContainsExternalFunction = false;
970 for (unsigned i = 0; i != Calls.size(); ++i) {
971 DSCallSite &CS = Calls[i];
973 // If the Callee is a useless edge, this must be an unreachable call site,
975 if (CS.isIndirectCall() && CS.getCalleeNode()->getNumReferrers() == 1 &&
976 CS.getCalleeNode()->getNodeFlags() == 0) { // No useful info?
977 std::cerr << "WARNING: Useless call site found??\n";
978 CS.swap(Calls.back());
982 // If the return value or any arguments point to a void node with no
983 // information at all in it, and the call node is the only node to point
984 // to it, remove the edge to the node (killing the node).
986 killIfUselessEdge(CS.getRetVal());
987 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
988 killIfUselessEdge(CS.getPtrArg(a));
990 // If this call site calls the same function as the last call site, and if
991 // the function pointer contains an external function, this node will
992 // never be resolved. Merge the arguments of the call node because no
993 // information will be lost.
995 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
996 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
998 if (NumDuplicateCalls == 1) {
1000 LastCalleeContainsExternalFunction =
1001 nodeContainsExternalFunction(LastCalleeNode);
1003 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
1006 if (LastCalleeContainsExternalFunction ||
1007 // This should be more than enough context sensitivity!
1008 // FIXME: Evaluate how many times this is tripped!
1009 NumDuplicateCalls > 20) {
1010 DSCallSite &OCS = Calls[i-1];
1013 // The node will now be eliminated as a duplicate!
1014 if (CS.getNumPtrArgs() < OCS.getNumPtrArgs())
1016 else if (CS.getNumPtrArgs() > OCS.getNumPtrArgs())
1020 if (CS.isDirectCall()) {
1021 LastCalleeFunc = CS.getCalleeFunc();
1024 LastCalleeNode = CS.getCalleeNode();
1027 NumDuplicateCalls = 0;
1032 Calls.erase(std::unique(Calls.begin(), Calls.end()),
1035 // Track the number of call nodes merged away...
1036 NumCallNodesMerged += NumFns-Calls.size();
1038 DEBUG(if (NumFns != Calls.size())
1039 std::cerr << "Merged " << (NumFns-Calls.size())
1040 << " call nodes in " << where << "\n";);
1044 // removeTriviallyDeadNodes - After the graph has been constructed, this method
1045 // removes all unreachable nodes that are created because they got merged with
1046 // other nodes in the graph. These nodes will all be trivially unreachable, so
1047 // we don't have to perform any non-trivial analysis here.
1049 void DSGraph::removeTriviallyDeadNodes() {
1050 removeIdenticalCalls(FunctionCalls, Func ? Func->getName() : "");
1051 removeIdenticalCalls(AuxFunctionCalls, Func ? Func->getName() : "");
1053 for (unsigned i = 0; i != Nodes.size(); ++i) {
1054 DSNode *Node = Nodes[i];
1055 if (Node->isComplete() && !Node->isModified() && !Node->isRead()) {
1056 // This is a useless node if it has no mod/ref info (checked above),
1057 // outgoing edges (which it cannot, as it is not modified in this
1058 // context), and it has no incoming edges. If it is a global node it may
1059 // have all of these properties and still have incoming edges, due to the
1060 // scalar map, so we check those now.
1062 if (Node->getNumReferrers() == Node->getGlobals().size()) {
1063 const std::vector<GlobalValue*> &Globals = Node->getGlobals();
1065 // Loop through and make sure all of the globals are referring directly
1067 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1068 DSNode *N = ScalarMap.find(Globals[j])->second.getNode();
1069 assert(N == Node && "ScalarMap doesn't match globals list!");
1072 // Make sure NumReferrers still agrees, if so, the node is truly dead.
1073 if (Node->getNumReferrers() == Globals.size()) {
1074 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1075 ScalarMap.erase(Globals[j]);
1076 Node->makeNodeDead();
1081 if (Node->getNodeFlags() == 0 && Node->hasNoReferrers()) {
1082 // This node is dead!
1083 delete Node; // Free memory...
1084 Nodes[i--] = Nodes.back();
1085 Nodes.pop_back(); // Remove from node list...
1091 /// markReachableNodes - This method recursively traverses the specified
1092 /// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
1093 /// to the set, which allows it to only traverse visited nodes once.
1095 void DSNode::markReachableNodes(hash_set<DSNode*> &ReachableNodes) {
1096 if (this == 0) return;
1097 assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
1098 if (ReachableNodes.count(this)) return; // Already marked reachable
1099 ReachableNodes.insert(this); // Is reachable now
1101 for (unsigned i = 0, e = getSize(); i < e; i += DS::PointerSize)
1102 getLink(i).getNode()->markReachableNodes(ReachableNodes);
1105 void DSCallSite::markReachableNodes(hash_set<DSNode*> &Nodes) {
1106 getRetVal().getNode()->markReachableNodes(Nodes);
1107 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
1109 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
1110 getPtrArg(i).getNode()->markReachableNodes(Nodes);
1113 // CanReachAliveNodes - Simple graph walker that recursively traverses the graph
1114 // looking for a node that is marked alive. If an alive node is found, return
1115 // true, otherwise return false. If an alive node is reachable, this node is
1116 // marked as alive...
1118 static bool CanReachAliveNodes(DSNode *N, hash_set<DSNode*> &Alive,
1119 hash_set<DSNode*> &Visited) {
1120 if (N == 0) return false;
1121 assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
1123 // If we know that this node is alive, return so!
1124 if (Alive.count(N)) return true;
1126 // Otherwise, we don't think the node is alive yet, check for infinite
1128 if (Visited.count(N)) return false; // Found a cycle
1129 Visited.insert(N); // No recursion, insert into Visited...
1131 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
1132 if (CanReachAliveNodes(N->getLink(i).getNode(), Alive, Visited)) {
1133 N->markReachableNodes(Alive);
1139 // CallSiteUsesAliveArgs - Return true if the specified call site can reach any
1142 static bool CallSiteUsesAliveArgs(DSCallSite &CS, hash_set<DSNode*> &Alive,
1143 hash_set<DSNode*> &Visited) {
1144 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited))
1146 if (CS.isIndirectCall() &&
1147 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited))
1149 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
1150 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited))
1155 // removeDeadNodes - Use a more powerful reachability analysis to eliminate
1156 // subgraphs that are unreachable. This often occurs because the data
1157 // structure doesn't "escape" into it's caller, and thus should be eliminated
1158 // from the caller's graph entirely. This is only appropriate to use when
1161 void DSGraph::removeDeadNodes(unsigned Flags) {
1162 // Reduce the amount of work we have to do... remove dummy nodes left over by
1164 removeTriviallyDeadNodes();
1166 // FIXME: Merge nontrivially identical call nodes...
1168 // Alive - a set that holds all nodes found to be reachable/alive.
1169 hash_set<DSNode*> Alive;
1170 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
1172 // Mark all nodes reachable by (non-global) scalar nodes as alive...
1173 for (hash_map<Value*, DSNodeHandle>::iterator I = ScalarMap.begin(),
1174 E = ScalarMap.end(); I != E; )
1175 if (isa<GlobalValue>(I->first)) { // Keep track of global nodes
1176 assert(I->second.getNode() && "Null global node?");
1177 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
1180 // Check to see if this is a worthless node generated for non-pointer
1181 // values, such as integers. Consider an addition of long types: A+B.
1182 // Assuming we can track all uses of the value in this context, and it is
1183 // NOT used as a pointer, we can delete the node. We will be able to
1184 // detect this situation if the node pointed to ONLY has Unknown bit set
1185 // in the node. In this case, the node is not incomplete, does not point
1186 // to any other nodes (no mod/ref bits set), and is therefore
1187 // uninteresting for data structure analysis. If we run across one of
1188 // these, prune the scalar pointing to it.
1190 DSNode *N = I->second.getNode();
1191 if (N->isUnknownNode() && !isa<Argument>(I->first)) {
1192 ScalarMap.erase(I++);
1194 I->second.getNode()->markReachableNodes(Alive);
1199 // The return value is alive as well...
1200 RetNode.getNode()->markReachableNodes(Alive);
1202 // Mark any nodes reachable by primary calls as alive...
1203 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1204 FunctionCalls[i].markReachableNodes(Alive);
1207 hash_set<DSNode*> Visited;
1208 std::vector<unsigned char> AuxFCallsAlive(AuxFunctionCalls.size());
1211 // If any global nodes points to a non-global that is "alive", the global is
1212 // "alive" as well... Remove it from the GlobalNodes list so we only have
1213 // unreachable globals in the list.
1216 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
1217 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited)) {
1218 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to erase
1219 GlobalNodes.pop_back(); // Erase efficiently
1223 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1224 if (!AuxFCallsAlive[i] &&
1225 CallSiteUsesAliveArgs(AuxFunctionCalls[i], Alive, Visited)) {
1226 AuxFunctionCalls[i].markReachableNodes(Alive);
1227 AuxFCallsAlive[i] = true;
1232 // Remove all dead aux function calls...
1233 unsigned CurIdx = 0;
1234 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1235 if (AuxFCallsAlive[i])
1236 AuxFunctionCalls[CurIdx++].swap(AuxFunctionCalls[i]);
1237 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
1238 assert(GlobalsGraph && "No globals graph available??");
1239 // Move the unreachable call nodes to the globals graph...
1240 GlobalsGraph->AuxFunctionCalls.insert(GlobalsGraph->AuxFunctionCalls.end(),
1241 AuxFunctionCalls.begin()+CurIdx,
1242 AuxFunctionCalls.end());
1244 // Crop all the useless ones out...
1245 AuxFunctionCalls.erase(AuxFunctionCalls.begin()+CurIdx,
1246 AuxFunctionCalls.end());
1248 // At this point, any nodes which are visited, but not alive, are nodes which
1249 // should be moved to the globals graph. Loop over all nodes, eliminating
1250 // completely unreachable nodes, and moving visited nodes to the globals graph
1252 std::vector<DSNode*> DeadNodes;
1253 DeadNodes.reserve(Nodes.size());
1254 for (unsigned i = 0; i != Nodes.size(); ++i)
1255 if (!Alive.count(Nodes[i])) {
1256 DSNode *N = Nodes[i];
1257 Nodes[i--] = Nodes.back(); // move node to end of vector
1258 Nodes.pop_back(); // Erase node from alive list.
1259 if (!(Flags & DSGraph::RemoveUnreachableGlobals) && // Not in TD pass
1260 Visited.count(N)) { // Visited but not alive?
1261 GlobalsGraph->Nodes.push_back(N); // Move node to globals graph
1262 N->setParentGraph(GlobalsGraph);
1263 } else { // Otherwise, delete the node
1264 assert((!N->isGlobalNode() ||
1265 (Flags & DSGraph::RemoveUnreachableGlobals))
1266 && "Killing a global?");
1267 //std::cerr << "[" << i+1 << "/" << DeadNodes.size()
1268 // << "] Node is dead: "; N->dump();
1269 DeadNodes.push_back(N);
1270 N->dropAllReferences();
1273 assert(Nodes[i]->getForwardNode() == 0 && "Alive forwarded node?");
1276 // Now that the nodes have either been deleted or moved to the globals graph,
1277 // loop over the scalarmap, updating the entries for globals...
1279 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) { // Not in the TD pass?
1280 // In this array we start the remapping, which can cause merging. Because
1281 // of this, the DSNode pointers in GlobalNodes may be invalidated, so we
1282 // must always go through the ScalarMap (which contains DSNodeHandles [which
1283 // cannot be invalidated by merging]).
1285 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i) {
1286 Value *G = GlobalNodes[i].first;
1287 hash_map<Value*, DSNodeHandle>::iterator I = ScalarMap.find(G);
1288 assert(I != ScalarMap.end() && "Global not in scalar map anymore?");
1289 assert(I->second.getNode() && "Global not pointing to anything?");
1290 assert(!Alive.count(I->second.getNode()) && "Node is alive??");
1291 GlobalsGraph->ScalarMap[G].mergeWith(I->second);
1292 assert(GlobalsGraph->ScalarMap[G].getNode() &&
1293 "Global not pointing to anything?");
1297 // Merging leaves behind silly nodes, we remove them to avoid polluting the
1299 if (!GlobalNodes.empty())
1300 GlobalsGraph->removeTriviallyDeadNodes();
1302 // If we are in the top-down pass, remove all unreachable globals from the
1304 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
1305 ScalarMap.erase(GlobalNodes[i].first);
1308 // Loop over all of the dead nodes now, deleting them since their referrer
1310 for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
1311 delete DeadNodes[i];
1313 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
1316 void DSGraph::AssertGraphOK() const {
1317 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
1318 Nodes[i]->assertOK();
1319 return; // FIXME: remove
1320 for (hash_map<Value*, DSNodeHandle>::const_iterator I = ScalarMap.begin(),
1321 E = ScalarMap.end(); I != E; ++I) {
1322 assert(I->second.getNode() && "Null node in scalarmap!");
1323 AssertNodeInGraph(I->second.getNode());
1324 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
1325 assert(I->second.getNode()->isGlobalNode() &&
1326 "Global points to node, but node isn't global?");
1327 AssertNodeContainsGlobal(I->second.getNode(), GV);
1330 AssertCallNodesInGraph();
1331 AssertAuxCallNodesInGraph();