Correctly handle global-argument aliases induced in main
[oota-llvm.git] / lib / Analysis / DataStructure / BottomUpClosure.cpp
1 //===- BottomUpClosure.cpp - Compute bottom-up interprocedural closure ----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "llvm/Analysis/DataStructure/DataStructure.h"
18 #include "llvm/Analysis/DataStructure/DSGraph.h"
19 #include "llvm/Module.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/Timer.h"
23 using namespace llvm;
24
25 namespace {
26   Statistic<> MaxSCC("budatastructure", "Maximum SCC Size in Call Graph");
27   Statistic<> NumBUInlines("budatastructures", "Number of graphs inlined");
28   Statistic<> NumCallEdges("budatastructures", "Number of 'actual' call edges");
29
30   RegisterAnalysis<BUDataStructures>
31   X("budatastructure", "Bottom-up Data Structure Analysis");
32 }
33
34 /// BuildGlobalECs - Look at all of the nodes in the globals graph.  If any node
35 /// contains multiple globals, DSA will never, ever, be able to tell the globals
36 /// apart.  Instead of maintaining this information in all of the graphs
37 /// throughout the entire program, store only a single global (the "leader") in
38 /// the graphs, and build equivalence classes for the rest of the globals.
39 static void BuildGlobalECs(DSGraph &GG, std::set<GlobalValue*> &ECGlobals) {
40   DSScalarMap &SM = GG.getScalarMap();
41   EquivalenceClasses<GlobalValue*> &GlobalECs = SM.getGlobalECs();
42   for (DSGraph::node_iterator I = GG.node_begin(), E = GG.node_end();
43        I != E; ++I) {
44     if (I->getGlobalsList().size() <= 1) continue;
45
46     // First, build up the equivalence set for this block of globals.
47     const std::vector<GlobalValue*> &GVs = I->getGlobalsList();
48     GlobalValue *First = GVs[0];
49     for (unsigned i = 1, e = GVs.size(); i != e; ++i)
50       GlobalECs.unionSets(First, GVs[i]);
51
52     // Next, get the leader element.
53     assert(First == GlobalECs.getLeaderValue(First) &&
54            "First did not end up being the leader?");
55
56     // Next, remove all globals from the scalar map that are not the leader.
57     assert(GVs[0] == First && "First had to be at the front!");
58     for (unsigned i = 1, e = GVs.size(); i != e; ++i) {
59       ECGlobals.insert(GVs[i]);
60       SM.erase(SM.find(GVs[i]));
61     }
62
63     // Finally, change the global node to only contain the leader.
64     I->clearGlobals();
65     I->addGlobal(First);
66   }
67
68   DEBUG(GG.AssertGraphOK());
69 }
70
71 /// EliminateUsesOfECGlobals - Once we have determined that some globals are in
72 /// really just equivalent to some other globals, remove the globals from the
73 /// specified DSGraph (if present), and merge any nodes with their leader nodes.
74 static void EliminateUsesOfECGlobals(DSGraph &G,
75                                      const std::set<GlobalValue*> &ECGlobals) {
76   DSScalarMap &SM = G.getScalarMap();
77   EquivalenceClasses<GlobalValue*> &GlobalECs = SM.getGlobalECs();
78
79   bool MadeChange = false;
80   for (DSScalarMap::global_iterator GI = SM.global_begin(), E = SM.global_end();
81        GI != E; ) {
82     GlobalValue *GV = *GI++;
83     if (!ECGlobals.count(GV)) continue;
84
85     const DSNodeHandle &GVNH = SM[GV];
86     assert(!GVNH.isNull() && "Global has null NH!?");
87
88     // Okay, this global is in some equivalence class.  Start by finding the
89     // leader of the class.
90     GlobalValue *Leader = GlobalECs.getLeaderValue(GV);
91
92     // If the leader isn't already in the graph, insert it into the node
93     // corresponding to GV.
94     if (!SM.global_count(Leader)) {
95       GVNH.getNode()->addGlobal(Leader);
96       SM[Leader] = GVNH;
97     } else {
98       // Otherwise, the leader is in the graph, make sure the nodes are the
99       // merged in the specified graph.
100       const DSNodeHandle &LNH = SM[Leader];
101       if (LNH.getNode() != GVNH.getNode())
102         LNH.mergeWith(GVNH);
103     }
104
105     // Next step, remove the global from the DSNode.
106     GVNH.getNode()->removeGlobal(GV);
107
108     // Finally, remove the global from the ScalarMap.
109     SM.erase(GV);
110     MadeChange = true;
111   }
112
113   DEBUG(if(MadeChange) G.AssertGraphOK());
114 }
115
116 // run - Calculate the bottom up data structure graphs for each function in the
117 // program.
118 //
119 bool BUDataStructures::runOnModule(Module &M) {
120   LocalDataStructures &LocalDSA = getAnalysis<LocalDataStructures>();
121   GlobalECs = LocalDSA.getGlobalECs();
122
123   GlobalsGraph = new DSGraph(LocalDSA.getGlobalsGraph(), GlobalECs);
124   GlobalsGraph->setPrintAuxCalls();
125
126   IndCallGraphMap = new std::map<std::vector<Function*>,
127                            std::pair<DSGraph*, std::vector<DSNodeHandle> > >();
128
129   std::vector<Function*> Stack;
130   hash_map<Function*, unsigned> ValMap;
131   unsigned NextID = 1;
132
133   Function *MainFunc = M.getMainFunction();
134   if (MainFunc)
135     calculateGraphs(MainFunc, Stack, NextID, ValMap);
136
137   // Calculate the graphs for any functions that are unreachable from main...
138   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
139     if (!I->isExternal() && !DSInfo.count(I)) {
140 #ifndef NDEBUG
141       if (MainFunc)
142         std::cerr << "*** Function unreachable from main: "
143                   << I->getName() << "\n";
144 #endif
145       calculateGraphs(I, Stack, NextID, ValMap);     // Calculate all graphs.
146     }
147
148   NumCallEdges += ActualCallees.size();
149
150   // If we computed any temporary indcallgraphs, free them now.
151   for (std::map<std::vector<Function*>,
152          std::pair<DSGraph*, std::vector<DSNodeHandle> > >::iterator I =
153          IndCallGraphMap->begin(), E = IndCallGraphMap->end(); I != E; ++I) {
154     I->second.second.clear();  // Drop arg refs into the graph.
155     delete I->second.first;
156   }
157   delete IndCallGraphMap;
158
159   // At the end of the bottom-up pass, the globals graph becomes complete.
160   // FIXME: This is not the right way to do this, but it is sorta better than
161   // nothing!  In particular, externally visible globals and unresolvable call
162   // nodes at the end of the BU phase should make things that they point to
163   // incomplete in the globals graph.
164   //
165   GlobalsGraph->removeTriviallyDeadNodes();
166   GlobalsGraph->maskIncompleteMarkers();
167
168   // Mark external globals incomplete.
169   GlobalsGraph->markIncompleteNodes(DSGraph::IgnoreGlobals);
170
171   // Grow the equivalence classes for the globals to include anything that we
172   // now know to be aliased.
173   std::set<GlobalValue*> ECGlobals;
174   BuildGlobalECs(*GlobalsGraph, ECGlobals);
175   if (!ECGlobals.empty()) {
176     NamedRegionTimer X("Bottom-UP EC Cleanup");
177     std::cerr << "Eliminating " << ECGlobals.size() << " EC Globals!\n";
178     for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
179            E = DSInfo.end(); I != E; ++I)
180       EliminateUsesOfECGlobals(*I->second, ECGlobals);
181   }
182
183   // Merge the globals variables (not the calls) from the globals graph back
184   // into the main function's graph so that the main function contains all of
185   // the information about global pools and GV usage in the program.
186   if (MainFunc && !MainFunc->isExternal()) {
187     DSGraph &MainGraph = getOrCreateGraph(MainFunc);
188     const DSGraph &GG = *MainGraph.getGlobalsGraph();
189     ReachabilityCloner RC(MainGraph, GG,
190                           DSGraph::DontCloneCallNodes |
191                           DSGraph::DontCloneAuxCallNodes);
192
193     // Clone the global nodes into this graph.
194     for (DSScalarMap::global_iterator I = GG.getScalarMap().global_begin(),
195            E = GG.getScalarMap().global_end(); I != E; ++I)
196       if (isa<GlobalVariable>(*I))
197         RC.getClonedNH(GG.getNodeForValue(*I));
198
199     MainGraph.maskIncompleteMarkers();
200     MainGraph.markIncompleteNodes(DSGraph::MarkFormalArgs |
201                                   DSGraph::IgnoreGlobals);
202   }
203
204   return false;
205 }
206
207 DSGraph &BUDataStructures::getOrCreateGraph(Function *F) {
208   // Has the graph already been created?
209   DSGraph *&Graph = DSInfo[F];
210   if (Graph) return *Graph;
211
212   DSGraph &LocGraph = getAnalysis<LocalDataStructures>().getDSGraph(*F);
213
214   // Steal the local graph.
215   Graph = new DSGraph(GlobalECs, LocGraph.getTargetData());
216   Graph->spliceFrom(LocGraph);
217
218   Graph->setGlobalsGraph(GlobalsGraph);
219   Graph->setPrintAuxCalls();
220
221   // Start with a copy of the original call sites...
222   Graph->getAuxFunctionCalls() = Graph->getFunctionCalls();
223   return *Graph;
224 }
225
226 static bool isVAHackFn(const Function *F) {
227   return F->getName() == "printf"  || F->getName() == "sscanf" ||
228     F->getName() == "fprintf" || F->getName() == "open" ||
229     F->getName() == "sprintf" || F->getName() == "fputs" ||
230     F->getName() == "fscanf" || F->getName() == "malloc" ||
231     F->getName() == "free";
232 }
233
234 static bool isResolvableFunc(const Function* callee) {
235   return !callee->isExternal() || isVAHackFn(callee);
236 }
237
238 static void GetAllCallees(const DSCallSite &CS,
239                           std::vector<Function*> &Callees) {
240   if (CS.isDirectCall()) {
241     if (isResolvableFunc(CS.getCalleeFunc()))
242       Callees.push_back(CS.getCalleeFunc());
243   } else if (!CS.getCalleeNode()->isIncomplete()) {
244     // Get all callees.
245     unsigned OldSize = Callees.size();
246     CS.getCalleeNode()->addFullFunctionList(Callees);
247
248     // If any of the callees are unresolvable, remove the whole batch!
249     for (unsigned i = OldSize, e = Callees.size(); i != e; ++i)
250       if (!isResolvableFunc(Callees[i])) {
251         Callees.erase(Callees.begin()+OldSize, Callees.end());
252         return;
253       }
254   }
255 }
256
257
258 /// GetAllAuxCallees - Return a list containing all of the resolvable callees in
259 /// the aux list for the specified graph in the Callees vector.
260 static void GetAllAuxCallees(DSGraph &G, std::vector<Function*> &Callees) {
261   Callees.clear();
262   for (DSGraph::afc_iterator I = G.afc_begin(), E = G.afc_end(); I != E; ++I)
263     GetAllCallees(*I, Callees);
264 }
265
266 unsigned BUDataStructures::calculateGraphs(Function *F,
267                                            std::vector<Function*> &Stack,
268                                            unsigned &NextID,
269                                      hash_map<Function*, unsigned> &ValMap) {
270   assert(!ValMap.count(F) && "Shouldn't revisit functions!");
271   unsigned Min = NextID++, MyID = Min;
272   ValMap[F] = Min;
273   Stack.push_back(F);
274
275   // FIXME!  This test should be generalized to be any function that we have
276   // already processed, in the case when there isn't a main or there are
277   // unreachable functions!
278   if (F->isExternal()) {   // sprintf, fprintf, sscanf, etc...
279     // No callees!
280     Stack.pop_back();
281     ValMap[F] = ~0;
282     return Min;
283   }
284
285   DSGraph &Graph = getOrCreateGraph(F);
286
287   // Find all callee functions.
288   std::vector<Function*> CalleeFunctions;
289   GetAllAuxCallees(Graph, CalleeFunctions);
290
291   // The edges out of the current node are the call site targets...
292   for (unsigned i = 0, e = CalleeFunctions.size(); i != e; ++i) {
293     Function *Callee = CalleeFunctions[i];
294     unsigned M;
295     // Have we visited the destination function yet?
296     hash_map<Function*, unsigned>::iterator It = ValMap.find(Callee);
297     if (It == ValMap.end())  // No, visit it now.
298       M = calculateGraphs(Callee, Stack, NextID, ValMap);
299     else                    // Yes, get it's number.
300       M = It->second;
301     if (M < Min) Min = M;
302   }
303
304   assert(ValMap[F] == MyID && "SCC construction assumption wrong!");
305   if (Min != MyID)
306     return Min;         // This is part of a larger SCC!
307
308   // If this is a new SCC, process it now.
309   if (Stack.back() == F) {           // Special case the single "SCC" case here.
310     DEBUG(std::cerr << "Visiting single node SCC #: " << MyID << " fn: "
311                     << F->getName() << "\n");
312     Stack.pop_back();
313     DSGraph &G = getDSGraph(*F);
314     DEBUG(std::cerr << "  [BU] Calculating graph for: " << F->getName()<< "\n");
315     calculateGraph(G);
316     DEBUG(std::cerr << "  [BU] Done inlining: " << F->getName() << " ["
317                     << G.getGraphSize() << "+" << G.getAuxFunctionCalls().size()
318                     << "]\n");
319
320     if (MaxSCC < 1) MaxSCC = 1;
321
322     // Should we revisit the graph?  Only do it if there are now new resolvable
323     // callees.
324     GetAllAuxCallees(Graph, CalleeFunctions);
325     if (!CalleeFunctions.empty()) {
326       ValMap.erase(F);
327       return calculateGraphs(F, Stack, NextID, ValMap);
328     } else {
329       ValMap[F] = ~0U;
330     }
331     return MyID;
332
333   } else {
334     // SCCFunctions - Keep track of the functions in the current SCC
335     //
336     std::vector<DSGraph*> SCCGraphs;
337
338     unsigned SCCSize = 1;
339     Function *NF = Stack.back();
340     ValMap[NF] = ~0U;
341     DSGraph &SCCGraph = getDSGraph(*NF);
342
343     // First thing first, collapse all of the DSGraphs into a single graph for
344     // the entire SCC.  Splice all of the graphs into one and discard all of the
345     // old graphs.
346     //
347     while (NF != F) {
348       Stack.pop_back();
349       NF = Stack.back();
350       ValMap[NF] = ~0U;
351
352       DSGraph &NFG = getDSGraph(*NF);
353
354       // Update the Function -> DSG map.
355       for (DSGraph::retnodes_iterator I = NFG.retnodes_begin(),
356              E = NFG.retnodes_end(); I != E; ++I)
357         DSInfo[I->first] = &SCCGraph;
358
359       SCCGraph.spliceFrom(NFG);
360       delete &NFG;
361
362       ++SCCSize;
363     }
364     Stack.pop_back();
365
366     std::cerr << "Calculating graph for SCC #: " << MyID << " of size: "
367               << SCCSize << "\n";
368
369     // Compute the Max SCC Size.
370     if (MaxSCC < SCCSize)
371       MaxSCC = SCCSize;
372
373     // Clean up the graph before we start inlining a bunch again...
374     SCCGraph.removeDeadNodes(DSGraph::KeepUnreachableGlobals);
375
376     // Now that we have one big happy family, resolve all of the call sites in
377     // the graph...
378     calculateGraph(SCCGraph);
379     DEBUG(std::cerr << "  [BU] Done inlining SCC  [" << SCCGraph.getGraphSize()
380                     << "+" << SCCGraph.getAuxFunctionCalls().size() << "]\n");
381
382     std::cerr << "DONE with SCC #: " << MyID << "\n";
383
384     // We never have to revisit "SCC" processed functions...
385     return MyID;
386   }
387
388   return MyID;  // == Min
389 }
390
391
392 // releaseMemory - If the pass pipeline is done with this pass, we can release
393 // our memory... here...
394 //
395 void BUDataStructures::releaseMyMemory() {
396   for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
397          E = DSInfo.end(); I != E; ++I) {
398     I->second->getReturnNodes().erase(I->first);
399     if (I->second->getReturnNodes().empty())
400       delete I->second;
401   }
402
403   // Empty map so next time memory is released, data structures are not
404   // re-deleted.
405   DSInfo.clear();
406   delete GlobalsGraph;
407   GlobalsGraph = 0;
408 }
409
410 DSGraph &BUDataStructures::CreateGraphForExternalFunction(const Function &Fn) {
411   Function *F = const_cast<Function*>(&Fn);
412   DSGraph *DSG = new DSGraph(GlobalECs, GlobalsGraph->getTargetData());
413   DSInfo[F] = DSG;
414   DSG->setGlobalsGraph(GlobalsGraph);
415   DSG->setPrintAuxCalls();
416
417   // Add function to the graph.
418   DSG->getReturnNodes().insert(std::make_pair(F, DSNodeHandle()));
419
420   if (F->getName() == "free") { // Taking the address of free.
421     
422     // Free should take a single pointer argument, mark it as heap memory.
423     DSNode *N = new DSNode(0, DSG);
424     N->setHeapNodeMarker();
425     DSG->getNodeForValue(F->arg_begin()).mergeWith(N);
426
427   } else {
428     std::cerr << "Unrecognized external function: " << F->getName() << "\n";
429     abort();
430   }
431
432   return *DSG;
433 }
434
435
436 void BUDataStructures::calculateGraph(DSGraph &Graph) {
437   // If this graph contains the main function, clone the globals graph into this
438   // graph before we inline callees and other fun stuff.
439   bool ContainsMain = false;
440   DSGraph::ReturnNodesTy &ReturnNodes = Graph.getReturnNodes();
441
442   for (DSGraph::ReturnNodesTy::iterator I = ReturnNodes.begin(),
443          E = ReturnNodes.end(); I != E; ++I)
444     if (I->first->hasExternalLinkage() && I->first->getName() == "main") {
445       ContainsMain = true;
446       break;
447     }
448
449   // If this graph contains main, copy the contents of the globals graph over.
450   // Note that this is *required* for correctness.  If a callee contains a use
451   // of a global, we have to make sure to link up nodes due to global-argument
452   // bindings.
453   if (ContainsMain) {
454     const DSGraph &GG = *Graph.getGlobalsGraph();
455     ReachabilityCloner RC(Graph, GG,
456                           DSGraph::DontCloneCallNodes |
457                           DSGraph::DontCloneAuxCallNodes);
458
459     // Clone the global nodes into this graph.
460     for (DSScalarMap::global_iterator I = GG.getScalarMap().global_begin(),
461            E = GG.getScalarMap().global_end(); I != E; ++I)
462       if (isa<GlobalVariable>(*I))
463         RC.getClonedNH(GG.getNodeForValue(*I));
464   }
465
466
467   // Move our call site list into TempFCs so that inline call sites go into the
468   // new call site list and doesn't invalidate our iterators!
469   std::list<DSCallSite> TempFCs;
470   std::list<DSCallSite> &AuxCallsList = Graph.getAuxFunctionCalls();
471   TempFCs.swap(AuxCallsList);
472
473   bool Printed = false;
474   std::vector<Function*> CalledFuncs;
475   while (!TempFCs.empty()) {
476     DSCallSite &CS = *TempFCs.begin();
477
478     CalledFuncs.clear();
479
480     // Fast path for noop calls.  Note that we don't care about merging globals
481     // in the callee with nodes in the caller here.
482     if (CS.getRetVal().isNull() && CS.getNumPtrArgs() == 0) {
483       TempFCs.erase(TempFCs.begin());
484       continue;
485     } else if (CS.isDirectCall() && isVAHackFn(CS.getCalleeFunc())) {
486       TempFCs.erase(TempFCs.begin());
487       continue;
488     }
489
490     GetAllCallees(CS, CalledFuncs);
491
492     if (CalledFuncs.empty()) {
493       // Remember that we could not resolve this yet!
494       AuxCallsList.splice(AuxCallsList.end(), TempFCs, TempFCs.begin());
495       continue;
496     } else {
497       DSGraph *GI;
498       Instruction *TheCall = CS.getCallSite().getInstruction();
499
500       if (CalledFuncs.size() == 1) {
501         Function *Callee = CalledFuncs[0];
502         ActualCallees.insert(std::make_pair(TheCall, Callee));
503
504         // Get the data structure graph for the called function.
505         GI = &getDSGraph(*Callee);  // Graph to inline
506         DEBUG(std::cerr << "    Inlining graph for " << Callee->getName());
507
508         DEBUG(std::cerr << "[" << GI->getGraphSize() << "+"
509               << GI->getAuxFunctionCalls().size() << "] into '"
510               << Graph.getFunctionNames() << "' [" << Graph.getGraphSize() <<"+"
511               << Graph.getAuxFunctionCalls().size() << "]\n");
512         Graph.mergeInGraph(CS, *Callee, *GI,
513                            DSGraph::StripAllocaBit|DSGraph::DontCloneCallNodes);
514         ++NumBUInlines;
515       } else {
516         if (!Printed)
517           std::cerr << "In Fns: " << Graph.getFunctionNames() << "\n";
518         std::cerr << "  calls " << CalledFuncs.size()
519                   << " fns from site: " << CS.getCallSite().getInstruction()
520                   << "  " << *CS.getCallSite().getInstruction();
521         std::cerr << "   Fns =";
522         unsigned NumPrinted = 0;
523
524         for (std::vector<Function*>::iterator I = CalledFuncs.begin(),
525                E = CalledFuncs.end(); I != E; ++I) {
526           if (NumPrinted++ < 8) std::cerr << " " << (*I)->getName();
527
528           // Add the call edges to the call graph.
529           ActualCallees.insert(std::make_pair(TheCall, *I));
530         }
531         std::cerr << "\n";
532
533         // See if we already computed a graph for this set of callees.
534         std::sort(CalledFuncs.begin(), CalledFuncs.end());
535         std::pair<DSGraph*, std::vector<DSNodeHandle> > &IndCallGraph =
536           (*IndCallGraphMap)[CalledFuncs];
537
538         if (IndCallGraph.first == 0) {
539           std::vector<Function*>::iterator I = CalledFuncs.begin(),
540             E = CalledFuncs.end();
541
542           // Start with a copy of the first graph.
543           GI = IndCallGraph.first = new DSGraph(getDSGraph(**I), GlobalECs);
544           GI->setGlobalsGraph(Graph.getGlobalsGraph());
545           std::vector<DSNodeHandle> &Args = IndCallGraph.second;
546
547           // Get the argument nodes for the first callee.  The return value is
548           // the 0th index in the vector.
549           GI->getFunctionArgumentsForCall(*I, Args);
550
551           // Merge all of the other callees into this graph.
552           for (++I; I != E; ++I) {
553             // If the graph already contains the nodes for the function, don't
554             // bother merging it in again.
555             if (!GI->containsFunction(*I)) {
556               GI->cloneInto(getDSGraph(**I));
557               ++NumBUInlines;
558             }
559
560             std::vector<DSNodeHandle> NextArgs;
561             GI->getFunctionArgumentsForCall(*I, NextArgs);
562             unsigned i = 0, e = Args.size();
563             for (; i != e; ++i) {
564               if (i == NextArgs.size()) break;
565               Args[i].mergeWith(NextArgs[i]);
566             }
567             for (e = NextArgs.size(); i != e; ++i)
568               Args.push_back(NextArgs[i]);
569           }
570
571           // Clean up the final graph!
572           GI->removeDeadNodes(DSGraph::KeepUnreachableGlobals);
573         } else {
574           std::cerr << "***\n*** RECYCLED GRAPH ***\n***\n";
575         }
576
577         GI = IndCallGraph.first;
578
579         // Merge the unified graph into this graph now.
580         DEBUG(std::cerr << "    Inlining multi callee graph "
581               << "[" << GI->getGraphSize() << "+"
582               << GI->getAuxFunctionCalls().size() << "] into '"
583               << Graph.getFunctionNames() << "' [" << Graph.getGraphSize() <<"+"
584               << Graph.getAuxFunctionCalls().size() << "]\n");
585
586         Graph.mergeInGraph(CS, IndCallGraph.second, *GI,
587                            DSGraph::StripAllocaBit |
588                            DSGraph::DontCloneCallNodes);
589         ++NumBUInlines;
590       }
591     }
592     TempFCs.erase(TempFCs.begin());
593   }
594
595   // Recompute the Incomplete markers
596   Graph.maskIncompleteMarkers();
597   Graph.markIncompleteNodes(DSGraph::MarkFormalArgs);
598
599   // Delete dead nodes.  Treat globals that are unreachable but that can
600   // reach live nodes as live.
601   Graph.removeDeadNodes(DSGraph::KeepUnreachableGlobals);
602
603   // When this graph is finalized, clone the globals in the graph into the
604   // globals graph to make sure it has everything, from all graphs.
605   DSScalarMap &MainSM = Graph.getScalarMap();
606   ReachabilityCloner RC(*GlobalsGraph, Graph, DSGraph::StripAllocaBit);
607
608   // Clone everything reachable from globals in the function graph into the
609   // globals graph.
610   for (DSScalarMap::global_iterator I = MainSM.global_begin(),
611          E = MainSM.global_end(); I != E; ++I)
612     RC.getClonedNH(MainSM[*I]);
613
614   //Graph.writeGraphToFile(std::cerr, "bu_" + F.getName());
615 }
616
617 static const Function *getFnForValue(const Value *V) {
618   if (const Instruction *I = dyn_cast<Instruction>(V))
619     return I->getParent()->getParent();
620   else if (const Argument *A = dyn_cast<Argument>(V))
621     return A->getParent();
622   else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
623     return BB->getParent();
624   return 0;
625 }
626
627 /// deleteValue/copyValue - Interfaces to update the DSGraphs in the program.
628 /// These correspond to the interfaces defined in the AliasAnalysis class.
629 void BUDataStructures::deleteValue(Value *V) {
630   if (const Function *F = getFnForValue(V)) {  // Function local value?
631     // If this is a function local value, just delete it from the scalar map!
632     getDSGraph(*F).getScalarMap().eraseIfExists(V);
633     return;
634   }
635
636   if (Function *F = dyn_cast<Function>(V)) {
637     assert(getDSGraph(*F).getReturnNodes().size() == 1 &&
638            "cannot handle scc's");
639     delete DSInfo[F];
640     DSInfo.erase(F);
641     return;
642   }
643
644   assert(!isa<GlobalVariable>(V) && "Do not know how to delete GV's yet!");
645 }
646
647 void BUDataStructures::copyValue(Value *From, Value *To) {
648   if (From == To) return;
649   if (const Function *F = getFnForValue(From)) {  // Function local value?
650     // If this is a function local value, just delete it from the scalar map!
651     getDSGraph(*F).getScalarMap().copyScalarIfExists(From, To);
652     return;
653   }
654
655   if (Function *FromF = dyn_cast<Function>(From)) {
656     Function *ToF = cast<Function>(To);
657     assert(!DSInfo.count(ToF) && "New Function already exists!");
658     DSGraph *NG = new DSGraph(getDSGraph(*FromF), GlobalECs);
659     DSInfo[ToF] = NG;
660     assert(NG->getReturnNodes().size() == 1 && "Cannot copy SCC's yet!");
661
662     // Change the Function* is the returnnodes map to the ToF.
663     DSNodeHandle Ret = NG->retnodes_begin()->second;
664     NG->getReturnNodes().clear();
665     NG->getReturnNodes()[ToF] = Ret;
666     return;
667   }
668
669   if (const Function *F = getFnForValue(To)) {
670     DSGraph &G = getDSGraph(*F);
671     G.getScalarMap().copyScalarIfExists(From, To);
672     return;
673   }
674
675   std::cerr << *From;
676   std::cerr << *To;
677   assert(0 && "Do not know how to copy this yet!");
678   abort();
679 }