blob: fc7bc5e7d6cc958046705aadfedc44c6e97067fe [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"
Chris Lattnerd92b01c2002-04-09 18:37:46 +000016#include "llvm/BasicBlock.h"
Chris Lattner175f37c2002-03-29 03:40:59 +000017#include "llvm/iMemory.h"
Chris Lattnere0618ca2002-03-29 05:50:20 +000018#include "llvm/iTerminators.h"
Chris Lattner441e16f2002-04-12 20:23:15 +000019#include "llvm/iPHINode.h"
Chris Lattnere0618ca2002-03-29 05:50:20 +000020#include "llvm/iOther.h"
Chris Lattner441e16f2002-04-12 20:23:15 +000021#include "llvm/DerivedTypes.h"
Chris Lattnere0618ca2002-03-29 05:50:20 +000022#include "llvm/ConstantVals.h"
23#include "llvm/Target/TargetData.h"
Chris Lattnerf32d65d2002-03-29 21:25:19 +000024#include "llvm/Support/InstVisitor.h"
Chris Lattner2e9fa6d2002-04-09 19:48:49 +000025#include "llvm/Argument.h"
Chris Lattner396d5d72002-03-30 04:02:31 +000026#include "Support/DepthFirstIterator.h"
Chris Lattnere0618ca2002-03-29 05:50:20 +000027#include "Support/STLExtras.h"
Chris Lattner175f37c2002-03-29 03:40:59 +000028#include <algorithm>
Chris Lattner64fd9352002-03-28 18:08:31 +000029
Chris Lattner441e16f2002-04-12 20:23:15 +000030// DEBUG_CREATE_POOLS - Enable this to turn on debug output for the pool
31// creation phase in the top level function of a transformed data structure.
32//
33#define DEBUG_CREATE_POOLS 1
34
35const Type *POINTERTYPE;
Chris Lattner692ad5d2002-03-29 17:13:46 +000036
Chris Lattnere0618ca2002-03-29 05:50:20 +000037// FIXME: This is dependant on the sparc backend layout conventions!!
38static TargetData TargetData("test");
39
Chris Lattner64fd9352002-03-28 18:08:31 +000040namespace {
Chris Lattner441e16f2002-04-12 20:23:15 +000041 struct PoolInfo {
42 DSNode *Node; // The node this pool allocation represents
43 Value *Handle; // LLVM value of the pool in the current context
44 const Type *NewType; // The transformed type of the memory objects
45 const Type *PoolType; // The type of the pool
46
47 const Type *getOldType() const { return Node->getType(); }
48
49 PoolInfo() { // Define a default ctor for map::operator[]
50 cerr << "Map subscript used to get element that doesn't exist!\n";
51 abort(); // Invalid
52 }
53
54 PoolInfo(DSNode *N, Value *H, const Type *NT, const Type *PT)
55 : Node(N), Handle(H), NewType(NT), PoolType(PT) {
56 // Handle can be null...
57 assert(N && NT && PT && "Pool info null!");
58 }
59
60 PoolInfo(DSNode *N) : Node(N), Handle(0), NewType(0), PoolType(0) {
61 assert(N && "Invalid pool info!");
62
63 // The new type of the memory object is the same as the old type, except
64 // that all of the pointer values are replaced with POINTERTYPE values.
65 assert(isa<StructType>(getOldType()) && "Can only handle structs!");
66 StructType *OldTy = cast<StructType>(getOldType());
67 vector<const Type *> NewElTypes;
68 NewElTypes.reserve(OldTy->getElementTypes().size());
69 for (StructType::ElementTypes::const_iterator
70 I = OldTy->getElementTypes().begin(),
71 E = OldTy->getElementTypes().end(); I != E; ++I)
72 if (PointerType *PT = dyn_cast<PointerType>(I->get()))
73 NewElTypes.push_back(POINTERTYPE);
74 else
75 NewElTypes.push_back(*I);
76 NewType = StructType::get(NewElTypes);
77 }
78 };
79
Chris Lattner692ad5d2002-03-29 17:13:46 +000080 // ScalarInfo - Information about an LLVM value that we know points to some
81 // datastructure we are processing.
82 //
83 struct ScalarInfo {
Chris Lattnerca9f4d32002-03-30 09:12:35 +000084 Value *Val; // Scalar value in Current Function
Chris Lattner441e16f2002-04-12 20:23:15 +000085 PoolInfo Pool; // The pool the scalar points into
Chris Lattner692ad5d2002-03-29 17:13:46 +000086
Chris Lattner441e16f2002-04-12 20:23:15 +000087 ScalarInfo(Value *V, const PoolInfo &PI) : Val(V), Pool(PI) {
88 assert(V && "Null value passed to ScalarInfo ctor!");
Chris Lattnerca9f4d32002-03-30 09:12:35 +000089 }
Chris Lattner692ad5d2002-03-29 17:13:46 +000090 };
91
Chris Lattner396d5d72002-03-30 04:02:31 +000092 // CallArgInfo - Information on one operand for a call that got expanded.
93 struct CallArgInfo {
Chris Lattnerca9f4d32002-03-30 09:12:35 +000094 int ArgNo; // Call argument number this corresponds to
95 DSNode *Node; // The graph node for the pool
96 Value *PoolHandle; // The LLVM value that is the pool pointer
Chris Lattner396d5d72002-03-30 04:02:31 +000097
Chris Lattnerca9f4d32002-03-30 09:12:35 +000098 CallArgInfo(int Arg, DSNode *N, Value *PH)
99 : ArgNo(Arg), Node(N), PoolHandle(PH) {
100 assert(Arg >= -1 && N && PH && "Illegal values to CallArgInfo ctor!");
Chris Lattner396d5d72002-03-30 04:02:31 +0000101 }
102
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000103 // operator< when sorting, sort by argument number.
Chris Lattner396d5d72002-03-30 04:02:31 +0000104 bool operator<(const CallArgInfo &CAI) const {
105 return ArgNo < CAI.ArgNo;
106 }
107 };
108
Chris Lattner692ad5d2002-03-29 17:13:46 +0000109 // TransformFunctionInfo - Information about how a function eeds to be
110 // transformed.
111 //
112 struct TransformFunctionInfo {
113 // ArgInfo - Maintain information about the arguments that need to be
Chris Lattner441e16f2002-04-12 20:23:15 +0000114 // processed. Each CallArgInfo corresponds to an argument that needs to
115 // have a pool pointer passed into the transformed function with it.
Chris Lattner692ad5d2002-03-29 17:13:46 +0000116 //
117 // As a special case, "argument" number -1 corresponds to the return value.
118 //
Chris Lattner396d5d72002-03-30 04:02:31 +0000119 vector<CallArgInfo> ArgInfo;
Chris Lattner692ad5d2002-03-29 17:13:46 +0000120
121 // Func - The function to be transformed...
122 Function *Func;
123
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000124 // The call instruction that is used to map CallArgInfo PoolHandle values
125 // into the new function values.
126 CallInst *Call;
127
Chris Lattner692ad5d2002-03-29 17:13:46 +0000128 // default ctor...
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000129 TransformFunctionInfo() : Func(0), Call(0) {}
Chris Lattner692ad5d2002-03-29 17:13:46 +0000130
Chris Lattner396d5d72002-03-30 04:02:31 +0000131 bool operator<(const TransformFunctionInfo &TFI) const {
Chris Lattner291a1b12002-03-29 19:05:48 +0000132 if (Func < TFI.Func) return true;
133 if (Func > TFI.Func) return false;
Chris Lattner291a1b12002-03-29 19:05:48 +0000134 if (ArgInfo.size() < TFI.ArgInfo.size()) return true;
135 if (ArgInfo.size() > TFI.ArgInfo.size()) return false;
Chris Lattner396d5d72002-03-30 04:02:31 +0000136 return ArgInfo < TFI.ArgInfo;
Chris Lattner692ad5d2002-03-29 17:13:46 +0000137 }
138
139 void finalizeConstruction() {
140 // Sort the vector so that the return value is first, followed by the
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000141 // argument records, in order. Note that this must be a stable sort so
142 // that the entries with the same sorting criteria (ie they are multiple
143 // pool entries for the same argument) are kept in depth first order.
144 stable_sort(ArgInfo.begin(), ArgInfo.end());
Chris Lattner692ad5d2002-03-29 17:13:46 +0000145 }
146 };
147
148
149 // Define the pass class that we implement...
Chris Lattner441e16f2002-04-12 20:23:15 +0000150 struct PoolAllocate : public Pass {
Chris Lattner175f37c2002-03-29 03:40:59 +0000151 PoolAllocate() {
Chris Lattner441e16f2002-04-12 20:23:15 +0000152 POINTERTYPE = Type::UShortTy;
Chris Lattner175f37c2002-03-29 03:40:59 +0000153
154 CurModule = 0; DS = 0;
155 PoolInit = PoolDestroy = PoolAlloc = PoolFree = 0;
Chris Lattner64fd9352002-03-28 18:08:31 +0000156 }
157
Chris Lattner441e16f2002-04-12 20:23:15 +0000158 // getPoolType - Get the type used by the backend for a pool of a particular
159 // type. This pool record is used to allocate nodes of type NodeType.
160 //
161 // Here, PoolTy = { NodeType*, sbyte*, uint }*
162 //
163 const StructType *getPoolType(const Type *NodeType) {
164 vector<const Type*> PoolElements;
165 PoolElements.push_back(PointerType::get(NodeType));
166 PoolElements.push_back(PointerType::get(Type::SByteTy));
167 PoolElements.push_back(Type::UIntTy);
168 return StructType::get(PoolElements);
169 }
170
Chris Lattner175f37c2002-03-29 03:40:59 +0000171 bool run(Module *M);
172
173 // getAnalysisUsageInfo - This function requires data structure information
174 // to be able to see what is pool allocatable.
Chris Lattner64fd9352002-03-28 18:08:31 +0000175 //
176 virtual void getAnalysisUsageInfo(Pass::AnalysisSet &Required,
Chris Lattner175f37c2002-03-29 03:40:59 +0000177 Pass::AnalysisSet &,Pass::AnalysisSet &) {
Chris Lattner64fd9352002-03-28 18:08:31 +0000178 Required.push_back(DataStructure::ID);
179 }
Chris Lattner175f37c2002-03-29 03:40:59 +0000180
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000181 public:
Chris Lattner175f37c2002-03-29 03:40:59 +0000182 // CurModule - The module being processed.
183 Module *CurModule;
184
185 // DS - The data structure graph for the module being processed.
186 DataStructure *DS;
187
188 // Prototypes that we add to support pool allocation...
189 Function *PoolInit, *PoolDestroy, *PoolAlloc, *PoolFree;
190
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000191 // The map of already transformed functions... note that the keys of this
192 // map do not have meaningful values for 'Call' or the 'PoolHandle' elements
193 // of the ArgInfo elements.
194 //
Chris Lattner692ad5d2002-03-29 17:13:46 +0000195 map<TransformFunctionInfo, Function*> TransformedFunctions;
196
197 // getTransformedFunction - Get a transformed function, or return null if
198 // the function specified hasn't been transformed yet.
199 //
200 Function *getTransformedFunction(TransformFunctionInfo &TFI) const {
201 map<TransformFunctionInfo, Function*>::const_iterator I =
202 TransformedFunctions.find(TFI);
203 if (I != TransformedFunctions.end()) return I->second;
204 return 0;
205 }
206
207
Chris Lattner441e16f2002-04-12 20:23:15 +0000208 // addPoolPrototypes - Add prototypes for the pool functions to the
209 // specified module and update the Pool* instance variables to point to
210 // them.
Chris Lattner175f37c2002-03-29 03:40:59 +0000211 //
212 void addPoolPrototypes(Module *M);
213
Chris Lattner66df97d2002-03-29 06:21:38 +0000214
215 // CreatePools - Insert instructions into the function we are processing to
216 // create all of the memory pool objects themselves. This also inserts
217 // destruction code. Add an alloca for each pool that is allocated to the
Chris Lattner441e16f2002-04-12 20:23:15 +0000218 // PoolDescs map.
Chris Lattner66df97d2002-03-29 06:21:38 +0000219 //
220 void CreatePools(Function *F, const vector<AllocDSNode*> &Allocs,
Chris Lattner441e16f2002-04-12 20:23:15 +0000221 map<DSNode*, PoolInfo> &PoolDescs);
Chris Lattner66df97d2002-03-29 06:21:38 +0000222
Chris Lattner175f37c2002-03-29 03:40:59 +0000223 // processFunction - Convert a function to use pool allocation where
224 // available.
225 //
226 bool processFunction(Function *F);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000227
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000228 // transformFunctionBody - This transforms the instruction in 'F' to use the
Chris Lattner441e16f2002-04-12 20:23:15 +0000229 // pools specified in PoolDescs when modifying data structure nodes
230 // specified in the PoolDescs map. IPFGraph is the closed data structure
231 // graph for F, of which the PoolDescriptor nodes come from.
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000232 //
233 void transformFunctionBody(Function *F, FunctionDSGraph &IPFGraph,
Chris Lattner441e16f2002-04-12 20:23:15 +0000234 map<DSNode*, PoolInfo> &PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000235
236 // transformFunction - Transform the specified function the specified way.
237 // It we have already transformed that function that way, don't do anything.
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000238 // The nodes in the TransformFunctionInfo come out of callers data structure
Chris Lattner441e16f2002-04-12 20:23:15 +0000239 // graph, and the PoolDescs passed in are the caller's.
Chris Lattner692ad5d2002-03-29 17:13:46 +0000240 //
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000241 void transformFunction(TransformFunctionInfo &TFI,
Chris Lattner441e16f2002-04-12 20:23:15 +0000242 FunctionDSGraph &CallerIPGraph,
243 map<DSNode*, PoolInfo> &PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000244
Chris Lattner64fd9352002-03-28 18:08:31 +0000245 };
246}
247
Chris Lattner692ad5d2002-03-29 17:13:46 +0000248// isNotPoolableAlloc - This is a predicate that returns true if the specified
Chris Lattner175f37c2002-03-29 03:40:59 +0000249// allocation node in a data structure graph is eligable for pool allocation.
250//
251static bool isNotPoolableAlloc(const AllocDSNode *DS) {
Chris Lattnere0618ca2002-03-29 05:50:20 +0000252 if (DS->isAllocaNode()) return true; // Do not pool allocate alloca's.
Chris Lattner175f37c2002-03-29 03:40:59 +0000253
254 MallocInst *MI = cast<MallocInst>(DS->getAllocation());
255 if (MI->isArrayAllocation() && !isa<Constant>(MI->getArraySize()))
Chris Lattnere0618ca2002-03-29 05:50:20 +0000256 return true; // Do not allow variable size allocations...
Chris Lattner175f37c2002-03-29 03:40:59 +0000257
Chris Lattnere0618ca2002-03-29 05:50:20 +0000258 return false;
Chris Lattner175f37c2002-03-29 03:40:59 +0000259}
260
Chris Lattner175f37c2002-03-29 03:40:59 +0000261// processFunction - Convert a function to use pool allocation where
262// available.
263//
264bool PoolAllocate::processFunction(Function *F) {
265 // Get the closed datastructure graph for the current function... if there are
266 // any allocations in this graph that are not escaping, we need to pool
267 // allocate them here!
268 //
269 FunctionDSGraph &IPGraph = DS->getClosedDSGraph(F);
270
271 // Get all of the allocations that do not escape the current function. Since
272 // they are still live (they exist in the graph at all), this means we must
273 // have scalar references to these nodes, but the scalars are never returned.
274 //
Chris Lattner692ad5d2002-03-29 17:13:46 +0000275 vector<AllocDSNode*> Allocs;
Chris Lattner175f37c2002-03-29 03:40:59 +0000276 IPGraph.getNonEscapingAllocations(Allocs);
277
278 // Filter out allocations that we cannot handle. Currently, this includes
279 // variable sized array allocations and alloca's (which we do not want to
280 // pool allocate)
281 //
282 Allocs.erase(remove_if(Allocs.begin(), Allocs.end(), isNotPoolableAlloc),
283 Allocs.end());
284
285
286 if (Allocs.empty()) return false; // Nothing to do.
287
Chris Lattner692ad5d2002-03-29 17:13:46 +0000288 // Insert instructions into the function we are processing to create all of
289 // the memory pool objects themselves. This also inserts destruction code.
Chris Lattner441e16f2002-04-12 20:23:15 +0000290 // This fills in the PoolDescs map to associate the alloc node with the
Chris Lattner396d5d72002-03-30 04:02:31 +0000291 // allocation of the memory pool corresponding to it.
Chris Lattner692ad5d2002-03-29 17:13:46 +0000292 //
Chris Lattner441e16f2002-04-12 20:23:15 +0000293 map<DSNode*, PoolInfo> PoolDescs;
294 CreatePools(F, Allocs, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000295
Chris Lattner441e16f2002-04-12 20:23:15 +0000296 cerr << "Transformed Entry Function: \n" << F;
297
298 // Now we need to figure out what called functions we need to transform, and
Chris Lattner692ad5d2002-03-29 17:13:46 +0000299 // how. To do this, we look at all of the scalars, seeing which functions are
300 // either used as a scalar value (so they return a data structure), or are
301 // passed one of our scalar values.
302 //
Chris Lattner441e16f2002-04-12 20:23:15 +0000303 transformFunctionBody(F, IPGraph, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000304
305 return true;
306}
307
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000308
Chris Lattner441e16f2002-04-12 20:23:15 +0000309//===----------------------------------------------------------------------===//
310//
311// NewInstructionCreator - This class is used to traverse the function being
312// modified, changing each instruction visit'ed to use and provide pointer
313// indexes instead of real pointers. This is what changes the body of a
314// function to use pool allocation.
315//
316class NewInstructionCreator : public InstVisitor<NewInstructionCreator> {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000317 PoolAllocate &PoolAllocator;
318 vector<ScalarInfo> &Scalars;
319 map<CallInst*, TransformFunctionInfo> &CallMap;
Chris Lattner441e16f2002-04-12 20:23:15 +0000320 map<Value*, Value*> &XFormMap; // Map old pointers to new indexes
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000321
Chris Lattner441e16f2002-04-12 20:23:15 +0000322 struct RefToUpdate {
323 Instruction *I; // Instruction to update
324 unsigned OpNum; // Operand number to update
325 Value *OldVal; // The old value it had
326
327 RefToUpdate(Instruction *i, unsigned o, Value *ov)
328 : I(i), OpNum(o), OldVal(ov) {}
329 };
330 vector<RefToUpdate> ReferencesToUpdate;
331
332 const ScalarInfo &getScalarRef(const Value *V) {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000333 for (unsigned i = 0, e = Scalars.size(); i != e; ++i)
334 if (Scalars[i].Val == V) return Scalars[i];
335 assert(0 && "Scalar not found in getScalar!");
336 abort();
337 return Scalars[0];
338 }
Chris Lattner441e16f2002-04-12 20:23:15 +0000339
340 const ScalarInfo *getScalar(const Value *V) {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000341 for (unsigned i = 0, e = Scalars.size(); i != e; ++i)
Chris Lattner441e16f2002-04-12 20:23:15 +0000342 if (Scalars[i].Val == V) return &Scalars[i];
343 return 0;
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000344 }
345
Chris Lattner441e16f2002-04-12 20:23:15 +0000346 BasicBlock::iterator ReplaceInstWith(Instruction *I, Instruction *New) {
347 BasicBlock *BB = I->getParent();
348 BasicBlock::iterator RI = find(BB->begin(), BB->end(), I);
349 BB->getInstList().replaceWith(RI, New);
350 XFormMap[I] = New;
351 return RI;
352 }
353
354 LoadInst *createPoolBaseInstruction(Value *PtrVal) {
355 const ScalarInfo &SC = getScalarRef(PtrVal);
356 vector<Value*> Args(3);
357 Args[0] = ConstantUInt::get(Type::UIntTy, 0); // No pointer offset
358 Args[1] = ConstantUInt::get(Type::UByteTy, 0); // Field #0 of pool descriptr
359 Args[2] = ConstantUInt::get(Type::UByteTy, 0); // Field #0 of poolalloc val
360 return new LoadInst(SC.Pool.Handle, Args, PtrVal->getName()+".poolbase");
361 }
362
363
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000364public:
Chris Lattner441e16f2002-04-12 20:23:15 +0000365 NewInstructionCreator(PoolAllocate &PA, vector<ScalarInfo> &S,
366 map<CallInst*, TransformFunctionInfo> &C,
367 map<Value*, Value*> &X)
368 : PoolAllocator(PA), Scalars(S), CallMap(C), XFormMap(X) {}
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000369
Chris Lattner441e16f2002-04-12 20:23:15 +0000370
371 // updateReferences - The NewInstructionCreator is responsible for creating
372 // new instructions to replace the old ones in the function, and then link up
373 // references to values to their new values. For it to do this, however, it
374 // keeps track of information about the value mapping of old values to new
375 // values that need to be patched up. Given this value map and a set of
376 // instruction operands to patch, updateReferences performs the updates.
377 //
378 void updateReferences() {
379 for (unsigned i = 0, e = ReferencesToUpdate.size(); i != e; ++i) {
380 RefToUpdate &Ref = ReferencesToUpdate[i];
381 Value *NewVal = XFormMap[Ref.OldVal];
382
383 if (NewVal == 0) {
384 if (isa<Constant>(Ref.OldVal) && // Refering to a null ptr?
385 cast<Constant>(Ref.OldVal)->isNullValue()) {
386 // Transform the null pointer into a null index... caching in XFormMap
387 XFormMap[Ref.OldVal] = NewVal =Constant::getNullConstant(POINTERTYPE);
388 //} else if (isa<Argument>(Ref.OldVal)) {
389 } else {
390 cerr << "Unknown reference to: " << Ref.OldVal << "\n";
391 assert(XFormMap[Ref.OldVal] &&
392 "Reference to value that was not updated found!");
393 }
394 }
395
396 Ref.I->setOperand(Ref.OpNum, NewVal);
397 }
398 ReferencesToUpdate.clear();
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000399 }
400
Chris Lattner441e16f2002-04-12 20:23:15 +0000401 //===--------------------------------------------------------------------===//
402 // Transformation methods:
403 // These methods specify how each type of instruction is transformed by the
404 // NewInstructionCreator instance...
405 //===--------------------------------------------------------------------===//
406
407 void visitGetElementPtrInst(GetElementPtrInst *I) {
408 assert(0 && "Cannot transform get element ptr instructions yet!");
409 }
410
411 // Replace the load instruction with a new one.
412 void visitLoadInst(LoadInst *I) {
413 Instruction *PoolBase = createPoolBaseInstruction(I->getOperand(0));
414
415 // Cast our index to be a UIntTy so we can use it to index into the pool...
416 CastInst *Index = new CastInst(Constant::getNullConstant(POINTERTYPE),
417 Type::UIntTy, I->getOperand(0)->getName());
418
419 ReferencesToUpdate.push_back(RefToUpdate(Index, 0, I->getOperand(0)));
420
421 vector<Value*> Indices(I->idx_begin(), I->idx_end());
422 assert(Indices[0] == ConstantUInt::get(Type::UIntTy, 0) &&
423 "Cannot handle array indexing yet!");
424 Indices[0] = Index;
425 Instruction *NewLoad = new LoadInst(PoolBase, Indices, I->getName());
426
427 // Replace the load instruction with the new load instruction...
428 BasicBlock::iterator II = ReplaceInstWith(I, NewLoad);
429
430 // Add the pool base calculator instruction before the load...
431 II = NewLoad->getParent()->getInstList().insert(II, PoolBase) + 1;
432
433 // Add the cast before the load instruction...
434 NewLoad->getParent()->getInstList().insert(II, Index);
435
436 // If not yielding a pool allocated pointer, use the new load value as the
437 // value in the program instead of the old load value...
438 //
439 if (!getScalar(I))
440 I->replaceAllUsesWith(NewLoad);
441 }
442
443 // Replace the store instruction with a new one. In the store instruction,
444 // the value stored could be a pointer type, meaning that the new store may
445 // have to change one or both of it's operands.
446 //
447 void visitStoreInst(StoreInst *I) {
448 assert(getScalar(I->getOperand(1)) &&
449 "Store inst found only storing pool allocated pointer. "
450 "Not imp yet!");
451
452 Value *Val = I->getOperand(0); // The value to store...
453 // Check to see if the value we are storing is a data structure pointer...
454 if (const ScalarInfo *ValScalar = getScalar(I->getOperand(0)))
455 Val = Constant::getNullConstant(POINTERTYPE); // Yes, store a dummy
456
457 Instruction *PoolBase = createPoolBaseInstruction(I->getOperand(1));
458
459 // Cast our index to be a UIntTy so we can use it to index into the pool...
460 CastInst *Index = new CastInst(Constant::getNullConstant(POINTERTYPE),
461 Type::UIntTy, I->getOperand(1)->getName());
462 ReferencesToUpdate.push_back(RefToUpdate(Index, 0, I->getOperand(1)));
463
464 vector<Value*> Indices(I->idx_begin(), I->idx_end());
465 assert(Indices[0] == ConstantUInt::get(Type::UIntTy, 0) &&
466 "Cannot handle array indexing yet!");
467 Indices[0] = Index;
468 Instruction *NewStore = new StoreInst(Val, PoolBase, Indices);
469
470 if (Val != I->getOperand(0)) // Value stored was a pointer?
471 ReferencesToUpdate.push_back(RefToUpdate(NewStore, 0, I->getOperand(0)));
472
473
474 // Replace the store instruction with the cast instruction...
475 BasicBlock::iterator II = ReplaceInstWith(I, Index);
476
477 // Add the pool base calculator instruction before the index...
478 II = Index->getParent()->getInstList().insert(II, PoolBase) + 2;
479
480 // Add the store after the cast instruction...
481 Index->getParent()->getInstList().insert(II, NewStore);
482 }
483
484
485 // Create call to poolalloc for every malloc instruction
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000486 void visitMallocInst(MallocInst *I) {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000487 vector<Value*> Args;
Chris Lattner441e16f2002-04-12 20:23:15 +0000488 Args.push_back(getScalarRef(I).Pool.Handle);
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000489 CallInst *Call = new CallInst(PoolAllocator.PoolAlloc, Args, I->getName());
Chris Lattner441e16f2002-04-12 20:23:15 +0000490 ReplaceInstWith(I, Call);
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000491 }
492
Chris Lattner441e16f2002-04-12 20:23:15 +0000493 // Convert a call to poolfree for every free instruction...
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000494 void visitFreeInst(FreeInst *I) {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000495 // Create a new call to poolfree before the free instruction
496 vector<Value*> Args;
Chris Lattner441e16f2002-04-12 20:23:15 +0000497 Args.push_back(Constant::getNullConstant(POINTERTYPE));
498 Args.push_back(getScalarRef(I->getOperand(0)).Pool.Handle);
499 Instruction *NewCall = new CallInst(PoolAllocator.PoolFree, Args);
500 ReplaceInstWith(I, NewCall);
501 ReferencesToUpdate.push_back(RefToUpdate(NewCall, 0, I->getOperand(0)));
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000502 }
503
504 // visitCallInst - Create a new call instruction with the extra arguments for
505 // all of the memory pools that the call needs.
506 //
507 void visitCallInst(CallInst *I) {
508 TransformFunctionInfo &TI = CallMap[I];
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000509
510 // Start with all of the old arguments...
511 vector<Value*> Args(I->op_begin()+1, I->op_end());
512
Chris Lattner441e16f2002-04-12 20:23:15 +0000513 for (unsigned i = 0, e = TI.ArgInfo.size(); i != e; ++i) {
514 // Replace all of the pointer arguments with our new pointer typed values.
515 if (TI.ArgInfo[i].ArgNo != -1)
516 Args[TI.ArgInfo[i].ArgNo] = Constant::getNullConstant(POINTERTYPE);
517
518 // Add all of the pool arguments...
Chris Lattner396d5d72002-03-30 04:02:31 +0000519 Args.push_back(TI.ArgInfo[i].PoolHandle);
Chris Lattner441e16f2002-04-12 20:23:15 +0000520 }
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000521
522 Function *NF = PoolAllocator.getTransformedFunction(TI);
Chris Lattner441e16f2002-04-12 20:23:15 +0000523 Instruction *NewCall = new CallInst(NF, Args, I->getName());
524 ReplaceInstWith(I, NewCall);
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000525
Chris Lattner441e16f2002-04-12 20:23:15 +0000526 // Keep track of the mapping of operands so that we can resolve them to real
527 // values later.
528 Value *RetVal = NewCall;
529 for (unsigned i = 0, e = TI.ArgInfo.size(); i != e; ++i)
530 if (TI.ArgInfo[i].ArgNo != -1)
531 ReferencesToUpdate.push_back(RefToUpdate(NewCall, TI.ArgInfo[i].ArgNo+1,
532 I->getOperand(TI.ArgInfo[i].ArgNo+1)));
533 else
534 RetVal = 0; // If returning a pointer, don't change retval...
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000535
Chris Lattner441e16f2002-04-12 20:23:15 +0000536 // If not returning a pointer, use the new call as the value in the program
537 // instead of the old call...
538 //
539 if (RetVal)
540 I->replaceAllUsesWith(RetVal);
541 }
542
543 // visitPHINode - Create a new PHI node of POINTERTYPE for all of the old Phi
544 // nodes...
545 //
546 void visitPHINode(PHINode *PN) {
547 Value *DummyVal = Constant::getNullConstant(POINTERTYPE);
548 PHINode *NewPhi = new PHINode(POINTERTYPE, PN->getName());
549 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
550 NewPhi->addIncoming(DummyVal, PN->getIncomingBlock(i));
551 ReferencesToUpdate.push_back(RefToUpdate(NewPhi, i*2,
552 PN->getIncomingValue(i)));
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000553 }
554
Chris Lattner441e16f2002-04-12 20:23:15 +0000555 ReplaceInstWith(PN, NewPhi);
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000556 }
557
Chris Lattner441e16f2002-04-12 20:23:15 +0000558 // visitReturnInst - Replace ret instruction with a new return...
Chris Lattner847b6e22002-03-30 20:53:14 +0000559 void visitReturnInst(ReturnInst *I) {
Chris Lattner441e16f2002-04-12 20:23:15 +0000560 Instruction *Ret = new ReturnInst(Constant::getNullConstant(POINTERTYPE));
561 ReplaceInstWith(I, Ret);
562 ReferencesToUpdate.push_back(RefToUpdate(Ret, 0, I->getOperand(0)));
Chris Lattner847b6e22002-03-30 20:53:14 +0000563 }
564
Chris Lattner441e16f2002-04-12 20:23:15 +0000565 // visitSetCondInst - Replace a conditional test instruction with a new one
Chris Lattnercf09a2a2002-04-01 00:45:33 +0000566 void visitSetCondInst(SetCondInst *SCI) {
Chris Lattner441e16f2002-04-12 20:23:15 +0000567 BinaryOperator *I = (BinaryOperator*)SCI;
568 Value *DummyVal = Constant::getNullConstant(POINTERTYPE);
569 BinaryOperator *New = BinaryOperator::create(I->getOpcode(), DummyVal,
570 DummyVal, I->getName());
571 ReplaceInstWith(I, New);
572
573 ReferencesToUpdate.push_back(RefToUpdate(New, 0, I->getOperand(0)));
574 ReferencesToUpdate.push_back(RefToUpdate(New, 1, I->getOperand(1)));
575
576 // Make sure branches refer to the new condition...
577 I->replaceAllUsesWith(New);
Chris Lattnercf09a2a2002-04-01 00:45:33 +0000578 }
579
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000580 void visitInstruction(Instruction *I) {
Chris Lattner441e16f2002-04-12 20:23:15 +0000581 cerr << "Unknown instruction to FunctionBodyTransformer:\n" << I;
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000582 }
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000583};
584
585
Chris Lattner441e16f2002-04-12 20:23:15 +0000586
587
Chris Lattner0dc225c2002-03-31 07:17:46 +0000588static void addCallInfo(DataStructure *DS,
589 TransformFunctionInfo &TFI, CallInst *CI, int Arg,
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000590 DSNode *GraphNode,
Chris Lattner441e16f2002-04-12 20:23:15 +0000591 map<DSNode*, PoolInfo> &PoolDescs) {
Chris Lattner0dc225c2002-03-31 07:17:46 +0000592 assert(CI->getCalledFunction() && "Cannot handle indirect calls yet!");
593 assert(TFI.Func == 0 || TFI.Func == CI->getCalledFunction() &&
594 "Function call record should always call the same function!");
595 assert(TFI.Call == 0 || TFI.Call == CI &&
596 "Call element already filled in with different value!");
597 TFI.Func = CI->getCalledFunction();
598 TFI.Call = CI;
599 //FunctionDSGraph &CalledGraph = DS->getClosedDSGraph(TFI.Func);
Chris Lattner396d5d72002-03-30 04:02:31 +0000600
601 // For now, add the entire graph that is pointed to by the call argument.
602 // This graph can and should be pruned to only what the function itself will
603 // use, because often this will be a dramatically smaller subset of what we
604 // are providing.
605 //
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000606 for (df_iterator<DSNode*> I = df_begin(GraphNode), E = df_end(GraphNode);
Chris Lattner441e16f2002-04-12 20:23:15 +0000607 I != E; ++I)
608 TFI.ArgInfo.push_back(CallArgInfo(Arg, *I, PoolDescs[*I].Handle));
Chris Lattner396d5d72002-03-30 04:02:31 +0000609}
610
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000611
612// transformFunctionBody - This transforms the instruction in 'F' to use the
Chris Lattner441e16f2002-04-12 20:23:15 +0000613// pools specified in PoolDescs when modifying data structure nodes specified in
614// the PoolDescs map. Specifically, scalar values specified in the Scalars
615// vector must be remapped. IPFGraph is the closed data structure graph for F,
616// of which the PoolDescriptor nodes come from.
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000617//
618void PoolAllocate::transformFunctionBody(Function *F, FunctionDSGraph &IPFGraph,
Chris Lattner441e16f2002-04-12 20:23:15 +0000619 map<DSNode*, PoolInfo> &PoolDescs) {
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000620
621 // Loop through the value map looking for scalars that refer to nonescaping
622 // allocations. Add them to the Scalars vector. Note that we may have
623 // multiple entries in the Scalars vector for each value if it points to more
624 // than one object.
625 //
626 map<Value*, PointerValSet> &ValMap = IPFGraph.getValueMap();
627 vector<ScalarInfo> Scalars;
628
Chris Lattner847b6e22002-03-30 20:53:14 +0000629 cerr << "Building scalar map:\n";
630
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000631 for (map<Value*, PointerValSet>::iterator I = ValMap.begin(),
632 E = ValMap.end(); I != E; ++I) {
633 const PointerValSet &PVS = I->second; // Set of things pointed to by scalar
634
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000635 // Check to see if the scalar points to a data structure node...
636 for (unsigned i = 0, e = PVS.size(); i != e; ++i) {
637 assert(PVS[i].Index == 0 && "Nonzero not handled yet!");
638
639 // If the allocation is in the nonescaping set...
Chris Lattner441e16f2002-04-12 20:23:15 +0000640 map<DSNode*, PoolInfo>::iterator AI = PoolDescs.find(PVS[i].Node);
641 if (AI != PoolDescs.end()) { // Add it to the list of scalars
642 Scalars.push_back(ScalarInfo(I->first, AI->second));
643 cerr << "\nScalar Mapping from:" << I->first
644 << "Scalar Mapping to: "; PVS.print(cerr);
645 }
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000646 }
647 }
648
649
650
Chris Lattner847b6e22002-03-30 20:53:14 +0000651 cerr << "\nIn '" << F->getName()
Chris Lattner175f37c2002-03-29 03:40:59 +0000652 << "': Found the following values that point to poolable nodes:\n";
653
654 for (unsigned i = 0, e = Scalars.size(); i != e; ++i)
Chris Lattner441e16f2002-04-12 20:23:15 +0000655 cerr << Scalars[i].Val;
656 cerr << "\n";
Chris Lattnere0618ca2002-03-29 05:50:20 +0000657
Chris Lattner692ad5d2002-03-29 17:13:46 +0000658 // CallMap - Contain an entry for every call instruction that needs to be
659 // transformed. Each entry in the map contains information about what we need
660 // to do to each call site to change it to work.
661 //
662 map<CallInst*, TransformFunctionInfo> CallMap;
Chris Lattner66df97d2002-03-29 06:21:38 +0000663
Chris Lattner441e16f2002-04-12 20:23:15 +0000664 // Now we need to figure out what called functions we need to transform, and
Chris Lattner692ad5d2002-03-29 17:13:46 +0000665 // how. To do this, we look at all of the scalars, seeing which functions are
666 // either used as a scalar value (so they return a data structure), or are
667 // passed one of our scalar values.
668 //
669 for (unsigned i = 0, e = Scalars.size(); i != e; ++i) {
670 Value *ScalarVal = Scalars[i].Val;
671
672 // Check to see if the scalar _IS_ a call...
673 if (CallInst *CI = dyn_cast<CallInst>(ScalarVal))
674 // If so, add information about the pool it will be returning...
Chris Lattner441e16f2002-04-12 20:23:15 +0000675 addCallInfo(DS, CallMap[CI], CI, -1, Scalars[i].Pool.Node, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000676
677 // Check to see if the scalar is an operand to a call...
678 for (Value::use_iterator UI = ScalarVal->use_begin(),
679 UE = ScalarVal->use_end(); UI != UE; ++UI) {
680 if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
681 // Find out which operand this is to the call instruction...
682 User::op_iterator OI = find(CI->op_begin(), CI->op_end(), ScalarVal);
683 assert(OI != CI->op_end() && "Call on use list but not an operand!?");
684 assert(OI != CI->op_begin() && "Pointer operand is call destination?");
685
686 // FIXME: This is broken if the same pointer is passed to a call more
687 // than once! It will get multiple entries for the first pointer.
688
689 // Add the operand number and pool handle to the call table...
Chris Lattner441e16f2002-04-12 20:23:15 +0000690 addCallInfo(DS, CallMap[CI], CI, OI-CI->op_begin()-1,
691 Scalars[i].Pool.Node, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000692 }
693 }
694 }
695
696 // Print out call map...
697 for (map<CallInst*, TransformFunctionInfo>::iterator I = CallMap.begin();
698 I != CallMap.end(); ++I) {
Chris Lattner441e16f2002-04-12 20:23:15 +0000699 cerr << "For call: " << I->first;
Chris Lattner692ad5d2002-03-29 17:13:46 +0000700 I->second.finalizeConstruction();
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000701 cerr << I->second.Func->getName() << " must pass pool pointer for args #";
Chris Lattner692ad5d2002-03-29 17:13:46 +0000702 for (unsigned i = 0; i < I->second.ArgInfo.size(); ++i)
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000703 cerr << I->second.ArgInfo[i].ArgNo << ", ";
Chris Lattner441e16f2002-04-12 20:23:15 +0000704 cerr << "\n\n";
Chris Lattner692ad5d2002-03-29 17:13:46 +0000705 }
706
707 // Loop through all of the call nodes, recursively creating the new functions
708 // that we want to call... This uses a map to prevent infinite recursion and
709 // to avoid duplicating functions unneccesarily.
710 //
711 for (map<CallInst*, TransformFunctionInfo>::iterator I = CallMap.begin(),
712 E = CallMap.end(); I != E; ++I) {
713 // Make sure the entries are sorted.
714 I->second.finalizeConstruction();
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000715
716 // Transform all of the functions we need, or at least ensure there is a
717 // cached version available.
Chris Lattner441e16f2002-04-12 20:23:15 +0000718 transformFunction(I->second, IPFGraph, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000719 }
720
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000721 // Now that all of the functions that we want to call are available, transform
Chris Lattner441e16f2002-04-12 20:23:15 +0000722 // the local function so that it uses the pools locally and passes them to the
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000723 // functions that we just hacked up.
724 //
725
726 // First step, find the instructions to be modified.
727 vector<Instruction*> InstToFix;
728 for (unsigned i = 0, e = Scalars.size(); i != e; ++i) {
729 Value *ScalarVal = Scalars[i].Val;
730
731 // Check to see if the scalar _IS_ an instruction. If so, it is involved.
732 if (Instruction *Inst = dyn_cast<Instruction>(ScalarVal))
733 InstToFix.push_back(Inst);
734
735 // All all of the instructions that use the scalar as an operand...
736 for (Value::use_iterator UI = ScalarVal->use_begin(),
737 UE = ScalarVal->use_end(); UI != UE; ++UI)
Chris Lattner441e16f2002-04-12 20:23:15 +0000738 InstToFix.push_back(cast<Instruction>(*UI));
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000739 }
740
741 // Eliminate duplicates by sorting, then removing equal neighbors.
742 sort(InstToFix.begin(), InstToFix.end());
743 InstToFix.erase(unique(InstToFix.begin(), InstToFix.end()), InstToFix.end());
744
Chris Lattner441e16f2002-04-12 20:23:15 +0000745 // Loop over all of the instructions to transform, creating the new
746 // replacement instructions for them. This also unlinks them from the
747 // function so they can be safely deleted later.
748 //
749 map<Value*, Value*> XFormMap;
750 NewInstructionCreator NIC(*this, Scalars, CallMap, XFormMap);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000751
Chris Lattner441e16f2002-04-12 20:23:15 +0000752 // Visit all instructions... creating the new instructions that we need and
753 // unlinking the old instructions from the function...
754 //
755 for (unsigned i = 0, e = InstToFix.size(); i != e; ++i) {
756 cerr << "Fixing: " << InstToFix[i];
757 NIC.visit(InstToFix[i]);
758 }
759 //NIC.visit(InstToFix.begin(), InstToFix.end());
760
761 // Make all instructions we will delete "let go" of their operands... so that
762 // we can safely delete Arguments whose types have changed...
763 //
764 for_each(InstToFix.begin(), InstToFix.end(),
765 mem_fun(&Instruction::dropAllReferences));
766
767 // Loop through all of the pointer arguments coming into the function,
768 // replacing them with arguments of POINTERTYPE to match the function type of
769 // the function.
770 //
771 FunctionType::ParamTypes::const_iterator TI =
772 F->getFunctionType()->getParamTypes().begin();
773 for (Function::ArgumentListType::iterator I = F->getArgumentList().begin(),
774 E = F->getArgumentList().end(); I != E; ++I, ++TI) {
775 Argument *Arg = *I;
776 if (Arg->getType() != *TI) {
777 assert(isa<PointerType>(Arg->getType()) && *TI == POINTERTYPE);
778 Argument *NewArg = new Argument(*TI, Arg->getName());
779 XFormMap[Arg] = NewArg; // Map old arg into new arg...
780
781
782 // Replace the old argument and then delete it...
783 delete F->getArgumentList().replaceWith(I, NewArg);
784 }
785 }
786
787 // Now that all of the new instructions have been created, we can update all
788 // of the references to dummy values to be references to the actual values
789 // that are computed.
790 //
791 NIC.updateReferences();
792
793 cerr << "TRANSFORMED FUNCTION:\n" << F;
794
795
796 // Delete all of the "instructions to fix"
797 for_each(InstToFix.begin(), InstToFix.end(), deleter<Instruction>);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000798
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000799 // Since we have liberally hacked the function to pieces, we want to inform
800 // the datastructure pass that its internal representation is out of date.
801 //
802 DS->invalidateFunction(F);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000803}
804
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000805static void addNodeMapping(DSNode *SrcNode, const PointerValSet &PVS,
806 map<DSNode*, PointerValSet> &NodeMapping) {
807 for (unsigned i = 0, e = PVS.size(); i != e; ++i)
808 if (NodeMapping[SrcNode].add(PVS[i])) { // Not in map yet?
809 assert(PVS[i].Index == 0 && "Node indexing not supported yet!");
810 DSNode *DestNode = PVS[i].Node;
Chris Lattner692ad5d2002-03-29 17:13:46 +0000811
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000812 // Loop over all of the outgoing links in the mapped graph
813 for (unsigned l = 0, le = DestNode->getNumOutgoingLinks(); l != le; ++l) {
814 PointerValSet &SrcSet = SrcNode->getOutgoingLink(l);
815 const PointerValSet &DestSet = DestNode->getOutgoingLink(l);
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000816
817 // Add all of the node mappings now!
818 for (unsigned si = 0, se = SrcSet.size(); si != se; ++si) {
819 assert(SrcSet[si].Index == 0 && "Can't handle node offset!");
820 addNodeMapping(SrcSet[si].Node, DestSet, NodeMapping);
821 }
822 }
823 }
824}
825
826// CalculateNodeMapping - There is a partial isomorphism between the graph
827// passed in and the graph that is actually used by the function. We need to
828// figure out what this mapping is so that we can transformFunctionBody the
829// instructions in the function itself. Note that every node in the graph that
830// we are interested in must be both in the local graph of the called function,
831// and in the local graph of the calling function. Because of this, we only
832// define the mapping for these nodes [conveniently these are the only nodes we
833// CAN define a mapping for...]
Chris Lattner692ad5d2002-03-29 17:13:46 +0000834//
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000835// The roots of the graph that we are transforming is rooted in the arguments
836// passed into the function from the caller. This is where we start our
837// mapping calculation.
838//
839// The NodeMapping calculated maps from the callers graph to the called graph.
840//
Chris Lattner847b6e22002-03-30 20:53:14 +0000841static void CalculateNodeMapping(Function *F, TransformFunctionInfo &TFI,
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000842 FunctionDSGraph &CallerGraph,
843 FunctionDSGraph &CalledGraph,
844 map<DSNode*, PointerValSet> &NodeMapping) {
845 int LastArgNo = -2;
846 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i) {
847 // Figure out what nodes in the called graph the TFI.ArgInfo[i].Node node
848 // corresponds to...
849 //
850 // Only consider first node of sequence. Extra nodes may may be added
851 // to the TFI if the data structure requires more nodes than just the
852 // one the argument points to. We are only interested in the one the
853 // argument points to though.
854 //
855 if (TFI.ArgInfo[i].ArgNo != LastArgNo) {
856 if (TFI.ArgInfo[i].ArgNo == -1) {
857 addNodeMapping(TFI.ArgInfo[i].Node, CalledGraph.getRetNodes(),
858 NodeMapping);
859 } else {
860 // Figure out which node argument # ArgNo points to in the called graph.
Chris Lattner847b6e22002-03-30 20:53:14 +0000861 Value *Arg = F->getArgumentList()[TFI.ArgInfo[i].ArgNo];
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000862 addNodeMapping(TFI.ArgInfo[i].Node, CalledGraph.getValueMap()[Arg],
863 NodeMapping);
864 }
865 LastArgNo = TFI.ArgInfo[i].ArgNo;
866 }
867 }
868}
869
870
871// transformFunction - Transform the specified function the specified way. It
872// we have already transformed that function that way, don't do anything. The
873// nodes in the TransformFunctionInfo come out of callers data structure graph.
874//
875void PoolAllocate::transformFunction(TransformFunctionInfo &TFI,
Chris Lattner441e16f2002-04-12 20:23:15 +0000876 FunctionDSGraph &CallerIPGraph,
877 map<DSNode*, PoolInfo> &CallerPoolDesc) {
Chris Lattner692ad5d2002-03-29 17:13:46 +0000878 if (getTransformedFunction(TFI)) return; // Function xformation already done?
879
Chris Lattner441e16f2002-04-12 20:23:15 +0000880 cerr << "********** Entering transformFunction for "
Chris Lattner0dc225c2002-03-31 07:17:46 +0000881 << TFI.Func->getName() << ":\n";
882 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i)
883 cerr << " ArgInfo[" << i << "] = " << TFI.ArgInfo[i].ArgNo << "\n";
884 cerr << "\n";
885
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000886 const FunctionType *OldFuncType = TFI.Func->getFunctionType();
Chris Lattner692ad5d2002-03-29 17:13:46 +0000887
Chris Lattner291a1b12002-03-29 19:05:48 +0000888 assert(!OldFuncType->isVarArg() && "Vararg functions not handled yet!");
Chris Lattner692ad5d2002-03-29 17:13:46 +0000889
Chris Lattner291a1b12002-03-29 19:05:48 +0000890 // Build the type for the new function that we are transforming
891 vector<const Type*> ArgTys;
Chris Lattner441e16f2002-04-12 20:23:15 +0000892 ArgTys.reserve(OldFuncType->getNumParams()+TFI.ArgInfo.size());
Chris Lattner291a1b12002-03-29 19:05:48 +0000893 for (unsigned i = 0, e = OldFuncType->getNumParams(); i != e; ++i)
894 ArgTys.push_back(OldFuncType->getParamType(i));
895
Chris Lattner441e16f2002-04-12 20:23:15 +0000896 const Type *RetType = OldFuncType->getReturnType();
897
Chris Lattner291a1b12002-03-29 19:05:48 +0000898 // Add one pool pointer for every argument that needs to be supplemented.
Chris Lattner441e16f2002-04-12 20:23:15 +0000899 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i) {
900 if (TFI.ArgInfo[i].ArgNo == -1)
901 RetType = POINTERTYPE; // Return a pointer
902 else
903 ArgTys[TFI.ArgInfo[i].ArgNo] = POINTERTYPE; // Pass a pointer
904 ArgTys.push_back(PointerType::get(CallerPoolDesc.find(TFI.ArgInfo[i].Node)
905 ->second.PoolType));
906 }
Chris Lattner291a1b12002-03-29 19:05:48 +0000907
908 // Build the new function type...
Chris Lattner441e16f2002-04-12 20:23:15 +0000909 const FunctionType *NewFuncType = FunctionType::get(RetType, ArgTys,
910 OldFuncType->isVarArg());
Chris Lattner291a1b12002-03-29 19:05:48 +0000911
912 // The new function is internal, because we know that only we can call it.
913 // This also helps subsequent IP transformations to eliminate duplicated pool
Chris Lattner441e16f2002-04-12 20:23:15 +0000914 // pointers (which look like the same value is always passed into a parameter,
915 // allowing it to be easily eliminated).
Chris Lattner291a1b12002-03-29 19:05:48 +0000916 //
917 Function *NewFunc = new Function(NewFuncType, true,
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000918 TFI.Func->getName()+".poolxform");
Chris Lattner291a1b12002-03-29 19:05:48 +0000919 CurModule->getFunctionList().push_back(NewFunc);
920
Chris Lattner441e16f2002-04-12 20:23:15 +0000921
922 cerr << "Created function prototype: " << NewFunc << "\n";
923
Chris Lattner291a1b12002-03-29 19:05:48 +0000924 // Add the newly formed function to the TransformedFunctions table so that
925 // infinite recursion does not occur!
926 //
927 TransformedFunctions[TFI] = NewFunc;
928
929 // Add arguments to the function... starting with all of the old arguments
930 vector<Value*> ArgMap;
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000931 for (unsigned i = 0, e = TFI.Func->getArgumentList().size(); i != e; ++i) {
Chris Lattner2e9fa6d2002-04-09 19:48:49 +0000932 const Argument *OFA = TFI.Func->getArgumentList()[i];
933 Argument *NFA = new Argument(OFA->getType(), OFA->getName());
Chris Lattner291a1b12002-03-29 19:05:48 +0000934 NewFunc->getArgumentList().push_back(NFA);
935 ArgMap.push_back(NFA); // Keep track of the arguments
936 }
937
938 // Now add all of the arguments corresponding to pools passed in...
939 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i) {
Chris Lattner441e16f2002-04-12 20:23:15 +0000940 CallArgInfo &AI = TFI.ArgInfo[i];
Chris Lattner291a1b12002-03-29 19:05:48 +0000941 string Name;
Chris Lattner441e16f2002-04-12 20:23:15 +0000942 if (AI.ArgNo == -1)
943 Name = "ret";
Chris Lattner291a1b12002-03-29 19:05:48 +0000944 else
Chris Lattner441e16f2002-04-12 20:23:15 +0000945 Name = ArgMap[AI.ArgNo]->getName(); // Get the arg name
946 const Type *Ty = PointerType::get(CallerPoolDesc[AI.Node].PoolType);
947 Argument *NFA = new Argument(Ty, Name+".pool");
Chris Lattner291a1b12002-03-29 19:05:48 +0000948 NewFunc->getArgumentList().push_back(NFA);
949 }
950
951 // Now clone the body of the old function into the new function...
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000952 CloneFunctionInto(NewFunc, TFI.Func, ArgMap);
Chris Lattner291a1b12002-03-29 19:05:48 +0000953
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000954 // Okay, now we have a function that is identical to the old one, except that
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000955 // it has extra arguments for the pools coming in. Now we have to get the
956 // data structure graph for the function we are replacing, and figure out how
957 // our graph nodes map to the graph nodes in the dest function.
958 //
Chris Lattner847b6e22002-03-30 20:53:14 +0000959 FunctionDSGraph &DSGraph = DS->getClosedDSGraph(NewFunc);
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000960
Chris Lattner441e16f2002-04-12 20:23:15 +0000961 // NodeMapping - Multimap from callers graph to called graph. We are
962 // guaranteed that the called function graph has more nodes than the caller,
963 // or exactly the same number of nodes. This is because the called function
964 // might not know that two nodes are merged when considering the callers
965 // context, but the caller obviously does. Because of this, a single node in
966 // the calling function's data structure graph can map to multiple nodes in
967 // the called functions graph.
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000968 //
969 map<DSNode*, PointerValSet> NodeMapping;
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000970
Chris Lattner847b6e22002-03-30 20:53:14 +0000971 CalculateNodeMapping(NewFunc, TFI, CallerIPGraph, DSGraph,
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000972 NodeMapping);
973
974 // Print out the node mapping...
Chris Lattner847b6e22002-03-30 20:53:14 +0000975 cerr << "\nNode mapping for call of " << NewFunc->getName() << "\n";
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000976 for (map<DSNode*, PointerValSet>::iterator I = NodeMapping.begin();
977 I != NodeMapping.end(); ++I) {
978 cerr << "Map: "; I->first->print(cerr);
979 cerr << "To: "; I->second.print(cerr);
980 cerr << "\n";
981 }
982
983 // Fill in the PoolDescriptor information for the transformed function so that
984 // it can determine which value holds the pool descriptor for each data
985 // structure node that it accesses.
986 //
Chris Lattner441e16f2002-04-12 20:23:15 +0000987 map<DSNode*, PoolInfo> PoolDescs;
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000988
Chris Lattner847b6e22002-03-30 20:53:14 +0000989 cerr << "\nCalculating the pool descriptor map:\n";
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000990
Chris Lattner441e16f2002-04-12 20:23:15 +0000991 // Calculate as much of the pool descriptor map as possible. Since we have
992 // the node mapping between the caller and callee functions, and we have the
993 // pool descriptor information of the caller, we can calculate a partical pool
994 // descriptor map for the called function.
995 //
996 // The nodes that we do not have complete information for are the ones that
997 // are accessed by loading pointers derived from arguments passed in, but that
998 // are not passed in directly. In this case, we have all of the information
999 // except a pool value. If the called function refers to this pool, the pool
1000 // value will be loaded from the pool graph and added to the map as neccesary.
1001 //
1002 for (map<DSNode*, PointerValSet>::iterator I = NodeMapping.begin();
1003 I != NodeMapping.end(); ++I) {
1004 DSNode *CallerNode = I->first;
1005 PoolInfo &CallerPI = CallerPoolDesc[CallerNode];
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001006
Chris Lattner441e16f2002-04-12 20:23:15 +00001007 // Check to see if we have a node pointer passed in for this value...
1008 Value *CalleeValue = 0;
1009 for (unsigned a = 0, ae = TFI.ArgInfo.size(); a != ae; ++a)
1010 if (TFI.ArgInfo[a].Node == CallerNode) {
1011 // Calculate the argument number that the pool is to the function
1012 // call... The call instruction should not have the pool operands added
1013 // yet.
1014 unsigned ArgNo = TFI.Call->getNumOperands()-1+a;
1015 cerr << "Should be argument #: " << ArgNo << "[i = " << a << "]\n";
1016 assert(ArgNo < NewFunc->getArgumentList().size() &&
1017 "Call already has pool arguments added??");
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001018
Chris Lattner441e16f2002-04-12 20:23:15 +00001019 // Map the pool argument into the called function...
1020 CalleeValue = NewFunc->getArgumentList()[ArgNo];
1021 break; // Found value, quit loop
1022 }
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001023
Chris Lattner441e16f2002-04-12 20:23:15 +00001024 // Loop over all of the data structure nodes that this incoming node maps to
1025 // Creating a PoolInfo structure for them.
1026 for (unsigned i = 0, e = I->second.size(); i != e; ++i) {
1027 assert(I->second[i].Index == 0 && "Doesn't handle subindexing yet!");
1028 DSNode *CalleeNode = I->second[i].Node;
1029
1030 // Add the descriptor. We already know everything about it by now, much
1031 // of it is the same as the caller info.
1032 //
1033 PoolDescs.insert(make_pair(CalleeNode,
1034 PoolInfo(CalleeNode, CalleeValue,
1035 CallerPI.NewType,
1036 CallerPI.PoolType)));
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001037 }
Chris Lattner847b6e22002-03-30 20:53:14 +00001038 }
1039
1040 // We must destroy the node mapping so that we don't have latent references
1041 // into the data structure graph for the new function. Otherwise we get
1042 // assertion failures when transformFunctionBody tries to invalidate the
1043 // graph.
1044 //
1045 NodeMapping.clear();
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001046
1047 // Now that we know everything we need about the function, transform the body
1048 // now!
1049 //
Chris Lattner441e16f2002-04-12 20:23:15 +00001050 transformFunctionBody(NewFunc, DSGraph, PoolDescs);
1051
1052 cerr << "Function after transformation:\n" << NewFunc;
Chris Lattner66df97d2002-03-29 06:21:38 +00001053}
1054
1055
1056// CreatePools - Insert instructions into the function we are processing to
1057// create all of the memory pool objects themselves. This also inserts
1058// destruction code. Add an alloca for each pool that is allocated to the
Chris Lattner441e16f2002-04-12 20:23:15 +00001059// PoolDescs vector.
Chris Lattner66df97d2002-03-29 06:21:38 +00001060//
1061void PoolAllocate::CreatePools(Function *F, const vector<AllocDSNode*> &Allocs,
Chris Lattner441e16f2002-04-12 20:23:15 +00001062 map<DSNode*, PoolInfo> &PoolDescs) {
1063 // Find all of the return nodes in the function...
Chris Lattnere0618ca2002-03-29 05:50:20 +00001064 vector<BasicBlock*> ReturnNodes;
1065 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
1066 if (isa<ReturnInst>((*I)->getTerminator()))
1067 ReturnNodes.push_back(*I);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001068
Chris Lattner441e16f2002-04-12 20:23:15 +00001069 map<DSNode*, PATypeHolder> AbsPoolTyMap;
1070
1071 // First pass over the allocations to process...
1072 for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
1073 // Create the pooldescriptor mapping... with null entries for everything
1074 // except the node & NewType fields.
1075 //
1076 map<DSNode*, PoolInfo>::iterator PI =
1077 PoolDescs.insert(make_pair(Allocs[i], PoolInfo(Allocs[i]))).first;
1078
1079 // Create the abstract pool types that will need to be resolved in a second
1080 // pass once an abstract type is created for each pool.
1081 //
1082 // Can only handle limited shapes for now...
1083 StructType *OldNodeTy = cast<StructType>(Allocs[i]->getType());
1084 vector<const Type*> PoolTypes;
1085
1086 // Pool type is the first element of the pool descriptor type...
1087 PoolTypes.push_back(getPoolType(PoolDescs[Allocs[i]].NewType));
1088
1089 for (unsigned j = 0, e = OldNodeTy->getElementTypes().size(); j != e; ++j) {
1090 if (isa<PointerType>(OldNodeTy->getElementTypes()[j]))
1091 PoolTypes.push_back(OpaqueType::get());
1092 else
1093 assert(OldNodeTy->getElementTypes()[j]->isPrimitiveType() &&
1094 "Complex types not handled yet!");
1095 }
1096 assert(Allocs[i]->getNumLinks() == PoolTypes.size()-1 &&
1097 "Node should have same number of pointers as pool!");
1098
1099 // Create the pool type, with opaque values for pointers...
1100 AbsPoolTyMap.insert(make_pair(Allocs[i], StructType::get(PoolTypes)));
1101#ifdef DEBUG_CREATE_POOLS
1102 cerr << "POOL TY: " << AbsPoolTyMap.find(Allocs[i])->second.get() << "\n";
1103#endif
1104 }
1105
1106 // Now that we have types for all of the pool types, link them all together.
1107 for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
1108 PATypeHolder &PoolTyH = AbsPoolTyMap.find(Allocs[i])->second;
1109
1110 // Resolve all of the outgoing pointer types of this pool node...
1111 for (unsigned p = 0, pe = Allocs[i]->getNumLinks(); p != pe; ++p) {
1112 PointerValSet &PVS = Allocs[i]->getLink(p);
1113 assert(!PVS.empty() && "Outgoing edge is empty, field unused, can"
1114 " probably just leave the type opaque or something dumb.");
1115 unsigned Out;
1116 for (Out = 0; AbsPoolTyMap.count(PVS[Out].Node) == 0; ++Out)
1117 assert(Out != PVS.size() && "No edge to an outgoing allocation node!?");
1118
1119 assert(PVS[Out].Index == 0 && "Subindexing not implemented yet!");
1120
1121 // The actual struct type could change each time through the loop, so it's
1122 // NOT loop invariant.
1123 StructType *PoolTy = cast<StructType>(PoolTyH.get());
1124
1125 // Get the opaque type...
1126 DerivedType *ElTy =
1127 cast<DerivedType>(PoolTy->getElementTypes()[p+1].get());
1128
1129#ifdef DEBUG_CREATE_POOLS
1130 cerr << "Refining " << ElTy << " of " << PoolTy << " to "
1131 << AbsPoolTyMap.find(PVS[Out].Node)->second.get() << "\n";
1132#endif
1133
1134 const Type *RefPoolTy = AbsPoolTyMap.find(PVS[Out].Node)->second.get();
1135 ElTy->refineAbstractTypeTo(PointerType::get(RefPoolTy));
1136
1137#ifdef DEBUG_CREATE_POOLS
1138 cerr << "Result pool type is: " << PoolTyH.get() << "\n";
1139#endif
1140 }
1141 }
1142
1143 // Create the code that goes in the entry and exit nodes for the function...
Chris Lattnere0618ca2002-03-29 05:50:20 +00001144 vector<Instruction*> EntryNodeInsts;
1145 for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
Chris Lattner441e16f2002-04-12 20:23:15 +00001146 PoolInfo &PI = PoolDescs[Allocs[i]];
1147
1148 // Fill in the pool type for this pool...
1149 PI.PoolType = AbsPoolTyMap.find(Allocs[i])->second.get();
1150 assert(!PI.PoolType->isAbstract() &&
1151 "Pool type should not be abstract anymore!");
1152
Chris Lattnere0618ca2002-03-29 05:50:20 +00001153 // Add an allocation and a free for each pool...
Chris Lattner441e16f2002-04-12 20:23:15 +00001154 AllocaInst *PoolAlloc = new AllocaInst(PointerType::get(PI.PoolType),
1155 0, "pool");
1156 PI.Handle = PoolAlloc;
Chris Lattnere0618ca2002-03-29 05:50:20 +00001157 EntryNodeInsts.push_back(PoolAlloc);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001158 AllocationInst *AI = Allocs[i]->getAllocation();
1159
1160 // Initialize the pool. We need to know how big each allocation is. For
1161 // our purposes here, we assume we are allocating a scalar, or array of
1162 // constant size.
1163 //
1164 unsigned ElSize = TargetData.getTypeSize(AI->getAllocatedType());
1165 ElSize *= cast<ConstantUInt>(AI->getArraySize())->getValue();
1166
1167 vector<Value*> Args;
Chris Lattnere0618ca2002-03-29 05:50:20 +00001168 Args.push_back(ConstantUInt::get(Type::UIntTy, ElSize));
Chris Lattner441e16f2002-04-12 20:23:15 +00001169 Args.push_back(PoolAlloc); // Pool to initialize
Chris Lattnere0618ca2002-03-29 05:50:20 +00001170 EntryNodeInsts.push_back(new CallInst(PoolInit, Args));
1171
Chris Lattner441e16f2002-04-12 20:23:15 +00001172 // FIXME: add code to initialize inter pool links
1173 cerr << "TODO: add code to initialize inter pool links!\n";
Chris Lattnere0618ca2002-03-29 05:50:20 +00001174
Chris Lattner441e16f2002-04-12 20:23:15 +00001175 // Add code to destroy the pool in all of the exit nodes of the function...
1176 Args.pop_back();
Chris Lattnere0618ca2002-03-29 05:50:20 +00001177 for (unsigned EN = 0, ENE = ReturnNodes.size(); EN != ENE; ++EN) {
1178 Instruction *Destroy = new CallInst(PoolDestroy, Args);
1179
1180 // Insert it before the return instruction...
1181 BasicBlock *RetNode = ReturnNodes[EN];
1182 RetNode->getInstList().insert(RetNode->end()-1, Destroy);
1183 }
1184 }
1185
1186 // Insert the entry node code into the entry block...
1187 F->getEntryNode()->getInstList().insert(F->getEntryNode()->begin()+1,
1188 EntryNodeInsts.begin(),
1189 EntryNodeInsts.end());
Chris Lattner175f37c2002-03-29 03:40:59 +00001190}
1191
1192
Chris Lattner441e16f2002-04-12 20:23:15 +00001193// addPoolPrototypes - Add prototypes for the pool functions to the specified
Chris Lattner175f37c2002-03-29 03:40:59 +00001194// module and update the Pool* instance variables to point to them.
1195//
1196void PoolAllocate::addPoolPrototypes(Module *M) {
Chris Lattner441e16f2002-04-12 20:23:15 +00001197 // Get poolinit function...
Chris Lattnere0618ca2002-03-29 05:50:20 +00001198 vector<const Type*> Args;
Chris Lattnere0618ca2002-03-29 05:50:20 +00001199 Args.push_back(Type::UIntTy); // Num bytes per element
Chris Lattner441e16f2002-04-12 20:23:15 +00001200 FunctionType *PoolInitTy = FunctionType::get(Type::VoidTy, Args, true);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001201 PoolInit = M->getOrInsertFunction("poolinit", PoolInitTy);
Chris Lattner175f37c2002-03-29 03:40:59 +00001202
Chris Lattnere0618ca2002-03-29 05:50:20 +00001203 // Get pooldestroy function...
1204 Args.pop_back(); // Only takes a pool...
Chris Lattner441e16f2002-04-12 20:23:15 +00001205 FunctionType *PoolDestroyTy = FunctionType::get(Type::VoidTy, Args, true);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001206 PoolDestroy = M->getOrInsertFunction("pooldestroy", PoolDestroyTy);
1207
Chris Lattnere0618ca2002-03-29 05:50:20 +00001208 // Get the poolalloc function...
Chris Lattner441e16f2002-04-12 20:23:15 +00001209 FunctionType *PoolAllocTy = FunctionType::get(POINTERTYPE, Args, true);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001210 PoolAlloc = M->getOrInsertFunction("poolalloc", PoolAllocTy);
1211
1212 // Get the poolfree function...
Chris Lattner441e16f2002-04-12 20:23:15 +00001213 Args.push_back(POINTERTYPE); // Pointer to free
1214 FunctionType *PoolFreeTy = FunctionType::get(Type::VoidTy, Args, true);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001215 PoolFree = M->getOrInsertFunction("poolfree", PoolFreeTy);
1216
1217 // Add the %PoolTy type to the symbol table of the module...
Chris Lattner441e16f2002-04-12 20:23:15 +00001218 //M->addTypeName("PoolTy", PoolTy->getElementType());
Chris Lattner175f37c2002-03-29 03:40:59 +00001219}
1220
1221
1222bool PoolAllocate::run(Module *M) {
1223 addPoolPrototypes(M);
1224 CurModule = M;
1225
1226 DS = &getAnalysis<DataStructure>();
1227 bool Changed = false;
Chris Lattner291a1b12002-03-29 19:05:48 +00001228
1229 // We cannot use an iterator here because it will get invalidated when we add
1230 // functions to the module later...
1231 for (unsigned i = 0; i != M->size(); ++i)
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001232 if (!M->getFunctionList()[i]->isExternal()) {
Chris Lattner291a1b12002-03-29 19:05:48 +00001233 Changed |= processFunction(M->getFunctionList()[i]);
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001234 if (Changed) {
1235 cerr << "Only processing one function\n";
1236 break;
1237 }
1238 }
Chris Lattner175f37c2002-03-29 03:40:59 +00001239
1240 CurModule = 0;
1241 DS = 0;
1242 return false;
1243}
1244
1245
1246// createPoolAllocatePass - Global function to access the functionality of this
1247// pass...
1248//
Chris Lattner64fd9352002-03-28 18:08:31 +00001249Pass *createPoolAllocatePass() { return new PoolAllocate(); }