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 //===----------------------------------------------------------------------===//
28 // DSNode Implementation
29 //===----------------------------------------------------------------------===//
31 DSNode::DSNode(unsigned NT, const Type *T, DSGraph *G)
32 : NumReferrers(0), Size(0), ParentGraph(G), Ty(Type::VoidTy), NodeType(NT) {
33 // Add the type entry if it is specified...
34 if (T) mergeTypeInfo(T, 0);
35 G->getNodes().push_back(this);
38 // DSNode copy constructor... do not copy over the referrers list!
39 DSNode::DSNode(const DSNode &N, DSGraph *G)
40 : NumReferrers(0), Size(N.Size), ParentGraph(G), Ty(N.Ty),
41 Links(N.Links), Globals(N.Globals), NodeType(N.NodeType) {
42 G->getNodes().push_back(this);
45 void DSNode::assertOK() const {
46 assert((Ty != Type::VoidTy ||
47 Ty == Type::VoidTy && (Size == 0 ||
48 (NodeType & DSNode::Array))) &&
52 /// forwardNode - Mark this node as being obsolete, and all references to it
53 /// should be forwarded to the specified node and offset.
55 void DSNode::forwardNode(DSNode *To, unsigned Offset) {
56 assert(this != To && "Cannot forward a node to itself!");
57 assert(ForwardNH.isNull() && "Already forwarding from this node!");
58 if (To->Size <= 1) Offset = 0;
59 assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
60 "Forwarded offset is wrong!");
61 ForwardNH.setNode(To);
62 ForwardNH.setOffset(Offset);
68 // addGlobal - Add an entry for a global value to the Globals list. This also
69 // marks the node with the 'G' flag if it does not already have it.
71 void DSNode::addGlobal(GlobalValue *GV) {
72 // Keep the list sorted.
73 std::vector<GlobalValue*>::iterator I =
74 std::lower_bound(Globals.begin(), Globals.end(), GV);
76 if (I == Globals.end() || *I != GV) {
77 //assert(GV->getType()->getElementType() == Ty);
78 Globals.insert(I, GV);
79 NodeType |= GlobalNode;
83 /// foldNodeCompletely - If we determine that this node has some funny
84 /// behavior happening to it that we cannot represent, we fold it down to a
85 /// single, completely pessimistic, node. This node is represented as a
86 /// single byte with a single TypeEntry of "void".
88 void DSNode::foldNodeCompletely() {
89 assert(!hasNoReferrers() &&
90 "Why would we collapse a node with no referrers?");
91 if (isNodeCompletelyFolded()) return; // If this node is already folded...
95 // Create the node we are going to forward to...
96 DSNode *DestNode = new DSNode(NodeType|DSNode::Array, 0, ParentGraph);
97 DestNode->Ty = Type::VoidTy;
99 DestNode->Globals.swap(Globals);
101 // Start forwarding to the destination node...
102 forwardNode(DestNode, 0);
105 DestNode->Links.push_back(Links[0]);
106 DSNodeHandle NH(DestNode);
108 // If we have links, merge all of our outgoing links together...
109 for (unsigned i = Links.size()-1; i != 0; --i)
110 NH.getNode()->Links[0].mergeWith(Links[i]);
113 DestNode->Links.resize(1);
117 /// isNodeCompletelyFolded - Return true if this node has been completely
118 /// folded down to something that can never be expanded, effectively losing
119 /// all of the field sensitivity that may be present in the node.
121 bool DSNode::isNodeCompletelyFolded() const {
122 return getSize() == 1 && Ty == Type::VoidTy && isArray();
126 /// mergeTypeInfo - This method merges the specified type into the current node
127 /// at the specified offset. This may update the current node's type record if
128 /// this gives more information to the node, it may do nothing to the node if
129 /// this information is already known, or it may merge the node completely (and
130 /// return true) if the information is incompatible with what is already known.
132 /// This method returns true if the node is completely folded, otherwise false.
134 bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset) {
135 // Check to make sure the Size member is up-to-date. Size can be one of the
137 // Size = 0, Ty = Void: Nothing is known about this node.
138 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
139 // Size = 1, Ty = Void, Array = 1: The node is collapsed
140 // Otherwise, sizeof(Ty) = Size
142 assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
143 (Size == 0 && !Ty->isSized() && !isArray()) ||
144 (Size == 1 && Ty == Type::VoidTy && isArray()) ||
145 (Size == 0 && !Ty->isSized() && !isArray()) ||
146 (TD.getTypeSize(Ty) == Size)) &&
147 "Size member of DSNode doesn't match the type structure!");
148 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
150 if (Offset == 0 && NewTy == Ty)
151 return false; // This should be a common case, handle it efficiently
153 // Return true immediately if the node is completely folded.
154 if (isNodeCompletelyFolded()) return true;
156 // If this is an array type, eliminate the outside arrays because they won't
157 // be used anyway. This greatly reduces the size of large static arrays used
158 // as global variables, for example.
160 bool WillBeArray = false;
161 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
162 // FIXME: we might want to keep small arrays, but must be careful about
163 // things like: [2 x [10000 x int*]]
164 NewTy = AT->getElementType();
168 // Figure out how big the new type we're merging in is...
169 unsigned NewTySize = NewTy->isSized() ? TD.getTypeSize(NewTy) : 0;
171 // Otherwise check to see if we can fold this type into the current node. If
172 // we can't, we fold the node completely, if we can, we potentially update our
175 if (Ty == Type::VoidTy) {
176 // If this is the first type that this node has seen, just accept it without
178 assert(Offset == 0 && "Cannot have an offset into a void node!");
179 assert(!isArray() && "This shouldn't happen!");
182 if (WillBeArray) NodeType |= Array;
185 // Calculate the number of outgoing links from this node.
186 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
190 // Handle node expansion case here...
191 if (Offset+NewTySize > Size) {
192 // It is illegal to grow this node if we have treated it as an array of
195 foldNodeCompletely();
199 if (Offset) { // We could handle this case, but we don't for now...
200 DEBUG(std::cerr << "UNIMP: Trying to merge a growth type into "
201 << "offset != 0: Collapsing!\n");
202 foldNodeCompletely();
206 // Okay, the situation is nice and simple, we are trying to merge a type in
207 // at offset 0 that is bigger than our current type. Implement this by
208 // switching to the new type and then merge in the smaller one, which should
209 // hit the other code path here. If the other code path decides it's not
210 // ok, it will collapse the node as appropriate.
212 const Type *OldTy = Ty;
215 if (WillBeArray) NodeType |= Array;
218 // Must grow links to be the appropriate size...
219 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
221 // Merge in the old type now... which is guaranteed to be smaller than the
223 return mergeTypeInfo(OldTy, 0);
226 assert(Offset <= Size &&
227 "Cannot merge something into a part of our type that doesn't exist!");
229 // Find the section of Ty that NewTy overlaps with... first we find the
230 // type that starts at offset Offset.
233 const Type *SubType = Ty;
235 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
237 switch (SubType->getPrimitiveID()) {
238 case Type::StructTyID: {
239 const StructType *STy = cast<StructType>(SubType);
240 const StructLayout &SL = *TD.getStructLayout(STy);
242 unsigned i = 0, e = SL.MemberOffsets.size();
243 for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
246 // The offset we are looking for must be in the i'th element...
247 SubType = STy->getElementTypes()[i];
248 O += SL.MemberOffsets[i];
251 case Type::ArrayTyID: {
252 SubType = cast<ArrayType>(SubType)->getElementType();
253 unsigned ElSize = TD.getTypeSize(SubType);
254 unsigned Remainder = (Offset-O) % ElSize;
255 O = Offset-Remainder;
259 foldNodeCompletely();
264 assert(O == Offset && "Could not achieve the correct offset!");
266 // If we found our type exactly, early exit
267 if (SubType == NewTy) return false;
269 // Okay, so we found the leader type at the offset requested. Search the list
270 // of types that starts at this offset. If SubType is currently an array or
271 // structure, the type desired may actually be the first element of the
274 unsigned SubTypeSize = SubType->isSized() ? TD.getTypeSize(SubType) : 0;
275 unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
276 while (SubType != NewTy) {
277 const Type *NextSubType = 0;
278 unsigned NextSubTypeSize = 0;
279 unsigned NextPadSize = 0;
280 switch (SubType->getPrimitiveID()) {
281 case Type::StructTyID: {
282 const StructType *STy = cast<StructType>(SubType);
283 const StructLayout &SL = *TD.getStructLayout(STy);
284 if (SL.MemberOffsets.size() > 1)
285 NextPadSize = SL.MemberOffsets[1];
287 NextPadSize = SubTypeSize;
288 NextSubType = STy->getElementTypes()[0];
289 NextSubTypeSize = TD.getTypeSize(NextSubType);
292 case Type::ArrayTyID:
293 NextSubType = cast<ArrayType>(SubType)->getElementType();
294 NextSubTypeSize = TD.getTypeSize(NextSubType);
295 NextPadSize = NextSubTypeSize;
301 if (NextSubType == 0)
302 break; // In the default case, break out of the loop
304 if (NextPadSize < NewTySize)
305 break; // Don't allow shrinking to a smaller type than NewTySize
306 SubType = NextSubType;
307 SubTypeSize = NextSubTypeSize;
308 PadSize = NextPadSize;
311 // If we found the type exactly, return it...
312 if (SubType == NewTy)
315 // Check to see if we have a compatible, but different type...
316 if (NewTySize == SubTypeSize) {
317 // Check to see if this type is obviously convertable... int -> uint f.e.
318 if (NewTy->isLosslesslyConvertableTo(SubType))
321 // Check to see if we have a pointer & integer mismatch going on here,
322 // loading a pointer as a long, for example.
324 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
325 NewTy->isInteger() && isa<PointerType>(SubType))
327 } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
328 // We are accessing the field, plus some structure padding. Ignore the
329 // structure padding.
334 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: " << Ty
335 << "\n due to:" << NewTy << " @ " << Offset << "!\n"
336 << "SubType: " << SubType << "\n\n");
338 foldNodeCompletely();
344 // addEdgeTo - Add an edge from the current node to the specified node. This
345 // can cause merging of nodes in the graph.
347 void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
348 if (NH.getNode() == 0) return; // Nothing to do
350 DSNodeHandle &ExistingEdge = getLink(Offset);
351 if (ExistingEdge.getNode()) {
352 // Merge the two nodes...
353 ExistingEdge.mergeWith(NH);
354 } else { // No merging to perform...
355 setLink(Offset, NH); // Just force a link in there...
360 // MergeSortedVectors - Efficiently merge a vector into another vector where
361 // duplicates are not allowed and both are sorted. This assumes that 'T's are
362 // efficiently copyable and have sane comparison semantics.
364 static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
365 const std::vector<GlobalValue*> &Src) {
366 // By far, the most common cases will be the simple ones. In these cases,
367 // avoid having to allocate a temporary vector...
369 if (Src.empty()) { // Nothing to merge in...
371 } else if (Dest.empty()) { // Just copy the result in...
373 } else if (Src.size() == 1) { // Insert a single element...
374 const GlobalValue *V = Src[0];
375 std::vector<GlobalValue*>::iterator I =
376 std::lower_bound(Dest.begin(), Dest.end(), V);
377 if (I == Dest.end() || *I != Src[0]) // If not already contained...
378 Dest.insert(I, Src[0]);
379 } else if (Dest.size() == 1) {
380 GlobalValue *Tmp = Dest[0]; // Save value in temporary...
381 Dest = Src; // Copy over list...
382 std::vector<GlobalValue*>::iterator I =
383 std::lower_bound(Dest.begin(), Dest.end(), Tmp);
384 if (I == Dest.end() || *I != Tmp) // If not already contained...
388 // Make a copy to the side of Dest...
389 std::vector<GlobalValue*> Old(Dest);
391 // Make space for all of the type entries now...
392 Dest.resize(Dest.size()+Src.size());
394 // Merge the two sorted ranges together... into Dest.
395 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
397 // Now erase any duplicate entries that may have accumulated into the
398 // vectors (because they were in both of the input sets)
399 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
404 // MergeNodes() - Helper function for DSNode::mergeWith().
405 // This function does the hard work of merging two nodes, CurNodeH
406 // and NH after filtering out trivial cases and making sure that
407 // CurNodeH.offset >= NH.offset.
410 // Since merging may cause either node to go away, we must always
411 // use the node-handles to refer to the nodes. These node handles are
412 // automatically updated during merging, so will always provide access
413 // to the correct node after a merge.
415 void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
416 assert(CurNodeH.getOffset() >= NH.getOffset() &&
417 "This should have been enforced in the caller.");
419 // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
420 // respect to NH.Offset) is now zero. NOffset is the distance from the base
421 // of our object that N starts from.
423 unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
424 unsigned NSize = NH.getNode()->getSize();
426 // Merge the type entries of the two nodes together...
427 if (NH.getNode()->Ty != Type::VoidTy)
428 CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
429 assert((CurNodeH.getNode()->NodeType & DSNode::DEAD) == 0);
431 // If we are merging a node with a completely folded node, then both nodes are
432 // now completely folded.
434 if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
435 if (!NH.getNode()->isNodeCompletelyFolded()) {
436 NH.getNode()->foldNodeCompletely();
437 assert(NH.getNode() && NH.getOffset() == 0 &&
438 "folding did not make offset 0?");
439 NOffset = NH.getOffset();
440 NSize = NH.getNode()->getSize();
441 assert(NOffset == 0 && NSize == 1);
443 } else if (NH.getNode()->isNodeCompletelyFolded()) {
444 CurNodeH.getNode()->foldNodeCompletely();
445 assert(CurNodeH.getNode() && CurNodeH.getOffset() == 0 &&
446 "folding did not make offset 0?");
447 NOffset = NH.getOffset();
448 NSize = NH.getNode()->getSize();
449 assert(NOffset == 0 && NSize == 1);
452 DSNode *N = NH.getNode();
453 if (CurNodeH.getNode() == N || N == 0) return;
454 assert((CurNodeH.getNode()->NodeType & DSNode::DEAD) == 0);
456 // Start forwarding to the new node!
457 CurNodeH.getNode()->NodeType |= N->NodeType;
458 N->forwardNode(CurNodeH.getNode(), NOffset);
459 assert((CurNodeH.getNode()->NodeType & DSNode::DEAD) == 0);
461 // Make all of the outgoing links of N now be outgoing links of CurNodeH.
463 for (unsigned i = 0; i < N->getNumLinks(); ++i) {
464 DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
465 if (Link.getNode()) {
466 // Compute the offset into the current node at which to
467 // merge this link. In the common case, this is a linear
468 // relation to the offset in the original node (with
469 // wrapping), but if the current node gets collapsed due to
470 // recursive merging, we must make sure to merge in all remaining
471 // links at offset zero.
472 unsigned MergeOffset = 0;
473 DSNode *CN = CurNodeH.getNode();
475 MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
476 CN->addEdgeTo(MergeOffset, Link);
480 // Now that there are no outgoing edges, all of the Links are dead.
483 // Merge the globals list...
484 if (!N->Globals.empty()) {
485 MergeSortedVectors(CurNodeH.getNode()->Globals, N->Globals);
487 // Delete the globals from the old node...
488 std::vector<GlobalValue*>().swap(N->Globals);
493 // mergeWith - Merge this node and the specified node, moving all links to and
494 // from the argument node into the current node, deleting the node argument.
495 // Offset indicates what offset the specified node is to be merged into the
498 // The specified node may be a null pointer (in which case, nothing happens).
500 void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
501 DSNode *N = NH.getNode();
502 if (N == 0 || (N == this && NH.getOffset() == Offset))
505 assert((N->NodeType & DSNode::DEAD) == 0);
506 assert((NodeType & DSNode::DEAD) == 0);
507 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
510 // We cannot merge two pieces of the same node together, collapse the node
512 DEBUG(std::cerr << "Attempting to merge two chunks of"
513 << " the same node together!\n");
514 foldNodeCompletely();
518 // If both nodes are not at offset 0, make sure that we are merging the node
519 // at an later offset into the node with the zero offset.
521 if (Offset < NH.getOffset()) {
522 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
524 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
525 // If the offsets are the same, merge the smaller node into the bigger node
526 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
530 // Ok, now we can merge the two nodes. Use a static helper that works with
531 // two node handles, since "this" may get merged away at intermediate steps.
532 DSNodeHandle CurNodeH(this, Offset);
533 DSNodeHandle NHCopy(NH);
534 DSNode::MergeNodes(CurNodeH, NHCopy);
537 //===----------------------------------------------------------------------===//
538 // DSCallSite Implementation
539 //===----------------------------------------------------------------------===//
541 // Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
542 Function &DSCallSite::getCaller() const {
543 return *Inst->getParent()->getParent();
547 //===----------------------------------------------------------------------===//
548 // DSGraph Implementation
549 //===----------------------------------------------------------------------===//
551 DSGraph::DSGraph(const DSGraph &G) : Func(G.Func), GlobalsGraph(0) {
552 PrintAuxCalls = false;
553 hash_map<const DSNode*, DSNodeHandle> NodeMap;
554 RetNode = cloneInto(G, ScalarMap, NodeMap);
557 DSGraph::DSGraph(const DSGraph &G,
558 hash_map<const DSNode*, DSNodeHandle> &NodeMap)
559 : Func(G.Func), GlobalsGraph(0) {
560 PrintAuxCalls = false;
561 RetNode = cloneInto(G, ScalarMap, NodeMap);
564 DSGraph::~DSGraph() {
565 FunctionCalls.clear();
566 AuxFunctionCalls.clear();
570 // Drop all intra-node references, so that assertions don't fail...
571 std::for_each(Nodes.begin(), Nodes.end(),
572 std::mem_fun(&DSNode::dropAllReferences));
574 // Delete all of the nodes themselves...
575 std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
578 // dump - Allow inspection of graph in a debugger.
579 void DSGraph::dump() const { print(std::cerr); }
582 /// remapLinks - Change all of the Links in the current node according to the
583 /// specified mapping.
585 void DSNode::remapLinks(hash_map<const DSNode*, DSNodeHandle> &OldNodeMap) {
586 for (unsigned i = 0, e = Links.size(); i != e; ++i) {
587 DSNodeHandle &H = OldNodeMap[Links[i].getNode()];
588 Links[i].setNode(H.getNode());
589 Links[i].setOffset(Links[i].getOffset()+H.getOffset());
594 // cloneInto - Clone the specified DSGraph into the current graph, returning the
595 // Return node of the graph. The translated ScalarMap for the old function is
596 // filled into the OldValMap member. If StripAllocas is set to true, Alloca
597 // markers are removed from the graph, as the graph is being cloned into a
598 // calling function's graph.
600 DSNodeHandle DSGraph::cloneInto(const DSGraph &G,
601 hash_map<Value*, DSNodeHandle> &OldValMap,
602 hash_map<const DSNode*, DSNodeHandle> &OldNodeMap,
603 unsigned CloneFlags) {
604 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
605 assert(&G != this && "Cannot clone graph into itself!");
607 unsigned FN = Nodes.size(); // First new node...
609 // Duplicate all of the nodes, populating the node map...
610 Nodes.reserve(FN+G.Nodes.size());
612 // Remove alloca or mod/ref bits as specified...
613 unsigned clearBits = (CloneFlags & StripAllocaBit ? DSNode::AllocaNode : 0)
614 | (CloneFlags & StripModRefBits ? (DSNode::Modified | DSNode::Read) : 0);
615 clearBits |= DSNode::DEAD; // Clear dead flag...
616 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
617 DSNode *Old = G.Nodes[i];
618 DSNode *New = new DSNode(*Old, this);
619 New->NodeType &= ~clearBits;
620 OldNodeMap[Old] = New;
624 Timer::addPeakMemoryMeasurement();
627 // Rewrite the links in the new nodes to point into the current graph now.
628 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
629 Nodes[i]->remapLinks(OldNodeMap);
631 // Copy the scalar map... merging all of the global nodes...
632 for (hash_map<Value*, DSNodeHandle>::const_iterator I = G.ScalarMap.begin(),
633 E = G.ScalarMap.end(); I != E; ++I) {
634 DSNodeHandle &H = OldValMap[I->first];
635 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
636 H.setOffset(I->second.getOffset()+MappedNode.getOffset());
637 H.setNode(MappedNode.getNode());
639 if (isa<GlobalValue>(I->first)) { // Is this a global?
640 hash_map<Value*, DSNodeHandle>::iterator GVI = ScalarMap.find(I->first);
641 if (GVI != ScalarMap.end()) // Is the global value in this fn already?
642 GVI->second.mergeWith(H);
644 ScalarMap[I->first] = H; // Add global pointer to this graph
648 if (!(CloneFlags & DontCloneCallNodes)) {
649 // Copy the function calls list...
650 unsigned FC = FunctionCalls.size(); // FirstCall
651 FunctionCalls.reserve(FC+G.FunctionCalls.size());
652 for (unsigned i = 0, ei = G.FunctionCalls.size(); i != ei; ++i)
653 FunctionCalls.push_back(DSCallSite(G.FunctionCalls[i], OldNodeMap));
656 if (!(CloneFlags & DontCloneAuxCallNodes)) {
657 // Copy the auxillary function calls list...
658 unsigned FC = AuxFunctionCalls.size(); // FirstCall
659 AuxFunctionCalls.reserve(FC+G.AuxFunctionCalls.size());
660 for (unsigned i = 0, ei = G.AuxFunctionCalls.size(); i != ei; ++i)
661 AuxFunctionCalls.push_back(DSCallSite(G.AuxFunctionCalls[i], OldNodeMap));
664 // Return the returned node pointer...
665 DSNodeHandle &MappedRet = OldNodeMap[G.RetNode.getNode()];
666 return DSNodeHandle(MappedRet.getNode(),
667 MappedRet.getOffset()+G.RetNode.getOffset());
670 /// mergeInGraph - The method is used for merging graphs together. If the
671 /// argument graph is not *this, it makes a clone of the specified graph, then
672 /// merges the nodes specified in the call site with the formal arguments in the
675 void DSGraph::mergeInGraph(DSCallSite &CS, const DSGraph &Graph,
676 unsigned CloneFlags) {
677 hash_map<Value*, DSNodeHandle> OldValMap;
679 hash_map<Value*, DSNodeHandle> *ScalarMap = &OldValMap;
681 // If this is not a recursive call, clone the graph into this graph...
682 if (&Graph != this) {
683 // Clone the callee's graph into the current graph, keeping
684 // track of where scalars in the old graph _used_ to point,
685 // and of the new nodes matching nodes of the old graph.
686 hash_map<const DSNode*, DSNodeHandle> OldNodeMap;
688 // The clone call may invalidate any of the vectors in the data
689 // structure graph. Strip locals and don't copy the list of callers
690 RetVal = cloneInto(Graph, OldValMap, OldNodeMap, CloneFlags);
691 ScalarMap = &OldValMap;
693 RetVal = getRetNode();
694 ScalarMap = &getScalarMap();
697 // Merge the return value with the return value of the context...
698 RetVal.mergeWith(CS.getRetVal());
700 // Resolve all of the function arguments...
701 Function &F = Graph.getFunction();
702 Function::aiterator AI = F.abegin();
704 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
705 // Advance the argument iterator to the first pointer argument...
706 while (AI != F.aend() && !isPointerType(AI->getType())) {
710 std::cerr << "Bad call to Function: " << F.getName() << "\n";
713 if (AI == F.aend()) break;
715 // Add the link from the argument scalar to the provided value
716 assert(ScalarMap->count(AI) && "Argument not in scalar map?");
717 DSNodeHandle &NH = (*ScalarMap)[AI];
718 assert(NH.getNode() && "Pointer argument without scalarmap entry?");
719 NH.mergeWith(CS.getPtrArg(i));
724 // markIncompleteNodes - Mark the specified node as having contents that are not
725 // known with the current analysis we have performed. Because a node makes all
726 // of the nodes it can reach imcomplete if the node itself is incomplete, we
727 // must recursively traverse the data structure graph, marking all reachable
728 // nodes as incomplete.
730 static void markIncompleteNode(DSNode *N) {
731 // Stop recursion if no node, or if node already marked...
732 if (N == 0 || (N->NodeType & DSNode::Incomplete)) return;
734 // Actually mark the node
735 N->NodeType |= DSNode::Incomplete;
737 // Recusively process children...
738 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
739 if (DSNode *DSN = N->getLink(i).getNode())
740 markIncompleteNode(DSN);
743 static void markIncomplete(DSCallSite &Call) {
744 // Then the return value is certainly incomplete!
745 markIncompleteNode(Call.getRetVal().getNode());
747 // All objects pointed to by function arguments are incomplete!
748 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
749 markIncompleteNode(Call.getPtrArg(i).getNode());
752 // markIncompleteNodes - Traverse the graph, identifying nodes that may be
753 // modified by other functions that have not been resolved yet. This marks
754 // nodes that are reachable through three sources of "unknownness":
756 // Global Variables, Function Calls, and Incoming Arguments
758 // For any node that may have unknown components (because something outside the
759 // scope of current analysis may have modified it), the 'Incomplete' flag is
760 // added to the NodeType.
762 void DSGraph::markIncompleteNodes(unsigned Flags) {
763 // Mark any incoming arguments as incomplete...
764 if ((Flags & DSGraph::MarkFormalArgs) && Func && Func->getName() != "main")
765 for (Function::aiterator I = Func->abegin(), E = Func->aend(); I != E; ++I)
766 if (isPointerType(I->getType()) && ScalarMap.find(I) != ScalarMap.end())
767 markIncompleteNode(ScalarMap[I].getNode());
769 // Mark stuff passed into functions calls as being incomplete...
770 if (!shouldPrintAuxCalls())
771 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
772 markIncomplete(FunctionCalls[i]);
774 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
775 markIncomplete(AuxFunctionCalls[i]);
778 // Mark all global nodes as incomplete...
779 if ((Flags & DSGraph::IgnoreGlobals) == 0)
780 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
781 if (Nodes[i]->NodeType & DSNode::GlobalNode)
782 markIncompleteNode(Nodes[i]);
785 static inline void killIfUselessEdge(DSNodeHandle &Edge) {
786 if (DSNode *N = Edge.getNode()) // Is there an edge?
787 if (N->getNumReferrers() == 1) // Does it point to a lonely node?
788 if ((N->NodeType & ~DSNode::Incomplete) == 0 && // No interesting info?
789 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
790 Edge.setNode(0); // Kill the edge!
793 static inline bool nodeContainsExternalFunction(const DSNode *N) {
794 const std::vector<GlobalValue*> &Globals = N->getGlobals();
795 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
796 if (Globals[i]->isExternal())
801 static void removeIdenticalCalls(std::vector<DSCallSite> &Calls,
802 const std::string &where) {
803 // Remove trivially identical function calls
804 unsigned NumFns = Calls.size();
805 std::sort(Calls.begin(), Calls.end()); // Sort by callee as primary key!
807 // Scan the call list cleaning it up as necessary...
808 DSNode *LastCalleeNode = 0;
809 Function *LastCalleeFunc = 0;
810 unsigned NumDuplicateCalls = 0;
811 bool LastCalleeContainsExternalFunction = false;
812 for (unsigned i = 0; i != Calls.size(); ++i) {
813 DSCallSite &CS = Calls[i];
815 // If the Callee is a useless edge, this must be an unreachable call site,
817 if (CS.isIndirectCall() && CS.getCalleeNode()->getNumReferrers() == 1 &&
818 CS.getCalleeNode()->NodeType == 0) { // No useful info?
819 std::cerr << "WARNING: Useless call site found??\n";
820 CS.swap(Calls.back());
824 // If the return value or any arguments point to a void node with no
825 // information at all in it, and the call node is the only node to point
826 // to it, remove the edge to the node (killing the node).
828 killIfUselessEdge(CS.getRetVal());
829 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
830 killIfUselessEdge(CS.getPtrArg(a));
832 // If this call site calls the same function as the last call site, and if
833 // the function pointer contains an external function, this node will
834 // never be resolved. Merge the arguments of the call node because no
835 // information will be lost.
837 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
838 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
840 if (NumDuplicateCalls == 1) {
842 LastCalleeContainsExternalFunction =
843 nodeContainsExternalFunction(LastCalleeNode);
845 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
848 if (LastCalleeContainsExternalFunction ||
849 // This should be more than enough context sensitivity!
850 // FIXME: Evaluate how many times this is tripped!
851 NumDuplicateCalls > 20) {
852 DSCallSite &OCS = Calls[i-1];
855 // The node will now be eliminated as a duplicate!
856 if (CS.getNumPtrArgs() < OCS.getNumPtrArgs())
858 else if (CS.getNumPtrArgs() > OCS.getNumPtrArgs())
862 if (CS.isDirectCall()) {
863 LastCalleeFunc = CS.getCalleeFunc();
866 LastCalleeNode = CS.getCalleeNode();
869 NumDuplicateCalls = 0;
874 Calls.erase(std::unique(Calls.begin(), Calls.end()),
877 // Track the number of call nodes merged away...
878 NumCallNodesMerged += NumFns-Calls.size();
880 DEBUG(if (NumFns != Calls.size())
881 std::cerr << "Merged " << (NumFns-Calls.size())
882 << " call nodes in " << where << "\n";);
886 // removeTriviallyDeadNodes - After the graph has been constructed, this method
887 // removes all unreachable nodes that are created because they got merged with
888 // other nodes in the graph. These nodes will all be trivially unreachable, so
889 // we don't have to perform any non-trivial analysis here.
891 void DSGraph::removeTriviallyDeadNodes() {
892 removeIdenticalCalls(FunctionCalls, Func ? Func->getName() : "");
893 removeIdenticalCalls(AuxFunctionCalls, Func ? Func->getName() : "");
895 for (unsigned i = 0; i != Nodes.size(); ++i) {
896 DSNode *Node = Nodes[i];
897 if (!(Node->NodeType & ~(DSNode::Composition | DSNode::Array |
899 // This is a useless node if it has no mod/ref info (checked above),
900 // outgoing edges (which it cannot, as it is not modified in this
901 // context), and it has no incoming edges. If it is a global node it may
902 // have all of these properties and still have incoming edges, due to the
903 // scalar map, so we check those now.
905 if (Node->getNumReferrers() == Node->getGlobals().size()) {
906 std::vector<GlobalValue*> &Globals = Node->getGlobals();
908 // Loop through and make sure all of the globals are referring directly
910 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
911 DSNode *N = ScalarMap.find(Globals[j])->second.getNode();
912 assert(N == Node && "ScalarMap doesn't match globals list!");
915 // Make sure numreferrers still agrees, if so, the node is truely dead.
916 if (Node->getNumReferrers() == Globals.size()) {
917 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
918 ScalarMap.erase(Globals[j]);
921 assert(Node->hasNoReferrers() && "Shouldn't have refs now!");
923 Node->NodeType = DSNode::DEAD;
928 if ((Node->NodeType & ~DSNode::DEAD) == 0 && Node->hasNoReferrers()) {
929 // This node is dead!
930 delete Node; // Free memory...
931 Nodes[i--] = Nodes.back();
932 Nodes.pop_back(); // Remove from node list...
938 /// markReachableNodes - This method recursively traverses the specified
939 /// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
940 /// to the set, which allows it to only traverse visited nodes once.
942 void DSNode::markReachableNodes(hash_set<DSNode*> &ReachableNodes) {
943 if (this == 0) return;
944 assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
945 if (ReachableNodes.count(this)) return; // Already marked reachable
946 ReachableNodes.insert(this); // Is reachable now
948 for (unsigned i = 0, e = getSize(); i < e; i += DS::PointerSize)
949 getLink(i).getNode()->markReachableNodes(ReachableNodes);
952 void DSCallSite::markReachableNodes(hash_set<DSNode*> &Nodes) {
953 getRetVal().getNode()->markReachableNodes(Nodes);
954 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
956 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
957 getPtrArg(i).getNode()->markReachableNodes(Nodes);
960 // CanReachAliveNodes - Simple graph walker that recursively traverses the graph
961 // looking for a node that is marked alive. If an alive node is found, return
962 // true, otherwise return false. If an alive node is reachable, this node is
963 // marked as alive...
965 static bool CanReachAliveNodes(DSNode *N, hash_set<DSNode*> &Alive,
966 hash_set<DSNode*> &Visited) {
967 if (N == 0) return false;
968 assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
970 // If we know that this node is alive, return so!
971 if (Alive.count(N)) return true;
973 // Otherwise, we don't think the node is alive yet, check for infinite
975 if (Visited.count(N)) return false; // Found a cycle
976 Visited.insert(N); // No recursion, insert into Visited...
978 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
979 if (CanReachAliveNodes(N->getLink(i).getNode(), Alive, Visited)) {
980 N->markReachableNodes(Alive);
986 // CallSiteUsesAliveArgs - Return true if the specified call site can reach any
989 static bool CallSiteUsesAliveArgs(DSCallSite &CS, hash_set<DSNode*> &Alive,
990 hash_set<DSNode*> &Visited) {
991 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited))
993 if (CS.isIndirectCall() &&
994 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited))
996 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
997 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited))
1002 // removeDeadNodes - Use a more powerful reachability analysis to eliminate
1003 // subgraphs that are unreachable. This often occurs because the data
1004 // structure doesn't "escape" into it's caller, and thus should be eliminated
1005 // from the caller's graph entirely. This is only appropriate to use when
1008 void DSGraph::removeDeadNodes(unsigned Flags) {
1009 // Reduce the amount of work we have to do... remove dummy nodes left over by
1011 removeTriviallyDeadNodes();
1013 // FIXME: Merge nontrivially identical call nodes...
1015 // Alive - a set that holds all nodes found to be reachable/alive.
1016 hash_set<DSNode*> Alive;
1017 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
1019 // Mark all nodes reachable by (non-global) scalar nodes as alive...
1020 for (hash_map<Value*, DSNodeHandle>::iterator I = ScalarMap.begin(),
1021 E = ScalarMap.end(); I != E; ++I)
1022 if (!isa<GlobalValue>(I->first))
1023 I->second.getNode()->markReachableNodes(Alive);
1024 else { // Keep track of global nodes
1025 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
1026 assert(I->second.getNode() && "Null global node?");
1029 // The return value is alive as well...
1030 RetNode.getNode()->markReachableNodes(Alive);
1032 // Mark any nodes reachable by primary calls as alive...
1033 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1034 FunctionCalls[i].markReachableNodes(Alive);
1037 hash_set<DSNode*> Visited;
1038 std::vector<unsigned char> AuxFCallsAlive(AuxFunctionCalls.size());
1041 // If any global nodes points to a non-global that is "alive", the global is
1042 // "alive" as well... Remove it from the GlobalNodes list so we only have
1043 // unreachable globals in the list.
1046 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
1047 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited)) {
1048 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to erase
1049 GlobalNodes.pop_back(); // Erase efficiently
1053 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1054 if (!AuxFCallsAlive[i] &&
1055 CallSiteUsesAliveArgs(AuxFunctionCalls[i], Alive, Visited)) {
1056 AuxFunctionCalls[i].markReachableNodes(Alive);
1057 AuxFCallsAlive[i] = true;
1062 // Remove all dead aux function calls...
1063 unsigned CurIdx = 0;
1064 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1065 if (AuxFCallsAlive[i])
1066 AuxFunctionCalls[CurIdx++].swap(AuxFunctionCalls[i]);
1067 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
1068 assert(GlobalsGraph && "No globals graph available??");
1069 // Move the unreachable call nodes to the globals graph...
1070 GlobalsGraph->AuxFunctionCalls.insert(GlobalsGraph->AuxFunctionCalls.end(),
1071 AuxFunctionCalls.begin()+CurIdx,
1072 AuxFunctionCalls.end());
1074 // Crop all the useless ones out...
1075 AuxFunctionCalls.erase(AuxFunctionCalls.begin()+CurIdx,
1076 AuxFunctionCalls.end());
1078 // At this point, any nodes which are visited, but not alive, are nodes which
1079 // should be moved to the globals graph. Loop over all nodes, eliminating
1080 // completely unreachable nodes, and moving visited nodes to the globals graph
1082 std::vector<DSNode*> DeadNodes;
1083 DeadNodes.reserve(Nodes.size());
1084 for (unsigned i = 0; i != Nodes.size(); ++i)
1085 if (!Alive.count(Nodes[i])) {
1086 DSNode *N = Nodes[i];
1087 Nodes[i--] = Nodes.back(); // move node to end of vector
1088 Nodes.pop_back(); // Erase node from alive list.
1089 if (!(Flags & DSGraph::RemoveUnreachableGlobals) && // Not in TD pass
1090 Visited.count(N)) { // Visited but not alive?
1091 GlobalsGraph->Nodes.push_back(N); // Move node to globals graph
1092 N->setParentGraph(GlobalsGraph);
1093 } else { // Otherwise, delete the node
1094 assert(((N->NodeType & DSNode::GlobalNode) == 0 ||
1095 (Flags & DSGraph::RemoveUnreachableGlobals))
1096 && "Killing a global?");
1097 //std::cerr << "[" << i+1 << "/" << DeadNodes.size()
1098 // << "] Node is dead: "; N->dump();
1099 DeadNodes.push_back(N);
1100 N->dropAllReferences();
1103 assert(Nodes[i]->getForwardNode() == 0 && "Alive forwarded node?");
1106 // Now that the nodes have either been deleted or moved to the globals graph,
1107 // loop over the scalarmap, updating the entries for globals...
1109 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) { // Not in the TD pass?
1110 // In this array we start the remapping, which can cause merging. Because
1111 // of this, the DSNode pointers in GlobalNodes may be invalidated, so we
1112 // must always go through the ScalarMap (which contains DSNodeHandles [which
1113 // cannot be invalidated by merging]).
1115 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i) {
1116 Value *G = GlobalNodes[i].first;
1117 hash_map<Value*, DSNodeHandle>::iterator I = ScalarMap.find(G);
1118 assert(I != ScalarMap.end() && "Global not in scalar map anymore?");
1119 assert(I->second.getNode() && "Global not pointing to anything?");
1120 assert(!Alive.count(I->second.getNode()) && "Node is alive??");
1121 GlobalsGraph->ScalarMap[G].mergeWith(I->second);
1122 assert(GlobalsGraph->ScalarMap[G].getNode() &&
1123 "Global not pointing to anything?");
1127 // Merging leaves behind silly nodes, we remove them to avoid polluting the
1129 if (!GlobalNodes.empty())
1130 GlobalsGraph->removeTriviallyDeadNodes();
1132 // If we are in the top-down pass, remove all unreachable globals from the
1134 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
1135 ScalarMap.erase(GlobalNodes[i].first);
1138 // Loop over all of the dead nodes now, deleting them since their referrer
1140 for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
1141 delete DeadNodes[i];
1143 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
1146 void DSGraph::AssertGraphOK() const {
1147 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
1148 Nodes[i]->assertOK();
1149 return; // FIXME: remove
1150 for (hash_map<Value*, DSNodeHandle>::const_iterator I = ScalarMap.begin(),
1151 E = ScalarMap.end(); I != E; ++I) {
1152 assert(I->second.getNode() && "Null node in scalarmap!");
1153 AssertNodeInGraph(I->second.getNode());
1154 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
1155 assert((I->second.getNode()->NodeType & DSNode::GlobalNode) &&
1156 "Global points to node, but node isn't global?");
1157 AssertNodeContainsGlobal(I->second.getNode(), GV);
1160 AssertCallNodesInGraph();
1161 AssertAuxCallNodesInGraph();