blob: 43683e4c355ab3a1f697d2ecc7d9702b4ccd6706 [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//
Chris Lattner457e1ac2002-04-15 22:42:23 +00007// This pass requires a DCE & instcombine pass to be run after it for best
8// results.
9//
Chris Lattner64fd9352002-03-28 18:08:31 +000010//===----------------------------------------------------------------------===//
11
12#include "llvm/Transforms/IPO/PoolAllocate.h"
Chris Lattner291a1b12002-03-29 19:05:48 +000013#include "llvm/Transforms/CloneFunction.h"
Chris Lattner64fd9352002-03-28 18:08:31 +000014#include "llvm/Analysis/DataStructure.h"
Chris Lattner396d5d72002-03-30 04:02:31 +000015#include "llvm/Analysis/DataStructureGraph.h"
Chris Lattner175f37c2002-03-29 03:40:59 +000016#include "llvm/Module.h"
17#include "llvm/Function.h"
Chris Lattnerd92b01c2002-04-09 18:37:46 +000018#include "llvm/BasicBlock.h"
Chris Lattner175f37c2002-03-29 03:40:59 +000019#include "llvm/iMemory.h"
Chris Lattnere0618ca2002-03-29 05:50:20 +000020#include "llvm/iTerminators.h"
Chris Lattner441e16f2002-04-12 20:23:15 +000021#include "llvm/iPHINode.h"
Chris Lattnere0618ca2002-03-29 05:50:20 +000022#include "llvm/iOther.h"
Chris Lattner441e16f2002-04-12 20:23:15 +000023#include "llvm/DerivedTypes.h"
Chris Lattnere0618ca2002-03-29 05:50:20 +000024#include "llvm/ConstantVals.h"
25#include "llvm/Target/TargetData.h"
Chris Lattnerf32d65d2002-03-29 21:25:19 +000026#include "llvm/Support/InstVisitor.h"
Chris Lattner2e9fa6d2002-04-09 19:48:49 +000027#include "llvm/Argument.h"
Chris Lattner396d5d72002-03-30 04:02:31 +000028#include "Support/DepthFirstIterator.h"
Chris Lattnere0618ca2002-03-29 05:50:20 +000029#include "Support/STLExtras.h"
Chris Lattner175f37c2002-03-29 03:40:59 +000030#include <algorithm>
Chris Lattner64fd9352002-03-28 18:08:31 +000031
Chris Lattner441e16f2002-04-12 20:23:15 +000032// DEBUG_CREATE_POOLS - Enable this to turn on debug output for the pool
33// creation phase in the top level function of a transformed data structure.
34//
Chris Lattneracf19022002-04-14 06:14:41 +000035//#define DEBUG_CREATE_POOLS 1
36
37// DEBUG_TRANSFORM_PROGRESS - Enable this to get lots of debug output on what
38// the transformation is doing.
39//
40//#define DEBUG_TRANSFORM_PROGRESS 1
Chris Lattner441e16f2002-04-12 20:23:15 +000041
Chris Lattner457e1ac2002-04-15 22:42:23 +000042// DEBUG_POOLBASE_LOAD_ELIMINATOR - Turn this on to get statistics about how
43// many static loads were eliminated from a function...
44//
45#define DEBUG_POOLBASE_LOAD_ELIMINATOR 1
46
Chris Lattner50e3d322002-04-13 23:13:18 +000047#include "Support/CommandLine.h"
48enum PtrSize {
49 Ptr8bits, Ptr16bits, Ptr32bits
50};
51
52static cl::Enum<enum PtrSize> ReqPointerSize("ptrsize", 0,
Chris Lattneracf19022002-04-14 06:14:41 +000053 "Set pointer size for -poolalloc pass",
Chris Lattner50e3d322002-04-13 23:13:18 +000054 clEnumValN(Ptr32bits, "32", "Use 32 bit indices for pointers"),
55 clEnumValN(Ptr16bits, "16", "Use 16 bit indices for pointers"),
56 clEnumValN(Ptr8bits , "8", "Use 8 bit indices for pointers"), 0);
57
Chris Lattner457e1ac2002-04-15 22:42:23 +000058static cl::Flag DisableRLE("no-pool-load-elim", "Disable pool load elimination after poolalloc pass", cl::Hidden);
59
Chris Lattner441e16f2002-04-12 20:23:15 +000060const Type *POINTERTYPE;
Chris Lattner692ad5d2002-03-29 17:13:46 +000061
Chris Lattnere0618ca2002-03-29 05:50:20 +000062// FIXME: This is dependant on the sparc backend layout conventions!!
63static TargetData TargetData("test");
64
Chris Lattner50e3d322002-04-13 23:13:18 +000065static const Type *getPointerTransformedType(const Type *Ty) {
66 if (PointerType *PT = dyn_cast<PointerType>(Ty)) {
67 return POINTERTYPE;
68 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
69 vector<const Type *> NewElTypes;
70 NewElTypes.reserve(STy->getElementTypes().size());
71 for (StructType::ElementTypes::const_iterator
72 I = STy->getElementTypes().begin(),
73 E = STy->getElementTypes().end(); I != E; ++I)
74 NewElTypes.push_back(getPointerTransformedType(*I));
75 return StructType::get(NewElTypes);
76 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
77 return ArrayType::get(getPointerTransformedType(ATy->getElementType()),
78 ATy->getNumElements());
79 } else {
80 assert(Ty->isPrimitiveType() && "Unknown derived type!");
81 return Ty;
82 }
83}
84
Chris Lattner64fd9352002-03-28 18:08:31 +000085namespace {
Chris Lattner441e16f2002-04-12 20:23:15 +000086 struct PoolInfo {
87 DSNode *Node; // The node this pool allocation represents
88 Value *Handle; // LLVM value of the pool in the current context
89 const Type *NewType; // The transformed type of the memory objects
90 const Type *PoolType; // The type of the pool
91
92 const Type *getOldType() const { return Node->getType(); }
93
94 PoolInfo() { // Define a default ctor for map::operator[]
95 cerr << "Map subscript used to get element that doesn't exist!\n";
96 abort(); // Invalid
97 }
98
99 PoolInfo(DSNode *N, Value *H, const Type *NT, const Type *PT)
100 : Node(N), Handle(H), NewType(NT), PoolType(PT) {
101 // Handle can be null...
102 assert(N && NT && PT && "Pool info null!");
103 }
104
105 PoolInfo(DSNode *N) : Node(N), Handle(0), NewType(0), PoolType(0) {
106 assert(N && "Invalid pool info!");
107
108 // The new type of the memory object is the same as the old type, except
109 // that all of the pointer values are replaced with POINTERTYPE values.
Chris Lattner50e3d322002-04-13 23:13:18 +0000110 NewType = getPointerTransformedType(getOldType());
Chris Lattner441e16f2002-04-12 20:23:15 +0000111 }
112 };
113
Chris Lattner692ad5d2002-03-29 17:13:46 +0000114 // ScalarInfo - Information about an LLVM value that we know points to some
115 // datastructure we are processing.
116 //
117 struct ScalarInfo {
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000118 Value *Val; // Scalar value in Current Function
Chris Lattner441e16f2002-04-12 20:23:15 +0000119 PoolInfo Pool; // The pool the scalar points into
Chris Lattner692ad5d2002-03-29 17:13:46 +0000120
Chris Lattner441e16f2002-04-12 20:23:15 +0000121 ScalarInfo(Value *V, const PoolInfo &PI) : Val(V), Pool(PI) {
122 assert(V && "Null value passed to ScalarInfo ctor!");
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000123 }
Chris Lattner692ad5d2002-03-29 17:13:46 +0000124 };
125
Chris Lattner396d5d72002-03-30 04:02:31 +0000126 // CallArgInfo - Information on one operand for a call that got expanded.
127 struct CallArgInfo {
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000128 int ArgNo; // Call argument number this corresponds to
129 DSNode *Node; // The graph node for the pool
130 Value *PoolHandle; // The LLVM value that is the pool pointer
Chris Lattner396d5d72002-03-30 04:02:31 +0000131
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000132 CallArgInfo(int Arg, DSNode *N, Value *PH)
133 : ArgNo(Arg), Node(N), PoolHandle(PH) {
134 assert(Arg >= -1 && N && PH && "Illegal values to CallArgInfo ctor!");
Chris Lattner396d5d72002-03-30 04:02:31 +0000135 }
136
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000137 // operator< when sorting, sort by argument number.
Chris Lattner396d5d72002-03-30 04:02:31 +0000138 bool operator<(const CallArgInfo &CAI) const {
139 return ArgNo < CAI.ArgNo;
140 }
141 };
142
Chris Lattner692ad5d2002-03-29 17:13:46 +0000143 // TransformFunctionInfo - Information about how a function eeds to be
144 // transformed.
145 //
146 struct TransformFunctionInfo {
147 // ArgInfo - Maintain information about the arguments that need to be
Chris Lattner441e16f2002-04-12 20:23:15 +0000148 // processed. Each CallArgInfo corresponds to an argument that needs to
149 // have a pool pointer passed into the transformed function with it.
Chris Lattner692ad5d2002-03-29 17:13:46 +0000150 //
151 // As a special case, "argument" number -1 corresponds to the return value.
152 //
Chris Lattner396d5d72002-03-30 04:02:31 +0000153 vector<CallArgInfo> ArgInfo;
Chris Lattner692ad5d2002-03-29 17:13:46 +0000154
155 // Func - The function to be transformed...
156 Function *Func;
157
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000158 // The call instruction that is used to map CallArgInfo PoolHandle values
159 // into the new function values.
160 CallInst *Call;
161
Chris Lattner692ad5d2002-03-29 17:13:46 +0000162 // default ctor...
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000163 TransformFunctionInfo() : Func(0), Call(0) {}
Chris Lattner692ad5d2002-03-29 17:13:46 +0000164
Chris Lattner396d5d72002-03-30 04:02:31 +0000165 bool operator<(const TransformFunctionInfo &TFI) const {
Chris Lattner291a1b12002-03-29 19:05:48 +0000166 if (Func < TFI.Func) return true;
167 if (Func > TFI.Func) return false;
Chris Lattner291a1b12002-03-29 19:05:48 +0000168 if (ArgInfo.size() < TFI.ArgInfo.size()) return true;
169 if (ArgInfo.size() > TFI.ArgInfo.size()) return false;
Chris Lattner396d5d72002-03-30 04:02:31 +0000170 return ArgInfo < TFI.ArgInfo;
Chris Lattner692ad5d2002-03-29 17:13:46 +0000171 }
172
173 void finalizeConstruction() {
174 // Sort the vector so that the return value is first, followed by the
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000175 // argument records, in order. Note that this must be a stable sort so
176 // that the entries with the same sorting criteria (ie they are multiple
177 // pool entries for the same argument) are kept in depth first order.
178 stable_sort(ArgInfo.begin(), ArgInfo.end());
Chris Lattner692ad5d2002-03-29 17:13:46 +0000179 }
Chris Lattner3e78dea2002-04-18 14:43:30 +0000180
181 // addCallInfo - For a specified function call CI, figure out which pool
182 // descriptors need to be passed in as arguments, and which arguments need
183 // to be transformed into indices. If Arg != -1, the specified call
184 // argument is passed in as a pointer to a data structure.
185 //
186 void addCallInfo(DataStructure *DS, CallInst *CI, int Arg,
187 DSNode *GraphNode, map<DSNode*, PoolInfo> &PoolDescs);
188
189 // Make sure that all dependant arguments are added to this transformation
190 // info. For example, if we call foo(null, P) and foo treats it's first and
191 // second arguments as belonging to the same data structure, the we MUST add
192 // entries to know that the null needs to be transformed into an index as
193 // well.
194 //
195 void ensureDependantArgumentsIncluded(DataStructure *DS,
196 map<DSNode*, PoolInfo> &PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000197 };
198
199
200 // Define the pass class that we implement...
Chris Lattner441e16f2002-04-12 20:23:15 +0000201 struct PoolAllocate : public Pass {
Chris Lattner175f37c2002-03-29 03:40:59 +0000202 PoolAllocate() {
Chris Lattner50e3d322002-04-13 23:13:18 +0000203 switch (ReqPointerSize) {
204 case Ptr32bits: POINTERTYPE = Type::UIntTy; break;
205 case Ptr16bits: POINTERTYPE = Type::UShortTy; break;
206 case Ptr8bits: POINTERTYPE = Type::UByteTy; break;
207 }
Chris Lattner175f37c2002-03-29 03:40:59 +0000208
209 CurModule = 0; DS = 0;
210 PoolInit = PoolDestroy = PoolAlloc = PoolFree = 0;
Chris Lattner64fd9352002-03-28 18:08:31 +0000211 }
212
Chris Lattner441e16f2002-04-12 20:23:15 +0000213 // getPoolType - Get the type used by the backend for a pool of a particular
214 // type. This pool record is used to allocate nodes of type NodeType.
215 //
216 // Here, PoolTy = { NodeType*, sbyte*, uint }*
217 //
218 const StructType *getPoolType(const Type *NodeType) {
219 vector<const Type*> PoolElements;
220 PoolElements.push_back(PointerType::get(NodeType));
221 PoolElements.push_back(PointerType::get(Type::SByteTy));
222 PoolElements.push_back(Type::UIntTy);
Chris Lattner8f796d62002-04-13 19:25:57 +0000223 StructType *Result = StructType::get(PoolElements);
224
225 // Add a name to the symbol table to correspond to the backend
226 // representation of this pool...
227 assert(CurModule && "No current module!?");
228 string Name = CurModule->getTypeName(NodeType);
229 if (Name.empty()) Name = CurModule->getTypeName(PoolElements[0]);
230 CurModule->addTypeName(Name+"oolbe", Result);
231
232 return Result;
Chris Lattner441e16f2002-04-12 20:23:15 +0000233 }
234
Chris Lattner175f37c2002-03-29 03:40:59 +0000235 bool run(Module *M);
236
237 // getAnalysisUsageInfo - This function requires data structure information
238 // to be able to see what is pool allocatable.
Chris Lattner64fd9352002-03-28 18:08:31 +0000239 //
240 virtual void getAnalysisUsageInfo(Pass::AnalysisSet &Required,
Chris Lattner175f37c2002-03-29 03:40:59 +0000241 Pass::AnalysisSet &,Pass::AnalysisSet &) {
Chris Lattner64fd9352002-03-28 18:08:31 +0000242 Required.push_back(DataStructure::ID);
243 }
Chris Lattner175f37c2002-03-29 03:40:59 +0000244
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000245 public:
Chris Lattner175f37c2002-03-29 03:40:59 +0000246 // CurModule - The module being processed.
247 Module *CurModule;
248
249 // DS - The data structure graph for the module being processed.
250 DataStructure *DS;
251
252 // Prototypes that we add to support pool allocation...
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000253 Function *PoolInit, *PoolDestroy, *PoolAlloc, *PoolAllocArray, *PoolFree;
Chris Lattner175f37c2002-03-29 03:40:59 +0000254
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000255 // The map of already transformed functions... note that the keys of this
256 // map do not have meaningful values for 'Call' or the 'PoolHandle' elements
257 // of the ArgInfo elements.
258 //
Chris Lattner692ad5d2002-03-29 17:13:46 +0000259 map<TransformFunctionInfo, Function*> TransformedFunctions;
260
261 // getTransformedFunction - Get a transformed function, or return null if
262 // the function specified hasn't been transformed yet.
263 //
264 Function *getTransformedFunction(TransformFunctionInfo &TFI) const {
265 map<TransformFunctionInfo, Function*>::const_iterator I =
266 TransformedFunctions.find(TFI);
267 if (I != TransformedFunctions.end()) return I->second;
268 return 0;
269 }
270
271
Chris Lattner441e16f2002-04-12 20:23:15 +0000272 // addPoolPrototypes - Add prototypes for the pool functions to the
273 // specified module and update the Pool* instance variables to point to
274 // them.
Chris Lattner175f37c2002-03-29 03:40:59 +0000275 //
276 void addPoolPrototypes(Module *M);
277
Chris Lattner66df97d2002-03-29 06:21:38 +0000278
279 // CreatePools - Insert instructions into the function we are processing to
280 // create all of the memory pool objects themselves. This also inserts
281 // destruction code. Add an alloca for each pool that is allocated to the
Chris Lattner441e16f2002-04-12 20:23:15 +0000282 // PoolDescs map.
Chris Lattner66df97d2002-03-29 06:21:38 +0000283 //
284 void CreatePools(Function *F, const vector<AllocDSNode*> &Allocs,
Chris Lattner441e16f2002-04-12 20:23:15 +0000285 map<DSNode*, PoolInfo> &PoolDescs);
Chris Lattner66df97d2002-03-29 06:21:38 +0000286
Chris Lattner175f37c2002-03-29 03:40:59 +0000287 // processFunction - Convert a function to use pool allocation where
288 // available.
289 //
290 bool processFunction(Function *F);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000291
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000292 // transformFunctionBody - This transforms the instruction in 'F' to use the
Chris Lattner441e16f2002-04-12 20:23:15 +0000293 // pools specified in PoolDescs when modifying data structure nodes
294 // specified in the PoolDescs map. IPFGraph is the closed data structure
295 // graph for F, of which the PoolDescriptor nodes come from.
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000296 //
297 void transformFunctionBody(Function *F, FunctionDSGraph &IPFGraph,
Chris Lattner441e16f2002-04-12 20:23:15 +0000298 map<DSNode*, PoolInfo> &PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000299
300 // transformFunction - Transform the specified function the specified way.
301 // It we have already transformed that function that way, don't do anything.
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000302 // The nodes in the TransformFunctionInfo come out of callers data structure
Chris Lattner441e16f2002-04-12 20:23:15 +0000303 // graph, and the PoolDescs passed in are the caller's.
Chris Lattner692ad5d2002-03-29 17:13:46 +0000304 //
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000305 void transformFunction(TransformFunctionInfo &TFI,
Chris Lattner441e16f2002-04-12 20:23:15 +0000306 FunctionDSGraph &CallerIPGraph,
307 map<DSNode*, PoolInfo> &PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000308
Chris Lattner64fd9352002-03-28 18:08:31 +0000309 };
310}
311
Chris Lattner692ad5d2002-03-29 17:13:46 +0000312// isNotPoolableAlloc - This is a predicate that returns true if the specified
Chris Lattner175f37c2002-03-29 03:40:59 +0000313// allocation node in a data structure graph is eligable for pool allocation.
314//
315static bool isNotPoolableAlloc(const AllocDSNode *DS) {
Chris Lattnere0618ca2002-03-29 05:50:20 +0000316 if (DS->isAllocaNode()) return true; // Do not pool allocate alloca's.
Chris Lattnere0618ca2002-03-29 05:50:20 +0000317 return false;
Chris Lattner175f37c2002-03-29 03:40:59 +0000318}
319
Chris Lattner175f37c2002-03-29 03:40:59 +0000320// processFunction - Convert a function to use pool allocation where
321// available.
322//
323bool PoolAllocate::processFunction(Function *F) {
324 // Get the closed datastructure graph for the current function... if there are
325 // any allocations in this graph that are not escaping, we need to pool
326 // allocate them here!
327 //
328 FunctionDSGraph &IPGraph = DS->getClosedDSGraph(F);
329
330 // Get all of the allocations that do not escape the current function. Since
331 // they are still live (they exist in the graph at all), this means we must
332 // have scalar references to these nodes, but the scalars are never returned.
333 //
Chris Lattner692ad5d2002-03-29 17:13:46 +0000334 vector<AllocDSNode*> Allocs;
Chris Lattner175f37c2002-03-29 03:40:59 +0000335 IPGraph.getNonEscapingAllocations(Allocs);
336
337 // Filter out allocations that we cannot handle. Currently, this includes
338 // variable sized array allocations and alloca's (which we do not want to
339 // pool allocate)
340 //
341 Allocs.erase(remove_if(Allocs.begin(), Allocs.end(), isNotPoolableAlloc),
342 Allocs.end());
343
344
345 if (Allocs.empty()) return false; // Nothing to do.
346
Chris Lattner3e78dea2002-04-18 14:43:30 +0000347#ifdef DEBUG_TRANSFORM_PROGRESS
348 cerr << "Transforming Function: " << F->getName() << "\n";
349#endif
350
Chris Lattner692ad5d2002-03-29 17:13:46 +0000351 // Insert instructions into the function we are processing to create all of
352 // the memory pool objects themselves. This also inserts destruction code.
Chris Lattner441e16f2002-04-12 20:23:15 +0000353 // This fills in the PoolDescs map to associate the alloc node with the
Chris Lattner396d5d72002-03-30 04:02:31 +0000354 // allocation of the memory pool corresponding to it.
Chris Lattner692ad5d2002-03-29 17:13:46 +0000355 //
Chris Lattner441e16f2002-04-12 20:23:15 +0000356 map<DSNode*, PoolInfo> PoolDescs;
357 CreatePools(F, Allocs, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000358
Chris Lattneracf19022002-04-14 06:14:41 +0000359#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +0000360 cerr << "Transformed Entry Function: \n" << F;
Chris Lattneracf19022002-04-14 06:14:41 +0000361#endif
Chris Lattner441e16f2002-04-12 20:23:15 +0000362
363 // Now we need to figure out what called functions we need to transform, and
Chris Lattner692ad5d2002-03-29 17:13:46 +0000364 // how. To do this, we look at all of the scalars, seeing which functions are
365 // either used as a scalar value (so they return a data structure), or are
366 // passed one of our scalar values.
367 //
Chris Lattner441e16f2002-04-12 20:23:15 +0000368 transformFunctionBody(F, IPGraph, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000369
370 return true;
371}
372
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000373
Chris Lattner441e16f2002-04-12 20:23:15 +0000374//===----------------------------------------------------------------------===//
375//
376// NewInstructionCreator - This class is used to traverse the function being
377// modified, changing each instruction visit'ed to use and provide pointer
378// indexes instead of real pointers. This is what changes the body of a
379// function to use pool allocation.
380//
381class NewInstructionCreator : public InstVisitor<NewInstructionCreator> {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000382 PoolAllocate &PoolAllocator;
383 vector<ScalarInfo> &Scalars;
384 map<CallInst*, TransformFunctionInfo> &CallMap;
Chris Lattner441e16f2002-04-12 20:23:15 +0000385 map<Value*, Value*> &XFormMap; // Map old pointers to new indexes
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000386
Chris Lattner441e16f2002-04-12 20:23:15 +0000387 struct RefToUpdate {
388 Instruction *I; // Instruction to update
389 unsigned OpNum; // Operand number to update
390 Value *OldVal; // The old value it had
391
392 RefToUpdate(Instruction *i, unsigned o, Value *ov)
393 : I(i), OpNum(o), OldVal(ov) {}
394 };
395 vector<RefToUpdate> ReferencesToUpdate;
396
397 const ScalarInfo &getScalarRef(const Value *V) {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000398 for (unsigned i = 0, e = Scalars.size(); i != e; ++i)
399 if (Scalars[i].Val == V) return Scalars[i];
Chris Lattner3e78dea2002-04-18 14:43:30 +0000400
401 cerr << "Could not find scalar " << V << " in scalar map!\n";
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000402 assert(0 && "Scalar not found in getScalar!");
403 abort();
404 return Scalars[0];
405 }
Chris Lattner441e16f2002-04-12 20:23:15 +0000406
407 const ScalarInfo *getScalar(const Value *V) {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000408 for (unsigned i = 0, e = Scalars.size(); i != e; ++i)
Chris Lattner441e16f2002-04-12 20:23:15 +0000409 if (Scalars[i].Val == V) return &Scalars[i];
410 return 0;
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000411 }
412
Chris Lattner441e16f2002-04-12 20:23:15 +0000413 BasicBlock::iterator ReplaceInstWith(Instruction *I, Instruction *New) {
414 BasicBlock *BB = I->getParent();
415 BasicBlock::iterator RI = find(BB->begin(), BB->end(), I);
416 BB->getInstList().replaceWith(RI, New);
417 XFormMap[I] = New;
418 return RI;
419 }
420
421 LoadInst *createPoolBaseInstruction(Value *PtrVal) {
422 const ScalarInfo &SC = getScalarRef(PtrVal);
423 vector<Value*> Args(3);
424 Args[0] = ConstantUInt::get(Type::UIntTy, 0); // No pointer offset
425 Args[1] = ConstantUInt::get(Type::UByteTy, 0); // Field #0 of pool descriptr
426 Args[2] = ConstantUInt::get(Type::UByteTy, 0); // Field #0 of poolalloc val
427 return new LoadInst(SC.Pool.Handle, Args, PtrVal->getName()+".poolbase");
428 }
429
430
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000431public:
Chris Lattner441e16f2002-04-12 20:23:15 +0000432 NewInstructionCreator(PoolAllocate &PA, vector<ScalarInfo> &S,
433 map<CallInst*, TransformFunctionInfo> &C,
434 map<Value*, Value*> &X)
435 : PoolAllocator(PA), Scalars(S), CallMap(C), XFormMap(X) {}
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000436
Chris Lattner441e16f2002-04-12 20:23:15 +0000437
438 // updateReferences - The NewInstructionCreator is responsible for creating
439 // new instructions to replace the old ones in the function, and then link up
440 // references to values to their new values. For it to do this, however, it
441 // keeps track of information about the value mapping of old values to new
442 // values that need to be patched up. Given this value map and a set of
443 // instruction operands to patch, updateReferences performs the updates.
444 //
445 void updateReferences() {
446 for (unsigned i = 0, e = ReferencesToUpdate.size(); i != e; ++i) {
447 RefToUpdate &Ref = ReferencesToUpdate[i];
448 Value *NewVal = XFormMap[Ref.OldVal];
449
450 if (NewVal == 0) {
451 if (isa<Constant>(Ref.OldVal) && // Refering to a null ptr?
452 cast<Constant>(Ref.OldVal)->isNullValue()) {
453 // Transform the null pointer into a null index... caching in XFormMap
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000454 XFormMap[Ref.OldVal] = NewVal = Constant::getNullValue(POINTERTYPE);
Chris Lattner441e16f2002-04-12 20:23:15 +0000455 //} else if (isa<Argument>(Ref.OldVal)) {
456 } else {
457 cerr << "Unknown reference to: " << Ref.OldVal << "\n";
458 assert(XFormMap[Ref.OldVal] &&
459 "Reference to value that was not updated found!");
460 }
461 }
462
463 Ref.I->setOperand(Ref.OpNum, NewVal);
464 }
465 ReferencesToUpdate.clear();
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000466 }
467
Chris Lattner441e16f2002-04-12 20:23:15 +0000468 //===--------------------------------------------------------------------===//
469 // Transformation methods:
470 // These methods specify how each type of instruction is transformed by the
471 // NewInstructionCreator instance...
472 //===--------------------------------------------------------------------===//
473
474 void visitGetElementPtrInst(GetElementPtrInst *I) {
475 assert(0 && "Cannot transform get element ptr instructions yet!");
476 }
477
478 // Replace the load instruction with a new one.
479 void visitLoadInst(LoadInst *I) {
480 Instruction *PoolBase = createPoolBaseInstruction(I->getOperand(0));
481
482 // Cast our index to be a UIntTy so we can use it to index into the pool...
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000483 CastInst *Index = new CastInst(Constant::getNullValue(POINTERTYPE),
Chris Lattner441e16f2002-04-12 20:23:15 +0000484 Type::UIntTy, I->getOperand(0)->getName());
485
486 ReferencesToUpdate.push_back(RefToUpdate(Index, 0, I->getOperand(0)));
487
488 vector<Value*> Indices(I->idx_begin(), I->idx_end());
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000489 Instruction *IdxInst =
490 BinaryOperator::create(Instruction::Add, Indices[0], Index,
491 I->getName()+".idx");
492 Indices[0] = IdxInst;
Chris Lattner441e16f2002-04-12 20:23:15 +0000493 Instruction *NewLoad = new LoadInst(PoolBase, Indices, I->getName());
494
495 // Replace the load instruction with the new load instruction...
496 BasicBlock::iterator II = ReplaceInstWith(I, NewLoad);
497
498 // Add the pool base calculator instruction before the load...
499 II = NewLoad->getParent()->getInstList().insert(II, PoolBase) + 1;
500
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000501 // Add the idx calculator instruction before the load...
502 II = NewLoad->getParent()->getInstList().insert(II, Index) + 1;
503
Chris Lattner441e16f2002-04-12 20:23:15 +0000504 // Add the cast before the load instruction...
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000505 NewLoad->getParent()->getInstList().insert(II, IdxInst);
Chris Lattner441e16f2002-04-12 20:23:15 +0000506
507 // If not yielding a pool allocated pointer, use the new load value as the
508 // value in the program instead of the old load value...
509 //
510 if (!getScalar(I))
511 I->replaceAllUsesWith(NewLoad);
512 }
513
514 // Replace the store instruction with a new one. In the store instruction,
515 // the value stored could be a pointer type, meaning that the new store may
516 // have to change one or both of it's operands.
517 //
518 void visitStoreInst(StoreInst *I) {
519 assert(getScalar(I->getOperand(1)) &&
520 "Store inst found only storing pool allocated pointer. "
521 "Not imp yet!");
522
523 Value *Val = I->getOperand(0); // The value to store...
524 // Check to see if the value we are storing is a data structure pointer...
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000525 //if (const ScalarInfo *ValScalar = getScalar(I->getOperand(0)))
526 if (isa<PointerType>(I->getOperand(0)->getType()))
527 Val = Constant::getNullValue(POINTERTYPE); // Yes, store a dummy
Chris Lattner441e16f2002-04-12 20:23:15 +0000528
529 Instruction *PoolBase = createPoolBaseInstruction(I->getOperand(1));
530
531 // Cast our index to be a UIntTy so we can use it to index into the pool...
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000532 CastInst *Index = new CastInst(Constant::getNullValue(POINTERTYPE),
Chris Lattner441e16f2002-04-12 20:23:15 +0000533 Type::UIntTy, I->getOperand(1)->getName());
534 ReferencesToUpdate.push_back(RefToUpdate(Index, 0, I->getOperand(1)));
535
536 vector<Value*> Indices(I->idx_begin(), I->idx_end());
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000537 Instruction *IdxInst =
538 BinaryOperator::create(Instruction::Add, Indices[0], Index, "idx");
539 Indices[0] = IdxInst;
540
Chris Lattner441e16f2002-04-12 20:23:15 +0000541 Instruction *NewStore = new StoreInst(Val, PoolBase, Indices);
542
543 if (Val != I->getOperand(0)) // Value stored was a pointer?
544 ReferencesToUpdate.push_back(RefToUpdate(NewStore, 0, I->getOperand(0)));
545
546
547 // Replace the store instruction with the cast instruction...
548 BasicBlock::iterator II = ReplaceInstWith(I, Index);
549
550 // Add the pool base calculator instruction before the index...
551 II = Index->getParent()->getInstList().insert(II, PoolBase) + 2;
552
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000553 // Add the indexing instruction...
554 II = Index->getParent()->getInstList().insert(II, IdxInst) + 1;
555
Chris Lattner441e16f2002-04-12 20:23:15 +0000556 // Add the store after the cast instruction...
557 Index->getParent()->getInstList().insert(II, NewStore);
558 }
559
560
561 // Create call to poolalloc for every malloc instruction
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000562 void visitMallocInst(MallocInst *I) {
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000563 const ScalarInfo &SCI = getScalarRef(I);
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000564 vector<Value*> Args;
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000565
566 CallInst *Call;
567 if (!I->isArrayAllocation()) {
568 Args.push_back(SCI.Pool.Handle);
569 Call = new CallInst(PoolAllocator.PoolAlloc, Args, I->getName());
570 } else {
571 Args.push_back(I->getArraySize());
572 Args.push_back(SCI.Pool.Handle);
573 Call = new CallInst(PoolAllocator.PoolAllocArray, Args, I->getName());
574 }
575
Chris Lattner441e16f2002-04-12 20:23:15 +0000576 ReplaceInstWith(I, Call);
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000577 }
578
Chris Lattner441e16f2002-04-12 20:23:15 +0000579 // Convert a call to poolfree for every free instruction...
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000580 void visitFreeInst(FreeInst *I) {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000581 // Create a new call to poolfree before the free instruction
582 vector<Value*> Args;
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000583 Args.push_back(Constant::getNullValue(POINTERTYPE));
Chris Lattner441e16f2002-04-12 20:23:15 +0000584 Args.push_back(getScalarRef(I->getOperand(0)).Pool.Handle);
585 Instruction *NewCall = new CallInst(PoolAllocator.PoolFree, Args);
586 ReplaceInstWith(I, NewCall);
Chris Lattner271255b2002-04-18 22:11:30 +0000587 ReferencesToUpdate.push_back(RefToUpdate(NewCall, 1, I->getOperand(0)));
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000588 }
589
590 // visitCallInst - Create a new call instruction with the extra arguments for
591 // all of the memory pools that the call needs.
592 //
593 void visitCallInst(CallInst *I) {
594 TransformFunctionInfo &TI = CallMap[I];
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000595
596 // Start with all of the old arguments...
597 vector<Value*> Args(I->op_begin()+1, I->op_end());
598
Chris Lattner441e16f2002-04-12 20:23:15 +0000599 for (unsigned i = 0, e = TI.ArgInfo.size(); i != e; ++i) {
600 // Replace all of the pointer arguments with our new pointer typed values.
601 if (TI.ArgInfo[i].ArgNo != -1)
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000602 Args[TI.ArgInfo[i].ArgNo] = Constant::getNullValue(POINTERTYPE);
Chris Lattner441e16f2002-04-12 20:23:15 +0000603
604 // Add all of the pool arguments...
Chris Lattner396d5d72002-03-30 04:02:31 +0000605 Args.push_back(TI.ArgInfo[i].PoolHandle);
Chris Lattner441e16f2002-04-12 20:23:15 +0000606 }
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000607
608 Function *NF = PoolAllocator.getTransformedFunction(TI);
Chris Lattner441e16f2002-04-12 20:23:15 +0000609 Instruction *NewCall = new CallInst(NF, Args, I->getName());
610 ReplaceInstWith(I, NewCall);
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000611
Chris Lattner441e16f2002-04-12 20:23:15 +0000612 // Keep track of the mapping of operands so that we can resolve them to real
613 // values later.
614 Value *RetVal = NewCall;
615 for (unsigned i = 0, e = TI.ArgInfo.size(); i != e; ++i)
616 if (TI.ArgInfo[i].ArgNo != -1)
617 ReferencesToUpdate.push_back(RefToUpdate(NewCall, TI.ArgInfo[i].ArgNo+1,
618 I->getOperand(TI.ArgInfo[i].ArgNo+1)));
619 else
620 RetVal = 0; // If returning a pointer, don't change retval...
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000621
Chris Lattner441e16f2002-04-12 20:23:15 +0000622 // If not returning a pointer, use the new call as the value in the program
623 // instead of the old call...
624 //
625 if (RetVal)
626 I->replaceAllUsesWith(RetVal);
627 }
628
629 // visitPHINode - Create a new PHI node of POINTERTYPE for all of the old Phi
630 // nodes...
631 //
632 void visitPHINode(PHINode *PN) {
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000633 Value *DummyVal = Constant::getNullValue(POINTERTYPE);
Chris Lattner441e16f2002-04-12 20:23:15 +0000634 PHINode *NewPhi = new PHINode(POINTERTYPE, PN->getName());
635 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
636 NewPhi->addIncoming(DummyVal, PN->getIncomingBlock(i));
637 ReferencesToUpdate.push_back(RefToUpdate(NewPhi, i*2,
638 PN->getIncomingValue(i)));
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000639 }
640
Chris Lattner441e16f2002-04-12 20:23:15 +0000641 ReplaceInstWith(PN, NewPhi);
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000642 }
643
Chris Lattner441e16f2002-04-12 20:23:15 +0000644 // visitReturnInst - Replace ret instruction with a new return...
Chris Lattner847b6e22002-03-30 20:53:14 +0000645 void visitReturnInst(ReturnInst *I) {
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000646 Instruction *Ret = new ReturnInst(Constant::getNullValue(POINTERTYPE));
Chris Lattner441e16f2002-04-12 20:23:15 +0000647 ReplaceInstWith(I, Ret);
648 ReferencesToUpdate.push_back(RefToUpdate(Ret, 0, I->getOperand(0)));
Chris Lattner847b6e22002-03-30 20:53:14 +0000649 }
650
Chris Lattner441e16f2002-04-12 20:23:15 +0000651 // visitSetCondInst - Replace a conditional test instruction with a new one
Chris Lattnercf09a2a2002-04-01 00:45:33 +0000652 void visitSetCondInst(SetCondInst *SCI) {
Chris Lattner441e16f2002-04-12 20:23:15 +0000653 BinaryOperator *I = (BinaryOperator*)SCI;
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000654 Value *DummyVal = Constant::getNullValue(POINTERTYPE);
Chris Lattner441e16f2002-04-12 20:23:15 +0000655 BinaryOperator *New = BinaryOperator::create(I->getOpcode(), DummyVal,
656 DummyVal, I->getName());
657 ReplaceInstWith(I, New);
658
659 ReferencesToUpdate.push_back(RefToUpdate(New, 0, I->getOperand(0)));
660 ReferencesToUpdate.push_back(RefToUpdate(New, 1, I->getOperand(1)));
661
662 // Make sure branches refer to the new condition...
663 I->replaceAllUsesWith(New);
Chris Lattnercf09a2a2002-04-01 00:45:33 +0000664 }
665
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000666 void visitInstruction(Instruction *I) {
Chris Lattner441e16f2002-04-12 20:23:15 +0000667 cerr << "Unknown instruction to FunctionBodyTransformer:\n" << I;
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000668 }
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000669};
670
671
Chris Lattner457e1ac2002-04-15 22:42:23 +0000672// PoolBaseLoadEliminator - Every load and store through a pool allocated
673// pointer causes a load of the real pool base out of the pool descriptor.
674// Iterate through the function, doing a local elimination pass of duplicate
675// loads. This attempts to turn the all too common:
676//
677// %reg109.poolbase22 = load %root.pool* %root.pool, uint 0, ubyte 0, ubyte 0
678// %reg207 = load %root.p* %reg109.poolbase22, uint %reg109, ubyte 0, ubyte 0
679// %reg109.poolbase23 = load %root.pool* %root.pool, uint 0, ubyte 0, ubyte 0
680// store double %reg207, %root.p* %reg109.poolbase23, uint %reg109, ...
681//
682// into:
683// %reg109.poolbase22 = load %root.pool* %root.pool, uint 0, ubyte 0, ubyte 0
684// %reg207 = load %root.p* %reg109.poolbase22, uint %reg109, ubyte 0, ubyte 0
685// store double %reg207, %root.p* %reg109.poolbase22, uint %reg109, ...
686//
687//
688class PoolBaseLoadEliminator : public InstVisitor<PoolBaseLoadEliminator> {
689 // PoolDescValues - Keep track of the values in the current function that are
690 // pool descriptors (loads from which we want to eliminate).
691 //
692 vector<Value*> PoolDescValues;
693
694 // PoolDescMap - As we are analyzing a BB, keep track of which load to use
695 // when referencing a pool descriptor.
696 //
697 map<Value*, LoadInst*> PoolDescMap;
698
699 // These two fields keep track of statistics of how effective we are, if
700 // debugging is enabled.
701 //
702 unsigned Eliminated, Remaining;
703public:
704 // Compact the pool descriptor map into a list of the pool descriptors in the
705 // current context that we should know about...
706 //
707 PoolBaseLoadEliminator(const map<DSNode*, PoolInfo> &PoolDescs) {
708 Eliminated = Remaining = 0;
709 for (map<DSNode*, PoolInfo>::const_iterator I = PoolDescs.begin(),
710 E = PoolDescs.end(); I != E; ++I)
711 PoolDescValues.push_back(I->second.Handle);
712
713 // Remove duplicates from the list of pool values
714 sort(PoolDescValues.begin(), PoolDescValues.end());
715 PoolDescValues.erase(unique(PoolDescValues.begin(), PoolDescValues.end()),
716 PoolDescValues.end());
717 }
718
719#ifdef DEBUG_POOLBASE_LOAD_ELIMINATOR
720 void visitFunction(Function *F) {
721 cerr << "Pool Load Elim '" << F->getName() << "'\t";
722 }
723 ~PoolBaseLoadEliminator() {
724 unsigned Total = Eliminated+Remaining;
725 if (Total)
726 cerr << "removed " << Eliminated << "["
727 << Eliminated*100/Total << "%] loads, leaving "
728 << Remaining << ".\n";
729 }
730#endif
731
732 // Loop over the function, looking for loads to eliminate. Because we are a
733 // local transformation, we reset all of our state when we enter a new basic
734 // block.
735 //
736 void visitBasicBlock(BasicBlock *) {
737 PoolDescMap.clear(); // Forget state.
738 }
739
740 // Starting with an empty basic block, we scan it looking for loads of the
741 // pool descriptor. When we find a load, we add it to the PoolDescMap,
742 // indicating that we have a value available to recycle next time we see the
743 // poolbase of this instruction being loaded.
744 //
745 void visitLoadInst(LoadInst *LI) {
746 Value *LoadAddr = LI->getPointerOperand();
747 map<Value*, LoadInst*>::iterator VIt = PoolDescMap.find(LoadAddr);
748 if (VIt != PoolDescMap.end()) { // We already have a value for this load?
749 LI->replaceAllUsesWith(VIt->second); // Make the current load dead
750 ++Eliminated;
751 } else {
752 // This load might not be a load of a pool pointer, check to see if it is
753 if (LI->getNumOperands() == 4 && // load pool, uint 0, ubyte 0, ubyte 0
754 find(PoolDescValues.begin(), PoolDescValues.end(), LoadAddr) !=
755 PoolDescValues.end()) {
756
757 assert("Make sure it's a load of the pool base, not a chaining field" &&
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000758 LI->getOperand(1) == Constant::getNullValue(Type::UIntTy) &&
759 LI->getOperand(2) == Constant::getNullValue(Type::UByteTy) &&
760 LI->getOperand(3) == Constant::getNullValue(Type::UByteTy));
Chris Lattner457e1ac2002-04-15 22:42:23 +0000761
762 // If it is a load of a pool base, keep track of it for future reference
763 PoolDescMap.insert(make_pair(LoadAddr, LI));
764 ++Remaining;
765 }
766 }
767 }
768
769 // If we run across a function call, forget all state... Calls to
770 // poolalloc/poolfree can invalidate the pool base pointer, so it should be
771 // reloaded the next time it is used. Furthermore, a call to a random
772 // function might call one of these functions, so be conservative. Through
773 // more analysis, this could be improved in the future.
774 //
775 void visitCallInst(CallInst *) {
776 PoolDescMap.clear();
777 }
778};
779
Chris Lattner3e78dea2002-04-18 14:43:30 +0000780static void addNodeMapping(DSNode *SrcNode, const PointerValSet &PVS,
781 map<DSNode*, PointerValSet> &NodeMapping) {
782 for (unsigned i = 0, e = PVS.size(); i != e; ++i)
783 if (NodeMapping[SrcNode].add(PVS[i])) { // Not in map yet?
784 assert(PVS[i].Index == 0 && "Node indexing not supported yet!");
785 DSNode *DestNode = PVS[i].Node;
786
787 // Loop over all of the outgoing links in the mapped graph
788 for (unsigned l = 0, le = DestNode->getNumOutgoingLinks(); l != le; ++l) {
789 PointerValSet &SrcSet = SrcNode->getOutgoingLink(l);
790 const PointerValSet &DestSet = DestNode->getOutgoingLink(l);
791
792 // Add all of the node mappings now!
793 for (unsigned si = 0, se = SrcSet.size(); si != se; ++si) {
794 assert(SrcSet[si].Index == 0 && "Can't handle node offset!");
795 addNodeMapping(SrcSet[si].Node, DestSet, NodeMapping);
796 }
797 }
798 }
799}
800
801// CalculateNodeMapping - There is a partial isomorphism between the graph
802// passed in and the graph that is actually used by the function. We need to
803// figure out what this mapping is so that we can transformFunctionBody the
804// instructions in the function itself. Note that every node in the graph that
805// we are interested in must be both in the local graph of the called function,
806// and in the local graph of the calling function. Because of this, we only
807// define the mapping for these nodes [conveniently these are the only nodes we
808// CAN define a mapping for...]
809//
810// The roots of the graph that we are transforming is rooted in the arguments
811// passed into the function from the caller. This is where we start our
812// mapping calculation.
813//
814// The NodeMapping calculated maps from the callers graph to the called graph.
815//
816static void CalculateNodeMapping(Function *F, TransformFunctionInfo &TFI,
817 FunctionDSGraph &CallerGraph,
818 FunctionDSGraph &CalledGraph,
819 map<DSNode*, PointerValSet> &NodeMapping) {
820 int LastArgNo = -2;
821 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i) {
822 // Figure out what nodes in the called graph the TFI.ArgInfo[i].Node node
823 // corresponds to...
824 //
825 // Only consider first node of sequence. Extra nodes may may be added
826 // to the TFI if the data structure requires more nodes than just the
827 // one the argument points to. We are only interested in the one the
828 // argument points to though.
829 //
830 if (TFI.ArgInfo[i].ArgNo != LastArgNo) {
831 if (TFI.ArgInfo[i].ArgNo == -1) {
832 addNodeMapping(TFI.ArgInfo[i].Node, CalledGraph.getRetNodes(),
833 NodeMapping);
834 } else {
835 // Figure out which node argument # ArgNo points to in the called graph.
836 Value *Arg = F->getArgumentList()[TFI.ArgInfo[i].ArgNo];
837 addNodeMapping(TFI.ArgInfo[i].Node, CalledGraph.getValueMap()[Arg],
838 NodeMapping);
839 }
840 LastArgNo = TFI.ArgInfo[i].ArgNo;
841 }
842 }
843}
Chris Lattner441e16f2002-04-12 20:23:15 +0000844
845
Chris Lattner3e78dea2002-04-18 14:43:30 +0000846
847
848// addCallInfo - For a specified function call CI, figure out which pool
849// descriptors need to be passed in as arguments, and which arguments need to be
850// transformed into indices. If Arg != -1, the specified call argument is
851// passed in as a pointer to a data structure.
852//
853void TransformFunctionInfo::addCallInfo(DataStructure *DS, CallInst *CI,
854 int Arg, DSNode *GraphNode,
855 map<DSNode*, PoolInfo> &PoolDescs) {
Chris Lattner0dc225c2002-03-31 07:17:46 +0000856 assert(CI->getCalledFunction() && "Cannot handle indirect calls yet!");
Chris Lattner3e78dea2002-04-18 14:43:30 +0000857 assert(Func == 0 || Func == CI->getCalledFunction() &&
Chris Lattner0dc225c2002-03-31 07:17:46 +0000858 "Function call record should always call the same function!");
Chris Lattner3e78dea2002-04-18 14:43:30 +0000859 assert(Call == 0 || Call == CI &&
Chris Lattner0dc225c2002-03-31 07:17:46 +0000860 "Call element already filled in with different value!");
Chris Lattner3e78dea2002-04-18 14:43:30 +0000861 Func = CI->getCalledFunction();
862 Call = CI;
863 //FunctionDSGraph &CalledGraph = DS->getClosedDSGraph(Func);
Chris Lattner396d5d72002-03-30 04:02:31 +0000864
865 // For now, add the entire graph that is pointed to by the call argument.
866 // This graph can and should be pruned to only what the function itself will
867 // use, because often this will be a dramatically smaller subset of what we
868 // are providing.
869 //
Chris Lattner3e78dea2002-04-18 14:43:30 +0000870 // FIXME: This should use pool links instead of extra arguments!
871 //
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000872 for (df_iterator<DSNode*> I = df_begin(GraphNode), E = df_end(GraphNode);
Chris Lattner441e16f2002-04-12 20:23:15 +0000873 I != E; ++I)
Chris Lattner3e78dea2002-04-18 14:43:30 +0000874 ArgInfo.push_back(CallArgInfo(Arg, *I, PoolDescs[*I].Handle));
875}
876
877static void markReachableNodes(const PointerValSet &Vals,
878 set<DSNode*> &ReachableNodes) {
879 for (unsigned n = 0, ne = Vals.size(); n != ne; ++n) {
880 DSNode *N = Vals[n].Node;
881 if (ReachableNodes.count(N) == 0) // Haven't already processed node?
882 ReachableNodes.insert(df_begin(N), df_end(N)); // Insert all
883 }
884}
885
886// Make sure that all dependant arguments are added to this transformation info.
887// For example, if we call foo(null, P) and foo treats it's first and second
888// arguments as belonging to the same data structure, the we MUST add entries to
889// know that the null needs to be transformed into an index as well.
890//
891void TransformFunctionInfo::ensureDependantArgumentsIncluded(DataStructure *DS,
892 map<DSNode*, PoolInfo> &PoolDescs) {
893 // FIXME: This does not work for indirect function calls!!!
894 if (Func == 0) return; // FIXME!
895
896 // Make sure argument entries are sorted.
897 finalizeConstruction();
898
899 // Loop over the function signature, checking to see if there are any pointer
900 // arguments that we do not convert... if there is something we haven't
901 // converted, set done to false.
902 //
903 unsigned PtrNo = 0;
904 bool Done = true;
905 if (isa<PointerType>(Func->getReturnType())) // Make sure we convert retval
906 if (PtrNo < ArgInfo.size() && ArgInfo[PtrNo++].ArgNo == -1) {
907 // We DO transform the ret val... skip all possible entries for retval
908 while (PtrNo < ArgInfo.size() && ArgInfo[PtrNo].ArgNo == -1)
909 PtrNo++;
910 } else {
911 Done = false;
912 }
913
914 for (unsigned i = 0, e = Func->getArgumentList().size(); i != e; ++i) {
915 Argument *Arg = Func->getArgumentList()[i];
916 if (isa<PointerType>(Arg->getType())) {
917 if (PtrNo < ArgInfo.size() && ArgInfo[PtrNo++].ArgNo == (int)i) {
918 // We DO transform this arg... skip all possible entries for argument
919 while (PtrNo < ArgInfo.size() && ArgInfo[PtrNo].ArgNo == (int)i)
920 PtrNo++;
921 } else {
922 Done = false;
923 break;
924 }
925 }
926 }
927
928 // If we already have entries for all pointer arguments and retvals, there
929 // certainly is no work to do. Bail out early to avoid building relatively
930 // expensive data structures.
931 //
932 if (Done) return;
933
934#ifdef DEBUG_TRANSFORM_PROGRESS
935 cerr << "Must ensure dependant arguments for: " << Func->getName() << "\n";
936#endif
937
938 // Otherwise, we MIGHT have to add the arguments/retval if they are part of
939 // the same datastructure graph as some other argument or retval that we ARE
940 // processing.
941 //
942 // Get the data structure graph for the called function.
943 //
944 FunctionDSGraph &CalledDS = DS->getClosedDSGraph(Func);
945
946 // Build a mapping between the nodes in our current graph and the nodes in the
947 // called function's graph. We build it based on our _incomplete_
948 // transformation information, because it contains all of the info that we
949 // should need.
950 //
951 map<DSNode*, PointerValSet> NodeMapping;
952 CalculateNodeMapping(Func, *this,
953 DS->getClosedDSGraph(Call->getParent()->getParent()),
954 CalledDS, NodeMapping);
955
956 // Build the inverted version of the node mapping, that maps from a node in
957 // the called functions graph to a single node in the caller graph.
958 //
959 map<DSNode*, DSNode*> InverseNodeMap;
960 for (map<DSNode*, PointerValSet>::iterator I = NodeMapping.begin(),
961 E = NodeMapping.end(); I != E; ++I) {
962 PointerValSet &CalledNodes = I->second;
963 for (unsigned i = 0, e = CalledNodes.size(); i != e; ++i)
964 InverseNodeMap[CalledNodes[i].Node] = I->first;
965 }
966 NodeMapping.clear(); // Done with information, free memory
967
968 // Build a set of reachable nodes from the arguments/retval that we ARE
969 // passing in...
970 set<DSNode*> ReachableNodes;
971
972 // Loop through all of the arguments, marking all of the reachable data
973 // structure nodes reachable if they are from this pointer...
974 //
975 for (unsigned i = 0, e = ArgInfo.size(); i != e; ++i) {
976 if (ArgInfo[i].ArgNo == -1) {
977 if (i == 0) // Only process retvals once (performance opt)
978 markReachableNodes(CalledDS.getRetNodes(), ReachableNodes);
979 } else { // If it's an argument value...
980 Argument *Arg = Func->getArgumentList()[ArgInfo[i].ArgNo];
981 if (isa<PointerType>(Arg->getType()))
982 markReachableNodes(CalledDS.getValueMap()[Arg], ReachableNodes);
983 }
984 }
985
986 // Now that we know which nodes are already reachable, see if any of the
987 // arguments that we are not passing values in for can reach one of the
988 // existing nodes...
989 //
990
991 // <FIXME> IN THEORY, we should allow arbitrary paths from the argument to
992 // nodes we know about. The problem is that if we do this, then I don't know
993 // how to get pool pointers for this head list. Since we are completely
994 // deadline driven, I'll just allow direct accesses to the graph. </FIXME>
995 //
996
997 PtrNo = 0;
998 if (isa<PointerType>(Func->getReturnType())) // Make sure we convert retval
999 if (PtrNo < ArgInfo.size() && ArgInfo[PtrNo++].ArgNo == -1) {
1000 // We DO transform the ret val... skip all possible entries for retval
1001 while (PtrNo < ArgInfo.size() && ArgInfo[PtrNo].ArgNo == -1)
1002 PtrNo++;
1003 } else {
1004 // See what the return value points to...
1005
1006 // FIXME: This should generalize to any number of nodes, just see if any
1007 // are reachable.
1008 assert(CalledDS.getRetNodes().size() == 1 &&
1009 "Assumes only one node is returned");
1010 DSNode *N = CalledDS.getRetNodes()[0].Node;
1011
1012 // If the return value is not marked as being passed in, but it NEEDS to
1013 // be transformed, then make it known now.
1014 //
1015 if (ReachableNodes.count(N)) {
1016#ifdef DEBUG_TRANSFORM_PROGRESS
1017 cerr << "ensure dependant arguments adds return value entry!\n";
1018#endif
1019 addCallInfo(DS, Call, -1, InverseNodeMap[N], PoolDescs);
1020
1021 // Keep sorted!
1022 finalizeConstruction();
1023 }
1024 }
1025
1026 for (unsigned i = 0, e = Func->getArgumentList().size(); i != e; ++i) {
1027 Argument *Arg = Func->getArgumentList()[i];
1028 if (isa<PointerType>(Arg->getType())) {
1029 if (PtrNo < ArgInfo.size() && ArgInfo[PtrNo++].ArgNo == (int)i) {
1030 // We DO transform this arg... skip all possible entries for argument
1031 while (PtrNo < ArgInfo.size() && ArgInfo[PtrNo].ArgNo == (int)i)
1032 PtrNo++;
1033 } else {
1034 // This should generalize to any number of nodes, just see if any are
1035 // reachable.
1036 assert(CalledDS.getValueMap()[Arg].size() == 1 &&
1037 "Only handle case where pointing to one node so far!");
1038
1039 // If the arg is not marked as being passed in, but it NEEDS to
1040 // be transformed, then make it known now.
1041 //
1042 DSNode *N = CalledDS.getValueMap()[Arg][0].Node;
1043 if (ReachableNodes.count(N)) {
1044#ifdef DEBUG_TRANSFORM_PROGRESS
1045 cerr << "ensure dependant arguments adds for arg #" << i << "\n";
1046#endif
1047 addCallInfo(DS, Call, i, InverseNodeMap[N], PoolDescs);
1048
1049 // Keep sorted!
1050 finalizeConstruction();
1051 }
1052 }
1053 }
1054 }
Chris Lattner396d5d72002-03-30 04:02:31 +00001055}
1056
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001057
1058// transformFunctionBody - This transforms the instruction in 'F' to use the
Chris Lattner441e16f2002-04-12 20:23:15 +00001059// pools specified in PoolDescs when modifying data structure nodes specified in
1060// the PoolDescs map. Specifically, scalar values specified in the Scalars
1061// vector must be remapped. IPFGraph is the closed data structure graph for F,
1062// of which the PoolDescriptor nodes come from.
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001063//
1064void PoolAllocate::transformFunctionBody(Function *F, FunctionDSGraph &IPFGraph,
Chris Lattner441e16f2002-04-12 20:23:15 +00001065 map<DSNode*, PoolInfo> &PoolDescs) {
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001066
1067 // Loop through the value map looking for scalars that refer to nonescaping
1068 // allocations. Add them to the Scalars vector. Note that we may have
1069 // multiple entries in the Scalars vector for each value if it points to more
1070 // than one object.
1071 //
1072 map<Value*, PointerValSet> &ValMap = IPFGraph.getValueMap();
1073 vector<ScalarInfo> Scalars;
1074
Chris Lattneracf19022002-04-14 06:14:41 +00001075#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner0e0c15b2002-04-27 02:29:32 +00001076 cerr << "Building scalar map for fn '" << F->getName() << "' body:\n";
Chris Lattneracf19022002-04-14 06:14:41 +00001077#endif
Chris Lattner847b6e22002-03-30 20:53:14 +00001078
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001079 for (map<Value*, PointerValSet>::iterator I = ValMap.begin(),
1080 E = ValMap.end(); I != E; ++I) {
1081 const PointerValSet &PVS = I->second; // Set of things pointed to by scalar
1082
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001083 // Check to see if the scalar points to a data structure node...
1084 for (unsigned i = 0, e = PVS.size(); i != e; ++i) {
Chris Lattner0e0c15b2002-04-27 02:29:32 +00001085 if (PVS[i].Index) { cerr << "Problem in " << F->getName() << " for " << I->first << "\n"; }
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001086 assert(PVS[i].Index == 0 && "Nonzero not handled yet!");
1087
1088 // If the allocation is in the nonescaping set...
Chris Lattner441e16f2002-04-12 20:23:15 +00001089 map<DSNode*, PoolInfo>::iterator AI = PoolDescs.find(PVS[i].Node);
1090 if (AI != PoolDescs.end()) { // Add it to the list of scalars
1091 Scalars.push_back(ScalarInfo(I->first, AI->second));
Chris Lattneracf19022002-04-14 06:14:41 +00001092#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001093 cerr << "\nScalar Mapping from:" << I->first
1094 << "Scalar Mapping to: "; PVS.print(cerr);
Chris Lattneracf19022002-04-14 06:14:41 +00001095#endif
Chris Lattner441e16f2002-04-12 20:23:15 +00001096 }
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001097 }
1098 }
1099
Chris Lattneracf19022002-04-14 06:14:41 +00001100#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner847b6e22002-03-30 20:53:14 +00001101 cerr << "\nIn '" << F->getName()
Chris Lattner175f37c2002-03-29 03:40:59 +00001102 << "': Found the following values that point to poolable nodes:\n";
1103
1104 for (unsigned i = 0, e = Scalars.size(); i != e; ++i)
Chris Lattner441e16f2002-04-12 20:23:15 +00001105 cerr << Scalars[i].Val;
1106 cerr << "\n";
Chris Lattneracf19022002-04-14 06:14:41 +00001107#endif
Chris Lattnere0618ca2002-03-29 05:50:20 +00001108
Chris Lattner692ad5d2002-03-29 17:13:46 +00001109 // CallMap - Contain an entry for every call instruction that needs to be
1110 // transformed. Each entry in the map contains information about what we need
1111 // to do to each call site to change it to work.
1112 //
1113 map<CallInst*, TransformFunctionInfo> CallMap;
Chris Lattner66df97d2002-03-29 06:21:38 +00001114
Chris Lattner441e16f2002-04-12 20:23:15 +00001115 // Now we need to figure out what called functions we need to transform, and
Chris Lattner692ad5d2002-03-29 17:13:46 +00001116 // how. To do this, we look at all of the scalars, seeing which functions are
1117 // either used as a scalar value (so they return a data structure), or are
1118 // passed one of our scalar values.
1119 //
1120 for (unsigned i = 0, e = Scalars.size(); i != e; ++i) {
1121 Value *ScalarVal = Scalars[i].Val;
1122
1123 // Check to see if the scalar _IS_ a call...
1124 if (CallInst *CI = dyn_cast<CallInst>(ScalarVal))
1125 // If so, add information about the pool it will be returning...
Chris Lattner3e78dea2002-04-18 14:43:30 +00001126 CallMap[CI].addCallInfo(DS, CI, -1, Scalars[i].Pool.Node, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +00001127
1128 // Check to see if the scalar is an operand to a call...
1129 for (Value::use_iterator UI = ScalarVal->use_begin(),
1130 UE = ScalarVal->use_end(); UI != UE; ++UI) {
1131 if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
1132 // Find out which operand this is to the call instruction...
1133 User::op_iterator OI = find(CI->op_begin(), CI->op_end(), ScalarVal);
1134 assert(OI != CI->op_end() && "Call on use list but not an operand!?");
1135 assert(OI != CI->op_begin() && "Pointer operand is call destination?");
1136
1137 // FIXME: This is broken if the same pointer is passed to a call more
1138 // than once! It will get multiple entries for the first pointer.
1139
1140 // Add the operand number and pool handle to the call table...
Chris Lattner3e78dea2002-04-18 14:43:30 +00001141 CallMap[CI].addCallInfo(DS, CI, OI-CI->op_begin()-1,
1142 Scalars[i].Pool.Node, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +00001143 }
1144 }
1145 }
1146
Chris Lattner3e78dea2002-04-18 14:43:30 +00001147 // Make sure that all dependant arguments are added as well. For example, if
1148 // we call foo(null, P) and foo treats it's first and second arguments as
1149 // belonging to the same data structure, the we MUST set up the CallMap to
1150 // know that the null needs to be transformed into an index as well.
1151 //
1152 for (map<CallInst*, TransformFunctionInfo>::iterator I = CallMap.begin();
1153 I != CallMap.end(); ++I)
1154 I->second.ensureDependantArgumentsIncluded(DS, PoolDescs);
1155
Chris Lattneracf19022002-04-14 06:14:41 +00001156#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner692ad5d2002-03-29 17:13:46 +00001157 // Print out call map...
1158 for (map<CallInst*, TransformFunctionInfo>::iterator I = CallMap.begin();
1159 I != CallMap.end(); ++I) {
Chris Lattner441e16f2002-04-12 20:23:15 +00001160 cerr << "For call: " << I->first;
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001161 cerr << I->second.Func->getName() << " must pass pool pointer for args #";
Chris Lattner692ad5d2002-03-29 17:13:46 +00001162 for (unsigned i = 0; i < I->second.ArgInfo.size(); ++i)
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001163 cerr << I->second.ArgInfo[i].ArgNo << ", ";
Chris Lattner441e16f2002-04-12 20:23:15 +00001164 cerr << "\n\n";
Chris Lattner692ad5d2002-03-29 17:13:46 +00001165 }
Chris Lattneracf19022002-04-14 06:14:41 +00001166#endif
Chris Lattner692ad5d2002-03-29 17:13:46 +00001167
1168 // Loop through all of the call nodes, recursively creating the new functions
1169 // that we want to call... This uses a map to prevent infinite recursion and
1170 // to avoid duplicating functions unneccesarily.
1171 //
1172 for (map<CallInst*, TransformFunctionInfo>::iterator I = CallMap.begin(),
1173 E = CallMap.end(); I != E; ++I) {
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001174 // Transform all of the functions we need, or at least ensure there is a
1175 // cached version available.
Chris Lattner441e16f2002-04-12 20:23:15 +00001176 transformFunction(I->second, IPFGraph, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +00001177 }
1178
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001179 // Now that all of the functions that we want to call are available, transform
Chris Lattner441e16f2002-04-12 20:23:15 +00001180 // the local function so that it uses the pools locally and passes them to the
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001181 // functions that we just hacked up.
1182 //
1183
1184 // First step, find the instructions to be modified.
1185 vector<Instruction*> InstToFix;
1186 for (unsigned i = 0, e = Scalars.size(); i != e; ++i) {
1187 Value *ScalarVal = Scalars[i].Val;
1188
1189 // Check to see if the scalar _IS_ an instruction. If so, it is involved.
1190 if (Instruction *Inst = dyn_cast<Instruction>(ScalarVal))
1191 InstToFix.push_back(Inst);
1192
1193 // All all of the instructions that use the scalar as an operand...
1194 for (Value::use_iterator UI = ScalarVal->use_begin(),
1195 UE = ScalarVal->use_end(); UI != UE; ++UI)
Chris Lattner441e16f2002-04-12 20:23:15 +00001196 InstToFix.push_back(cast<Instruction>(*UI));
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001197 }
1198
Chris Lattner50e3d322002-04-13 23:13:18 +00001199 // Make sure that we get return instructions that return a null value from the
1200 // function...
1201 //
1202 if (!IPFGraph.getRetNodes().empty()) {
1203 assert(IPFGraph.getRetNodes().size() == 1 && "Can only return one node?");
1204 PointerVal RetNode = IPFGraph.getRetNodes()[0];
1205 assert(RetNode.Index == 0 && "Subindexing not implemented yet!");
1206
1207 // Only process return instructions if the return value of this function is
1208 // part of one of the data structures we are transforming...
1209 //
1210 if (PoolDescs.count(RetNode.Node)) {
1211 // Loop over all of the basic blocks, adding return instructions...
1212 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
1213 if (ReturnInst *RI = dyn_cast<ReturnInst>((*I)->getTerminator()))
1214 InstToFix.push_back(RI);
1215 }
1216 }
1217
1218
1219
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001220 // Eliminate duplicates by sorting, then removing equal neighbors.
1221 sort(InstToFix.begin(), InstToFix.end());
1222 InstToFix.erase(unique(InstToFix.begin(), InstToFix.end()), InstToFix.end());
1223
Chris Lattner441e16f2002-04-12 20:23:15 +00001224 // Loop over all of the instructions to transform, creating the new
1225 // replacement instructions for them. This also unlinks them from the
1226 // function so they can be safely deleted later.
1227 //
1228 map<Value*, Value*> XFormMap;
1229 NewInstructionCreator NIC(*this, Scalars, CallMap, XFormMap);
Chris Lattner692ad5d2002-03-29 17:13:46 +00001230
Chris Lattner441e16f2002-04-12 20:23:15 +00001231 // Visit all instructions... creating the new instructions that we need and
1232 // unlinking the old instructions from the function...
1233 //
Chris Lattneracf19022002-04-14 06:14:41 +00001234#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001235 for (unsigned i = 0, e = InstToFix.size(); i != e; ++i) {
1236 cerr << "Fixing: " << InstToFix[i];
1237 NIC.visit(InstToFix[i]);
1238 }
Chris Lattneracf19022002-04-14 06:14:41 +00001239#else
1240 NIC.visit(InstToFix.begin(), InstToFix.end());
1241#endif
Chris Lattner441e16f2002-04-12 20:23:15 +00001242
1243 // Make all instructions we will delete "let go" of their operands... so that
1244 // we can safely delete Arguments whose types have changed...
1245 //
1246 for_each(InstToFix.begin(), InstToFix.end(),
1247 mem_fun(&Instruction::dropAllReferences));
1248
1249 // Loop through all of the pointer arguments coming into the function,
1250 // replacing them with arguments of POINTERTYPE to match the function type of
1251 // the function.
1252 //
1253 FunctionType::ParamTypes::const_iterator TI =
1254 F->getFunctionType()->getParamTypes().begin();
1255 for (Function::ArgumentListType::iterator I = F->getArgumentList().begin(),
1256 E = F->getArgumentList().end(); I != E; ++I, ++TI) {
1257 Argument *Arg = *I;
1258 if (Arg->getType() != *TI) {
1259 assert(isa<PointerType>(Arg->getType()) && *TI == POINTERTYPE);
1260 Argument *NewArg = new Argument(*TI, Arg->getName());
1261 XFormMap[Arg] = NewArg; // Map old arg into new arg...
1262
Chris Lattner441e16f2002-04-12 20:23:15 +00001263 // Replace the old argument and then delete it...
1264 delete F->getArgumentList().replaceWith(I, NewArg);
1265 }
1266 }
1267
1268 // Now that all of the new instructions have been created, we can update all
1269 // of the references to dummy values to be references to the actual values
1270 // that are computed.
1271 //
1272 NIC.updateReferences();
1273
Chris Lattneracf19022002-04-14 06:14:41 +00001274#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001275 cerr << "TRANSFORMED FUNCTION:\n" << F;
Chris Lattneracf19022002-04-14 06:14:41 +00001276#endif
Chris Lattner441e16f2002-04-12 20:23:15 +00001277
1278 // Delete all of the "instructions to fix"
1279 for_each(InstToFix.begin(), InstToFix.end(), deleter<Instruction>);
Chris Lattner692ad5d2002-03-29 17:13:46 +00001280
Chris Lattner457e1ac2002-04-15 22:42:23 +00001281 // Eliminate pool base loads that we can easily prove are redundant
1282 if (!DisableRLE)
1283 PoolBaseLoadEliminator(PoolDescs).visit(F);
1284
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001285 // Since we have liberally hacked the function to pieces, we want to inform
1286 // the datastructure pass that its internal representation is out of date.
1287 //
1288 DS->invalidateFunction(F);
Chris Lattner692ad5d2002-03-29 17:13:46 +00001289}
1290
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001291
1292
1293// transformFunction - Transform the specified function the specified way. It
1294// we have already transformed that function that way, don't do anything. The
1295// nodes in the TransformFunctionInfo come out of callers data structure graph.
1296//
1297void PoolAllocate::transformFunction(TransformFunctionInfo &TFI,
Chris Lattner441e16f2002-04-12 20:23:15 +00001298 FunctionDSGraph &CallerIPGraph,
1299 map<DSNode*, PoolInfo> &CallerPoolDesc) {
Chris Lattner692ad5d2002-03-29 17:13:46 +00001300 if (getTransformedFunction(TFI)) return; // Function xformation already done?
1301
Chris Lattneracf19022002-04-14 06:14:41 +00001302#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001303 cerr << "********** Entering transformFunction for "
Chris Lattner0dc225c2002-03-31 07:17:46 +00001304 << TFI.Func->getName() << ":\n";
1305 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i)
1306 cerr << " ArgInfo[" << i << "] = " << TFI.ArgInfo[i].ArgNo << "\n";
1307 cerr << "\n";
Chris Lattneracf19022002-04-14 06:14:41 +00001308#endif
Chris Lattner0dc225c2002-03-31 07:17:46 +00001309
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001310 const FunctionType *OldFuncType = TFI.Func->getFunctionType();
Chris Lattner692ad5d2002-03-29 17:13:46 +00001311
Chris Lattner291a1b12002-03-29 19:05:48 +00001312 assert(!OldFuncType->isVarArg() && "Vararg functions not handled yet!");
Chris Lattner692ad5d2002-03-29 17:13:46 +00001313
Chris Lattner291a1b12002-03-29 19:05:48 +00001314 // Build the type for the new function that we are transforming
1315 vector<const Type*> ArgTys;
Chris Lattner441e16f2002-04-12 20:23:15 +00001316 ArgTys.reserve(OldFuncType->getNumParams()+TFI.ArgInfo.size());
Chris Lattner291a1b12002-03-29 19:05:48 +00001317 for (unsigned i = 0, e = OldFuncType->getNumParams(); i != e; ++i)
1318 ArgTys.push_back(OldFuncType->getParamType(i));
1319
Chris Lattner441e16f2002-04-12 20:23:15 +00001320 const Type *RetType = OldFuncType->getReturnType();
1321
Chris Lattner291a1b12002-03-29 19:05:48 +00001322 // Add one pool pointer for every argument that needs to be supplemented.
Chris Lattner441e16f2002-04-12 20:23:15 +00001323 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i) {
1324 if (TFI.ArgInfo[i].ArgNo == -1)
1325 RetType = POINTERTYPE; // Return a pointer
1326 else
1327 ArgTys[TFI.ArgInfo[i].ArgNo] = POINTERTYPE; // Pass a pointer
1328 ArgTys.push_back(PointerType::get(CallerPoolDesc.find(TFI.ArgInfo[i].Node)
1329 ->second.PoolType));
1330 }
Chris Lattner291a1b12002-03-29 19:05:48 +00001331
1332 // Build the new function type...
Chris Lattner441e16f2002-04-12 20:23:15 +00001333 const FunctionType *NewFuncType = FunctionType::get(RetType, ArgTys,
1334 OldFuncType->isVarArg());
Chris Lattner291a1b12002-03-29 19:05:48 +00001335
1336 // The new function is internal, because we know that only we can call it.
1337 // This also helps subsequent IP transformations to eliminate duplicated pool
Chris Lattner441e16f2002-04-12 20:23:15 +00001338 // pointers (which look like the same value is always passed into a parameter,
1339 // allowing it to be easily eliminated).
Chris Lattner291a1b12002-03-29 19:05:48 +00001340 //
1341 Function *NewFunc = new Function(NewFuncType, true,
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001342 TFI.Func->getName()+".poolxform");
Chris Lattner291a1b12002-03-29 19:05:48 +00001343 CurModule->getFunctionList().push_back(NewFunc);
1344
Chris Lattner441e16f2002-04-12 20:23:15 +00001345
Chris Lattneracf19022002-04-14 06:14:41 +00001346#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001347 cerr << "Created function prototype: " << NewFunc << "\n";
Chris Lattneracf19022002-04-14 06:14:41 +00001348#endif
Chris Lattner441e16f2002-04-12 20:23:15 +00001349
Chris Lattner291a1b12002-03-29 19:05:48 +00001350 // Add the newly formed function to the TransformedFunctions table so that
1351 // infinite recursion does not occur!
1352 //
1353 TransformedFunctions[TFI] = NewFunc;
1354
1355 // Add arguments to the function... starting with all of the old arguments
1356 vector<Value*> ArgMap;
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001357 for (unsigned i = 0, e = TFI.Func->getArgumentList().size(); i != e; ++i) {
Chris Lattner2e9fa6d2002-04-09 19:48:49 +00001358 const Argument *OFA = TFI.Func->getArgumentList()[i];
1359 Argument *NFA = new Argument(OFA->getType(), OFA->getName());
Chris Lattner291a1b12002-03-29 19:05:48 +00001360 NewFunc->getArgumentList().push_back(NFA);
1361 ArgMap.push_back(NFA); // Keep track of the arguments
1362 }
1363
1364 // Now add all of the arguments corresponding to pools passed in...
1365 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i) {
Chris Lattner441e16f2002-04-12 20:23:15 +00001366 CallArgInfo &AI = TFI.ArgInfo[i];
Chris Lattner291a1b12002-03-29 19:05:48 +00001367 string Name;
Chris Lattner441e16f2002-04-12 20:23:15 +00001368 if (AI.ArgNo == -1)
1369 Name = "ret";
Chris Lattner291a1b12002-03-29 19:05:48 +00001370 else
Chris Lattner441e16f2002-04-12 20:23:15 +00001371 Name = ArgMap[AI.ArgNo]->getName(); // Get the arg name
1372 const Type *Ty = PointerType::get(CallerPoolDesc[AI.Node].PoolType);
1373 Argument *NFA = new Argument(Ty, Name+".pool");
Chris Lattner291a1b12002-03-29 19:05:48 +00001374 NewFunc->getArgumentList().push_back(NFA);
1375 }
1376
1377 // Now clone the body of the old function into the new function...
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001378 CloneFunctionInto(NewFunc, TFI.Func, ArgMap);
Chris Lattner291a1b12002-03-29 19:05:48 +00001379
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001380 // Okay, now we have a function that is identical to the old one, except that
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001381 // it has extra arguments for the pools coming in. Now we have to get the
1382 // data structure graph for the function we are replacing, and figure out how
1383 // our graph nodes map to the graph nodes in the dest function.
1384 //
Chris Lattner847b6e22002-03-30 20:53:14 +00001385 FunctionDSGraph &DSGraph = DS->getClosedDSGraph(NewFunc);
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001386
Chris Lattner441e16f2002-04-12 20:23:15 +00001387 // NodeMapping - Multimap from callers graph to called graph. We are
1388 // guaranteed that the called function graph has more nodes than the caller,
1389 // or exactly the same number of nodes. This is because the called function
1390 // might not know that two nodes are merged when considering the callers
1391 // context, but the caller obviously does. Because of this, a single node in
1392 // the calling function's data structure graph can map to multiple nodes in
1393 // the called functions graph.
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001394 //
1395 map<DSNode*, PointerValSet> NodeMapping;
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001396
Chris Lattner847b6e22002-03-30 20:53:14 +00001397 CalculateNodeMapping(NewFunc, TFI, CallerIPGraph, DSGraph,
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001398 NodeMapping);
1399
1400 // Print out the node mapping...
Chris Lattneracf19022002-04-14 06:14:41 +00001401#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner847b6e22002-03-30 20:53:14 +00001402 cerr << "\nNode mapping for call of " << NewFunc->getName() << "\n";
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001403 for (map<DSNode*, PointerValSet>::iterator I = NodeMapping.begin();
1404 I != NodeMapping.end(); ++I) {
1405 cerr << "Map: "; I->first->print(cerr);
1406 cerr << "To: "; I->second.print(cerr);
1407 cerr << "\n";
1408 }
Chris Lattneracf19022002-04-14 06:14:41 +00001409#endif
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001410
1411 // Fill in the PoolDescriptor information for the transformed function so that
1412 // it can determine which value holds the pool descriptor for each data
1413 // structure node that it accesses.
1414 //
Chris Lattner441e16f2002-04-12 20:23:15 +00001415 map<DSNode*, PoolInfo> PoolDescs;
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001416
Chris Lattneracf19022002-04-14 06:14:41 +00001417#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner847b6e22002-03-30 20:53:14 +00001418 cerr << "\nCalculating the pool descriptor map:\n";
Chris Lattneracf19022002-04-14 06:14:41 +00001419#endif
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001420
Chris Lattner441e16f2002-04-12 20:23:15 +00001421 // Calculate as much of the pool descriptor map as possible. Since we have
1422 // the node mapping between the caller and callee functions, and we have the
1423 // pool descriptor information of the caller, we can calculate a partical pool
1424 // descriptor map for the called function.
1425 //
1426 // The nodes that we do not have complete information for are the ones that
1427 // are accessed by loading pointers derived from arguments passed in, but that
1428 // are not passed in directly. In this case, we have all of the information
1429 // except a pool value. If the called function refers to this pool, the pool
1430 // value will be loaded from the pool graph and added to the map as neccesary.
1431 //
1432 for (map<DSNode*, PointerValSet>::iterator I = NodeMapping.begin();
1433 I != NodeMapping.end(); ++I) {
1434 DSNode *CallerNode = I->first;
1435 PoolInfo &CallerPI = CallerPoolDesc[CallerNode];
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001436
Chris Lattner441e16f2002-04-12 20:23:15 +00001437 // Check to see if we have a node pointer passed in for this value...
1438 Value *CalleeValue = 0;
1439 for (unsigned a = 0, ae = TFI.ArgInfo.size(); a != ae; ++a)
1440 if (TFI.ArgInfo[a].Node == CallerNode) {
1441 // Calculate the argument number that the pool is to the function
1442 // call... The call instruction should not have the pool operands added
1443 // yet.
1444 unsigned ArgNo = TFI.Call->getNumOperands()-1+a;
Chris Lattneracf19022002-04-14 06:14:41 +00001445#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001446 cerr << "Should be argument #: " << ArgNo << "[i = " << a << "]\n";
Chris Lattneracf19022002-04-14 06:14:41 +00001447#endif
Chris Lattner441e16f2002-04-12 20:23:15 +00001448 assert(ArgNo < NewFunc->getArgumentList().size() &&
1449 "Call already has pool arguments added??");
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001450
Chris Lattner441e16f2002-04-12 20:23:15 +00001451 // Map the pool argument into the called function...
1452 CalleeValue = NewFunc->getArgumentList()[ArgNo];
1453 break; // Found value, quit loop
1454 }
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001455
Chris Lattner441e16f2002-04-12 20:23:15 +00001456 // Loop over all of the data structure nodes that this incoming node maps to
1457 // Creating a PoolInfo structure for them.
1458 for (unsigned i = 0, e = I->second.size(); i != e; ++i) {
1459 assert(I->second[i].Index == 0 && "Doesn't handle subindexing yet!");
1460 DSNode *CalleeNode = I->second[i].Node;
1461
1462 // Add the descriptor. We already know everything about it by now, much
1463 // of it is the same as the caller info.
1464 //
1465 PoolDescs.insert(make_pair(CalleeNode,
1466 PoolInfo(CalleeNode, CalleeValue,
1467 CallerPI.NewType,
1468 CallerPI.PoolType)));
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001469 }
Chris Lattner847b6e22002-03-30 20:53:14 +00001470 }
1471
1472 // We must destroy the node mapping so that we don't have latent references
1473 // into the data structure graph for the new function. Otherwise we get
1474 // assertion failures when transformFunctionBody tries to invalidate the
1475 // graph.
1476 //
1477 NodeMapping.clear();
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001478
1479 // Now that we know everything we need about the function, transform the body
1480 // now!
1481 //
Chris Lattner441e16f2002-04-12 20:23:15 +00001482 transformFunctionBody(NewFunc, DSGraph, PoolDescs);
1483
Chris Lattneracf19022002-04-14 06:14:41 +00001484#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001485 cerr << "Function after transformation:\n" << NewFunc;
Chris Lattneracf19022002-04-14 06:14:41 +00001486#endif
Chris Lattner66df97d2002-03-29 06:21:38 +00001487}
1488
Chris Lattner8f796d62002-04-13 19:25:57 +00001489static unsigned countPointerTypes(const Type *Ty) {
1490 if (isa<PointerType>(Ty)) {
1491 return 1;
1492 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1493 unsigned Num = 0;
1494 for (unsigned i = 0, e = STy->getElementTypes().size(); i != e; ++i)
1495 Num += countPointerTypes(STy->getElementTypes()[i]);
1496 return Num;
1497 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1498 return countPointerTypes(ATy->getElementType());
1499 } else {
1500 assert(Ty->isPrimitiveType() && "Unknown derived type!");
1501 return 0;
1502 }
1503}
Chris Lattner66df97d2002-03-29 06:21:38 +00001504
1505// CreatePools - Insert instructions into the function we are processing to
1506// create all of the memory pool objects themselves. This also inserts
1507// destruction code. Add an alloca for each pool that is allocated to the
Chris Lattner441e16f2002-04-12 20:23:15 +00001508// PoolDescs vector.
Chris Lattner66df97d2002-03-29 06:21:38 +00001509//
1510void PoolAllocate::CreatePools(Function *F, const vector<AllocDSNode*> &Allocs,
Chris Lattner441e16f2002-04-12 20:23:15 +00001511 map<DSNode*, PoolInfo> &PoolDescs) {
1512 // Find all of the return nodes in the function...
Chris Lattnere0618ca2002-03-29 05:50:20 +00001513 vector<BasicBlock*> ReturnNodes;
1514 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
1515 if (isa<ReturnInst>((*I)->getTerminator()))
1516 ReturnNodes.push_back(*I);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001517
Chris Lattner3e78dea2002-04-18 14:43:30 +00001518#ifdef DEBUG_CREATE_POOLS
1519 cerr << "Allocs that we are pool allocating:\n";
1520 for (unsigned i = 0, e = Allocs.size(); i != e; ++i)
1521 Allocs[i]->dump();
1522#endif
1523
Chris Lattner441e16f2002-04-12 20:23:15 +00001524 map<DSNode*, PATypeHolder> AbsPoolTyMap;
1525
1526 // First pass over the allocations to process...
1527 for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
1528 // Create the pooldescriptor mapping... with null entries for everything
1529 // except the node & NewType fields.
1530 //
1531 map<DSNode*, PoolInfo>::iterator PI =
1532 PoolDescs.insert(make_pair(Allocs[i], PoolInfo(Allocs[i]))).first;
1533
Chris Lattner8f796d62002-04-13 19:25:57 +00001534 // Add a symbol table entry for the new type if there was one for the old
1535 // type...
1536 string OldName = CurModule->getTypeName(Allocs[i]->getType());
Chris Lattner0e0c15b2002-04-27 02:29:32 +00001537 if (OldName.empty()) OldName = "node";
1538 CurModule->addTypeName(OldName+".p", PI->second.NewType);
Chris Lattner8f796d62002-04-13 19:25:57 +00001539
Chris Lattner441e16f2002-04-12 20:23:15 +00001540 // Create the abstract pool types that will need to be resolved in a second
1541 // pass once an abstract type is created for each pool.
1542 //
1543 // Can only handle limited shapes for now...
Chris Lattner0e0c15b2002-04-27 02:29:32 +00001544 const Type *OldNodeTy = Allocs[i]->getType();
Chris Lattner441e16f2002-04-12 20:23:15 +00001545 vector<const Type*> PoolTypes;
1546
1547 // Pool type is the first element of the pool descriptor type...
1548 PoolTypes.push_back(getPoolType(PoolDescs[Allocs[i]].NewType));
Chris Lattner8f796d62002-04-13 19:25:57 +00001549
1550 unsigned NumPointers = countPointerTypes(OldNodeTy);
1551 while (NumPointers--) // Add a different opaque type for each pointer
1552 PoolTypes.push_back(OpaqueType::get());
1553
Chris Lattner441e16f2002-04-12 20:23:15 +00001554 assert(Allocs[i]->getNumLinks() == PoolTypes.size()-1 &&
1555 "Node should have same number of pointers as pool!");
1556
Chris Lattner8f796d62002-04-13 19:25:57 +00001557 StructType *PoolType = StructType::get(PoolTypes);
1558
1559 // Add a symbol table entry for the pooltype if possible...
Chris Lattner0e0c15b2002-04-27 02:29:32 +00001560 CurModule->addTypeName(OldName+".pool", PoolType);
Chris Lattner8f796d62002-04-13 19:25:57 +00001561
Chris Lattner441e16f2002-04-12 20:23:15 +00001562 // Create the pool type, with opaque values for pointers...
Chris Lattner8f796d62002-04-13 19:25:57 +00001563 AbsPoolTyMap.insert(make_pair(Allocs[i], PoolType));
Chris Lattner441e16f2002-04-12 20:23:15 +00001564#ifdef DEBUG_CREATE_POOLS
1565 cerr << "POOL TY: " << AbsPoolTyMap.find(Allocs[i])->second.get() << "\n";
1566#endif
1567 }
1568
1569 // Now that we have types for all of the pool types, link them all together.
1570 for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
1571 PATypeHolder &PoolTyH = AbsPoolTyMap.find(Allocs[i])->second;
1572
1573 // Resolve all of the outgoing pointer types of this pool node...
1574 for (unsigned p = 0, pe = Allocs[i]->getNumLinks(); p != pe; ++p) {
1575 PointerValSet &PVS = Allocs[i]->getLink(p);
1576 assert(!PVS.empty() && "Outgoing edge is empty, field unused, can"
1577 " probably just leave the type opaque or something dumb.");
1578 unsigned Out;
1579 for (Out = 0; AbsPoolTyMap.count(PVS[Out].Node) == 0; ++Out)
1580 assert(Out != PVS.size() && "No edge to an outgoing allocation node!?");
1581
1582 assert(PVS[Out].Index == 0 && "Subindexing not implemented yet!");
1583
1584 // The actual struct type could change each time through the loop, so it's
1585 // NOT loop invariant.
1586 StructType *PoolTy = cast<StructType>(PoolTyH.get());
1587
1588 // Get the opaque type...
1589 DerivedType *ElTy =
1590 cast<DerivedType>(PoolTy->getElementTypes()[p+1].get());
1591
1592#ifdef DEBUG_CREATE_POOLS
1593 cerr << "Refining " << ElTy << " of " << PoolTy << " to "
1594 << AbsPoolTyMap.find(PVS[Out].Node)->second.get() << "\n";
1595#endif
1596
1597 const Type *RefPoolTy = AbsPoolTyMap.find(PVS[Out].Node)->second.get();
1598 ElTy->refineAbstractTypeTo(PointerType::get(RefPoolTy));
1599
1600#ifdef DEBUG_CREATE_POOLS
1601 cerr << "Result pool type is: " << PoolTyH.get() << "\n";
1602#endif
1603 }
1604 }
1605
1606 // Create the code that goes in the entry and exit nodes for the function...
Chris Lattnere0618ca2002-03-29 05:50:20 +00001607 vector<Instruction*> EntryNodeInsts;
1608 for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
Chris Lattner441e16f2002-04-12 20:23:15 +00001609 PoolInfo &PI = PoolDescs[Allocs[i]];
1610
1611 // Fill in the pool type for this pool...
1612 PI.PoolType = AbsPoolTyMap.find(Allocs[i])->second.get();
1613 assert(!PI.PoolType->isAbstract() &&
1614 "Pool type should not be abstract anymore!");
1615
Chris Lattnere0618ca2002-03-29 05:50:20 +00001616 // Add an allocation and a free for each pool...
Chris Lattner5da145b2002-04-13 19:52:54 +00001617 AllocaInst *PoolAlloc
1618 = new AllocaInst(PointerType::get(PI.PoolType), 0,
1619 CurModule->getTypeName(PI.PoolType));
Chris Lattner441e16f2002-04-12 20:23:15 +00001620 PI.Handle = PoolAlloc;
Chris Lattnere0618ca2002-03-29 05:50:20 +00001621 EntryNodeInsts.push_back(PoolAlloc);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001622 AllocationInst *AI = Allocs[i]->getAllocation();
1623
1624 // Initialize the pool. We need to know how big each allocation is. For
1625 // our purposes here, we assume we are allocating a scalar, or array of
1626 // constant size.
1627 //
Chris Lattneracf19022002-04-14 06:14:41 +00001628 unsigned ElSize = TargetData.getTypeSize(PI.NewType);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001629
1630 vector<Value*> Args;
Chris Lattnere0618ca2002-03-29 05:50:20 +00001631 Args.push_back(ConstantUInt::get(Type::UIntTy, ElSize));
Chris Lattner441e16f2002-04-12 20:23:15 +00001632 Args.push_back(PoolAlloc); // Pool to initialize
Chris Lattnere0618ca2002-03-29 05:50:20 +00001633 EntryNodeInsts.push_back(new CallInst(PoolInit, Args));
1634
Chris Lattner441e16f2002-04-12 20:23:15 +00001635 // Add code to destroy the pool in all of the exit nodes of the function...
Chris Lattner8f796d62002-04-13 19:25:57 +00001636 Args.clear();
1637 Args.push_back(PoolAlloc); // Pool to initialize
1638
Chris Lattnere0618ca2002-03-29 05:50:20 +00001639 for (unsigned EN = 0, ENE = ReturnNodes.size(); EN != ENE; ++EN) {
1640 Instruction *Destroy = new CallInst(PoolDestroy, Args);
1641
1642 // Insert it before the return instruction...
1643 BasicBlock *RetNode = ReturnNodes[EN];
1644 RetNode->getInstList().insert(RetNode->end()-1, Destroy);
1645 }
1646 }
1647
Chris Lattner5da145b2002-04-13 19:52:54 +00001648 // Now that all of the pool descriptors have been created, link them together
1649 // so that called functions can get links as neccesary...
1650 //
1651 for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
1652 PoolInfo &PI = PoolDescs[Allocs[i]];
1653
1654 // For every pointer in the data structure, initialize a link that
1655 // indicates which pool to access...
1656 //
1657 vector<Value*> Indices(2);
1658 Indices[0] = ConstantUInt::get(Type::UIntTy, 0);
1659 for (unsigned l = 0, le = PI.Node->getNumLinks(); l != le; ++l)
1660 // Only store an entry for the field if the field is used!
1661 if (!PI.Node->getLink(l).empty()) {
1662 assert(PI.Node->getLink(l).size() == 1 && "Should have only one link!");
1663 PointerVal PV = PI.Node->getLink(l)[0];
1664 assert(PV.Index == 0 && "Subindexing not supported yet!");
1665 PoolInfo &LinkedPool = PoolDescs[PV.Node];
1666 Indices[1] = ConstantUInt::get(Type::UByteTy, 1+l);
1667
1668 EntryNodeInsts.push_back(new StoreInst(LinkedPool.Handle, PI.Handle,
1669 Indices));
1670 }
1671 }
1672
Chris Lattnere0618ca2002-03-29 05:50:20 +00001673 // Insert the entry node code into the entry block...
1674 F->getEntryNode()->getInstList().insert(F->getEntryNode()->begin()+1,
1675 EntryNodeInsts.begin(),
1676 EntryNodeInsts.end());
Chris Lattner175f37c2002-03-29 03:40:59 +00001677}
1678
1679
Chris Lattner441e16f2002-04-12 20:23:15 +00001680// addPoolPrototypes - Add prototypes for the pool functions to the specified
Chris Lattner175f37c2002-03-29 03:40:59 +00001681// module and update the Pool* instance variables to point to them.
1682//
1683void PoolAllocate::addPoolPrototypes(Module *M) {
Chris Lattner441e16f2002-04-12 20:23:15 +00001684 // Get poolinit function...
Chris Lattnere0618ca2002-03-29 05:50:20 +00001685 vector<const Type*> Args;
Chris Lattnere0618ca2002-03-29 05:50:20 +00001686 Args.push_back(Type::UIntTy); // Num bytes per element
Chris Lattner441e16f2002-04-12 20:23:15 +00001687 FunctionType *PoolInitTy = FunctionType::get(Type::VoidTy, Args, true);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001688 PoolInit = M->getOrInsertFunction("poolinit", PoolInitTy);
Chris Lattner175f37c2002-03-29 03:40:59 +00001689
Chris Lattnere0618ca2002-03-29 05:50:20 +00001690 // Get pooldestroy function...
1691 Args.pop_back(); // Only takes a pool...
Chris Lattner441e16f2002-04-12 20:23:15 +00001692 FunctionType *PoolDestroyTy = FunctionType::get(Type::VoidTy, Args, true);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001693 PoolDestroy = M->getOrInsertFunction("pooldestroy", PoolDestroyTy);
1694
Chris Lattnere0618ca2002-03-29 05:50:20 +00001695 // Get the poolalloc function...
Chris Lattner441e16f2002-04-12 20:23:15 +00001696 FunctionType *PoolAllocTy = FunctionType::get(POINTERTYPE, Args, true);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001697 PoolAlloc = M->getOrInsertFunction("poolalloc", PoolAllocTy);
1698
1699 // Get the poolfree function...
Chris Lattner441e16f2002-04-12 20:23:15 +00001700 Args.push_back(POINTERTYPE); // Pointer to free
1701 FunctionType *PoolFreeTy = FunctionType::get(Type::VoidTy, Args, true);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001702 PoolFree = M->getOrInsertFunction("poolfree", PoolFreeTy);
1703
Chris Lattner0e0c15b2002-04-27 02:29:32 +00001704 Args[0] = Type::UIntTy; // Number of slots to allocate
1705 FunctionType *PoolAllocArrayTy = FunctionType::get(POINTERTYPE, Args, true);
1706 PoolAllocArray = M->getOrInsertFunction("poolallocarray", PoolAllocArrayTy);
Chris Lattner175f37c2002-03-29 03:40:59 +00001707}
1708
1709
1710bool PoolAllocate::run(Module *M) {
1711 addPoolPrototypes(M);
1712 CurModule = M;
1713
1714 DS = &getAnalysis<DataStructure>();
1715 bool Changed = false;
Chris Lattner291a1b12002-03-29 19:05:48 +00001716
1717 // We cannot use an iterator here because it will get invalidated when we add
1718 // functions to the module later...
1719 for (unsigned i = 0; i != M->size(); ++i)
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001720 if (!M->getFunctionList()[i]->isExternal()) {
Chris Lattner291a1b12002-03-29 19:05:48 +00001721 Changed |= processFunction(M->getFunctionList()[i]);
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001722 if (Changed) {
1723 cerr << "Only processing one function\n";
1724 break;
1725 }
1726 }
Chris Lattner175f37c2002-03-29 03:40:59 +00001727
1728 CurModule = 0;
1729 DS = 0;
1730 return false;
1731}
1732
1733
1734// createPoolAllocatePass - Global function to access the functionality of this
1735// pass...
1736//
Chris Lattner64fd9352002-03-28 18:08:31 +00001737Pass *createPoolAllocatePass() { return new PoolAllocate(); }