aboutsummaryrefslogtreecommitdiff
path: root/lib/Analysis/DataStructure/BottomUpClosure.cpp
blob: 36a3d1763ac5c34eb58832009ce14f78c9ecf76a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
//===- BottomUpClosure.cpp - Compute bottom-up interprocedural closure ----===//
//
// This file implements the BUDataStructures class, which represents the
// Bottom-Up Interprocedural closure of the data structure graph over the
// program.  This is useful for applications like pool allocation, but **not**
// applications like alias analysis.
//
//===----------------------------------------------------------------------===//

#include "llvm/Analysis/DataStructure.h"
#include "llvm/Analysis/DSGraph.h"
#include "llvm/Module.h"
#include "Support/Statistic.h"
using std::map;

static RegisterAnalysis<BUDataStructures>
X("budatastructure", "Bottom-up Data Structure Analysis Closure");

using namespace DS;

// run - Calculate the bottom up data structure graphs for each function in the
// program.
//
bool BUDataStructures::run(Module &M) {
  GlobalsGraph = new DSGraph();

  // Simply calculate the graphs for each function...
  for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
    if (!I->isExternal())
      calculateGraph(*I, 0);
  return false;
}

// releaseMemory - If the pass pipeline is done with this pass, we can release
// our memory... here...
//
void BUDataStructures::releaseMemory() {
  for (map<const Function*, DSGraph*>::iterator I = DSInfo.begin(),
         E = DSInfo.end(); I != E; ++I)
    delete I->second;

  // Empty map so next time memory is released, data structures are not
  // re-deleted.
  DSInfo.clear();
  delete GlobalsGraph;
  GlobalsGraph = 0;
}


// Return true if a graph was inlined
// Can not modify the part of the AuxCallList < FirstResolvableCall.
//
bool BUDataStructures::ResolveFunctionCalls(DSGraph &G,
                                            unsigned &FirstResolvableCall,
                                   std::map<Function*, DSCallSite> &InProcess,
                                            unsigned Indent) {
  std::vector<DSCallSite> &FCs = G.getAuxFunctionCalls();
  bool Changed = false;

  // Loop while there are call sites that we can resolve!
  while (FirstResolvableCall != FCs.size()) {
    DSCallSite Call = FCs[FirstResolvableCall];

    // If the function list is incomplete...
    if (Call.getCallee().getNode()->NodeType & DSNode::Incomplete) {
      // If incomplete, we cannot resolve it, so leave it at the beginning of
      // the call list with the other unresolvable calls...
      ++FirstResolvableCall;
    } else {
      // Start inlining all of the functions we can... some may not be
      // inlinable if they are external...
      //
      const std::vector<GlobalValue*> &Callees =
        Call.getCallee().getNode()->getGlobals();

      bool hasExternalTarget = false;
      
      // Loop over the functions, inlining whatever we can...
      for (unsigned c = 0, e = Callees.size(); c != e; ++c) {
        // Must be a function type, so this cast should succeed unless something
        // really wierd is happening.
        Function &FI = cast<Function>(*Callees[c]);

        if (FI.getName() == "printf" || FI.getName() == "sscanf" ||
            FI.getName() == "fprintf" || FI.getName() == "open" ||
            FI.getName() == "sprintf" || FI.getName() == "fputs") {
          // Ignore
        } else if (FI.isExternal()) {
          // If the function is external, then we cannot resolve this call site!
          hasExternalTarget = true;
          break;
        } else {
          std::map<Function*, DSCallSite>::iterator I =
            InProcess.lower_bound(&FI);

          if (I != InProcess.end() && I->first == &FI) {  // Recursion detected?
            // Merge two call sites to eliminate recursion...
            Call.mergeWith(I->second);

            DEBUG(std::cerr << std::string(Indent*2, ' ')
                  << "* Recursion detected for function " << FI.getName()<<"\n");
          } else {
            DEBUG(std::cerr << std::string(Indent*2, ' ')
                  << "Inlining: " << FI.getName() << "\n");
            
            // Get the data structure graph for the called function, closing it
            // if possible...
            //
            DSGraph &GI = calculateGraph(FI, Indent+1);  // Graph to inline

            DEBUG(std::cerr << std::string(Indent*2, ' ')
                  << "Got graph for: " << FI.getName() << "["
                  << GI.getGraphSize() << "+"
                  << GI.getAuxFunctionCalls().size() << "] "
                  << " in: " << G.getFunction().getName() << "["
                  << G.getGraphSize() << "+"
                  << G.getAuxFunctionCalls().size() << "]\n");

            // Keep track of how many call sites are added by the inlining...
            unsigned NumCalls = FCs.size();

            // Resolve the arguments and return value
            G.mergeInGraph(Call, GI, DSGraph::StripAllocaBit |
                           DSGraph::DontCloneCallNodes);

            // Added a call site?
            if (FCs.size() != NumCalls) {
              // Otherwise we need to inline the graph.  Temporarily add the
              // current function to the InProcess map to be able to handle
              // recursion successfully.
              //
              I = InProcess.insert(I, std::make_pair(&FI, Call));

              // ResolveFunctionCalls - Resolve the function calls that just got
              // inlined...
              //
              Changed |= ResolveFunctionCalls(G, NumCalls, InProcess, Indent+1);
              
              // Now that we are done processing the inlined graph, remove our
              // cycle detector record...
              //
              //InProcess.erase(I);
            }
          }
        }
      }

      if (hasExternalTarget) {
        // If we cannot resolve this call site...
        ++FirstResolvableCall;
      } else {
        Changed = true;
        FCs.erase(FCs.begin()+FirstResolvableCall);
      }
    }
  }

  return Changed;
}

DSGraph &BUDataStructures::calculateGraph(Function &F, unsigned Indent) {
  // Make sure this graph has not already been calculated, or that we don't get
  // into an infinite loop with mutually recursive functions.
  //
  DSGraph *&GraphPtr = DSInfo[&F];
  if (GraphPtr) return *GraphPtr;

  // Copy the local version into DSInfo...
  GraphPtr = new DSGraph(getAnalysis<LocalDataStructures>().getDSGraph(F));
  DSGraph &Graph = *GraphPtr;

  Graph.setGlobalsGraph(GlobalsGraph);
  Graph.setPrintAuxCalls();

  // Start resolving calls...
  std::vector<DSCallSite> &FCs = Graph.getAuxFunctionCalls();

  // Start with a copy of the original call sites...
  FCs = Graph.getFunctionCalls();

  DEBUG(std::cerr << std::string(Indent*2, ' ')
                  << "[BU] Calculating graph for: " << F.getName() << "\n");

  bool Changed;
  while (1) {
    unsigned FirstResolvableCall = 0;
    std::map<Function *, DSCallSite> InProcess;

    // Insert a call site for self to handle self recursion...
    std::vector<DSNodeHandle> Args;
    Args.reserve(F.asize());
    for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
      if (isPointerType(I->getType()))
        Args.push_back(Graph.getNodeForValue(I));

    InProcess.insert(std::make_pair(&F, 
           DSCallSite(*(CallInst*)0, Graph.getRetNode(),(DSNode*)0,Args)));

    Changed = ResolveFunctionCalls(Graph, FirstResolvableCall, InProcess,
                                   Indent);

    if (Changed) {
      Graph.maskIncompleteMarkers();
      Graph.markIncompleteNodes();
      Graph.removeDeadNodes();
      break;
    } else {
      break;
    }
  }

#if 0  
  bool Inlined;
  do {
    Inlined = false;

    for (unsigned i = 0; i != FCs.size(); ++i) {
      // Copy the call, because inlining graphs may invalidate the FCs vector.
      DSCallSite Call = FCs[i];

      // If the function list is complete...
      if ((Call.getCallee().getNode()->NodeType & DSNode::Incomplete)==0) {
        // Start inlining all of the functions we can... some may not be
        // inlinable if they are external...
        //
        std::vector<GlobalValue*> Callees =
          Call.getCallee().getNode()->getGlobals();

        unsigned OldNumCalls = FCs.size();

        // Loop over the functions, inlining whatever we can...
        for (unsigned c = 0; c != Callees.size(); ++c) {
          // Must be a function type, so this cast MUST succeed.
          Function &FI = cast<Function>(*Callees[c]);

          if (&FI == &F) {
            // Self recursion... simply link up the formal arguments with the
            // actual arguments...
            DEBUG(std::cerr << std::string(Indent*2, ' ')
                  << "[BU] Self Inlining: " << F.getName() << "\n");

            // Handle self recursion by resolving the arguments and return value
            Graph.mergeInGraph(Call, Graph, DSGraph::StripAllocaBit);

            // Erase the entry in the callees vector
            Callees.erase(Callees.begin()+c--);

          } else if (!FI.isExternal()) {
            DEBUG(std::cerr << std::string(Indent*2, ' ')
                  << "[BU] In " << F.getName() << " inlining: "
                  << FI.getName() << "\n");
            
            // Get the data structure graph for the called function, closing it
            // if possible (which is only impossible in the case of mutual
            // recursion...
            //
            DSGraph &GI = calculateGraph(FI, Indent+1);  // Graph to inline

            DEBUG(std::cerr << std::string(Indent*2, ' ')
                  << "[BU] Got graph for " << FI.getName()
                  << " in: " << F.getName() << "[" << GI.getGraphSize() << "+"
                  << GI.getAuxFunctionCalls().size() << "]\n");

            // Handle self recursion by resolving the arguments and return value
            Graph.mergeInGraph(Call, GI, DSGraph::StripAllocaBit |
                                DSGraph::DontCloneCallNodes);

            // Erase the entry in the Callees vector
            Callees.erase(Callees.begin()+c--);

          } else if (FI.getName() == "printf" || FI.getName() == "sscanf" ||
                     FI.getName() == "fprintf" || FI.getName() == "open" ||
                     FI.getName() == "sprintf" || FI.getName() == "fputs") {