blob: 426541288b50439f67564f9c0fa6a81dfa2bd022 [file] [log] [blame]
Chris Lattner64fd9352002-03-28 18:08:31 +00001//===-- PoolAllocate.cpp - Pool Allocation Pass ---------------------------===//
2//
3// This transform changes programs so that disjoint data structures are
4// allocated out of different pools of memory, increasing locality and shrinking
5// pointer size.
6//
7//===----------------------------------------------------------------------===//
8
9#include "llvm/Transforms/IPO/PoolAllocate.h"
Chris Lattner291a1b12002-03-29 19:05:48 +000010#include "llvm/Transforms/CloneFunction.h"
Chris Lattner64fd9352002-03-28 18:08:31 +000011#include "llvm/Analysis/DataStructure.h"
Chris Lattner396d5d72002-03-30 04:02:31 +000012#include "llvm/Analysis/DataStructureGraph.h"
Chris Lattner64fd9352002-03-28 18:08:31 +000013#include "llvm/Pass.h"
Chris Lattner175f37c2002-03-29 03:40:59 +000014#include "llvm/Module.h"
15#include "llvm/Function.h"
16#include "llvm/iMemory.h"
Chris Lattnere0618ca2002-03-29 05:50:20 +000017#include "llvm/iTerminators.h"
18#include "llvm/iOther.h"
19#include "llvm/ConstantVals.h"
20#include "llvm/Target/TargetData.h"
Chris Lattnerf32d65d2002-03-29 21:25:19 +000021#include "llvm/Support/InstVisitor.h"
Chris Lattner396d5d72002-03-30 04:02:31 +000022#include "Support/DepthFirstIterator.h"
Chris Lattnere0618ca2002-03-29 05:50:20 +000023#include "Support/STLExtras.h"
Chris Lattner175f37c2002-03-29 03:40:59 +000024#include <algorithm>
Chris Lattner64fd9352002-03-28 18:08:31 +000025
Chris Lattner692ad5d2002-03-29 17:13:46 +000026
Chris Lattnere0618ca2002-03-29 05:50:20 +000027// FIXME: This is dependant on the sparc backend layout conventions!!
28static TargetData TargetData("test");
29
Chris Lattner64fd9352002-03-28 18:08:31 +000030namespace {
Chris Lattner692ad5d2002-03-29 17:13:46 +000031 // ScalarInfo - Information about an LLVM value that we know points to some
32 // datastructure we are processing.
33 //
34 struct ScalarInfo {
Chris Lattnerca9f4d32002-03-30 09:12:35 +000035 Value *Val; // Scalar value in Current Function
36 DSNode *Node; // DataStructure node it points to
37 Value *PoolHandle; // PoolTy* LLVM value
Chris Lattner692ad5d2002-03-29 17:13:46 +000038
Chris Lattnerca9f4d32002-03-30 09:12:35 +000039 ScalarInfo(Value *V, DSNode *N, Value *PH)
40 : Val(V), Node(N), PoolHandle(PH) {
41 assert(V && N && PH && "Null value passed to ScalarInfo ctor!");
42 }
Chris Lattner692ad5d2002-03-29 17:13:46 +000043 };
44
Chris Lattner396d5d72002-03-30 04:02:31 +000045 // CallArgInfo - Information on one operand for a call that got expanded.
46 struct CallArgInfo {
Chris Lattnerca9f4d32002-03-30 09:12:35 +000047 int ArgNo; // Call argument number this corresponds to
48 DSNode *Node; // The graph node for the pool
49 Value *PoolHandle; // The LLVM value that is the pool pointer
Chris Lattner396d5d72002-03-30 04:02:31 +000050
Chris Lattnerca9f4d32002-03-30 09:12:35 +000051 CallArgInfo(int Arg, DSNode *N, Value *PH)
52 : ArgNo(Arg), Node(N), PoolHandle(PH) {
53 assert(Arg >= -1 && N && PH && "Illegal values to CallArgInfo ctor!");
Chris Lattner396d5d72002-03-30 04:02:31 +000054 }
55
Chris Lattnerca9f4d32002-03-30 09:12:35 +000056 // operator< when sorting, sort by argument number.
Chris Lattner396d5d72002-03-30 04:02:31 +000057 bool operator<(const CallArgInfo &CAI) const {
58 return ArgNo < CAI.ArgNo;
59 }
60 };
61
Chris Lattner692ad5d2002-03-29 17:13:46 +000062 // TransformFunctionInfo - Information about how a function eeds to be
63 // transformed.
64 //
65 struct TransformFunctionInfo {
66 // ArgInfo - Maintain information about the arguments that need to be
67 // processed. Each pair corresponds to an argument (whose number is the
68 // first element) that needs to have a pool pointer (the second element)
69 // passed into the transformed function with it.
70 //
71 // As a special case, "argument" number -1 corresponds to the return value.
72 //
Chris Lattner396d5d72002-03-30 04:02:31 +000073 vector<CallArgInfo> ArgInfo;
Chris Lattner692ad5d2002-03-29 17:13:46 +000074
75 // Func - The function to be transformed...
76 Function *Func;
77
Chris Lattnerca9f4d32002-03-30 09:12:35 +000078 // The call instruction that is used to map CallArgInfo PoolHandle values
79 // into the new function values.
80 CallInst *Call;
81
Chris Lattner692ad5d2002-03-29 17:13:46 +000082 // default ctor...
Chris Lattnerca9f4d32002-03-30 09:12:35 +000083 TransformFunctionInfo() : Func(0), Call(0) {}
Chris Lattner692ad5d2002-03-29 17:13:46 +000084
Chris Lattner396d5d72002-03-30 04:02:31 +000085 bool operator<(const TransformFunctionInfo &TFI) const {
Chris Lattner291a1b12002-03-29 19:05:48 +000086 if (Func < TFI.Func) return true;
87 if (Func > TFI.Func) return false;
Chris Lattner291a1b12002-03-29 19:05:48 +000088 if (ArgInfo.size() < TFI.ArgInfo.size()) return true;
89 if (ArgInfo.size() > TFI.ArgInfo.size()) return false;
Chris Lattner396d5d72002-03-30 04:02:31 +000090 return ArgInfo < TFI.ArgInfo;
Chris Lattner692ad5d2002-03-29 17:13:46 +000091 }
92
93 void finalizeConstruction() {
94 // Sort the vector so that the return value is first, followed by the
Chris Lattnerca9f4d32002-03-30 09:12:35 +000095 // argument records, in order. Note that this must be a stable sort so
96 // that the entries with the same sorting criteria (ie they are multiple
97 // pool entries for the same argument) are kept in depth first order.
98 stable_sort(ArgInfo.begin(), ArgInfo.end());
Chris Lattner692ad5d2002-03-29 17:13:46 +000099 }
100 };
101
102
103 // Define the pass class that we implement...
Chris Lattner175f37c2002-03-29 03:40:59 +0000104 class PoolAllocate : public Pass {
105 // PoolTy - The type of a scalar value that contains a pool pointer.
106 PointerType *PoolTy;
107 public:
108
109 PoolAllocate() {
110 // Initialize the PoolTy instance variable, since the type never changes.
111 vector<const Type*> PoolElements;
112 PoolElements.push_back(PointerType::get(Type::SByteTy));
113 PoolElements.push_back(Type::UIntTy);
114 PoolTy = PointerType::get(StructType::get(PoolElements));
115 // PoolTy = { sbyte*, uint }*
116
117 CurModule = 0; DS = 0;
118 PoolInit = PoolDestroy = PoolAlloc = PoolFree = 0;
Chris Lattner64fd9352002-03-28 18:08:31 +0000119 }
120
Chris Lattner175f37c2002-03-29 03:40:59 +0000121 bool run(Module *M);
122
123 // getAnalysisUsageInfo - This function requires data structure information
124 // to be able to see what is pool allocatable.
Chris Lattner64fd9352002-03-28 18:08:31 +0000125 //
126 virtual void getAnalysisUsageInfo(Pass::AnalysisSet &Required,
Chris Lattner175f37c2002-03-29 03:40:59 +0000127 Pass::AnalysisSet &,Pass::AnalysisSet &) {
Chris Lattner64fd9352002-03-28 18:08:31 +0000128 Required.push_back(DataStructure::ID);
129 }
Chris Lattner175f37c2002-03-29 03:40:59 +0000130
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000131 public:
Chris Lattner175f37c2002-03-29 03:40:59 +0000132 // CurModule - The module being processed.
133 Module *CurModule;
134
135 // DS - The data structure graph for the module being processed.
136 DataStructure *DS;
137
138 // Prototypes that we add to support pool allocation...
139 Function *PoolInit, *PoolDestroy, *PoolAlloc, *PoolFree;
140
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000141 // The map of already transformed functions... note that the keys of this
142 // map do not have meaningful values for 'Call' or the 'PoolHandle' elements
143 // of the ArgInfo elements.
144 //
Chris Lattner692ad5d2002-03-29 17:13:46 +0000145 map<TransformFunctionInfo, Function*> TransformedFunctions;
146
147 // getTransformedFunction - Get a transformed function, or return null if
148 // the function specified hasn't been transformed yet.
149 //
150 Function *getTransformedFunction(TransformFunctionInfo &TFI) const {
151 map<TransformFunctionInfo, Function*>::const_iterator I =
152 TransformedFunctions.find(TFI);
153 if (I != TransformedFunctions.end()) return I->second;
154 return 0;
155 }
156
157
Chris Lattner175f37c2002-03-29 03:40:59 +0000158 // addPoolPrototypes - Add prototypes for the pool methods to the specified
159 // module and update the Pool* instance variables to point to them.
160 //
161 void addPoolPrototypes(Module *M);
162
Chris Lattner66df97d2002-03-29 06:21:38 +0000163
164 // CreatePools - Insert instructions into the function we are processing to
165 // create all of the memory pool objects themselves. This also inserts
166 // destruction code. Add an alloca for each pool that is allocated to the
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000167 // PoolDescriptors map.
Chris Lattner66df97d2002-03-29 06:21:38 +0000168 //
169 void CreatePools(Function *F, const vector<AllocDSNode*> &Allocs,
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000170 map<DSNode*, Value*> &PoolDescriptors);
Chris Lattner66df97d2002-03-29 06:21:38 +0000171
Chris Lattner175f37c2002-03-29 03:40:59 +0000172 // processFunction - Convert a function to use pool allocation where
173 // available.
174 //
175 bool processFunction(Function *F);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000176
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000177 // transformFunctionBody - This transforms the instruction in 'F' to use the
178 // pools specified in PoolDescriptors when modifying data structure nodes
179 // specified in the PoolDescriptors map. IPFGraph is the closed data
180 // structure graph for F, of which the PoolDescriptor nodes come from.
181 //
182 void transformFunctionBody(Function *F, FunctionDSGraph &IPFGraph,
183 map<DSNode*, Value*> &PoolDescriptors);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000184
185 // transformFunction - Transform the specified function the specified way.
186 // It we have already transformed that function that way, don't do anything.
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000187 // The nodes in the TransformFunctionInfo come out of callers data structure
188 // graph.
Chris Lattner692ad5d2002-03-29 17:13:46 +0000189 //
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000190 void transformFunction(TransformFunctionInfo &TFI,
191 FunctionDSGraph &CallerIPGraph);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000192
Chris Lattner64fd9352002-03-28 18:08:31 +0000193 };
194}
195
Chris Lattner175f37c2002-03-29 03:40:59 +0000196
197
Chris Lattner692ad5d2002-03-29 17:13:46 +0000198// isNotPoolableAlloc - This is a predicate that returns true if the specified
Chris Lattner175f37c2002-03-29 03:40:59 +0000199// allocation node in a data structure graph is eligable for pool allocation.
200//
201static bool isNotPoolableAlloc(const AllocDSNode *DS) {
Chris Lattnere0618ca2002-03-29 05:50:20 +0000202 if (DS->isAllocaNode()) return true; // Do not pool allocate alloca's.
Chris Lattner175f37c2002-03-29 03:40:59 +0000203
204 MallocInst *MI = cast<MallocInst>(DS->getAllocation());
205 if (MI->isArrayAllocation() && !isa<Constant>(MI->getArraySize()))
Chris Lattnere0618ca2002-03-29 05:50:20 +0000206 return true; // Do not allow variable size allocations...
Chris Lattner175f37c2002-03-29 03:40:59 +0000207
Chris Lattnere0618ca2002-03-29 05:50:20 +0000208 return false;
Chris Lattner175f37c2002-03-29 03:40:59 +0000209}
210
Chris Lattner175f37c2002-03-29 03:40:59 +0000211// processFunction - Convert a function to use pool allocation where
212// available.
213//
214bool PoolAllocate::processFunction(Function *F) {
215 // Get the closed datastructure graph for the current function... if there are
216 // any allocations in this graph that are not escaping, we need to pool
217 // allocate them here!
218 //
219 FunctionDSGraph &IPGraph = DS->getClosedDSGraph(F);
220
221 // Get all of the allocations that do not escape the current function. Since
222 // they are still live (they exist in the graph at all), this means we must
223 // have scalar references to these nodes, but the scalars are never returned.
224 //
Chris Lattner692ad5d2002-03-29 17:13:46 +0000225 vector<AllocDSNode*> Allocs;
Chris Lattner175f37c2002-03-29 03:40:59 +0000226 IPGraph.getNonEscapingAllocations(Allocs);
227
228 // Filter out allocations that we cannot handle. Currently, this includes
229 // variable sized array allocations and alloca's (which we do not want to
230 // pool allocate)
231 //
232 Allocs.erase(remove_if(Allocs.begin(), Allocs.end(), isNotPoolableAlloc),
233 Allocs.end());
234
235
236 if (Allocs.empty()) return false; // Nothing to do.
237
Chris Lattner692ad5d2002-03-29 17:13:46 +0000238 // Insert instructions into the function we are processing to create all of
239 // the memory pool objects themselves. This also inserts destruction code.
Chris Lattner396d5d72002-03-30 04:02:31 +0000240 // This fills in the PoolDescriptors map to associate the alloc node with the
241 // allocation of the memory pool corresponding to it.
Chris Lattner692ad5d2002-03-29 17:13:46 +0000242 //
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000243 map<DSNode*, Value*> PoolDescriptors;
Chris Lattner692ad5d2002-03-29 17:13:46 +0000244 CreatePools(F, Allocs, PoolDescriptors);
245
Chris Lattner692ad5d2002-03-29 17:13:46 +0000246 // Now we need to figure out what called methods we need to transform, and
247 // how. To do this, we look at all of the scalars, seeing which functions are
248 // either used as a scalar value (so they return a data structure), or are
249 // passed one of our scalar values.
250 //
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000251 transformFunctionBody(F, IPGraph, PoolDescriptors);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000252
253 return true;
254}
255
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000256
257class FunctionBodyTransformer : public InstVisitor<FunctionBodyTransformer> {
258 PoolAllocate &PoolAllocator;
259 vector<ScalarInfo> &Scalars;
260 map<CallInst*, TransformFunctionInfo> &CallMap;
261
262 const ScalarInfo &getScalar(const Value *V) {
263 for (unsigned i = 0, e = Scalars.size(); i != e; ++i)
264 if (Scalars[i].Val == V) return Scalars[i];
265 assert(0 && "Scalar not found in getScalar!");
266 abort();
267 return Scalars[0];
268 }
269
270 // updateScalars - Map the scalars array entries that look like 'From' to look
271 // like 'To'.
272 //
273 void updateScalars(Value *From, Value *To) {
274 for (unsigned i = 0, e = Scalars.size(); i != e; ++i)
275 if (Scalars[i].Val == From) Scalars[i].Val = To;
276 }
277
278public:
279 FunctionBodyTransformer(PoolAllocate &PA, vector<ScalarInfo> &S,
280 map<CallInst*, TransformFunctionInfo> &C)
281 : PoolAllocator(PA), Scalars(S), CallMap(C) {}
282
283 void visitMemAccessInst(MemAccessInst *MAI) {
284 // Don't do anything to load, store, or GEP yet...
285 }
286
287 // Convert a malloc instruction into a call to poolalloc
288 void visitMallocInst(MallocInst *I) {
289 const ScalarInfo &SC = getScalar(I);
290 BasicBlock *BB = I->getParent();
291 BasicBlock::iterator MI = find(BB->begin(), BB->end(), I);
292 BB->getInstList().remove(MI); // Remove the Malloc instruction from the BB
293
294 // Create a new call to poolalloc before the malloc instruction
295 vector<Value*> Args;
296 Args.push_back(SC.PoolHandle);
297 CallInst *Call = new CallInst(PoolAllocator.PoolAlloc, Args, I->getName());
298 MI = BB->getInstList().insert(MI, Call)+1;
299
300 // If the type desired is not void*, cast it now...
301 Value *Ptr = Call;
302 if (Call->getType() != I->getType()) {
303 CastInst *CI = new CastInst(Ptr, I->getType(), I->getName());
304 BB->getInstList().insert(MI, CI);
305 Ptr = CI;
306 }
307
308 // Change everything that used the malloc to now use the pool alloc...
309 I->replaceAllUsesWith(Ptr);
310
311 // Update the scalars array...
312 updateScalars(I, Ptr);
313
314 // Delete the instruction now.
315 delete I;
316 }
317
318 // Convert the free instruction into a call to poolfree
319 void visitFreeInst(FreeInst *I) {
320 Value *Ptr = I->getOperand(0);
321 const ScalarInfo &SC = getScalar(Ptr);
322 BasicBlock *BB = I->getParent();
323 BasicBlock::iterator FI = find(BB->begin(), BB->end(), I);
324
325 // If the value is not an sbyte*, convert it now!
326 if (Ptr->getType() != PointerType::get(Type::SByteTy)) {
327 CastInst *CI = new CastInst(Ptr, PointerType::get(Type::SByteTy),
328 Ptr->getName());
329 FI = BB->getInstList().insert(FI, CI)+1;
330 Ptr = CI;
331 }
332
333 // Create a new call to poolfree before the free instruction
334 vector<Value*> Args;
335 Args.push_back(SC.PoolHandle);
336 Args.push_back(Ptr);
337 CallInst *Call = new CallInst(PoolAllocator.PoolFree, Args);
338 FI = BB->getInstList().insert(FI, Call)+1;
339
340 // Remove the old free instruction...
341 delete BB->getInstList().remove(FI);
342 }
343
344 // visitCallInst - Create a new call instruction with the extra arguments for
345 // all of the memory pools that the call needs.
346 //
347 void visitCallInst(CallInst *I) {
348 TransformFunctionInfo &TI = CallMap[I];
349 BasicBlock *BB = I->getParent();
350 BasicBlock::iterator CI = find(BB->begin(), BB->end(), I);
351 BB->getInstList().remove(CI); // Remove the old call instruction
352
353 // Start with all of the old arguments...
354 vector<Value*> Args(I->op_begin()+1, I->op_end());
355
356 // Add all of the pool arguments...
357 for (unsigned i = 0, e = TI.ArgInfo.size(); i != e; ++i)
Chris Lattner396d5d72002-03-30 04:02:31 +0000358 Args.push_back(TI.ArgInfo[i].PoolHandle);
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000359
360 Function *NF = PoolAllocator.getTransformedFunction(TI);
361 CallInst *NewCall = new CallInst(NF, Args, I->getName());
362 BB->getInstList().insert(CI, NewCall);
363
364 // Change everything that used the malloc to now use the pool alloc...
365 if (I->getType() != Type::VoidTy) {
366 I->replaceAllUsesWith(NewCall);
367
368 // Update the scalars array...
369 updateScalars(I, NewCall);
370 }
371
372 delete I; // Delete the old call instruction now...
373 }
374
Chris Lattner396d5d72002-03-30 04:02:31 +0000375 void visitPHINode(PHINode *PN) {
376 // Handle PHI Node
377 }
378
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000379 void visitInstruction(Instruction *I) {
380 cerr << "Unknown instruction to FunctionBodyTransformer:\n";
381 I->dump();
382 }
383
384};
385
386
Chris Lattner396d5d72002-03-30 04:02:31 +0000387static void addCallInfo(TransformFunctionInfo &TFI, CallInst *CI, int Arg,
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000388 DSNode *GraphNode,
389 map<DSNode*, Value*> &PoolDescriptors) {
Chris Lattner396d5d72002-03-30 04:02:31 +0000390
391 // For now, add the entire graph that is pointed to by the call argument.
392 // This graph can and should be pruned to only what the function itself will
393 // use, because often this will be a dramatically smaller subset of what we
394 // are providing.
395 //
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000396 for (df_iterator<DSNode*> I = df_begin(GraphNode), E = df_end(GraphNode);
Chris Lattner396d5d72002-03-30 04:02:31 +0000397 I != E; ++I) {
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000398 TFI.ArgInfo.push_back(CallArgInfo(Arg, *I, PoolDescriptors[*I]));
Chris Lattner396d5d72002-03-30 04:02:31 +0000399 }
400
401 assert(CI->getCalledFunction() && "Cannot handle indirect calls yet!");
402 assert(TFI.Func == 0 || TFI.Func == CI->getCalledFunction() &&
403 "Function call record should always call the same function!");
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000404 assert(TFI.Call == 0 || TFI.Call == CI &&
405 "Call element already filled in with different value!");
Chris Lattner396d5d72002-03-30 04:02:31 +0000406 TFI.Func = CI->getCalledFunction();
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000407 TFI.Call = CI;
Chris Lattner396d5d72002-03-30 04:02:31 +0000408}
409
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000410
411// transformFunctionBody - This transforms the instruction in 'F' to use the
412// pools specified in PoolDescriptors when modifying data structure nodes
413// specified in the PoolDescriptors map. Specifically, scalar values specified
414// in the Scalars vector must be remapped. IPFGraph is the closed data
415// structure graph for F, of which the PoolDescriptor nodes come from.
416//
417void PoolAllocate::transformFunctionBody(Function *F, FunctionDSGraph &IPFGraph,
418 map<DSNode*, Value*> &PoolDescriptors) {
419
420 // Loop through the value map looking for scalars that refer to nonescaping
421 // allocations. Add them to the Scalars vector. Note that we may have
422 // multiple entries in the Scalars vector for each value if it points to more
423 // than one object.
424 //
425 map<Value*, PointerValSet> &ValMap = IPFGraph.getValueMap();
426 vector<ScalarInfo> Scalars;
427
428 for (map<Value*, PointerValSet>::iterator I = ValMap.begin(),
429 E = ValMap.end(); I != E; ++I) {
430 const PointerValSet &PVS = I->second; // Set of things pointed to by scalar
431
432 assert(PVS.size() == 1 &&
433 "Only handle scalars that point to one thing so far!");
434
435 // Check to see if the scalar points to a data structure node...
436 for (unsigned i = 0, e = PVS.size(); i != e; ++i) {
437 assert(PVS[i].Index == 0 && "Nonzero not handled yet!");
438
439 // If the allocation is in the nonescaping set...
440 map<DSNode*, Value*>::iterator AI = PoolDescriptors.find(PVS[i].Node);
441 if (AI != PoolDescriptors.end()) // Add it to the list of scalars
442 Scalars.push_back(ScalarInfo(I->first, PVS[i].Node, AI->second));
443 }
444 }
445
446
447
Chris Lattner175f37c2002-03-29 03:40:59 +0000448 cerr << "In '" << F->getName()
449 << "': Found the following values that point to poolable nodes:\n";
450
451 for (unsigned i = 0, e = Scalars.size(); i != e; ++i)
Chris Lattner692ad5d2002-03-29 17:13:46 +0000452 Scalars[i].Val->dump();
Chris Lattnere0618ca2002-03-29 05:50:20 +0000453
Chris Lattner692ad5d2002-03-29 17:13:46 +0000454 // CallMap - Contain an entry for every call instruction that needs to be
455 // transformed. Each entry in the map contains information about what we need
456 // to do to each call site to change it to work.
457 //
458 map<CallInst*, TransformFunctionInfo> CallMap;
Chris Lattner66df97d2002-03-29 06:21:38 +0000459
Chris Lattner692ad5d2002-03-29 17:13:46 +0000460 // Now we need to figure out what called methods we need to transform, and
461 // how. To do this, we look at all of the scalars, seeing which functions are
462 // either used as a scalar value (so they return a data structure), or are
463 // passed one of our scalar values.
464 //
465 for (unsigned i = 0, e = Scalars.size(); i != e; ++i) {
466 Value *ScalarVal = Scalars[i].Val;
467
468 // Check to see if the scalar _IS_ a call...
469 if (CallInst *CI = dyn_cast<CallInst>(ScalarVal))
470 // If so, add information about the pool it will be returning...
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000471 addCallInfo(CallMap[CI], CI, -1, Scalars[i].Node, PoolDescriptors);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000472
473 // Check to see if the scalar is an operand to a call...
474 for (Value::use_iterator UI = ScalarVal->use_begin(),
475 UE = ScalarVal->use_end(); UI != UE; ++UI) {
476 if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
477 // Find out which operand this is to the call instruction...
478 User::op_iterator OI = find(CI->op_begin(), CI->op_end(), ScalarVal);
479 assert(OI != CI->op_end() && "Call on use list but not an operand!?");
480 assert(OI != CI->op_begin() && "Pointer operand is call destination?");
481
482 // FIXME: This is broken if the same pointer is passed to a call more
483 // than once! It will get multiple entries for the first pointer.
484
485 // Add the operand number and pool handle to the call table...
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000486 addCallInfo(CallMap[CI], CI, OI-CI->op_begin()-1, Scalars[i].Node,
Chris Lattner396d5d72002-03-30 04:02:31 +0000487 PoolDescriptors);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000488 }
489 }
490 }
491
492 // Print out call map...
493 for (map<CallInst*, TransformFunctionInfo>::iterator I = CallMap.begin();
494 I != CallMap.end(); ++I) {
495 cerr << "\nFor call: ";
496 I->first->dump();
497 I->second.finalizeConstruction();
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000498 cerr << I->second.Func->getName() << " must pass pool pointer for args #";
Chris Lattner692ad5d2002-03-29 17:13:46 +0000499 for (unsigned i = 0; i < I->second.ArgInfo.size(); ++i)
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000500 cerr << I->second.ArgInfo[i].ArgNo << ", ";
Chris Lattner692ad5d2002-03-29 17:13:46 +0000501 cerr << "\n";
502 }
503
504 // Loop through all of the call nodes, recursively creating the new functions
505 // that we want to call... This uses a map to prevent infinite recursion and
506 // to avoid duplicating functions unneccesarily.
507 //
508 for (map<CallInst*, TransformFunctionInfo>::iterator I = CallMap.begin(),
509 E = CallMap.end(); I != E; ++I) {
510 // Make sure the entries are sorted.
511 I->second.finalizeConstruction();
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000512
513 // Transform all of the functions we need, or at least ensure there is a
514 // cached version available.
515 transformFunction(I->second, IPFGraph);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000516 }
517
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000518 // Now that all of the functions that we want to call are available, transform
519 // the local method so that it uses the pools locally and passes them to the
520 // functions that we just hacked up.
521 //
522
523 // First step, find the instructions to be modified.
524 vector<Instruction*> InstToFix;
525 for (unsigned i = 0, e = Scalars.size(); i != e; ++i) {
526 Value *ScalarVal = Scalars[i].Val;
527
528 // Check to see if the scalar _IS_ an instruction. If so, it is involved.
529 if (Instruction *Inst = dyn_cast<Instruction>(ScalarVal))
530 InstToFix.push_back(Inst);
531
532 // All all of the instructions that use the scalar as an operand...
533 for (Value::use_iterator UI = ScalarVal->use_begin(),
534 UE = ScalarVal->use_end(); UI != UE; ++UI)
535 InstToFix.push_back(dyn_cast<Instruction>(*UI));
536 }
537
538 // Eliminate duplicates by sorting, then removing equal neighbors.
539 sort(InstToFix.begin(), InstToFix.end());
540 InstToFix.erase(unique(InstToFix.begin(), InstToFix.end()), InstToFix.end());
541
542 // Use a FunctionBodyTransformer to transform all of the involved instructions
543 FunctionBodyTransformer FBT(*this, Scalars, CallMap);
544 for (unsigned i = 0, e = InstToFix.size(); i != e; ++i)
545 FBT.visit(InstToFix[i]);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000546
547
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000548 // Since we have liberally hacked the function to pieces, we want to inform
549 // the datastructure pass that its internal representation is out of date.
550 //
551 DS->invalidateFunction(F);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000552}
553
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000554static void addNodeMapping(DSNode *SrcNode, const PointerValSet &PVS,
555 map<DSNode*, PointerValSet> &NodeMapping) {
556 for (unsigned i = 0, e = PVS.size(); i != e; ++i)
557 if (NodeMapping[SrcNode].add(PVS[i])) { // Not in map yet?
558 assert(PVS[i].Index == 0 && "Node indexing not supported yet!");
559 DSNode *DestNode = PVS[i].Node;
Chris Lattner692ad5d2002-03-29 17:13:46 +0000560
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000561 // Loop over all of the outgoing links in the mapped graph
562 for (unsigned l = 0, le = DestNode->getNumOutgoingLinks(); l != le; ++l) {
563 PointerValSet &SrcSet = SrcNode->getOutgoingLink(l);
564 const PointerValSet &DestSet = DestNode->getOutgoingLink(l);
565 assert((!SrcSet.empty() || DestSet.empty()) &&
566 "Dest graph should be a proper subset of the src graph!");
567
568 // Add all of the node mappings now!
569 for (unsigned si = 0, se = SrcSet.size(); si != se; ++si) {
570 assert(SrcSet[si].Index == 0 && "Can't handle node offset!");
571 addNodeMapping(SrcSet[si].Node, DestSet, NodeMapping);
572 }
573 }
574 }
575}
576
577// CalculateNodeMapping - There is a partial isomorphism between the graph
578// passed in and the graph that is actually used by the function. We need to
579// figure out what this mapping is so that we can transformFunctionBody the
580// instructions in the function itself. Note that every node in the graph that
581// we are interested in must be both in the local graph of the called function,
582// and in the local graph of the calling function. Because of this, we only
583// define the mapping for these nodes [conveniently these are the only nodes we
584// CAN define a mapping for...]
Chris Lattner692ad5d2002-03-29 17:13:46 +0000585//
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000586// The roots of the graph that we are transforming is rooted in the arguments
587// passed into the function from the caller. This is where we start our
588// mapping calculation.
589//
590// The NodeMapping calculated maps from the callers graph to the called graph.
591//
592static void CalculateNodeMapping(TransformFunctionInfo &TFI,
593 FunctionDSGraph &CallerGraph,
594 FunctionDSGraph &CalledGraph,
595 map<DSNode*, PointerValSet> &NodeMapping) {
596 int LastArgNo = -2;
597 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i) {
598 // Figure out what nodes in the called graph the TFI.ArgInfo[i].Node node
599 // corresponds to...
600 //
601 // Only consider first node of sequence. Extra nodes may may be added
602 // to the TFI if the data structure requires more nodes than just the
603 // one the argument points to. We are only interested in the one the
604 // argument points to though.
605 //
606 if (TFI.ArgInfo[i].ArgNo != LastArgNo) {
607 if (TFI.ArgInfo[i].ArgNo == -1) {
608 addNodeMapping(TFI.ArgInfo[i].Node, CalledGraph.getRetNodes(),
609 NodeMapping);
610 } else {
611 // Figure out which node argument # ArgNo points to in the called graph.
612 Value *Arg = TFI.Func->getArgumentList()[TFI.ArgInfo[i].ArgNo];
613 addNodeMapping(TFI.ArgInfo[i].Node, CalledGraph.getValueMap()[Arg],
614 NodeMapping);
615 }
616 LastArgNo = TFI.ArgInfo[i].ArgNo;
617 }
618 }
619}
620
621
622// transformFunction - Transform the specified function the specified way. It
623// we have already transformed that function that way, don't do anything. The
624// nodes in the TransformFunctionInfo come out of callers data structure graph.
625//
626void PoolAllocate::transformFunction(TransformFunctionInfo &TFI,
627 FunctionDSGraph &CallerIPGraph) {
Chris Lattner692ad5d2002-03-29 17:13:46 +0000628 if (getTransformedFunction(TFI)) return; // Function xformation already done?
629
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000630 const FunctionType *OldFuncType = TFI.Func->getFunctionType();
Chris Lattner692ad5d2002-03-29 17:13:46 +0000631
Chris Lattner291a1b12002-03-29 19:05:48 +0000632 assert(!OldFuncType->isVarArg() && "Vararg functions not handled yet!");
Chris Lattner692ad5d2002-03-29 17:13:46 +0000633
Chris Lattner291a1b12002-03-29 19:05:48 +0000634 // Build the type for the new function that we are transforming
635 vector<const Type*> ArgTys;
636 for (unsigned i = 0, e = OldFuncType->getNumParams(); i != e; ++i)
637 ArgTys.push_back(OldFuncType->getParamType(i));
638
639 // Add one pool pointer for every argument that needs to be supplemented.
640 ArgTys.insert(ArgTys.end(), TFI.ArgInfo.size(), PoolTy);
641
642 // Build the new function type...
643 const // FIXME when types are not const
644 FunctionType *NewFuncType = FunctionType::get(OldFuncType->getReturnType(),
645 ArgTys,OldFuncType->isVarArg());
646
647 // The new function is internal, because we know that only we can call it.
648 // This also helps subsequent IP transformations to eliminate duplicated pool
649 // pointers. [in the future when they are implemented].
650 //
651 Function *NewFunc = new Function(NewFuncType, true,
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000652 TFI.Func->getName()+".poolxform");
Chris Lattner291a1b12002-03-29 19:05:48 +0000653 CurModule->getFunctionList().push_back(NewFunc);
654
655 // Add the newly formed function to the TransformedFunctions table so that
656 // infinite recursion does not occur!
657 //
658 TransformedFunctions[TFI] = NewFunc;
659
660 // Add arguments to the function... starting with all of the old arguments
661 vector<Value*> ArgMap;
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000662 for (unsigned i = 0, e = TFI.Func->getArgumentList().size(); i != e; ++i) {
663 const FunctionArgument *OFA = TFI.Func->getArgumentList()[i];
Chris Lattner291a1b12002-03-29 19:05:48 +0000664 FunctionArgument *NFA = new FunctionArgument(OFA->getType(),OFA->getName());
665 NewFunc->getArgumentList().push_back(NFA);
666 ArgMap.push_back(NFA); // Keep track of the arguments
667 }
668
669 // Now add all of the arguments corresponding to pools passed in...
670 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i) {
671 string Name;
Chris Lattner396d5d72002-03-30 04:02:31 +0000672 if (TFI.ArgInfo[i].ArgNo == -1)
Chris Lattner291a1b12002-03-29 19:05:48 +0000673 Name = "retpool";
674 else
Chris Lattner396d5d72002-03-30 04:02:31 +0000675 Name = ArgMap[TFI.ArgInfo[i].ArgNo]->getName(); // Get the arg name
Chris Lattner291a1b12002-03-29 19:05:48 +0000676 FunctionArgument *NFA = new FunctionArgument(PoolTy, Name+".pool");
677 NewFunc->getArgumentList().push_back(NFA);
678 }
679
680 // Now clone the body of the old function into the new function...
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000681 CloneFunctionInto(NewFunc, TFI.Func, ArgMap);
Chris Lattner291a1b12002-03-29 19:05:48 +0000682
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000683 // Okay, now we have a function that is identical to the old one, except that
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000684 // it has extra arguments for the pools coming in. Now we have to get the
685 // data structure graph for the function we are replacing, and figure out how
686 // our graph nodes map to the graph nodes in the dest function.
687 //
688 FunctionDSGraph &DSGraph = DS->getClosedDSGraph(TFI.Func);
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000689
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000690 // NodeMapping - Multimap from callers graph to called graph.
691 //
692 map<DSNode*, PointerValSet> NodeMapping;
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000693
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000694 CalculateNodeMapping(TFI, CallerIPGraph, DSGraph,
695 NodeMapping);
696
697 // Print out the node mapping...
698 cerr << "\nNode mapping for call of " << TFI.Func->getName() << "\n";
699 for (map<DSNode*, PointerValSet>::iterator I = NodeMapping.begin();
700 I != NodeMapping.end(); ++I) {
701 cerr << "Map: "; I->first->print(cerr);
702 cerr << "To: "; I->second.print(cerr);
703 cerr << "\n";
704 }
705
706 // Fill in the PoolDescriptor information for the transformed function so that
707 // it can determine which value holds the pool descriptor for each data
708 // structure node that it accesses.
709 //
710 map<DSNode*, Value*> PoolDescriptors;
711
712 cerr << "FIXME: PoolDescriptors not built!\n";
713
714#if 0
715 // First add the incoming arguments to the scalar map...
716 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i)
717 if (TFI.ArgInfo[i].ArgNo == -1) {
718
719 } else {
720 Value *Arg = TFI.Func->getArgumentList()[TFI.ArgInfo[i].ArgNo];
721
722 // Find out what nodes the argument points to in the called functions data
723 // structure graph...
724 //
725 PointerValSet &ArgNodes = DSGraph.getValueMap()[Arg];
726
727 // Add mappings for all of the arguments of this function...
728 for (unsigned ArgVal = 0, AVE = ArgNodes.size(); ArgVal != AVE; ++ArgVal){
729 assert(ArgNodes[ArgVal].Index == 0 &&
730 "Arg that points into an object not handled yet!");
731 DSNode *ArgNode = ArgNodes[ArgVal].Node;
732 Scalars.push_back(ScalarInfo(Arg, ArgNode, PoolDescriptors[ArgNode]));
733 }
734 ArgOffset++;
735 }
736
737 // Now that we know everything we need about the function, transform the body
738 // now!
739 //
740 transformFunctionBody(TFI.Func, DSGraph, PoolDescriptors);
741
742 cerr << "Function after transformation:\n";
743 TFI.Func->dump();
744#endif
Chris Lattner66df97d2002-03-29 06:21:38 +0000745}
746
747
748// CreatePools - Insert instructions into the function we are processing to
749// create all of the memory pool objects themselves. This also inserts
750// destruction code. Add an alloca for each pool that is allocated to the
751// PoolDescriptors vector.
752//
753void PoolAllocate::CreatePools(Function *F, const vector<AllocDSNode*> &Allocs,
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000754 map<DSNode*, Value*> &PoolDescriptors) {
Chris Lattnere0618ca2002-03-29 05:50:20 +0000755 // FIXME: This should use an IP version of the UnifyAllExits pass!
756 vector<BasicBlock*> ReturnNodes;
757 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
758 if (isa<ReturnInst>((*I)->getTerminator()))
759 ReturnNodes.push_back(*I);
760
761
762 // Create the code that goes in the entry and exit nodes for the method...
763 vector<Instruction*> EntryNodeInsts;
764 for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
765 // Add an allocation and a free for each pool...
766 AllocaInst *PoolAlloc = new AllocaInst(PoolTy, 0, "pool");
767 EntryNodeInsts.push_back(PoolAlloc);
Chris Lattner396d5d72002-03-30 04:02:31 +0000768 PoolDescriptors[Allocs[i]] = PoolAlloc; // Keep track of pool allocas
Chris Lattnere0618ca2002-03-29 05:50:20 +0000769 AllocationInst *AI = Allocs[i]->getAllocation();
770
771 // Initialize the pool. We need to know how big each allocation is. For
772 // our purposes here, we assume we are allocating a scalar, or array of
773 // constant size.
774 //
775 unsigned ElSize = TargetData.getTypeSize(AI->getAllocatedType());
776 ElSize *= cast<ConstantUInt>(AI->getArraySize())->getValue();
777
778 vector<Value*> Args;
779 Args.push_back(PoolAlloc); // Pool to initialize
780 Args.push_back(ConstantUInt::get(Type::UIntTy, ElSize));
781 EntryNodeInsts.push_back(new CallInst(PoolInit, Args));
782
783 // Destroy the pool...
784 Args.pop_back();
785
786 for (unsigned EN = 0, ENE = ReturnNodes.size(); EN != ENE; ++EN) {
787 Instruction *Destroy = new CallInst(PoolDestroy, Args);
788
789 // Insert it before the return instruction...
790 BasicBlock *RetNode = ReturnNodes[EN];
791 RetNode->getInstList().insert(RetNode->end()-1, Destroy);
792 }
793 }
794
795 // Insert the entry node code into the entry block...
796 F->getEntryNode()->getInstList().insert(F->getEntryNode()->begin()+1,
797 EntryNodeInsts.begin(),
798 EntryNodeInsts.end());
Chris Lattner175f37c2002-03-29 03:40:59 +0000799}
800
801
Chris Lattner175f37c2002-03-29 03:40:59 +0000802// addPoolPrototypes - Add prototypes for the pool methods to the specified
803// module and update the Pool* instance variables to point to them.
804//
805void PoolAllocate::addPoolPrototypes(Module *M) {
Chris Lattnere0618ca2002-03-29 05:50:20 +0000806 // Get PoolInit function...
807 vector<const Type*> Args;
808 Args.push_back(PoolTy); // Pool to initialize
809 Args.push_back(Type::UIntTy); // Num bytes per element
810 FunctionType *PoolInitTy = FunctionType::get(Type::VoidTy, Args, false);
811 PoolInit = M->getOrInsertFunction("poolinit", PoolInitTy);
Chris Lattner175f37c2002-03-29 03:40:59 +0000812
Chris Lattnere0618ca2002-03-29 05:50:20 +0000813 // Get pooldestroy function...
814 Args.pop_back(); // Only takes a pool...
815 FunctionType *PoolDestroyTy = FunctionType::get(Type::VoidTy, Args, false);
816 PoolDestroy = M->getOrInsertFunction("pooldestroy", PoolDestroyTy);
817
818 const Type *PtrVoid = PointerType::get(Type::SByteTy);
819
820 // Get the poolalloc function...
821 FunctionType *PoolAllocTy = FunctionType::get(PtrVoid, Args, false);
822 PoolAlloc = M->getOrInsertFunction("poolalloc", PoolAllocTy);
823
824 // Get the poolfree function...
825 Args.push_back(PtrVoid);
826 FunctionType *PoolFreeTy = FunctionType::get(Type::VoidTy, Args, false);
827 PoolFree = M->getOrInsertFunction("poolfree", PoolFreeTy);
828
829 // Add the %PoolTy type to the symbol table of the module...
830 M->addTypeName("PoolTy", PoolTy->getElementType());
Chris Lattner175f37c2002-03-29 03:40:59 +0000831}
832
833
834bool PoolAllocate::run(Module *M) {
835 addPoolPrototypes(M);
836 CurModule = M;
837
838 DS = &getAnalysis<DataStructure>();
839 bool Changed = false;
Chris Lattner291a1b12002-03-29 19:05:48 +0000840
841 // We cannot use an iterator here because it will get invalidated when we add
842 // functions to the module later...
843 for (unsigned i = 0; i != M->size(); ++i)
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000844 if (!M->getFunctionList()[i]->isExternal()) {
Chris Lattner291a1b12002-03-29 19:05:48 +0000845 Changed |= processFunction(M->getFunctionList()[i]);
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000846 if (Changed) {
847 cerr << "Only processing one function\n";
848 break;
849 }
850 }
Chris Lattner175f37c2002-03-29 03:40:59 +0000851
852 CurModule = 0;
853 DS = 0;
854 return false;
855}
856
857
858// createPoolAllocatePass - Global function to access the functionality of this
859// pass...
860//
Chris Lattner64fd9352002-03-28 18:08:31 +0000861Pass *createPoolAllocatePass() { return new PoolAllocate(); }