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 "llvm/Assembly/Writer.h"
13 #include "Support/Debug.h"
14 #include "Support/STLExtras.h"
15 #include "Support/Statistic.h"
16 #include "Support/Timer.h"
20 Statistic<> NumFolds ("dsnode", "Number of nodes completely folded");
21 Statistic<> NumCallNodesMerged("dsnode", "Number of call nodes merged");
24 namespace DS { // TODO: FIXME
29 DSNode *DSNodeHandle::HandleForwarding() const {
30 assert(!N->ForwardNH.isNull() && "Can only be invoked if forwarding!");
32 // Handle node forwarding here!
33 DSNode *Next = N->ForwardNH.getNode(); // Cause recursive shrinkage
34 Offset += N->ForwardNH.getOffset();
36 if (--N->NumReferrers == 0) {
37 // Removing the last referrer to the node, sever the forwarding link
43 if (N->Size <= Offset) {
44 assert(N->Size <= 1 && "Forwarded to shrunk but not collapsed node?");
50 //===----------------------------------------------------------------------===//
51 // DSNode Implementation
52 //===----------------------------------------------------------------------===//
54 DSNode::DSNode(const Type *T, DSGraph *G)
55 : NumReferrers(0), Size(0), ParentGraph(G), Ty(Type::VoidTy), NodeType(0) {
56 // Add the type entry if it is specified...
57 if (T) mergeTypeInfo(T, 0);
58 G->getNodes().push_back(this);
61 // DSNode copy constructor... do not copy over the referrers list!
62 DSNode::DSNode(const DSNode &N, DSGraph *G)
63 : NumReferrers(0), Size(N.Size), ParentGraph(G),
64 Ty(N.Ty), Links(N.Links), Globals(N.Globals), NodeType(N.NodeType) {
65 G->getNodes().push_back(this);
68 void DSNode::assertOK() const {
69 assert((Ty != Type::VoidTy ||
70 Ty == Type::VoidTy && (Size == 0 ||
71 (NodeType & DSNode::Array))) &&
74 assert(ParentGraph && "Node has no parent?");
75 const DSGraph::ScalarMapTy &SM = ParentGraph->getScalarMap();
76 for (unsigned i = 0, e = Globals.size(); i != e; ++i) {
77 assert(SM.find(Globals[i]) != SM.end());
78 assert(SM.find(Globals[i])->second.getNode() == this);
82 /// forwardNode - Mark this node as being obsolete, and all references to it
83 /// should be forwarded to the specified node and offset.
85 void DSNode::forwardNode(DSNode *To, unsigned Offset) {
86 assert(this != To && "Cannot forward a node to itself!");
87 assert(ForwardNH.isNull() && "Already forwarding from this node!");
88 if (To->Size <= 1) Offset = 0;
89 assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
90 "Forwarded offset is wrong!");
91 ForwardNH.setNode(To);
92 ForwardNH.setOffset(Offset);
98 // addGlobal - Add an entry for a global value to the Globals list. This also
99 // marks the node with the 'G' flag if it does not already have it.
101 void DSNode::addGlobal(GlobalValue *GV) {
102 // Keep the list sorted.
103 std::vector<GlobalValue*>::iterator I =
104 std::lower_bound(Globals.begin(), Globals.end(), GV);
106 if (I == Globals.end() || *I != GV) {
107 //assert(GV->getType()->getElementType() == Ty);
108 Globals.insert(I, GV);
109 NodeType |= GlobalNode;
113 /// foldNodeCompletely - If we determine that this node has some funny
114 /// behavior happening to it that we cannot represent, we fold it down to a
115 /// single, completely pessimistic, node. This node is represented as a
116 /// single byte with a single TypeEntry of "void".
118 void DSNode::foldNodeCompletely() {
119 if (isNodeCompletelyFolded()) return; // If this node is already folded...
123 // Create the node we are going to forward to...
124 DSNode *DestNode = new DSNode(0, ParentGraph);
125 DestNode->NodeType = NodeType|DSNode::Array;
126 DestNode->Ty = Type::VoidTy;
128 DestNode->Globals.swap(Globals);
130 // Start forwarding to the destination node...
131 forwardNode(DestNode, 0);
134 DestNode->Links.push_back(Links[0]);
135 DSNodeHandle NH(DestNode);
137 // If we have links, merge all of our outgoing links together...
138 for (unsigned i = Links.size()-1; i != 0; --i)
139 NH.getNode()->Links[0].mergeWith(Links[i]);
142 DestNode->Links.resize(1);
146 /// isNodeCompletelyFolded - Return true if this node has been completely
147 /// folded down to something that can never be expanded, effectively losing
148 /// all of the field sensitivity that may be present in the node.
150 bool DSNode::isNodeCompletelyFolded() const {
151 return getSize() == 1 && Ty == Type::VoidTy && isArray();
156 /// TypeElementWalker Class - Used for implementation of physical subtyping...
158 class TypeElementWalker {
163 StackState(const Type *T, unsigned Off = 0)
164 : Ty(T), Offset(Off), Idx(0) {}
167 std::vector<StackState> Stack;
169 TypeElementWalker(const Type *T) {
174 bool isDone() const { return Stack.empty(); }
175 const Type *getCurrentType() const { return Stack.back().Ty; }
176 unsigned getCurrentOffset() const { return Stack.back().Offset; }
178 void StepToNextType() {
179 PopStackAndAdvance();
184 /// PopStackAndAdvance - Pop the current element off of the stack and
185 /// advance the underlying element to the next contained member.
186 void PopStackAndAdvance() {
187 assert(!Stack.empty() && "Cannot pop an empty stack!");
189 while (!Stack.empty()) {
190 StackState &SS = Stack.back();
191 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
193 if (SS.Idx != ST->getElementTypes().size()) {
194 const StructLayout *SL = TD.getStructLayout(ST);
195 SS.Offset += SL->MemberOffsets[SS.Idx]-SL->MemberOffsets[SS.Idx-1];
198 Stack.pop_back(); // At the end of the structure
200 const ArrayType *AT = cast<ArrayType>(SS.Ty);
202 if (SS.Idx != AT->getNumElements()) {
203 SS.Offset += TD.getTypeSize(AT->getElementType());
206 Stack.pop_back(); // At the end of the array
211 /// StepToLeaf - Used by physical subtyping to move to the first leaf node
212 /// on the type stack.
214 if (Stack.empty()) return;
215 while (!Stack.empty() && !Stack.back().Ty->isFirstClassType()) {
216 StackState &SS = Stack.back();
217 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
218 if (ST->getElementTypes().empty()) {
220 PopStackAndAdvance();
222 // Step into the structure...
223 assert(SS.Idx < ST->getElementTypes().size());
224 const StructLayout *SL = TD.getStructLayout(ST);
225 Stack.push_back(StackState(ST->getElementTypes()[SS.Idx],
226 SS.Offset+SL->MemberOffsets[SS.Idx]));
229 const ArrayType *AT = cast<ArrayType>(SS.Ty);
230 if (AT->getNumElements() == 0) {
232 PopStackAndAdvance();
234 // Step into the array...
235 assert(SS.Idx < AT->getNumElements());
236 Stack.push_back(StackState(AT->getElementType(),
238 TD.getTypeSize(AT->getElementType())));
246 /// ElementTypesAreCompatible - Check to see if the specified types are
247 /// "physically" compatible. If so, return true, else return false. We only
248 /// have to check the fields in T1: T2 may be larger than T1.
250 static bool ElementTypesAreCompatible(const Type *T1, const Type *T2) {
251 TypeElementWalker T1W(T1), T2W(T2);
253 while (!T1W.isDone() && !T2W.isDone()) {
254 if (T1W.getCurrentOffset() != T2W.getCurrentOffset())
257 const Type *T1 = T1W.getCurrentType();
258 const Type *T2 = T2W.getCurrentType();
259 if (T1 != T2 && !T1->isLosslesslyConvertibleTo(T2))
262 T1W.StepToNextType();
263 T2W.StepToNextType();
270 /// mergeTypeInfo - This method merges the specified type into the current node
271 /// at the specified offset. This may update the current node's type record if
272 /// this gives more information to the node, it may do nothing to the node if
273 /// this information is already known, or it may merge the node completely (and
274 /// return true) if the information is incompatible with what is already known.
276 /// This method returns true if the node is completely folded, otherwise false.
278 bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset,
279 bool FoldIfIncompatible) {
280 // Check to make sure the Size member is up-to-date. Size can be one of the
282 // Size = 0, Ty = Void: Nothing is known about this node.
283 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
284 // Size = 1, Ty = Void, Array = 1: The node is collapsed
285 // Otherwise, sizeof(Ty) = Size
287 assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
288 (Size == 0 && !Ty->isSized() && !isArray()) ||
289 (Size == 1 && Ty == Type::VoidTy && isArray()) ||
290 (Size == 0 && !Ty->isSized() && !isArray()) ||
291 (TD.getTypeSize(Ty) == Size)) &&
292 "Size member of DSNode doesn't match the type structure!");
293 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
295 if (Offset == 0 && NewTy == Ty)
296 return false; // This should be a common case, handle it efficiently
298 // Return true immediately if the node is completely folded.
299 if (isNodeCompletelyFolded()) return true;
301 // If this is an array type, eliminate the outside arrays because they won't
302 // be used anyway. This greatly reduces the size of large static arrays used
303 // as global variables, for example.
305 bool WillBeArray = false;
306 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
307 // FIXME: we might want to keep small arrays, but must be careful about
308 // things like: [2 x [10000 x int*]]
309 NewTy = AT->getElementType();
313 // Figure out how big the new type we're merging in is...
314 unsigned NewTySize = NewTy->isSized() ? TD.getTypeSize(NewTy) : 0;
316 // Otherwise check to see if we can fold this type into the current node. If
317 // we can't, we fold the node completely, if we can, we potentially update our
320 if (Ty == Type::VoidTy) {
321 // If this is the first type that this node has seen, just accept it without
323 assert(Offset == 0 && "Cannot have an offset into a void node!");
324 assert(!isArray() && "This shouldn't happen!");
327 if (WillBeArray) NodeType |= Array;
330 // Calculate the number of outgoing links from this node.
331 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
335 // Handle node expansion case here...
336 if (Offset+NewTySize > Size) {
337 // It is illegal to grow this node if we have treated it as an array of
340 if (FoldIfIncompatible) foldNodeCompletely();
344 if (Offset) { // We could handle this case, but we don't for now...
345 std::cerr << "UNIMP: Trying to merge a growth type into "
346 << "offset != 0: Collapsing!\n";
347 if (FoldIfIncompatible) foldNodeCompletely();
351 // Okay, the situation is nice and simple, we are trying to merge a type in
352 // at offset 0 that is bigger than our current type. Implement this by
353 // switching to the new type and then merge in the smaller one, which should
354 // hit the other code path here. If the other code path decides it's not
355 // ok, it will collapse the node as appropriate.
357 const Type *OldTy = Ty;
360 if (WillBeArray) NodeType |= Array;
363 // Must grow links to be the appropriate size...
364 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
366 // Merge in the old type now... which is guaranteed to be smaller than the
368 return mergeTypeInfo(OldTy, 0);
371 assert(Offset <= Size &&
372 "Cannot merge something into a part of our type that doesn't exist!");
374 // Find the section of Ty that NewTy overlaps with... first we find the
375 // type that starts at offset Offset.
378 const Type *SubType = Ty;
380 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
382 switch (SubType->getPrimitiveID()) {
383 case Type::StructTyID: {
384 const StructType *STy = cast<StructType>(SubType);
385 const StructLayout &SL = *TD.getStructLayout(STy);
387 unsigned i = 0, e = SL.MemberOffsets.size();
388 for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
391 // The offset we are looking for must be in the i'th element...
392 SubType = STy->getElementTypes()[i];
393 O += SL.MemberOffsets[i];
396 case Type::ArrayTyID: {
397 SubType = cast<ArrayType>(SubType)->getElementType();
398 unsigned ElSize = TD.getTypeSize(SubType);
399 unsigned Remainder = (Offset-O) % ElSize;
400 O = Offset-Remainder;
404 if (FoldIfIncompatible) foldNodeCompletely();
409 assert(O == Offset && "Could not achieve the correct offset!");
411 // If we found our type exactly, early exit
412 if (SubType == NewTy) return false;
414 unsigned SubTypeSize = SubType->isSized() ? TD.getTypeSize(SubType) : 0;
416 // Ok, we are getting desperate now. Check for physical subtyping, where we
417 // just require each element in the node to be compatible.
418 if (NewTySize <= SubTypeSize && NewTySize && NewTySize < 256 &&
419 SubTypeSize && SubTypeSize < 256 &&
420 ElementTypesAreCompatible(NewTy, SubType))
423 // Okay, so we found the leader type at the offset requested. Search the list
424 // of types that starts at this offset. If SubType is currently an array or
425 // structure, the type desired may actually be the first element of the
428 unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
429 while (SubType != NewTy) {
430 const Type *NextSubType = 0;
431 unsigned NextSubTypeSize = 0;
432 unsigned NextPadSize = 0;
433 switch (SubType->getPrimitiveID()) {
434 case Type::StructTyID: {
435 const StructType *STy = cast<StructType>(SubType);
436 const StructLayout &SL = *TD.getStructLayout(STy);
437 if (SL.MemberOffsets.size() > 1)
438 NextPadSize = SL.MemberOffsets[1];
440 NextPadSize = SubTypeSize;
441 NextSubType = STy->getElementTypes()[0];
442 NextSubTypeSize = TD.getTypeSize(NextSubType);
445 case Type::ArrayTyID:
446 NextSubType = cast<ArrayType>(SubType)->getElementType();
447 NextSubTypeSize = TD.getTypeSize(NextSubType);
448 NextPadSize = NextSubTypeSize;
454 if (NextSubType == 0)
455 break; // In the default case, break out of the loop
457 if (NextPadSize < NewTySize)
458 break; // Don't allow shrinking to a smaller type than NewTySize
459 SubType = NextSubType;
460 SubTypeSize = NextSubTypeSize;
461 PadSize = NextPadSize;
464 // If we found the type exactly, return it...
465 if (SubType == NewTy)
468 // Check to see if we have a compatible, but different type...
469 if (NewTySize == SubTypeSize) {
470 // Check to see if this type is obviously convertible... int -> uint f.e.
471 if (NewTy->isLosslesslyConvertibleTo(SubType))
474 // Check to see if we have a pointer & integer mismatch going on here,
475 // loading a pointer as a long, for example.
477 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
478 NewTy->isInteger() && isa<PointerType>(SubType))
480 } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
481 // We are accessing the field, plus some structure padding. Ignore the
482 // structure padding.
487 if (getParentGraph()->getReturnNodes().size())
488 M = getParentGraph()->getReturnNodes().begin()->first->getParent();
489 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: ";
490 WriteTypeSymbolic(std::cerr, Ty, M) << "\n due to:";
491 WriteTypeSymbolic(std::cerr, NewTy, M) << " @ " << Offset << "!\n"
493 WriteTypeSymbolic(std::cerr, SubType, M) << "\n\n");
495 if (FoldIfIncompatible) foldNodeCompletely();
501 // addEdgeTo - Add an edge from the current node to the specified node. This
502 // can cause merging of nodes in the graph.
504 void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
505 if (NH.getNode() == 0) return; // Nothing to do
507 DSNodeHandle &ExistingEdge = getLink(Offset);
508 if (ExistingEdge.getNode()) {
509 // Merge the two nodes...
510 ExistingEdge.mergeWith(NH);
511 } else { // No merging to perform...
512 setLink(Offset, NH); // Just force a link in there...
517 // MergeSortedVectors - Efficiently merge a vector into another vector where
518 // duplicates are not allowed and both are sorted. This assumes that 'T's are
519 // efficiently copyable and have sane comparison semantics.
521 static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
522 const std::vector<GlobalValue*> &Src) {
523 // By far, the most common cases will be the simple ones. In these cases,
524 // avoid having to allocate a temporary vector...
526 if (Src.empty()) { // Nothing to merge in...
528 } else if (Dest.empty()) { // Just copy the result in...
530 } else if (Src.size() == 1) { // Insert a single element...
531 const GlobalValue *V = Src[0];
532 std::vector<GlobalValue*>::iterator I =
533 std::lower_bound(Dest.begin(), Dest.end(), V);
534 if (I == Dest.end() || *I != Src[0]) // If not already contained...
535 Dest.insert(I, Src[0]);
536 } else if (Dest.size() == 1) {
537 GlobalValue *Tmp = Dest[0]; // Save value in temporary...
538 Dest = Src; // Copy over list...
539 std::vector<GlobalValue*>::iterator I =
540 std::lower_bound(Dest.begin(), Dest.end(), Tmp);
541 if (I == Dest.end() || *I != Tmp) // If not already contained...
545 // Make a copy to the side of Dest...
546 std::vector<GlobalValue*> Old(Dest);
548 // Make space for all of the type entries now...
549 Dest.resize(Dest.size()+Src.size());
551 // Merge the two sorted ranges together... into Dest.
552 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
554 // Now erase any duplicate entries that may have accumulated into the
555 // vectors (because they were in both of the input sets)
556 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
561 // MergeNodes() - Helper function for DSNode::mergeWith().
562 // This function does the hard work of merging two nodes, CurNodeH
563 // and NH after filtering out trivial cases and making sure that
564 // CurNodeH.offset >= NH.offset.
567 // Since merging may cause either node to go away, we must always
568 // use the node-handles to refer to the nodes. These node handles are
569 // automatically updated during merging, so will always provide access
570 // to the correct node after a merge.
572 void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
573 assert(CurNodeH.getOffset() >= NH.getOffset() &&
574 "This should have been enforced in the caller.");
576 // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
577 // respect to NH.Offset) is now zero. NOffset is the distance from the base
578 // of our object that N starts from.
580 unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
581 unsigned NSize = NH.getNode()->getSize();
583 // If the two nodes are of different size, and the smaller node has the array
584 // bit set, collapse!
585 if (NSize != CurNodeH.getNode()->getSize()) {
586 if (NSize < CurNodeH.getNode()->getSize()) {
587 if (NH.getNode()->isArray())
588 NH.getNode()->foldNodeCompletely();
589 } else if (CurNodeH.getNode()->isArray()) {
590 NH.getNode()->foldNodeCompletely();
594 // Merge the type entries of the two nodes together...
595 if (NH.getNode()->Ty != Type::VoidTy)
596 CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
597 assert(!CurNodeH.getNode()->isDeadNode());
599 // If we are merging a node with a completely folded node, then both nodes are
600 // now completely folded.
602 if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
603 if (!NH.getNode()->isNodeCompletelyFolded()) {
604 NH.getNode()->foldNodeCompletely();
605 assert(NH.getNode() && NH.getOffset() == 0 &&
606 "folding did not make offset 0?");
607 NOffset = NH.getOffset();
608 NSize = NH.getNode()->getSize();
609 assert(NOffset == 0 && NSize == 1);
611 } else if (NH.getNode()->isNodeCompletelyFolded()) {
612 CurNodeH.getNode()->foldNodeCompletely();
613 assert(CurNodeH.getNode() && CurNodeH.getOffset() == 0 &&
614 "folding did not make offset 0?");
615 NOffset = NH.getOffset();
616 NSize = NH.getNode()->getSize();
617 assert(NOffset == 0 && NSize == 1);
620 DSNode *N = NH.getNode();
621 if (CurNodeH.getNode() == N || N == 0) return;
622 assert(!CurNodeH.getNode()->isDeadNode());
624 // Merge the NodeType information...
625 CurNodeH.getNode()->NodeType |= N->NodeType;
627 // Start forwarding to the new node!
628 N->forwardNode(CurNodeH.getNode(), NOffset);
629 assert(!CurNodeH.getNode()->isDeadNode());
631 // Make all of the outgoing links of N now be outgoing links of CurNodeH.
633 for (unsigned i = 0; i < N->getNumLinks(); ++i) {
634 DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
635 if (Link.getNode()) {
636 // Compute the offset into the current node at which to
637 // merge this link. In the common case, this is a linear
638 // relation to the offset in the original node (with
639 // wrapping), but if the current node gets collapsed due to
640 // recursive merging, we must make sure to merge in all remaining
641 // links at offset zero.
642 unsigned MergeOffset = 0;
643 DSNode *CN = CurNodeH.getNode();
645 MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
646 CN->addEdgeTo(MergeOffset, Link);
650 // Now that there are no outgoing edges, all of the Links are dead.
653 // Merge the globals list...
654 if (!N->Globals.empty()) {
655 MergeSortedVectors(CurNodeH.getNode()->Globals, N->Globals);
657 // Delete the globals from the old node...
658 std::vector<GlobalValue*>().swap(N->Globals);
663 // mergeWith - Merge this node and the specified node, moving all links to and
664 // from the argument node into the current node, deleting the node argument.
665 // Offset indicates what offset the specified node is to be merged into the
668 // The specified node may be a null pointer (in which case, nothing happens).
670 void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
671 DSNode *N = NH.getNode();
672 if (N == 0 || (N == this && NH.getOffset() == Offset))
675 assert(!N->isDeadNode() && !isDeadNode());
676 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
679 // We cannot merge two pieces of the same node together, collapse the node
681 DEBUG(std::cerr << "Attempting to merge two chunks of"
682 << " the same node together!\n");
683 foldNodeCompletely();
687 // If both nodes are not at offset 0, make sure that we are merging the node
688 // at an later offset into the node with the zero offset.
690 if (Offset < NH.getOffset()) {
691 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
693 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
694 // If the offsets are the same, merge the smaller node into the bigger node
695 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
699 // Ok, now we can merge the two nodes. Use a static helper that works with
700 // two node handles, since "this" may get merged away at intermediate steps.
701 DSNodeHandle CurNodeH(this, Offset);
702 DSNodeHandle NHCopy(NH);
703 DSNode::MergeNodes(CurNodeH, NHCopy);
706 //===----------------------------------------------------------------------===//
707 // DSCallSite Implementation
708 //===----------------------------------------------------------------------===//
710 // Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
711 Function &DSCallSite::getCaller() const {
712 return *Inst->getParent()->getParent();
716 //===----------------------------------------------------------------------===//
717 // DSGraph Implementation
718 //===----------------------------------------------------------------------===//
720 /// getFunctionNames - Return a space separated list of the name of the
721 /// functions in this graph (if any)
722 std::string DSGraph::getFunctionNames() const {
723 switch (getReturnNodes().size()) {
724 case 0: return "Globals graph";
725 case 1: return getReturnNodes().begin()->first->getName();
728 for (DSGraph::ReturnNodesTy::const_iterator I = getReturnNodes().begin();
729 I != getReturnNodes().end(); ++I)
730 Return += I->first->getName() + " ";
731 Return.erase(Return.end()-1, Return.end()); // Remove last space character
737 DSGraph::DSGraph(const DSGraph &G) : GlobalsGraph(0) {
738 PrintAuxCalls = false;
740 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
741 InlinedGlobals.clear(); // clear set of "up-to-date" globals
744 DSGraph::DSGraph(const DSGraph &G, NodeMapTy &NodeMap)
746 PrintAuxCalls = false;
747 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
748 InlinedGlobals.clear(); // clear set of "up-to-date" globals
751 DSGraph::~DSGraph() {
752 FunctionCalls.clear();
753 AuxFunctionCalls.clear();
754 InlinedGlobals.clear();
758 // Drop all intra-node references, so that assertions don't fail...
759 std::for_each(Nodes.begin(), Nodes.end(),
760 std::mem_fun(&DSNode::dropAllReferences));
762 // Delete all of the nodes themselves...
763 std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
766 // dump - Allow inspection of graph in a debugger.
767 void DSGraph::dump() const { print(std::cerr); }
770 /// remapLinks - Change all of the Links in the current node according to the
771 /// specified mapping.
773 void DSNode::remapLinks(DSGraph::NodeMapTy &OldNodeMap) {
774 for (unsigned i = 0, e = Links.size(); i != e; ++i) {
775 DSNodeHandle &H = OldNodeMap[Links[i].getNode()];
776 Links[i].setNode(H.getNode());
777 Links[i].setOffset(Links[i].getOffset()+H.getOffset());
782 /// cloneReachableNodes - Clone all reachable nodes from *Node into the
783 /// current graph. This is a recursive function. The map OldNodeMap is a
784 /// map from the original nodes to their clones.
786 void DSGraph::cloneReachableNodes(const DSNode* Node,
787 unsigned BitsToClear,
788 NodeMapTy& OldNodeMap,
789 NodeMapTy& CompletedNodeMap) {
790 if (CompletedNodeMap.find(Node) != CompletedNodeMap.end())
793 DSNodeHandle& NH = OldNodeMap[Node];
794 if (NH.getNode() != NULL)
797 // else Node has not yet been cloned: clone it and clear the specified bits
798 NH = new DSNode(*Node, this); // enters in OldNodeMap
799 NH.getNode()->maskNodeTypes(~BitsToClear);
801 // now recursively clone nodes pointed to by this node
802 for (unsigned i = 0, e = Node->getNumLinks(); i != e; ++i) {
803 const DSNodeHandle &Link = Node->getLink(i << DS::PointerShift);
804 if (const DSNode* nextNode = Link.getNode())
805 cloneReachableNodes(nextNode, BitsToClear, OldNodeMap, CompletedNodeMap);
809 void DSGraph::cloneReachableSubgraph(const DSGraph& G,
810 const hash_set<const DSNode*>& RootNodes,
811 NodeMapTy& OldNodeMap,
812 NodeMapTy& CompletedNodeMap,
813 unsigned CloneFlags) {
814 if (RootNodes.empty())
817 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
818 assert(&G != this && "Cannot clone graph into itself!");
819 assert((*RootNodes.begin())->getParentGraph() == &G &&
820 "Root nodes do not belong to this graph!");
822 // Remove alloca or mod/ref bits as specified...
823 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
824 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
825 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
826 BitsToClear |= DSNode::DEAD; // Clear dead flag...
828 // Clone all nodes reachable from each root node, using a recursive helper
829 for (hash_set<const DSNode*>::const_iterator I = RootNodes.begin(),
830 E = RootNodes.end(); I != E; ++I)
831 cloneReachableNodes(*I, BitsToClear, OldNodeMap, CompletedNodeMap);
833 // Merge the map entries in OldNodeMap and CompletedNodeMap to remap links
834 NodeMapTy MergedMap(OldNodeMap);
835 MergedMap.insert(CompletedNodeMap.begin(), CompletedNodeMap.end());
837 // Rewrite the links in the newly created nodes (the nodes in OldNodeMap)
838 // to point into the current graph. MergedMap gives the full mapping.
839 for (NodeMapTy::iterator I=OldNodeMap.begin(), E=OldNodeMap.end(); I!= E; ++I)
840 I->second.getNode()->remapLinks(MergedMap);
842 // Now merge cloned global nodes with their copies in the current graph
843 // Just look through OldNodeMap to find such nodes!
844 for (NodeMapTy::iterator I=OldNodeMap.begin(), E=OldNodeMap.end(); I!= E; ++I)
845 if (I->first->isGlobalNode()) {
846 DSNodeHandle &GClone = I->second;
847 assert(GClone.getNode() != NULL && "NULL node in OldNodeMap?");
848 const std::vector<GlobalValue*> &Globals = I->first->getGlobals();
849 for (unsigned gi = 0, ge = Globals.size(); gi != ge; ++gi) {
850 DSNodeHandle &GH = ScalarMap[Globals[gi]];
851 GH.mergeWith(GClone);
857 /// updateFromGlobalGraph - This function rematerializes global nodes and
858 /// nodes reachable from them from the globals graph into the current graph.
859 /// It invokes cloneReachableSubgraph, using the globals in the current graph
860 /// as the roots. It also uses the vector InlinedGlobals to avoid cloning and
861 /// merging globals that are already up-to-date in the current graph. In
862 /// practice, in the TD pass, this is likely to be a large fraction of the
863 /// live global nodes in each function (since most live nodes are likely to
864 /// have been brought up-to-date in at _some_ caller or callee).
866 void DSGraph::updateFromGlobalGraph() {
868 // Use a map to keep track of the mapping between nodes in the globals graph
869 // and this graph for up-to-date global nodes, which do not need to be cloned.
870 NodeMapTy CompletedMap;
872 // Put the live, non-up-to-date global nodes into a set and the up-to-date
873 // ones in the map above, mapping node in GlobalsGraph to the up-to-date node.
874 hash_set<const DSNode*> GlobalNodeSet;
875 for (ScalarMapTy::const_iterator I = getScalarMap().begin(),
876 E = getScalarMap().end(); I != E; ++I)
877 if (GlobalValue* GV = dyn_cast<GlobalValue>(I->first)) {
878 DSNode* GNode = I->second.getNode();
879 assert(GNode && "No node for live global in current Graph?");
880 if (const DSNode* GGNode = GlobalsGraph->ScalarMap[GV].getNode())
881 if (InlinedGlobals.count(GV) == 0) // GNode is not up-to-date
882 GlobalNodeSet.insert(GGNode);
883 else { // GNode is up-to-date
884 CompletedMap[GGNode] = I->second;
885 assert(GGNode->getNumLinks() == GNode->getNumLinks() &&
886 "Links dont match in a node that is supposed to be up-to-date?"
887 "\nremapLinks() will not work if the links don't match!");
891 // Clone the subgraph reachable from the vector of nodes in GlobalNodes
892 // and merge the cloned global nodes with the corresponding ones, if any.
893 NodeMapTy OldNodeMap;
894 cloneReachableSubgraph(*GlobalsGraph, GlobalNodeSet, OldNodeMap,CompletedMap);
896 // Merging global nodes leaves behind unused nodes: get rid of them now.
897 OldNodeMap.clear(); // remove references before dead node cleanup
898 CompletedMap.clear(); // remove references before dead node cleanup
899 removeTriviallyDeadNodes();
902 /// cloneInto - Clone the specified DSGraph into the current graph. The
903 /// translated ScalarMap for the old function is filled into the OldValMap
904 /// member, and the translated ReturnNodes map is returned into ReturnNodes.
906 /// The CloneFlags member controls various aspects of the cloning process.
908 void DSGraph::cloneInto(const DSGraph &G, ScalarMapTy &OldValMap,
909 ReturnNodesTy &OldReturnNodes, NodeMapTy &OldNodeMap,
910 unsigned CloneFlags) {
911 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
912 assert(&G != this && "Cannot clone graph into itself!");
914 unsigned FN = Nodes.size(); // First new node...
916 // Duplicate all of the nodes, populating the node map...
917 Nodes.reserve(FN+G.Nodes.size());
919 // Remove alloca or mod/ref bits as specified...
920 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
921 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
922 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
923 BitsToClear |= DSNode::DEAD; // Clear dead flag...
924 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
925 DSNode *Old = G.Nodes[i];
926 DSNode *New = new DSNode(*Old, this);
927 New->maskNodeTypes(~BitsToClear);
928 OldNodeMap[Old] = New;
932 Timer::addPeakMemoryMeasurement();
935 // Rewrite the links in the new nodes to point into the current graph now.
936 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
937 Nodes[i]->remapLinks(OldNodeMap);
939 // Copy the scalar map... merging all of the global nodes...
940 for (ScalarMapTy::const_iterator I = G.ScalarMap.begin(),
941 E = G.ScalarMap.end(); I != E; ++I) {
942 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
943 DSNodeHandle &H = OldValMap[I->first];
944 H.mergeWith(DSNodeHandle(MappedNode.getNode(),
945 I->second.getOffset()+MappedNode.getOffset()));
947 // If this is a global, add the global to this fn or merge if already exists
948 if (GlobalValue* GV = dyn_cast<GlobalValue>(I->first)) {
949 ScalarMap[GV].mergeWith(H);
950 InlinedGlobals.insert(GV);
954 if (!(CloneFlags & DontCloneCallNodes)) {
955 // Copy the function calls list...
956 unsigned FC = FunctionCalls.size(); // FirstCall
957 FunctionCalls.reserve(FC+G.FunctionCalls.size());
958 for (unsigned i = 0, ei = G.FunctionCalls.size(); i != ei; ++i)
959 FunctionCalls.push_back(DSCallSite(G.FunctionCalls[i], OldNodeMap));
962 if (!(CloneFlags & DontCloneAuxCallNodes)) {
963 // Copy the auxiliary function calls list...
964 unsigned FC = AuxFunctionCalls.size(); // FirstCall
965 AuxFunctionCalls.reserve(FC+G.AuxFunctionCalls.size());
966 for (unsigned i = 0, ei = G.AuxFunctionCalls.size(); i != ei; ++i)
967 AuxFunctionCalls.push_back(DSCallSite(G.AuxFunctionCalls[i], OldNodeMap));
970 // Map the return node pointers over...
971 for (ReturnNodesTy::const_iterator I = G.getReturnNodes().begin(),
972 E = G.getReturnNodes().end(); I != E; ++I) {
973 const DSNodeHandle &Ret = I->second;
974 DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
975 OldReturnNodes.insert(std::make_pair(I->first,
976 DSNodeHandle(MappedRet.getNode(),
977 MappedRet.getOffset()+Ret.getOffset())));
981 /// mergeInGraph - The method is used for merging graphs together. If the
982 /// argument graph is not *this, it makes a clone of the specified graph, then
983 /// merges the nodes specified in the call site with the formal arguments in the
986 void DSGraph::mergeInGraph(const DSCallSite &CS, Function &F,
987 const DSGraph &Graph, unsigned CloneFlags) {
988 ScalarMapTy OldValMap, *ScalarMap;
991 // If this is not a recursive call, clone the graph into this graph...
992 if (&Graph != this) {
993 // Clone the callee's graph into the current graph, keeping
994 // track of where scalars in the old graph _used_ to point,
995 // and of the new nodes matching nodes of the old graph.
996 NodeMapTy OldNodeMap;
998 // The clone call may invalidate any of the vectors in the data
999 // structure graph. Strip locals and don't copy the list of callers
1000 ReturnNodesTy OldRetNodes;
1001 cloneInto(Graph, OldValMap, OldRetNodes, OldNodeMap, CloneFlags);
1003 // We need to map the arguments for the function to the cloned nodes old
1004 // argument values. Do this now.
1005 RetVal = OldRetNodes[&F];
1006 ScalarMap = &OldValMap;
1008 RetVal = getReturnNodeFor(F);
1009 ScalarMap = &getScalarMap();
1012 // Merge the return value with the return value of the context...
1013 RetVal.mergeWith(CS.getRetVal());
1015 // Resolve all of the function arguments...
1016 Function::aiterator AI = F.abegin();
1018 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
1019 // Advance the argument iterator to the first pointer argument...
1020 while (AI != F.aend() && !isPointerType(AI->getType())) {
1024 std::cerr << "Bad call to Function: " << F.getName() << "\n";
1027 if (AI == F.aend()) break;
1029 // Add the link from the argument scalar to the provided value
1030 assert(ScalarMap->count(AI) && "Argument not in scalar map?");
1031 DSNodeHandle &NH = (*ScalarMap)[AI];
1032 assert(NH.getNode() && "Pointer argument without scalarmap entry?");
1033 NH.mergeWith(CS.getPtrArg(i));
1037 /// getCallSiteForArguments - Get the arguments and return value bindings for
1038 /// the specified function in the current graph.
1040 DSCallSite DSGraph::getCallSiteForArguments(Function &F) const {
1041 std::vector<DSNodeHandle> Args;
1043 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
1044 if (isPointerType(I->getType()))
1045 Args.push_back(getScalarMap().find(I)->second);
1047 return DSCallSite(*(CallInst*)0, getReturnNodeFor(F), &F, Args);
1052 // markIncompleteNodes - Mark the specified node as having contents that are not
1053 // known with the current analysis we have performed. Because a node makes all
1054 // of the nodes it can reach incomplete if the node itself is incomplete, we
1055 // must recursively traverse the data structure graph, marking all reachable
1056 // nodes as incomplete.
1058 static void markIncompleteNode(DSNode *N) {
1059 // Stop recursion if no node, or if node already marked...
1060 if (N == 0 || N->isIncomplete()) return;
1062 // Actually mark the node
1063 N->setIncompleteMarker();
1065 // Recursively process children...
1066 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
1067 if (DSNode *DSN = N->getLink(i).getNode())
1068 markIncompleteNode(DSN);
1071 static void markIncomplete(DSCallSite &Call) {
1072 // Then the return value is certainly incomplete!
1073 markIncompleteNode(Call.getRetVal().getNode());
1075 // All objects pointed to by function arguments are incomplete!
1076 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
1077 markIncompleteNode(Call.getPtrArg(i).getNode());
1080 // markIncompleteNodes - Traverse the graph, identifying nodes that may be
1081 // modified by other functions that have not been resolved yet. This marks
1082 // nodes that are reachable through three sources of "unknownness":
1084 // Global Variables, Function Calls, and Incoming Arguments
1086 // For any node that may have unknown components (because something outside the
1087 // scope of current analysis may have modified it), the 'Incomplete' flag is
1088 // added to the NodeType.
1090 void DSGraph::markIncompleteNodes(unsigned Flags) {
1091 // Mark any incoming arguments as incomplete...
1092 if (Flags & DSGraph::MarkFormalArgs)
1093 for (ReturnNodesTy::iterator FI = ReturnNodes.begin(), E =ReturnNodes.end();
1095 Function &F = *FI->first;
1096 if (F.getName() != "main")
1097 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
1098 if (isPointerType(I->getType()) &&
1099 ScalarMap.find(I) != ScalarMap.end())
1100 markIncompleteNode(ScalarMap[I].getNode());
1103 // Mark stuff passed into functions calls as being incomplete...
1104 if (!shouldPrintAuxCalls())
1105 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1106 markIncomplete(FunctionCalls[i]);
1108 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1109 markIncomplete(AuxFunctionCalls[i]);
1112 // Mark all global nodes as incomplete...
1113 if ((Flags & DSGraph::IgnoreGlobals) == 0)
1114 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
1115 if (Nodes[i]->isGlobalNode() && Nodes[i]->getNumLinks())
1116 markIncompleteNode(Nodes[i]);
1119 static inline void killIfUselessEdge(DSNodeHandle &Edge) {
1120 if (DSNode *N = Edge.getNode()) // Is there an edge?
1121 if (N->getNumReferrers() == 1) // Does it point to a lonely node?
1122 // No interesting info?
1123 if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
1124 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
1125 Edge.setNode(0); // Kill the edge!
1128 static inline bool nodeContainsExternalFunction(const DSNode *N) {
1129 const std::vector<GlobalValue*> &Globals = N->getGlobals();
1130 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
1131 if (Globals[i]->isExternal())
1136 static void removeIdenticalCalls(std::vector<DSCallSite> &Calls) {
1138 // Remove trivially identical function calls
1139 unsigned NumFns = Calls.size();
1140 std::sort(Calls.begin(), Calls.end()); // Sort by callee as primary key!
1142 // Scan the call list cleaning it up as necessary...
1143 DSNode *LastCalleeNode = 0;
1144 Function *LastCalleeFunc = 0;
1145 unsigned NumDuplicateCalls = 0;
1146 bool LastCalleeContainsExternalFunction = false;
1147 for (unsigned i = 0; i != Calls.size(); ++i) {
1148 DSCallSite &CS = Calls[i];
1150 // If the Callee is a useless edge, this must be an unreachable call site,
1152 if (CS.isIndirectCall() && CS.getCalleeNode()->getNumReferrers() == 1 &&
1153 CS.getCalleeNode()->getNodeFlags() == 0) { // No useful info?
1154 std::cerr << "WARNING: Useless call site found??\n";
1155 CS.swap(Calls.back());
1159 // If the return value or any arguments point to a void node with no
1160 // information at all in it, and the call node is the only node to point
1161 // to it, remove the edge to the node (killing the node).
1163 killIfUselessEdge(CS.getRetVal());
1164 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
1165 killIfUselessEdge(CS.getPtrArg(a));
1167 // If this call site calls the same function as the last call site, and if
1168 // the function pointer contains an external function, this node will
1169 // never be resolved. Merge the arguments of the call node because no
1170 // information will be lost.
1172 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
1173 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
1174 ++NumDuplicateCalls;
1175 if (NumDuplicateCalls == 1) {
1177 LastCalleeContainsExternalFunction =
1178 nodeContainsExternalFunction(LastCalleeNode);
1180 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
1184 if (LastCalleeContainsExternalFunction ||
1185 // This should be more than enough context sensitivity!
1186 // FIXME: Evaluate how many times this is tripped!
1187 NumDuplicateCalls > 20) {
1188 DSCallSite &OCS = Calls[i-1];
1191 // The node will now be eliminated as a duplicate!
1192 if (CS.getNumPtrArgs() < OCS.getNumPtrArgs())
1194 else if (CS.getNumPtrArgs() > OCS.getNumPtrArgs())
1199 if (CS.isDirectCall()) {
1200 LastCalleeFunc = CS.getCalleeFunc();
1203 LastCalleeNode = CS.getCalleeNode();
1206 NumDuplicateCalls = 0;
1211 Calls.erase(std::unique(Calls.begin(), Calls.end()),
1214 // Track the number of call nodes merged away...
1215 NumCallNodesMerged += NumFns-Calls.size();
1217 DEBUG(if (NumFns != Calls.size())
1218 std::cerr << "Merged " << (NumFns-Calls.size()) << " call nodes.\n";);
1222 // removeTriviallyDeadNodes - After the graph has been constructed, this method
1223 // removes all unreachable nodes that are created because they got merged with
1224 // other nodes in the graph. These nodes will all be trivially unreachable, so
1225 // we don't have to perform any non-trivial analysis here.
1227 void DSGraph::removeTriviallyDeadNodes() {
1228 removeIdenticalCalls(FunctionCalls);
1229 removeIdenticalCalls(AuxFunctionCalls);
1231 bool isGlobalsGraph = !GlobalsGraph;
1233 for (unsigned i = 0; i != Nodes.size(); ++i) {
1234 DSNode *Node = Nodes[i];
1236 // Do not remove *any* global nodes in the globals graph.
1237 // This is a special case because such nodes may not have I, M, R flags set.
1238 if (Node->isGlobalNode() && isGlobalsGraph)
1241 if (Node->isComplete() && !Node->isModified() && !Node->isRead()) {
1242 // This is a useless node if it has no mod/ref info (checked above),
1243 // outgoing edges (which it cannot, as it is not modified in this
1244 // context), and it has no incoming edges. If it is a global node it may
1245 // have all of these properties and still have incoming edges, due to the
1246 // scalar map, so we check those now.
1248 if (Node->getNumReferrers() == Node->getGlobals().size()) {
1249 const std::vector<GlobalValue*> &Globals = Node->getGlobals();
1251 // Loop through and make sure all of the globals are referring directly
1253 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1254 DSNode *N = ScalarMap.find(Globals[j])->second.getNode();
1255 assert(N == Node && "ScalarMap doesn't match globals list!");
1258 // Make sure NumReferrers still agrees, if so, the node is truly dead.
1259 if (Node->getNumReferrers() == Globals.size()) {
1260 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1261 ScalarMap.erase(Globals[j]);
1262 Node->makeNodeDead();
1266 #ifdef SANER_CODE_FOR_CHECKING_IF_ALL_REFERRERS_ARE_FROM_SCALARMAP
1268 // *** It seems to me that we should be able to simply check if
1269 // *** there are fewer or equal #referrers as #globals and make
1270 // *** sure that all those referrers are in the scalar map?
1272 if (Node->getNumReferrers() <= Node->getGlobals().size()) {
1273 const std::vector<GlobalValue*> &Globals = Node->getGlobals();
1276 // Loop through and make sure all of the globals are referring directly
1278 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1279 DSNode *N = ScalarMap.find(Globals[j])->second.getNode();
1280 assert(N == Node && "ScalarMap doesn't match globals list!");
1284 // Make sure NumReferrers still agrees. The node is truly dead.
1285 assert(Node->getNumReferrers() == Globals.size());
1286 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1287 ScalarMap.erase(Globals[j]);
1288 Node->makeNodeDead();
1293 if (Node->getNodeFlags() == 0 && Node->hasNoReferrers()) {
1294 // This node is dead!
1295 delete Node; // Free memory...
1296 Nodes[i--] = Nodes.back();
1297 Nodes.pop_back(); // Remove from node list...
1303 /// markReachableNodes - This method recursively traverses the specified
1304 /// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
1305 /// to the set, which allows it to only traverse visited nodes once.
1307 void DSNode::markReachableNodes(hash_set<DSNode*> &ReachableNodes) {
1308 if (this == 0) return;
1309 assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
1310 if (ReachableNodes.count(this)) return; // Already marked reachable
1311 ReachableNodes.insert(this); // Is reachable now
1313 for (unsigned i = 0, e = getSize(); i < e; i += DS::PointerSize)
1314 getLink(i).getNode()->markReachableNodes(ReachableNodes);
1317 void DSCallSite::markReachableNodes(hash_set<DSNode*> &Nodes) {
1318 getRetVal().getNode()->markReachableNodes(Nodes);
1319 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
1321 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
1322 getPtrArg(i).getNode()->markReachableNodes(Nodes);
1325 // CanReachAliveNodes - Simple graph walker that recursively traverses the graph
1326 // looking for a node that is marked alive. If an alive node is found, return
1327 // true, otherwise return false. If an alive node is reachable, this node is
1328 // marked as alive...
1330 static bool CanReachAliveNodes(DSNode *N, hash_set<DSNode*> &Alive,
1331 hash_set<DSNode*> &Visited,
1332 bool IgnoreGlobals) {
1333 if (N == 0) return false;
1334 assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
1336 // If this is a global node, it will end up in the globals graph anyway, so we
1337 // don't need to worry about it.
1338 if (IgnoreGlobals && N->isGlobalNode()) return false;
1340 // If we know that this node is alive, return so!
1341 if (Alive.count(N)) return true;
1343 // Otherwise, we don't think the node is alive yet, check for infinite
1345 if (Visited.count(N)) return false; // Found a cycle
1346 Visited.insert(N); // No recursion, insert into Visited...
1348 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
1349 if (CanReachAliveNodes(N->getLink(i).getNode(), Alive, Visited,
1351 N->markReachableNodes(Alive);
1357 // CallSiteUsesAliveArgs - Return true if the specified call site can reach any
1360 static bool CallSiteUsesAliveArgs(DSCallSite &CS, hash_set<DSNode*> &Alive,
1361 hash_set<DSNode*> &Visited,
1362 bool IgnoreGlobals) {
1363 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited,
1366 if (CS.isIndirectCall() &&
1367 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited, IgnoreGlobals))
1369 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
1370 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited,
1376 // removeDeadNodes - Use a more powerful reachability analysis to eliminate
1377 // subgraphs that are unreachable. This often occurs because the data
1378 // structure doesn't "escape" into it's caller, and thus should be eliminated
1379 // from the caller's graph entirely. This is only appropriate to use when
1382 void DSGraph::removeDeadNodes(unsigned Flags) {
1383 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
1385 // Reduce the amount of work we have to do... remove dummy nodes left over by
1387 removeTriviallyDeadNodes();
1389 // FIXME: Merge non-trivially identical call nodes...
1391 // Alive - a set that holds all nodes found to be reachable/alive.
1392 hash_set<DSNode*> Alive;
1393 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
1395 // Mark all nodes reachable by (non-global) scalar nodes as alive...
1396 for (ScalarMapTy::iterator I = ScalarMap.begin(), E = ScalarMap.end(); I !=E;)
1397 if (isa<GlobalValue>(I->first)) { // Keep track of global nodes
1398 assert(I->second.getNode() && "Null global node?");
1399 assert(I->second.getNode()->isGlobalNode() && "Should be a global node!");
1400 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
1403 // Check to see if this is a worthless node generated for non-pointer
1404 // values, such as integers. Consider an addition of long types: A+B.
1405 // Assuming we can track all uses of the value in this context, and it is
1406 // NOT used as a pointer, we can delete the node. We will be able to
1407 // detect this situation if the node pointed to ONLY has Unknown bit set
1408 // in the node. In this case, the node is not incomplete, does not point
1409 // to any other nodes (no mod/ref bits set), and is therefore
1410 // uninteresting for data structure analysis. If we run across one of
1411 // these, prune the scalar pointing to it.
1413 DSNode *N = I->second.getNode();
1414 if (N->getNodeFlags() == DSNode::UnknownNode && !isa<Argument>(I->first)){
1415 ScalarMap.erase(I++);
1417 I->second.getNode()->markReachableNodes(Alive);
1422 // The return value is alive as well...
1423 for (ReturnNodesTy::iterator I = ReturnNodes.begin(), E = ReturnNodes.end();
1425 I->second.getNode()->markReachableNodes(Alive);
1427 // Mark any nodes reachable by primary calls as alive...
1428 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1429 FunctionCalls[i].markReachableNodes(Alive);
1431 // Copy and merge all information about globals to the GlobalsGraph
1432 // if this is not a final pass (where unreachable globals are removed)
1433 NodeMapTy GlobalNodeMap;
1434 hash_set<const DSNode*> GlobalNodeSet;
1436 for (std::vector<std::pair<Value*, DSNode*> >::const_iterator
1437 I = GlobalNodes.begin(), E = GlobalNodes.end(); I != E; ++I)
1438 GlobalNodeSet.insert(I->second); // put global nodes into a set
1440 // Now find globals and aux call nodes that are already live or reach a live
1441 // value (which makes them live in turn), and continue till no more are found.
1444 hash_set<DSNode*> Visited;
1445 std::vector<unsigned char> AuxFCallsAlive(AuxFunctionCalls.size());
1448 // If any global node points to a non-global that is "alive", the global is
1449 // "alive" as well... Remove it from the GlobalNodes list so we only have
1450 // unreachable globals in the list.
1453 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
1454 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
1455 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited,
1456 Flags & DSGraph::RemoveUnreachableGlobals)) {
1457 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to...
1458 GlobalNodes.pop_back(); // erase efficiently
1462 // Mark only unresolvable call nodes for moving to the GlobalsGraph since
1463 // call nodes that get resolved will be difficult to remove from that graph.
1464 // The final unresolved call nodes must be handled specially at the end of
1465 // the BU pass (i.e., in main or other roots of the call graph).
1466 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1467 if (!AuxFCallsAlive[i] &&
1468 (AuxFunctionCalls[i].isIndirectCall()
1469 || CallSiteUsesAliveArgs(AuxFunctionCalls[i], Alive, Visited,
1470 Flags & DSGraph::RemoveUnreachableGlobals))) {
1471 AuxFunctionCalls[i].markReachableNodes(Alive);
1472 AuxFCallsAlive[i] = true;
1477 // Move dead aux function calls to the end of the list
1478 unsigned CurIdx = 0;
1479 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1480 if (AuxFCallsAlive[i])
1481 AuxFunctionCalls[CurIdx++].swap(AuxFunctionCalls[i]);
1483 // Copy and merge all global nodes and dead aux call nodes into the
1484 // GlobalsGraph, and all nodes reachable from those nodes
1486 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
1488 // First, add the dead aux call nodes to the set of root nodes for cloning
1489 // -- return value at this call site, if any
1490 // -- actual arguments passed at this call site
1491 // -- callee node at this call site, if this is an indirect call
1492 for (unsigned i = CurIdx, e = AuxFunctionCalls.size(); i != e; ++i) {
1493 if (const DSNode* RetNode = AuxFunctionCalls[i].getRetVal().getNode())
1494 GlobalNodeSet.insert(RetNode);
1495 for (unsigned j=0, N=AuxFunctionCalls[i].getNumPtrArgs(); j < N; ++j)
1496 if (const DSNode* ArgTarget=AuxFunctionCalls[i].getPtrArg(j).getNode())
1497 GlobalNodeSet.insert(ArgTarget);
1498 if (AuxFunctionCalls[i].isIndirectCall())
1499 GlobalNodeSet.insert(AuxFunctionCalls[i].getCalleeNode());
1502 // There are no "pre-completed" nodes so use any empty map for those.
1503 // Strip all alloca bits since the current function is only for the BU pass.
1504 // Strip all incomplete bits since they are short-lived properties and they
1505 // will be correctly computed when rematerializing nodes into the functions.
1507 NodeMapTy CompletedMap;
1508 GlobalsGraph->cloneReachableSubgraph(*this, GlobalNodeSet,
1509 GlobalNodeMap, CompletedMap,
1510 (DSGraph::StripAllocaBit |
1511 DSGraph::StripIncompleteBit));
1514 // Remove all dead aux function calls...
1515 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
1516 assert(GlobalsGraph && "No globals graph available??");
1518 // Copy the unreachable call nodes to the globals graph, updating
1519 // their target pointers using the GlobalNodeMap
1520 for (unsigned i = CurIdx, e = AuxFunctionCalls.size(); i != e; ++i)
1521 GlobalsGraph->AuxFunctionCalls.push_back(DSCallSite(AuxFunctionCalls[i],
1524 // Crop all the useless ones out...
1525 AuxFunctionCalls.erase(AuxFunctionCalls.begin()+CurIdx,
1526 AuxFunctionCalls.end());
1528 // We are finally done with the GlobalNodeMap so we can clear it and
1529 // then get rid of unused nodes in the GlobalsGraph produced by merging.
1530 GlobalNodeMap.clear();
1531 GlobalsGraph->removeTriviallyDeadNodes();
1533 // At this point, any nodes which are visited, but not alive, are nodes
1534 // which can be removed. Loop over all nodes, eliminating completely
1535 // unreachable nodes.
1537 std::vector<DSNode*> DeadNodes;
1538 DeadNodes.reserve(Nodes.size());
1539 for (unsigned i = 0; i != Nodes.size(); ++i)
1540 if (!Alive.count(Nodes[i])) {
1541 DSNode *N = Nodes[i];
1542 Nodes[i--] = Nodes.back(); // move node to end of vector
1543 Nodes.pop_back(); // Erase node from alive list.
1544 DeadNodes.push_back(N);
1545 N->dropAllReferences();
1547 assert(Nodes[i]->getForwardNode() == 0 && "Alive forwarded node?");
1550 // Remove all unreachable globals from the ScalarMap.
1551 // If flag RemoveUnreachableGlobals is set, GlobalNodes has only dead nodes.
1552 // In either case, the dead nodes will not be in the set Alive.
1553 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i) {
1554 assert(((Flags & DSGraph::RemoveUnreachableGlobals) ||
1555 !Alive.count(GlobalNodes[i].second)) && "huh? non-dead global");
1556 if (!Alive.count(GlobalNodes[i].second))
1557 ScalarMap.erase(GlobalNodes[i].first);
1560 // Delete all dead nodes now since their referrer counts are zero.
1561 for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
1562 delete DeadNodes[i];
1564 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
1567 void DSGraph::AssertGraphOK() const {
1568 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
1569 Nodes[i]->assertOK();
1571 for (ScalarMapTy::const_iterator I = ScalarMap.begin(),
1572 E = ScalarMap.end(); I != E; ++I) {
1573 assert(I->second.getNode() && "Null node in scalarmap!");
1574 AssertNodeInGraph(I->second.getNode());
1575 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
1576 assert(I->second.getNode()->isGlobalNode() &&
1577 "Global points to node, but node isn't global?");
1578 AssertNodeContainsGlobal(I->second.getNode(), GV);
1581 AssertCallNodesInGraph();
1582 AssertAuxCallNodesInGraph();
1585 /// mergeInGlobalsGraph - This method is useful for clients to incorporate the
1586 /// globals graph into the DS, BU or TD graph for a function. This code retains
1587 /// all globals, i.e., does not delete unreachable globals after they are
1590 void DSGraph::mergeInGlobalsGraph() {
1591 NodeMapTy GlobalNodeMap;
1592 ScalarMapTy OldValMap;
1593 ReturnNodesTy OldRetNodes;
1594 cloneInto(*GlobalsGraph, OldValMap, OldRetNodes, GlobalNodeMap,
1595 DSGraph::KeepAllocaBit | DSGraph::DontCloneCallNodes |
1596 DSGraph::DontCloneAuxCallNodes);
1598 // Now merge existing global nodes in the GlobalsGraph with their copies
1599 for (ScalarMapTy::iterator I = ScalarMap.begin(), E = ScalarMap.end();
1601 if (isa<GlobalValue>(I->first)) { // Found a global node
1602 DSNodeHandle &GH = I->second;
1603 DSNodeHandle &GGNodeH = GlobalsGraph->getScalarMap()[I->first];
1604 GH.mergeWith(GlobalNodeMap[GGNodeH.getNode()]);
1607 // Merging leaves behind unused nodes: get rid of them now.
1608 GlobalNodeMap.clear();
1610 OldRetNodes.clear();
1611 removeTriviallyDeadNodes();