blob: 0fec909a908e476756745e8612238edf1a79c056 [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
Chris Lattner99a53f62002-07-24 17:12:05 +00009#include "llvm/Transforms/IPO.h"
Chris Lattner7608a462002-05-07 18:36:35 +000010#include "llvm/Transforms/Utils/CloneFunction.h"
Chris Lattner1a535e12002-10-10 20:33:46 +000011#include "llvm/Analysis/DataStructure.h"
Chris Lattner175f37c2002-03-29 03:40:59 +000012#include "llvm/Module.h"
Chris Lattner175f37c2002-03-29 03:40:59 +000013#include "llvm/iMemory.h"
Chris Lattnere0618ca2002-03-29 05:50:20 +000014#include "llvm/iTerminators.h"
Chris Lattner441e16f2002-04-12 20:23:15 +000015#include "llvm/iPHINode.h"
Chris Lattnere0618ca2002-03-29 05:50:20 +000016#include "llvm/iOther.h"
Chris Lattner441e16f2002-04-12 20:23:15 +000017#include "llvm/DerivedTypes.h"
Chris Lattnerca142372002-04-28 19:55:58 +000018#include "llvm/Constants.h"
Chris Lattnere0618ca2002-03-29 05:50:20 +000019#include "llvm/Target/TargetData.h"
Chris Lattnerf32d65d2002-03-29 21:25:19 +000020#include "llvm/Support/InstVisitor.h"
Chris Lattner396d5d72002-03-30 04:02:31 +000021#include "Support/DepthFirstIterator.h"
Chris Lattnere0618ca2002-03-29 05:50:20 +000022#include "Support/STLExtras.h"
Chris Lattner175f37c2002-03-29 03:40:59 +000023#include <algorithm>
Anand Shukla2bc64192002-06-25 21:07:58 +000024using std::vector;
25using std::cerr;
26using std::map;
27using std::string;
28using std::set;
Chris Lattner64fd9352002-03-28 18:08:31 +000029
Chris Lattner87d180e2002-07-10 22:36:47 +000030#if 0
31
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
Chris Lattnerf5cad152002-07-22 02:10:13 +000052static cl::opt<PtrSize>
53ReqPointerSize("poolalloc-ptr-size",
54 cl::desc("Set pointer size for -poolalloc pass"),
55 cl::values(
Chris Lattner50e3d322002-04-13 23:13:18 +000056 clEnumValN(Ptr32bits, "32", "Use 32 bit indices for pointers"),
57 clEnumValN(Ptr16bits, "16", "Use 16 bit indices for pointers"),
Chris Lattnerf5cad152002-07-22 02:10:13 +000058 clEnumValN(Ptr8bits , "8", "Use 8 bit indices for pointers"),
59 0));
Chris Lattner50e3d322002-04-13 23:13:18 +000060
Chris Lattnerf5cad152002-07-22 02:10:13 +000061static cl::opt<bool>
62DisableRLE("no-pool-load-elim", cl::Hidden,
63 cl::desc("Disable pool load elimination after poolalloc pass"));
Chris Lattner457e1ac2002-04-15 22:42:23 +000064
Chris Lattner441e16f2002-04-12 20:23:15 +000065const Type *POINTERTYPE;
Chris Lattner692ad5d2002-03-29 17:13:46 +000066
Chris Lattnere0618ca2002-03-29 05:50:20 +000067// FIXME: This is dependant on the sparc backend layout conventions!!
68static TargetData TargetData("test");
69
Chris Lattner50e3d322002-04-13 23:13:18 +000070static const Type *getPointerTransformedType(const Type *Ty) {
Chris Lattner7076ff22002-06-25 16:13:21 +000071 if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
Chris Lattner50e3d322002-04-13 23:13:18 +000072 return POINTERTYPE;
Chris Lattner7076ff22002-06-25 16:13:21 +000073 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
Chris Lattner50e3d322002-04-13 23:13:18 +000074 vector<const Type *> NewElTypes;
75 NewElTypes.reserve(STy->getElementTypes().size());
76 for (StructType::ElementTypes::const_iterator
77 I = STy->getElementTypes().begin(),
78 E = STy->getElementTypes().end(); I != E; ++I)
79 NewElTypes.push_back(getPointerTransformedType(*I));
80 return StructType::get(NewElTypes);
Chris Lattner7076ff22002-06-25 16:13:21 +000081 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
Chris Lattner50e3d322002-04-13 23:13:18 +000082 return ArrayType::get(getPointerTransformedType(ATy->getElementType()),
83 ATy->getNumElements());
84 } else {
85 assert(Ty->isPrimitiveType() && "Unknown derived type!");
86 return Ty;
87 }
88}
89
Chris Lattner64fd9352002-03-28 18:08:31 +000090namespace {
Chris Lattner441e16f2002-04-12 20:23:15 +000091 struct PoolInfo {
92 DSNode *Node; // The node this pool allocation represents
93 Value *Handle; // LLVM value of the pool in the current context
94 const Type *NewType; // The transformed type of the memory objects
95 const Type *PoolType; // The type of the pool
96
97 const Type *getOldType() const { return Node->getType(); }
98
99 PoolInfo() { // Define a default ctor for map::operator[]
100 cerr << "Map subscript used to get element that doesn't exist!\n";
101 abort(); // Invalid
102 }
103
104 PoolInfo(DSNode *N, Value *H, const Type *NT, const Type *PT)
105 : Node(N), Handle(H), NewType(NT), PoolType(PT) {
106 // Handle can be null...
107 assert(N && NT && PT && "Pool info null!");
108 }
109
110 PoolInfo(DSNode *N) : Node(N), Handle(0), NewType(0), PoolType(0) {
111 assert(N && "Invalid pool info!");
112
113 // The new type of the memory object is the same as the old type, except
114 // that all of the pointer values are replaced with POINTERTYPE values.
Chris Lattner50e3d322002-04-13 23:13:18 +0000115 NewType = getPointerTransformedType(getOldType());
Chris Lattner441e16f2002-04-12 20:23:15 +0000116 }
117 };
118
Chris Lattner692ad5d2002-03-29 17:13:46 +0000119 // ScalarInfo - Information about an LLVM value that we know points to some
120 // datastructure we are processing.
121 //
122 struct ScalarInfo {
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000123 Value *Val; // Scalar value in Current Function
Chris Lattner441e16f2002-04-12 20:23:15 +0000124 PoolInfo Pool; // The pool the scalar points into
Chris Lattner692ad5d2002-03-29 17:13:46 +0000125
Chris Lattner441e16f2002-04-12 20:23:15 +0000126 ScalarInfo(Value *V, const PoolInfo &PI) : Val(V), Pool(PI) {
127 assert(V && "Null value passed to ScalarInfo ctor!");
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000128 }
Chris Lattner692ad5d2002-03-29 17:13:46 +0000129 };
130
Chris Lattner396d5d72002-03-30 04:02:31 +0000131 // CallArgInfo - Information on one operand for a call that got expanded.
132 struct CallArgInfo {
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000133 int ArgNo; // Call argument number this corresponds to
134 DSNode *Node; // The graph node for the pool
135 Value *PoolHandle; // The LLVM value that is the pool pointer
Chris Lattner396d5d72002-03-30 04:02:31 +0000136
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000137 CallArgInfo(int Arg, DSNode *N, Value *PH)
138 : ArgNo(Arg), Node(N), PoolHandle(PH) {
139 assert(Arg >= -1 && N && PH && "Illegal values to CallArgInfo ctor!");
Chris Lattner396d5d72002-03-30 04:02:31 +0000140 }
141
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000142 // operator< when sorting, sort by argument number.
Chris Lattner396d5d72002-03-30 04:02:31 +0000143 bool operator<(const CallArgInfo &CAI) const {
144 return ArgNo < CAI.ArgNo;
145 }
146 };
147
Chris Lattner692ad5d2002-03-29 17:13:46 +0000148 // TransformFunctionInfo - Information about how a function eeds to be
149 // transformed.
150 //
151 struct TransformFunctionInfo {
152 // ArgInfo - Maintain information about the arguments that need to be
Chris Lattner441e16f2002-04-12 20:23:15 +0000153 // processed. Each CallArgInfo corresponds to an argument that needs to
154 // have a pool pointer passed into the transformed function with it.
Chris Lattner692ad5d2002-03-29 17:13:46 +0000155 //
156 // As a special case, "argument" number -1 corresponds to the return value.
157 //
Chris Lattner396d5d72002-03-30 04:02:31 +0000158 vector<CallArgInfo> ArgInfo;
Chris Lattner692ad5d2002-03-29 17:13:46 +0000159
160 // Func - The function to be transformed...
161 Function *Func;
162
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000163 // The call instruction that is used to map CallArgInfo PoolHandle values
164 // into the new function values.
165 CallInst *Call;
166
Chris Lattner692ad5d2002-03-29 17:13:46 +0000167 // default ctor...
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000168 TransformFunctionInfo() : Func(0), Call(0) {}
Chris Lattner692ad5d2002-03-29 17:13:46 +0000169
Chris Lattner396d5d72002-03-30 04:02:31 +0000170 bool operator<(const TransformFunctionInfo &TFI) const {
Chris Lattner291a1b12002-03-29 19:05:48 +0000171 if (Func < TFI.Func) return true;
172 if (Func > TFI.Func) return false;
Chris Lattner291a1b12002-03-29 19:05:48 +0000173 if (ArgInfo.size() < TFI.ArgInfo.size()) return true;
174 if (ArgInfo.size() > TFI.ArgInfo.size()) return false;
Chris Lattner396d5d72002-03-30 04:02:31 +0000175 return ArgInfo < TFI.ArgInfo;
Chris Lattner692ad5d2002-03-29 17:13:46 +0000176 }
177
178 void finalizeConstruction() {
179 // Sort the vector so that the return value is first, followed by the
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000180 // argument records, in order. Note that this must be a stable sort so
181 // that the entries with the same sorting criteria (ie they are multiple
182 // pool entries for the same argument) are kept in depth first order.
Anand Shukla2bc64192002-06-25 21:07:58 +0000183 std::stable_sort(ArgInfo.begin(), ArgInfo.end());
Chris Lattner692ad5d2002-03-29 17:13:46 +0000184 }
Chris Lattner3e78dea2002-04-18 14:43:30 +0000185
186 // addCallInfo - For a specified function call CI, figure out which pool
187 // descriptors need to be passed in as arguments, and which arguments need
188 // to be transformed into indices. If Arg != -1, the specified call
189 // argument is passed in as a pointer to a data structure.
190 //
191 void addCallInfo(DataStructure *DS, CallInst *CI, int Arg,
192 DSNode *GraphNode, map<DSNode*, PoolInfo> &PoolDescs);
193
194 // Make sure that all dependant arguments are added to this transformation
195 // info. For example, if we call foo(null, P) and foo treats it's first and
196 // second arguments as belonging to the same data structure, the we MUST add
197 // entries to know that the null needs to be transformed into an index as
198 // well.
199 //
200 void ensureDependantArgumentsIncluded(DataStructure *DS,
201 map<DSNode*, PoolInfo> &PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000202 };
203
204
205 // Define the pass class that we implement...
Chris Lattner441e16f2002-04-12 20:23:15 +0000206 struct PoolAllocate : public Pass {
Chris Lattner175f37c2002-03-29 03:40:59 +0000207 PoolAllocate() {
Chris Lattner50e3d322002-04-13 23:13:18 +0000208 switch (ReqPointerSize) {
209 case Ptr32bits: POINTERTYPE = Type::UIntTy; break;
210 case Ptr16bits: POINTERTYPE = Type::UShortTy; break;
211 case Ptr8bits: POINTERTYPE = Type::UByteTy; break;
212 }
Chris Lattner175f37c2002-03-29 03:40:59 +0000213
214 CurModule = 0; DS = 0;
215 PoolInit = PoolDestroy = PoolAlloc = PoolFree = 0;
Chris Lattner64fd9352002-03-28 18:08:31 +0000216 }
217
Chris Lattner441e16f2002-04-12 20:23:15 +0000218 // getPoolType - Get the type used by the backend for a pool of a particular
219 // type. This pool record is used to allocate nodes of type NodeType.
220 //
221 // Here, PoolTy = { NodeType*, sbyte*, uint }*
222 //
223 const StructType *getPoolType(const Type *NodeType) {
224 vector<const Type*> PoolElements;
225 PoolElements.push_back(PointerType::get(NodeType));
226 PoolElements.push_back(PointerType::get(Type::SByteTy));
227 PoolElements.push_back(Type::UIntTy);
Chris Lattner8f796d62002-04-13 19:25:57 +0000228 StructType *Result = StructType::get(PoolElements);
229
230 // Add a name to the symbol table to correspond to the backend
231 // representation of this pool...
232 assert(CurModule && "No current module!?");
233 string Name = CurModule->getTypeName(NodeType);
234 if (Name.empty()) Name = CurModule->getTypeName(PoolElements[0]);
235 CurModule->addTypeName(Name+"oolbe", Result);
236
237 return Result;
Chris Lattner441e16f2002-04-12 20:23:15 +0000238 }
239
Chris Lattner7076ff22002-06-25 16:13:21 +0000240 bool run(Module &M);
Chris Lattner175f37c2002-03-29 03:40:59 +0000241
Chris Lattnerc8e66542002-04-27 06:56:12 +0000242 // getAnalysisUsage - This function requires data structure information
Chris Lattner175f37c2002-03-29 03:40:59 +0000243 // to be able to see what is pool allocatable.
Chris Lattner64fd9352002-03-28 18:08:31 +0000244 //
Chris Lattnerc8e66542002-04-27 06:56:12 +0000245 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf0ed55d2002-08-08 19:01:30 +0000246 AU.addRequired<DataStructure>();
Chris Lattner64fd9352002-03-28 18:08:31 +0000247 }
Chris Lattner175f37c2002-03-29 03:40:59 +0000248
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000249 public:
Chris Lattner175f37c2002-03-29 03:40:59 +0000250 // CurModule - The module being processed.
251 Module *CurModule;
252
253 // DS - The data structure graph for the module being processed.
254 DataStructure *DS;
255
256 // Prototypes that we add to support pool allocation...
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000257 Function *PoolInit, *PoolDestroy, *PoolAlloc, *PoolAllocArray, *PoolFree;
Chris Lattner175f37c2002-03-29 03:40:59 +0000258
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000259 // The map of already transformed functions... note that the keys of this
260 // map do not have meaningful values for 'Call' or the 'PoolHandle' elements
261 // of the ArgInfo elements.
262 //
Chris Lattner692ad5d2002-03-29 17:13:46 +0000263 map<TransformFunctionInfo, Function*> TransformedFunctions;
264
265 // getTransformedFunction - Get a transformed function, or return null if
266 // the function specified hasn't been transformed yet.
267 //
268 Function *getTransformedFunction(TransformFunctionInfo &TFI) const {
269 map<TransformFunctionInfo, Function*>::const_iterator I =
270 TransformedFunctions.find(TFI);
271 if (I != TransformedFunctions.end()) return I->second;
272 return 0;
273 }
274
275
Chris Lattner441e16f2002-04-12 20:23:15 +0000276 // addPoolPrototypes - Add prototypes for the pool functions to the
277 // specified module and update the Pool* instance variables to point to
278 // them.
Chris Lattner175f37c2002-03-29 03:40:59 +0000279 //
Chris Lattner7076ff22002-06-25 16:13:21 +0000280 void addPoolPrototypes(Module &M);
Chris Lattner175f37c2002-03-29 03:40:59 +0000281
Chris Lattner66df97d2002-03-29 06:21:38 +0000282
283 // CreatePools - Insert instructions into the function we are processing to
284 // create all of the memory pool objects themselves. This also inserts
285 // destruction code. Add an alloca for each pool that is allocated to the
Chris Lattner441e16f2002-04-12 20:23:15 +0000286 // PoolDescs map.
Chris Lattner66df97d2002-03-29 06:21:38 +0000287 //
288 void CreatePools(Function *F, const vector<AllocDSNode*> &Allocs,
Chris Lattner441e16f2002-04-12 20:23:15 +0000289 map<DSNode*, PoolInfo> &PoolDescs);
Chris Lattner66df97d2002-03-29 06:21:38 +0000290
Chris Lattner175f37c2002-03-29 03:40:59 +0000291 // processFunction - Convert a function to use pool allocation where
292 // available.
293 //
294 bool processFunction(Function *F);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000295
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000296 // transformFunctionBody - This transforms the instruction in 'F' to use the
Chris Lattner441e16f2002-04-12 20:23:15 +0000297 // pools specified in PoolDescs when modifying data structure nodes
298 // specified in the PoolDescs map. IPFGraph is the closed data structure
299 // graph for F, of which the PoolDescriptor nodes come from.
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000300 //
301 void transformFunctionBody(Function *F, FunctionDSGraph &IPFGraph,
Chris Lattner441e16f2002-04-12 20:23:15 +0000302 map<DSNode*, PoolInfo> &PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000303
304 // transformFunction - Transform the specified function the specified way.
305 // It we have already transformed that function that way, don't do anything.
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000306 // The nodes in the TransformFunctionInfo come out of callers data structure
Chris Lattner441e16f2002-04-12 20:23:15 +0000307 // graph, and the PoolDescs passed in are the caller's.
Chris Lattner692ad5d2002-03-29 17:13:46 +0000308 //
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000309 void transformFunction(TransformFunctionInfo &TFI,
Chris Lattner441e16f2002-04-12 20:23:15 +0000310 FunctionDSGraph &CallerIPGraph,
311 map<DSNode*, PoolInfo> &PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000312
Chris Lattner64fd9352002-03-28 18:08:31 +0000313 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000314
Chris Lattnera2c09852002-07-26 21:12:44 +0000315 RegisterOpt<PoolAllocate> X("poolalloc",
316 "Pool allocate disjoint datastructures");
Chris Lattner64fd9352002-03-28 18:08:31 +0000317}
318
Chris Lattner692ad5d2002-03-29 17:13:46 +0000319// isNotPoolableAlloc - This is a predicate that returns true if the specified
Chris Lattner175f37c2002-03-29 03:40:59 +0000320// allocation node in a data structure graph is eligable for pool allocation.
321//
322static bool isNotPoolableAlloc(const AllocDSNode *DS) {
Chris Lattnere0618ca2002-03-29 05:50:20 +0000323 if (DS->isAllocaNode()) return true; // Do not pool allocate alloca's.
Chris Lattnere0618ca2002-03-29 05:50:20 +0000324 return false;
Chris Lattner175f37c2002-03-29 03:40:59 +0000325}
326
Chris Lattner175f37c2002-03-29 03:40:59 +0000327// processFunction - Convert a function to use pool allocation where
328// available.
329//
330bool PoolAllocate::processFunction(Function *F) {
331 // Get the closed datastructure graph for the current function... if there are
332 // any allocations in this graph that are not escaping, we need to pool
333 // allocate them here!
334 //
335 FunctionDSGraph &IPGraph = DS->getClosedDSGraph(F);
336
337 // Get all of the allocations that do not escape the current function. Since
338 // they are still live (they exist in the graph at all), this means we must
339 // have scalar references to these nodes, but the scalars are never returned.
340 //
Chris Lattner692ad5d2002-03-29 17:13:46 +0000341 vector<AllocDSNode*> Allocs;
Chris Lattner175f37c2002-03-29 03:40:59 +0000342 IPGraph.getNonEscapingAllocations(Allocs);
343
344 // Filter out allocations that we cannot handle. Currently, this includes
345 // variable sized array allocations and alloca's (which we do not want to
346 // pool allocate)
347 //
Anand Shukla2bc64192002-06-25 21:07:58 +0000348 Allocs.erase(std::remove_if(Allocs.begin(), Allocs.end(), isNotPoolableAlloc),
Chris Lattner175f37c2002-03-29 03:40:59 +0000349 Allocs.end());
350
351
352 if (Allocs.empty()) return false; // Nothing to do.
353
Chris Lattner3e78dea2002-04-18 14:43:30 +0000354#ifdef DEBUG_TRANSFORM_PROGRESS
355 cerr << "Transforming Function: " << F->getName() << "\n";
356#endif
357
Chris Lattner692ad5d2002-03-29 17:13:46 +0000358 // Insert instructions into the function we are processing to create all of
359 // the memory pool objects themselves. This also inserts destruction code.
Chris Lattner441e16f2002-04-12 20:23:15 +0000360 // This fills in the PoolDescs map to associate the alloc node with the
Chris Lattner396d5d72002-03-30 04:02:31 +0000361 // allocation of the memory pool corresponding to it.
Chris Lattner692ad5d2002-03-29 17:13:46 +0000362 //
Chris Lattner441e16f2002-04-12 20:23:15 +0000363 map<DSNode*, PoolInfo> PoolDescs;
364 CreatePools(F, Allocs, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000365
Chris Lattneracf19022002-04-14 06:14:41 +0000366#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +0000367 cerr << "Transformed Entry Function: \n" << F;
Chris Lattneracf19022002-04-14 06:14:41 +0000368#endif
Chris Lattner441e16f2002-04-12 20:23:15 +0000369
370 // Now we need to figure out what called functions we need to transform, and
Chris Lattner692ad5d2002-03-29 17:13:46 +0000371 // how. To do this, we look at all of the scalars, seeing which functions are
372 // either used as a scalar value (so they return a data structure), or are
373 // passed one of our scalar values.
374 //
Chris Lattner441e16f2002-04-12 20:23:15 +0000375 transformFunctionBody(F, IPGraph, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000376
377 return true;
378}
379
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000380
Chris Lattner441e16f2002-04-12 20:23:15 +0000381//===----------------------------------------------------------------------===//
382//
383// NewInstructionCreator - This class is used to traverse the function being
384// modified, changing each instruction visit'ed to use and provide pointer
385// indexes instead of real pointers. This is what changes the body of a
386// function to use pool allocation.
387//
388class NewInstructionCreator : public InstVisitor<NewInstructionCreator> {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000389 PoolAllocate &PoolAllocator;
390 vector<ScalarInfo> &Scalars;
391 map<CallInst*, TransformFunctionInfo> &CallMap;
Chris Lattner441e16f2002-04-12 20:23:15 +0000392 map<Value*, Value*> &XFormMap; // Map old pointers to new indexes
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000393
Chris Lattner441e16f2002-04-12 20:23:15 +0000394 struct RefToUpdate {
395 Instruction *I; // Instruction to update
396 unsigned OpNum; // Operand number to update
397 Value *OldVal; // The old value it had
398
399 RefToUpdate(Instruction *i, unsigned o, Value *ov)
400 : I(i), OpNum(o), OldVal(ov) {}
401 };
402 vector<RefToUpdate> ReferencesToUpdate;
403
404 const ScalarInfo &getScalarRef(const Value *V) {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000405 for (unsigned i = 0, e = Scalars.size(); i != e; ++i)
406 if (Scalars[i].Val == V) return Scalars[i];
Chris Lattner3e78dea2002-04-18 14:43:30 +0000407
408 cerr << "Could not find scalar " << V << " in scalar map!\n";
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000409 assert(0 && "Scalar not found in getScalar!");
410 abort();
411 return Scalars[0];
412 }
Chris Lattner441e16f2002-04-12 20:23:15 +0000413
414 const ScalarInfo *getScalar(const Value *V) {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000415 for (unsigned i = 0, e = Scalars.size(); i != e; ++i)
Chris Lattner441e16f2002-04-12 20:23:15 +0000416 if (Scalars[i].Val == V) return &Scalars[i];
417 return 0;
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000418 }
419
Chris Lattner7076ff22002-06-25 16:13:21 +0000420 BasicBlock::iterator ReplaceInstWith(Instruction &I, Instruction *New) {
421 BasicBlock *BB = I.getParent();
422 BasicBlock::iterator RI = &I;
423 BB->getInstList().remove(RI);
424 BB->getInstList().insert(RI, New);
425 XFormMap[&I] = New;
426 return New;
Chris Lattner441e16f2002-04-12 20:23:15 +0000427 }
428
Chris Lattner39db8712002-05-02 17:38:14 +0000429 Instruction *createPoolBaseInstruction(Value *PtrVal) {
Chris Lattner441e16f2002-04-12 20:23:15 +0000430 const ScalarInfo &SC = getScalarRef(PtrVal);
431 vector<Value*> Args(3);
432 Args[0] = ConstantUInt::get(Type::UIntTy, 0); // No pointer offset
433 Args[1] = ConstantUInt::get(Type::UByteTy, 0); // Field #0 of pool descriptr
434 Args[2] = ConstantUInt::get(Type::UByteTy, 0); // Field #0 of poolalloc val
Chris Lattner39db8712002-05-02 17:38:14 +0000435 return new LoadInst(SC.Pool.Handle, Args, PtrVal->getName()+".poolbase");
Chris Lattner441e16f2002-04-12 20:23:15 +0000436 }
437
438
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000439public:
Chris Lattner441e16f2002-04-12 20:23:15 +0000440 NewInstructionCreator(PoolAllocate &PA, vector<ScalarInfo> &S,
441 map<CallInst*, TransformFunctionInfo> &C,
442 map<Value*, Value*> &X)
443 : PoolAllocator(PA), Scalars(S), CallMap(C), XFormMap(X) {}
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000444
Chris Lattner441e16f2002-04-12 20:23:15 +0000445
446 // updateReferences - The NewInstructionCreator is responsible for creating
447 // new instructions to replace the old ones in the function, and then link up
448 // references to values to their new values. For it to do this, however, it
449 // keeps track of information about the value mapping of old values to new
450 // values that need to be patched up. Given this value map and a set of
451 // instruction operands to patch, updateReferences performs the updates.
452 //
453 void updateReferences() {
454 for (unsigned i = 0, e = ReferencesToUpdate.size(); i != e; ++i) {
455 RefToUpdate &Ref = ReferencesToUpdate[i];
456 Value *NewVal = XFormMap[Ref.OldVal];
457
458 if (NewVal == 0) {
459 if (isa<Constant>(Ref.OldVal) && // Refering to a null ptr?
460 cast<Constant>(Ref.OldVal)->isNullValue()) {
461 // Transform the null pointer into a null index... caching in XFormMap
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000462 XFormMap[Ref.OldVal] = NewVal = Constant::getNullValue(POINTERTYPE);
Chris Lattner441e16f2002-04-12 20:23:15 +0000463 //} else if (isa<Argument>(Ref.OldVal)) {
464 } else {
465 cerr << "Unknown reference to: " << Ref.OldVal << "\n";
466 assert(XFormMap[Ref.OldVal] &&
467 "Reference to value that was not updated found!");
468 }
469 }
470
471 Ref.I->setOperand(Ref.OpNum, NewVal);
472 }
473 ReferencesToUpdate.clear();
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000474 }
475
Chris Lattner441e16f2002-04-12 20:23:15 +0000476 //===--------------------------------------------------------------------===//
477 // Transformation methods:
478 // These methods specify how each type of instruction is transformed by the
479 // NewInstructionCreator instance...
480 //===--------------------------------------------------------------------===//
481
Chris Lattner7076ff22002-06-25 16:13:21 +0000482 void visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattner441e16f2002-04-12 20:23:15 +0000483 assert(0 && "Cannot transform get element ptr instructions yet!");
484 }
485
486 // Replace the load instruction with a new one.
Chris Lattner7076ff22002-06-25 16:13:21 +0000487 void visitLoadInst(LoadInst &I) {
Chris Lattner39db8712002-05-02 17:38:14 +0000488 vector<Instruction *> BeforeInsts;
Chris Lattner441e16f2002-04-12 20:23:15 +0000489
490 // Cast our index to be a UIntTy so we can use it to index into the pool...
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000491 CastInst *Index = new CastInst(Constant::getNullValue(POINTERTYPE),
Chris Lattner7076ff22002-06-25 16:13:21 +0000492 Type::UIntTy, I.getOperand(0)->getName());
Chris Lattner39db8712002-05-02 17:38:14 +0000493 BeforeInsts.push_back(Index);
Chris Lattner7076ff22002-06-25 16:13:21 +0000494 ReferencesToUpdate.push_back(RefToUpdate(Index, 0, I.getOperand(0)));
Chris Lattner39db8712002-05-02 17:38:14 +0000495
496 // Include the pool base instruction...
Chris Lattner7076ff22002-06-25 16:13:21 +0000497 Instruction *PoolBase = createPoolBaseInstruction(I.getOperand(0));
Chris Lattner39db8712002-05-02 17:38:14 +0000498 BeforeInsts.push_back(PoolBase);
499
500 Instruction *IdxInst =
Chris Lattner7076ff22002-06-25 16:13:21 +0000501 BinaryOperator::create(Instruction::Add, *I.idx_begin(), Index,
502 I.getName()+".idx");
Chris Lattner39db8712002-05-02 17:38:14 +0000503 BeforeInsts.push_back(IdxInst);
Chris Lattner441e16f2002-04-12 20:23:15 +0000504
Chris Lattner7076ff22002-06-25 16:13:21 +0000505 vector<Value*> Indices(I.idx_begin(), I.idx_end());
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000506 Indices[0] = IdxInst;
Chris Lattner39db8712002-05-02 17:38:14 +0000507 Instruction *Address = new GetElementPtrInst(PoolBase, Indices,
Chris Lattner7076ff22002-06-25 16:13:21 +0000508 I.getName()+".addr");
Chris Lattner39db8712002-05-02 17:38:14 +0000509 BeforeInsts.push_back(Address);
510
Chris Lattner7076ff22002-06-25 16:13:21 +0000511 Instruction *NewLoad = new LoadInst(Address, I.getName());
Chris Lattner441e16f2002-04-12 20:23:15 +0000512
513 // Replace the load instruction with the new load instruction...
514 BasicBlock::iterator II = ReplaceInstWith(I, NewLoad);
515
Chris Lattner39db8712002-05-02 17:38:14 +0000516 // Add all of the instructions before the load...
517 NewLoad->getParent()->getInstList().insert(II, BeforeInsts.begin(),
518 BeforeInsts.end());
Chris Lattner441e16f2002-04-12 20:23:15 +0000519
520 // If not yielding a pool allocated pointer, use the new load value as the
521 // value in the program instead of the old load value...
522 //
Chris Lattner7076ff22002-06-25 16:13:21 +0000523 if (!getScalar(&I))
524 I.replaceAllUsesWith(NewLoad);
Chris Lattner441e16f2002-04-12 20:23:15 +0000525 }
526
527 // Replace the store instruction with a new one. In the store instruction,
528 // the value stored could be a pointer type, meaning that the new store may
529 // have to change one or both of it's operands.
530 //
Chris Lattner7076ff22002-06-25 16:13:21 +0000531 void visitStoreInst(StoreInst &I) {
532 assert(getScalar(I.getOperand(1)) &&
Chris Lattner441e16f2002-04-12 20:23:15 +0000533 "Store inst found only storing pool allocated pointer. "
534 "Not imp yet!");
535
Chris Lattner7076ff22002-06-25 16:13:21 +0000536 Value *Val = I.getOperand(0); // The value to store...
Chris Lattner39db8712002-05-02 17:38:14 +0000537
Chris Lattner441e16f2002-04-12 20:23:15 +0000538 // Check to see if the value we are storing is a data structure pointer...
Chris Lattner7076ff22002-06-25 16:13:21 +0000539 //if (const ScalarInfo *ValScalar = getScalar(I.getOperand(0)))
540 if (isa<PointerType>(I.getOperand(0)->getType()))
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000541 Val = Constant::getNullValue(POINTERTYPE); // Yes, store a dummy
Chris Lattner441e16f2002-04-12 20:23:15 +0000542
Chris Lattner7076ff22002-06-25 16:13:21 +0000543 Instruction *PoolBase = createPoolBaseInstruction(I.getOperand(1));
Chris Lattner441e16f2002-04-12 20:23:15 +0000544
545 // Cast our index to be a UIntTy so we can use it to index into the pool...
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000546 CastInst *Index = new CastInst(Constant::getNullValue(POINTERTYPE),
Chris Lattner7076ff22002-06-25 16:13:21 +0000547 Type::UIntTy, I.getOperand(1)->getName());
548 ReferencesToUpdate.push_back(RefToUpdate(Index, 0, I.getOperand(1)));
Chris Lattner441e16f2002-04-12 20:23:15 +0000549
Chris Lattner39db8712002-05-02 17:38:14 +0000550 // Instructions to add after the Index...
551 vector<Instruction*> AfterInsts;
552
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000553 Instruction *IdxInst =
Chris Lattner7076ff22002-06-25 16:13:21 +0000554 BinaryOperator::create(Instruction::Add, *I.idx_begin(), Index, "idx");
Chris Lattner39db8712002-05-02 17:38:14 +0000555 AfterInsts.push_back(IdxInst);
556
Chris Lattner7076ff22002-06-25 16:13:21 +0000557 vector<Value*> Indices(I.idx_begin(), I.idx_end());
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000558 Indices[0] = IdxInst;
Chris Lattner39db8712002-05-02 17:38:14 +0000559 Instruction *Address = new GetElementPtrInst(PoolBase, Indices,
Chris Lattner7076ff22002-06-25 16:13:21 +0000560 I.getName()+"storeaddr");
Chris Lattner39db8712002-05-02 17:38:14 +0000561 AfterInsts.push_back(Address);
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000562
Chris Lattner39db8712002-05-02 17:38:14 +0000563 Instruction *NewStore = new StoreInst(Val, Address);
564 AfterInsts.push_back(NewStore);
Chris Lattner7076ff22002-06-25 16:13:21 +0000565 if (Val != I.getOperand(0)) // Value stored was a pointer?
566 ReferencesToUpdate.push_back(RefToUpdate(NewStore, 0, I.getOperand(0)));
Chris Lattner441e16f2002-04-12 20:23:15 +0000567
568
569 // Replace the store instruction with the cast instruction...
570 BasicBlock::iterator II = ReplaceInstWith(I, Index);
571
572 // Add the pool base calculator instruction before the index...
Chris Lattner7076ff22002-06-25 16:13:21 +0000573 II = ++Index->getParent()->getInstList().insert(II, PoolBase);
574 ++II;
Chris Lattner441e16f2002-04-12 20:23:15 +0000575
Chris Lattner39db8712002-05-02 17:38:14 +0000576 // Add the instructions that go after the index...
577 Index->getParent()->getInstList().insert(II, AfterInsts.begin(),
578 AfterInsts.end());
Chris Lattner441e16f2002-04-12 20:23:15 +0000579 }
580
581
582 // Create call to poolalloc for every malloc instruction
Chris Lattner7076ff22002-06-25 16:13:21 +0000583 void visitMallocInst(MallocInst &I) {
584 const ScalarInfo &SCI = getScalarRef(&I);
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000585 vector<Value*> Args;
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000586
587 CallInst *Call;
Chris Lattner7076ff22002-06-25 16:13:21 +0000588 if (!I.isArrayAllocation()) {
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000589 Args.push_back(SCI.Pool.Handle);
Chris Lattner7076ff22002-06-25 16:13:21 +0000590 Call = new CallInst(PoolAllocator.PoolAlloc, Args, I.getName());
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000591 } else {
Chris Lattner7076ff22002-06-25 16:13:21 +0000592 Args.push_back(I.getArraySize());
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000593 Args.push_back(SCI.Pool.Handle);
Chris Lattner7076ff22002-06-25 16:13:21 +0000594 Call = new CallInst(PoolAllocator.PoolAllocArray, Args, I.getName());
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000595 }
596
Chris Lattner441e16f2002-04-12 20:23:15 +0000597 ReplaceInstWith(I, Call);
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000598 }
599
Chris Lattner441e16f2002-04-12 20:23:15 +0000600 // Convert a call to poolfree for every free instruction...
Chris Lattner7076ff22002-06-25 16:13:21 +0000601 void visitFreeInst(FreeInst &I) {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000602 // Create a new call to poolfree before the free instruction
603 vector<Value*> Args;
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000604 Args.push_back(Constant::getNullValue(POINTERTYPE));
Chris Lattner7076ff22002-06-25 16:13:21 +0000605 Args.push_back(getScalarRef(I.getOperand(0)).Pool.Handle);
Chris Lattner441e16f2002-04-12 20:23:15 +0000606 Instruction *NewCall = new CallInst(PoolAllocator.PoolFree, Args);
607 ReplaceInstWith(I, NewCall);
Chris Lattner7076ff22002-06-25 16:13:21 +0000608 ReferencesToUpdate.push_back(RefToUpdate(NewCall, 1, I.getOperand(0)));
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000609 }
610
611 // visitCallInst - Create a new call instruction with the extra arguments for
612 // all of the memory pools that the call needs.
613 //
Chris Lattner7076ff22002-06-25 16:13:21 +0000614 void visitCallInst(CallInst &I) {
615 TransformFunctionInfo &TI = CallMap[&I];
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000616
617 // Start with all of the old arguments...
Chris Lattner7076ff22002-06-25 16:13:21 +0000618 vector<Value*> Args(I.op_begin()+1, I.op_end());
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000619
Chris Lattner441e16f2002-04-12 20:23:15 +0000620 for (unsigned i = 0, e = TI.ArgInfo.size(); i != e; ++i) {
621 // Replace all of the pointer arguments with our new pointer typed values.
622 if (TI.ArgInfo[i].ArgNo != -1)
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000623 Args[TI.ArgInfo[i].ArgNo] = Constant::getNullValue(POINTERTYPE);
Chris Lattner441e16f2002-04-12 20:23:15 +0000624
625 // Add all of the pool arguments...
Chris Lattner396d5d72002-03-30 04:02:31 +0000626 Args.push_back(TI.ArgInfo[i].PoolHandle);
Chris Lattner441e16f2002-04-12 20:23:15 +0000627 }
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000628
629 Function *NF = PoolAllocator.getTransformedFunction(TI);
Chris Lattner7076ff22002-06-25 16:13:21 +0000630 Instruction *NewCall = new CallInst(NF, Args, I.getName());
Chris Lattner441e16f2002-04-12 20:23:15 +0000631 ReplaceInstWith(I, NewCall);
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000632
Chris Lattner441e16f2002-04-12 20:23:15 +0000633 // Keep track of the mapping of operands so that we can resolve them to real
634 // values later.
635 Value *RetVal = NewCall;
636 for (unsigned i = 0, e = TI.ArgInfo.size(); i != e; ++i)
637 if (TI.ArgInfo[i].ArgNo != -1)
638 ReferencesToUpdate.push_back(RefToUpdate(NewCall, TI.ArgInfo[i].ArgNo+1,
Chris Lattner7076ff22002-06-25 16:13:21 +0000639 I.getOperand(TI.ArgInfo[i].ArgNo+1)));
Chris Lattner441e16f2002-04-12 20:23:15 +0000640 else
641 RetVal = 0; // If returning a pointer, don't change retval...
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000642
Chris Lattner441e16f2002-04-12 20:23:15 +0000643 // If not returning a pointer, use the new call as the value in the program
644 // instead of the old call...
645 //
646 if (RetVal)
Chris Lattner7076ff22002-06-25 16:13:21 +0000647 I.replaceAllUsesWith(RetVal);
Chris Lattner441e16f2002-04-12 20:23:15 +0000648 }
649
650 // visitPHINode - Create a new PHI node of POINTERTYPE for all of the old Phi
651 // nodes...
652 //
Chris Lattner7076ff22002-06-25 16:13:21 +0000653 void visitPHINode(PHINode &PN) {
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000654 Value *DummyVal = Constant::getNullValue(POINTERTYPE);
Chris Lattner7076ff22002-06-25 16:13:21 +0000655 PHINode *NewPhi = new PHINode(POINTERTYPE, PN.getName());
656 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
657 NewPhi->addIncoming(DummyVal, PN.getIncomingBlock(i));
Chris Lattner441e16f2002-04-12 20:23:15 +0000658 ReferencesToUpdate.push_back(RefToUpdate(NewPhi, i*2,
Chris Lattner7076ff22002-06-25 16:13:21 +0000659 PN.getIncomingValue(i)));
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000660 }
661
Chris Lattner441e16f2002-04-12 20:23:15 +0000662 ReplaceInstWith(PN, NewPhi);
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000663 }
664
Chris Lattner441e16f2002-04-12 20:23:15 +0000665 // visitReturnInst - Replace ret instruction with a new return...
Chris Lattner7076ff22002-06-25 16:13:21 +0000666 void visitReturnInst(ReturnInst &I) {
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000667 Instruction *Ret = new ReturnInst(Constant::getNullValue(POINTERTYPE));
Chris Lattner441e16f2002-04-12 20:23:15 +0000668 ReplaceInstWith(I, Ret);
Chris Lattner7076ff22002-06-25 16:13:21 +0000669 ReferencesToUpdate.push_back(RefToUpdate(Ret, 0, I.getOperand(0)));
Chris Lattner847b6e22002-03-30 20:53:14 +0000670 }
671
Chris Lattner441e16f2002-04-12 20:23:15 +0000672 // visitSetCondInst - Replace a conditional test instruction with a new one
Chris Lattner7076ff22002-06-25 16:13:21 +0000673 void visitSetCondInst(SetCondInst &SCI) {
674 BinaryOperator &I = (BinaryOperator&)SCI;
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000675 Value *DummyVal = Constant::getNullValue(POINTERTYPE);
Chris Lattner7076ff22002-06-25 16:13:21 +0000676 BinaryOperator *New = BinaryOperator::create(I.getOpcode(), DummyVal,
677 DummyVal, I.getName());
Chris Lattner441e16f2002-04-12 20:23:15 +0000678 ReplaceInstWith(I, New);
679
Chris Lattner7076ff22002-06-25 16:13:21 +0000680 ReferencesToUpdate.push_back(RefToUpdate(New, 0, I.getOperand(0)));
681 ReferencesToUpdate.push_back(RefToUpdate(New, 1, I.getOperand(1)));
Chris Lattner441e16f2002-04-12 20:23:15 +0000682
683 // Make sure branches refer to the new condition...
Chris Lattner7076ff22002-06-25 16:13:21 +0000684 I.replaceAllUsesWith(New);
Chris Lattnercf09a2a2002-04-01 00:45:33 +0000685 }
686
Chris Lattner7076ff22002-06-25 16:13:21 +0000687 void visitInstruction(Instruction &I) {
Chris Lattner441e16f2002-04-12 20:23:15 +0000688 cerr << "Unknown instruction to FunctionBodyTransformer:\n" << I;
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000689 }
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000690};
691
692
Chris Lattner457e1ac2002-04-15 22:42:23 +0000693// PoolBaseLoadEliminator - Every load and store through a pool allocated
694// pointer causes a load of the real pool base out of the pool descriptor.
695// Iterate through the function, doing a local elimination pass of duplicate
696// loads. This attempts to turn the all too common:
697//
698// %reg109.poolbase22 = load %root.pool* %root.pool, uint 0, ubyte 0, ubyte 0
699// %reg207 = load %root.p* %reg109.poolbase22, uint %reg109, ubyte 0, ubyte 0
700// %reg109.poolbase23 = load %root.pool* %root.pool, uint 0, ubyte 0, ubyte 0
701// store double %reg207, %root.p* %reg109.poolbase23, uint %reg109, ...
702//
703// into:
704// %reg109.poolbase22 = load %root.pool* %root.pool, uint 0, ubyte 0, ubyte 0
705// %reg207 = load %root.p* %reg109.poolbase22, uint %reg109, ubyte 0, ubyte 0
706// store double %reg207, %root.p* %reg109.poolbase22, uint %reg109, ...
707//
708//
709class PoolBaseLoadEliminator : public InstVisitor<PoolBaseLoadEliminator> {
710 // PoolDescValues - Keep track of the values in the current function that are
711 // pool descriptors (loads from which we want to eliminate).
712 //
713 vector<Value*> PoolDescValues;
714
715 // PoolDescMap - As we are analyzing a BB, keep track of which load to use
716 // when referencing a pool descriptor.
717 //
718 map<Value*, LoadInst*> PoolDescMap;
719
720 // These two fields keep track of statistics of how effective we are, if
721 // debugging is enabled.
722 //
723 unsigned Eliminated, Remaining;
724public:
725 // Compact the pool descriptor map into a list of the pool descriptors in the
726 // current context that we should know about...
727 //
728 PoolBaseLoadEliminator(const map<DSNode*, PoolInfo> &PoolDescs) {
729 Eliminated = Remaining = 0;
730 for (map<DSNode*, PoolInfo>::const_iterator I = PoolDescs.begin(),
731 E = PoolDescs.end(); I != E; ++I)
732 PoolDescValues.push_back(I->second.Handle);
733
734 // Remove duplicates from the list of pool values
735 sort(PoolDescValues.begin(), PoolDescValues.end());
736 PoolDescValues.erase(unique(PoolDescValues.begin(), PoolDescValues.end()),
737 PoolDescValues.end());
738 }
739
740#ifdef DEBUG_POOLBASE_LOAD_ELIMINATOR
Chris Lattner7076ff22002-06-25 16:13:21 +0000741 void visitFunction(Function &F) {
742 cerr << "Pool Load Elim '" << F.getName() << "'\t";
Chris Lattner457e1ac2002-04-15 22:42:23 +0000743 }
744 ~PoolBaseLoadEliminator() {
745 unsigned Total = Eliminated+Remaining;
746 if (Total)
747 cerr << "removed " << Eliminated << "["
748 << Eliminated*100/Total << "%] loads, leaving "
749 << Remaining << ".\n";
750 }
751#endif
752
753 // Loop over the function, looking for loads to eliminate. Because we are a
754 // local transformation, we reset all of our state when we enter a new basic
755 // block.
756 //
Chris Lattner7076ff22002-06-25 16:13:21 +0000757 void visitBasicBlock(BasicBlock &) {
Chris Lattner457e1ac2002-04-15 22:42:23 +0000758 PoolDescMap.clear(); // Forget state.
759 }
760
761 // Starting with an empty basic block, we scan it looking for loads of the
762 // pool descriptor. When we find a load, we add it to the PoolDescMap,
763 // indicating that we have a value available to recycle next time we see the
764 // poolbase of this instruction being loaded.
765 //
Chris Lattner7076ff22002-06-25 16:13:21 +0000766 void visitLoadInst(LoadInst &LI) {
767 Value *LoadAddr = LI.getPointerOperand();
Chris Lattner457e1ac2002-04-15 22:42:23 +0000768 map<Value*, LoadInst*>::iterator VIt = PoolDescMap.find(LoadAddr);
769 if (VIt != PoolDescMap.end()) { // We already have a value for this load?
Chris Lattner7076ff22002-06-25 16:13:21 +0000770 LI.replaceAllUsesWith(VIt->second); // Make the current load dead
Chris Lattner457e1ac2002-04-15 22:42:23 +0000771 ++Eliminated;
772 } else {
773 // This load might not be a load of a pool pointer, check to see if it is
Chris Lattner7076ff22002-06-25 16:13:21 +0000774 if (LI.getNumOperands() == 4 && // load pool, uint 0, ubyte 0, ubyte 0
Chris Lattner457e1ac2002-04-15 22:42:23 +0000775 find(PoolDescValues.begin(), PoolDescValues.end(), LoadAddr) !=
776 PoolDescValues.end()) {
777
778 assert("Make sure it's a load of the pool base, not a chaining field" &&
Chris Lattner7076ff22002-06-25 16:13:21 +0000779 LI.getOperand(1) == Constant::getNullValue(Type::UIntTy) &&
780 LI.getOperand(2) == Constant::getNullValue(Type::UByteTy) &&
781 LI.getOperand(3) == Constant::getNullValue(Type::UByteTy));
Chris Lattner457e1ac2002-04-15 22:42:23 +0000782
783 // If it is a load of a pool base, keep track of it for future reference
Anand Shukla2bc64192002-06-25 21:07:58 +0000784 PoolDescMap.insert(std::make_pair(LoadAddr, &LI));
Chris Lattner457e1ac2002-04-15 22:42:23 +0000785 ++Remaining;
786 }
787 }
788 }
789
790 // If we run across a function call, forget all state... Calls to
791 // poolalloc/poolfree can invalidate the pool base pointer, so it should be
792 // reloaded the next time it is used. Furthermore, a call to a random
793 // function might call one of these functions, so be conservative. Through
794 // more analysis, this could be improved in the future.
795 //
Chris Lattner7076ff22002-06-25 16:13:21 +0000796 void visitCallInst(CallInst &) {
Chris Lattner457e1ac2002-04-15 22:42:23 +0000797 PoolDescMap.clear();
798 }
799};
800
Chris Lattner3e78dea2002-04-18 14:43:30 +0000801static void addNodeMapping(DSNode *SrcNode, const PointerValSet &PVS,
802 map<DSNode*, PointerValSet> &NodeMapping) {
803 for (unsigned i = 0, e = PVS.size(); i != e; ++i)
804 if (NodeMapping[SrcNode].add(PVS[i])) { // Not in map yet?
805 assert(PVS[i].Index == 0 && "Node indexing not supported yet!");
806 DSNode *DestNode = PVS[i].Node;
807
808 // Loop over all of the outgoing links in the mapped graph
809 for (unsigned l = 0, le = DestNode->getNumOutgoingLinks(); l != le; ++l) {
810 PointerValSet &SrcSet = SrcNode->getOutgoingLink(l);
811 const PointerValSet &DestSet = DestNode->getOutgoingLink(l);
812
813 // Add all of the node mappings now!
814 for (unsigned si = 0, se = SrcSet.size(); si != se; ++si) {
815 assert(SrcSet[si].Index == 0 && "Can't handle node offset!");
816 addNodeMapping(SrcSet[si].Node, DestSet, NodeMapping);
817 }
818 }
819 }
820}
821
822// CalculateNodeMapping - There is a partial isomorphism between the graph
823// passed in and the graph that is actually used by the function. We need to
824// figure out what this mapping is so that we can transformFunctionBody the
825// instructions in the function itself. Note that every node in the graph that
826// we are interested in must be both in the local graph of the called function,
827// and in the local graph of the calling function. Because of this, we only
828// define the mapping for these nodes [conveniently these are the only nodes we
829// CAN define a mapping for...]
830//
831// The roots of the graph that we are transforming is rooted in the arguments
832// passed into the function from the caller. This is where we start our
833// mapping calculation.
834//
835// The NodeMapping calculated maps from the callers graph to the called graph.
836//
837static void CalculateNodeMapping(Function *F, TransformFunctionInfo &TFI,
838 FunctionDSGraph &CallerGraph,
839 FunctionDSGraph &CalledGraph,
840 map<DSNode*, PointerValSet> &NodeMapping) {
841 int LastArgNo = -2;
842 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i) {
843 // Figure out what nodes in the called graph the TFI.ArgInfo[i].Node node
844 // corresponds to...
845 //
846 // Only consider first node of sequence. Extra nodes may may be added
847 // to the TFI if the data structure requires more nodes than just the
848 // one the argument points to. We are only interested in the one the
849 // argument points to though.
850 //
851 if (TFI.ArgInfo[i].ArgNo != LastArgNo) {
852 if (TFI.ArgInfo[i].ArgNo == -1) {
853 addNodeMapping(TFI.ArgInfo[i].Node, CalledGraph.getRetNodes(),
854 NodeMapping);
855 } else {
856 // Figure out which node argument # ArgNo points to in the called graph.
Chris Lattner7076ff22002-06-25 16:13:21 +0000857 Function::aiterator AI = F->abegin();
858 std::advance(AI, TFI.ArgInfo[i].ArgNo);
859 addNodeMapping(TFI.ArgInfo[i].Node, CalledGraph.getValueMap()[AI],
Chris Lattner3e78dea2002-04-18 14:43:30 +0000860 NodeMapping);
861 }
862 LastArgNo = TFI.ArgInfo[i].ArgNo;
863 }
864 }
865}
Chris Lattner441e16f2002-04-12 20:23:15 +0000866
867
Chris Lattner3e78dea2002-04-18 14:43:30 +0000868
869
870// addCallInfo - For a specified function call CI, figure out which pool
871// descriptors need to be passed in as arguments, and which arguments need to be
872// transformed into indices. If Arg != -1, the specified call argument is
873// passed in as a pointer to a data structure.
874//
875void TransformFunctionInfo::addCallInfo(DataStructure *DS, CallInst *CI,
876 int Arg, DSNode *GraphNode,
877 map<DSNode*, PoolInfo> &PoolDescs) {
Chris Lattner0dc225c2002-03-31 07:17:46 +0000878 assert(CI->getCalledFunction() && "Cannot handle indirect calls yet!");
Chris Lattner3e78dea2002-04-18 14:43:30 +0000879 assert(Func == 0 || Func == CI->getCalledFunction() &&
Chris Lattner0dc225c2002-03-31 07:17:46 +0000880 "Function call record should always call the same function!");
Chris Lattner3e78dea2002-04-18 14:43:30 +0000881 assert(Call == 0 || Call == CI &&
Chris Lattner0dc225c2002-03-31 07:17:46 +0000882 "Call element already filled in with different value!");
Chris Lattner3e78dea2002-04-18 14:43:30 +0000883 Func = CI->getCalledFunction();
884 Call = CI;
885 //FunctionDSGraph &CalledGraph = DS->getClosedDSGraph(Func);
Chris Lattner396d5d72002-03-30 04:02:31 +0000886
887 // For now, add the entire graph that is pointed to by the call argument.
888 // This graph can and should be pruned to only what the function itself will
889 // use, because often this will be a dramatically smaller subset of what we
890 // are providing.
891 //
Chris Lattner3e78dea2002-04-18 14:43:30 +0000892 // FIXME: This should use pool links instead of extra arguments!
893 //
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000894 for (df_iterator<DSNode*> I = df_begin(GraphNode), E = df_end(GraphNode);
Chris Lattner441e16f2002-04-12 20:23:15 +0000895 I != E; ++I)
Chris Lattner3e78dea2002-04-18 14:43:30 +0000896 ArgInfo.push_back(CallArgInfo(Arg, *I, PoolDescs[*I].Handle));
897}
898
899static void markReachableNodes(const PointerValSet &Vals,
900 set<DSNode*> &ReachableNodes) {
901 for (unsigned n = 0, ne = Vals.size(); n != ne; ++n) {
902 DSNode *N = Vals[n].Node;
903 if (ReachableNodes.count(N) == 0) // Haven't already processed node?
904 ReachableNodes.insert(df_begin(N), df_end(N)); // Insert all
905 }
906}
907
908// Make sure that all dependant arguments are added to this transformation info.
909// For example, if we call foo(null, P) and foo treats it's first and second
910// arguments as belonging to the same data structure, the we MUST add entries to
911// know that the null needs to be transformed into an index as well.
912//
913void TransformFunctionInfo::ensureDependantArgumentsIncluded(DataStructure *DS,
914 map<DSNode*, PoolInfo> &PoolDescs) {
915 // FIXME: This does not work for indirect function calls!!!
916 if (Func == 0) return; // FIXME!
917
918 // Make sure argument entries are sorted.
919 finalizeConstruction();
920
921 // Loop over the function signature, checking to see if there are any pointer
922 // arguments that we do not convert... if there is something we haven't
923 // converted, set done to false.
924 //
925 unsigned PtrNo = 0;
926 bool Done = true;
927 if (isa<PointerType>(Func->getReturnType())) // Make sure we convert retval
928 if (PtrNo < ArgInfo.size() && ArgInfo[PtrNo++].ArgNo == -1) {
929 // We DO transform the ret val... skip all possible entries for retval
930 while (PtrNo < ArgInfo.size() && ArgInfo[PtrNo].ArgNo == -1)
931 PtrNo++;
932 } else {
933 Done = false;
934 }
935
Chris Lattner7076ff22002-06-25 16:13:21 +0000936 unsigned i = 0;
937 for (Function::aiterator I = Func->abegin(), E = Func->aend(); I!=E; ++I,++i){
938 if (isa<PointerType>(I->getType())) {
Chris Lattner3e78dea2002-04-18 14:43:30 +0000939 if (PtrNo < ArgInfo.size() && ArgInfo[PtrNo++].ArgNo == (int)i) {
940 // We DO transform this arg... skip all possible entries for argument
941 while (PtrNo < ArgInfo.size() && ArgInfo[PtrNo].ArgNo == (int)i)
942 PtrNo++;
943 } else {
944 Done = false;
945 break;
946 }
947 }
948 }
949
950 // If we already have entries for all pointer arguments and retvals, there
951 // certainly is no work to do. Bail out early to avoid building relatively
952 // expensive data structures.
953 //
954 if (Done) return;
955
956#ifdef DEBUG_TRANSFORM_PROGRESS
957 cerr << "Must ensure dependant arguments for: " << Func->getName() << "\n";
958#endif
959
960 // Otherwise, we MIGHT have to add the arguments/retval if they are part of
961 // the same datastructure graph as some other argument or retval that we ARE
962 // processing.
963 //
964 // Get the data structure graph for the called function.
965 //
966 FunctionDSGraph &CalledDS = DS->getClosedDSGraph(Func);
967
968 // Build a mapping between the nodes in our current graph and the nodes in the
969 // called function's graph. We build it based on our _incomplete_
970 // transformation information, because it contains all of the info that we
971 // should need.
972 //
973 map<DSNode*, PointerValSet> NodeMapping;
974 CalculateNodeMapping(Func, *this,
975 DS->getClosedDSGraph(Call->getParent()->getParent()),
976 CalledDS, NodeMapping);
977
978 // Build the inverted version of the node mapping, that maps from a node in
979 // the called functions graph to a single node in the caller graph.
980 //
981 map<DSNode*, DSNode*> InverseNodeMap;
982 for (map<DSNode*, PointerValSet>::iterator I = NodeMapping.begin(),
983 E = NodeMapping.end(); I != E; ++I) {
984 PointerValSet &CalledNodes = I->second;
985 for (unsigned i = 0, e = CalledNodes.size(); i != e; ++i)
986 InverseNodeMap[CalledNodes[i].Node] = I->first;
987 }
988 NodeMapping.clear(); // Done with information, free memory
989
990 // Build a set of reachable nodes from the arguments/retval that we ARE
991 // passing in...
992 set<DSNode*> ReachableNodes;
993
994 // Loop through all of the arguments, marking all of the reachable data
995 // structure nodes reachable if they are from this pointer...
996 //
997 for (unsigned i = 0, e = ArgInfo.size(); i != e; ++i) {
998 if (ArgInfo[i].ArgNo == -1) {
999 if (i == 0) // Only process retvals once (performance opt)
1000 markReachableNodes(CalledDS.getRetNodes(), ReachableNodes);
1001 } else { // If it's an argument value...
Chris Lattner7076ff22002-06-25 16:13:21 +00001002 Function::aiterator AI = Func->abegin();
1003 std::advance(AI, ArgInfo[i].ArgNo);
1004 if (isa<PointerType>(AI->getType()))
1005 markReachableNodes(CalledDS.getValueMap()[AI], ReachableNodes);
Chris Lattner3e78dea2002-04-18 14:43:30 +00001006 }
1007 }
1008
1009 // Now that we know which nodes are already reachable, see if any of the
1010 // arguments that we are not passing values in for can reach one of the
1011 // existing nodes...
1012 //
1013
1014 // <FIXME> IN THEORY, we should allow arbitrary paths from the argument to
1015 // nodes we know about. The problem is that if we do this, then I don't know
1016 // how to get pool pointers for this head list. Since we are completely
1017 // deadline driven, I'll just allow direct accesses to the graph. </FIXME>
1018 //
1019
1020 PtrNo = 0;
1021 if (isa<PointerType>(Func->getReturnType())) // Make sure we convert retval
1022 if (PtrNo < ArgInfo.size() && ArgInfo[PtrNo++].ArgNo == -1) {
1023 // We DO transform the ret val... skip all possible entries for retval
1024 while (PtrNo < ArgInfo.size() && ArgInfo[PtrNo].ArgNo == -1)
1025 PtrNo++;
1026 } else {
1027 // See what the return value points to...
1028
1029 // FIXME: This should generalize to any number of nodes, just see if any
1030 // are reachable.
1031 assert(CalledDS.getRetNodes().size() == 1 &&
1032 "Assumes only one node is returned");
1033 DSNode *N = CalledDS.getRetNodes()[0].Node;
1034
1035 // If the return value is not marked as being passed in, but it NEEDS to
1036 // be transformed, then make it known now.
1037 //
1038 if (ReachableNodes.count(N)) {
1039#ifdef DEBUG_TRANSFORM_PROGRESS
1040 cerr << "ensure dependant arguments adds return value entry!\n";
1041#endif
1042 addCallInfo(DS, Call, -1, InverseNodeMap[N], PoolDescs);
1043
1044 // Keep sorted!
1045 finalizeConstruction();
1046 }
1047 }
1048
Chris Lattner7076ff22002-06-25 16:13:21 +00001049 i = 0;
1050 for (Function::aiterator I = Func->abegin(), E = Func->aend(); I!=E; ++I, ++i)
1051 if (isa<PointerType>(I->getType())) {
Chris Lattner3e78dea2002-04-18 14:43:30 +00001052 if (PtrNo < ArgInfo.size() && ArgInfo[PtrNo++].ArgNo == (int)i) {
1053 // We DO transform this arg... skip all possible entries for argument
1054 while (PtrNo < ArgInfo.size() && ArgInfo[PtrNo].ArgNo == (int)i)
1055 PtrNo++;
1056 } else {
1057 // This should generalize to any number of nodes, just see if any are
1058 // reachable.
Chris Lattner7076ff22002-06-25 16:13:21 +00001059 assert(CalledDS.getValueMap()[I].size() == 1 &&
Chris Lattner3e78dea2002-04-18 14:43:30 +00001060 "Only handle case where pointing to one node so far!");
1061
1062 // If the arg is not marked as being passed in, but it NEEDS to
1063 // be transformed, then make it known now.
1064 //
Chris Lattner7076ff22002-06-25 16:13:21 +00001065 DSNode *N = CalledDS.getValueMap()[I][0].Node;
Chris Lattner3e78dea2002-04-18 14:43:30 +00001066 if (ReachableNodes.count(N)) {
1067#ifdef DEBUG_TRANSFORM_PROGRESS
1068 cerr << "ensure dependant arguments adds for arg #" << i << "\n";
1069#endif
1070 addCallInfo(DS, Call, i, InverseNodeMap[N], PoolDescs);
1071
1072 // Keep sorted!
1073 finalizeConstruction();
1074 }
1075 }
1076 }
Chris Lattner396d5d72002-03-30 04:02:31 +00001077}
1078
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001079
1080// transformFunctionBody - This transforms the instruction in 'F' to use the
Chris Lattner441e16f2002-04-12 20:23:15 +00001081// pools specified in PoolDescs when modifying data structure nodes specified in
1082// the PoolDescs map. Specifically, scalar values specified in the Scalars
1083// vector must be remapped. IPFGraph is the closed data structure graph for F,
1084// of which the PoolDescriptor nodes come from.
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001085//
1086void PoolAllocate::transformFunctionBody(Function *F, FunctionDSGraph &IPFGraph,
Chris Lattner441e16f2002-04-12 20:23:15 +00001087 map<DSNode*, PoolInfo> &PoolDescs) {
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001088
1089 // Loop through the value map looking for scalars that refer to nonescaping
1090 // allocations. Add them to the Scalars vector. Note that we may have
1091 // multiple entries in the Scalars vector for each value if it points to more
1092 // than one object.
1093 //
1094 map<Value*, PointerValSet> &ValMap = IPFGraph.getValueMap();
1095 vector<ScalarInfo> Scalars;
1096
Chris Lattneracf19022002-04-14 06:14:41 +00001097#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner0e0c15b2002-04-27 02:29:32 +00001098 cerr << "Building scalar map for fn '" << F->getName() << "' body:\n";
Chris Lattneracf19022002-04-14 06:14:41 +00001099#endif
Chris Lattner847b6e22002-03-30 20:53:14 +00001100
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001101 for (map<Value*, PointerValSet>::iterator I = ValMap.begin(),
1102 E = ValMap.end(); I != E; ++I) {
1103 const PointerValSet &PVS = I->second; // Set of things pointed to by scalar
1104
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001105 // Check to see if the scalar points to a data structure node...
1106 for (unsigned i = 0, e = PVS.size(); i != e; ++i) {
Chris Lattner0e0c15b2002-04-27 02:29:32 +00001107 if (PVS[i].Index) { cerr << "Problem in " << F->getName() << " for " << I->first << "\n"; }
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001108 assert(PVS[i].Index == 0 && "Nonzero not handled yet!");
1109
1110 // If the allocation is in the nonescaping set...
Chris Lattner441e16f2002-04-12 20:23:15 +00001111 map<DSNode*, PoolInfo>::iterator AI = PoolDescs.find(PVS[i].Node);
1112 if (AI != PoolDescs.end()) { // Add it to the list of scalars
1113 Scalars.push_back(ScalarInfo(I->first, AI->second));
Chris Lattneracf19022002-04-14 06:14:41 +00001114#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001115 cerr << "\nScalar Mapping from:" << I->first
1116 << "Scalar Mapping to: "; PVS.print(cerr);
Chris Lattneracf19022002-04-14 06:14:41 +00001117#endif
Chris Lattner441e16f2002-04-12 20:23:15 +00001118 }
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001119 }
1120 }
1121
Chris Lattneracf19022002-04-14 06:14:41 +00001122#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner847b6e22002-03-30 20:53:14 +00001123 cerr << "\nIn '" << F->getName()
Chris Lattner175f37c2002-03-29 03:40:59 +00001124 << "': Found the following values that point to poolable nodes:\n";
1125
1126 for (unsigned i = 0, e = Scalars.size(); i != e; ++i)
Chris Lattner441e16f2002-04-12 20:23:15 +00001127 cerr << Scalars[i].Val;
1128 cerr << "\n";
Chris Lattneracf19022002-04-14 06:14:41 +00001129#endif
Chris Lattnere0618ca2002-03-29 05:50:20 +00001130
Chris Lattner692ad5d2002-03-29 17:13:46 +00001131 // CallMap - Contain an entry for every call instruction that needs to be
1132 // transformed. Each entry in the map contains information about what we need
1133 // to do to each call site to change it to work.
1134 //
1135 map<CallInst*, TransformFunctionInfo> CallMap;
Chris Lattner66df97d2002-03-29 06:21:38 +00001136
Chris Lattner441e16f2002-04-12 20:23:15 +00001137 // Now we need to figure out what called functions we need to transform, and
Chris Lattner692ad5d2002-03-29 17:13:46 +00001138 // how. To do this, we look at all of the scalars, seeing which functions are
1139 // either used as a scalar value (so they return a data structure), or are
1140 // passed one of our scalar values.
1141 //
1142 for (unsigned i = 0, e = Scalars.size(); i != e; ++i) {
1143 Value *ScalarVal = Scalars[i].Val;
1144
1145 // Check to see if the scalar _IS_ a call...
1146 if (CallInst *CI = dyn_cast<CallInst>(ScalarVal))
1147 // If so, add information about the pool it will be returning...
Chris Lattner3e78dea2002-04-18 14:43:30 +00001148 CallMap[CI].addCallInfo(DS, CI, -1, Scalars[i].Pool.Node, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +00001149
1150 // Check to see if the scalar is an operand to a call...
1151 for (Value::use_iterator UI = ScalarVal->use_begin(),
1152 UE = ScalarVal->use_end(); UI != UE; ++UI) {
1153 if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
1154 // Find out which operand this is to the call instruction...
1155 User::op_iterator OI = find(CI->op_begin(), CI->op_end(), ScalarVal);
1156 assert(OI != CI->op_end() && "Call on use list but not an operand!?");
1157 assert(OI != CI->op_begin() && "Pointer operand is call destination?");
1158
1159 // FIXME: This is broken if the same pointer is passed to a call more
1160 // than once! It will get multiple entries for the first pointer.
1161
1162 // Add the operand number and pool handle to the call table...
Chris Lattner3e78dea2002-04-18 14:43:30 +00001163 CallMap[CI].addCallInfo(DS, CI, OI-CI->op_begin()-1,
1164 Scalars[i].Pool.Node, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +00001165 }
1166 }
1167 }
1168
Chris Lattner3e78dea2002-04-18 14:43:30 +00001169 // Make sure that all dependant arguments are added as well. For example, if
1170 // we call foo(null, P) and foo treats it's first and second arguments as
1171 // belonging to the same data structure, the we MUST set up the CallMap to
1172 // know that the null needs to be transformed into an index as well.
1173 //
1174 for (map<CallInst*, TransformFunctionInfo>::iterator I = CallMap.begin();
1175 I != CallMap.end(); ++I)
1176 I->second.ensureDependantArgumentsIncluded(DS, PoolDescs);
1177
Chris Lattneracf19022002-04-14 06:14:41 +00001178#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner692ad5d2002-03-29 17:13:46 +00001179 // Print out call map...
1180 for (map<CallInst*, TransformFunctionInfo>::iterator I = CallMap.begin();
1181 I != CallMap.end(); ++I) {
Chris Lattner441e16f2002-04-12 20:23:15 +00001182 cerr << "For call: " << I->first;
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001183 cerr << I->second.Func->getName() << " must pass pool pointer for args #";
Chris Lattner692ad5d2002-03-29 17:13:46 +00001184 for (unsigned i = 0; i < I->second.ArgInfo.size(); ++i)
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001185 cerr << I->second.ArgInfo[i].ArgNo << ", ";
Chris Lattner441e16f2002-04-12 20:23:15 +00001186 cerr << "\n\n";
Chris Lattner692ad5d2002-03-29 17:13:46 +00001187 }
Chris Lattneracf19022002-04-14 06:14:41 +00001188#endif
Chris Lattner692ad5d2002-03-29 17:13:46 +00001189
1190 // Loop through all of the call nodes, recursively creating the new functions
1191 // that we want to call... This uses a map to prevent infinite recursion and
1192 // to avoid duplicating functions unneccesarily.
1193 //
1194 for (map<CallInst*, TransformFunctionInfo>::iterator I = CallMap.begin(),
1195 E = CallMap.end(); I != E; ++I) {
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001196 // Transform all of the functions we need, or at least ensure there is a
1197 // cached version available.
Chris Lattner441e16f2002-04-12 20:23:15 +00001198 transformFunction(I->second, IPFGraph, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +00001199 }
1200
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001201 // Now that all of the functions that we want to call are available, transform
Chris Lattner441e16f2002-04-12 20:23:15 +00001202 // the local function so that it uses the pools locally and passes them to the
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001203 // functions that we just hacked up.
1204 //
1205
1206 // First step, find the instructions to be modified.
1207 vector<Instruction*> InstToFix;
1208 for (unsigned i = 0, e = Scalars.size(); i != e; ++i) {
1209 Value *ScalarVal = Scalars[i].Val;
1210
1211 // Check to see if the scalar _IS_ an instruction. If so, it is involved.
1212 if (Instruction *Inst = dyn_cast<Instruction>(ScalarVal))
1213 InstToFix.push_back(Inst);
1214
1215 // All all of the instructions that use the scalar as an operand...
1216 for (Value::use_iterator UI = ScalarVal->use_begin(),
1217 UE = ScalarVal->use_end(); UI != UE; ++UI)
Chris Lattner441e16f2002-04-12 20:23:15 +00001218 InstToFix.push_back(cast<Instruction>(*UI));
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001219 }
1220
Chris Lattner50e3d322002-04-13 23:13:18 +00001221 // Make sure that we get return instructions that return a null value from the
1222 // function...
1223 //
1224 if (!IPFGraph.getRetNodes().empty()) {
1225 assert(IPFGraph.getRetNodes().size() == 1 && "Can only return one node?");
1226 PointerVal RetNode = IPFGraph.getRetNodes()[0];
1227 assert(RetNode.Index == 0 && "Subindexing not implemented yet!");
1228
1229 // Only process return instructions if the return value of this function is
1230 // part of one of the data structures we are transforming...
1231 //
1232 if (PoolDescs.count(RetNode.Node)) {
1233 // Loop over all of the basic blocks, adding return instructions...
1234 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
Chris Lattner7076ff22002-06-25 16:13:21 +00001235 if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator()))
Chris Lattner50e3d322002-04-13 23:13:18 +00001236 InstToFix.push_back(RI);
1237 }
1238 }
1239
1240
1241
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001242 // Eliminate duplicates by sorting, then removing equal neighbors.
1243 sort(InstToFix.begin(), InstToFix.end());
1244 InstToFix.erase(unique(InstToFix.begin(), InstToFix.end()), InstToFix.end());
1245
Chris Lattner441e16f2002-04-12 20:23:15 +00001246 // Loop over all of the instructions to transform, creating the new
1247 // replacement instructions for them. This also unlinks them from the
1248 // function so they can be safely deleted later.
1249 //
1250 map<Value*, Value*> XFormMap;
1251 NewInstructionCreator NIC(*this, Scalars, CallMap, XFormMap);
Chris Lattner692ad5d2002-03-29 17:13:46 +00001252
Chris Lattner441e16f2002-04-12 20:23:15 +00001253 // Visit all instructions... creating the new instructions that we need and
1254 // unlinking the old instructions from the function...
1255 //
Chris Lattneracf19022002-04-14 06:14:41 +00001256#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001257 for (unsigned i = 0, e = InstToFix.size(); i != e; ++i) {
1258 cerr << "Fixing: " << InstToFix[i];
Chris Lattner7076ff22002-06-25 16:13:21 +00001259 NIC.visit(*InstToFix[i]);
Chris Lattner441e16f2002-04-12 20:23:15 +00001260 }
Chris Lattneracf19022002-04-14 06:14:41 +00001261#else
1262 NIC.visit(InstToFix.begin(), InstToFix.end());
1263#endif
Chris Lattner441e16f2002-04-12 20:23:15 +00001264
1265 // Make all instructions we will delete "let go" of their operands... so that
1266 // we can safely delete Arguments whose types have changed...
1267 //
1268 for_each(InstToFix.begin(), InstToFix.end(),
Anand Shukla2bc64192002-06-25 21:07:58 +00001269 std::mem_fun(&Instruction::dropAllReferences));
Chris Lattner441e16f2002-04-12 20:23:15 +00001270
1271 // Loop through all of the pointer arguments coming into the function,
1272 // replacing them with arguments of POINTERTYPE to match the function type of
1273 // the function.
1274 //
1275 FunctionType::ParamTypes::const_iterator TI =
1276 F->getFunctionType()->getParamTypes().begin();
Chris Lattner7076ff22002-06-25 16:13:21 +00001277 for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I, ++TI) {
1278 if (I->getType() != *TI) {
1279 assert(isa<PointerType>(I->getType()) && *TI == POINTERTYPE);
1280 Argument *NewArg = new Argument(*TI, I->getName());
1281 XFormMap[I] = NewArg; // Map old arg into new arg...
Chris Lattner441e16f2002-04-12 20:23:15 +00001282
Chris Lattner441e16f2002-04-12 20:23:15 +00001283 // Replace the old argument and then delete it...
Chris Lattner7076ff22002-06-25 16:13:21 +00001284 I = F->getArgumentList().erase(I);
1285 I = F->getArgumentList().insert(I, NewArg);
Chris Lattner441e16f2002-04-12 20:23:15 +00001286 }
1287 }
1288
1289 // Now that all of the new instructions have been created, we can update all
1290 // of the references to dummy values to be references to the actual values
1291 // that are computed.
1292 //
1293 NIC.updateReferences();
1294
Chris Lattneracf19022002-04-14 06:14:41 +00001295#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001296 cerr << "TRANSFORMED FUNCTION:\n" << F;
Chris Lattneracf19022002-04-14 06:14:41 +00001297#endif
Chris Lattner441e16f2002-04-12 20:23:15 +00001298
1299 // Delete all of the "instructions to fix"
1300 for_each(InstToFix.begin(), InstToFix.end(), deleter<Instruction>);
Chris Lattner692ad5d2002-03-29 17:13:46 +00001301
Chris Lattner457e1ac2002-04-15 22:42:23 +00001302 // Eliminate pool base loads that we can easily prove are redundant
1303 if (!DisableRLE)
1304 PoolBaseLoadEliminator(PoolDescs).visit(F);
1305
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001306 // Since we have liberally hacked the function to pieces, we want to inform
1307 // the datastructure pass that its internal representation is out of date.
1308 //
1309 DS->invalidateFunction(F);
Chris Lattner692ad5d2002-03-29 17:13:46 +00001310}
1311
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001312
1313
1314// transformFunction - Transform the specified function the specified way. It
1315// we have already transformed that function that way, don't do anything. The
1316// nodes in the TransformFunctionInfo come out of callers data structure graph.
1317//
1318void PoolAllocate::transformFunction(TransformFunctionInfo &TFI,
Chris Lattner441e16f2002-04-12 20:23:15 +00001319 FunctionDSGraph &CallerIPGraph,
1320 map<DSNode*, PoolInfo> &CallerPoolDesc) {
Chris Lattner692ad5d2002-03-29 17:13:46 +00001321 if (getTransformedFunction(TFI)) return; // Function xformation already done?
1322
Chris Lattneracf19022002-04-14 06:14:41 +00001323#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001324 cerr << "********** Entering transformFunction for "
Chris Lattner0dc225c2002-03-31 07:17:46 +00001325 << TFI.Func->getName() << ":\n";
1326 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i)
1327 cerr << " ArgInfo[" << i << "] = " << TFI.ArgInfo[i].ArgNo << "\n";
1328 cerr << "\n";
Chris Lattneracf19022002-04-14 06:14:41 +00001329#endif
Chris Lattner0dc225c2002-03-31 07:17:46 +00001330
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001331 const FunctionType *OldFuncType = TFI.Func->getFunctionType();
Chris Lattner692ad5d2002-03-29 17:13:46 +00001332
Chris Lattner291a1b12002-03-29 19:05:48 +00001333 assert(!OldFuncType->isVarArg() && "Vararg functions not handled yet!");
Chris Lattner692ad5d2002-03-29 17:13:46 +00001334
Chris Lattner291a1b12002-03-29 19:05:48 +00001335 // Build the type for the new function that we are transforming
1336 vector<const Type*> ArgTys;
Chris Lattner441e16f2002-04-12 20:23:15 +00001337 ArgTys.reserve(OldFuncType->getNumParams()+TFI.ArgInfo.size());
Chris Lattner291a1b12002-03-29 19:05:48 +00001338 for (unsigned i = 0, e = OldFuncType->getNumParams(); i != e; ++i)
1339 ArgTys.push_back(OldFuncType->getParamType(i));
1340
Chris Lattner441e16f2002-04-12 20:23:15 +00001341 const Type *RetType = OldFuncType->getReturnType();
1342
Chris Lattner291a1b12002-03-29 19:05:48 +00001343 // Add one pool pointer for every argument that needs to be supplemented.
Chris Lattner441e16f2002-04-12 20:23:15 +00001344 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i) {
1345 if (TFI.ArgInfo[i].ArgNo == -1)
1346 RetType = POINTERTYPE; // Return a pointer
1347 else
1348 ArgTys[TFI.ArgInfo[i].ArgNo] = POINTERTYPE; // Pass a pointer
1349 ArgTys.push_back(PointerType::get(CallerPoolDesc.find(TFI.ArgInfo[i].Node)
1350 ->second.PoolType));
1351 }
Chris Lattner291a1b12002-03-29 19:05:48 +00001352
1353 // Build the new function type...
Chris Lattner441e16f2002-04-12 20:23:15 +00001354 const FunctionType *NewFuncType = FunctionType::get(RetType, ArgTys,
1355 OldFuncType->isVarArg());
Chris Lattner291a1b12002-03-29 19:05:48 +00001356
1357 // The new function is internal, because we know that only we can call it.
1358 // This also helps subsequent IP transformations to eliminate duplicated pool
Chris Lattner441e16f2002-04-12 20:23:15 +00001359 // pointers (which look like the same value is always passed into a parameter,
1360 // allowing it to be easily eliminated).
Chris Lattner291a1b12002-03-29 19:05:48 +00001361 //
1362 Function *NewFunc = new Function(NewFuncType, true,
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001363 TFI.Func->getName()+".poolxform");
Chris Lattner291a1b12002-03-29 19:05:48 +00001364 CurModule->getFunctionList().push_back(NewFunc);
1365
Chris Lattner441e16f2002-04-12 20:23:15 +00001366
Chris Lattneracf19022002-04-14 06:14:41 +00001367#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001368 cerr << "Created function prototype: " << NewFunc << "\n";
Chris Lattneracf19022002-04-14 06:14:41 +00001369#endif
Chris Lattner441e16f2002-04-12 20:23:15 +00001370
Chris Lattner291a1b12002-03-29 19:05:48 +00001371 // Add the newly formed function to the TransformedFunctions table so that
1372 // infinite recursion does not occur!
1373 //
1374 TransformedFunctions[TFI] = NewFunc;
1375
1376 // Add arguments to the function... starting with all of the old arguments
1377 vector<Value*> ArgMap;
Chris Lattner7076ff22002-06-25 16:13:21 +00001378 for (Function::const_aiterator I = TFI.Func->abegin(), E = TFI.Func->aend();
1379 I != E; ++I) {
1380 Argument *NFA = new Argument(I->getType(), I->getName());
Chris Lattner291a1b12002-03-29 19:05:48 +00001381 NewFunc->getArgumentList().push_back(NFA);
1382 ArgMap.push_back(NFA); // Keep track of the arguments
1383 }
1384
1385 // Now add all of the arguments corresponding to pools passed in...
1386 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i) {
Chris Lattner441e16f2002-04-12 20:23:15 +00001387 CallArgInfo &AI = TFI.ArgInfo[i];
Chris Lattner291a1b12002-03-29 19:05:48 +00001388 string Name;
Chris Lattner441e16f2002-04-12 20:23:15 +00001389 if (AI.ArgNo == -1)
1390 Name = "ret";
Chris Lattner291a1b12002-03-29 19:05:48 +00001391 else
Chris Lattner441e16f2002-04-12 20:23:15 +00001392 Name = ArgMap[AI.ArgNo]->getName(); // Get the arg name
1393 const Type *Ty = PointerType::get(CallerPoolDesc[AI.Node].PoolType);
1394 Argument *NFA = new Argument(Ty, Name+".pool");
Chris Lattner291a1b12002-03-29 19:05:48 +00001395 NewFunc->getArgumentList().push_back(NFA);
1396 }
1397
1398 // Now clone the body of the old function into the new function...
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001399 CloneFunctionInto(NewFunc, TFI.Func, ArgMap);
Chris Lattner291a1b12002-03-29 19:05:48 +00001400
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001401 // Okay, now we have a function that is identical to the old one, except that
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001402 // it has extra arguments for the pools coming in. Now we have to get the
1403 // data structure graph for the function we are replacing, and figure out how
1404 // our graph nodes map to the graph nodes in the dest function.
1405 //
Chris Lattner847b6e22002-03-30 20:53:14 +00001406 FunctionDSGraph &DSGraph = DS->getClosedDSGraph(NewFunc);
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001407
Chris Lattner441e16f2002-04-12 20:23:15 +00001408 // NodeMapping - Multimap from callers graph to called graph. We are
1409 // guaranteed that the called function graph has more nodes than the caller,
1410 // or exactly the same number of nodes. This is because the called function
1411 // might not know that two nodes are merged when considering the callers
1412 // context, but the caller obviously does. Because of this, a single node in
1413 // the calling function's data structure graph can map to multiple nodes in
1414 // the called functions graph.
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001415 //
1416 map<DSNode*, PointerValSet> NodeMapping;
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001417
Chris Lattner847b6e22002-03-30 20:53:14 +00001418 CalculateNodeMapping(NewFunc, TFI, CallerIPGraph, DSGraph,
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001419 NodeMapping);
1420
1421 // Print out the node mapping...
Chris Lattneracf19022002-04-14 06:14:41 +00001422#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner847b6e22002-03-30 20:53:14 +00001423 cerr << "\nNode mapping for call of " << NewFunc->getName() << "\n";
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001424 for (map<DSNode*, PointerValSet>::iterator I = NodeMapping.begin();
1425 I != NodeMapping.end(); ++I) {
1426 cerr << "Map: "; I->first->print(cerr);
1427 cerr << "To: "; I->second.print(cerr);
1428 cerr << "\n";
1429 }
Chris Lattneracf19022002-04-14 06:14:41 +00001430#endif
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001431
1432 // Fill in the PoolDescriptor information for the transformed function so that
1433 // it can determine which value holds the pool descriptor for each data
1434 // structure node that it accesses.
1435 //
Chris Lattner441e16f2002-04-12 20:23:15 +00001436 map<DSNode*, PoolInfo> PoolDescs;
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001437
Chris Lattneracf19022002-04-14 06:14:41 +00001438#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner847b6e22002-03-30 20:53:14 +00001439 cerr << "\nCalculating the pool descriptor map:\n";
Chris Lattneracf19022002-04-14 06:14:41 +00001440#endif
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001441
Chris Lattner441e16f2002-04-12 20:23:15 +00001442 // Calculate as much of the pool descriptor map as possible. Since we have
1443 // the node mapping between the caller and callee functions, and we have the
1444 // pool descriptor information of the caller, we can calculate a partical pool
1445 // descriptor map for the called function.
1446 //
1447 // The nodes that we do not have complete information for are the ones that
1448 // are accessed by loading pointers derived from arguments passed in, but that
1449 // are not passed in directly. In this case, we have all of the information
1450 // except a pool value. If the called function refers to this pool, the pool
1451 // value will be loaded from the pool graph and added to the map as neccesary.
1452 //
1453 for (map<DSNode*, PointerValSet>::iterator I = NodeMapping.begin();
1454 I != NodeMapping.end(); ++I) {
1455 DSNode *CallerNode = I->first;
1456 PoolInfo &CallerPI = CallerPoolDesc[CallerNode];
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001457
Chris Lattner441e16f2002-04-12 20:23:15 +00001458 // Check to see if we have a node pointer passed in for this value...
1459 Value *CalleeValue = 0;
1460 for (unsigned a = 0, ae = TFI.ArgInfo.size(); a != ae; ++a)
1461 if (TFI.ArgInfo[a].Node == CallerNode) {
1462 // Calculate the argument number that the pool is to the function
1463 // call... The call instruction should not have the pool operands added
1464 // yet.
1465 unsigned ArgNo = TFI.Call->getNumOperands()-1+a;
Chris Lattneracf19022002-04-14 06:14:41 +00001466#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001467 cerr << "Should be argument #: " << ArgNo << "[i = " << a << "]\n";
Chris Lattneracf19022002-04-14 06:14:41 +00001468#endif
Chris Lattner7076ff22002-06-25 16:13:21 +00001469 assert(ArgNo < NewFunc->asize() &&
Chris Lattner441e16f2002-04-12 20:23:15 +00001470 "Call already has pool arguments added??");
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001471
Chris Lattner441e16f2002-04-12 20:23:15 +00001472 // Map the pool argument into the called function...
Chris Lattner7076ff22002-06-25 16:13:21 +00001473 Function::aiterator AI = NewFunc->abegin();
1474 std::advance(AI, ArgNo);
1475 CalleeValue = AI;
Chris Lattner441e16f2002-04-12 20:23:15 +00001476 break; // Found value, quit loop
1477 }
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001478
Chris Lattner441e16f2002-04-12 20:23:15 +00001479 // Loop over all of the data structure nodes that this incoming node maps to
1480 // Creating a PoolInfo structure for them.
1481 for (unsigned i = 0, e = I->second.size(); i != e; ++i) {
1482 assert(I->second[i].Index == 0 && "Doesn't handle subindexing yet!");
1483 DSNode *CalleeNode = I->second[i].Node;
1484
1485 // Add the descriptor. We already know everything about it by now, much
1486 // of it is the same as the caller info.
1487 //
Anand Shukla2bc64192002-06-25 21:07:58 +00001488 PoolDescs.insert(std::make_pair(CalleeNode,
Chris Lattner441e16f2002-04-12 20:23:15 +00001489 PoolInfo(CalleeNode, CalleeValue,
1490 CallerPI.NewType,
1491 CallerPI.PoolType)));
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001492 }
Chris Lattner847b6e22002-03-30 20:53:14 +00001493 }
1494
1495 // We must destroy the node mapping so that we don't have latent references
1496 // into the data structure graph for the new function. Otherwise we get
1497 // assertion failures when transformFunctionBody tries to invalidate the
1498 // graph.
1499 //
1500 NodeMapping.clear();
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001501
1502 // Now that we know everything we need about the function, transform the body
1503 // now!
1504 //
Chris Lattner441e16f2002-04-12 20:23:15 +00001505 transformFunctionBody(NewFunc, DSGraph, PoolDescs);
1506
Chris Lattneracf19022002-04-14 06:14:41 +00001507#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001508 cerr << "Function after transformation:\n" << NewFunc;
Chris Lattneracf19022002-04-14 06:14:41 +00001509#endif
Chris Lattner66df97d2002-03-29 06:21:38 +00001510}
1511
Chris Lattner8f796d62002-04-13 19:25:57 +00001512static unsigned countPointerTypes(const Type *Ty) {
1513 if (isa<PointerType>(Ty)) {
1514 return 1;
Chris Lattner7076ff22002-06-25 16:13:21 +00001515 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
Chris Lattner8f796d62002-04-13 19:25:57 +00001516 unsigned Num = 0;
1517 for (unsigned i = 0, e = STy->getElementTypes().size(); i != e; ++i)
1518 Num += countPointerTypes(STy->getElementTypes()[i]);
1519 return Num;
Chris Lattner7076ff22002-06-25 16:13:21 +00001520 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
Chris Lattner8f796d62002-04-13 19:25:57 +00001521 return countPointerTypes(ATy->getElementType());
1522 } else {
1523 assert(Ty->isPrimitiveType() && "Unknown derived type!");
1524 return 0;
1525 }
1526}
Chris Lattner66df97d2002-03-29 06:21:38 +00001527
1528// CreatePools - Insert instructions into the function we are processing to
1529// create all of the memory pool objects themselves. This also inserts
1530// destruction code. Add an alloca for each pool that is allocated to the
Chris Lattner441e16f2002-04-12 20:23:15 +00001531// PoolDescs vector.
Chris Lattner66df97d2002-03-29 06:21:38 +00001532//
1533void PoolAllocate::CreatePools(Function *F, const vector<AllocDSNode*> &Allocs,
Chris Lattner441e16f2002-04-12 20:23:15 +00001534 map<DSNode*, PoolInfo> &PoolDescs) {
1535 // Find all of the return nodes in the function...
Chris Lattnere0618ca2002-03-29 05:50:20 +00001536 vector<BasicBlock*> ReturnNodes;
1537 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
Chris Lattner7076ff22002-06-25 16:13:21 +00001538 if (isa<ReturnInst>(I->getTerminator()))
1539 ReturnNodes.push_back(I);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001540
Chris Lattner3e78dea2002-04-18 14:43:30 +00001541#ifdef DEBUG_CREATE_POOLS
1542 cerr << "Allocs that we are pool allocating:\n";
1543 for (unsigned i = 0, e = Allocs.size(); i != e; ++i)
1544 Allocs[i]->dump();
1545#endif
1546
Chris Lattner441e16f2002-04-12 20:23:15 +00001547 map<DSNode*, PATypeHolder> AbsPoolTyMap;
1548
1549 // First pass over the allocations to process...
1550 for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
1551 // Create the pooldescriptor mapping... with null entries for everything
1552 // except the node & NewType fields.
1553 //
1554 map<DSNode*, PoolInfo>::iterator PI =
Anand Shukla2bc64192002-06-25 21:07:58 +00001555 PoolDescs.insert(std::make_pair(Allocs[i], PoolInfo(Allocs[i]))).first;
Chris Lattner441e16f2002-04-12 20:23:15 +00001556
Chris Lattner8f796d62002-04-13 19:25:57 +00001557 // Add a symbol table entry for the new type if there was one for the old
1558 // type...
1559 string OldName = CurModule->getTypeName(Allocs[i]->getType());
Chris Lattner0e0c15b2002-04-27 02:29:32 +00001560 if (OldName.empty()) OldName = "node";
1561 CurModule->addTypeName(OldName+".p", PI->second.NewType);
Chris Lattner8f796d62002-04-13 19:25:57 +00001562
Chris Lattner441e16f2002-04-12 20:23:15 +00001563 // Create the abstract pool types that will need to be resolved in a second
1564 // pass once an abstract type is created for each pool.
1565 //
1566 // Can only handle limited shapes for now...
Chris Lattner0e0c15b2002-04-27 02:29:32 +00001567 const Type *OldNodeTy = Allocs[i]->getType();
Chris Lattner441e16f2002-04-12 20:23:15 +00001568 vector<const Type*> PoolTypes;
1569
1570 // Pool type is the first element of the pool descriptor type...
1571 PoolTypes.push_back(getPoolType(PoolDescs[Allocs[i]].NewType));
Chris Lattner8f796d62002-04-13 19:25:57 +00001572
1573 unsigned NumPointers = countPointerTypes(OldNodeTy);
1574 while (NumPointers--) // Add a different opaque type for each pointer
1575 PoolTypes.push_back(OpaqueType::get());
1576
Chris Lattner441e16f2002-04-12 20:23:15 +00001577 assert(Allocs[i]->getNumLinks() == PoolTypes.size()-1 &&
1578 "Node should have same number of pointers as pool!");
1579
Chris Lattner8f796d62002-04-13 19:25:57 +00001580 StructType *PoolType = StructType::get(PoolTypes);
1581
1582 // Add a symbol table entry for the pooltype if possible...
Chris Lattner0e0c15b2002-04-27 02:29:32 +00001583 CurModule->addTypeName(OldName+".pool", PoolType);
Chris Lattner8f796d62002-04-13 19:25:57 +00001584
Chris Lattner441e16f2002-04-12 20:23:15 +00001585 // Create the pool type, with opaque values for pointers...
Anand Shukla2bc64192002-06-25 21:07:58 +00001586 AbsPoolTyMap.insert(std::make_pair(Allocs[i], PoolType));
Chris Lattner441e16f2002-04-12 20:23:15 +00001587#ifdef DEBUG_CREATE_POOLS
1588 cerr << "POOL TY: " << AbsPoolTyMap.find(Allocs[i])->second.get() << "\n";
1589#endif
1590 }
1591
1592 // Now that we have types for all of the pool types, link them all together.
1593 for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
1594 PATypeHolder &PoolTyH = AbsPoolTyMap.find(Allocs[i])->second;
1595
1596 // Resolve all of the outgoing pointer types of this pool node...
1597 for (unsigned p = 0, pe = Allocs[i]->getNumLinks(); p != pe; ++p) {
1598 PointerValSet &PVS = Allocs[i]->getLink(p);
1599 assert(!PVS.empty() && "Outgoing edge is empty, field unused, can"
1600 " probably just leave the type opaque or something dumb.");
1601 unsigned Out;
1602 for (Out = 0; AbsPoolTyMap.count(PVS[Out].Node) == 0; ++Out)
1603 assert(Out != PVS.size() && "No edge to an outgoing allocation node!?");
1604
1605 assert(PVS[Out].Index == 0 && "Subindexing not implemented yet!");
1606
1607 // The actual struct type could change each time through the loop, so it's
1608 // NOT loop invariant.
Chris Lattner7076ff22002-06-25 16:13:21 +00001609 const StructType *PoolTy = cast<StructType>(PoolTyH.get());
Chris Lattner441e16f2002-04-12 20:23:15 +00001610
1611 // Get the opaque type...
Chris Lattner7076ff22002-06-25 16:13:21 +00001612 DerivedType *ElTy = (DerivedType*)(PoolTy->getElementTypes()[p+1].get());
Chris Lattner441e16f2002-04-12 20:23:15 +00001613
1614#ifdef DEBUG_CREATE_POOLS
1615 cerr << "Refining " << ElTy << " of " << PoolTy << " to "
1616 << AbsPoolTyMap.find(PVS[Out].Node)->second.get() << "\n";
1617#endif
1618
1619 const Type *RefPoolTy = AbsPoolTyMap.find(PVS[Out].Node)->second.get();
1620 ElTy->refineAbstractTypeTo(PointerType::get(RefPoolTy));
1621
1622#ifdef DEBUG_CREATE_POOLS
1623 cerr << "Result pool type is: " << PoolTyH.get() << "\n";
1624#endif
1625 }
1626 }
1627
1628 // Create the code that goes in the entry and exit nodes for the function...
Chris Lattnere0618ca2002-03-29 05:50:20 +00001629 vector<Instruction*> EntryNodeInsts;
1630 for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
Chris Lattner441e16f2002-04-12 20:23:15 +00001631 PoolInfo &PI = PoolDescs[Allocs[i]];
1632
1633 // Fill in the pool type for this pool...
1634 PI.PoolType = AbsPoolTyMap.find(Allocs[i])->second.get();
1635 assert(!PI.PoolType->isAbstract() &&
1636 "Pool type should not be abstract anymore!");
1637
Chris Lattnere0618ca2002-03-29 05:50:20 +00001638 // Add an allocation and a free for each pool...
Chris Lattnerfc91ee92002-09-13 22:28:50 +00001639 AllocaInst *PoolAlloc = new AllocaInst(PI.PoolType, 0,
1640 CurModule->getTypeName(PI.PoolType));
Chris Lattner441e16f2002-04-12 20:23:15 +00001641 PI.Handle = PoolAlloc;
Chris Lattnere0618ca2002-03-29 05:50:20 +00001642 EntryNodeInsts.push_back(PoolAlloc);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001643 AllocationInst *AI = Allocs[i]->getAllocation();
1644
1645 // Initialize the pool. We need to know how big each allocation is. For
1646 // our purposes here, we assume we are allocating a scalar, or array of
1647 // constant size.
1648 //
Chris Lattneracf19022002-04-14 06:14:41 +00001649 unsigned ElSize = TargetData.getTypeSize(PI.NewType);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001650
1651 vector<Value*> Args;
Chris Lattnere0618ca2002-03-29 05:50:20 +00001652 Args.push_back(ConstantUInt::get(Type::UIntTy, ElSize));
Chris Lattner441e16f2002-04-12 20:23:15 +00001653 Args.push_back(PoolAlloc); // Pool to initialize
Chris Lattnere0618ca2002-03-29 05:50:20 +00001654 EntryNodeInsts.push_back(new CallInst(PoolInit, Args));
1655
Chris Lattner441e16f2002-04-12 20:23:15 +00001656 // Add code to destroy the pool in all of the exit nodes of the function...
Chris Lattner8f796d62002-04-13 19:25:57 +00001657 Args.clear();
1658 Args.push_back(PoolAlloc); // Pool to initialize
1659
Chris Lattnere0618ca2002-03-29 05:50:20 +00001660 for (unsigned EN = 0, ENE = ReturnNodes.size(); EN != ENE; ++EN) {
1661 Instruction *Destroy = new CallInst(PoolDestroy, Args);
1662
1663 // Insert it before the return instruction...
1664 BasicBlock *RetNode = ReturnNodes[EN];
Chris Lattner7076ff22002-06-25 16:13:21 +00001665 RetNode->getInstList().insert(RetNode->end()--, Destroy);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001666 }
1667 }
1668
Chris Lattner5da145b2002-04-13 19:52:54 +00001669 // Now that all of the pool descriptors have been created, link them together
1670 // so that called functions can get links as neccesary...
1671 //
1672 for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
1673 PoolInfo &PI = PoolDescs[Allocs[i]];
1674
1675 // For every pointer in the data structure, initialize a link that
1676 // indicates which pool to access...
1677 //
1678 vector<Value*> Indices(2);
1679 Indices[0] = ConstantUInt::get(Type::UIntTy, 0);
1680 for (unsigned l = 0, le = PI.Node->getNumLinks(); l != le; ++l)
1681 // Only store an entry for the field if the field is used!
1682 if (!PI.Node->getLink(l).empty()) {
1683 assert(PI.Node->getLink(l).size() == 1 && "Should have only one link!");
1684 PointerVal PV = PI.Node->getLink(l)[0];
1685 assert(PV.Index == 0 && "Subindexing not supported yet!");
1686 PoolInfo &LinkedPool = PoolDescs[PV.Node];
1687 Indices[1] = ConstantUInt::get(Type::UByteTy, 1+l);
1688
1689 EntryNodeInsts.push_back(new StoreInst(LinkedPool.Handle, PI.Handle,
1690 Indices));
1691 }
1692 }
1693
Chris Lattnere0618ca2002-03-29 05:50:20 +00001694 // Insert the entry node code into the entry block...
Chris Lattner7076ff22002-06-25 16:13:21 +00001695 F->getEntryNode().getInstList().insert(++F->getEntryNode().begin(),
Chris Lattnere0618ca2002-03-29 05:50:20 +00001696 EntryNodeInsts.begin(),
1697 EntryNodeInsts.end());
Chris Lattner175f37c2002-03-29 03:40:59 +00001698}
1699
1700
Chris Lattner441e16f2002-04-12 20:23:15 +00001701// addPoolPrototypes - Add prototypes for the pool functions to the specified
Chris Lattner175f37c2002-03-29 03:40:59 +00001702// module and update the Pool* instance variables to point to them.
1703//
Chris Lattner7076ff22002-06-25 16:13:21 +00001704void PoolAllocate::addPoolPrototypes(Module &M) {
Chris Lattner441e16f2002-04-12 20:23:15 +00001705 // Get poolinit function...
Chris Lattnere0618ca2002-03-29 05:50:20 +00001706 vector<const Type*> Args;
Chris Lattnere0618ca2002-03-29 05:50:20 +00001707 Args.push_back(Type::UIntTy); // Num bytes per element
Chris Lattner441e16f2002-04-12 20:23:15 +00001708 FunctionType *PoolInitTy = FunctionType::get(Type::VoidTy, Args, true);
Chris Lattner7076ff22002-06-25 16:13:21 +00001709 PoolInit = M.getOrInsertFunction("poolinit", PoolInitTy);
Chris Lattner175f37c2002-03-29 03:40:59 +00001710
Chris Lattnere0618ca2002-03-29 05:50:20 +00001711 // Get pooldestroy function...
1712 Args.pop_back(); // Only takes a pool...
Chris Lattner441e16f2002-04-12 20:23:15 +00001713 FunctionType *PoolDestroyTy = FunctionType::get(Type::VoidTy, Args, true);
Chris Lattner7076ff22002-06-25 16:13:21 +00001714 PoolDestroy = M.getOrInsertFunction("pooldestroy", PoolDestroyTy);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001715
Chris Lattnere0618ca2002-03-29 05:50:20 +00001716 // Get the poolalloc function...
Chris Lattner441e16f2002-04-12 20:23:15 +00001717 FunctionType *PoolAllocTy = FunctionType::get(POINTERTYPE, Args, true);
Chris Lattner7076ff22002-06-25 16:13:21 +00001718 PoolAlloc = M.getOrInsertFunction("poolalloc", PoolAllocTy);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001719
1720 // Get the poolfree function...
Chris Lattner441e16f2002-04-12 20:23:15 +00001721 Args.push_back(POINTERTYPE); // Pointer to free
1722 FunctionType *PoolFreeTy = FunctionType::get(Type::VoidTy, Args, true);
Chris Lattner7076ff22002-06-25 16:13:21 +00001723 PoolFree = M.getOrInsertFunction("poolfree", PoolFreeTy);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001724
Chris Lattner0e0c15b2002-04-27 02:29:32 +00001725 Args[0] = Type::UIntTy; // Number of slots to allocate
1726 FunctionType *PoolAllocArrayTy = FunctionType::get(POINTERTYPE, Args, true);
Chris Lattner7076ff22002-06-25 16:13:21 +00001727 PoolAllocArray = M.getOrInsertFunction("poolallocarray", PoolAllocArrayTy);
Chris Lattner175f37c2002-03-29 03:40:59 +00001728}
1729
1730
Chris Lattner7076ff22002-06-25 16:13:21 +00001731bool PoolAllocate::run(Module &M) {
Chris Lattner175f37c2002-03-29 03:40:59 +00001732 addPoolPrototypes(M);
Chris Lattner7076ff22002-06-25 16:13:21 +00001733 CurModule = &M;
Chris Lattner175f37c2002-03-29 03:40:59 +00001734
1735 DS = &getAnalysis<DataStructure>();
1736 bool Changed = false;
Chris Lattner291a1b12002-03-29 19:05:48 +00001737
Chris Lattner7076ff22002-06-25 16:13:21 +00001738 for (Module::iterator I = M.begin(); I != M.end(); ++I)
1739 if (!I->isExternal()) {
1740 Changed |= processFunction(I);
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001741 if (Changed) {
1742 cerr << "Only processing one function\n";
1743 break;
1744 }
1745 }
Chris Lattner175f37c2002-03-29 03:40:59 +00001746
1747 CurModule = 0;
1748 DS = 0;
1749 return false;
1750}
Chris Lattner87d180e2002-07-10 22:36:47 +00001751#endif
Chris Lattner175f37c2002-03-29 03:40:59 +00001752
1753// createPoolAllocatePass - Global function to access the functionality of this
1754// pass...
1755//
Chris Lattner87d180e2002-07-10 22:36:47 +00001756Pass *createPoolAllocatePass() {
1757 assert(0 && "Pool allocator disabled!");
Chris Lattner10073a92002-07-25 06:17:51 +00001758 return 0;
Chris Lattner87d180e2002-07-10 22:36:47 +00001759 //return new PoolAllocate();
1760}