blob: 1d1e2fe14c76945ca816f311c44304361c01e5d6 [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);
Chris Lattner8f796d62002-04-13 19:25:57 +0000168 StructType *Result = StructType::get(PoolElements);
169
170 // Add a name to the symbol table to correspond to the backend
171 // representation of this pool...
172 assert(CurModule && "No current module!?");
173 string Name = CurModule->getTypeName(NodeType);
174 if (Name.empty()) Name = CurModule->getTypeName(PoolElements[0]);
175 CurModule->addTypeName(Name+"oolbe", Result);
176
177 return Result;
Chris Lattner441e16f2002-04-12 20:23:15 +0000178 }
179
Chris Lattner175f37c2002-03-29 03:40:59 +0000180 bool run(Module *M);
181
182 // getAnalysisUsageInfo - This function requires data structure information
183 // to be able to see what is pool allocatable.
Chris Lattner64fd9352002-03-28 18:08:31 +0000184 //
185 virtual void getAnalysisUsageInfo(Pass::AnalysisSet &Required,
Chris Lattner175f37c2002-03-29 03:40:59 +0000186 Pass::AnalysisSet &,Pass::AnalysisSet &) {
Chris Lattner64fd9352002-03-28 18:08:31 +0000187 Required.push_back(DataStructure::ID);
188 }
Chris Lattner175f37c2002-03-29 03:40:59 +0000189
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000190 public:
Chris Lattner175f37c2002-03-29 03:40:59 +0000191 // CurModule - The module being processed.
192 Module *CurModule;
193
194 // DS - The data structure graph for the module being processed.
195 DataStructure *DS;
196
197 // Prototypes that we add to support pool allocation...
198 Function *PoolInit, *PoolDestroy, *PoolAlloc, *PoolFree;
199
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000200 // The map of already transformed functions... note that the keys of this
201 // map do not have meaningful values for 'Call' or the 'PoolHandle' elements
202 // of the ArgInfo elements.
203 //
Chris Lattner692ad5d2002-03-29 17:13:46 +0000204 map<TransformFunctionInfo, Function*> TransformedFunctions;
205
206 // getTransformedFunction - Get a transformed function, or return null if
207 // the function specified hasn't been transformed yet.
208 //
209 Function *getTransformedFunction(TransformFunctionInfo &TFI) const {
210 map<TransformFunctionInfo, Function*>::const_iterator I =
211 TransformedFunctions.find(TFI);
212 if (I != TransformedFunctions.end()) return I->second;
213 return 0;
214 }
215
216
Chris Lattner441e16f2002-04-12 20:23:15 +0000217 // addPoolPrototypes - Add prototypes for the pool functions to the
218 // specified module and update the Pool* instance variables to point to
219 // them.
Chris Lattner175f37c2002-03-29 03:40:59 +0000220 //
221 void addPoolPrototypes(Module *M);
222
Chris Lattner66df97d2002-03-29 06:21:38 +0000223
224 // CreatePools - Insert instructions into the function we are processing to
225 // create all of the memory pool objects themselves. This also inserts
226 // destruction code. Add an alloca for each pool that is allocated to the
Chris Lattner441e16f2002-04-12 20:23:15 +0000227 // PoolDescs map.
Chris Lattner66df97d2002-03-29 06:21:38 +0000228 //
229 void CreatePools(Function *F, const vector<AllocDSNode*> &Allocs,
Chris Lattner441e16f2002-04-12 20:23:15 +0000230 map<DSNode*, PoolInfo> &PoolDescs);
Chris Lattner66df97d2002-03-29 06:21:38 +0000231
Chris Lattner175f37c2002-03-29 03:40:59 +0000232 // processFunction - Convert a function to use pool allocation where
233 // available.
234 //
235 bool processFunction(Function *F);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000236
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000237 // transformFunctionBody - This transforms the instruction in 'F' to use the
Chris Lattner441e16f2002-04-12 20:23:15 +0000238 // pools specified in PoolDescs when modifying data structure nodes
239 // specified in the PoolDescs map. IPFGraph is the closed data structure
240 // graph for F, of which the PoolDescriptor nodes come from.
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000241 //
242 void transformFunctionBody(Function *F, FunctionDSGraph &IPFGraph,
Chris Lattner441e16f2002-04-12 20:23:15 +0000243 map<DSNode*, PoolInfo> &PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000244
245 // transformFunction - Transform the specified function the specified way.
246 // It we have already transformed that function that way, don't do anything.
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000247 // The nodes in the TransformFunctionInfo come out of callers data structure
Chris Lattner441e16f2002-04-12 20:23:15 +0000248 // graph, and the PoolDescs passed in are the caller's.
Chris Lattner692ad5d2002-03-29 17:13:46 +0000249 //
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000250 void transformFunction(TransformFunctionInfo &TFI,
Chris Lattner441e16f2002-04-12 20:23:15 +0000251 FunctionDSGraph &CallerIPGraph,
252 map<DSNode*, PoolInfo> &PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000253
Chris Lattner64fd9352002-03-28 18:08:31 +0000254 };
255}
256
Chris Lattner692ad5d2002-03-29 17:13:46 +0000257// isNotPoolableAlloc - This is a predicate that returns true if the specified
Chris Lattner175f37c2002-03-29 03:40:59 +0000258// allocation node in a data structure graph is eligable for pool allocation.
259//
260static bool isNotPoolableAlloc(const AllocDSNode *DS) {
Chris Lattnere0618ca2002-03-29 05:50:20 +0000261 if (DS->isAllocaNode()) return true; // Do not pool allocate alloca's.
Chris Lattner175f37c2002-03-29 03:40:59 +0000262
263 MallocInst *MI = cast<MallocInst>(DS->getAllocation());
264 if (MI->isArrayAllocation() && !isa<Constant>(MI->getArraySize()))
Chris Lattnere0618ca2002-03-29 05:50:20 +0000265 return true; // Do not allow variable size allocations...
Chris Lattner175f37c2002-03-29 03:40:59 +0000266
Chris Lattnere0618ca2002-03-29 05:50:20 +0000267 return false;
Chris Lattner175f37c2002-03-29 03:40:59 +0000268}
269
Chris Lattner175f37c2002-03-29 03:40:59 +0000270// processFunction - Convert a function to use pool allocation where
271// available.
272//
273bool PoolAllocate::processFunction(Function *F) {
274 // Get the closed datastructure graph for the current function... if there are
275 // any allocations in this graph that are not escaping, we need to pool
276 // allocate them here!
277 //
278 FunctionDSGraph &IPGraph = DS->getClosedDSGraph(F);
279
280 // Get all of the allocations that do not escape the current function. Since
281 // they are still live (they exist in the graph at all), this means we must
282 // have scalar references to these nodes, but the scalars are never returned.
283 //
Chris Lattner692ad5d2002-03-29 17:13:46 +0000284 vector<AllocDSNode*> Allocs;
Chris Lattner175f37c2002-03-29 03:40:59 +0000285 IPGraph.getNonEscapingAllocations(Allocs);
286
287 // Filter out allocations that we cannot handle. Currently, this includes
288 // variable sized array allocations and alloca's (which we do not want to
289 // pool allocate)
290 //
291 Allocs.erase(remove_if(Allocs.begin(), Allocs.end(), isNotPoolableAlloc),
292 Allocs.end());
293
294
295 if (Allocs.empty()) return false; // Nothing to do.
296
Chris Lattner692ad5d2002-03-29 17:13:46 +0000297 // Insert instructions into the function we are processing to create all of
298 // the memory pool objects themselves. This also inserts destruction code.
Chris Lattner441e16f2002-04-12 20:23:15 +0000299 // This fills in the PoolDescs map to associate the alloc node with the
Chris Lattner396d5d72002-03-30 04:02:31 +0000300 // allocation of the memory pool corresponding to it.
Chris Lattner692ad5d2002-03-29 17:13:46 +0000301 //
Chris Lattner441e16f2002-04-12 20:23:15 +0000302 map<DSNode*, PoolInfo> PoolDescs;
303 CreatePools(F, Allocs, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000304
Chris Lattner441e16f2002-04-12 20:23:15 +0000305 cerr << "Transformed Entry Function: \n" << F;
306
307 // Now we need to figure out what called functions we need to transform, and
Chris Lattner692ad5d2002-03-29 17:13:46 +0000308 // how. To do this, we look at all of the scalars, seeing which functions are
309 // either used as a scalar value (so they return a data structure), or are
310 // passed one of our scalar values.
311 //
Chris Lattner441e16f2002-04-12 20:23:15 +0000312 transformFunctionBody(F, IPGraph, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000313
314 return true;
315}
316
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000317
Chris Lattner441e16f2002-04-12 20:23:15 +0000318//===----------------------------------------------------------------------===//
319//
320// NewInstructionCreator - This class is used to traverse the function being
321// modified, changing each instruction visit'ed to use and provide pointer
322// indexes instead of real pointers. This is what changes the body of a
323// function to use pool allocation.
324//
325class NewInstructionCreator : public InstVisitor<NewInstructionCreator> {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000326 PoolAllocate &PoolAllocator;
327 vector<ScalarInfo> &Scalars;
328 map<CallInst*, TransformFunctionInfo> &CallMap;
Chris Lattner441e16f2002-04-12 20:23:15 +0000329 map<Value*, Value*> &XFormMap; // Map old pointers to new indexes
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000330
Chris Lattner441e16f2002-04-12 20:23:15 +0000331 struct RefToUpdate {
332 Instruction *I; // Instruction to update
333 unsigned OpNum; // Operand number to update
334 Value *OldVal; // The old value it had
335
336 RefToUpdate(Instruction *i, unsigned o, Value *ov)
337 : I(i), OpNum(o), OldVal(ov) {}
338 };
339 vector<RefToUpdate> ReferencesToUpdate;
340
341 const ScalarInfo &getScalarRef(const Value *V) {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000342 for (unsigned i = 0, e = Scalars.size(); i != e; ++i)
343 if (Scalars[i].Val == V) return Scalars[i];
344 assert(0 && "Scalar not found in getScalar!");
345 abort();
346 return Scalars[0];
347 }
Chris Lattner441e16f2002-04-12 20:23:15 +0000348
349 const ScalarInfo *getScalar(const Value *V) {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000350 for (unsigned i = 0, e = Scalars.size(); i != e; ++i)
Chris Lattner441e16f2002-04-12 20:23:15 +0000351 if (Scalars[i].Val == V) return &Scalars[i];
352 return 0;
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000353 }
354
Chris Lattner441e16f2002-04-12 20:23:15 +0000355 BasicBlock::iterator ReplaceInstWith(Instruction *I, Instruction *New) {
356 BasicBlock *BB = I->getParent();
357 BasicBlock::iterator RI = find(BB->begin(), BB->end(), I);
358 BB->getInstList().replaceWith(RI, New);
359 XFormMap[I] = New;
360 return RI;
361 }
362
363 LoadInst *createPoolBaseInstruction(Value *PtrVal) {
364 const ScalarInfo &SC = getScalarRef(PtrVal);
365 vector<Value*> Args(3);
366 Args[0] = ConstantUInt::get(Type::UIntTy, 0); // No pointer offset
367 Args[1] = ConstantUInt::get(Type::UByteTy, 0); // Field #0 of pool descriptr
368 Args[2] = ConstantUInt::get(Type::UByteTy, 0); // Field #0 of poolalloc val
369 return new LoadInst(SC.Pool.Handle, Args, PtrVal->getName()+".poolbase");
370 }
371
372
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000373public:
Chris Lattner441e16f2002-04-12 20:23:15 +0000374 NewInstructionCreator(PoolAllocate &PA, vector<ScalarInfo> &S,
375 map<CallInst*, TransformFunctionInfo> &C,
376 map<Value*, Value*> &X)
377 : PoolAllocator(PA), Scalars(S), CallMap(C), XFormMap(X) {}
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000378
Chris Lattner441e16f2002-04-12 20:23:15 +0000379
380 // updateReferences - The NewInstructionCreator is responsible for creating
381 // new instructions to replace the old ones in the function, and then link up
382 // references to values to their new values. For it to do this, however, it
383 // keeps track of information about the value mapping of old values to new
384 // values that need to be patched up. Given this value map and a set of
385 // instruction operands to patch, updateReferences performs the updates.
386 //
387 void updateReferences() {
388 for (unsigned i = 0, e = ReferencesToUpdate.size(); i != e; ++i) {
389 RefToUpdate &Ref = ReferencesToUpdate[i];
390 Value *NewVal = XFormMap[Ref.OldVal];
391
392 if (NewVal == 0) {
393 if (isa<Constant>(Ref.OldVal) && // Refering to a null ptr?
394 cast<Constant>(Ref.OldVal)->isNullValue()) {
395 // Transform the null pointer into a null index... caching in XFormMap
396 XFormMap[Ref.OldVal] = NewVal =Constant::getNullConstant(POINTERTYPE);
397 //} else if (isa<Argument>(Ref.OldVal)) {
398 } else {
399 cerr << "Unknown reference to: " << Ref.OldVal << "\n";
400 assert(XFormMap[Ref.OldVal] &&
401 "Reference to value that was not updated found!");
402 }
403 }
404
405 Ref.I->setOperand(Ref.OpNum, NewVal);
406 }
407 ReferencesToUpdate.clear();
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000408 }
409
Chris Lattner441e16f2002-04-12 20:23:15 +0000410 //===--------------------------------------------------------------------===//
411 // Transformation methods:
412 // These methods specify how each type of instruction is transformed by the
413 // NewInstructionCreator instance...
414 //===--------------------------------------------------------------------===//
415
416 void visitGetElementPtrInst(GetElementPtrInst *I) {
417 assert(0 && "Cannot transform get element ptr instructions yet!");
418 }
419
420 // Replace the load instruction with a new one.
421 void visitLoadInst(LoadInst *I) {
422 Instruction *PoolBase = createPoolBaseInstruction(I->getOperand(0));
423
424 // Cast our index to be a UIntTy so we can use it to index into the pool...
425 CastInst *Index = new CastInst(Constant::getNullConstant(POINTERTYPE),
426 Type::UIntTy, I->getOperand(0)->getName());
427
428 ReferencesToUpdate.push_back(RefToUpdate(Index, 0, I->getOperand(0)));
429
430 vector<Value*> Indices(I->idx_begin(), I->idx_end());
431 assert(Indices[0] == ConstantUInt::get(Type::UIntTy, 0) &&
432 "Cannot handle array indexing yet!");
433 Indices[0] = Index;
434 Instruction *NewLoad = new LoadInst(PoolBase, Indices, I->getName());
435
436 // Replace the load instruction with the new load instruction...
437 BasicBlock::iterator II = ReplaceInstWith(I, NewLoad);
438
439 // Add the pool base calculator instruction before the load...
440 II = NewLoad->getParent()->getInstList().insert(II, PoolBase) + 1;
441
442 // Add the cast before the load instruction...
443 NewLoad->getParent()->getInstList().insert(II, Index);
444
445 // If not yielding a pool allocated pointer, use the new load value as the
446 // value in the program instead of the old load value...
447 //
448 if (!getScalar(I))
449 I->replaceAllUsesWith(NewLoad);
450 }
451
452 // Replace the store instruction with a new one. In the store instruction,
453 // the value stored could be a pointer type, meaning that the new store may
454 // have to change one or both of it's operands.
455 //
456 void visitStoreInst(StoreInst *I) {
457 assert(getScalar(I->getOperand(1)) &&
458 "Store inst found only storing pool allocated pointer. "
459 "Not imp yet!");
460
461 Value *Val = I->getOperand(0); // The value to store...
462 // Check to see if the value we are storing is a data structure pointer...
463 if (const ScalarInfo *ValScalar = getScalar(I->getOperand(0)))
464 Val = Constant::getNullConstant(POINTERTYPE); // Yes, store a dummy
465
466 Instruction *PoolBase = createPoolBaseInstruction(I->getOperand(1));
467
468 // Cast our index to be a UIntTy so we can use it to index into the pool...
469 CastInst *Index = new CastInst(Constant::getNullConstant(POINTERTYPE),
470 Type::UIntTy, I->getOperand(1)->getName());
471 ReferencesToUpdate.push_back(RefToUpdate(Index, 0, I->getOperand(1)));
472
473 vector<Value*> Indices(I->idx_begin(), I->idx_end());
474 assert(Indices[0] == ConstantUInt::get(Type::UIntTy, 0) &&
475 "Cannot handle array indexing yet!");
476 Indices[0] = Index;
477 Instruction *NewStore = new StoreInst(Val, PoolBase, Indices);
478
479 if (Val != I->getOperand(0)) // Value stored was a pointer?
480 ReferencesToUpdate.push_back(RefToUpdate(NewStore, 0, I->getOperand(0)));
481
482
483 // Replace the store instruction with the cast instruction...
484 BasicBlock::iterator II = ReplaceInstWith(I, Index);
485
486 // Add the pool base calculator instruction before the index...
487 II = Index->getParent()->getInstList().insert(II, PoolBase) + 2;
488
489 // Add the store after the cast instruction...
490 Index->getParent()->getInstList().insert(II, NewStore);
491 }
492
493
494 // Create call to poolalloc for every malloc instruction
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000495 void visitMallocInst(MallocInst *I) {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000496 vector<Value*> Args;
Chris Lattner441e16f2002-04-12 20:23:15 +0000497 Args.push_back(getScalarRef(I).Pool.Handle);
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000498 CallInst *Call = new CallInst(PoolAllocator.PoolAlloc, Args, I->getName());
Chris Lattner441e16f2002-04-12 20:23:15 +0000499 ReplaceInstWith(I, Call);
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000500 }
501
Chris Lattner441e16f2002-04-12 20:23:15 +0000502 // Convert a call to poolfree for every free instruction...
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000503 void visitFreeInst(FreeInst *I) {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000504 // Create a new call to poolfree before the free instruction
505 vector<Value*> Args;
Chris Lattner441e16f2002-04-12 20:23:15 +0000506 Args.push_back(Constant::getNullConstant(POINTERTYPE));
507 Args.push_back(getScalarRef(I->getOperand(0)).Pool.Handle);
508 Instruction *NewCall = new CallInst(PoolAllocator.PoolFree, Args);
509 ReplaceInstWith(I, NewCall);
510 ReferencesToUpdate.push_back(RefToUpdate(NewCall, 0, I->getOperand(0)));
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000511 }
512
513 // visitCallInst - Create a new call instruction with the extra arguments for
514 // all of the memory pools that the call needs.
515 //
516 void visitCallInst(CallInst *I) {
517 TransformFunctionInfo &TI = CallMap[I];
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000518
519 // Start with all of the old arguments...
520 vector<Value*> Args(I->op_begin()+1, I->op_end());
521
Chris Lattner441e16f2002-04-12 20:23:15 +0000522 for (unsigned i = 0, e = TI.ArgInfo.size(); i != e; ++i) {
523 // Replace all of the pointer arguments with our new pointer typed values.
524 if (TI.ArgInfo[i].ArgNo != -1)
525 Args[TI.ArgInfo[i].ArgNo] = Constant::getNullConstant(POINTERTYPE);
526
527 // Add all of the pool arguments...
Chris Lattner396d5d72002-03-30 04:02:31 +0000528 Args.push_back(TI.ArgInfo[i].PoolHandle);
Chris Lattner441e16f2002-04-12 20:23:15 +0000529 }
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000530
531 Function *NF = PoolAllocator.getTransformedFunction(TI);
Chris Lattner441e16f2002-04-12 20:23:15 +0000532 Instruction *NewCall = new CallInst(NF, Args, I->getName());
533 ReplaceInstWith(I, NewCall);
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000534
Chris Lattner441e16f2002-04-12 20:23:15 +0000535 // Keep track of the mapping of operands so that we can resolve them to real
536 // values later.
537 Value *RetVal = NewCall;
538 for (unsigned i = 0, e = TI.ArgInfo.size(); i != e; ++i)
539 if (TI.ArgInfo[i].ArgNo != -1)
540 ReferencesToUpdate.push_back(RefToUpdate(NewCall, TI.ArgInfo[i].ArgNo+1,
541 I->getOperand(TI.ArgInfo[i].ArgNo+1)));
542 else
543 RetVal = 0; // If returning a pointer, don't change retval...
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000544
Chris Lattner441e16f2002-04-12 20:23:15 +0000545 // If not returning a pointer, use the new call as the value in the program
546 // instead of the old call...
547 //
548 if (RetVal)
549 I->replaceAllUsesWith(RetVal);
550 }
551
552 // visitPHINode - Create a new PHI node of POINTERTYPE for all of the old Phi
553 // nodes...
554 //
555 void visitPHINode(PHINode *PN) {
556 Value *DummyVal = Constant::getNullConstant(POINTERTYPE);
557 PHINode *NewPhi = new PHINode(POINTERTYPE, PN->getName());
558 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
559 NewPhi->addIncoming(DummyVal, PN->getIncomingBlock(i));
560 ReferencesToUpdate.push_back(RefToUpdate(NewPhi, i*2,
561 PN->getIncomingValue(i)));
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000562 }
563
Chris Lattner441e16f2002-04-12 20:23:15 +0000564 ReplaceInstWith(PN, NewPhi);
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000565 }
566
Chris Lattner441e16f2002-04-12 20:23:15 +0000567 // visitReturnInst - Replace ret instruction with a new return...
Chris Lattner847b6e22002-03-30 20:53:14 +0000568 void visitReturnInst(ReturnInst *I) {
Chris Lattner441e16f2002-04-12 20:23:15 +0000569 Instruction *Ret = new ReturnInst(Constant::getNullConstant(POINTERTYPE));
570 ReplaceInstWith(I, Ret);
571 ReferencesToUpdate.push_back(RefToUpdate(Ret, 0, I->getOperand(0)));
Chris Lattner847b6e22002-03-30 20:53:14 +0000572 }
573
Chris Lattner441e16f2002-04-12 20:23:15 +0000574 // visitSetCondInst - Replace a conditional test instruction with a new one
Chris Lattnercf09a2a2002-04-01 00:45:33 +0000575 void visitSetCondInst(SetCondInst *SCI) {
Chris Lattner441e16f2002-04-12 20:23:15 +0000576 BinaryOperator *I = (BinaryOperator*)SCI;
577 Value *DummyVal = Constant::getNullConstant(POINTERTYPE);
578 BinaryOperator *New = BinaryOperator::create(I->getOpcode(), DummyVal,
579 DummyVal, I->getName());
580 ReplaceInstWith(I, New);
581
582 ReferencesToUpdate.push_back(RefToUpdate(New, 0, I->getOperand(0)));
583 ReferencesToUpdate.push_back(RefToUpdate(New, 1, I->getOperand(1)));
584
585 // Make sure branches refer to the new condition...
586 I->replaceAllUsesWith(New);
Chris Lattnercf09a2a2002-04-01 00:45:33 +0000587 }
588
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000589 void visitInstruction(Instruction *I) {
Chris Lattner441e16f2002-04-12 20:23:15 +0000590 cerr << "Unknown instruction to FunctionBodyTransformer:\n" << I;
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000591 }
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000592};
593
594
Chris Lattner441e16f2002-04-12 20:23:15 +0000595
596
Chris Lattner0dc225c2002-03-31 07:17:46 +0000597static void addCallInfo(DataStructure *DS,
598 TransformFunctionInfo &TFI, CallInst *CI, int Arg,
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000599 DSNode *GraphNode,
Chris Lattner441e16f2002-04-12 20:23:15 +0000600 map<DSNode*, PoolInfo> &PoolDescs) {
Chris Lattner0dc225c2002-03-31 07:17:46 +0000601 assert(CI->getCalledFunction() && "Cannot handle indirect calls yet!");
602 assert(TFI.Func == 0 || TFI.Func == CI->getCalledFunction() &&
603 "Function call record should always call the same function!");
604 assert(TFI.Call == 0 || TFI.Call == CI &&
605 "Call element already filled in with different value!");
606 TFI.Func = CI->getCalledFunction();
607 TFI.Call = CI;
608 //FunctionDSGraph &CalledGraph = DS->getClosedDSGraph(TFI.Func);
Chris Lattner396d5d72002-03-30 04:02:31 +0000609
610 // For now, add the entire graph that is pointed to by the call argument.
611 // This graph can and should be pruned to only what the function itself will
612 // use, because often this will be a dramatically smaller subset of what we
613 // are providing.
614 //
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000615 for (df_iterator<DSNode*> I = df_begin(GraphNode), E = df_end(GraphNode);
Chris Lattner441e16f2002-04-12 20:23:15 +0000616 I != E; ++I)
617 TFI.ArgInfo.push_back(CallArgInfo(Arg, *I, PoolDescs[*I].Handle));
Chris Lattner396d5d72002-03-30 04:02:31 +0000618}
619
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000620
621// transformFunctionBody - This transforms the instruction in 'F' to use the
Chris Lattner441e16f2002-04-12 20:23:15 +0000622// pools specified in PoolDescs when modifying data structure nodes specified in
623// the PoolDescs map. Specifically, scalar values specified in the Scalars
624// vector must be remapped. IPFGraph is the closed data structure graph for F,
625// of which the PoolDescriptor nodes come from.
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000626//
627void PoolAllocate::transformFunctionBody(Function *F, FunctionDSGraph &IPFGraph,
Chris Lattner441e16f2002-04-12 20:23:15 +0000628 map<DSNode*, PoolInfo> &PoolDescs) {
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000629
630 // Loop through the value map looking for scalars that refer to nonescaping
631 // allocations. Add them to the Scalars vector. Note that we may have
632 // multiple entries in the Scalars vector for each value if it points to more
633 // than one object.
634 //
635 map<Value*, PointerValSet> &ValMap = IPFGraph.getValueMap();
636 vector<ScalarInfo> Scalars;
637
Chris Lattner847b6e22002-03-30 20:53:14 +0000638 cerr << "Building scalar map:\n";
639
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000640 for (map<Value*, PointerValSet>::iterator I = ValMap.begin(),
641 E = ValMap.end(); I != E; ++I) {
642 const PointerValSet &PVS = I->second; // Set of things pointed to by scalar
643
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000644 // Check to see if the scalar points to a data structure node...
645 for (unsigned i = 0, e = PVS.size(); i != e; ++i) {
646 assert(PVS[i].Index == 0 && "Nonzero not handled yet!");
647
648 // If the allocation is in the nonescaping set...
Chris Lattner441e16f2002-04-12 20:23:15 +0000649 map<DSNode*, PoolInfo>::iterator AI = PoolDescs.find(PVS[i].Node);
650 if (AI != PoolDescs.end()) { // Add it to the list of scalars
651 Scalars.push_back(ScalarInfo(I->first, AI->second));
652 cerr << "\nScalar Mapping from:" << I->first
653 << "Scalar Mapping to: "; PVS.print(cerr);
654 }
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000655 }
656 }
657
658
659
Chris Lattner847b6e22002-03-30 20:53:14 +0000660 cerr << "\nIn '" << F->getName()
Chris Lattner175f37c2002-03-29 03:40:59 +0000661 << "': Found the following values that point to poolable nodes:\n";
662
663 for (unsigned i = 0, e = Scalars.size(); i != e; ++i)
Chris Lattner441e16f2002-04-12 20:23:15 +0000664 cerr << Scalars[i].Val;
665 cerr << "\n";
Chris Lattnere0618ca2002-03-29 05:50:20 +0000666
Chris Lattner692ad5d2002-03-29 17:13:46 +0000667 // CallMap - Contain an entry for every call instruction that needs to be
668 // transformed. Each entry in the map contains information about what we need
669 // to do to each call site to change it to work.
670 //
671 map<CallInst*, TransformFunctionInfo> CallMap;
Chris Lattner66df97d2002-03-29 06:21:38 +0000672
Chris Lattner441e16f2002-04-12 20:23:15 +0000673 // Now we need to figure out what called functions we need to transform, and
Chris Lattner692ad5d2002-03-29 17:13:46 +0000674 // how. To do this, we look at all of the scalars, seeing which functions are
675 // either used as a scalar value (so they return a data structure), or are
676 // passed one of our scalar values.
677 //
678 for (unsigned i = 0, e = Scalars.size(); i != e; ++i) {
679 Value *ScalarVal = Scalars[i].Val;
680
681 // Check to see if the scalar _IS_ a call...
682 if (CallInst *CI = dyn_cast<CallInst>(ScalarVal))
683 // If so, add information about the pool it will be returning...
Chris Lattner441e16f2002-04-12 20:23:15 +0000684 addCallInfo(DS, CallMap[CI], CI, -1, Scalars[i].Pool.Node, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000685
686 // Check to see if the scalar is an operand to a call...
687 for (Value::use_iterator UI = ScalarVal->use_begin(),
688 UE = ScalarVal->use_end(); UI != UE; ++UI) {
689 if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
690 // Find out which operand this is to the call instruction...
691 User::op_iterator OI = find(CI->op_begin(), CI->op_end(), ScalarVal);
692 assert(OI != CI->op_end() && "Call on use list but not an operand!?");
693 assert(OI != CI->op_begin() && "Pointer operand is call destination?");
694
695 // FIXME: This is broken if the same pointer is passed to a call more
696 // than once! It will get multiple entries for the first pointer.
697
698 // Add the operand number and pool handle to the call table...
Chris Lattner441e16f2002-04-12 20:23:15 +0000699 addCallInfo(DS, CallMap[CI], CI, OI-CI->op_begin()-1,
700 Scalars[i].Pool.Node, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000701 }
702 }
703 }
704
705 // Print out call map...
706 for (map<CallInst*, TransformFunctionInfo>::iterator I = CallMap.begin();
707 I != CallMap.end(); ++I) {
Chris Lattner441e16f2002-04-12 20:23:15 +0000708 cerr << "For call: " << I->first;
Chris Lattner692ad5d2002-03-29 17:13:46 +0000709 I->second.finalizeConstruction();
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000710 cerr << I->second.Func->getName() << " must pass pool pointer for args #";
Chris Lattner692ad5d2002-03-29 17:13:46 +0000711 for (unsigned i = 0; i < I->second.ArgInfo.size(); ++i)
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000712 cerr << I->second.ArgInfo[i].ArgNo << ", ";
Chris Lattner441e16f2002-04-12 20:23:15 +0000713 cerr << "\n\n";
Chris Lattner692ad5d2002-03-29 17:13:46 +0000714 }
715
716 // Loop through all of the call nodes, recursively creating the new functions
717 // that we want to call... This uses a map to prevent infinite recursion and
718 // to avoid duplicating functions unneccesarily.
719 //
720 for (map<CallInst*, TransformFunctionInfo>::iterator I = CallMap.begin(),
721 E = CallMap.end(); I != E; ++I) {
722 // Make sure the entries are sorted.
723 I->second.finalizeConstruction();
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000724
725 // Transform all of the functions we need, or at least ensure there is a
726 // cached version available.
Chris Lattner441e16f2002-04-12 20:23:15 +0000727 transformFunction(I->second, IPFGraph, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000728 }
729
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000730 // Now that all of the functions that we want to call are available, transform
Chris Lattner441e16f2002-04-12 20:23:15 +0000731 // the local function so that it uses the pools locally and passes them to the
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000732 // functions that we just hacked up.
733 //
734
735 // First step, find the instructions to be modified.
736 vector<Instruction*> InstToFix;
737 for (unsigned i = 0, e = Scalars.size(); i != e; ++i) {
738 Value *ScalarVal = Scalars[i].Val;
739
740 // Check to see if the scalar _IS_ an instruction. If so, it is involved.
741 if (Instruction *Inst = dyn_cast<Instruction>(ScalarVal))
742 InstToFix.push_back(Inst);
743
744 // All all of the instructions that use the scalar as an operand...
745 for (Value::use_iterator UI = ScalarVal->use_begin(),
746 UE = ScalarVal->use_end(); UI != UE; ++UI)
Chris Lattner441e16f2002-04-12 20:23:15 +0000747 InstToFix.push_back(cast<Instruction>(*UI));
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000748 }
749
750 // Eliminate duplicates by sorting, then removing equal neighbors.
751 sort(InstToFix.begin(), InstToFix.end());
752 InstToFix.erase(unique(InstToFix.begin(), InstToFix.end()), InstToFix.end());
753
Chris Lattner441e16f2002-04-12 20:23:15 +0000754 // Loop over all of the instructions to transform, creating the new
755 // replacement instructions for them. This also unlinks them from the
756 // function so they can be safely deleted later.
757 //
758 map<Value*, Value*> XFormMap;
759 NewInstructionCreator NIC(*this, Scalars, CallMap, XFormMap);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000760
Chris Lattner441e16f2002-04-12 20:23:15 +0000761 // Visit all instructions... creating the new instructions that we need and
762 // unlinking the old instructions from the function...
763 //
764 for (unsigned i = 0, e = InstToFix.size(); i != e; ++i) {
765 cerr << "Fixing: " << InstToFix[i];
766 NIC.visit(InstToFix[i]);
767 }
768 //NIC.visit(InstToFix.begin(), InstToFix.end());
769
770 // Make all instructions we will delete "let go" of their operands... so that
771 // we can safely delete Arguments whose types have changed...
772 //
773 for_each(InstToFix.begin(), InstToFix.end(),
774 mem_fun(&Instruction::dropAllReferences));
775
776 // Loop through all of the pointer arguments coming into the function,
777 // replacing them with arguments of POINTERTYPE to match the function type of
778 // the function.
779 //
780 FunctionType::ParamTypes::const_iterator TI =
781 F->getFunctionType()->getParamTypes().begin();
782 for (Function::ArgumentListType::iterator I = F->getArgumentList().begin(),
783 E = F->getArgumentList().end(); I != E; ++I, ++TI) {
784 Argument *Arg = *I;
785 if (Arg->getType() != *TI) {
786 assert(isa<PointerType>(Arg->getType()) && *TI == POINTERTYPE);
787 Argument *NewArg = new Argument(*TI, Arg->getName());
788 XFormMap[Arg] = NewArg; // Map old arg into new arg...
789
790
791 // Replace the old argument and then delete it...
792 delete F->getArgumentList().replaceWith(I, NewArg);
793 }
794 }
795
796 // Now that all of the new instructions have been created, we can update all
797 // of the references to dummy values to be references to the actual values
798 // that are computed.
799 //
800 NIC.updateReferences();
801
802 cerr << "TRANSFORMED FUNCTION:\n" << F;
803
804
805 // Delete all of the "instructions to fix"
806 for_each(InstToFix.begin(), InstToFix.end(), deleter<Instruction>);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000807
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000808 // Since we have liberally hacked the function to pieces, we want to inform
809 // the datastructure pass that its internal representation is out of date.
810 //
811 DS->invalidateFunction(F);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000812}
813
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000814static void addNodeMapping(DSNode *SrcNode, const PointerValSet &PVS,
815 map<DSNode*, PointerValSet> &NodeMapping) {
816 for (unsigned i = 0, e = PVS.size(); i != e; ++i)
817 if (NodeMapping[SrcNode].add(PVS[i])) { // Not in map yet?
818 assert(PVS[i].Index == 0 && "Node indexing not supported yet!");
819 DSNode *DestNode = PVS[i].Node;
Chris Lattner692ad5d2002-03-29 17:13:46 +0000820
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000821 // Loop over all of the outgoing links in the mapped graph
822 for (unsigned l = 0, le = DestNode->getNumOutgoingLinks(); l != le; ++l) {
823 PointerValSet &SrcSet = SrcNode->getOutgoingLink(l);
824 const PointerValSet &DestSet = DestNode->getOutgoingLink(l);
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000825
826 // Add all of the node mappings now!
827 for (unsigned si = 0, se = SrcSet.size(); si != se; ++si) {
828 assert(SrcSet[si].Index == 0 && "Can't handle node offset!");
829 addNodeMapping(SrcSet[si].Node, DestSet, NodeMapping);
830 }
831 }
832 }
833}
834
835// CalculateNodeMapping - There is a partial isomorphism between the graph
836// passed in and the graph that is actually used by the function. We need to
837// figure out what this mapping is so that we can transformFunctionBody the
838// instructions in the function itself. Note that every node in the graph that
839// we are interested in must be both in the local graph of the called function,
840// and in the local graph of the calling function. Because of this, we only
841// define the mapping for these nodes [conveniently these are the only nodes we
842// CAN define a mapping for...]
Chris Lattner692ad5d2002-03-29 17:13:46 +0000843//
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000844// The roots of the graph that we are transforming is rooted in the arguments
845// passed into the function from the caller. This is where we start our
846// mapping calculation.
847//
848// The NodeMapping calculated maps from the callers graph to the called graph.
849//
Chris Lattner847b6e22002-03-30 20:53:14 +0000850static void CalculateNodeMapping(Function *F, TransformFunctionInfo &TFI,
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000851 FunctionDSGraph &CallerGraph,
852 FunctionDSGraph &CalledGraph,
853 map<DSNode*, PointerValSet> &NodeMapping) {
854 int LastArgNo = -2;
855 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i) {
856 // Figure out what nodes in the called graph the TFI.ArgInfo[i].Node node
857 // corresponds to...
858 //
859 // Only consider first node of sequence. Extra nodes may may be added
860 // to the TFI if the data structure requires more nodes than just the
861 // one the argument points to. We are only interested in the one the
862 // argument points to though.
863 //
864 if (TFI.ArgInfo[i].ArgNo != LastArgNo) {
865 if (TFI.ArgInfo[i].ArgNo == -1) {
866 addNodeMapping(TFI.ArgInfo[i].Node, CalledGraph.getRetNodes(),
867 NodeMapping);
868 } else {
869 // Figure out which node argument # ArgNo points to in the called graph.
Chris Lattner847b6e22002-03-30 20:53:14 +0000870 Value *Arg = F->getArgumentList()[TFI.ArgInfo[i].ArgNo];
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000871 addNodeMapping(TFI.ArgInfo[i].Node, CalledGraph.getValueMap()[Arg],
872 NodeMapping);
873 }
874 LastArgNo = TFI.ArgInfo[i].ArgNo;
875 }
876 }
877}
878
879
880// transformFunction - Transform the specified function the specified way. It
881// we have already transformed that function that way, don't do anything. The
882// nodes in the TransformFunctionInfo come out of callers data structure graph.
883//
884void PoolAllocate::transformFunction(TransformFunctionInfo &TFI,
Chris Lattner441e16f2002-04-12 20:23:15 +0000885 FunctionDSGraph &CallerIPGraph,
886 map<DSNode*, PoolInfo> &CallerPoolDesc) {
Chris Lattner692ad5d2002-03-29 17:13:46 +0000887 if (getTransformedFunction(TFI)) return; // Function xformation already done?
888
Chris Lattner441e16f2002-04-12 20:23:15 +0000889 cerr << "********** Entering transformFunction for "
Chris Lattner0dc225c2002-03-31 07:17:46 +0000890 << TFI.Func->getName() << ":\n";
891 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i)
892 cerr << " ArgInfo[" << i << "] = " << TFI.ArgInfo[i].ArgNo << "\n";
893 cerr << "\n";
894
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000895 const FunctionType *OldFuncType = TFI.Func->getFunctionType();
Chris Lattner692ad5d2002-03-29 17:13:46 +0000896
Chris Lattner291a1b12002-03-29 19:05:48 +0000897 assert(!OldFuncType->isVarArg() && "Vararg functions not handled yet!");
Chris Lattner692ad5d2002-03-29 17:13:46 +0000898
Chris Lattner291a1b12002-03-29 19:05:48 +0000899 // Build the type for the new function that we are transforming
900 vector<const Type*> ArgTys;
Chris Lattner441e16f2002-04-12 20:23:15 +0000901 ArgTys.reserve(OldFuncType->getNumParams()+TFI.ArgInfo.size());
Chris Lattner291a1b12002-03-29 19:05:48 +0000902 for (unsigned i = 0, e = OldFuncType->getNumParams(); i != e; ++i)
903 ArgTys.push_back(OldFuncType->getParamType(i));
904
Chris Lattner441e16f2002-04-12 20:23:15 +0000905 const Type *RetType = OldFuncType->getReturnType();
906
Chris Lattner291a1b12002-03-29 19:05:48 +0000907 // Add one pool pointer for every argument that needs to be supplemented.
Chris Lattner441e16f2002-04-12 20:23:15 +0000908 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i) {
909 if (TFI.ArgInfo[i].ArgNo == -1)
910 RetType = POINTERTYPE; // Return a pointer
911 else
912 ArgTys[TFI.ArgInfo[i].ArgNo] = POINTERTYPE; // Pass a pointer
913 ArgTys.push_back(PointerType::get(CallerPoolDesc.find(TFI.ArgInfo[i].Node)
914 ->second.PoolType));
915 }
Chris Lattner291a1b12002-03-29 19:05:48 +0000916
917 // Build the new function type...
Chris Lattner441e16f2002-04-12 20:23:15 +0000918 const FunctionType *NewFuncType = FunctionType::get(RetType, ArgTys,
919 OldFuncType->isVarArg());
Chris Lattner291a1b12002-03-29 19:05:48 +0000920
921 // The new function is internal, because we know that only we can call it.
922 // This also helps subsequent IP transformations to eliminate duplicated pool
Chris Lattner441e16f2002-04-12 20:23:15 +0000923 // pointers (which look like the same value is always passed into a parameter,
924 // allowing it to be easily eliminated).
Chris Lattner291a1b12002-03-29 19:05:48 +0000925 //
926 Function *NewFunc = new Function(NewFuncType, true,
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000927 TFI.Func->getName()+".poolxform");
Chris Lattner291a1b12002-03-29 19:05:48 +0000928 CurModule->getFunctionList().push_back(NewFunc);
929
Chris Lattner441e16f2002-04-12 20:23:15 +0000930
931 cerr << "Created function prototype: " << NewFunc << "\n";
932
Chris Lattner291a1b12002-03-29 19:05:48 +0000933 // Add the newly formed function to the TransformedFunctions table so that
934 // infinite recursion does not occur!
935 //
936 TransformedFunctions[TFI] = NewFunc;
937
938 // Add arguments to the function... starting with all of the old arguments
939 vector<Value*> ArgMap;
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000940 for (unsigned i = 0, e = TFI.Func->getArgumentList().size(); i != e; ++i) {
Chris Lattner2e9fa6d2002-04-09 19:48:49 +0000941 const Argument *OFA = TFI.Func->getArgumentList()[i];
942 Argument *NFA = new Argument(OFA->getType(), OFA->getName());
Chris Lattner291a1b12002-03-29 19:05:48 +0000943 NewFunc->getArgumentList().push_back(NFA);
944 ArgMap.push_back(NFA); // Keep track of the arguments
945 }
946
947 // Now add all of the arguments corresponding to pools passed in...
948 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i) {
Chris Lattner441e16f2002-04-12 20:23:15 +0000949 CallArgInfo &AI = TFI.ArgInfo[i];
Chris Lattner291a1b12002-03-29 19:05:48 +0000950 string Name;
Chris Lattner441e16f2002-04-12 20:23:15 +0000951 if (AI.ArgNo == -1)
952 Name = "ret";
Chris Lattner291a1b12002-03-29 19:05:48 +0000953 else
Chris Lattner441e16f2002-04-12 20:23:15 +0000954 Name = ArgMap[AI.ArgNo]->getName(); // Get the arg name
955 const Type *Ty = PointerType::get(CallerPoolDesc[AI.Node].PoolType);
956 Argument *NFA = new Argument(Ty, Name+".pool");
Chris Lattner291a1b12002-03-29 19:05:48 +0000957 NewFunc->getArgumentList().push_back(NFA);
958 }
959
960 // Now clone the body of the old function into the new function...
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000961 CloneFunctionInto(NewFunc, TFI.Func, ArgMap);
Chris Lattner291a1b12002-03-29 19:05:48 +0000962
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000963 // Okay, now we have a function that is identical to the old one, except that
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000964 // it has extra arguments for the pools coming in. Now we have to get the
965 // data structure graph for the function we are replacing, and figure out how
966 // our graph nodes map to the graph nodes in the dest function.
967 //
Chris Lattner847b6e22002-03-30 20:53:14 +0000968 FunctionDSGraph &DSGraph = DS->getClosedDSGraph(NewFunc);
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000969
Chris Lattner441e16f2002-04-12 20:23:15 +0000970 // NodeMapping - Multimap from callers graph to called graph. We are
971 // guaranteed that the called function graph has more nodes than the caller,
972 // or exactly the same number of nodes. This is because the called function
973 // might not know that two nodes are merged when considering the callers
974 // context, but the caller obviously does. Because of this, a single node in
975 // the calling function's data structure graph can map to multiple nodes in
976 // the called functions graph.
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000977 //
978 map<DSNode*, PointerValSet> NodeMapping;
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000979
Chris Lattner847b6e22002-03-30 20:53:14 +0000980 CalculateNodeMapping(NewFunc, TFI, CallerIPGraph, DSGraph,
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000981 NodeMapping);
982
983 // Print out the node mapping...
Chris Lattner847b6e22002-03-30 20:53:14 +0000984 cerr << "\nNode mapping for call of " << NewFunc->getName() << "\n";
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000985 for (map<DSNode*, PointerValSet>::iterator I = NodeMapping.begin();
986 I != NodeMapping.end(); ++I) {
987 cerr << "Map: "; I->first->print(cerr);
988 cerr << "To: "; I->second.print(cerr);
989 cerr << "\n";
990 }
991
992 // Fill in the PoolDescriptor information for the transformed function so that
993 // it can determine which value holds the pool descriptor for each data
994 // structure node that it accesses.
995 //
Chris Lattner441e16f2002-04-12 20:23:15 +0000996 map<DSNode*, PoolInfo> PoolDescs;
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000997
Chris Lattner847b6e22002-03-30 20:53:14 +0000998 cerr << "\nCalculating the pool descriptor map:\n";
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000999
Chris Lattner441e16f2002-04-12 20:23:15 +00001000 // Calculate as much of the pool descriptor map as possible. Since we have
1001 // the node mapping between the caller and callee functions, and we have the
1002 // pool descriptor information of the caller, we can calculate a partical pool
1003 // descriptor map for the called function.
1004 //
1005 // The nodes that we do not have complete information for are the ones that
1006 // are accessed by loading pointers derived from arguments passed in, but that
1007 // are not passed in directly. In this case, we have all of the information
1008 // except a pool value. If the called function refers to this pool, the pool
1009 // value will be loaded from the pool graph and added to the map as neccesary.
1010 //
1011 for (map<DSNode*, PointerValSet>::iterator I = NodeMapping.begin();
1012 I != NodeMapping.end(); ++I) {
1013 DSNode *CallerNode = I->first;
1014 PoolInfo &CallerPI = CallerPoolDesc[CallerNode];
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001015
Chris Lattner441e16f2002-04-12 20:23:15 +00001016 // Check to see if we have a node pointer passed in for this value...
1017 Value *CalleeValue = 0;
1018 for (unsigned a = 0, ae = TFI.ArgInfo.size(); a != ae; ++a)
1019 if (TFI.ArgInfo[a].Node == CallerNode) {
1020 // Calculate the argument number that the pool is to the function
1021 // call... The call instruction should not have the pool operands added
1022 // yet.
1023 unsigned ArgNo = TFI.Call->getNumOperands()-1+a;
1024 cerr << "Should be argument #: " << ArgNo << "[i = " << a << "]\n";
1025 assert(ArgNo < NewFunc->getArgumentList().size() &&
1026 "Call already has pool arguments added??");
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001027
Chris Lattner441e16f2002-04-12 20:23:15 +00001028 // Map the pool argument into the called function...
1029 CalleeValue = NewFunc->getArgumentList()[ArgNo];
1030 break; // Found value, quit loop
1031 }
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001032
Chris Lattner441e16f2002-04-12 20:23:15 +00001033 // Loop over all of the data structure nodes that this incoming node maps to
1034 // Creating a PoolInfo structure for them.
1035 for (unsigned i = 0, e = I->second.size(); i != e; ++i) {
1036 assert(I->second[i].Index == 0 && "Doesn't handle subindexing yet!");
1037 DSNode *CalleeNode = I->second[i].Node;
1038
1039 // Add the descriptor. We already know everything about it by now, much
1040 // of it is the same as the caller info.
1041 //
1042 PoolDescs.insert(make_pair(CalleeNode,
1043 PoolInfo(CalleeNode, CalleeValue,
1044 CallerPI.NewType,
1045 CallerPI.PoolType)));
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001046 }
Chris Lattner847b6e22002-03-30 20:53:14 +00001047 }
1048
1049 // We must destroy the node mapping so that we don't have latent references
1050 // into the data structure graph for the new function. Otherwise we get
1051 // assertion failures when transformFunctionBody tries to invalidate the
1052 // graph.
1053 //
1054 NodeMapping.clear();
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001055
1056 // Now that we know everything we need about the function, transform the body
1057 // now!
1058 //
Chris Lattner441e16f2002-04-12 20:23:15 +00001059 transformFunctionBody(NewFunc, DSGraph, PoolDescs);
1060
1061 cerr << "Function after transformation:\n" << NewFunc;
Chris Lattner66df97d2002-03-29 06:21:38 +00001062}
1063
Chris Lattner8f796d62002-04-13 19:25:57 +00001064static unsigned countPointerTypes(const Type *Ty) {
1065 if (isa<PointerType>(Ty)) {
1066 return 1;
1067 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1068 unsigned Num = 0;
1069 for (unsigned i = 0, e = STy->getElementTypes().size(); i != e; ++i)
1070 Num += countPointerTypes(STy->getElementTypes()[i]);
1071 return Num;
1072 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1073 return countPointerTypes(ATy->getElementType());
1074 } else {
1075 assert(Ty->isPrimitiveType() && "Unknown derived type!");
1076 return 0;
1077 }
1078}
Chris Lattner66df97d2002-03-29 06:21:38 +00001079
1080// CreatePools - Insert instructions into the function we are processing to
1081// create all of the memory pool objects themselves. This also inserts
1082// destruction code. Add an alloca for each pool that is allocated to the
Chris Lattner441e16f2002-04-12 20:23:15 +00001083// PoolDescs vector.
Chris Lattner66df97d2002-03-29 06:21:38 +00001084//
1085void PoolAllocate::CreatePools(Function *F, const vector<AllocDSNode*> &Allocs,
Chris Lattner441e16f2002-04-12 20:23:15 +00001086 map<DSNode*, PoolInfo> &PoolDescs) {
1087 // Find all of the return nodes in the function...
Chris Lattnere0618ca2002-03-29 05:50:20 +00001088 vector<BasicBlock*> ReturnNodes;
1089 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
1090 if (isa<ReturnInst>((*I)->getTerminator()))
1091 ReturnNodes.push_back(*I);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001092
Chris Lattner441e16f2002-04-12 20:23:15 +00001093 map<DSNode*, PATypeHolder> AbsPoolTyMap;
1094
1095 // First pass over the allocations to process...
1096 for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
1097 // Create the pooldescriptor mapping... with null entries for everything
1098 // except the node & NewType fields.
1099 //
1100 map<DSNode*, PoolInfo>::iterator PI =
1101 PoolDescs.insert(make_pair(Allocs[i], PoolInfo(Allocs[i]))).first;
1102
Chris Lattner8f796d62002-04-13 19:25:57 +00001103 // Add a symbol table entry for the new type if there was one for the old
1104 // type...
1105 string OldName = CurModule->getTypeName(Allocs[i]->getType());
1106 if (!OldName.empty())
1107 CurModule->addTypeName(OldName+".p", PI->second.NewType);
1108
Chris Lattner441e16f2002-04-12 20:23:15 +00001109 // Create the abstract pool types that will need to be resolved in a second
1110 // pass once an abstract type is created for each pool.
1111 //
1112 // Can only handle limited shapes for now...
1113 StructType *OldNodeTy = cast<StructType>(Allocs[i]->getType());
1114 vector<const Type*> PoolTypes;
1115
1116 // Pool type is the first element of the pool descriptor type...
1117 PoolTypes.push_back(getPoolType(PoolDescs[Allocs[i]].NewType));
Chris Lattner8f796d62002-04-13 19:25:57 +00001118
1119 unsigned NumPointers = countPointerTypes(OldNodeTy);
1120 while (NumPointers--) // Add a different opaque type for each pointer
1121 PoolTypes.push_back(OpaqueType::get());
1122
Chris Lattner441e16f2002-04-12 20:23:15 +00001123 assert(Allocs[i]->getNumLinks() == PoolTypes.size()-1 &&
1124 "Node should have same number of pointers as pool!");
1125
Chris Lattner8f796d62002-04-13 19:25:57 +00001126 StructType *PoolType = StructType::get(PoolTypes);
1127
1128 // Add a symbol table entry for the pooltype if possible...
1129 if (!OldName.empty()) CurModule->addTypeName(OldName+".pool", PoolType);
1130
Chris Lattner441e16f2002-04-12 20:23:15 +00001131 // Create the pool type, with opaque values for pointers...
Chris Lattner8f796d62002-04-13 19:25:57 +00001132 AbsPoolTyMap.insert(make_pair(Allocs[i], PoolType));
Chris Lattner441e16f2002-04-12 20:23:15 +00001133#ifdef DEBUG_CREATE_POOLS
1134 cerr << "POOL TY: " << AbsPoolTyMap.find(Allocs[i])->second.get() << "\n";
1135#endif
1136 }
1137
1138 // Now that we have types for all of the pool types, link them all together.
1139 for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
1140 PATypeHolder &PoolTyH = AbsPoolTyMap.find(Allocs[i])->second;
1141
1142 // Resolve all of the outgoing pointer types of this pool node...
1143 for (unsigned p = 0, pe = Allocs[i]->getNumLinks(); p != pe; ++p) {
1144 PointerValSet &PVS = Allocs[i]->getLink(p);
1145 assert(!PVS.empty() && "Outgoing edge is empty, field unused, can"
1146 " probably just leave the type opaque or something dumb.");
1147 unsigned Out;
1148 for (Out = 0; AbsPoolTyMap.count(PVS[Out].Node) == 0; ++Out)
1149 assert(Out != PVS.size() && "No edge to an outgoing allocation node!?");
1150
1151 assert(PVS[Out].Index == 0 && "Subindexing not implemented yet!");
1152
1153 // The actual struct type could change each time through the loop, so it's
1154 // NOT loop invariant.
1155 StructType *PoolTy = cast<StructType>(PoolTyH.get());
1156
1157 // Get the opaque type...
1158 DerivedType *ElTy =
1159 cast<DerivedType>(PoolTy->getElementTypes()[p+1].get());
1160
1161#ifdef DEBUG_CREATE_POOLS
1162 cerr << "Refining " << ElTy << " of " << PoolTy << " to "
1163 << AbsPoolTyMap.find(PVS[Out].Node)->second.get() << "\n";
1164#endif
1165
1166 const Type *RefPoolTy = AbsPoolTyMap.find(PVS[Out].Node)->second.get();
1167 ElTy->refineAbstractTypeTo(PointerType::get(RefPoolTy));
1168
1169#ifdef DEBUG_CREATE_POOLS
1170 cerr << "Result pool type is: " << PoolTyH.get() << "\n";
1171#endif
1172 }
1173 }
1174
1175 // Create the code that goes in the entry and exit nodes for the function...
Chris Lattnere0618ca2002-03-29 05:50:20 +00001176 vector<Instruction*> EntryNodeInsts;
1177 for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
Chris Lattner441e16f2002-04-12 20:23:15 +00001178 PoolInfo &PI = PoolDescs[Allocs[i]];
1179
1180 // Fill in the pool type for this pool...
1181 PI.PoolType = AbsPoolTyMap.find(Allocs[i])->second.get();
1182 assert(!PI.PoolType->isAbstract() &&
1183 "Pool type should not be abstract anymore!");
1184
Chris Lattnere0618ca2002-03-29 05:50:20 +00001185 // Add an allocation and a free for each pool...
Chris Lattner5da145b2002-04-13 19:52:54 +00001186 AllocaInst *PoolAlloc
1187 = new AllocaInst(PointerType::get(PI.PoolType), 0,
1188 CurModule->getTypeName(PI.PoolType));
Chris Lattner441e16f2002-04-12 20:23:15 +00001189 PI.Handle = PoolAlloc;
Chris Lattnere0618ca2002-03-29 05:50:20 +00001190 EntryNodeInsts.push_back(PoolAlloc);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001191 AllocationInst *AI = Allocs[i]->getAllocation();
1192
1193 // Initialize the pool. We need to know how big each allocation is. For
1194 // our purposes here, we assume we are allocating a scalar, or array of
1195 // constant size.
1196 //
1197 unsigned ElSize = TargetData.getTypeSize(AI->getAllocatedType());
1198 ElSize *= cast<ConstantUInt>(AI->getArraySize())->getValue();
1199
1200 vector<Value*> Args;
Chris Lattnere0618ca2002-03-29 05:50:20 +00001201 Args.push_back(ConstantUInt::get(Type::UIntTy, ElSize));
Chris Lattner441e16f2002-04-12 20:23:15 +00001202 Args.push_back(PoolAlloc); // Pool to initialize
Chris Lattnere0618ca2002-03-29 05:50:20 +00001203 EntryNodeInsts.push_back(new CallInst(PoolInit, Args));
1204
Chris Lattner441e16f2002-04-12 20:23:15 +00001205 // Add code to destroy the pool in all of the exit nodes of the function...
Chris Lattner8f796d62002-04-13 19:25:57 +00001206 Args.clear();
1207 Args.push_back(PoolAlloc); // Pool to initialize
1208
Chris Lattnere0618ca2002-03-29 05:50:20 +00001209 for (unsigned EN = 0, ENE = ReturnNodes.size(); EN != ENE; ++EN) {
1210 Instruction *Destroy = new CallInst(PoolDestroy, Args);
1211
1212 // Insert it before the return instruction...
1213 BasicBlock *RetNode = ReturnNodes[EN];
1214 RetNode->getInstList().insert(RetNode->end()-1, Destroy);
1215 }
1216 }
1217
Chris Lattner5da145b2002-04-13 19:52:54 +00001218 // Now that all of the pool descriptors have been created, link them together
1219 // so that called functions can get links as neccesary...
1220 //
1221 for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
1222 PoolInfo &PI = PoolDescs[Allocs[i]];
1223
1224 // For every pointer in the data structure, initialize a link that
1225 // indicates which pool to access...
1226 //
1227 vector<Value*> Indices(2);
1228 Indices[0] = ConstantUInt::get(Type::UIntTy, 0);
1229 for (unsigned l = 0, le = PI.Node->getNumLinks(); l != le; ++l)
1230 // Only store an entry for the field if the field is used!
1231 if (!PI.Node->getLink(l).empty()) {
1232 assert(PI.Node->getLink(l).size() == 1 && "Should have only one link!");
1233 PointerVal PV = PI.Node->getLink(l)[0];
1234 assert(PV.Index == 0 && "Subindexing not supported yet!");
1235 PoolInfo &LinkedPool = PoolDescs[PV.Node];
1236 Indices[1] = ConstantUInt::get(Type::UByteTy, 1+l);
1237
1238 EntryNodeInsts.push_back(new StoreInst(LinkedPool.Handle, PI.Handle,
1239 Indices));
1240 }
1241 }
1242
Chris Lattnere0618ca2002-03-29 05:50:20 +00001243 // Insert the entry node code into the entry block...
1244 F->getEntryNode()->getInstList().insert(F->getEntryNode()->begin()+1,
1245 EntryNodeInsts.begin(),
1246 EntryNodeInsts.end());
Chris Lattner175f37c2002-03-29 03:40:59 +00001247}
1248
1249
Chris Lattner441e16f2002-04-12 20:23:15 +00001250// addPoolPrototypes - Add prototypes for the pool functions to the specified
Chris Lattner175f37c2002-03-29 03:40:59 +00001251// module and update the Pool* instance variables to point to them.
1252//
1253void PoolAllocate::addPoolPrototypes(Module *M) {
Chris Lattner441e16f2002-04-12 20:23:15 +00001254 // Get poolinit function...
Chris Lattnere0618ca2002-03-29 05:50:20 +00001255 vector<const Type*> Args;
Chris Lattnere0618ca2002-03-29 05:50:20 +00001256 Args.push_back(Type::UIntTy); // Num bytes per element
Chris Lattner441e16f2002-04-12 20:23:15 +00001257 FunctionType *PoolInitTy = FunctionType::get(Type::VoidTy, Args, true);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001258 PoolInit = M->getOrInsertFunction("poolinit", PoolInitTy);
Chris Lattner175f37c2002-03-29 03:40:59 +00001259
Chris Lattnere0618ca2002-03-29 05:50:20 +00001260 // Get pooldestroy function...
1261 Args.pop_back(); // Only takes a pool...
Chris Lattner441e16f2002-04-12 20:23:15 +00001262 FunctionType *PoolDestroyTy = FunctionType::get(Type::VoidTy, Args, true);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001263 PoolDestroy = M->getOrInsertFunction("pooldestroy", PoolDestroyTy);
1264
Chris Lattnere0618ca2002-03-29 05:50:20 +00001265 // Get the poolalloc function...
Chris Lattner441e16f2002-04-12 20:23:15 +00001266 FunctionType *PoolAllocTy = FunctionType::get(POINTERTYPE, Args, true);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001267 PoolAlloc = M->getOrInsertFunction("poolalloc", PoolAllocTy);
1268
1269 // Get the poolfree function...
Chris Lattner441e16f2002-04-12 20:23:15 +00001270 Args.push_back(POINTERTYPE); // Pointer to free
1271 FunctionType *PoolFreeTy = FunctionType::get(Type::VoidTy, Args, true);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001272 PoolFree = M->getOrInsertFunction("poolfree", PoolFreeTy);
1273
1274 // Add the %PoolTy type to the symbol table of the module...
Chris Lattner441e16f2002-04-12 20:23:15 +00001275 //M->addTypeName("PoolTy", PoolTy->getElementType());
Chris Lattner175f37c2002-03-29 03:40:59 +00001276}
1277
1278
1279bool PoolAllocate::run(Module *M) {
1280 addPoolPrototypes(M);
1281 CurModule = M;
1282
1283 DS = &getAnalysis<DataStructure>();
1284 bool Changed = false;
Chris Lattner291a1b12002-03-29 19:05:48 +00001285
1286 // We cannot use an iterator here because it will get invalidated when we add
1287 // functions to the module later...
1288 for (unsigned i = 0; i != M->size(); ++i)
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001289 if (!M->getFunctionList()[i]->isExternal()) {
Chris Lattner291a1b12002-03-29 19:05:48 +00001290 Changed |= processFunction(M->getFunctionList()[i]);
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001291 if (Changed) {
1292 cerr << "Only processing one function\n";
1293 break;
1294 }
1295 }
Chris Lattner175f37c2002-03-29 03:40:59 +00001296
1297 CurModule = 0;
1298 DS = 0;
1299 return false;
1300}
1301
1302
1303// createPoolAllocatePass - Global function to access the functionality of this
1304// pass...
1305//
Chris Lattner64fd9352002-03-28 18:08:31 +00001306Pass *createPoolAllocatePass() { return new PoolAllocate(); }