blob: 33110bd467f88ff3fc61885a345bcaaf3b7b8fe7 [file] [log] [blame]
Chris Lattner64fd9352002-03-28 18:08:31 +00001//===-- PoolAllocate.cpp - Pool Allocation Pass ---------------------------===//
2//
3// This transform changes programs so that disjoint data structures are
4// allocated out of different pools of memory, increasing locality and shrinking
5// pointer size.
6//
Chris Lattner457e1ac2002-04-15 22:42:23 +00007// This pass requires a DCE & instcombine pass to be run after it for best
8// results.
9//
Chris Lattner64fd9352002-03-28 18:08:31 +000010//===----------------------------------------------------------------------===//
11
Chris Lattner99a53f62002-07-24 17:12:05 +000012#include "llvm/Transforms/IPO.h"
Chris Lattner7608a462002-05-07 18:36:35 +000013#include "llvm/Transforms/Utils/CloneFunction.h"
Chris Lattner396d5d72002-03-30 04:02:31 +000014#include "llvm/Analysis/DataStructureGraph.h"
Chris Lattner175f37c2002-03-29 03:40:59 +000015#include "llvm/Module.h"
Chris Lattner175f37c2002-03-29 03:40:59 +000016#include "llvm/iMemory.h"
Chris Lattnere0618ca2002-03-29 05:50:20 +000017#include "llvm/iTerminators.h"
Chris Lattner441e16f2002-04-12 20:23:15 +000018#include "llvm/iPHINode.h"
Chris Lattnere0618ca2002-03-29 05:50:20 +000019#include "llvm/iOther.h"
Chris Lattner441e16f2002-04-12 20:23:15 +000020#include "llvm/DerivedTypes.h"
Chris Lattnerca142372002-04-28 19:55:58 +000021#include "llvm/Constants.h"
Chris Lattnere0618ca2002-03-29 05:50:20 +000022#include "llvm/Target/TargetData.h"
Chris Lattnerf32d65d2002-03-29 21:25:19 +000023#include "llvm/Support/InstVisitor.h"
Chris Lattner396d5d72002-03-30 04:02:31 +000024#include "Support/DepthFirstIterator.h"
Chris Lattnere0618ca2002-03-29 05:50:20 +000025#include "Support/STLExtras.h"
Chris Lattner175f37c2002-03-29 03:40:59 +000026#include <algorithm>
Anand Shukla2bc64192002-06-25 21:07:58 +000027using std::vector;
28using std::cerr;
29using std::map;
30using std::string;
31using std::set;
Chris Lattner64fd9352002-03-28 18:08:31 +000032
Chris Lattner87d180e2002-07-10 22:36:47 +000033#if 0
34
Chris Lattner441e16f2002-04-12 20:23:15 +000035// DEBUG_CREATE_POOLS - Enable this to turn on debug output for the pool
36// creation phase in the top level function of a transformed data structure.
37//
Chris Lattneracf19022002-04-14 06:14:41 +000038//#define DEBUG_CREATE_POOLS 1
39
40// DEBUG_TRANSFORM_PROGRESS - Enable this to get lots of debug output on what
41// the transformation is doing.
42//
43//#define DEBUG_TRANSFORM_PROGRESS 1
Chris Lattner441e16f2002-04-12 20:23:15 +000044
Chris Lattner457e1ac2002-04-15 22:42:23 +000045// DEBUG_POOLBASE_LOAD_ELIMINATOR - Turn this on to get statistics about how
46// many static loads were eliminated from a function...
47//
48#define DEBUG_POOLBASE_LOAD_ELIMINATOR 1
49
Chris Lattner50e3d322002-04-13 23:13:18 +000050#include "Support/CommandLine.h"
51enum PtrSize {
52 Ptr8bits, Ptr16bits, Ptr32bits
53};
54
Chris Lattnerf5cad152002-07-22 02:10:13 +000055static cl::opt<PtrSize>
56ReqPointerSize("poolalloc-ptr-size",
57 cl::desc("Set pointer size for -poolalloc pass"),
58 cl::values(
Chris Lattner50e3d322002-04-13 23:13:18 +000059 clEnumValN(Ptr32bits, "32", "Use 32 bit indices for pointers"),
60 clEnumValN(Ptr16bits, "16", "Use 16 bit indices for pointers"),
Chris Lattnerf5cad152002-07-22 02:10:13 +000061 clEnumValN(Ptr8bits , "8", "Use 8 bit indices for pointers"),
62 0));
Chris Lattner50e3d322002-04-13 23:13:18 +000063
Chris Lattnerf5cad152002-07-22 02:10:13 +000064static cl::opt<bool>
65DisableRLE("no-pool-load-elim", cl::Hidden,
66 cl::desc("Disable pool load elimination after poolalloc pass"));
Chris Lattner457e1ac2002-04-15 22:42:23 +000067
Chris Lattner441e16f2002-04-12 20:23:15 +000068const Type *POINTERTYPE;
Chris Lattner692ad5d2002-03-29 17:13:46 +000069
Chris Lattnere0618ca2002-03-29 05:50:20 +000070// FIXME: This is dependant on the sparc backend layout conventions!!
71static TargetData TargetData("test");
72
Chris Lattner50e3d322002-04-13 23:13:18 +000073static const Type *getPointerTransformedType(const Type *Ty) {
Chris Lattner7076ff22002-06-25 16:13:21 +000074 if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
Chris Lattner50e3d322002-04-13 23:13:18 +000075 return POINTERTYPE;
Chris Lattner7076ff22002-06-25 16:13:21 +000076 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
Chris Lattner50e3d322002-04-13 23:13:18 +000077 vector<const Type *> NewElTypes;
78 NewElTypes.reserve(STy->getElementTypes().size());
79 for (StructType::ElementTypes::const_iterator
80 I = STy->getElementTypes().begin(),
81 E = STy->getElementTypes().end(); I != E; ++I)
82 NewElTypes.push_back(getPointerTransformedType(*I));
83 return StructType::get(NewElTypes);
Chris Lattner7076ff22002-06-25 16:13:21 +000084 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
Chris Lattner50e3d322002-04-13 23:13:18 +000085 return ArrayType::get(getPointerTransformedType(ATy->getElementType()),
86 ATy->getNumElements());
87 } else {
88 assert(Ty->isPrimitiveType() && "Unknown derived type!");
89 return Ty;
90 }
91}
92
Chris Lattner64fd9352002-03-28 18:08:31 +000093namespace {
Chris Lattner441e16f2002-04-12 20:23:15 +000094 struct PoolInfo {
95 DSNode *Node; // The node this pool allocation represents
96 Value *Handle; // LLVM value of the pool in the current context
97 const Type *NewType; // The transformed type of the memory objects
98 const Type *PoolType; // The type of the pool
99
100 const Type *getOldType() const { return Node->getType(); }
101
102 PoolInfo() { // Define a default ctor for map::operator[]
103 cerr << "Map subscript used to get element that doesn't exist!\n";
104 abort(); // Invalid
105 }
106
107 PoolInfo(DSNode *N, Value *H, const Type *NT, const Type *PT)
108 : Node(N), Handle(H), NewType(NT), PoolType(PT) {
109 // Handle can be null...
110 assert(N && NT && PT && "Pool info null!");
111 }
112
113 PoolInfo(DSNode *N) : Node(N), Handle(0), NewType(0), PoolType(0) {
114 assert(N && "Invalid pool info!");
115
116 // The new type of the memory object is the same as the old type, except
117 // that all of the pointer values are replaced with POINTERTYPE values.
Chris Lattner50e3d322002-04-13 23:13:18 +0000118 NewType = getPointerTransformedType(getOldType());
Chris Lattner441e16f2002-04-12 20:23:15 +0000119 }
120 };
121
Chris Lattner692ad5d2002-03-29 17:13:46 +0000122 // ScalarInfo - Information about an LLVM value that we know points to some
123 // datastructure we are processing.
124 //
125 struct ScalarInfo {
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000126 Value *Val; // Scalar value in Current Function
Chris Lattner441e16f2002-04-12 20:23:15 +0000127 PoolInfo Pool; // The pool the scalar points into
Chris Lattner692ad5d2002-03-29 17:13:46 +0000128
Chris Lattner441e16f2002-04-12 20:23:15 +0000129 ScalarInfo(Value *V, const PoolInfo &PI) : Val(V), Pool(PI) {
130 assert(V && "Null value passed to ScalarInfo ctor!");
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000131 }
Chris Lattner692ad5d2002-03-29 17:13:46 +0000132 };
133
Chris Lattner396d5d72002-03-30 04:02:31 +0000134 // CallArgInfo - Information on one operand for a call that got expanded.
135 struct CallArgInfo {
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000136 int ArgNo; // Call argument number this corresponds to
137 DSNode *Node; // The graph node for the pool
138 Value *PoolHandle; // The LLVM value that is the pool pointer
Chris Lattner396d5d72002-03-30 04:02:31 +0000139
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000140 CallArgInfo(int Arg, DSNode *N, Value *PH)
141 : ArgNo(Arg), Node(N), PoolHandle(PH) {
142 assert(Arg >= -1 && N && PH && "Illegal values to CallArgInfo ctor!");
Chris Lattner396d5d72002-03-30 04:02:31 +0000143 }
144
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000145 // operator< when sorting, sort by argument number.
Chris Lattner396d5d72002-03-30 04:02:31 +0000146 bool operator<(const CallArgInfo &CAI) const {
147 return ArgNo < CAI.ArgNo;
148 }
149 };
150
Chris Lattner692ad5d2002-03-29 17:13:46 +0000151 // TransformFunctionInfo - Information about how a function eeds to be
152 // transformed.
153 //
154 struct TransformFunctionInfo {
155 // ArgInfo - Maintain information about the arguments that need to be
Chris Lattner441e16f2002-04-12 20:23:15 +0000156 // processed. Each CallArgInfo corresponds to an argument that needs to
157 // have a pool pointer passed into the transformed function with it.
Chris Lattner692ad5d2002-03-29 17:13:46 +0000158 //
159 // As a special case, "argument" number -1 corresponds to the return value.
160 //
Chris Lattner396d5d72002-03-30 04:02:31 +0000161 vector<CallArgInfo> ArgInfo;
Chris Lattner692ad5d2002-03-29 17:13:46 +0000162
163 // Func - The function to be transformed...
164 Function *Func;
165
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000166 // The call instruction that is used to map CallArgInfo PoolHandle values
167 // into the new function values.
168 CallInst *Call;
169
Chris Lattner692ad5d2002-03-29 17:13:46 +0000170 // default ctor...
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000171 TransformFunctionInfo() : Func(0), Call(0) {}
Chris Lattner692ad5d2002-03-29 17:13:46 +0000172
Chris Lattner396d5d72002-03-30 04:02:31 +0000173 bool operator<(const TransformFunctionInfo &TFI) const {
Chris Lattner291a1b12002-03-29 19:05:48 +0000174 if (Func < TFI.Func) return true;
175 if (Func > TFI.Func) return false;
Chris Lattner291a1b12002-03-29 19:05:48 +0000176 if (ArgInfo.size() < TFI.ArgInfo.size()) return true;
177 if (ArgInfo.size() > TFI.ArgInfo.size()) return false;
Chris Lattner396d5d72002-03-30 04:02:31 +0000178 return ArgInfo < TFI.ArgInfo;
Chris Lattner692ad5d2002-03-29 17:13:46 +0000179 }
180
181 void finalizeConstruction() {
182 // Sort the vector so that the return value is first, followed by the
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000183 // argument records, in order. Note that this must be a stable sort so
184 // that the entries with the same sorting criteria (ie they are multiple
185 // pool entries for the same argument) are kept in depth first order.
Anand Shukla2bc64192002-06-25 21:07:58 +0000186 std::stable_sort(ArgInfo.begin(), ArgInfo.end());
Chris Lattner692ad5d2002-03-29 17:13:46 +0000187 }
Chris Lattner3e78dea2002-04-18 14:43:30 +0000188
189 // addCallInfo - For a specified function call CI, figure out which pool
190 // descriptors need to be passed in as arguments, and which arguments need
191 // to be transformed into indices. If Arg != -1, the specified call
192 // argument is passed in as a pointer to a data structure.
193 //
194 void addCallInfo(DataStructure *DS, CallInst *CI, int Arg,
195 DSNode *GraphNode, map<DSNode*, PoolInfo> &PoolDescs);
196
197 // Make sure that all dependant arguments are added to this transformation
198 // info. For example, if we call foo(null, P) and foo treats it's first and
199 // second arguments as belonging to the same data structure, the we MUST add
200 // entries to know that the null needs to be transformed into an index as
201 // well.
202 //
203 void ensureDependantArgumentsIncluded(DataStructure *DS,
204 map<DSNode*, PoolInfo> &PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000205 };
206
207
208 // Define the pass class that we implement...
Chris Lattner441e16f2002-04-12 20:23:15 +0000209 struct PoolAllocate : public Pass {
Chris Lattner175f37c2002-03-29 03:40:59 +0000210 PoolAllocate() {
Chris Lattner50e3d322002-04-13 23:13:18 +0000211 switch (ReqPointerSize) {
212 case Ptr32bits: POINTERTYPE = Type::UIntTy; break;
213 case Ptr16bits: POINTERTYPE = Type::UShortTy; break;
214 case Ptr8bits: POINTERTYPE = Type::UByteTy; break;
215 }
Chris Lattner175f37c2002-03-29 03:40:59 +0000216
217 CurModule = 0; DS = 0;
218 PoolInit = PoolDestroy = PoolAlloc = PoolFree = 0;
Chris Lattner64fd9352002-03-28 18:08:31 +0000219 }
220
Chris Lattner441e16f2002-04-12 20:23:15 +0000221 // getPoolType - Get the type used by the backend for a pool of a particular
222 // type. This pool record is used to allocate nodes of type NodeType.
223 //
224 // Here, PoolTy = { NodeType*, sbyte*, uint }*
225 //
226 const StructType *getPoolType(const Type *NodeType) {
227 vector<const Type*> PoolElements;
228 PoolElements.push_back(PointerType::get(NodeType));
229 PoolElements.push_back(PointerType::get(Type::SByteTy));
230 PoolElements.push_back(Type::UIntTy);
Chris Lattner8f796d62002-04-13 19:25:57 +0000231 StructType *Result = StructType::get(PoolElements);
232
233 // Add a name to the symbol table to correspond to the backend
234 // representation of this pool...
235 assert(CurModule && "No current module!?");
236 string Name = CurModule->getTypeName(NodeType);
237 if (Name.empty()) Name = CurModule->getTypeName(PoolElements[0]);
238 CurModule->addTypeName(Name+"oolbe", Result);
239
240 return Result;
Chris Lattner441e16f2002-04-12 20:23:15 +0000241 }
242
Chris Lattner7076ff22002-06-25 16:13:21 +0000243 bool run(Module &M);
Chris Lattner175f37c2002-03-29 03:40:59 +0000244
Chris Lattnerc8e66542002-04-27 06:56:12 +0000245 // getAnalysisUsage - This function requires data structure information
Chris Lattner175f37c2002-03-29 03:40:59 +0000246 // to be able to see what is pool allocatable.
Chris Lattner64fd9352002-03-28 18:08:31 +0000247 //
Chris Lattnerc8e66542002-04-27 06:56:12 +0000248 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf0ed55d2002-08-08 19:01:30 +0000249 AU.addRequired<DataStructure>();
Chris Lattner64fd9352002-03-28 18:08:31 +0000250 }
Chris Lattner175f37c2002-03-29 03:40:59 +0000251
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000252 public:
Chris Lattner175f37c2002-03-29 03:40:59 +0000253 // CurModule - The module being processed.
254 Module *CurModule;
255
256 // DS - The data structure graph for the module being processed.
257 DataStructure *DS;
258
259 // Prototypes that we add to support pool allocation...
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000260 Function *PoolInit, *PoolDestroy, *PoolAlloc, *PoolAllocArray, *PoolFree;
Chris Lattner175f37c2002-03-29 03:40:59 +0000261
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000262 // The map of already transformed functions... note that the keys of this
263 // map do not have meaningful values for 'Call' or the 'PoolHandle' elements
264 // of the ArgInfo elements.
265 //
Chris Lattner692ad5d2002-03-29 17:13:46 +0000266 map<TransformFunctionInfo, Function*> TransformedFunctions;
267
268 // getTransformedFunction - Get a transformed function, or return null if
269 // the function specified hasn't been transformed yet.
270 //
271 Function *getTransformedFunction(TransformFunctionInfo &TFI) const {
272 map<TransformFunctionInfo, Function*>::const_iterator I =
273 TransformedFunctions.find(TFI);
274 if (I != TransformedFunctions.end()) return I->second;
275 return 0;
276 }
277
278
Chris Lattner441e16f2002-04-12 20:23:15 +0000279 // addPoolPrototypes - Add prototypes for the pool functions to the
280 // specified module and update the Pool* instance variables to point to
281 // them.
Chris Lattner175f37c2002-03-29 03:40:59 +0000282 //
Chris Lattner7076ff22002-06-25 16:13:21 +0000283 void addPoolPrototypes(Module &M);
Chris Lattner175f37c2002-03-29 03:40:59 +0000284
Chris Lattner66df97d2002-03-29 06:21:38 +0000285
286 // CreatePools - Insert instructions into the function we are processing to
287 // create all of the memory pool objects themselves. This also inserts
288 // destruction code. Add an alloca for each pool that is allocated to the
Chris Lattner441e16f2002-04-12 20:23:15 +0000289 // PoolDescs map.
Chris Lattner66df97d2002-03-29 06:21:38 +0000290 //
291 void CreatePools(Function *F, const vector<AllocDSNode*> &Allocs,
Chris Lattner441e16f2002-04-12 20:23:15 +0000292 map<DSNode*, PoolInfo> &PoolDescs);
Chris Lattner66df97d2002-03-29 06:21:38 +0000293
Chris Lattner175f37c2002-03-29 03:40:59 +0000294 // processFunction - Convert a function to use pool allocation where
295 // available.
296 //
297 bool processFunction(Function *F);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000298
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000299 // transformFunctionBody - This transforms the instruction in 'F' to use the
Chris Lattner441e16f2002-04-12 20:23:15 +0000300 // pools specified in PoolDescs when modifying data structure nodes
301 // specified in the PoolDescs map. IPFGraph is the closed data structure
302 // graph for F, of which the PoolDescriptor nodes come from.
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000303 //
304 void transformFunctionBody(Function *F, FunctionDSGraph &IPFGraph,
Chris Lattner441e16f2002-04-12 20:23:15 +0000305 map<DSNode*, PoolInfo> &PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000306
307 // transformFunction - Transform the specified function the specified way.
308 // It we have already transformed that function that way, don't do anything.
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000309 // The nodes in the TransformFunctionInfo come out of callers data structure
Chris Lattner441e16f2002-04-12 20:23:15 +0000310 // graph, and the PoolDescs passed in are the caller's.
Chris Lattner692ad5d2002-03-29 17:13:46 +0000311 //
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000312 void transformFunction(TransformFunctionInfo &TFI,
Chris Lattner441e16f2002-04-12 20:23:15 +0000313 FunctionDSGraph &CallerIPGraph,
314 map<DSNode*, PoolInfo> &PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000315
Chris Lattner64fd9352002-03-28 18:08:31 +0000316 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000317
Chris Lattnera2c09852002-07-26 21:12:44 +0000318 RegisterOpt<PoolAllocate> X("poolalloc",
319 "Pool allocate disjoint datastructures");
Chris Lattner64fd9352002-03-28 18:08:31 +0000320}
321
Chris Lattner692ad5d2002-03-29 17:13:46 +0000322// isNotPoolableAlloc - This is a predicate that returns true if the specified
Chris Lattner175f37c2002-03-29 03:40:59 +0000323// allocation node in a data structure graph is eligable for pool allocation.
324//
325static bool isNotPoolableAlloc(const AllocDSNode *DS) {
Chris Lattnere0618ca2002-03-29 05:50:20 +0000326 if (DS->isAllocaNode()) return true; // Do not pool allocate alloca's.
Chris Lattnere0618ca2002-03-29 05:50:20 +0000327 return false;
Chris Lattner175f37c2002-03-29 03:40:59 +0000328}
329
Chris Lattner175f37c2002-03-29 03:40:59 +0000330// processFunction - Convert a function to use pool allocation where
331// available.
332//
333bool PoolAllocate::processFunction(Function *F) {
334 // Get the closed datastructure graph for the current function... if there are
335 // any allocations in this graph that are not escaping, we need to pool
336 // allocate them here!
337 //
338 FunctionDSGraph &IPGraph = DS->getClosedDSGraph(F);
339
340 // Get all of the allocations that do not escape the current function. Since
341 // they are still live (they exist in the graph at all), this means we must
342 // have scalar references to these nodes, but the scalars are never returned.
343 //
Chris Lattner692ad5d2002-03-29 17:13:46 +0000344 vector<AllocDSNode*> Allocs;
Chris Lattner175f37c2002-03-29 03:40:59 +0000345 IPGraph.getNonEscapingAllocations(Allocs);
346
347 // Filter out allocations that we cannot handle. Currently, this includes
348 // variable sized array allocations and alloca's (which we do not want to
349 // pool allocate)
350 //
Anand Shukla2bc64192002-06-25 21:07:58 +0000351 Allocs.erase(std::remove_if(Allocs.begin(), Allocs.end(), isNotPoolableAlloc),
Chris Lattner175f37c2002-03-29 03:40:59 +0000352 Allocs.end());
353
354
355 if (Allocs.empty()) return false; // Nothing to do.
356
Chris Lattner3e78dea2002-04-18 14:43:30 +0000357#ifdef DEBUG_TRANSFORM_PROGRESS
358 cerr << "Transforming Function: " << F->getName() << "\n";
359#endif
360
Chris Lattner692ad5d2002-03-29 17:13:46 +0000361 // Insert instructions into the function we are processing to create all of
362 // the memory pool objects themselves. This also inserts destruction code.
Chris Lattner441e16f2002-04-12 20:23:15 +0000363 // This fills in the PoolDescs map to associate the alloc node with the
Chris Lattner396d5d72002-03-30 04:02:31 +0000364 // allocation of the memory pool corresponding to it.
Chris Lattner692ad5d2002-03-29 17:13:46 +0000365 //
Chris Lattner441e16f2002-04-12 20:23:15 +0000366 map<DSNode*, PoolInfo> PoolDescs;
367 CreatePools(F, Allocs, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000368
Chris Lattneracf19022002-04-14 06:14:41 +0000369#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +0000370 cerr << "Transformed Entry Function: \n" << F;
Chris Lattneracf19022002-04-14 06:14:41 +0000371#endif
Chris Lattner441e16f2002-04-12 20:23:15 +0000372
373 // Now we need to figure out what called functions we need to transform, and
Chris Lattner692ad5d2002-03-29 17:13:46 +0000374 // how. To do this, we look at all of the scalars, seeing which functions are
375 // either used as a scalar value (so they return a data structure), or are
376 // passed one of our scalar values.
377 //
Chris Lattner441e16f2002-04-12 20:23:15 +0000378 transformFunctionBody(F, IPGraph, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000379
380 return true;
381}
382
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000383
Chris Lattner441e16f2002-04-12 20:23:15 +0000384//===----------------------------------------------------------------------===//
385//
386// NewInstructionCreator - This class is used to traverse the function being
387// modified, changing each instruction visit'ed to use and provide pointer
388// indexes instead of real pointers. This is what changes the body of a
389// function to use pool allocation.
390//
391class NewInstructionCreator : public InstVisitor<NewInstructionCreator> {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000392 PoolAllocate &PoolAllocator;
393 vector<ScalarInfo> &Scalars;
394 map<CallInst*, TransformFunctionInfo> &CallMap;
Chris Lattner441e16f2002-04-12 20:23:15 +0000395 map<Value*, Value*> &XFormMap; // Map old pointers to new indexes
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000396
Chris Lattner441e16f2002-04-12 20:23:15 +0000397 struct RefToUpdate {
398 Instruction *I; // Instruction to update
399 unsigned OpNum; // Operand number to update
400 Value *OldVal; // The old value it had
401
402 RefToUpdate(Instruction *i, unsigned o, Value *ov)
403 : I(i), OpNum(o), OldVal(ov) {}
404 };
405 vector<RefToUpdate> ReferencesToUpdate;
406
407 const ScalarInfo &getScalarRef(const Value *V) {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000408 for (unsigned i = 0, e = Scalars.size(); i != e; ++i)
409 if (Scalars[i].Val == V) return Scalars[i];
Chris Lattner3e78dea2002-04-18 14:43:30 +0000410
411 cerr << "Could not find scalar " << V << " in scalar map!\n";
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000412 assert(0 && "Scalar not found in getScalar!");
413 abort();
414 return Scalars[0];
415 }
Chris Lattner441e16f2002-04-12 20:23:15 +0000416
417 const ScalarInfo *getScalar(const Value *V) {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000418 for (unsigned i = 0, e = Scalars.size(); i != e; ++i)
Chris Lattner441e16f2002-04-12 20:23:15 +0000419 if (Scalars[i].Val == V) return &Scalars[i];
420 return 0;
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000421 }
422
Chris Lattner7076ff22002-06-25 16:13:21 +0000423 BasicBlock::iterator ReplaceInstWith(Instruction &I, Instruction *New) {
424 BasicBlock *BB = I.getParent();
425 BasicBlock::iterator RI = &I;
426 BB->getInstList().remove(RI);
427 BB->getInstList().insert(RI, New);
428 XFormMap[&I] = New;
429 return New;
Chris Lattner441e16f2002-04-12 20:23:15 +0000430 }
431
Chris Lattner39db8712002-05-02 17:38:14 +0000432 Instruction *createPoolBaseInstruction(Value *PtrVal) {
Chris Lattner441e16f2002-04-12 20:23:15 +0000433 const ScalarInfo &SC = getScalarRef(PtrVal);
434 vector<Value*> Args(3);
435 Args[0] = ConstantUInt::get(Type::UIntTy, 0); // No pointer offset
436 Args[1] = ConstantUInt::get(Type::UByteTy, 0); // Field #0 of pool descriptr
437 Args[2] = ConstantUInt::get(Type::UByteTy, 0); // Field #0 of poolalloc val
Chris Lattner39db8712002-05-02 17:38:14 +0000438 return new LoadInst(SC.Pool.Handle, Args, PtrVal->getName()+".poolbase");
Chris Lattner441e16f2002-04-12 20:23:15 +0000439 }
440
441
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000442public:
Chris Lattner441e16f2002-04-12 20:23:15 +0000443 NewInstructionCreator(PoolAllocate &PA, vector<ScalarInfo> &S,
444 map<CallInst*, TransformFunctionInfo> &C,
445 map<Value*, Value*> &X)
446 : PoolAllocator(PA), Scalars(S), CallMap(C), XFormMap(X) {}
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000447
Chris Lattner441e16f2002-04-12 20:23:15 +0000448
449 // updateReferences - The NewInstructionCreator is responsible for creating
450 // new instructions to replace the old ones in the function, and then link up
451 // references to values to their new values. For it to do this, however, it
452 // keeps track of information about the value mapping of old values to new
453 // values that need to be patched up. Given this value map and a set of
454 // instruction operands to patch, updateReferences performs the updates.
455 //
456 void updateReferences() {
457 for (unsigned i = 0, e = ReferencesToUpdate.size(); i != e; ++i) {
458 RefToUpdate &Ref = ReferencesToUpdate[i];
459 Value *NewVal = XFormMap[Ref.OldVal];
460
461 if (NewVal == 0) {
462 if (isa<Constant>(Ref.OldVal) && // Refering to a null ptr?
463 cast<Constant>(Ref.OldVal)->isNullValue()) {
464 // Transform the null pointer into a null index... caching in XFormMap
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000465 XFormMap[Ref.OldVal] = NewVal = Constant::getNullValue(POINTERTYPE);
Chris Lattner441e16f2002-04-12 20:23:15 +0000466 //} else if (isa<Argument>(Ref.OldVal)) {
467 } else {
468 cerr << "Unknown reference to: " << Ref.OldVal << "\n";
469 assert(XFormMap[Ref.OldVal] &&
470 "Reference to value that was not updated found!");
471 }
472 }
473
474 Ref.I->setOperand(Ref.OpNum, NewVal);
475 }
476 ReferencesToUpdate.clear();
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000477 }
478
Chris Lattner441e16f2002-04-12 20:23:15 +0000479 //===--------------------------------------------------------------------===//
480 // Transformation methods:
481 // These methods specify how each type of instruction is transformed by the
482 // NewInstructionCreator instance...
483 //===--------------------------------------------------------------------===//
484
Chris Lattner7076ff22002-06-25 16:13:21 +0000485 void visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattner441e16f2002-04-12 20:23:15 +0000486 assert(0 && "Cannot transform get element ptr instructions yet!");
487 }
488
489 // Replace the load instruction with a new one.
Chris Lattner7076ff22002-06-25 16:13:21 +0000490 void visitLoadInst(LoadInst &I) {
Chris Lattner39db8712002-05-02 17:38:14 +0000491 vector<Instruction *> BeforeInsts;
Chris Lattner441e16f2002-04-12 20:23:15 +0000492
493 // Cast our index to be a UIntTy so we can use it to index into the pool...
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000494 CastInst *Index = new CastInst(Constant::getNullValue(POINTERTYPE),
Chris Lattner7076ff22002-06-25 16:13:21 +0000495 Type::UIntTy, I.getOperand(0)->getName());
Chris Lattner39db8712002-05-02 17:38:14 +0000496 BeforeInsts.push_back(Index);
Chris Lattner7076ff22002-06-25 16:13:21 +0000497 ReferencesToUpdate.push_back(RefToUpdate(Index, 0, I.getOperand(0)));
Chris Lattner39db8712002-05-02 17:38:14 +0000498
499 // Include the pool base instruction...
Chris Lattner7076ff22002-06-25 16:13:21 +0000500 Instruction *PoolBase = createPoolBaseInstruction(I.getOperand(0));
Chris Lattner39db8712002-05-02 17:38:14 +0000501 BeforeInsts.push_back(PoolBase);
502
503 Instruction *IdxInst =
Chris Lattner7076ff22002-06-25 16:13:21 +0000504 BinaryOperator::create(Instruction::Add, *I.idx_begin(), Index,
505 I.getName()+".idx");
Chris Lattner39db8712002-05-02 17:38:14 +0000506 BeforeInsts.push_back(IdxInst);
Chris Lattner441e16f2002-04-12 20:23:15 +0000507
Chris Lattner7076ff22002-06-25 16:13:21 +0000508 vector<Value*> Indices(I.idx_begin(), I.idx_end());
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000509 Indices[0] = IdxInst;
Chris Lattner39db8712002-05-02 17:38:14 +0000510 Instruction *Address = new GetElementPtrInst(PoolBase, Indices,
Chris Lattner7076ff22002-06-25 16:13:21 +0000511 I.getName()+".addr");
Chris Lattner39db8712002-05-02 17:38:14 +0000512 BeforeInsts.push_back(Address);
513
Chris Lattner7076ff22002-06-25 16:13:21 +0000514 Instruction *NewLoad = new LoadInst(Address, I.getName());
Chris Lattner441e16f2002-04-12 20:23:15 +0000515
516 // Replace the load instruction with the new load instruction...
517 BasicBlock::iterator II = ReplaceInstWith(I, NewLoad);
518
Chris Lattner39db8712002-05-02 17:38:14 +0000519 // Add all of the instructions before the load...
520 NewLoad->getParent()->getInstList().insert(II, BeforeInsts.begin(),
521 BeforeInsts.end());
Chris Lattner441e16f2002-04-12 20:23:15 +0000522
523 // If not yielding a pool allocated pointer, use the new load value as the
524 // value in the program instead of the old load value...
525 //
Chris Lattner7076ff22002-06-25 16:13:21 +0000526 if (!getScalar(&I))
527 I.replaceAllUsesWith(NewLoad);
Chris Lattner441e16f2002-04-12 20:23:15 +0000528 }
529
530 // Replace the store instruction with a new one. In the store instruction,
531 // the value stored could be a pointer type, meaning that the new store may
532 // have to change one or both of it's operands.
533 //
Chris Lattner7076ff22002-06-25 16:13:21 +0000534 void visitStoreInst(StoreInst &I) {
535 assert(getScalar(I.getOperand(1)) &&
Chris Lattner441e16f2002-04-12 20:23:15 +0000536 "Store inst found only storing pool allocated pointer. "
537 "Not imp yet!");
538
Chris Lattner7076ff22002-06-25 16:13:21 +0000539 Value *Val = I.getOperand(0); // The value to store...
Chris Lattner39db8712002-05-02 17:38:14 +0000540
Chris Lattner441e16f2002-04-12 20:23:15 +0000541 // Check to see if the value we are storing is a data structure pointer...
Chris Lattner7076ff22002-06-25 16:13:21 +0000542 //if (const ScalarInfo *ValScalar = getScalar(I.getOperand(0)))
543 if (isa<PointerType>(I.getOperand(0)->getType()))
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000544 Val = Constant::getNullValue(POINTERTYPE); // Yes, store a dummy
Chris Lattner441e16f2002-04-12 20:23:15 +0000545
Chris Lattner7076ff22002-06-25 16:13:21 +0000546 Instruction *PoolBase = createPoolBaseInstruction(I.getOperand(1));
Chris Lattner441e16f2002-04-12 20:23:15 +0000547
548 // Cast our index to be a UIntTy so we can use it to index into the pool...
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000549 CastInst *Index = new CastInst(Constant::getNullValue(POINTERTYPE),
Chris Lattner7076ff22002-06-25 16:13:21 +0000550 Type::UIntTy, I.getOperand(1)->getName());
551 ReferencesToUpdate.push_back(RefToUpdate(Index, 0, I.getOperand(1)));
Chris Lattner441e16f2002-04-12 20:23:15 +0000552
Chris Lattner39db8712002-05-02 17:38:14 +0000553 // Instructions to add after the Index...
554 vector<Instruction*> AfterInsts;
555
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000556 Instruction *IdxInst =
Chris Lattner7076ff22002-06-25 16:13:21 +0000557 BinaryOperator::create(Instruction::Add, *I.idx_begin(), Index, "idx");
Chris Lattner39db8712002-05-02 17:38:14 +0000558 AfterInsts.push_back(IdxInst);
559
Chris Lattner7076ff22002-06-25 16:13:21 +0000560 vector<Value*> Indices(I.idx_begin(), I.idx_end());
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000561 Indices[0] = IdxInst;
Chris Lattner39db8712002-05-02 17:38:14 +0000562 Instruction *Address = new GetElementPtrInst(PoolBase, Indices,
Chris Lattner7076ff22002-06-25 16:13:21 +0000563 I.getName()+"storeaddr");
Chris Lattner39db8712002-05-02 17:38:14 +0000564 AfterInsts.push_back(Address);
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000565
Chris Lattner39db8712002-05-02 17:38:14 +0000566 Instruction *NewStore = new StoreInst(Val, Address);
567 AfterInsts.push_back(NewStore);
Chris Lattner7076ff22002-06-25 16:13:21 +0000568 if (Val != I.getOperand(0)) // Value stored was a pointer?
569 ReferencesToUpdate.push_back(RefToUpdate(NewStore, 0, I.getOperand(0)));
Chris Lattner441e16f2002-04-12 20:23:15 +0000570
571
572 // Replace the store instruction with the cast instruction...
573 BasicBlock::iterator II = ReplaceInstWith(I, Index);
574
575 // Add the pool base calculator instruction before the index...
Chris Lattner7076ff22002-06-25 16:13:21 +0000576 II = ++Index->getParent()->getInstList().insert(II, PoolBase);
577 ++II;
Chris Lattner441e16f2002-04-12 20:23:15 +0000578
Chris Lattner39db8712002-05-02 17:38:14 +0000579 // Add the instructions that go after the index...
580 Index->getParent()->getInstList().insert(II, AfterInsts.begin(),
581 AfterInsts.end());
Chris Lattner441e16f2002-04-12 20:23:15 +0000582 }
583
584
585 // Create call to poolalloc for every malloc instruction
Chris Lattner7076ff22002-06-25 16:13:21 +0000586 void visitMallocInst(MallocInst &I) {
587 const ScalarInfo &SCI = getScalarRef(&I);
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000588 vector<Value*> Args;
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000589
590 CallInst *Call;
Chris Lattner7076ff22002-06-25 16:13:21 +0000591 if (!I.isArrayAllocation()) {
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000592 Args.push_back(SCI.Pool.Handle);
Chris Lattner7076ff22002-06-25 16:13:21 +0000593 Call = new CallInst(PoolAllocator.PoolAlloc, Args, I.getName());
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000594 } else {
Chris Lattner7076ff22002-06-25 16:13:21 +0000595 Args.push_back(I.getArraySize());
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000596 Args.push_back(SCI.Pool.Handle);
Chris Lattner7076ff22002-06-25 16:13:21 +0000597 Call = new CallInst(PoolAllocator.PoolAllocArray, Args, I.getName());
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000598 }
599
Chris Lattner441e16f2002-04-12 20:23:15 +0000600 ReplaceInstWith(I, Call);
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000601 }
602
Chris Lattner441e16f2002-04-12 20:23:15 +0000603 // Convert a call to poolfree for every free instruction...
Chris Lattner7076ff22002-06-25 16:13:21 +0000604 void visitFreeInst(FreeInst &I) {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000605 // Create a new call to poolfree before the free instruction
606 vector<Value*> Args;
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000607 Args.push_back(Constant::getNullValue(POINTERTYPE));
Chris Lattner7076ff22002-06-25 16:13:21 +0000608 Args.push_back(getScalarRef(I.getOperand(0)).Pool.Handle);
Chris Lattner441e16f2002-04-12 20:23:15 +0000609 Instruction *NewCall = new CallInst(PoolAllocator.PoolFree, Args);
610 ReplaceInstWith(I, NewCall);
Chris Lattner7076ff22002-06-25 16:13:21 +0000611 ReferencesToUpdate.push_back(RefToUpdate(NewCall, 1, I.getOperand(0)));
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000612 }
613
614 // visitCallInst - Create a new call instruction with the extra arguments for
615 // all of the memory pools that the call needs.
616 //
Chris Lattner7076ff22002-06-25 16:13:21 +0000617 void visitCallInst(CallInst &I) {
618 TransformFunctionInfo &TI = CallMap[&I];
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000619
620 // Start with all of the old arguments...
Chris Lattner7076ff22002-06-25 16:13:21 +0000621 vector<Value*> Args(I.op_begin()+1, I.op_end());
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000622
Chris Lattner441e16f2002-04-12 20:23:15 +0000623 for (unsigned i = 0, e = TI.ArgInfo.size(); i != e; ++i) {
624 // Replace all of the pointer arguments with our new pointer typed values.
625 if (TI.ArgInfo[i].ArgNo != -1)
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000626 Args[TI.ArgInfo[i].ArgNo] = Constant::getNullValue(POINTERTYPE);
Chris Lattner441e16f2002-04-12 20:23:15 +0000627
628 // Add all of the pool arguments...
Chris Lattner396d5d72002-03-30 04:02:31 +0000629 Args.push_back(TI.ArgInfo[i].PoolHandle);
Chris Lattner441e16f2002-04-12 20:23:15 +0000630 }
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000631
632 Function *NF = PoolAllocator.getTransformedFunction(TI);
Chris Lattner7076ff22002-06-25 16:13:21 +0000633 Instruction *NewCall = new CallInst(NF, Args, I.getName());
Chris Lattner441e16f2002-04-12 20:23:15 +0000634 ReplaceInstWith(I, NewCall);
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000635
Chris Lattner441e16f2002-04-12 20:23:15 +0000636 // Keep track of the mapping of operands so that we can resolve them to real
637 // values later.
638 Value *RetVal = NewCall;
639 for (unsigned i = 0, e = TI.ArgInfo.size(); i != e; ++i)
640 if (TI.ArgInfo[i].ArgNo != -1)
641 ReferencesToUpdate.push_back(RefToUpdate(NewCall, TI.ArgInfo[i].ArgNo+1,
Chris Lattner7076ff22002-06-25 16:13:21 +0000642 I.getOperand(TI.ArgInfo[i].ArgNo+1)));
Chris Lattner441e16f2002-04-12 20:23:15 +0000643 else
644 RetVal = 0; // If returning a pointer, don't change retval...
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000645
Chris Lattner441e16f2002-04-12 20:23:15 +0000646 // If not returning a pointer, use the new call as the value in the program
647 // instead of the old call...
648 //
649 if (RetVal)
Chris Lattner7076ff22002-06-25 16:13:21 +0000650 I.replaceAllUsesWith(RetVal);
Chris Lattner441e16f2002-04-12 20:23:15 +0000651 }
652
653 // visitPHINode - Create a new PHI node of POINTERTYPE for all of the old Phi
654 // nodes...
655 //
Chris Lattner7076ff22002-06-25 16:13:21 +0000656 void visitPHINode(PHINode &PN) {
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000657 Value *DummyVal = Constant::getNullValue(POINTERTYPE);
Chris Lattner7076ff22002-06-25 16:13:21 +0000658 PHINode *NewPhi = new PHINode(POINTERTYPE, PN.getName());
659 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
660 NewPhi->addIncoming(DummyVal, PN.getIncomingBlock(i));
Chris Lattner441e16f2002-04-12 20:23:15 +0000661 ReferencesToUpdate.push_back(RefToUpdate(NewPhi, i*2,
Chris Lattner7076ff22002-06-25 16:13:21 +0000662 PN.getIncomingValue(i)));
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000663 }
664
Chris Lattner441e16f2002-04-12 20:23:15 +0000665 ReplaceInstWith(PN, NewPhi);
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000666 }
667
Chris Lattner441e16f2002-04-12 20:23:15 +0000668 // visitReturnInst - Replace ret instruction with a new return...
Chris Lattner7076ff22002-06-25 16:13:21 +0000669 void visitReturnInst(ReturnInst &I) {
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000670 Instruction *Ret = new ReturnInst(Constant::getNullValue(POINTERTYPE));
Chris Lattner441e16f2002-04-12 20:23:15 +0000671 ReplaceInstWith(I, Ret);
Chris Lattner7076ff22002-06-25 16:13:21 +0000672 ReferencesToUpdate.push_back(RefToUpdate(Ret, 0, I.getOperand(0)));
Chris Lattner847b6e22002-03-30 20:53:14 +0000673 }
674
Chris Lattner441e16f2002-04-12 20:23:15 +0000675 // visitSetCondInst - Replace a conditional test instruction with a new one
Chris Lattner7076ff22002-06-25 16:13:21 +0000676 void visitSetCondInst(SetCondInst &SCI) {
677 BinaryOperator &I = (BinaryOperator&)SCI;
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000678 Value *DummyVal = Constant::getNullValue(POINTERTYPE);
Chris Lattner7076ff22002-06-25 16:13:21 +0000679 BinaryOperator *New = BinaryOperator::create(I.getOpcode(), DummyVal,
680 DummyVal, I.getName());
Chris Lattner441e16f2002-04-12 20:23:15 +0000681 ReplaceInstWith(I, New);
682
Chris Lattner7076ff22002-06-25 16:13:21 +0000683 ReferencesToUpdate.push_back(RefToUpdate(New, 0, I.getOperand(0)));
684 ReferencesToUpdate.push_back(RefToUpdate(New, 1, I.getOperand(1)));
Chris Lattner441e16f2002-04-12 20:23:15 +0000685
686 // Make sure branches refer to the new condition...
Chris Lattner7076ff22002-06-25 16:13:21 +0000687 I.replaceAllUsesWith(New);
Chris Lattnercf09a2a2002-04-01 00:45:33 +0000688 }
689
Chris Lattner7076ff22002-06-25 16:13:21 +0000690 void visitInstruction(Instruction &I) {
Chris Lattner441e16f2002-04-12 20:23:15 +0000691 cerr << "Unknown instruction to FunctionBodyTransformer:\n" << I;
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000692 }
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000693};
694
695
Chris Lattner457e1ac2002-04-15 22:42:23 +0000696// PoolBaseLoadEliminator - Every load and store through a pool allocated
697// pointer causes a load of the real pool base out of the pool descriptor.
698// Iterate through the function, doing a local elimination pass of duplicate
699// loads. This attempts to turn the all too common:
700//
701// %reg109.poolbase22 = load %root.pool* %root.pool, uint 0, ubyte 0, ubyte 0
702// %reg207 = load %root.p* %reg109.poolbase22, uint %reg109, ubyte 0, ubyte 0
703// %reg109.poolbase23 = load %root.pool* %root.pool, uint 0, ubyte 0, ubyte 0
704// store double %reg207, %root.p* %reg109.poolbase23, uint %reg109, ...
705//
706// into:
707// %reg109.poolbase22 = load %root.pool* %root.pool, uint 0, ubyte 0, ubyte 0
708// %reg207 = load %root.p* %reg109.poolbase22, uint %reg109, ubyte 0, ubyte 0
709// store double %reg207, %root.p* %reg109.poolbase22, uint %reg109, ...
710//
711//
712class PoolBaseLoadEliminator : public InstVisitor<PoolBaseLoadEliminator> {
713 // PoolDescValues - Keep track of the values in the current function that are
714 // pool descriptors (loads from which we want to eliminate).
715 //
716 vector<Value*> PoolDescValues;
717
718 // PoolDescMap - As we are analyzing a BB, keep track of which load to use
719 // when referencing a pool descriptor.
720 //
721 map<Value*, LoadInst*> PoolDescMap;
722
723 // These two fields keep track of statistics of how effective we are, if
724 // debugging is enabled.
725 //
726 unsigned Eliminated, Remaining;
727public:
728 // Compact the pool descriptor map into a list of the pool descriptors in the
729 // current context that we should know about...
730 //
731 PoolBaseLoadEliminator(const map<DSNode*, PoolInfo> &PoolDescs) {
732 Eliminated = Remaining = 0;
733 for (map<DSNode*, PoolInfo>::const_iterator I = PoolDescs.begin(),
734 E = PoolDescs.end(); I != E; ++I)
735 PoolDescValues.push_back(I->second.Handle);
736
737 // Remove duplicates from the list of pool values
738 sort(PoolDescValues.begin(), PoolDescValues.end());
739 PoolDescValues.erase(unique(PoolDescValues.begin(), PoolDescValues.end()),
740 PoolDescValues.end());
741 }
742
743#ifdef DEBUG_POOLBASE_LOAD_ELIMINATOR
Chris Lattner7076ff22002-06-25 16:13:21 +0000744 void visitFunction(Function &F) {
745 cerr << "Pool Load Elim '" << F.getName() << "'\t";
Chris Lattner457e1ac2002-04-15 22:42:23 +0000746 }
747 ~PoolBaseLoadEliminator() {
748 unsigned Total = Eliminated+Remaining;
749 if (Total)
750 cerr << "removed " << Eliminated << "["
751 << Eliminated*100/Total << "%] loads, leaving "
752 << Remaining << ".\n";
753 }
754#endif
755
756 // Loop over the function, looking for loads to eliminate. Because we are a
757 // local transformation, we reset all of our state when we enter a new basic
758 // block.
759 //
Chris Lattner7076ff22002-06-25 16:13:21 +0000760 void visitBasicBlock(BasicBlock &) {
Chris Lattner457e1ac2002-04-15 22:42:23 +0000761 PoolDescMap.clear(); // Forget state.
762 }
763
764 // Starting with an empty basic block, we scan it looking for loads of the
765 // pool descriptor. When we find a load, we add it to the PoolDescMap,
766 // indicating that we have a value available to recycle next time we see the
767 // poolbase of this instruction being loaded.
768 //
Chris Lattner7076ff22002-06-25 16:13:21 +0000769 void visitLoadInst(LoadInst &LI) {
770 Value *LoadAddr = LI.getPointerOperand();
Chris Lattner457e1ac2002-04-15 22:42:23 +0000771 map<Value*, LoadInst*>::iterator VIt = PoolDescMap.find(LoadAddr);
772 if (VIt != PoolDescMap.end()) { // We already have a value for this load?
Chris Lattner7076ff22002-06-25 16:13:21 +0000773 LI.replaceAllUsesWith(VIt->second); // Make the current load dead
Chris Lattner457e1ac2002-04-15 22:42:23 +0000774 ++Eliminated;
775 } else {
776 // This load might not be a load of a pool pointer, check to see if it is
Chris Lattner7076ff22002-06-25 16:13:21 +0000777 if (LI.getNumOperands() == 4 && // load pool, uint 0, ubyte 0, ubyte 0
Chris Lattner457e1ac2002-04-15 22:42:23 +0000778 find(PoolDescValues.begin(), PoolDescValues.end(), LoadAddr) !=
779 PoolDescValues.end()) {
780
781 assert("Make sure it's a load of the pool base, not a chaining field" &&
Chris Lattner7076ff22002-06-25 16:13:21 +0000782 LI.getOperand(1) == Constant::getNullValue(Type::UIntTy) &&
783 LI.getOperand(2) == Constant::getNullValue(Type::UByteTy) &&
784 LI.getOperand(3) == Constant::getNullValue(Type::UByteTy));
Chris Lattner457e1ac2002-04-15 22:42:23 +0000785
786 // If it is a load of a pool base, keep track of it for future reference
Anand Shukla2bc64192002-06-25 21:07:58 +0000787 PoolDescMap.insert(std::make_pair(LoadAddr, &LI));
Chris Lattner457e1ac2002-04-15 22:42:23 +0000788 ++Remaining;
789 }
790 }
791 }
792
793 // If we run across a function call, forget all state... Calls to
794 // poolalloc/poolfree can invalidate the pool base pointer, so it should be
795 // reloaded the next time it is used. Furthermore, a call to a random
796 // function might call one of these functions, so be conservative. Through
797 // more analysis, this could be improved in the future.
798 //
Chris Lattner7076ff22002-06-25 16:13:21 +0000799 void visitCallInst(CallInst &) {
Chris Lattner457e1ac2002-04-15 22:42:23 +0000800 PoolDescMap.clear();
801 }
802};
803
Chris Lattner3e78dea2002-04-18 14:43:30 +0000804static void addNodeMapping(DSNode *SrcNode, const PointerValSet &PVS,
805 map<DSNode*, PointerValSet> &NodeMapping) {
806 for (unsigned i = 0, e = PVS.size(); i != e; ++i)
807 if (NodeMapping[SrcNode].add(PVS[i])) { // Not in map yet?
808 assert(PVS[i].Index == 0 && "Node indexing not supported yet!");
809 DSNode *DestNode = PVS[i].Node;
810
811 // Loop over all of the outgoing links in the mapped graph
812 for (unsigned l = 0, le = DestNode->getNumOutgoingLinks(); l != le; ++l) {
813 PointerValSet &SrcSet = SrcNode->getOutgoingLink(l);
814 const PointerValSet &DestSet = DestNode->getOutgoingLink(l);
815
816 // Add all of the node mappings now!
817 for (unsigned si = 0, se = SrcSet.size(); si != se; ++si) {
818 assert(SrcSet[si].Index == 0 && "Can't handle node offset!");
819 addNodeMapping(SrcSet[si].Node, DestSet, NodeMapping);
820 }
821 }
822 }
823}
824
825// CalculateNodeMapping - There is a partial isomorphism between the graph
826// passed in and the graph that is actually used by the function. We need to
827// figure out what this mapping is so that we can transformFunctionBody the
828// instructions in the function itself. Note that every node in the graph that
829// we are interested in must be both in the local graph of the called function,
830// and in the local graph of the calling function. Because of this, we only
831// define the mapping for these nodes [conveniently these are the only nodes we
832// CAN define a mapping for...]
833//
834// The roots of the graph that we are transforming is rooted in the arguments
835// passed into the function from the caller. This is where we start our
836// mapping calculation.
837//
838// The NodeMapping calculated maps from the callers graph to the called graph.
839//
840static void CalculateNodeMapping(Function *F, TransformFunctionInfo &TFI,
841 FunctionDSGraph &CallerGraph,
842 FunctionDSGraph &CalledGraph,
843 map<DSNode*, PointerValSet> &NodeMapping) {
844 int LastArgNo = -2;
845 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i) {
846 // Figure out what nodes in the called graph the TFI.ArgInfo[i].Node node
847 // corresponds to...
848 //
849 // Only consider first node of sequence. Extra nodes may may be added
850 // to the TFI if the data structure requires more nodes than just the
851 // one the argument points to. We are only interested in the one the
852 // argument points to though.
853 //
854 if (TFI.ArgInfo[i].ArgNo != LastArgNo) {
855 if (TFI.ArgInfo[i].ArgNo == -1) {
856 addNodeMapping(TFI.ArgInfo[i].Node, CalledGraph.getRetNodes(),
857 NodeMapping);
858 } else {
859 // Figure out which node argument # ArgNo points to in the called graph.
Chris Lattner7076ff22002-06-25 16:13:21 +0000860 Function::aiterator AI = F->abegin();
861 std::advance(AI, TFI.ArgInfo[i].ArgNo);
862 addNodeMapping(TFI.ArgInfo[i].Node, CalledGraph.getValueMap()[AI],
Chris Lattner3e78dea2002-04-18 14:43:30 +0000863 NodeMapping);
864 }
865 LastArgNo = TFI.ArgInfo[i].ArgNo;
866 }
867 }
868}
Chris Lattner441e16f2002-04-12 20:23:15 +0000869
870
Chris Lattner3e78dea2002-04-18 14:43:30 +0000871
872
873// addCallInfo - For a specified function call CI, figure out which pool
874// descriptors need to be passed in as arguments, and which arguments need to be
875// transformed into indices. If Arg != -1, the specified call argument is
876// passed in as a pointer to a data structure.
877//
878void TransformFunctionInfo::addCallInfo(DataStructure *DS, CallInst *CI,
879 int Arg, DSNode *GraphNode,
880 map<DSNode*, PoolInfo> &PoolDescs) {
Chris Lattner0dc225c2002-03-31 07:17:46 +0000881 assert(CI->getCalledFunction() && "Cannot handle indirect calls yet!");
Chris Lattner3e78dea2002-04-18 14:43:30 +0000882 assert(Func == 0 || Func == CI->getCalledFunction() &&
Chris Lattner0dc225c2002-03-31 07:17:46 +0000883 "Function call record should always call the same function!");
Chris Lattner3e78dea2002-04-18 14:43:30 +0000884 assert(Call == 0 || Call == CI &&
Chris Lattner0dc225c2002-03-31 07:17:46 +0000885 "Call element already filled in with different value!");
Chris Lattner3e78dea2002-04-18 14:43:30 +0000886 Func = CI->getCalledFunction();
887 Call = CI;
888 //FunctionDSGraph &CalledGraph = DS->getClosedDSGraph(Func);
Chris Lattner396d5d72002-03-30 04:02:31 +0000889
890 // For now, add the entire graph that is pointed to by the call argument.
891 // This graph can and should be pruned to only what the function itself will
892 // use, because often this will be a dramatically smaller subset of what we
893 // are providing.
894 //
Chris Lattner3e78dea2002-04-18 14:43:30 +0000895 // FIXME: This should use pool links instead of extra arguments!
896 //
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000897 for (df_iterator<DSNode*> I = df_begin(GraphNode), E = df_end(GraphNode);
Chris Lattner441e16f2002-04-12 20:23:15 +0000898 I != E; ++I)
Chris Lattner3e78dea2002-04-18 14:43:30 +0000899 ArgInfo.push_back(CallArgInfo(Arg, *I, PoolDescs[*I].Handle));
900}
901
902static void markReachableNodes(const PointerValSet &Vals,
903 set<DSNode*> &ReachableNodes) {
904 for (unsigned n = 0, ne = Vals.size(); n != ne; ++n) {
905 DSNode *N = Vals[n].Node;
906 if (ReachableNodes.count(N) == 0) // Haven't already processed node?
907 ReachableNodes.insert(df_begin(N), df_end(N)); // Insert all
908 }
909}
910
911// Make sure that all dependant arguments are added to this transformation info.
912// For example, if we call foo(null, P) and foo treats it's first and second
913// arguments as belonging to the same data structure, the we MUST add entries to
914// know that the null needs to be transformed into an index as well.
915//
916void TransformFunctionInfo::ensureDependantArgumentsIncluded(DataStructure *DS,
917 map<DSNode*, PoolInfo> &PoolDescs) {
918 // FIXME: This does not work for indirect function calls!!!
919 if (Func == 0) return; // FIXME!
920
921 // Make sure argument entries are sorted.
922 finalizeConstruction();
923
924 // Loop over the function signature, checking to see if there are any pointer
925 // arguments that we do not convert... if there is something we haven't
926 // converted, set done to false.
927 //
928 unsigned PtrNo = 0;
929 bool Done = true;
930 if (isa<PointerType>(Func->getReturnType())) // Make sure we convert retval
931 if (PtrNo < ArgInfo.size() && ArgInfo[PtrNo++].ArgNo == -1) {
932 // We DO transform the ret val... skip all possible entries for retval
933 while (PtrNo < ArgInfo.size() && ArgInfo[PtrNo].ArgNo == -1)
934 PtrNo++;
935 } else {
936 Done = false;
937 }
938
Chris Lattner7076ff22002-06-25 16:13:21 +0000939 unsigned i = 0;
940 for (Function::aiterator I = Func->abegin(), E = Func->aend(); I!=E; ++I,++i){
941 if (isa<PointerType>(I->getType())) {
Chris Lattner3e78dea2002-04-18 14:43:30 +0000942 if (PtrNo < ArgInfo.size() && ArgInfo[PtrNo++].ArgNo == (int)i) {
943 // We DO transform this arg... skip all possible entries for argument
944 while (PtrNo < ArgInfo.size() && ArgInfo[PtrNo].ArgNo == (int)i)
945 PtrNo++;
946 } else {
947 Done = false;
948 break;
949 }
950 }
951 }
952
953 // If we already have entries for all pointer arguments and retvals, there
954 // certainly is no work to do. Bail out early to avoid building relatively
955 // expensive data structures.
956 //
957 if (Done) return;
958
959#ifdef DEBUG_TRANSFORM_PROGRESS
960 cerr << "Must ensure dependant arguments for: " << Func->getName() << "\n";
961#endif
962
963 // Otherwise, we MIGHT have to add the arguments/retval if they are part of
964 // the same datastructure graph as some other argument or retval that we ARE
965 // processing.
966 //
967 // Get the data structure graph for the called function.
968 //
969 FunctionDSGraph &CalledDS = DS->getClosedDSGraph(Func);
970
971 // Build a mapping between the nodes in our current graph and the nodes in the
972 // called function's graph. We build it based on our _incomplete_
973 // transformation information, because it contains all of the info that we
974 // should need.
975 //
976 map<DSNode*, PointerValSet> NodeMapping;
977 CalculateNodeMapping(Func, *this,
978 DS->getClosedDSGraph(Call->getParent()->getParent()),
979 CalledDS, NodeMapping);
980
981 // Build the inverted version of the node mapping, that maps from a node in
982 // the called functions graph to a single node in the caller graph.
983 //
984 map<DSNode*, DSNode*> InverseNodeMap;
985 for (map<DSNode*, PointerValSet>::iterator I = NodeMapping.begin(),
986 E = NodeMapping.end(); I != E; ++I) {
987 PointerValSet &CalledNodes = I->second;
988 for (unsigned i = 0, e = CalledNodes.size(); i != e; ++i)
989 InverseNodeMap[CalledNodes[i].Node] = I->first;
990 }
991 NodeMapping.clear(); // Done with information, free memory
992
993 // Build a set of reachable nodes from the arguments/retval that we ARE
994 // passing in...
995 set<DSNode*> ReachableNodes;
996
997 // Loop through all of the arguments, marking all of the reachable data
998 // structure nodes reachable if they are from this pointer...
999 //
1000 for (unsigned i = 0, e = ArgInfo.size(); i != e; ++i) {
1001 if (ArgInfo[i].ArgNo == -1) {
1002 if (i == 0) // Only process retvals once (performance opt)
1003 markReachableNodes(CalledDS.getRetNodes(), ReachableNodes);
1004 } else { // If it's an argument value...
Chris Lattner7076ff22002-06-25 16:13:21 +00001005 Function::aiterator AI = Func->abegin();
1006 std::advance(AI, ArgInfo[i].ArgNo);
1007 if (isa<PointerType>(AI->getType()))
1008 markReachableNodes(CalledDS.getValueMap()[AI], ReachableNodes);
Chris Lattner3e78dea2002-04-18 14:43:30 +00001009 }
1010 }
1011
1012 // Now that we know which nodes are already reachable, see if any of the
1013 // arguments that we are not passing values in for can reach one of the
1014 // existing nodes...
1015 //
1016
1017 // <FIXME> IN THEORY, we should allow arbitrary paths from the argument to
1018 // nodes we know about. The problem is that if we do this, then I don't know
1019 // how to get pool pointers for this head list. Since we are completely
1020 // deadline driven, I'll just allow direct accesses to the graph. </FIXME>
1021 //
1022
1023 PtrNo = 0;
1024 if (isa<PointerType>(Func->getReturnType())) // Make sure we convert retval
1025 if (PtrNo < ArgInfo.size() && ArgInfo[PtrNo++].ArgNo == -1) {
1026 // We DO transform the ret val... skip all possible entries for retval
1027 while (PtrNo < ArgInfo.size() && ArgInfo[PtrNo].ArgNo == -1)
1028 PtrNo++;
1029 } else {
1030 // See what the return value points to...
1031
1032 // FIXME: This should generalize to any number of nodes, just see if any
1033 // are reachable.
1034 assert(CalledDS.getRetNodes().size() == 1 &&
1035 "Assumes only one node is returned");
1036 DSNode *N = CalledDS.getRetNodes()[0].Node;
1037
1038 // If the return value is not marked as being passed in, but it NEEDS to
1039 // be transformed, then make it known now.
1040 //
1041 if (ReachableNodes.count(N)) {
1042#ifdef DEBUG_TRANSFORM_PROGRESS
1043 cerr << "ensure dependant arguments adds return value entry!\n";
1044#endif
1045 addCallInfo(DS, Call, -1, InverseNodeMap[N], PoolDescs);
1046
1047 // Keep sorted!
1048 finalizeConstruction();
1049 }
1050 }
1051
Chris Lattner7076ff22002-06-25 16:13:21 +00001052 i = 0;
1053 for (Function::aiterator I = Func->abegin(), E = Func->aend(); I!=E; ++I, ++i)
1054 if (isa<PointerType>(I->getType())) {
Chris Lattner3e78dea2002-04-18 14:43:30 +00001055 if (PtrNo < ArgInfo.size() && ArgInfo[PtrNo++].ArgNo == (int)i) {
1056 // We DO transform this arg... skip all possible entries for argument
1057 while (PtrNo < ArgInfo.size() && ArgInfo[PtrNo].ArgNo == (int)i)
1058 PtrNo++;
1059 } else {
1060 // This should generalize to any number of nodes, just see if any are
1061 // reachable.
Chris Lattner7076ff22002-06-25 16:13:21 +00001062 assert(CalledDS.getValueMap()[I].size() == 1 &&
Chris Lattner3e78dea2002-04-18 14:43:30 +00001063 "Only handle case where pointing to one node so far!");
1064
1065 // If the arg is not marked as being passed in, but it NEEDS to
1066 // be transformed, then make it known now.
1067 //
Chris Lattner7076ff22002-06-25 16:13:21 +00001068 DSNode *N = CalledDS.getValueMap()[I][0].Node;
Chris Lattner3e78dea2002-04-18 14:43:30 +00001069 if (ReachableNodes.count(N)) {
1070#ifdef DEBUG_TRANSFORM_PROGRESS
1071 cerr << "ensure dependant arguments adds for arg #" << i << "\n";
1072#endif
1073 addCallInfo(DS, Call, i, InverseNodeMap[N], PoolDescs);
1074
1075 // Keep sorted!
1076 finalizeConstruction();
1077 }
1078 }
1079 }
Chris Lattner396d5d72002-03-30 04:02:31 +00001080}
1081
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001082
1083// transformFunctionBody - This transforms the instruction in 'F' to use the
Chris Lattner441e16f2002-04-12 20:23:15 +00001084// pools specified in PoolDescs when modifying data structure nodes specified in
1085// the PoolDescs map. Specifically, scalar values specified in the Scalars
1086// vector must be remapped. IPFGraph is the closed data structure graph for F,
1087// of which the PoolDescriptor nodes come from.
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001088//
1089void PoolAllocate::transformFunctionBody(Function *F, FunctionDSGraph &IPFGraph,
Chris Lattner441e16f2002-04-12 20:23:15 +00001090 map<DSNode*, PoolInfo> &PoolDescs) {
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001091
1092 // Loop through the value map looking for scalars that refer to nonescaping
1093 // allocations. Add them to the Scalars vector. Note that we may have
1094 // multiple entries in the Scalars vector for each value if it points to more
1095 // than one object.
1096 //
1097 map<Value*, PointerValSet> &ValMap = IPFGraph.getValueMap();
1098 vector<ScalarInfo> Scalars;
1099
Chris Lattneracf19022002-04-14 06:14:41 +00001100#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner0e0c15b2002-04-27 02:29:32 +00001101 cerr << "Building scalar map for fn '" << F->getName() << "' body:\n";
Chris Lattneracf19022002-04-14 06:14:41 +00001102#endif
Chris Lattner847b6e22002-03-30 20:53:14 +00001103
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001104 for (map<Value*, PointerValSet>::iterator I = ValMap.begin(),
1105 E = ValMap.end(); I != E; ++I) {
1106 const PointerValSet &PVS = I->second; // Set of things pointed to by scalar
1107
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001108 // Check to see if the scalar points to a data structure node...
1109 for (unsigned i = 0, e = PVS.size(); i != e; ++i) {
Chris Lattner0e0c15b2002-04-27 02:29:32 +00001110 if (PVS[i].Index) { cerr << "Problem in " << F->getName() << " for " << I->first << "\n"; }
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001111 assert(PVS[i].Index == 0 && "Nonzero not handled yet!");
1112
1113 // If the allocation is in the nonescaping set...
Chris Lattner441e16f2002-04-12 20:23:15 +00001114 map<DSNode*, PoolInfo>::iterator AI = PoolDescs.find(PVS[i].Node);
1115 if (AI != PoolDescs.end()) { // Add it to the list of scalars
1116 Scalars.push_back(ScalarInfo(I->first, AI->second));
Chris Lattneracf19022002-04-14 06:14:41 +00001117#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001118 cerr << "\nScalar Mapping from:" << I->first
1119 << "Scalar Mapping to: "; PVS.print(cerr);
Chris Lattneracf19022002-04-14 06:14:41 +00001120#endif
Chris Lattner441e16f2002-04-12 20:23:15 +00001121 }
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001122 }
1123 }
1124
Chris Lattneracf19022002-04-14 06:14:41 +00001125#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner847b6e22002-03-30 20:53:14 +00001126 cerr << "\nIn '" << F->getName()
Chris Lattner175f37c2002-03-29 03:40:59 +00001127 << "': Found the following values that point to poolable nodes:\n";
1128
1129 for (unsigned i = 0, e = Scalars.size(); i != e; ++i)
Chris Lattner441e16f2002-04-12 20:23:15 +00001130 cerr << Scalars[i].Val;
1131 cerr << "\n";
Chris Lattneracf19022002-04-14 06:14:41 +00001132#endif
Chris Lattnere0618ca2002-03-29 05:50:20 +00001133
Chris Lattner692ad5d2002-03-29 17:13:46 +00001134 // CallMap - Contain an entry for every call instruction that needs to be
1135 // transformed. Each entry in the map contains information about what we need
1136 // to do to each call site to change it to work.
1137 //
1138 map<CallInst*, TransformFunctionInfo> CallMap;
Chris Lattner66df97d2002-03-29 06:21:38 +00001139
Chris Lattner441e16f2002-04-12 20:23:15 +00001140 // Now we need to figure out what called functions we need to transform, and
Chris Lattner692ad5d2002-03-29 17:13:46 +00001141 // how. To do this, we look at all of the scalars, seeing which functions are
1142 // either used as a scalar value (so they return a data structure), or are
1143 // passed one of our scalar values.
1144 //
1145 for (unsigned i = 0, e = Scalars.size(); i != e; ++i) {
1146 Value *ScalarVal = Scalars[i].Val;
1147
1148 // Check to see if the scalar _IS_ a call...
1149 if (CallInst *CI = dyn_cast<CallInst>(ScalarVal))
1150 // If so, add information about the pool it will be returning...
Chris Lattner3e78dea2002-04-18 14:43:30 +00001151 CallMap[CI].addCallInfo(DS, CI, -1, Scalars[i].Pool.Node, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +00001152
1153 // Check to see if the scalar is an operand to a call...
1154 for (Value::use_iterator UI = ScalarVal->use_begin(),
1155 UE = ScalarVal->use_end(); UI != UE; ++UI) {
1156 if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
1157 // Find out which operand this is to the call instruction...
1158 User::op_iterator OI = find(CI->op_begin(), CI->op_end(), ScalarVal);
1159 assert(OI != CI->op_end() && "Call on use list but not an operand!?");
1160 assert(OI != CI->op_begin() && "Pointer operand is call destination?");
1161
1162 // FIXME: This is broken if the same pointer is passed to a call more
1163 // than once! It will get multiple entries for the first pointer.
1164
1165 // Add the operand number and pool handle to the call table...
Chris Lattner3e78dea2002-04-18 14:43:30 +00001166 CallMap[CI].addCallInfo(DS, CI, OI-CI->op_begin()-1,
1167 Scalars[i].Pool.Node, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +00001168 }
1169 }
1170 }
1171
Chris Lattner3e78dea2002-04-18 14:43:30 +00001172 // Make sure that all dependant arguments are added as well. For example, if
1173 // we call foo(null, P) and foo treats it's first and second arguments as
1174 // belonging to the same data structure, the we MUST set up the CallMap to
1175 // know that the null needs to be transformed into an index as well.
1176 //
1177 for (map<CallInst*, TransformFunctionInfo>::iterator I = CallMap.begin();
1178 I != CallMap.end(); ++I)
1179 I->second.ensureDependantArgumentsIncluded(DS, PoolDescs);
1180
Chris Lattneracf19022002-04-14 06:14:41 +00001181#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner692ad5d2002-03-29 17:13:46 +00001182 // Print out call map...
1183 for (map<CallInst*, TransformFunctionInfo>::iterator I = CallMap.begin();
1184 I != CallMap.end(); ++I) {
Chris Lattner441e16f2002-04-12 20:23:15 +00001185 cerr << "For call: " << I->first;
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001186 cerr << I->second.Func->getName() << " must pass pool pointer for args #";
Chris Lattner692ad5d2002-03-29 17:13:46 +00001187 for (unsigned i = 0; i < I->second.ArgInfo.size(); ++i)
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001188 cerr << I->second.ArgInfo[i].ArgNo << ", ";
Chris Lattner441e16f2002-04-12 20:23:15 +00001189 cerr << "\n\n";
Chris Lattner692ad5d2002-03-29 17:13:46 +00001190 }
Chris Lattneracf19022002-04-14 06:14:41 +00001191#endif
Chris Lattner692ad5d2002-03-29 17:13:46 +00001192
1193 // Loop through all of the call nodes, recursively creating the new functions
1194 // that we want to call... This uses a map to prevent infinite recursion and
1195 // to avoid duplicating functions unneccesarily.
1196 //
1197 for (map<CallInst*, TransformFunctionInfo>::iterator I = CallMap.begin(),
1198 E = CallMap.end(); I != E; ++I) {
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001199 // Transform all of the functions we need, or at least ensure there is a
1200 // cached version available.
Chris Lattner441e16f2002-04-12 20:23:15 +00001201 transformFunction(I->second, IPFGraph, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +00001202 }
1203
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001204 // Now that all of the functions that we want to call are available, transform
Chris Lattner441e16f2002-04-12 20:23:15 +00001205 // the local function so that it uses the pools locally and passes them to the
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001206 // functions that we just hacked up.
1207 //
1208
1209 // First step, find the instructions to be modified.
1210 vector<Instruction*> InstToFix;
1211 for (unsigned i = 0, e = Scalars.size(); i != e; ++i) {
1212 Value *ScalarVal = Scalars[i].Val;
1213
1214 // Check to see if the scalar _IS_ an instruction. If so, it is involved.
1215 if (Instruction *Inst = dyn_cast<Instruction>(ScalarVal))
1216 InstToFix.push_back(Inst);
1217
1218 // All all of the instructions that use the scalar as an operand...
1219 for (Value::use_iterator UI = ScalarVal->use_begin(),
1220 UE = ScalarVal->use_end(); UI != UE; ++UI)
Chris Lattner441e16f2002-04-12 20:23:15 +00001221 InstToFix.push_back(cast<Instruction>(*UI));
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001222 }
1223
Chris Lattner50e3d322002-04-13 23:13:18 +00001224 // Make sure that we get return instructions that return a null value from the
1225 // function...
1226 //
1227 if (!IPFGraph.getRetNodes().empty()) {
1228 assert(IPFGraph.getRetNodes().size() == 1 && "Can only return one node?");
1229 PointerVal RetNode = IPFGraph.getRetNodes()[0];
1230 assert(RetNode.Index == 0 && "Subindexing not implemented yet!");
1231
1232 // Only process return instructions if the return value of this function is
1233 // part of one of the data structures we are transforming...
1234 //
1235 if (PoolDescs.count(RetNode.Node)) {
1236 // Loop over all of the basic blocks, adding return instructions...
1237 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
Chris Lattner7076ff22002-06-25 16:13:21 +00001238 if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator()))
Chris Lattner50e3d322002-04-13 23:13:18 +00001239 InstToFix.push_back(RI);
1240 }
1241 }
1242
1243
1244
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001245 // Eliminate duplicates by sorting, then removing equal neighbors.
1246 sort(InstToFix.begin(), InstToFix.end());
1247 InstToFix.erase(unique(InstToFix.begin(), InstToFix.end()), InstToFix.end());
1248
Chris Lattner441e16f2002-04-12 20:23:15 +00001249 // Loop over all of the instructions to transform, creating the new
1250 // replacement instructions for them. This also unlinks them from the
1251 // function so they can be safely deleted later.
1252 //
1253 map<Value*, Value*> XFormMap;
1254 NewInstructionCreator NIC(*this, Scalars, CallMap, XFormMap);
Chris Lattner692ad5d2002-03-29 17:13:46 +00001255
Chris Lattner441e16f2002-04-12 20:23:15 +00001256 // Visit all instructions... creating the new instructions that we need and
1257 // unlinking the old instructions from the function...
1258 //
Chris Lattneracf19022002-04-14 06:14:41 +00001259#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001260 for (unsigned i = 0, e = InstToFix.size(); i != e; ++i) {
1261 cerr << "Fixing: " << InstToFix[i];
Chris Lattner7076ff22002-06-25 16:13:21 +00001262 NIC.visit(*InstToFix[i]);
Chris Lattner441e16f2002-04-12 20:23:15 +00001263 }
Chris Lattneracf19022002-04-14 06:14:41 +00001264#else
1265 NIC.visit(InstToFix.begin(), InstToFix.end());
1266#endif
Chris Lattner441e16f2002-04-12 20:23:15 +00001267
1268 // Make all instructions we will delete "let go" of their operands... so that
1269 // we can safely delete Arguments whose types have changed...
1270 //
1271 for_each(InstToFix.begin(), InstToFix.end(),
Anand Shukla2bc64192002-06-25 21:07:58 +00001272 std::mem_fun(&Instruction::dropAllReferences));
Chris Lattner441e16f2002-04-12 20:23:15 +00001273
1274 // Loop through all of the pointer arguments coming into the function,
1275 // replacing them with arguments of POINTERTYPE to match the function type of
1276 // the function.
1277 //
1278 FunctionType::ParamTypes::const_iterator TI =
1279 F->getFunctionType()->getParamTypes().begin();
Chris Lattner7076ff22002-06-25 16:13:21 +00001280 for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I, ++TI) {
1281 if (I->getType() != *TI) {
1282 assert(isa<PointerType>(I->getType()) && *TI == POINTERTYPE);
1283 Argument *NewArg = new Argument(*TI, I->getName());
1284 XFormMap[I] = NewArg; // Map old arg into new arg...
Chris Lattner441e16f2002-04-12 20:23:15 +00001285
Chris Lattner441e16f2002-04-12 20:23:15 +00001286 // Replace the old argument and then delete it...
Chris Lattner7076ff22002-06-25 16:13:21 +00001287 I = F->getArgumentList().erase(I);
1288 I = F->getArgumentList().insert(I, NewArg);
Chris Lattner441e16f2002-04-12 20:23:15 +00001289 }
1290 }
1291
1292 // Now that all of the new instructions have been created, we can update all
1293 // of the references to dummy values to be references to the actual values
1294 // that are computed.
1295 //
1296 NIC.updateReferences();
1297
Chris Lattneracf19022002-04-14 06:14:41 +00001298#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001299 cerr << "TRANSFORMED FUNCTION:\n" << F;
Chris Lattneracf19022002-04-14 06:14:41 +00001300#endif
Chris Lattner441e16f2002-04-12 20:23:15 +00001301
1302 // Delete all of the "instructions to fix"
1303 for_each(InstToFix.begin(), InstToFix.end(), deleter<Instruction>);
Chris Lattner692ad5d2002-03-29 17:13:46 +00001304
Chris Lattner457e1ac2002-04-15 22:42:23 +00001305 // Eliminate pool base loads that we can easily prove are redundant
1306 if (!DisableRLE)
1307 PoolBaseLoadEliminator(PoolDescs).visit(F);
1308
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001309 // Since we have liberally hacked the function to pieces, we want to inform
1310 // the datastructure pass that its internal representation is out of date.
1311 //
1312 DS->invalidateFunction(F);
Chris Lattner692ad5d2002-03-29 17:13:46 +00001313}
1314
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001315
1316
1317// transformFunction - Transform the specified function the specified way. It
1318// we have already transformed that function that way, don't do anything. The
1319// nodes in the TransformFunctionInfo come out of callers data structure graph.
1320//
1321void PoolAllocate::transformFunction(TransformFunctionInfo &TFI,
Chris Lattner441e16f2002-04-12 20:23:15 +00001322 FunctionDSGraph &CallerIPGraph,
1323 map<DSNode*, PoolInfo> &CallerPoolDesc) {
Chris Lattner692ad5d2002-03-29 17:13:46 +00001324 if (getTransformedFunction(TFI)) return; // Function xformation already done?
1325
Chris Lattneracf19022002-04-14 06:14:41 +00001326#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001327 cerr << "********** Entering transformFunction for "
Chris Lattner0dc225c2002-03-31 07:17:46 +00001328 << TFI.Func->getName() << ":\n";
1329 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i)
1330 cerr << " ArgInfo[" << i << "] = " << TFI.ArgInfo[i].ArgNo << "\n";
1331 cerr << "\n";
Chris Lattneracf19022002-04-14 06:14:41 +00001332#endif
Chris Lattner0dc225c2002-03-31 07:17:46 +00001333
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001334 const FunctionType *OldFuncType = TFI.Func->getFunctionType();
Chris Lattner692ad5d2002-03-29 17:13:46 +00001335
Chris Lattner291a1b12002-03-29 19:05:48 +00001336 assert(!OldFuncType->isVarArg() && "Vararg functions not handled yet!");
Chris Lattner692ad5d2002-03-29 17:13:46 +00001337
Chris Lattner291a1b12002-03-29 19:05:48 +00001338 // Build the type for the new function that we are transforming
1339 vector<const Type*> ArgTys;
Chris Lattner441e16f2002-04-12 20:23:15 +00001340 ArgTys.reserve(OldFuncType->getNumParams()+TFI.ArgInfo.size());
Chris Lattner291a1b12002-03-29 19:05:48 +00001341 for (unsigned i = 0, e = OldFuncType->getNumParams(); i != e; ++i)
1342 ArgTys.push_back(OldFuncType->getParamType(i));
1343
Chris Lattner441e16f2002-04-12 20:23:15 +00001344 const Type *RetType = OldFuncType->getReturnType();
1345
Chris Lattner291a1b12002-03-29 19:05:48 +00001346 // Add one pool pointer for every argument that needs to be supplemented.
Chris Lattner441e16f2002-04-12 20:23:15 +00001347 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i) {
1348 if (TFI.ArgInfo[i].ArgNo == -1)
1349 RetType = POINTERTYPE; // Return a pointer
1350 else
1351 ArgTys[TFI.ArgInfo[i].ArgNo] = POINTERTYPE; // Pass a pointer
1352 ArgTys.push_back(PointerType::get(CallerPoolDesc.find(TFI.ArgInfo[i].Node)
1353 ->second.PoolType));
1354 }
Chris Lattner291a1b12002-03-29 19:05:48 +00001355
1356 // Build the new function type...
Chris Lattner441e16f2002-04-12 20:23:15 +00001357 const FunctionType *NewFuncType = FunctionType::get(RetType, ArgTys,
1358 OldFuncType->isVarArg());
Chris Lattner291a1b12002-03-29 19:05:48 +00001359
1360 // The new function is internal, because we know that only we can call it.
1361 // This also helps subsequent IP transformations to eliminate duplicated pool
Chris Lattner441e16f2002-04-12 20:23:15 +00001362 // pointers (which look like the same value is always passed into a parameter,
1363 // allowing it to be easily eliminated).
Chris Lattner291a1b12002-03-29 19:05:48 +00001364 //
1365 Function *NewFunc = new Function(NewFuncType, true,
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001366 TFI.Func->getName()+".poolxform");
Chris Lattner291a1b12002-03-29 19:05:48 +00001367 CurModule->getFunctionList().push_back(NewFunc);
1368
Chris Lattner441e16f2002-04-12 20:23:15 +00001369
Chris Lattneracf19022002-04-14 06:14:41 +00001370#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001371 cerr << "Created function prototype: " << NewFunc << "\n";
Chris Lattneracf19022002-04-14 06:14:41 +00001372#endif
Chris Lattner441e16f2002-04-12 20:23:15 +00001373
Chris Lattner291a1b12002-03-29 19:05:48 +00001374 // Add the newly formed function to the TransformedFunctions table so that
1375 // infinite recursion does not occur!
1376 //
1377 TransformedFunctions[TFI] = NewFunc;
1378
1379 // Add arguments to the function... starting with all of the old arguments
1380 vector<Value*> ArgMap;
Chris Lattner7076ff22002-06-25 16:13:21 +00001381 for (Function::const_aiterator I = TFI.Func->abegin(), E = TFI.Func->aend();
1382 I != E; ++I) {
1383 Argument *NFA = new Argument(I->getType(), I->getName());
Chris Lattner291a1b12002-03-29 19:05:48 +00001384 NewFunc->getArgumentList().push_back(NFA);
1385 ArgMap.push_back(NFA); // Keep track of the arguments
1386 }
1387
1388 // Now add all of the arguments corresponding to pools passed in...
1389 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i) {
Chris Lattner441e16f2002-04-12 20:23:15 +00001390 CallArgInfo &AI = TFI.ArgInfo[i];
Chris Lattner291a1b12002-03-29 19:05:48 +00001391 string Name;
Chris Lattner441e16f2002-04-12 20:23:15 +00001392 if (AI.ArgNo == -1)
1393 Name = "ret";
Chris Lattner291a1b12002-03-29 19:05:48 +00001394 else
Chris Lattner441e16f2002-04-12 20:23:15 +00001395 Name = ArgMap[AI.ArgNo]->getName(); // Get the arg name
1396 const Type *Ty = PointerType::get(CallerPoolDesc[AI.Node].PoolType);
1397 Argument *NFA = new Argument(Ty, Name+".pool");
Chris Lattner291a1b12002-03-29 19:05:48 +00001398 NewFunc->getArgumentList().push_back(NFA);
1399 }
1400
1401 // Now clone the body of the old function into the new function...
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001402 CloneFunctionInto(NewFunc, TFI.Func, ArgMap);
Chris Lattner291a1b12002-03-29 19:05:48 +00001403
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001404 // Okay, now we have a function that is identical to the old one, except that
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001405 // it has extra arguments for the pools coming in. Now we have to get the
1406 // data structure graph for the function we are replacing, and figure out how
1407 // our graph nodes map to the graph nodes in the dest function.
1408 //
Chris Lattner847b6e22002-03-30 20:53:14 +00001409 FunctionDSGraph &DSGraph = DS->getClosedDSGraph(NewFunc);
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001410
Chris Lattner441e16f2002-04-12 20:23:15 +00001411 // NodeMapping - Multimap from callers graph to called graph. We are
1412 // guaranteed that the called function graph has more nodes than the caller,
1413 // or exactly the same number of nodes. This is because the called function
1414 // might not know that two nodes are merged when considering the callers
1415 // context, but the caller obviously does. Because of this, a single node in
1416 // the calling function's data structure graph can map to multiple nodes in
1417 // the called functions graph.
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001418 //
1419 map<DSNode*, PointerValSet> NodeMapping;
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001420
Chris Lattner847b6e22002-03-30 20:53:14 +00001421 CalculateNodeMapping(NewFunc, TFI, CallerIPGraph, DSGraph,
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001422 NodeMapping);
1423
1424 // Print out the node mapping...
Chris Lattneracf19022002-04-14 06:14:41 +00001425#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner847b6e22002-03-30 20:53:14 +00001426 cerr << "\nNode mapping for call of " << NewFunc->getName() << "\n";
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001427 for (map<DSNode*, PointerValSet>::iterator I = NodeMapping.begin();
1428 I != NodeMapping.end(); ++I) {
1429 cerr << "Map: "; I->first->print(cerr);
1430 cerr << "To: "; I->second.print(cerr);
1431 cerr << "\n";
1432 }
Chris Lattneracf19022002-04-14 06:14:41 +00001433#endif
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001434
1435 // Fill in the PoolDescriptor information for the transformed function so that
1436 // it can determine which value holds the pool descriptor for each data
1437 // structure node that it accesses.
1438 //
Chris Lattner441e16f2002-04-12 20:23:15 +00001439 map<DSNode*, PoolInfo> PoolDescs;
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001440
Chris Lattneracf19022002-04-14 06:14:41 +00001441#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner847b6e22002-03-30 20:53:14 +00001442 cerr << "\nCalculating the pool descriptor map:\n";
Chris Lattneracf19022002-04-14 06:14:41 +00001443#endif
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001444
Chris Lattner441e16f2002-04-12 20:23:15 +00001445 // Calculate as much of the pool descriptor map as possible. Since we have
1446 // the node mapping between the caller and callee functions, and we have the
1447 // pool descriptor information of the caller, we can calculate a partical pool
1448 // descriptor map for the called function.
1449 //
1450 // The nodes that we do not have complete information for are the ones that
1451 // are accessed by loading pointers derived from arguments passed in, but that
1452 // are not passed in directly. In this case, we have all of the information
1453 // except a pool value. If the called function refers to this pool, the pool
1454 // value will be loaded from the pool graph and added to the map as neccesary.
1455 //
1456 for (map<DSNode*, PointerValSet>::iterator I = NodeMapping.begin();
1457 I != NodeMapping.end(); ++I) {
1458 DSNode *CallerNode = I->first;
1459 PoolInfo &CallerPI = CallerPoolDesc[CallerNode];
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001460
Chris Lattner441e16f2002-04-12 20:23:15 +00001461 // Check to see if we have a node pointer passed in for this value...
1462 Value *CalleeValue = 0;
1463 for (unsigned a = 0, ae = TFI.ArgInfo.size(); a != ae; ++a)
1464 if (TFI.ArgInfo[a].Node == CallerNode) {
1465 // Calculate the argument number that the pool is to the function
1466 // call... The call instruction should not have the pool operands added
1467 // yet.
1468 unsigned ArgNo = TFI.Call->getNumOperands()-1+a;
Chris Lattneracf19022002-04-14 06:14:41 +00001469#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001470 cerr << "Should be argument #: " << ArgNo << "[i = " << a << "]\n";
Chris Lattneracf19022002-04-14 06:14:41 +00001471#endif
Chris Lattner7076ff22002-06-25 16:13:21 +00001472 assert(ArgNo < NewFunc->asize() &&
Chris Lattner441e16f2002-04-12 20:23:15 +00001473 "Call already has pool arguments added??");
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001474
Chris Lattner441e16f2002-04-12 20:23:15 +00001475 // Map the pool argument into the called function...
Chris Lattner7076ff22002-06-25 16:13:21 +00001476 Function::aiterator AI = NewFunc->abegin();
1477 std::advance(AI, ArgNo);
1478 CalleeValue = AI;
Chris Lattner441e16f2002-04-12 20:23:15 +00001479 break; // Found value, quit loop
1480 }
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001481
Chris Lattner441e16f2002-04-12 20:23:15 +00001482 // Loop over all of the data structure nodes that this incoming node maps to
1483 // Creating a PoolInfo structure for them.
1484 for (unsigned i = 0, e = I->second.size(); i != e; ++i) {
1485 assert(I->second[i].Index == 0 && "Doesn't handle subindexing yet!");
1486 DSNode *CalleeNode = I->second[i].Node;
1487
1488 // Add the descriptor. We already know everything about it by now, much
1489 // of it is the same as the caller info.
1490 //
Anand Shukla2bc64192002-06-25 21:07:58 +00001491 PoolDescs.insert(std::make_pair(CalleeNode,
Chris Lattner441e16f2002-04-12 20:23:15 +00001492 PoolInfo(CalleeNode, CalleeValue,
1493 CallerPI.NewType,
1494 CallerPI.PoolType)));
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001495 }
Chris Lattner847b6e22002-03-30 20:53:14 +00001496 }
1497
1498 // We must destroy the node mapping so that we don't have latent references
1499 // into the data structure graph for the new function. Otherwise we get
1500 // assertion failures when transformFunctionBody tries to invalidate the
1501 // graph.
1502 //
1503 NodeMapping.clear();
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001504
1505 // Now that we know everything we need about the function, transform the body
1506 // now!
1507 //
Chris Lattner441e16f2002-04-12 20:23:15 +00001508 transformFunctionBody(NewFunc, DSGraph, PoolDescs);
1509
Chris Lattneracf19022002-04-14 06:14:41 +00001510#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001511 cerr << "Function after transformation:\n" << NewFunc;
Chris Lattneracf19022002-04-14 06:14:41 +00001512#endif
Chris Lattner66df97d2002-03-29 06:21:38 +00001513}
1514
Chris Lattner8f796d62002-04-13 19:25:57 +00001515static unsigned countPointerTypes(const Type *Ty) {
1516 if (isa<PointerType>(Ty)) {
1517 return 1;
Chris Lattner7076ff22002-06-25 16:13:21 +00001518 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
Chris Lattner8f796d62002-04-13 19:25:57 +00001519 unsigned Num = 0;
1520 for (unsigned i = 0, e = STy->getElementTypes().size(); i != e; ++i)
1521 Num += countPointerTypes(STy->getElementTypes()[i]);
1522 return Num;
Chris Lattner7076ff22002-06-25 16:13:21 +00001523 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
Chris Lattner8f796d62002-04-13 19:25:57 +00001524 return countPointerTypes(ATy->getElementType());
1525 } else {
1526 assert(Ty->isPrimitiveType() && "Unknown derived type!");
1527 return 0;
1528 }
1529}
Chris Lattner66df97d2002-03-29 06:21:38 +00001530
1531// CreatePools - Insert instructions into the function we are processing to
1532// create all of the memory pool objects themselves. This also inserts
1533// destruction code. Add an alloca for each pool that is allocated to the
Chris Lattner441e16f2002-04-12 20:23:15 +00001534// PoolDescs vector.
Chris Lattner66df97d2002-03-29 06:21:38 +00001535//
1536void PoolAllocate::CreatePools(Function *F, const vector<AllocDSNode*> &Allocs,
Chris Lattner441e16f2002-04-12 20:23:15 +00001537 map<DSNode*, PoolInfo> &PoolDescs) {
1538 // Find all of the return nodes in the function...
Chris Lattnere0618ca2002-03-29 05:50:20 +00001539 vector<BasicBlock*> ReturnNodes;
1540 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
Chris Lattner7076ff22002-06-25 16:13:21 +00001541 if (isa<ReturnInst>(I->getTerminator()))
1542 ReturnNodes.push_back(I);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001543
Chris Lattner3e78dea2002-04-18 14:43:30 +00001544#ifdef DEBUG_CREATE_POOLS
1545 cerr << "Allocs that we are pool allocating:\n";
1546 for (unsigned i = 0, e = Allocs.size(); i != e; ++i)
1547 Allocs[i]->dump();
1548#endif
1549
Chris Lattner441e16f2002-04-12 20:23:15 +00001550 map<DSNode*, PATypeHolder> AbsPoolTyMap;
1551
1552 // First pass over the allocations to process...
1553 for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
1554 // Create the pooldescriptor mapping... with null entries for everything
1555 // except the node & NewType fields.
1556 //
1557 map<DSNode*, PoolInfo>::iterator PI =
Anand Shukla2bc64192002-06-25 21:07:58 +00001558 PoolDescs.insert(std::make_pair(Allocs[i], PoolInfo(Allocs[i]))).first;
Chris Lattner441e16f2002-04-12 20:23:15 +00001559
Chris Lattner8f796d62002-04-13 19:25:57 +00001560 // Add a symbol table entry for the new type if there was one for the old
1561 // type...
1562 string OldName = CurModule->getTypeName(Allocs[i]->getType());
Chris Lattner0e0c15b2002-04-27 02:29:32 +00001563 if (OldName.empty()) OldName = "node";
1564 CurModule->addTypeName(OldName+".p", PI->second.NewType);
Chris Lattner8f796d62002-04-13 19:25:57 +00001565
Chris Lattner441e16f2002-04-12 20:23:15 +00001566 // Create the abstract pool types that will need to be resolved in a second
1567 // pass once an abstract type is created for each pool.
1568 //
1569 // Can only handle limited shapes for now...
Chris Lattner0e0c15b2002-04-27 02:29:32 +00001570 const Type *OldNodeTy = Allocs[i]->getType();
Chris Lattner441e16f2002-04-12 20:23:15 +00001571 vector<const Type*> PoolTypes;
1572
1573 // Pool type is the first element of the pool descriptor type...
1574 PoolTypes.push_back(getPoolType(PoolDescs[Allocs[i]].NewType));
Chris Lattner8f796d62002-04-13 19:25:57 +00001575
1576 unsigned NumPointers = countPointerTypes(OldNodeTy);
1577 while (NumPointers--) // Add a different opaque type for each pointer
1578 PoolTypes.push_back(OpaqueType::get());
1579
Chris Lattner441e16f2002-04-12 20:23:15 +00001580 assert(Allocs[i]->getNumLinks() == PoolTypes.size()-1 &&
1581 "Node should have same number of pointers as pool!");
1582
Chris Lattner8f796d62002-04-13 19:25:57 +00001583 StructType *PoolType = StructType::get(PoolTypes);
1584
1585 // Add a symbol table entry for the pooltype if possible...
Chris Lattner0e0c15b2002-04-27 02:29:32 +00001586 CurModule->addTypeName(OldName+".pool", PoolType);
Chris Lattner8f796d62002-04-13 19:25:57 +00001587
Chris Lattner441e16f2002-04-12 20:23:15 +00001588 // Create the pool type, with opaque values for pointers...
Anand Shukla2bc64192002-06-25 21:07:58 +00001589 AbsPoolTyMap.insert(std::make_pair(Allocs[i], PoolType));
Chris Lattner441e16f2002-04-12 20:23:15 +00001590#ifdef DEBUG_CREATE_POOLS
1591 cerr << "POOL TY: " << AbsPoolTyMap.find(Allocs[i])->second.get() << "\n";
1592#endif
1593 }
1594
1595 // Now that we have types for all of the pool types, link them all together.
1596 for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
1597 PATypeHolder &PoolTyH = AbsPoolTyMap.find(Allocs[i])->second;
1598
1599 // Resolve all of the outgoing pointer types of this pool node...
1600 for (unsigned p = 0, pe = Allocs[i]->getNumLinks(); p != pe; ++p) {
1601 PointerValSet &PVS = Allocs[i]->getLink(p);
1602 assert(!PVS.empty() && "Outgoing edge is empty, field unused, can"
1603 " probably just leave the type opaque or something dumb.");
1604 unsigned Out;
1605 for (Out = 0; AbsPoolTyMap.count(PVS[Out].Node) == 0; ++Out)
1606 assert(Out != PVS.size() && "No edge to an outgoing allocation node!?");
1607
1608 assert(PVS[Out].Index == 0 && "Subindexing not implemented yet!");
1609
1610 // The actual struct type could change each time through the loop, so it's
1611 // NOT loop invariant.
Chris Lattner7076ff22002-06-25 16:13:21 +00001612 const StructType *PoolTy = cast<StructType>(PoolTyH.get());
Chris Lattner441e16f2002-04-12 20:23:15 +00001613
1614 // Get the opaque type...
Chris Lattner7076ff22002-06-25 16:13:21 +00001615 DerivedType *ElTy = (DerivedType*)(PoolTy->getElementTypes()[p+1].get());
Chris Lattner441e16f2002-04-12 20:23:15 +00001616
1617#ifdef DEBUG_CREATE_POOLS
1618 cerr << "Refining " << ElTy << " of " << PoolTy << " to "
1619 << AbsPoolTyMap.find(PVS[Out].Node)->second.get() << "\n";
1620#endif
1621
1622 const Type *RefPoolTy = AbsPoolTyMap.find(PVS[Out].Node)->second.get();
1623 ElTy->refineAbstractTypeTo(PointerType::get(RefPoolTy));
1624
1625#ifdef DEBUG_CREATE_POOLS
1626 cerr << "Result pool type is: " << PoolTyH.get() << "\n";
1627#endif
1628 }
1629 }
1630
1631 // Create the code that goes in the entry and exit nodes for the function...
Chris Lattnere0618ca2002-03-29 05:50:20 +00001632 vector<Instruction*> EntryNodeInsts;
1633 for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
Chris Lattner441e16f2002-04-12 20:23:15 +00001634 PoolInfo &PI = PoolDescs[Allocs[i]];
1635
1636 // Fill in the pool type for this pool...
1637 PI.PoolType = AbsPoolTyMap.find(Allocs[i])->second.get();
1638 assert(!PI.PoolType->isAbstract() &&
1639 "Pool type should not be abstract anymore!");
1640
Chris Lattnere0618ca2002-03-29 05:50:20 +00001641 // Add an allocation and a free for each pool...
Chris Lattnerfc91ee92002-09-13 22:28:50 +00001642 AllocaInst *PoolAlloc = new AllocaInst(PI.PoolType, 0,
1643 CurModule->getTypeName(PI.PoolType));
Chris Lattner441e16f2002-04-12 20:23:15 +00001644 PI.Handle = PoolAlloc;
Chris Lattnere0618ca2002-03-29 05:50:20 +00001645 EntryNodeInsts.push_back(PoolAlloc);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001646 AllocationInst *AI = Allocs[i]->getAllocation();
1647
1648 // Initialize the pool. We need to know how big each allocation is. For
1649 // our purposes here, we assume we are allocating a scalar, or array of
1650 // constant size.
1651 //
Chris Lattneracf19022002-04-14 06:14:41 +00001652 unsigned ElSize = TargetData.getTypeSize(PI.NewType);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001653
1654 vector<Value*> Args;
Chris Lattnere0618ca2002-03-29 05:50:20 +00001655 Args.push_back(ConstantUInt::get(Type::UIntTy, ElSize));
Chris Lattner441e16f2002-04-12 20:23:15 +00001656 Args.push_back(PoolAlloc); // Pool to initialize
Chris Lattnere0618ca2002-03-29 05:50:20 +00001657 EntryNodeInsts.push_back(new CallInst(PoolInit, Args));
1658
Chris Lattner441e16f2002-04-12 20:23:15 +00001659 // Add code to destroy the pool in all of the exit nodes of the function...
Chris Lattner8f796d62002-04-13 19:25:57 +00001660 Args.clear();
1661 Args.push_back(PoolAlloc); // Pool to initialize
1662
Chris Lattnere0618ca2002-03-29 05:50:20 +00001663 for (unsigned EN = 0, ENE = ReturnNodes.size(); EN != ENE; ++EN) {
1664 Instruction *Destroy = new CallInst(PoolDestroy, Args);
1665
1666 // Insert it before the return instruction...
1667 BasicBlock *RetNode = ReturnNodes[EN];
Chris Lattner7076ff22002-06-25 16:13:21 +00001668 RetNode->getInstList().insert(RetNode->end()--, Destroy);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001669 }
1670 }
1671
Chris Lattner5da145b2002-04-13 19:52:54 +00001672 // Now that all of the pool descriptors have been created, link them together
1673 // so that called functions can get links as neccesary...
1674 //
1675 for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
1676 PoolInfo &PI = PoolDescs[Allocs[i]];
1677
1678 // For every pointer in the data structure, initialize a link that
1679 // indicates which pool to access...
1680 //
1681 vector<Value*> Indices(2);
1682 Indices[0] = ConstantUInt::get(Type::UIntTy, 0);
1683 for (unsigned l = 0, le = PI.Node->getNumLinks(); l != le; ++l)
1684 // Only store an entry for the field if the field is used!
1685 if (!PI.Node->getLink(l).empty()) {
1686 assert(PI.Node->getLink(l).size() == 1 && "Should have only one link!");
1687 PointerVal PV = PI.Node->getLink(l)[0];
1688 assert(PV.Index == 0 && "Subindexing not supported yet!");
1689 PoolInfo &LinkedPool = PoolDescs[PV.Node];
1690 Indices[1] = ConstantUInt::get(Type::UByteTy, 1+l);
1691
1692 EntryNodeInsts.push_back(new StoreInst(LinkedPool.Handle, PI.Handle,
1693 Indices));
1694 }
1695 }
1696
Chris Lattnere0618ca2002-03-29 05:50:20 +00001697 // Insert the entry node code into the entry block...
Chris Lattner7076ff22002-06-25 16:13:21 +00001698 F->getEntryNode().getInstList().insert(++F->getEntryNode().begin(),
Chris Lattnere0618ca2002-03-29 05:50:20 +00001699 EntryNodeInsts.begin(),
1700 EntryNodeInsts.end());
Chris Lattner175f37c2002-03-29 03:40:59 +00001701}
1702
1703
Chris Lattner441e16f2002-04-12 20:23:15 +00001704// addPoolPrototypes - Add prototypes for the pool functions to the specified
Chris Lattner175f37c2002-03-29 03:40:59 +00001705// module and update the Pool* instance variables to point to them.
1706//
Chris Lattner7076ff22002-06-25 16:13:21 +00001707void PoolAllocate::addPoolPrototypes(Module &M) {
Chris Lattner441e16f2002-04-12 20:23:15 +00001708 // Get poolinit function...
Chris Lattnere0618ca2002-03-29 05:50:20 +00001709 vector<const Type*> Args;
Chris Lattnere0618ca2002-03-29 05:50:20 +00001710 Args.push_back(Type::UIntTy); // Num bytes per element
Chris Lattner441e16f2002-04-12 20:23:15 +00001711 FunctionType *PoolInitTy = FunctionType::get(Type::VoidTy, Args, true);
Chris Lattner7076ff22002-06-25 16:13:21 +00001712 PoolInit = M.getOrInsertFunction("poolinit", PoolInitTy);
Chris Lattner175f37c2002-03-29 03:40:59 +00001713
Chris Lattnere0618ca2002-03-29 05:50:20 +00001714 // Get pooldestroy function...
1715 Args.pop_back(); // Only takes a pool...
Chris Lattner441e16f2002-04-12 20:23:15 +00001716 FunctionType *PoolDestroyTy = FunctionType::get(Type::VoidTy, Args, true);
Chris Lattner7076ff22002-06-25 16:13:21 +00001717 PoolDestroy = M.getOrInsertFunction("pooldestroy", PoolDestroyTy);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001718
Chris Lattnere0618ca2002-03-29 05:50:20 +00001719 // Get the poolalloc function...
Chris Lattner441e16f2002-04-12 20:23:15 +00001720 FunctionType *PoolAllocTy = FunctionType::get(POINTERTYPE, Args, true);
Chris Lattner7076ff22002-06-25 16:13:21 +00001721 PoolAlloc = M.getOrInsertFunction("poolalloc", PoolAllocTy);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001722
1723 // Get the poolfree function...
Chris Lattner441e16f2002-04-12 20:23:15 +00001724 Args.push_back(POINTERTYPE); // Pointer to free
1725 FunctionType *PoolFreeTy = FunctionType::get(Type::VoidTy, Args, true);
Chris Lattner7076ff22002-06-25 16:13:21 +00001726 PoolFree = M.getOrInsertFunction("poolfree", PoolFreeTy);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001727
Chris Lattner0e0c15b2002-04-27 02:29:32 +00001728 Args[0] = Type::UIntTy; // Number of slots to allocate
1729 FunctionType *PoolAllocArrayTy = FunctionType::get(POINTERTYPE, Args, true);
Chris Lattner7076ff22002-06-25 16:13:21 +00001730 PoolAllocArray = M.getOrInsertFunction("poolallocarray", PoolAllocArrayTy);
Chris Lattner175f37c2002-03-29 03:40:59 +00001731}
1732
1733
Chris Lattner7076ff22002-06-25 16:13:21 +00001734bool PoolAllocate::run(Module &M) {
Chris Lattner175f37c2002-03-29 03:40:59 +00001735 addPoolPrototypes(M);
Chris Lattner7076ff22002-06-25 16:13:21 +00001736 CurModule = &M;
Chris Lattner175f37c2002-03-29 03:40:59 +00001737
1738 DS = &getAnalysis<DataStructure>();
1739 bool Changed = false;
Chris Lattner291a1b12002-03-29 19:05:48 +00001740
Chris Lattner7076ff22002-06-25 16:13:21 +00001741 for (Module::iterator I = M.begin(); I != M.end(); ++I)
1742 if (!I->isExternal()) {
1743 Changed |= processFunction(I);
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001744 if (Changed) {
1745 cerr << "Only processing one function\n";
1746 break;
1747 }
1748 }
Chris Lattner175f37c2002-03-29 03:40:59 +00001749
1750 CurModule = 0;
1751 DS = 0;
1752 return false;
1753}
Chris Lattner87d180e2002-07-10 22:36:47 +00001754#endif
Chris Lattner175f37c2002-03-29 03:40:59 +00001755
1756// createPoolAllocatePass - Global function to access the functionality of this
1757// pass...
1758//
Chris Lattner87d180e2002-07-10 22:36:47 +00001759Pass *createPoolAllocatePass() {
1760 assert(0 && "Pool allocator disabled!");
Chris Lattner10073a92002-07-25 06:17:51 +00001761 return 0;
Chris Lattner87d180e2002-07-10 22:36:47 +00001762 //return new PoolAllocate();
1763}