1 //===- BottomUpClosure.cpp - Compute bottom-up interprocedural closure ----===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the BUDataStructures class, which represents the
11 // Bottom-Up Interprocedural closure of the data structure graph over the
12 // program. This is useful for applications like pool allocation, but **not**
13 // applications like alias analysis.
15 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "bu_dsa"
17 #include "llvm/Analysis/DataStructure/DataStructure.h"
18 #include "llvm/Analysis/DataStructure/DSGraph.h"
19 #include "llvm/Module.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/Timer.h"
29 Statistic<> MaxSCC("budatastructure", "Maximum SCC Size in Call Graph");
30 Statistic<> NumBUInlines("budatastructures", "Number of graphs inlined");
31 Statistic<> NumCallEdges("budatastructures", "Number of 'actual' call edges");
34 AddGlobals("budatastructures-annotate-calls",
35 cl::desc("Annotate call sites with functions as they are resolved"));
37 UpdateGlobals("budatastructures-update-from-globals",
38 cl::desc("Update local graph from global graph when processing function"));
40 RegisterAnalysis<BUDataStructures>
41 X("budatastructure", "Bottom-up Data Structure Analysis");
44 static bool GetAllCallees(const DSCallSite &CS,
45 std::vector<Function*> &Callees);
47 /// BuildGlobalECs - Look at all of the nodes in the globals graph. If any node
48 /// contains multiple globals, DSA will never, ever, be able to tell the globals
49 /// apart. Instead of maintaining this information in all of the graphs
50 /// throughout the entire program, store only a single global (the "leader") in
51 /// the graphs, and build equivalence classes for the rest of the globals.
52 static void BuildGlobalECs(DSGraph &GG, std::set<GlobalValue*> &ECGlobals) {
53 DSScalarMap &SM = GG.getScalarMap();
54 EquivalenceClasses<GlobalValue*> &GlobalECs = SM.getGlobalECs();
55 for (DSGraph::node_iterator I = GG.node_begin(), E = GG.node_end();
57 if (I->getGlobalsList().size() <= 1) continue;
59 // First, build up the equivalence set for this block of globals.
60 const std::vector<GlobalValue*> &GVs = I->getGlobalsList();
61 GlobalValue *First = GVs[0];
62 for (unsigned i = 1, e = GVs.size(); i != e; ++i)
63 GlobalECs.unionSets(First, GVs[i]);
65 // Next, get the leader element.
66 assert(First == GlobalECs.getLeaderValue(First) &&
67 "First did not end up being the leader?");
69 // Next, remove all globals from the scalar map that are not the leader.
70 assert(GVs[0] == First && "First had to be at the front!");
71 for (unsigned i = 1, e = GVs.size(); i != e; ++i) {
72 ECGlobals.insert(GVs[i]);
73 SM.erase(SM.find(GVs[i]));
76 // Finally, change the global node to only contain the leader.
81 DEBUG(GG.AssertGraphOK());
84 /// EliminateUsesOfECGlobals - Once we have determined that some globals are in
85 /// really just equivalent to some other globals, remove the globals from the
86 /// specified DSGraph (if present), and merge any nodes with their leader nodes.
87 static void EliminateUsesOfECGlobals(DSGraph &G,
88 const std::set<GlobalValue*> &ECGlobals) {
89 DSScalarMap &SM = G.getScalarMap();
90 EquivalenceClasses<GlobalValue*> &GlobalECs = SM.getGlobalECs();
92 bool MadeChange = false;
93 for (DSScalarMap::global_iterator GI = SM.global_begin(), E = SM.global_end();
95 GlobalValue *GV = *GI++;
96 if (!ECGlobals.count(GV)) continue;
98 const DSNodeHandle &GVNH = SM[GV];
99 assert(!GVNH.isNull() && "Global has null NH!?");
101 // Okay, this global is in some equivalence class. Start by finding the
102 // leader of the class.
103 GlobalValue *Leader = GlobalECs.getLeaderValue(GV);
105 // If the leader isn't already in the graph, insert it into the node
106 // corresponding to GV.
107 if (!SM.global_count(Leader)) {
108 GVNH.getNode()->addGlobal(Leader);
111 // Otherwise, the leader is in the graph, make sure the nodes are the
112 // merged in the specified graph.
113 const DSNodeHandle &LNH = SM[Leader];
114 if (LNH.getNode() != GVNH.getNode())
118 // Next step, remove the global from the DSNode.
119 GVNH.getNode()->removeGlobal(GV);
121 // Finally, remove the global from the ScalarMap.
126 DEBUG(if(MadeChange) G.AssertGraphOK());
129 static void AddGlobalToNode(BUDataStructures* B, DSCallSite D, Function* F) {
132 if(D.isIndirectCall()) {
133 DSGraph* GI = &B->getDSGraph(D.getCaller());
134 DSNodeHandle& NHF = GI->getNodeForValue(F);
135 DSCallSite DL = GI->getDSCallSiteForCallSite(D.getCallSite());
136 if (DL.getCalleeNode() != NHF.getNode() || NHF.isNull()) {
138 DSNode *N = new DSNode(F->getType()->getElementType(), GI); // Create the node
141 DEBUG(std::cerr << "Adding " << F->getName() << " to a call node in "
142 << D.getCaller().getName() << "\n");
144 DL.getCalleeNode()->mergeWith(NHF, 0);
149 // run - Calculate the bottom up data structure graphs for each function in the
152 bool BUDataStructures::runOnModule(Module &M) {
153 LocalDataStructures &LocalDSA = getAnalysis<LocalDataStructures>();
154 GlobalECs = LocalDSA.getGlobalECs();
156 GlobalsGraph = new DSGraph(LocalDSA.getGlobalsGraph(), GlobalECs);
157 GlobalsGraph->setPrintAuxCalls();
159 IndCallGraphMap = new std::map<std::vector<Function*>,
160 std::pair<DSGraph*, std::vector<DSNodeHandle> > >();
162 std::vector<Function*> Stack;
163 hash_map<Function*, unsigned> ValMap;
166 Function *MainFunc = M.getMainFunction();
169 calculateGraphs(MainFunc, Stack, NextID, ValMap);
171 // Calculate the graphs for any functions that are unreachable from main...
172 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
173 if (!I->isExternal() && !DSInfo.count(I)) {
176 std::cerr << "*** BU: Function unreachable from main: "
177 << I->getName() << "\n";
179 calculateGraphs(I, Stack, NextID, ValMap); // Calculate all graphs.
182 // If we computed any temporary indcallgraphs, free them now.
183 for (std::map<std::vector<Function*>,
184 std::pair<DSGraph*, std::vector<DSNodeHandle> > >::iterator I =
185 IndCallGraphMap->begin(), E = IndCallGraphMap->end(); I != E; ++I) {
186 I->second.second.clear(); // Drop arg refs into the graph.
187 delete I->second.first;
189 delete IndCallGraphMap;
191 // At the end of the bottom-up pass, the globals graph becomes complete.
192 // FIXME: This is not the right way to do this, but it is sorta better than
193 // nothing! In particular, externally visible globals and unresolvable call
194 // nodes at the end of the BU phase should make things that they point to
195 // incomplete in the globals graph.
197 GlobalsGraph->removeTriviallyDeadNodes();
198 GlobalsGraph->maskIncompleteMarkers();
200 // Mark external globals incomplete.
201 GlobalsGraph->markIncompleteNodes(DSGraph::IgnoreGlobals);
203 // Grow the equivalence classes for the globals to include anything that we
204 // now know to be aliased.
205 std::set<GlobalValue*> ECGlobals;
206 BuildGlobalECs(*GlobalsGraph, ECGlobals);
207 if (!ECGlobals.empty()) {
208 NamedRegionTimer X("Bottom-UP EC Cleanup");
209 std::cerr << "Eliminating " << ECGlobals.size() << " EC Globals!\n";
210 for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
211 E = DSInfo.end(); I != E; ++I)
212 EliminateUsesOfECGlobals(*I->second, ECGlobals);
215 // Merge the globals variables (not the calls) from the globals graph back
216 // into the main function's graph so that the main function contains all of
217 // the information about global pools and GV usage in the program.
218 if (MainFunc && !MainFunc->isExternal()) {
219 DSGraph &MainGraph = getOrCreateGraph(MainFunc);
220 const DSGraph &GG = *MainGraph.getGlobalsGraph();
221 ReachabilityCloner RC(MainGraph, GG, DSGraph::DontCloneCallNodes |
222 DSGraph::DontCloneAuxCallNodes);
224 // Clone the global nodes into this graph.
225 for (DSScalarMap::global_iterator I = GG.getScalarMap().global_begin(),
226 E = GG.getScalarMap().global_end(); I != E; ++I)
227 if (isa<GlobalVariable>(*I))
228 RC.getClonedNH(GG.getNodeForValue(*I));
230 MainGraph.maskIncompleteMarkers();
231 MainGraph.markIncompleteNodes(DSGraph::MarkFormalArgs |
232 DSGraph::IgnoreGlobals);
234 //Debug messages if along the way we didn't resolve a call site
235 //also update the call graph and callsites we did find.
236 for(DSGraph::afc_iterator ii = MainGraph.afc_begin(),
237 ee = MainGraph.afc_end(); ii != ee; ++ii) {
238 std::vector<Function*> Funcs;
239 GetAllCallees(*ii, Funcs);
240 std::cerr << "Lost site\n";
241 for (std::vector<Function*>::iterator iif = Funcs.begin(), eef = Funcs.end();
243 AddGlobalToNode(this, *ii, *iif);
244 std::cerr << "Adding\n";
245 ActualCallees.insert(std::make_pair(ii->getCallSite().getInstruction(), *iif));
251 NumCallEdges += ActualCallees.size();
256 DSGraph &BUDataStructures::getOrCreateGraph(Function *F) {
257 // Has the graph already been created?
258 DSGraph *&Graph = DSInfo[F];
259 if (Graph) return *Graph;
261 DSGraph &LocGraph = getAnalysis<LocalDataStructures>().getDSGraph(*F);
263 // Steal the local graph.
264 Graph = new DSGraph(GlobalECs, LocGraph.getTargetData());
265 Graph->spliceFrom(LocGraph);
267 Graph->setGlobalsGraph(GlobalsGraph);
268 Graph->setPrintAuxCalls();
270 // Start with a copy of the original call sites...
271 Graph->getAuxFunctionCalls() = Graph->getFunctionCalls();
275 static bool isVAHackFn(const Function *F) {
276 return F->getName() == "printf" || F->getName() == "sscanf" ||
277 F->getName() == "fprintf" || F->getName() == "open" ||
278 F->getName() == "sprintf" || F->getName() == "fputs" ||
279 F->getName() == "fscanf" || F->getName() == "malloc" ||
280 F->getName() == "free";
283 static bool isResolvableFunc(const Function* callee) {
284 return !callee->isExternal() || isVAHackFn(callee);
287 //returns true if all callees were resolved
288 static bool GetAllCallees(const DSCallSite &CS,
289 std::vector<Function*> &Callees) {
290 if (CS.isDirectCall()) {
291 if (isResolvableFunc(CS.getCalleeFunc())) {
292 Callees.push_back(CS.getCalleeFunc());
298 bool retval = CS.getCalleeNode()->isComplete();
299 unsigned OldSize = Callees.size();
300 CS.getCalleeNode()->addFullFunctionList(Callees);
302 // If any of the callees are unresolvable, remove that one
303 for (unsigned i = OldSize; i != Callees.size(); ++i)
304 if (!isResolvableFunc(Callees[i])) {
305 Callees.erase(Callees.begin()+i);
314 /// GetAllAuxCallees - Return a list containing all of the resolvable callees in
315 /// the aux list for the specified graph in the Callees vector.
316 static void GetAllAuxCallees(DSGraph &G, std::vector<Function*> &Callees) {
318 for (DSGraph::afc_iterator I = G.afc_begin(), E = G.afc_end(); I != E; ++I)
319 GetAllCallees(*I, Callees);
322 unsigned BUDataStructures::calculateGraphs(Function *F,
323 std::vector<Function*> &Stack,
325 hash_map<Function*, unsigned> &ValMap) {
326 assert(!ValMap.count(F) && "Shouldn't revisit functions!");
327 unsigned Min = NextID++, MyID = Min;
331 // FIXME! This test should be generalized to be any function that we have
332 // already processed, in the case when there isn't a main or there are
333 // unreachable functions!
334 if (F->isExternal()) { // sprintf, fprintf, sscanf, etc...
341 DSGraph &Graph = getOrCreateGraph(F);
343 Graph.updateFromGlobalGraph();
345 // Find all callee functions.
346 std::vector<Function*> CalleeFunctions;
347 GetAllAuxCallees(Graph, CalleeFunctions);
349 // The edges out of the current node are the call site targets...
350 for (unsigned i = 0, e = CalleeFunctions.size(); i != e; ++i) {
351 Function *Callee = CalleeFunctions[i];
353 // Have we visited the destination function yet?
354 hash_map<Function*, unsigned>::iterator It = ValMap.find(Callee);
355 if (It == ValMap.end()) // No, visit it now.
356 M = calculateGraphs(Callee, Stack, NextID, ValMap);
357 else // Yes, get it's number.
359 if (M < Min) Min = M;
362 assert(ValMap[F] == MyID && "SCC construction assumption wrong!");
364 return Min; // This is part of a larger SCC!
366 // If this is a new SCC, process it now.
367 if (Stack.back() == F) { // Special case the single "SCC" case here.
368 DEBUG(std::cerr << "Visiting single node SCC #: " << MyID << " fn: "
369 << F->getName() << "\n");
371 DSGraph &G = getDSGraph(*F);
372 DEBUG(std::cerr << " [BU] Calculating graph for: " << F->getName()<< "\n");
373 bool redo = calculateGraph(G);
374 DEBUG(std::cerr << " [BU] Done inlining: " << F->getName() << " ["
375 << G.getGraphSize() << "+" << G.getAuxFunctionCalls().size()
378 if (MaxSCC < 1) MaxSCC = 1;
380 // Should we revisit the graph? Only do it if there are now new resolvable
383 DEBUG(std::cerr << "Recalculating " << F->getName() << " due to new knowledge\n");
385 return calculateGraphs(F, Stack, NextID, ValMap);
392 // SCCFunctions - Keep track of the functions in the current SCC
394 std::vector<DSGraph*> SCCGraphs;
396 unsigned SCCSize = 1;
397 Function *NF = Stack.back();
399 DSGraph &SCCGraph = getDSGraph(*NF);
401 // First thing first, collapse all of the DSGraphs into a single graph for
402 // the entire SCC. Splice all of the graphs into one and discard all of the
410 DSGraph &NFG = getDSGraph(*NF);
412 // Update the Function -> DSG map.
413 for (DSGraph::retnodes_iterator I = NFG.retnodes_begin(),
414 E = NFG.retnodes_end(); I != E; ++I)
415 DSInfo[I->first] = &SCCGraph;
417 SCCGraph.spliceFrom(NFG);
424 std::cerr << "Calculating graph for SCC #: " << MyID << " of size: "
427 // Compute the Max SCC Size.
428 if (MaxSCC < SCCSize)
431 // Clean up the graph before we start inlining a bunch again...
432 SCCGraph.removeDeadNodes(DSGraph::KeepUnreachableGlobals);
434 // Now that we have one big happy family, resolve all of the call sites in
436 bool redo = calculateGraph(SCCGraph);
437 DEBUG(std::cerr << " [BU] Done inlining SCC [" << SCCGraph.getGraphSize()
438 << "+" << SCCGraph.getAuxFunctionCalls().size() << "]\n");
441 DEBUG(std::cerr << "MISSING REDO\n");
444 std::cerr << "DONE with SCC #: " << MyID << "\n";
446 // We never have to revisit "SCC" processed functions...
450 return MyID; // == Min
454 // releaseMemory - If the pass pipeline is done with this pass, we can release
455 // our memory... here...
457 void BUDataStructures::releaseMyMemory() {
458 for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
459 E = DSInfo.end(); I != E; ++I) {
460 I->second->getReturnNodes().erase(I->first);
461 if (I->second->getReturnNodes().empty())
465 // Empty map so next time memory is released, data structures are not
472 DSGraph &BUDataStructures::CreateGraphForExternalFunction(const Function &Fn) {
473 Function *F = const_cast<Function*>(&Fn);
474 DSGraph *DSG = new DSGraph(GlobalECs, GlobalsGraph->getTargetData());
476 DSG->setGlobalsGraph(GlobalsGraph);
477 DSG->setPrintAuxCalls();
479 // Add function to the graph.
480 DSG->getReturnNodes().insert(std::make_pair(F, DSNodeHandle()));
482 if (F->getName() == "free") { // Taking the address of free.
484 // Free should take a single pointer argument, mark it as heap memory.
485 DSNode *N = new DSNode(0, DSG);
486 N->setHeapNodeMarker();
487 DSG->getNodeForValue(F->arg_begin()).mergeWith(N);
490 std::cerr << "Unrecognized external function: " << F->getName() << "\n";
498 bool BUDataStructures::calculateGraph(DSGraph &Graph) {
499 // If this graph contains the main function, clone the globals graph into this
500 // graph before we inline callees and other fun stuff.
501 bool ContainsMain = false;
502 DSGraph::ReturnNodesTy &ReturnNodes = Graph.getReturnNodes();
504 for (DSGraph::ReturnNodesTy::iterator I = ReturnNodes.begin(),
505 E = ReturnNodes.end(); I != E; ++I)
506 if (I->first->hasExternalLinkage() && I->first->getName() == "main") {
511 // If this graph contains main, copy the contents of the globals graph over.
512 // Note that this is *required* for correctness. If a callee contains a use
513 // of a global, we have to make sure to link up nodes due to global-argument
516 const DSGraph &GG = *Graph.getGlobalsGraph();
517 ReachabilityCloner RC(Graph, GG,
518 DSGraph::DontCloneCallNodes |
519 DSGraph::DontCloneAuxCallNodes);
521 // Clone the global nodes into this graph.
522 for (DSScalarMap::global_iterator I = GG.getScalarMap().global_begin(),
523 E = GG.getScalarMap().global_end(); I != E; ++I)
524 if (isa<GlobalVariable>(*I))
525 RC.getClonedNH(GG.getNodeForValue(*I));
529 // Move our call site list into TempFCs so that inline call sites go into the
530 // new call site list and doesn't invalidate our iterators!
531 std::list<DSCallSite> TempFCs;
532 std::list<DSCallSite> &AuxCallsList = Graph.getAuxFunctionCalls();
533 TempFCs.swap(AuxCallsList);
534 //remember what we've seen (or will see)
535 unsigned oldSize = TempFCs.size();
537 bool Printed = false;
538 bool missingNode = false;
540 while (!TempFCs.empty()) {
541 DSCallSite &CS = *TempFCs.begin();
542 Instruction *TheCall = CS.getCallSite().getInstruction();
545 // Fast path for noop calls. Note that we don't care about merging globals
546 // in the callee with nodes in the caller here.
547 if (CS.isDirectCall()) {
548 if (!isVAHackFn(CS.getCalleeFunc()) && isResolvableFunc(CS.getCalleeFunc())) {
549 Function* Callee = CS.getCalleeFunc();
550 ActualCallees.insert(std::make_pair(TheCall, Callee));
552 assert(doneDSGraph(Callee) && "Direct calls should always be precomputed");
553 GI = &getDSGraph(*Callee); // Graph to inline
554 DEBUG(std::cerr << " Inlining graph for " << Callee->getName());
555 DEBUG(std::cerr << "[" << GI->getGraphSize() << "+"
556 << GI->getAuxFunctionCalls().size() << "] into '"
557 << Graph.getFunctionNames() << "' [" << Graph.getGraphSize() <<"+"
558 << Graph.getAuxFunctionCalls().size() << "]\n");
559 Graph.mergeInGraph(CS, *Callee, *GI,
560 DSGraph::StripAllocaBit|DSGraph::DontCloneCallNodes);
563 DEBUG(std::cerr << "Graph " << Graph.getFunctionNames() << " Call Site " <<
564 CS.getCallSite().getInstruction() << " never resolvable\n");
570 std::vector<Function*> CalledFuncs;
571 bool resolved = GetAllCallees(CS, CalledFuncs);
573 if (CalledFuncs.empty()) {
574 DEBUG(std::cerr << "Graph " << Graph.getFunctionNames() << " Call Site " <<
575 CS.getCallSite().getInstruction() << " delayed\n");
579 std::cerr << "In Fns: " << Graph.getFunctionNames() << "\n";
580 std::cerr << " calls " << CalledFuncs.size()
581 << " fns from site: " << CS.getCallSite().getInstruction()
582 << " " << *CS.getCallSite().getInstruction();
583 std::cerr << " Fns =";
585 unsigned NumPrinted = 0;
587 for (std::vector<Function*>::iterator I = CalledFuncs.begin(),
588 E = CalledFuncs.end(); I != E; ++I) {
589 DEBUG(if (NumPrinted++ < 8) std::cerr << " " << (*I)->getName(););
591 // Add the call edges to the call graph.
592 ActualCallees.insert(std::make_pair(TheCall, *I));
594 DEBUG(std::cerr << "\n");
596 // See if we already computed a graph for this set of callees.
597 std::sort(CalledFuncs.begin(), CalledFuncs.end());
598 std::pair<DSGraph*, std::vector<DSNodeHandle> > &IndCallGraph =
599 (*IndCallGraphMap)[CalledFuncs];
601 if (IndCallGraph.first == 0) {
602 std::vector<Function*>::iterator I = CalledFuncs.begin(),
603 E = CalledFuncs.end();
605 // Start with a copy of the first graph.
606 if (!doneDSGraph(*I)) {
607 AuxCallsList.splice(AuxCallsList.end(), TempFCs, TempFCs.begin());
612 AddGlobalToNode(this, CS, *I);
614 GI = IndCallGraph.first = new DSGraph(getDSGraph(**I), GlobalECs);
615 GI->setGlobalsGraph(Graph.getGlobalsGraph());
616 std::vector<DSNodeHandle> &Args = IndCallGraph.second;
618 // Get the argument nodes for the first callee. The return value is
619 // the 0th index in the vector.
620 GI->getFunctionArgumentsForCall(*I, Args);
622 // Merge all of the other callees into this graph.
623 bool locMissing = false;
624 for (++I; I != E && !locMissing; ++I) {
625 AddGlobalToNode(this, CS, *I);
626 // If the graph already contains the nodes for the function, don't
627 // bother merging it in again.
628 if (!GI->containsFunction(*I)) {
629 if (!doneDSGraph(*I)) {
634 GI->cloneInto(getDSGraph(**I));
638 std::vector<DSNodeHandle> NextArgs;
639 GI->getFunctionArgumentsForCall(*I, NextArgs);
640 unsigned i = 0, e = Args.size();
641 for (; i != e; ++i) {
642 if (i == NextArgs.size()) break;
643 Args[i].mergeWith(NextArgs[i]);
645 for (e = NextArgs.size(); i != e; ++i)
646 Args.push_back(NextArgs[i]);
649 AuxCallsList.splice(AuxCallsList.end(), TempFCs, TempFCs.begin());
654 // Clean up the final graph!
655 GI->removeDeadNodes(DSGraph::KeepUnreachableGlobals);
657 DEBUG(std::cerr << "***\n*** RECYCLED GRAPH ***\n***\n");
658 for (std::vector<Function*>::iterator I = CalledFuncs.begin(), E = CalledFuncs.end(); I != E; ++I) {
659 AddGlobalToNode(this, CS, *I);
663 GI = IndCallGraph.first;
665 if (AlreadyInlined[CS.getCallSite()] != CalledFuncs) {
666 AlreadyInlined[CS.getCallSite()].swap(CalledFuncs);
668 // Merge the unified graph into this graph now.
669 DEBUG(std::cerr << " Inlining multi callee graph "
670 << "[" << GI->getGraphSize() << "+"
671 << GI->getAuxFunctionCalls().size() << "] into '"
672 << Graph.getFunctionNames() << "' [" << Graph.getGraphSize() <<"+"
673 << Graph.getAuxFunctionCalls().size() << "]\n");
675 Graph.mergeInGraph(CS, IndCallGraph.second, *GI,
676 DSGraph::StripAllocaBit |
677 DSGraph::DontCloneCallNodes);
681 DEBUG(std::cerr << " Skipping already inlined graph\n");
684 AuxCallsList.splice(AuxCallsList.end(), TempFCs, TempFCs.begin());
688 // Recompute the Incomplete markers
689 Graph.maskIncompleteMarkers();
690 Graph.markIncompleteNodes(DSGraph::MarkFormalArgs);
692 // Delete dead nodes. Treat globals that are unreachable but that can
693 // reach live nodes as live.
694 Graph.removeDeadNodes(DSGraph::KeepUnreachableGlobals);
696 // When this graph is finalized, clone the globals in the graph into the
697 // globals graph to make sure it has everything, from all graphs.
698 DSScalarMap &MainSM = Graph.getScalarMap();
699 ReachabilityCloner RC(*GlobalsGraph, Graph, DSGraph::StripAllocaBit);
701 // Clone everything reachable from globals in the function graph into the
703 for (DSScalarMap::global_iterator I = MainSM.global_begin(),
704 E = MainSM.global_end(); I != E; ++I)
705 RC.getClonedNH(MainSM[*I]);
707 //Graph.writeGraphToFile(std::cerr, "bu_" + F.getName());
709 AuxCallsList.unique();
710 //conditionally prune the call list keeping only one copy of each actual
712 if (AuxCallsList.size() > 100) {
713 DEBUG(std::cerr << "Reducing Aux from " << AuxCallsList.size());
714 std::map<CallSite, std::list<DSCallSite>::iterator> keepers;
715 TempFCs.swap(AuxCallsList);
716 for( std::list<DSCallSite>::iterator ii = TempFCs.begin(), ee = TempFCs.end();
718 keepers[ii->getCallSite()] = ii;
719 for (std::map<CallSite, std::list<DSCallSite>::iterator>::iterator
720 ii = keepers.begin(), ee = keepers.end();
722 AuxCallsList.splice(AuxCallsList.end(), TempFCs, ii->second);
723 DEBUG(std::cerr << " to " << AuxCallsList.size() << "\n");
725 return missingNode || oldSize != AuxCallsList.size();
728 static const Function *getFnForValue(const Value *V) {
729 if (const Instruction *I = dyn_cast<Instruction>(V))
730 return I->getParent()->getParent();
731 else if (const Argument *A = dyn_cast<Argument>(V))
732 return A->getParent();
733 else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
734 return BB->getParent();
738 /// deleteValue/copyValue - Interfaces to update the DSGraphs in the program.
739 /// These correspond to the interfaces defined in the AliasAnalysis class.
740 void BUDataStructures::deleteValue(Value *V) {
741 if (const Function *F = getFnForValue(V)) { // Function local value?
742 // If this is a function local value, just delete it from the scalar map!
743 getDSGraph(*F).getScalarMap().eraseIfExists(V);
747 if (Function *F = dyn_cast<Function>(V)) {
748 assert(getDSGraph(*F).getReturnNodes().size() == 1 &&
749 "cannot handle scc's");
755 assert(!isa<GlobalVariable>(V) && "Do not know how to delete GV's yet!");
758 void BUDataStructures::copyValue(Value *From, Value *To) {
759 if (From == To) return;
760 if (const Function *F = getFnForValue(From)) { // Function local value?
761 // If this is a function local value, just delete it from the scalar map!
762 getDSGraph(*F).getScalarMap().copyScalarIfExists(From, To);
766 if (Function *FromF = dyn_cast<Function>(From)) {
767 Function *ToF = cast<Function>(To);
768 assert(!DSInfo.count(ToF) && "New Function already exists!");
769 DSGraph *NG = new DSGraph(getDSGraph(*FromF), GlobalECs);
771 assert(NG->getReturnNodes().size() == 1 && "Cannot copy SCC's yet!");
773 // Change the Function* is the returnnodes map to the ToF.
774 DSNodeHandle Ret = NG->retnodes_begin()->second;
775 NG->getReturnNodes().clear();
776 NG->getReturnNodes()[ToF] = Ret;
780 if (const Function *F = getFnForValue(To)) {
781 DSGraph &G = getDSGraph(*F);
782 G.getScalarMap().copyScalarIfExists(From, To);
788 assert(0 && "Do not know how to copy this yet!");