blob: 0620d1d02d9cda30c153ccc89639fc23989b81c7 [file] [log] [blame]
Chris Lattner64fd9352002-03-28 18:08:31 +00001//===-- PoolAllocate.cpp - Pool Allocation Pass ---------------------------===//
2//
3// This transform changes programs so that disjoint data structures are
4// allocated out of different pools of memory, increasing locality and shrinking
5// pointer size.
6//
Chris Lattner457e1ac2002-04-15 22:42:23 +00007// This pass requires a DCE & instcombine pass to be run after it for best
8// results.
9//
Chris Lattner64fd9352002-03-28 18:08:31 +000010//===----------------------------------------------------------------------===//
11
12#include "llvm/Transforms/IPO/PoolAllocate.h"
Chris Lattner291a1b12002-03-29 19:05:48 +000013#include "llvm/Transforms/CloneFunction.h"
Chris Lattner64fd9352002-03-28 18:08:31 +000014#include "llvm/Analysis/DataStructure.h"
Chris Lattner396d5d72002-03-30 04:02:31 +000015#include "llvm/Analysis/DataStructureGraph.h"
Chris Lattner175f37c2002-03-29 03:40:59 +000016#include "llvm/Module.h"
17#include "llvm/Function.h"
Chris Lattnerd92b01c2002-04-09 18:37:46 +000018#include "llvm/BasicBlock.h"
Chris Lattner175f37c2002-03-29 03:40:59 +000019#include "llvm/iMemory.h"
Chris Lattnere0618ca2002-03-29 05:50:20 +000020#include "llvm/iTerminators.h"
Chris Lattner441e16f2002-04-12 20:23:15 +000021#include "llvm/iPHINode.h"
Chris Lattnere0618ca2002-03-29 05:50:20 +000022#include "llvm/iOther.h"
Chris Lattner441e16f2002-04-12 20:23:15 +000023#include "llvm/DerivedTypes.h"
Chris Lattnere0618ca2002-03-29 05:50:20 +000024#include "llvm/ConstantVals.h"
25#include "llvm/Target/TargetData.h"
Chris Lattnerf32d65d2002-03-29 21:25:19 +000026#include "llvm/Support/InstVisitor.h"
Chris Lattner2e9fa6d2002-04-09 19:48:49 +000027#include "llvm/Argument.h"
Chris Lattner396d5d72002-03-30 04:02:31 +000028#include "Support/DepthFirstIterator.h"
Chris Lattnere0618ca2002-03-29 05:50:20 +000029#include "Support/STLExtras.h"
Chris Lattner175f37c2002-03-29 03:40:59 +000030#include <algorithm>
Chris Lattner64fd9352002-03-28 18:08:31 +000031
Chris Lattner441e16f2002-04-12 20:23:15 +000032// DEBUG_CREATE_POOLS - Enable this to turn on debug output for the pool
33// creation phase in the top level function of a transformed data structure.
34//
Chris Lattneracf19022002-04-14 06:14:41 +000035//#define DEBUG_CREATE_POOLS 1
36
37// DEBUG_TRANSFORM_PROGRESS - Enable this to get lots of debug output on what
38// the transformation is doing.
39//
40//#define DEBUG_TRANSFORM_PROGRESS 1
Chris Lattner441e16f2002-04-12 20:23:15 +000041
Chris Lattner457e1ac2002-04-15 22:42:23 +000042// DEBUG_POOLBASE_LOAD_ELIMINATOR - Turn this on to get statistics about how
43// many static loads were eliminated from a function...
44//
45#define DEBUG_POOLBASE_LOAD_ELIMINATOR 1
46
Chris Lattner50e3d322002-04-13 23:13:18 +000047#include "Support/CommandLine.h"
48enum PtrSize {
49 Ptr8bits, Ptr16bits, Ptr32bits
50};
51
52static cl::Enum<enum PtrSize> ReqPointerSize("ptrsize", 0,
Chris Lattneracf19022002-04-14 06:14:41 +000053 "Set pointer size for -poolalloc pass",
Chris Lattner50e3d322002-04-13 23:13:18 +000054 clEnumValN(Ptr32bits, "32", "Use 32 bit indices for pointers"),
55 clEnumValN(Ptr16bits, "16", "Use 16 bit indices for pointers"),
56 clEnumValN(Ptr8bits , "8", "Use 8 bit indices for pointers"), 0);
57
Chris Lattner457e1ac2002-04-15 22:42:23 +000058static cl::Flag DisableRLE("no-pool-load-elim", "Disable pool load elimination after poolalloc pass", cl::Hidden);
59
Chris Lattner441e16f2002-04-12 20:23:15 +000060const Type *POINTERTYPE;
Chris Lattner692ad5d2002-03-29 17:13:46 +000061
Chris Lattnere0618ca2002-03-29 05:50:20 +000062// FIXME: This is dependant on the sparc backend layout conventions!!
63static TargetData TargetData("test");
64
Chris Lattner50e3d322002-04-13 23:13:18 +000065static const Type *getPointerTransformedType(const Type *Ty) {
66 if (PointerType *PT = dyn_cast<PointerType>(Ty)) {
67 return POINTERTYPE;
68 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
69 vector<const Type *> NewElTypes;
70 NewElTypes.reserve(STy->getElementTypes().size());
71 for (StructType::ElementTypes::const_iterator
72 I = STy->getElementTypes().begin(),
73 E = STy->getElementTypes().end(); I != E; ++I)
74 NewElTypes.push_back(getPointerTransformedType(*I));
75 return StructType::get(NewElTypes);
76 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
77 return ArrayType::get(getPointerTransformedType(ATy->getElementType()),
78 ATy->getNumElements());
79 } else {
80 assert(Ty->isPrimitiveType() && "Unknown derived type!");
81 return Ty;
82 }
83}
84
Chris Lattner64fd9352002-03-28 18:08:31 +000085namespace {
Chris Lattner441e16f2002-04-12 20:23:15 +000086 struct PoolInfo {
87 DSNode *Node; // The node this pool allocation represents
88 Value *Handle; // LLVM value of the pool in the current context
89 const Type *NewType; // The transformed type of the memory objects
90 const Type *PoolType; // The type of the pool
91
92 const Type *getOldType() const { return Node->getType(); }
93
94 PoolInfo() { // Define a default ctor for map::operator[]
95 cerr << "Map subscript used to get element that doesn't exist!\n";
96 abort(); // Invalid
97 }
98
99 PoolInfo(DSNode *N, Value *H, const Type *NT, const Type *PT)
100 : Node(N), Handle(H), NewType(NT), PoolType(PT) {
101 // Handle can be null...
102 assert(N && NT && PT && "Pool info null!");
103 }
104
105 PoolInfo(DSNode *N) : Node(N), Handle(0), NewType(0), PoolType(0) {
106 assert(N && "Invalid pool info!");
107
108 // The new type of the memory object is the same as the old type, except
109 // that all of the pointer values are replaced with POINTERTYPE values.
Chris Lattner50e3d322002-04-13 23:13:18 +0000110 NewType = getPointerTransformedType(getOldType());
Chris Lattner441e16f2002-04-12 20:23:15 +0000111 }
112 };
113
Chris Lattner692ad5d2002-03-29 17:13:46 +0000114 // ScalarInfo - Information about an LLVM value that we know points to some
115 // datastructure we are processing.
116 //
117 struct ScalarInfo {
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000118 Value *Val; // Scalar value in Current Function
Chris Lattner441e16f2002-04-12 20:23:15 +0000119 PoolInfo Pool; // The pool the scalar points into
Chris Lattner692ad5d2002-03-29 17:13:46 +0000120
Chris Lattner441e16f2002-04-12 20:23:15 +0000121 ScalarInfo(Value *V, const PoolInfo &PI) : Val(V), Pool(PI) {
122 assert(V && "Null value passed to ScalarInfo ctor!");
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000123 }
Chris Lattner692ad5d2002-03-29 17:13:46 +0000124 };
125
Chris Lattner396d5d72002-03-30 04:02:31 +0000126 // CallArgInfo - Information on one operand for a call that got expanded.
127 struct CallArgInfo {
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000128 int ArgNo; // Call argument number this corresponds to
129 DSNode *Node; // The graph node for the pool
130 Value *PoolHandle; // The LLVM value that is the pool pointer
Chris Lattner396d5d72002-03-30 04:02:31 +0000131
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000132 CallArgInfo(int Arg, DSNode *N, Value *PH)
133 : ArgNo(Arg), Node(N), PoolHandle(PH) {
134 assert(Arg >= -1 && N && PH && "Illegal values to CallArgInfo ctor!");
Chris Lattner396d5d72002-03-30 04:02:31 +0000135 }
136
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000137 // operator< when sorting, sort by argument number.
Chris Lattner396d5d72002-03-30 04:02:31 +0000138 bool operator<(const CallArgInfo &CAI) const {
139 return ArgNo < CAI.ArgNo;
140 }
141 };
142
Chris Lattner692ad5d2002-03-29 17:13:46 +0000143 // TransformFunctionInfo - Information about how a function eeds to be
144 // transformed.
145 //
146 struct TransformFunctionInfo {
147 // ArgInfo - Maintain information about the arguments that need to be
Chris Lattner441e16f2002-04-12 20:23:15 +0000148 // processed. Each CallArgInfo corresponds to an argument that needs to
149 // have a pool pointer passed into the transformed function with it.
Chris Lattner692ad5d2002-03-29 17:13:46 +0000150 //
151 // As a special case, "argument" number -1 corresponds to the return value.
152 //
Chris Lattner396d5d72002-03-30 04:02:31 +0000153 vector<CallArgInfo> ArgInfo;
Chris Lattner692ad5d2002-03-29 17:13:46 +0000154
155 // Func - The function to be transformed...
156 Function *Func;
157
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000158 // The call instruction that is used to map CallArgInfo PoolHandle values
159 // into the new function values.
160 CallInst *Call;
161
Chris Lattner692ad5d2002-03-29 17:13:46 +0000162 // default ctor...
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000163 TransformFunctionInfo() : Func(0), Call(0) {}
Chris Lattner692ad5d2002-03-29 17:13:46 +0000164
Chris Lattner396d5d72002-03-30 04:02:31 +0000165 bool operator<(const TransformFunctionInfo &TFI) const {
Chris Lattner291a1b12002-03-29 19:05:48 +0000166 if (Func < TFI.Func) return true;
167 if (Func > TFI.Func) return false;
Chris Lattner291a1b12002-03-29 19:05:48 +0000168 if (ArgInfo.size() < TFI.ArgInfo.size()) return true;
169 if (ArgInfo.size() > TFI.ArgInfo.size()) return false;
Chris Lattner396d5d72002-03-30 04:02:31 +0000170 return ArgInfo < TFI.ArgInfo;
Chris Lattner692ad5d2002-03-29 17:13:46 +0000171 }
172
173 void finalizeConstruction() {
174 // Sort the vector so that the return value is first, followed by the
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000175 // argument records, in order. Note that this must be a stable sort so
176 // that the entries with the same sorting criteria (ie they are multiple
177 // pool entries for the same argument) are kept in depth first order.
178 stable_sort(ArgInfo.begin(), ArgInfo.end());
Chris Lattner692ad5d2002-03-29 17:13:46 +0000179 }
Chris Lattner3e78dea2002-04-18 14:43:30 +0000180
181 // addCallInfo - For a specified function call CI, figure out which pool
182 // descriptors need to be passed in as arguments, and which arguments need
183 // to be transformed into indices. If Arg != -1, the specified call
184 // argument is passed in as a pointer to a data structure.
185 //
186 void addCallInfo(DataStructure *DS, CallInst *CI, int Arg,
187 DSNode *GraphNode, map<DSNode*, PoolInfo> &PoolDescs);
188
189 // Make sure that all dependant arguments are added to this transformation
190 // info. For example, if we call foo(null, P) and foo treats it's first and
191 // second arguments as belonging to the same data structure, the we MUST add
192 // entries to know that the null needs to be transformed into an index as
193 // well.
194 //
195 void ensureDependantArgumentsIncluded(DataStructure *DS,
196 map<DSNode*, PoolInfo> &PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000197 };
198
199
200 // Define the pass class that we implement...
Chris Lattner441e16f2002-04-12 20:23:15 +0000201 struct PoolAllocate : public Pass {
Chris Lattner175f37c2002-03-29 03:40:59 +0000202 PoolAllocate() {
Chris Lattner50e3d322002-04-13 23:13:18 +0000203 switch (ReqPointerSize) {
204 case Ptr32bits: POINTERTYPE = Type::UIntTy; break;
205 case Ptr16bits: POINTERTYPE = Type::UShortTy; break;
206 case Ptr8bits: POINTERTYPE = Type::UByteTy; break;
207 }
Chris Lattner175f37c2002-03-29 03:40:59 +0000208
209 CurModule = 0; DS = 0;
210 PoolInit = PoolDestroy = PoolAlloc = PoolFree = 0;
Chris Lattner64fd9352002-03-28 18:08:31 +0000211 }
212
Chris Lattner441e16f2002-04-12 20:23:15 +0000213 // getPoolType - Get the type used by the backend for a pool of a particular
214 // type. This pool record is used to allocate nodes of type NodeType.
215 //
216 // Here, PoolTy = { NodeType*, sbyte*, uint }*
217 //
218 const StructType *getPoolType(const Type *NodeType) {
219 vector<const Type*> PoolElements;
220 PoolElements.push_back(PointerType::get(NodeType));
221 PoolElements.push_back(PointerType::get(Type::SByteTy));
222 PoolElements.push_back(Type::UIntTy);
Chris Lattner8f796d62002-04-13 19:25:57 +0000223 StructType *Result = StructType::get(PoolElements);
224
225 // Add a name to the symbol table to correspond to the backend
226 // representation of this pool...
227 assert(CurModule && "No current module!?");
228 string Name = CurModule->getTypeName(NodeType);
229 if (Name.empty()) Name = CurModule->getTypeName(PoolElements[0]);
230 CurModule->addTypeName(Name+"oolbe", Result);
231
232 return Result;
Chris Lattner441e16f2002-04-12 20:23:15 +0000233 }
234
Chris Lattner175f37c2002-03-29 03:40:59 +0000235 bool run(Module *M);
236
237 // getAnalysisUsageInfo - This function requires data structure information
238 // to be able to see what is pool allocatable.
Chris Lattner64fd9352002-03-28 18:08:31 +0000239 //
240 virtual void getAnalysisUsageInfo(Pass::AnalysisSet &Required,
Chris Lattner175f37c2002-03-29 03:40:59 +0000241 Pass::AnalysisSet &,Pass::AnalysisSet &) {
Chris Lattner64fd9352002-03-28 18:08:31 +0000242 Required.push_back(DataStructure::ID);
243 }
Chris Lattner175f37c2002-03-29 03:40:59 +0000244
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000245 public:
Chris Lattner175f37c2002-03-29 03:40:59 +0000246 // CurModule - The module being processed.
247 Module *CurModule;
248
249 // DS - The data structure graph for the module being processed.
250 DataStructure *DS;
251
252 // Prototypes that we add to support pool allocation...
253 Function *PoolInit, *PoolDestroy, *PoolAlloc, *PoolFree;
254
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000255 // The map of already transformed functions... note that the keys of this
256 // map do not have meaningful values for 'Call' or the 'PoolHandle' elements
257 // of the ArgInfo elements.
258 //
Chris Lattner692ad5d2002-03-29 17:13:46 +0000259 map<TransformFunctionInfo, Function*> TransformedFunctions;
260
261 // getTransformedFunction - Get a transformed function, or return null if
262 // the function specified hasn't been transformed yet.
263 //
264 Function *getTransformedFunction(TransformFunctionInfo &TFI) const {
265 map<TransformFunctionInfo, Function*>::const_iterator I =
266 TransformedFunctions.find(TFI);
267 if (I != TransformedFunctions.end()) return I->second;
268 return 0;
269 }
270
271
Chris Lattner441e16f2002-04-12 20:23:15 +0000272 // addPoolPrototypes - Add prototypes for the pool functions to the
273 // specified module and update the Pool* instance variables to point to
274 // them.
Chris Lattner175f37c2002-03-29 03:40:59 +0000275 //
276 void addPoolPrototypes(Module *M);
277
Chris Lattner66df97d2002-03-29 06:21:38 +0000278
279 // CreatePools - Insert instructions into the function we are processing to
280 // create all of the memory pool objects themselves. This also inserts
281 // destruction code. Add an alloca for each pool that is allocated to the
Chris Lattner441e16f2002-04-12 20:23:15 +0000282 // PoolDescs map.
Chris Lattner66df97d2002-03-29 06:21:38 +0000283 //
284 void CreatePools(Function *F, const vector<AllocDSNode*> &Allocs,
Chris Lattner441e16f2002-04-12 20:23:15 +0000285 map<DSNode*, PoolInfo> &PoolDescs);
Chris Lattner66df97d2002-03-29 06:21:38 +0000286
Chris Lattner175f37c2002-03-29 03:40:59 +0000287 // processFunction - Convert a function to use pool allocation where
288 // available.
289 //
290 bool processFunction(Function *F);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000291
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000292 // transformFunctionBody - This transforms the instruction in 'F' to use the
Chris Lattner441e16f2002-04-12 20:23:15 +0000293 // pools specified in PoolDescs when modifying data structure nodes
294 // specified in the PoolDescs map. IPFGraph is the closed data structure
295 // graph for F, of which the PoolDescriptor nodes come from.
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000296 //
297 void transformFunctionBody(Function *F, FunctionDSGraph &IPFGraph,
Chris Lattner441e16f2002-04-12 20:23:15 +0000298 map<DSNode*, PoolInfo> &PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000299
300 // transformFunction - Transform the specified function the specified way.
301 // It we have already transformed that function that way, don't do anything.
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000302 // The nodes in the TransformFunctionInfo come out of callers data structure
Chris Lattner441e16f2002-04-12 20:23:15 +0000303 // graph, and the PoolDescs passed in are the caller's.
Chris Lattner692ad5d2002-03-29 17:13:46 +0000304 //
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000305 void transformFunction(TransformFunctionInfo &TFI,
Chris Lattner441e16f2002-04-12 20:23:15 +0000306 FunctionDSGraph &CallerIPGraph,
307 map<DSNode*, PoolInfo> &PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000308
Chris Lattner64fd9352002-03-28 18:08:31 +0000309 };
310}
311
Chris Lattner692ad5d2002-03-29 17:13:46 +0000312// isNotPoolableAlloc - This is a predicate that returns true if the specified
Chris Lattner175f37c2002-03-29 03:40:59 +0000313// allocation node in a data structure graph is eligable for pool allocation.
314//
315static bool isNotPoolableAlloc(const AllocDSNode *DS) {
Chris Lattnere0618ca2002-03-29 05:50:20 +0000316 if (DS->isAllocaNode()) return true; // Do not pool allocate alloca's.
Chris Lattner175f37c2002-03-29 03:40:59 +0000317
318 MallocInst *MI = cast<MallocInst>(DS->getAllocation());
319 if (MI->isArrayAllocation() && !isa<Constant>(MI->getArraySize()))
Chris Lattnere0618ca2002-03-29 05:50:20 +0000320 return true; // Do not allow variable size allocations...
Chris Lattner175f37c2002-03-29 03:40:59 +0000321
Chris Lattnere0618ca2002-03-29 05:50:20 +0000322 return false;
Chris Lattner175f37c2002-03-29 03:40:59 +0000323}
324
Chris Lattner175f37c2002-03-29 03:40:59 +0000325// processFunction - Convert a function to use pool allocation where
326// available.
327//
328bool PoolAllocate::processFunction(Function *F) {
329 // Get the closed datastructure graph for the current function... if there are
330 // any allocations in this graph that are not escaping, we need to pool
331 // allocate them here!
332 //
333 FunctionDSGraph &IPGraph = DS->getClosedDSGraph(F);
334
335 // Get all of the allocations that do not escape the current function. Since
336 // they are still live (they exist in the graph at all), this means we must
337 // have scalar references to these nodes, but the scalars are never returned.
338 //
Chris Lattner692ad5d2002-03-29 17:13:46 +0000339 vector<AllocDSNode*> Allocs;
Chris Lattner175f37c2002-03-29 03:40:59 +0000340 IPGraph.getNonEscapingAllocations(Allocs);
341
342 // Filter out allocations that we cannot handle. Currently, this includes
343 // variable sized array allocations and alloca's (which we do not want to
344 // pool allocate)
345 //
346 Allocs.erase(remove_if(Allocs.begin(), Allocs.end(), isNotPoolableAlloc),
347 Allocs.end());
348
349
350 if (Allocs.empty()) return false; // Nothing to do.
351
Chris Lattner3e78dea2002-04-18 14:43:30 +0000352#ifdef DEBUG_TRANSFORM_PROGRESS
353 cerr << "Transforming Function: " << F->getName() << "\n";
354#endif
355
Chris Lattner692ad5d2002-03-29 17:13:46 +0000356 // Insert instructions into the function we are processing to create all of
357 // the memory pool objects themselves. This also inserts destruction code.
Chris Lattner441e16f2002-04-12 20:23:15 +0000358 // This fills in the PoolDescs map to associate the alloc node with the
Chris Lattner396d5d72002-03-30 04:02:31 +0000359 // allocation of the memory pool corresponding to it.
Chris Lattner692ad5d2002-03-29 17:13:46 +0000360 //
Chris Lattner441e16f2002-04-12 20:23:15 +0000361 map<DSNode*, PoolInfo> PoolDescs;
362 CreatePools(F, Allocs, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000363
Chris Lattneracf19022002-04-14 06:14:41 +0000364#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +0000365 cerr << "Transformed Entry Function: \n" << F;
Chris Lattneracf19022002-04-14 06:14:41 +0000366#endif
Chris Lattner441e16f2002-04-12 20:23:15 +0000367
368 // Now we need to figure out what called functions we need to transform, and
Chris Lattner692ad5d2002-03-29 17:13:46 +0000369 // how. To do this, we look at all of the scalars, seeing which functions are
370 // either used as a scalar value (so they return a data structure), or are
371 // passed one of our scalar values.
372 //
Chris Lattner441e16f2002-04-12 20:23:15 +0000373 transformFunctionBody(F, IPGraph, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000374
375 return true;
376}
377
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000378
Chris Lattner441e16f2002-04-12 20:23:15 +0000379//===----------------------------------------------------------------------===//
380//
381// NewInstructionCreator - This class is used to traverse the function being
382// modified, changing each instruction visit'ed to use and provide pointer
383// indexes instead of real pointers. This is what changes the body of a
384// function to use pool allocation.
385//
386class NewInstructionCreator : public InstVisitor<NewInstructionCreator> {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000387 PoolAllocate &PoolAllocator;
388 vector<ScalarInfo> &Scalars;
389 map<CallInst*, TransformFunctionInfo> &CallMap;
Chris Lattner441e16f2002-04-12 20:23:15 +0000390 map<Value*, Value*> &XFormMap; // Map old pointers to new indexes
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000391
Chris Lattner441e16f2002-04-12 20:23:15 +0000392 struct RefToUpdate {
393 Instruction *I; // Instruction to update
394 unsigned OpNum; // Operand number to update
395 Value *OldVal; // The old value it had
396
397 RefToUpdate(Instruction *i, unsigned o, Value *ov)
398 : I(i), OpNum(o), OldVal(ov) {}
399 };
400 vector<RefToUpdate> ReferencesToUpdate;
401
402 const ScalarInfo &getScalarRef(const Value *V) {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000403 for (unsigned i = 0, e = Scalars.size(); i != e; ++i)
404 if (Scalars[i].Val == V) return Scalars[i];
Chris Lattner3e78dea2002-04-18 14:43:30 +0000405
406 cerr << "Could not find scalar " << V << " in scalar map!\n";
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000407 assert(0 && "Scalar not found in getScalar!");
408 abort();
409 return Scalars[0];
410 }
Chris Lattner441e16f2002-04-12 20:23:15 +0000411
412 const ScalarInfo *getScalar(const Value *V) {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000413 for (unsigned i = 0, e = Scalars.size(); i != e; ++i)
Chris Lattner441e16f2002-04-12 20:23:15 +0000414 if (Scalars[i].Val == V) return &Scalars[i];
415 return 0;
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000416 }
417
Chris Lattner441e16f2002-04-12 20:23:15 +0000418 BasicBlock::iterator ReplaceInstWith(Instruction *I, Instruction *New) {
419 BasicBlock *BB = I->getParent();
420 BasicBlock::iterator RI = find(BB->begin(), BB->end(), I);
421 BB->getInstList().replaceWith(RI, New);
422 XFormMap[I] = New;
423 return RI;
424 }
425
426 LoadInst *createPoolBaseInstruction(Value *PtrVal) {
427 const ScalarInfo &SC = getScalarRef(PtrVal);
428 vector<Value*> Args(3);
429 Args[0] = ConstantUInt::get(Type::UIntTy, 0); // No pointer offset
430 Args[1] = ConstantUInt::get(Type::UByteTy, 0); // Field #0 of pool descriptr
431 Args[2] = ConstantUInt::get(Type::UByteTy, 0); // Field #0 of poolalloc val
432 return new LoadInst(SC.Pool.Handle, Args, PtrVal->getName()+".poolbase");
433 }
434
435
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000436public:
Chris Lattner441e16f2002-04-12 20:23:15 +0000437 NewInstructionCreator(PoolAllocate &PA, vector<ScalarInfo> &S,
438 map<CallInst*, TransformFunctionInfo> &C,
439 map<Value*, Value*> &X)
440 : PoolAllocator(PA), Scalars(S), CallMap(C), XFormMap(X) {}
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000441
Chris Lattner441e16f2002-04-12 20:23:15 +0000442
443 // updateReferences - The NewInstructionCreator is responsible for creating
444 // new instructions to replace the old ones in the function, and then link up
445 // references to values to their new values. For it to do this, however, it
446 // keeps track of information about the value mapping of old values to new
447 // values that need to be patched up. Given this value map and a set of
448 // instruction operands to patch, updateReferences performs the updates.
449 //
450 void updateReferences() {
451 for (unsigned i = 0, e = ReferencesToUpdate.size(); i != e; ++i) {
452 RefToUpdate &Ref = ReferencesToUpdate[i];
453 Value *NewVal = XFormMap[Ref.OldVal];
454
455 if (NewVal == 0) {
456 if (isa<Constant>(Ref.OldVal) && // Refering to a null ptr?
457 cast<Constant>(Ref.OldVal)->isNullValue()) {
458 // Transform the null pointer into a null index... caching in XFormMap
459 XFormMap[Ref.OldVal] = NewVal =Constant::getNullConstant(POINTERTYPE);
460 //} else if (isa<Argument>(Ref.OldVal)) {
461 } else {
462 cerr << "Unknown reference to: " << Ref.OldVal << "\n";
463 assert(XFormMap[Ref.OldVal] &&
464 "Reference to value that was not updated found!");
465 }
466 }
467
468 Ref.I->setOperand(Ref.OpNum, NewVal);
469 }
470 ReferencesToUpdate.clear();
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000471 }
472
Chris Lattner441e16f2002-04-12 20:23:15 +0000473 //===--------------------------------------------------------------------===//
474 // Transformation methods:
475 // These methods specify how each type of instruction is transformed by the
476 // NewInstructionCreator instance...
477 //===--------------------------------------------------------------------===//
478
479 void visitGetElementPtrInst(GetElementPtrInst *I) {
480 assert(0 && "Cannot transform get element ptr instructions yet!");
481 }
482
483 // Replace the load instruction with a new one.
484 void visitLoadInst(LoadInst *I) {
485 Instruction *PoolBase = createPoolBaseInstruction(I->getOperand(0));
486
487 // Cast our index to be a UIntTy so we can use it to index into the pool...
488 CastInst *Index = new CastInst(Constant::getNullConstant(POINTERTYPE),
489 Type::UIntTy, I->getOperand(0)->getName());
490
491 ReferencesToUpdate.push_back(RefToUpdate(Index, 0, I->getOperand(0)));
492
493 vector<Value*> Indices(I->idx_begin(), I->idx_end());
494 assert(Indices[0] == ConstantUInt::get(Type::UIntTy, 0) &&
495 "Cannot handle array indexing yet!");
496 Indices[0] = Index;
497 Instruction *NewLoad = new LoadInst(PoolBase, Indices, I->getName());
498
499 // Replace the load instruction with the new load instruction...
500 BasicBlock::iterator II = ReplaceInstWith(I, NewLoad);
501
502 // Add the pool base calculator instruction before the load...
503 II = NewLoad->getParent()->getInstList().insert(II, PoolBase) + 1;
504
505 // Add the cast before the load instruction...
506 NewLoad->getParent()->getInstList().insert(II, Index);
507
508 // If not yielding a pool allocated pointer, use the new load value as the
509 // value in the program instead of the old load value...
510 //
511 if (!getScalar(I))
512 I->replaceAllUsesWith(NewLoad);
513 }
514
515 // Replace the store instruction with a new one. In the store instruction,
516 // the value stored could be a pointer type, meaning that the new store may
517 // have to change one or both of it's operands.
518 //
519 void visitStoreInst(StoreInst *I) {
520 assert(getScalar(I->getOperand(1)) &&
521 "Store inst found only storing pool allocated pointer. "
522 "Not imp yet!");
523
524 Value *Val = I->getOperand(0); // The value to store...
525 // Check to see if the value we are storing is a data structure pointer...
526 if (const ScalarInfo *ValScalar = getScalar(I->getOperand(0)))
527 Val = Constant::getNullConstant(POINTERTYPE); // Yes, store a dummy
528
529 Instruction *PoolBase = createPoolBaseInstruction(I->getOperand(1));
530
531 // Cast our index to be a UIntTy so we can use it to index into the pool...
532 CastInst *Index = new CastInst(Constant::getNullConstant(POINTERTYPE),
533 Type::UIntTy, I->getOperand(1)->getName());
534 ReferencesToUpdate.push_back(RefToUpdate(Index, 0, I->getOperand(1)));
535
536 vector<Value*> Indices(I->idx_begin(), I->idx_end());
537 assert(Indices[0] == ConstantUInt::get(Type::UIntTy, 0) &&
538 "Cannot handle array indexing yet!");
539 Indices[0] = Index;
540 Instruction *NewStore = new StoreInst(Val, PoolBase, Indices);
541
542 if (Val != I->getOperand(0)) // Value stored was a pointer?
543 ReferencesToUpdate.push_back(RefToUpdate(NewStore, 0, I->getOperand(0)));
544
545
546 // Replace the store instruction with the cast instruction...
547 BasicBlock::iterator II = ReplaceInstWith(I, Index);
548
549 // Add the pool base calculator instruction before the index...
550 II = Index->getParent()->getInstList().insert(II, PoolBase) + 2;
551
552 // Add the store after the cast instruction...
553 Index->getParent()->getInstList().insert(II, NewStore);
554 }
555
556
557 // Create call to poolalloc for every malloc instruction
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000558 void visitMallocInst(MallocInst *I) {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000559 vector<Value*> Args;
Chris Lattner441e16f2002-04-12 20:23:15 +0000560 Args.push_back(getScalarRef(I).Pool.Handle);
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000561 CallInst *Call = new CallInst(PoolAllocator.PoolAlloc, Args, I->getName());
Chris Lattner441e16f2002-04-12 20:23:15 +0000562 ReplaceInstWith(I, Call);
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000563 }
564
Chris Lattner441e16f2002-04-12 20:23:15 +0000565 // Convert a call to poolfree for every free instruction...
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000566 void visitFreeInst(FreeInst *I) {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000567 // Create a new call to poolfree before the free instruction
568 vector<Value*> Args;
Chris Lattner441e16f2002-04-12 20:23:15 +0000569 Args.push_back(Constant::getNullConstant(POINTERTYPE));
570 Args.push_back(getScalarRef(I->getOperand(0)).Pool.Handle);
571 Instruction *NewCall = new CallInst(PoolAllocator.PoolFree, Args);
572 ReplaceInstWith(I, NewCall);
Chris Lattner271255b2002-04-18 22:11:30 +0000573 ReferencesToUpdate.push_back(RefToUpdate(NewCall, 1, I->getOperand(0)));
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000574 }
575
576 // visitCallInst - Create a new call instruction with the extra arguments for
577 // all of the memory pools that the call needs.
578 //
579 void visitCallInst(CallInst *I) {
580 TransformFunctionInfo &TI = CallMap[I];
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000581
582 // Start with all of the old arguments...
583 vector<Value*> Args(I->op_begin()+1, I->op_end());
584
Chris Lattner441e16f2002-04-12 20:23:15 +0000585 for (unsigned i = 0, e = TI.ArgInfo.size(); i != e; ++i) {
586 // Replace all of the pointer arguments with our new pointer typed values.
587 if (TI.ArgInfo[i].ArgNo != -1)
588 Args[TI.ArgInfo[i].ArgNo] = Constant::getNullConstant(POINTERTYPE);
589
590 // Add all of the pool arguments...
Chris Lattner396d5d72002-03-30 04:02:31 +0000591 Args.push_back(TI.ArgInfo[i].PoolHandle);
Chris Lattner441e16f2002-04-12 20:23:15 +0000592 }
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000593
594 Function *NF = PoolAllocator.getTransformedFunction(TI);
Chris Lattner441e16f2002-04-12 20:23:15 +0000595 Instruction *NewCall = new CallInst(NF, Args, I->getName());
596 ReplaceInstWith(I, NewCall);
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000597
Chris Lattner441e16f2002-04-12 20:23:15 +0000598 // Keep track of the mapping of operands so that we can resolve them to real
599 // values later.
600 Value *RetVal = NewCall;
601 for (unsigned i = 0, e = TI.ArgInfo.size(); i != e; ++i)
602 if (TI.ArgInfo[i].ArgNo != -1)
603 ReferencesToUpdate.push_back(RefToUpdate(NewCall, TI.ArgInfo[i].ArgNo+1,
604 I->getOperand(TI.ArgInfo[i].ArgNo+1)));
605 else
606 RetVal = 0; // If returning a pointer, don't change retval...
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000607
Chris Lattner441e16f2002-04-12 20:23:15 +0000608 // If not returning a pointer, use the new call as the value in the program
609 // instead of the old call...
610 //
611 if (RetVal)
612 I->replaceAllUsesWith(RetVal);
613 }
614
615 // visitPHINode - Create a new PHI node of POINTERTYPE for all of the old Phi
616 // nodes...
617 //
618 void visitPHINode(PHINode *PN) {
619 Value *DummyVal = Constant::getNullConstant(POINTERTYPE);
620 PHINode *NewPhi = new PHINode(POINTERTYPE, PN->getName());
621 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
622 NewPhi->addIncoming(DummyVal, PN->getIncomingBlock(i));
623 ReferencesToUpdate.push_back(RefToUpdate(NewPhi, i*2,
624 PN->getIncomingValue(i)));
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000625 }
626
Chris Lattner441e16f2002-04-12 20:23:15 +0000627 ReplaceInstWith(PN, NewPhi);
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000628 }
629
Chris Lattner441e16f2002-04-12 20:23:15 +0000630 // visitReturnInst - Replace ret instruction with a new return...
Chris Lattner847b6e22002-03-30 20:53:14 +0000631 void visitReturnInst(ReturnInst *I) {
Chris Lattner441e16f2002-04-12 20:23:15 +0000632 Instruction *Ret = new ReturnInst(Constant::getNullConstant(POINTERTYPE));
633 ReplaceInstWith(I, Ret);
634 ReferencesToUpdate.push_back(RefToUpdate(Ret, 0, I->getOperand(0)));
Chris Lattner847b6e22002-03-30 20:53:14 +0000635 }
636
Chris Lattner441e16f2002-04-12 20:23:15 +0000637 // visitSetCondInst - Replace a conditional test instruction with a new one
Chris Lattnercf09a2a2002-04-01 00:45:33 +0000638 void visitSetCondInst(SetCondInst *SCI) {
Chris Lattner441e16f2002-04-12 20:23:15 +0000639 BinaryOperator *I = (BinaryOperator*)SCI;
640 Value *DummyVal = Constant::getNullConstant(POINTERTYPE);
641 BinaryOperator *New = BinaryOperator::create(I->getOpcode(), DummyVal,
642 DummyVal, I->getName());
643 ReplaceInstWith(I, New);
644
645 ReferencesToUpdate.push_back(RefToUpdate(New, 0, I->getOperand(0)));
646 ReferencesToUpdate.push_back(RefToUpdate(New, 1, I->getOperand(1)));
647
648 // Make sure branches refer to the new condition...
649 I->replaceAllUsesWith(New);
Chris Lattnercf09a2a2002-04-01 00:45:33 +0000650 }
651
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000652 void visitInstruction(Instruction *I) {
Chris Lattner441e16f2002-04-12 20:23:15 +0000653 cerr << "Unknown instruction to FunctionBodyTransformer:\n" << I;
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000654 }
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000655};
656
657
Chris Lattner457e1ac2002-04-15 22:42:23 +0000658// PoolBaseLoadEliminator - Every load and store through a pool allocated
659// pointer causes a load of the real pool base out of the pool descriptor.
660// Iterate through the function, doing a local elimination pass of duplicate
661// loads. This attempts to turn the all too common:
662//
663// %reg109.poolbase22 = load %root.pool* %root.pool, uint 0, ubyte 0, ubyte 0
664// %reg207 = load %root.p* %reg109.poolbase22, uint %reg109, ubyte 0, ubyte 0
665// %reg109.poolbase23 = load %root.pool* %root.pool, uint 0, ubyte 0, ubyte 0
666// store double %reg207, %root.p* %reg109.poolbase23, uint %reg109, ...
667//
668// into:
669// %reg109.poolbase22 = load %root.pool* %root.pool, uint 0, ubyte 0, ubyte 0
670// %reg207 = load %root.p* %reg109.poolbase22, uint %reg109, ubyte 0, ubyte 0
671// store double %reg207, %root.p* %reg109.poolbase22, uint %reg109, ...
672//
673//
674class PoolBaseLoadEliminator : public InstVisitor<PoolBaseLoadEliminator> {
675 // PoolDescValues - Keep track of the values in the current function that are
676 // pool descriptors (loads from which we want to eliminate).
677 //
678 vector<Value*> PoolDescValues;
679
680 // PoolDescMap - As we are analyzing a BB, keep track of which load to use
681 // when referencing a pool descriptor.
682 //
683 map<Value*, LoadInst*> PoolDescMap;
684
685 // These two fields keep track of statistics of how effective we are, if
686 // debugging is enabled.
687 //
688 unsigned Eliminated, Remaining;
689public:
690 // Compact the pool descriptor map into a list of the pool descriptors in the
691 // current context that we should know about...
692 //
693 PoolBaseLoadEliminator(const map<DSNode*, PoolInfo> &PoolDescs) {
694 Eliminated = Remaining = 0;
695 for (map<DSNode*, PoolInfo>::const_iterator I = PoolDescs.begin(),
696 E = PoolDescs.end(); I != E; ++I)
697 PoolDescValues.push_back(I->second.Handle);
698
699 // Remove duplicates from the list of pool values
700 sort(PoolDescValues.begin(), PoolDescValues.end());
701 PoolDescValues.erase(unique(PoolDescValues.begin(), PoolDescValues.end()),
702 PoolDescValues.end());
703 }
704
705#ifdef DEBUG_POOLBASE_LOAD_ELIMINATOR
706 void visitFunction(Function *F) {
707 cerr << "Pool Load Elim '" << F->getName() << "'\t";
708 }
709 ~PoolBaseLoadEliminator() {
710 unsigned Total = Eliminated+Remaining;
711 if (Total)
712 cerr << "removed " << Eliminated << "["
713 << Eliminated*100/Total << "%] loads, leaving "
714 << Remaining << ".\n";
715 }
716#endif
717
718 // Loop over the function, looking for loads to eliminate. Because we are a
719 // local transformation, we reset all of our state when we enter a new basic
720 // block.
721 //
722 void visitBasicBlock(BasicBlock *) {
723 PoolDescMap.clear(); // Forget state.
724 }
725
726 // Starting with an empty basic block, we scan it looking for loads of the
727 // pool descriptor. When we find a load, we add it to the PoolDescMap,
728 // indicating that we have a value available to recycle next time we see the
729 // poolbase of this instruction being loaded.
730 //
731 void visitLoadInst(LoadInst *LI) {
732 Value *LoadAddr = LI->getPointerOperand();
733 map<Value*, LoadInst*>::iterator VIt = PoolDescMap.find(LoadAddr);
734 if (VIt != PoolDescMap.end()) { // We already have a value for this load?
735 LI->replaceAllUsesWith(VIt->second); // Make the current load dead
736 ++Eliminated;
737 } else {
738 // This load might not be a load of a pool pointer, check to see if it is
739 if (LI->getNumOperands() == 4 && // load pool, uint 0, ubyte 0, ubyte 0
740 find(PoolDescValues.begin(), PoolDescValues.end(), LoadAddr) !=
741 PoolDescValues.end()) {
742
743 assert("Make sure it's a load of the pool base, not a chaining field" &&
744 LI->getOperand(1) == Constant::getNullConstant(Type::UIntTy) &&
745 LI->getOperand(2) == Constant::getNullConstant(Type::UByteTy) &&
746 LI->getOperand(3) == Constant::getNullConstant(Type::UByteTy));
747
748 // If it is a load of a pool base, keep track of it for future reference
749 PoolDescMap.insert(make_pair(LoadAddr, LI));
750 ++Remaining;
751 }
752 }
753 }
754
755 // If we run across a function call, forget all state... Calls to
756 // poolalloc/poolfree can invalidate the pool base pointer, so it should be
757 // reloaded the next time it is used. Furthermore, a call to a random
758 // function might call one of these functions, so be conservative. Through
759 // more analysis, this could be improved in the future.
760 //
761 void visitCallInst(CallInst *) {
762 PoolDescMap.clear();
763 }
764};
765
Chris Lattner3e78dea2002-04-18 14:43:30 +0000766static void addNodeMapping(DSNode *SrcNode, const PointerValSet &PVS,
767 map<DSNode*, PointerValSet> &NodeMapping) {
768 for (unsigned i = 0, e = PVS.size(); i != e; ++i)
769 if (NodeMapping[SrcNode].add(PVS[i])) { // Not in map yet?
770 assert(PVS[i].Index == 0 && "Node indexing not supported yet!");
771 DSNode *DestNode = PVS[i].Node;
772
773 // Loop over all of the outgoing links in the mapped graph
774 for (unsigned l = 0, le = DestNode->getNumOutgoingLinks(); l != le; ++l) {
775 PointerValSet &SrcSet = SrcNode->getOutgoingLink(l);
776 const PointerValSet &DestSet = DestNode->getOutgoingLink(l);
777
778 // Add all of the node mappings now!
779 for (unsigned si = 0, se = SrcSet.size(); si != se; ++si) {
780 assert(SrcSet[si].Index == 0 && "Can't handle node offset!");
781 addNodeMapping(SrcSet[si].Node, DestSet, NodeMapping);
782 }
783 }
784 }
785}
786
787// CalculateNodeMapping - There is a partial isomorphism between the graph
788// passed in and the graph that is actually used by the function. We need to
789// figure out what this mapping is so that we can transformFunctionBody the
790// instructions in the function itself. Note that every node in the graph that
791// we are interested in must be both in the local graph of the called function,
792// and in the local graph of the calling function. Because of this, we only
793// define the mapping for these nodes [conveniently these are the only nodes we
794// CAN define a mapping for...]
795//
796// The roots of the graph that we are transforming is rooted in the arguments
797// passed into the function from the caller. This is where we start our
798// mapping calculation.
799//
800// The NodeMapping calculated maps from the callers graph to the called graph.
801//
802static void CalculateNodeMapping(Function *F, TransformFunctionInfo &TFI,
803 FunctionDSGraph &CallerGraph,
804 FunctionDSGraph &CalledGraph,
805 map<DSNode*, PointerValSet> &NodeMapping) {
806 int LastArgNo = -2;
807 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i) {
808 // Figure out what nodes in the called graph the TFI.ArgInfo[i].Node node
809 // corresponds to...
810 //
811 // Only consider first node of sequence. Extra nodes may may be added
812 // to the TFI if the data structure requires more nodes than just the
813 // one the argument points to. We are only interested in the one the
814 // argument points to though.
815 //
816 if (TFI.ArgInfo[i].ArgNo != LastArgNo) {
817 if (TFI.ArgInfo[i].ArgNo == -1) {
818 addNodeMapping(TFI.ArgInfo[i].Node, CalledGraph.getRetNodes(),
819 NodeMapping);
820 } else {
821 // Figure out which node argument # ArgNo points to in the called graph.
822 Value *Arg = F->getArgumentList()[TFI.ArgInfo[i].ArgNo];
823 addNodeMapping(TFI.ArgInfo[i].Node, CalledGraph.getValueMap()[Arg],
824 NodeMapping);
825 }
826 LastArgNo = TFI.ArgInfo[i].ArgNo;
827 }
828 }
829}
Chris Lattner441e16f2002-04-12 20:23:15 +0000830
831
Chris Lattner3e78dea2002-04-18 14:43:30 +0000832
833
834// addCallInfo - For a specified function call CI, figure out which pool
835// descriptors need to be passed in as arguments, and which arguments need to be
836// transformed into indices. If Arg != -1, the specified call argument is
837// passed in as a pointer to a data structure.
838//
839void TransformFunctionInfo::addCallInfo(DataStructure *DS, CallInst *CI,
840 int Arg, DSNode *GraphNode,
841 map<DSNode*, PoolInfo> &PoolDescs) {
Chris Lattner0dc225c2002-03-31 07:17:46 +0000842 assert(CI->getCalledFunction() && "Cannot handle indirect calls yet!");
Chris Lattner3e78dea2002-04-18 14:43:30 +0000843 assert(Func == 0 || Func == CI->getCalledFunction() &&
Chris Lattner0dc225c2002-03-31 07:17:46 +0000844 "Function call record should always call the same function!");
Chris Lattner3e78dea2002-04-18 14:43:30 +0000845 assert(Call == 0 || Call == CI &&
Chris Lattner0dc225c2002-03-31 07:17:46 +0000846 "Call element already filled in with different value!");
Chris Lattner3e78dea2002-04-18 14:43:30 +0000847 Func = CI->getCalledFunction();
848 Call = CI;
849 //FunctionDSGraph &CalledGraph = DS->getClosedDSGraph(Func);
Chris Lattner396d5d72002-03-30 04:02:31 +0000850
851 // For now, add the entire graph that is pointed to by the call argument.
852 // This graph can and should be pruned to only what the function itself will
853 // use, because often this will be a dramatically smaller subset of what we
854 // are providing.
855 //
Chris Lattner3e78dea2002-04-18 14:43:30 +0000856 // FIXME: This should use pool links instead of extra arguments!
857 //
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000858 for (df_iterator<DSNode*> I = df_begin(GraphNode), E = df_end(GraphNode);
Chris Lattner441e16f2002-04-12 20:23:15 +0000859 I != E; ++I)
Chris Lattner3e78dea2002-04-18 14:43:30 +0000860 ArgInfo.push_back(CallArgInfo(Arg, *I, PoolDescs[*I].Handle));
861}
862
863static void markReachableNodes(const PointerValSet &Vals,
864 set<DSNode*> &ReachableNodes) {
865 for (unsigned n = 0, ne = Vals.size(); n != ne; ++n) {
866 DSNode *N = Vals[n].Node;
867 if (ReachableNodes.count(N) == 0) // Haven't already processed node?
868 ReachableNodes.insert(df_begin(N), df_end(N)); // Insert all
869 }
870}
871
872// Make sure that all dependant arguments are added to this transformation info.
873// For example, if we call foo(null, P) and foo treats it's first and second
874// arguments as belonging to the same data structure, the we MUST add entries to
875// know that the null needs to be transformed into an index as well.
876//
877void TransformFunctionInfo::ensureDependantArgumentsIncluded(DataStructure *DS,
878 map<DSNode*, PoolInfo> &PoolDescs) {
879 // FIXME: This does not work for indirect function calls!!!
880 if (Func == 0) return; // FIXME!
881
882 // Make sure argument entries are sorted.
883 finalizeConstruction();
884
885 // Loop over the function signature, checking to see if there are any pointer
886 // arguments that we do not convert... if there is something we haven't
887 // converted, set done to false.
888 //
889 unsigned PtrNo = 0;
890 bool Done = true;
891 if (isa<PointerType>(Func->getReturnType())) // Make sure we convert retval
892 if (PtrNo < ArgInfo.size() && ArgInfo[PtrNo++].ArgNo == -1) {
893 // We DO transform the ret val... skip all possible entries for retval
894 while (PtrNo < ArgInfo.size() && ArgInfo[PtrNo].ArgNo == -1)
895 PtrNo++;
896 } else {
897 Done = false;
898 }
899
900 for (unsigned i = 0, e = Func->getArgumentList().size(); i != e; ++i) {
901 Argument *Arg = Func->getArgumentList()[i];
902 if (isa<PointerType>(Arg->getType())) {
903 if (PtrNo < ArgInfo.size() && ArgInfo[PtrNo++].ArgNo == (int)i) {
904 // We DO transform this arg... skip all possible entries for argument
905 while (PtrNo < ArgInfo.size() && ArgInfo[PtrNo].ArgNo == (int)i)
906 PtrNo++;
907 } else {
908 Done = false;
909 break;
910 }
911 }
912 }
913
914 // If we already have entries for all pointer arguments and retvals, there
915 // certainly is no work to do. Bail out early to avoid building relatively
916 // expensive data structures.
917 //
918 if (Done) return;
919
920#ifdef DEBUG_TRANSFORM_PROGRESS
921 cerr << "Must ensure dependant arguments for: " << Func->getName() << "\n";
922#endif
923
924 // Otherwise, we MIGHT have to add the arguments/retval if they are part of
925 // the same datastructure graph as some other argument or retval that we ARE
926 // processing.
927 //
928 // Get the data structure graph for the called function.
929 //
930 FunctionDSGraph &CalledDS = DS->getClosedDSGraph(Func);
931
932 // Build a mapping between the nodes in our current graph and the nodes in the
933 // called function's graph. We build it based on our _incomplete_
934 // transformation information, because it contains all of the info that we
935 // should need.
936 //
937 map<DSNode*, PointerValSet> NodeMapping;
938 CalculateNodeMapping(Func, *this,
939 DS->getClosedDSGraph(Call->getParent()->getParent()),
940 CalledDS, NodeMapping);
941
942 // Build the inverted version of the node mapping, that maps from a node in
943 // the called functions graph to a single node in the caller graph.
944 //
945 map<DSNode*, DSNode*> InverseNodeMap;
946 for (map<DSNode*, PointerValSet>::iterator I = NodeMapping.begin(),
947 E = NodeMapping.end(); I != E; ++I) {
948 PointerValSet &CalledNodes = I->second;
949 for (unsigned i = 0, e = CalledNodes.size(); i != e; ++i)
950 InverseNodeMap[CalledNodes[i].Node] = I->first;
951 }
952 NodeMapping.clear(); // Done with information, free memory
953
954 // Build a set of reachable nodes from the arguments/retval that we ARE
955 // passing in...
956 set<DSNode*> ReachableNodes;
957
958 // Loop through all of the arguments, marking all of the reachable data
959 // structure nodes reachable if they are from this pointer...
960 //
961 for (unsigned i = 0, e = ArgInfo.size(); i != e; ++i) {
962 if (ArgInfo[i].ArgNo == -1) {
963 if (i == 0) // Only process retvals once (performance opt)
964 markReachableNodes(CalledDS.getRetNodes(), ReachableNodes);
965 } else { // If it's an argument value...
966 Argument *Arg = Func->getArgumentList()[ArgInfo[i].ArgNo];
967 if (isa<PointerType>(Arg->getType()))
968 markReachableNodes(CalledDS.getValueMap()[Arg], ReachableNodes);
969 }
970 }
971
972 // Now that we know which nodes are already reachable, see if any of the
973 // arguments that we are not passing values in for can reach one of the
974 // existing nodes...
975 //
976
977 // <FIXME> IN THEORY, we should allow arbitrary paths from the argument to
978 // nodes we know about. The problem is that if we do this, then I don't know
979 // how to get pool pointers for this head list. Since we are completely
980 // deadline driven, I'll just allow direct accesses to the graph. </FIXME>
981 //
982
983 PtrNo = 0;
984 if (isa<PointerType>(Func->getReturnType())) // Make sure we convert retval
985 if (PtrNo < ArgInfo.size() && ArgInfo[PtrNo++].ArgNo == -1) {
986 // We DO transform the ret val... skip all possible entries for retval
987 while (PtrNo < ArgInfo.size() && ArgInfo[PtrNo].ArgNo == -1)
988 PtrNo++;
989 } else {
990 // See what the return value points to...
991
992 // FIXME: This should generalize to any number of nodes, just see if any
993 // are reachable.
994 assert(CalledDS.getRetNodes().size() == 1 &&
995 "Assumes only one node is returned");
996 DSNode *N = CalledDS.getRetNodes()[0].Node;
997
998 // If the return value is not marked as being passed in, but it NEEDS to
999 // be transformed, then make it known now.
1000 //
1001 if (ReachableNodes.count(N)) {
1002#ifdef DEBUG_TRANSFORM_PROGRESS
1003 cerr << "ensure dependant arguments adds return value entry!\n";
1004#endif
1005 addCallInfo(DS, Call, -1, InverseNodeMap[N], PoolDescs);
1006
1007 // Keep sorted!
1008 finalizeConstruction();
1009 }
1010 }
1011
1012 for (unsigned i = 0, e = Func->getArgumentList().size(); i != e; ++i) {
1013 Argument *Arg = Func->getArgumentList()[i];
1014 if (isa<PointerType>(Arg->getType())) {
1015 if (PtrNo < ArgInfo.size() && ArgInfo[PtrNo++].ArgNo == (int)i) {
1016 // We DO transform this arg... skip all possible entries for argument
1017 while (PtrNo < ArgInfo.size() && ArgInfo[PtrNo].ArgNo == (int)i)
1018 PtrNo++;
1019 } else {
1020 // This should generalize to any number of nodes, just see if any are
1021 // reachable.
1022 assert(CalledDS.getValueMap()[Arg].size() == 1 &&
1023 "Only handle case where pointing to one node so far!");
1024
1025 // If the arg is not marked as being passed in, but it NEEDS to
1026 // be transformed, then make it known now.
1027 //
1028 DSNode *N = CalledDS.getValueMap()[Arg][0].Node;
1029 if (ReachableNodes.count(N)) {
1030#ifdef DEBUG_TRANSFORM_PROGRESS
1031 cerr << "ensure dependant arguments adds for arg #" << i << "\n";
1032#endif
1033 addCallInfo(DS, Call, i, InverseNodeMap[N], PoolDescs);
1034
1035 // Keep sorted!
1036 finalizeConstruction();
1037 }
1038 }
1039 }
1040 }
Chris Lattner396d5d72002-03-30 04:02:31 +00001041}
1042
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001043
1044// transformFunctionBody - This transforms the instruction in 'F' to use the
Chris Lattner441e16f2002-04-12 20:23:15 +00001045// pools specified in PoolDescs when modifying data structure nodes specified in
1046// the PoolDescs map. Specifically, scalar values specified in the Scalars
1047// vector must be remapped. IPFGraph is the closed data structure graph for F,
1048// of which the PoolDescriptor nodes come from.
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001049//
1050void PoolAllocate::transformFunctionBody(Function *F, FunctionDSGraph &IPFGraph,
Chris Lattner441e16f2002-04-12 20:23:15 +00001051 map<DSNode*, PoolInfo> &PoolDescs) {
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001052
1053 // Loop through the value map looking for scalars that refer to nonescaping
1054 // allocations. Add them to the Scalars vector. Note that we may have
1055 // multiple entries in the Scalars vector for each value if it points to more
1056 // than one object.
1057 //
1058 map<Value*, PointerValSet> &ValMap = IPFGraph.getValueMap();
1059 vector<ScalarInfo> Scalars;
1060
Chris Lattneracf19022002-04-14 06:14:41 +00001061#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner847b6e22002-03-30 20:53:14 +00001062 cerr << "Building scalar map:\n";
Chris Lattneracf19022002-04-14 06:14:41 +00001063#endif
Chris Lattner847b6e22002-03-30 20:53:14 +00001064
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001065 for (map<Value*, PointerValSet>::iterator I = ValMap.begin(),
1066 E = ValMap.end(); I != E; ++I) {
1067 const PointerValSet &PVS = I->second; // Set of things pointed to by scalar
1068
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001069 // Check to see if the scalar points to a data structure node...
1070 for (unsigned i = 0, e = PVS.size(); i != e; ++i) {
1071 assert(PVS[i].Index == 0 && "Nonzero not handled yet!");
1072
1073 // If the allocation is in the nonescaping set...
Chris Lattner441e16f2002-04-12 20:23:15 +00001074 map<DSNode*, PoolInfo>::iterator AI = PoolDescs.find(PVS[i].Node);
1075 if (AI != PoolDescs.end()) { // Add it to the list of scalars
1076 Scalars.push_back(ScalarInfo(I->first, AI->second));
Chris Lattneracf19022002-04-14 06:14:41 +00001077#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001078 cerr << "\nScalar Mapping from:" << I->first
1079 << "Scalar Mapping to: "; PVS.print(cerr);
Chris Lattneracf19022002-04-14 06:14:41 +00001080#endif
Chris Lattner441e16f2002-04-12 20:23:15 +00001081 }
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001082 }
1083 }
1084
Chris Lattneracf19022002-04-14 06:14:41 +00001085#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner847b6e22002-03-30 20:53:14 +00001086 cerr << "\nIn '" << F->getName()
Chris Lattner175f37c2002-03-29 03:40:59 +00001087 << "': Found the following values that point to poolable nodes:\n";
1088
1089 for (unsigned i = 0, e = Scalars.size(); i != e; ++i)
Chris Lattner441e16f2002-04-12 20:23:15 +00001090 cerr << Scalars[i].Val;
1091 cerr << "\n";
Chris Lattneracf19022002-04-14 06:14:41 +00001092#endif
Chris Lattnere0618ca2002-03-29 05:50:20 +00001093
Chris Lattner692ad5d2002-03-29 17:13:46 +00001094 // CallMap - Contain an entry for every call instruction that needs to be
1095 // transformed. Each entry in the map contains information about what we need
1096 // to do to each call site to change it to work.
1097 //
1098 map<CallInst*, TransformFunctionInfo> CallMap;
Chris Lattner66df97d2002-03-29 06:21:38 +00001099
Chris Lattner441e16f2002-04-12 20:23:15 +00001100 // Now we need to figure out what called functions we need to transform, and
Chris Lattner692ad5d2002-03-29 17:13:46 +00001101 // how. To do this, we look at all of the scalars, seeing which functions are
1102 // either used as a scalar value (so they return a data structure), or are
1103 // passed one of our scalar values.
1104 //
1105 for (unsigned i = 0, e = Scalars.size(); i != e; ++i) {
1106 Value *ScalarVal = Scalars[i].Val;
1107
1108 // Check to see if the scalar _IS_ a call...
1109 if (CallInst *CI = dyn_cast<CallInst>(ScalarVal))
1110 // If so, add information about the pool it will be returning...
Chris Lattner3e78dea2002-04-18 14:43:30 +00001111 CallMap[CI].addCallInfo(DS, CI, -1, Scalars[i].Pool.Node, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +00001112
1113 // Check to see if the scalar is an operand to a call...
1114 for (Value::use_iterator UI = ScalarVal->use_begin(),
1115 UE = ScalarVal->use_end(); UI != UE; ++UI) {
1116 if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
1117 // Find out which operand this is to the call instruction...
1118 User::op_iterator OI = find(CI->op_begin(), CI->op_end(), ScalarVal);
1119 assert(OI != CI->op_end() && "Call on use list but not an operand!?");
1120 assert(OI != CI->op_begin() && "Pointer operand is call destination?");
1121
1122 // FIXME: This is broken if the same pointer is passed to a call more
1123 // than once! It will get multiple entries for the first pointer.
1124
1125 // Add the operand number and pool handle to the call table...
Chris Lattner3e78dea2002-04-18 14:43:30 +00001126 CallMap[CI].addCallInfo(DS, CI, OI-CI->op_begin()-1,
1127 Scalars[i].Pool.Node, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +00001128 }
1129 }
1130 }
1131
Chris Lattner3e78dea2002-04-18 14:43:30 +00001132 // Make sure that all dependant arguments are added as well. For example, if
1133 // we call foo(null, P) and foo treats it's first and second arguments as
1134 // belonging to the same data structure, the we MUST set up the CallMap to
1135 // know that the null needs to be transformed into an index as well.
1136 //
1137 for (map<CallInst*, TransformFunctionInfo>::iterator I = CallMap.begin();
1138 I != CallMap.end(); ++I)
1139 I->second.ensureDependantArgumentsIncluded(DS, PoolDescs);
1140
Chris Lattneracf19022002-04-14 06:14:41 +00001141#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner692ad5d2002-03-29 17:13:46 +00001142 // Print out call map...
1143 for (map<CallInst*, TransformFunctionInfo>::iterator I = CallMap.begin();
1144 I != CallMap.end(); ++I) {
Chris Lattner441e16f2002-04-12 20:23:15 +00001145 cerr << "For call: " << I->first;
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001146 cerr << I->second.Func->getName() << " must pass pool pointer for args #";
Chris Lattner692ad5d2002-03-29 17:13:46 +00001147 for (unsigned i = 0; i < I->second.ArgInfo.size(); ++i)
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001148 cerr << I->second.ArgInfo[i].ArgNo << ", ";
Chris Lattner441e16f2002-04-12 20:23:15 +00001149 cerr << "\n\n";
Chris Lattner692ad5d2002-03-29 17:13:46 +00001150 }
Chris Lattneracf19022002-04-14 06:14:41 +00001151#endif
Chris Lattner692ad5d2002-03-29 17:13:46 +00001152
1153 // Loop through all of the call nodes, recursively creating the new functions
1154 // that we want to call... This uses a map to prevent infinite recursion and
1155 // to avoid duplicating functions unneccesarily.
1156 //
1157 for (map<CallInst*, TransformFunctionInfo>::iterator I = CallMap.begin(),
1158 E = CallMap.end(); I != E; ++I) {
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001159 // Transform all of the functions we need, or at least ensure there is a
1160 // cached version available.
Chris Lattner441e16f2002-04-12 20:23:15 +00001161 transformFunction(I->second, IPFGraph, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +00001162 }
1163
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001164 // Now that all of the functions that we want to call are available, transform
Chris Lattner441e16f2002-04-12 20:23:15 +00001165 // the local function so that it uses the pools locally and passes them to the
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001166 // functions that we just hacked up.
1167 //
1168
1169 // First step, find the instructions to be modified.
1170 vector<Instruction*> InstToFix;
1171 for (unsigned i = 0, e = Scalars.size(); i != e; ++i) {
1172 Value *ScalarVal = Scalars[i].Val;
1173
1174 // Check to see if the scalar _IS_ an instruction. If so, it is involved.
1175 if (Instruction *Inst = dyn_cast<Instruction>(ScalarVal))
1176 InstToFix.push_back(Inst);
1177
1178 // All all of the instructions that use the scalar as an operand...
1179 for (Value::use_iterator UI = ScalarVal->use_begin(),
1180 UE = ScalarVal->use_end(); UI != UE; ++UI)
Chris Lattner441e16f2002-04-12 20:23:15 +00001181 InstToFix.push_back(cast<Instruction>(*UI));
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001182 }
1183
Chris Lattner50e3d322002-04-13 23:13:18 +00001184 // Make sure that we get return instructions that return a null value from the
1185 // function...
1186 //
1187 if (!IPFGraph.getRetNodes().empty()) {
1188 assert(IPFGraph.getRetNodes().size() == 1 && "Can only return one node?");
1189 PointerVal RetNode = IPFGraph.getRetNodes()[0];
1190 assert(RetNode.Index == 0 && "Subindexing not implemented yet!");
1191
1192 // Only process return instructions if the return value of this function is
1193 // part of one of the data structures we are transforming...
1194 //
1195 if (PoolDescs.count(RetNode.Node)) {
1196 // Loop over all of the basic blocks, adding return instructions...
1197 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
1198 if (ReturnInst *RI = dyn_cast<ReturnInst>((*I)->getTerminator()))
1199 InstToFix.push_back(RI);
1200 }
1201 }
1202
1203
1204
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001205 // Eliminate duplicates by sorting, then removing equal neighbors.
1206 sort(InstToFix.begin(), InstToFix.end());
1207 InstToFix.erase(unique(InstToFix.begin(), InstToFix.end()), InstToFix.end());
1208
Chris Lattner441e16f2002-04-12 20:23:15 +00001209 // Loop over all of the instructions to transform, creating the new
1210 // replacement instructions for them. This also unlinks them from the
1211 // function so they can be safely deleted later.
1212 //
1213 map<Value*, Value*> XFormMap;
1214 NewInstructionCreator NIC(*this, Scalars, CallMap, XFormMap);
Chris Lattner692ad5d2002-03-29 17:13:46 +00001215
Chris Lattner441e16f2002-04-12 20:23:15 +00001216 // Visit all instructions... creating the new instructions that we need and
1217 // unlinking the old instructions from the function...
1218 //
Chris Lattneracf19022002-04-14 06:14:41 +00001219#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001220 for (unsigned i = 0, e = InstToFix.size(); i != e; ++i) {
1221 cerr << "Fixing: " << InstToFix[i];
1222 NIC.visit(InstToFix[i]);
1223 }
Chris Lattneracf19022002-04-14 06:14:41 +00001224#else
1225 NIC.visit(InstToFix.begin(), InstToFix.end());
1226#endif
Chris Lattner441e16f2002-04-12 20:23:15 +00001227
1228 // Make all instructions we will delete "let go" of their operands... so that
1229 // we can safely delete Arguments whose types have changed...
1230 //
1231 for_each(InstToFix.begin(), InstToFix.end(),
1232 mem_fun(&Instruction::dropAllReferences));
1233
1234 // Loop through all of the pointer arguments coming into the function,
1235 // replacing them with arguments of POINTERTYPE to match the function type of
1236 // the function.
1237 //
1238 FunctionType::ParamTypes::const_iterator TI =
1239 F->getFunctionType()->getParamTypes().begin();
1240 for (Function::ArgumentListType::iterator I = F->getArgumentList().begin(),
1241 E = F->getArgumentList().end(); I != E; ++I, ++TI) {
1242 Argument *Arg = *I;
1243 if (Arg->getType() != *TI) {
1244 assert(isa<PointerType>(Arg->getType()) && *TI == POINTERTYPE);
1245 Argument *NewArg = new Argument(*TI, Arg->getName());
1246 XFormMap[Arg] = NewArg; // Map old arg into new arg...
1247
Chris Lattner441e16f2002-04-12 20:23:15 +00001248 // Replace the old argument and then delete it...
1249 delete F->getArgumentList().replaceWith(I, NewArg);
1250 }
1251 }
1252
1253 // Now that all of the new instructions have been created, we can update all
1254 // of the references to dummy values to be references to the actual values
1255 // that are computed.
1256 //
1257 NIC.updateReferences();
1258
Chris Lattneracf19022002-04-14 06:14:41 +00001259#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001260 cerr << "TRANSFORMED FUNCTION:\n" << F;
Chris Lattneracf19022002-04-14 06:14:41 +00001261#endif
Chris Lattner441e16f2002-04-12 20:23:15 +00001262
1263 // Delete all of the "instructions to fix"
1264 for_each(InstToFix.begin(), InstToFix.end(), deleter<Instruction>);
Chris Lattner692ad5d2002-03-29 17:13:46 +00001265
Chris Lattner457e1ac2002-04-15 22:42:23 +00001266 // Eliminate pool base loads that we can easily prove are redundant
1267 if (!DisableRLE)
1268 PoolBaseLoadEliminator(PoolDescs).visit(F);
1269
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001270 // Since we have liberally hacked the function to pieces, we want to inform
1271 // the datastructure pass that its internal representation is out of date.
1272 //
1273 DS->invalidateFunction(F);
Chris Lattner692ad5d2002-03-29 17:13:46 +00001274}
1275
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001276
1277
1278// transformFunction - Transform the specified function the specified way. It
1279// we have already transformed that function that way, don't do anything. The
1280// nodes in the TransformFunctionInfo come out of callers data structure graph.
1281//
1282void PoolAllocate::transformFunction(TransformFunctionInfo &TFI,
Chris Lattner441e16f2002-04-12 20:23:15 +00001283 FunctionDSGraph &CallerIPGraph,
1284 map<DSNode*, PoolInfo> &CallerPoolDesc) {
Chris Lattner692ad5d2002-03-29 17:13:46 +00001285 if (getTransformedFunction(TFI)) return; // Function xformation already done?
1286
Chris Lattneracf19022002-04-14 06:14:41 +00001287#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001288 cerr << "********** Entering transformFunction for "
Chris Lattner0dc225c2002-03-31 07:17:46 +00001289 << TFI.Func->getName() << ":\n";
1290 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i)
1291 cerr << " ArgInfo[" << i << "] = " << TFI.ArgInfo[i].ArgNo << "\n";
1292 cerr << "\n";
Chris Lattneracf19022002-04-14 06:14:41 +00001293#endif
Chris Lattner0dc225c2002-03-31 07:17:46 +00001294
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001295 const FunctionType *OldFuncType = TFI.Func->getFunctionType();
Chris Lattner692ad5d2002-03-29 17:13:46 +00001296
Chris Lattner291a1b12002-03-29 19:05:48 +00001297 assert(!OldFuncType->isVarArg() && "Vararg functions not handled yet!");
Chris Lattner692ad5d2002-03-29 17:13:46 +00001298
Chris Lattner291a1b12002-03-29 19:05:48 +00001299 // Build the type for the new function that we are transforming
1300 vector<const Type*> ArgTys;
Chris Lattner441e16f2002-04-12 20:23:15 +00001301 ArgTys.reserve(OldFuncType->getNumParams()+TFI.ArgInfo.size());
Chris Lattner291a1b12002-03-29 19:05:48 +00001302 for (unsigned i = 0, e = OldFuncType->getNumParams(); i != e; ++i)
1303 ArgTys.push_back(OldFuncType->getParamType(i));
1304
Chris Lattner441e16f2002-04-12 20:23:15 +00001305 const Type *RetType = OldFuncType->getReturnType();
1306
Chris Lattner291a1b12002-03-29 19:05:48 +00001307 // Add one pool pointer for every argument that needs to be supplemented.
Chris Lattner441e16f2002-04-12 20:23:15 +00001308 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i) {
1309 if (TFI.ArgInfo[i].ArgNo == -1)
1310 RetType = POINTERTYPE; // Return a pointer
1311 else
1312 ArgTys[TFI.ArgInfo[i].ArgNo] = POINTERTYPE; // Pass a pointer
1313 ArgTys.push_back(PointerType::get(CallerPoolDesc.find(TFI.ArgInfo[i].Node)
1314 ->second.PoolType));
1315 }
Chris Lattner291a1b12002-03-29 19:05:48 +00001316
1317 // Build the new function type...
Chris Lattner441e16f2002-04-12 20:23:15 +00001318 const FunctionType *NewFuncType = FunctionType::get(RetType, ArgTys,
1319 OldFuncType->isVarArg());
Chris Lattner291a1b12002-03-29 19:05:48 +00001320
1321 // The new function is internal, because we know that only we can call it.
1322 // This also helps subsequent IP transformations to eliminate duplicated pool
Chris Lattner441e16f2002-04-12 20:23:15 +00001323 // pointers (which look like the same value is always passed into a parameter,
1324 // allowing it to be easily eliminated).
Chris Lattner291a1b12002-03-29 19:05:48 +00001325 //
1326 Function *NewFunc = new Function(NewFuncType, true,
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001327 TFI.Func->getName()+".poolxform");
Chris Lattner291a1b12002-03-29 19:05:48 +00001328 CurModule->getFunctionList().push_back(NewFunc);
1329
Chris Lattner441e16f2002-04-12 20:23:15 +00001330
Chris Lattneracf19022002-04-14 06:14:41 +00001331#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001332 cerr << "Created function prototype: " << NewFunc << "\n";
Chris Lattneracf19022002-04-14 06:14:41 +00001333#endif
Chris Lattner441e16f2002-04-12 20:23:15 +00001334
Chris Lattner291a1b12002-03-29 19:05:48 +00001335 // Add the newly formed function to the TransformedFunctions table so that
1336 // infinite recursion does not occur!
1337 //
1338 TransformedFunctions[TFI] = NewFunc;
1339
1340 // Add arguments to the function... starting with all of the old arguments
1341 vector<Value*> ArgMap;
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001342 for (unsigned i = 0, e = TFI.Func->getArgumentList().size(); i != e; ++i) {
Chris Lattner2e9fa6d2002-04-09 19:48:49 +00001343 const Argument *OFA = TFI.Func->getArgumentList()[i];
1344 Argument *NFA = new Argument(OFA->getType(), OFA->getName());
Chris Lattner291a1b12002-03-29 19:05:48 +00001345 NewFunc->getArgumentList().push_back(NFA);
1346 ArgMap.push_back(NFA); // Keep track of the arguments
1347 }
1348
1349 // Now add all of the arguments corresponding to pools passed in...
1350 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i) {
Chris Lattner441e16f2002-04-12 20:23:15 +00001351 CallArgInfo &AI = TFI.ArgInfo[i];
Chris Lattner291a1b12002-03-29 19:05:48 +00001352 string Name;
Chris Lattner441e16f2002-04-12 20:23:15 +00001353 if (AI.ArgNo == -1)
1354 Name = "ret";
Chris Lattner291a1b12002-03-29 19:05:48 +00001355 else
Chris Lattner441e16f2002-04-12 20:23:15 +00001356 Name = ArgMap[AI.ArgNo]->getName(); // Get the arg name
1357 const Type *Ty = PointerType::get(CallerPoolDesc[AI.Node].PoolType);
1358 Argument *NFA = new Argument(Ty, Name+".pool");
Chris Lattner291a1b12002-03-29 19:05:48 +00001359 NewFunc->getArgumentList().push_back(NFA);
1360 }
1361
1362 // Now clone the body of the old function into the new function...
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001363 CloneFunctionInto(NewFunc, TFI.Func, ArgMap);
Chris Lattner291a1b12002-03-29 19:05:48 +00001364
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001365 // Okay, now we have a function that is identical to the old one, except that
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001366 // it has extra arguments for the pools coming in. Now we have to get the
1367 // data structure graph for the function we are replacing, and figure out how
1368 // our graph nodes map to the graph nodes in the dest function.
1369 //
Chris Lattner847b6e22002-03-30 20:53:14 +00001370 FunctionDSGraph &DSGraph = DS->getClosedDSGraph(NewFunc);
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001371
Chris Lattner441e16f2002-04-12 20:23:15 +00001372 // NodeMapping - Multimap from callers graph to called graph. We are
1373 // guaranteed that the called function graph has more nodes than the caller,
1374 // or exactly the same number of nodes. This is because the called function
1375 // might not know that two nodes are merged when considering the callers
1376 // context, but the caller obviously does. Because of this, a single node in
1377 // the calling function's data structure graph can map to multiple nodes in
1378 // the called functions graph.
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001379 //
1380 map<DSNode*, PointerValSet> NodeMapping;
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001381
Chris Lattner847b6e22002-03-30 20:53:14 +00001382 CalculateNodeMapping(NewFunc, TFI, CallerIPGraph, DSGraph,
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001383 NodeMapping);
1384
1385 // Print out the node mapping...
Chris Lattneracf19022002-04-14 06:14:41 +00001386#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner847b6e22002-03-30 20:53:14 +00001387 cerr << "\nNode mapping for call of " << NewFunc->getName() << "\n";
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001388 for (map<DSNode*, PointerValSet>::iterator I = NodeMapping.begin();
1389 I != NodeMapping.end(); ++I) {
1390 cerr << "Map: "; I->first->print(cerr);
1391 cerr << "To: "; I->second.print(cerr);
1392 cerr << "\n";
1393 }
Chris Lattneracf19022002-04-14 06:14:41 +00001394#endif
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001395
1396 // Fill in the PoolDescriptor information for the transformed function so that
1397 // it can determine which value holds the pool descriptor for each data
1398 // structure node that it accesses.
1399 //
Chris Lattner441e16f2002-04-12 20:23:15 +00001400 map<DSNode*, PoolInfo> PoolDescs;
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001401
Chris Lattneracf19022002-04-14 06:14:41 +00001402#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner847b6e22002-03-30 20:53:14 +00001403 cerr << "\nCalculating the pool descriptor map:\n";
Chris Lattneracf19022002-04-14 06:14:41 +00001404#endif
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001405
Chris Lattner441e16f2002-04-12 20:23:15 +00001406 // Calculate as much of the pool descriptor map as possible. Since we have
1407 // the node mapping between the caller and callee functions, and we have the
1408 // pool descriptor information of the caller, we can calculate a partical pool
1409 // descriptor map for the called function.
1410 //
1411 // The nodes that we do not have complete information for are the ones that
1412 // are accessed by loading pointers derived from arguments passed in, but that
1413 // are not passed in directly. In this case, we have all of the information
1414 // except a pool value. If the called function refers to this pool, the pool
1415 // value will be loaded from the pool graph and added to the map as neccesary.
1416 //
1417 for (map<DSNode*, PointerValSet>::iterator I = NodeMapping.begin();
1418 I != NodeMapping.end(); ++I) {
1419 DSNode *CallerNode = I->first;
1420 PoolInfo &CallerPI = CallerPoolDesc[CallerNode];
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001421
Chris Lattner441e16f2002-04-12 20:23:15 +00001422 // Check to see if we have a node pointer passed in for this value...
1423 Value *CalleeValue = 0;
1424 for (unsigned a = 0, ae = TFI.ArgInfo.size(); a != ae; ++a)
1425 if (TFI.ArgInfo[a].Node == CallerNode) {
1426 // Calculate the argument number that the pool is to the function
1427 // call... The call instruction should not have the pool operands added
1428 // yet.
1429 unsigned ArgNo = TFI.Call->getNumOperands()-1+a;
Chris Lattneracf19022002-04-14 06:14:41 +00001430#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001431 cerr << "Should be argument #: " << ArgNo << "[i = " << a << "]\n";
Chris Lattneracf19022002-04-14 06:14:41 +00001432#endif
Chris Lattner441e16f2002-04-12 20:23:15 +00001433 assert(ArgNo < NewFunc->getArgumentList().size() &&
1434 "Call already has pool arguments added??");
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001435
Chris Lattner441e16f2002-04-12 20:23:15 +00001436 // Map the pool argument into the called function...
1437 CalleeValue = NewFunc->getArgumentList()[ArgNo];
1438 break; // Found value, quit loop
1439 }
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001440
Chris Lattner441e16f2002-04-12 20:23:15 +00001441 // Loop over all of the data structure nodes that this incoming node maps to
1442 // Creating a PoolInfo structure for them.
1443 for (unsigned i = 0, e = I->second.size(); i != e; ++i) {
1444 assert(I->second[i].Index == 0 && "Doesn't handle subindexing yet!");
1445 DSNode *CalleeNode = I->second[i].Node;
1446
1447 // Add the descriptor. We already know everything about it by now, much
1448 // of it is the same as the caller info.
1449 //
1450 PoolDescs.insert(make_pair(CalleeNode,
1451 PoolInfo(CalleeNode, CalleeValue,
1452 CallerPI.NewType,
1453 CallerPI.PoolType)));
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001454 }
Chris Lattner847b6e22002-03-30 20:53:14 +00001455 }
1456
1457 // We must destroy the node mapping so that we don't have latent references
1458 // into the data structure graph for the new function. Otherwise we get
1459 // assertion failures when transformFunctionBody tries to invalidate the
1460 // graph.
1461 //
1462 NodeMapping.clear();
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001463
1464 // Now that we know everything we need about the function, transform the body
1465 // now!
1466 //
Chris Lattner441e16f2002-04-12 20:23:15 +00001467 transformFunctionBody(NewFunc, DSGraph, PoolDescs);
1468
Chris Lattneracf19022002-04-14 06:14:41 +00001469#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001470 cerr << "Function after transformation:\n" << NewFunc;
Chris Lattneracf19022002-04-14 06:14:41 +00001471#endif
Chris Lattner66df97d2002-03-29 06:21:38 +00001472}
1473
Chris Lattner8f796d62002-04-13 19:25:57 +00001474static unsigned countPointerTypes(const Type *Ty) {
1475 if (isa<PointerType>(Ty)) {
1476 return 1;
1477 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1478 unsigned Num = 0;
1479 for (unsigned i = 0, e = STy->getElementTypes().size(); i != e; ++i)
1480 Num += countPointerTypes(STy->getElementTypes()[i]);
1481 return Num;
1482 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1483 return countPointerTypes(ATy->getElementType());
1484 } else {
1485 assert(Ty->isPrimitiveType() && "Unknown derived type!");
1486 return 0;
1487 }
1488}
Chris Lattner66df97d2002-03-29 06:21:38 +00001489
1490// CreatePools - Insert instructions into the function we are processing to
1491// create all of the memory pool objects themselves. This also inserts
1492// destruction code. Add an alloca for each pool that is allocated to the
Chris Lattner441e16f2002-04-12 20:23:15 +00001493// PoolDescs vector.
Chris Lattner66df97d2002-03-29 06:21:38 +00001494//
1495void PoolAllocate::CreatePools(Function *F, const vector<AllocDSNode*> &Allocs,
Chris Lattner441e16f2002-04-12 20:23:15 +00001496 map<DSNode*, PoolInfo> &PoolDescs) {
1497 // Find all of the return nodes in the function...
Chris Lattnere0618ca2002-03-29 05:50:20 +00001498 vector<BasicBlock*> ReturnNodes;
1499 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
1500 if (isa<ReturnInst>((*I)->getTerminator()))
1501 ReturnNodes.push_back(*I);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001502
Chris Lattner3e78dea2002-04-18 14:43:30 +00001503#ifdef DEBUG_CREATE_POOLS
1504 cerr << "Allocs that we are pool allocating:\n";
1505 for (unsigned i = 0, e = Allocs.size(); i != e; ++i)
1506 Allocs[i]->dump();
1507#endif
1508
Chris Lattner441e16f2002-04-12 20:23:15 +00001509 map<DSNode*, PATypeHolder> AbsPoolTyMap;
1510
1511 // First pass over the allocations to process...
1512 for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
1513 // Create the pooldescriptor mapping... with null entries for everything
1514 // except the node & NewType fields.
1515 //
1516 map<DSNode*, PoolInfo>::iterator PI =
1517 PoolDescs.insert(make_pair(Allocs[i], PoolInfo(Allocs[i]))).first;
1518
Chris Lattner8f796d62002-04-13 19:25:57 +00001519 // Add a symbol table entry for the new type if there was one for the old
1520 // type...
1521 string OldName = CurModule->getTypeName(Allocs[i]->getType());
1522 if (!OldName.empty())
1523 CurModule->addTypeName(OldName+".p", PI->second.NewType);
1524
Chris Lattner441e16f2002-04-12 20:23:15 +00001525 // Create the abstract pool types that will need to be resolved in a second
1526 // pass once an abstract type is created for each pool.
1527 //
1528 // Can only handle limited shapes for now...
1529 StructType *OldNodeTy = cast<StructType>(Allocs[i]->getType());
1530 vector<const Type*> PoolTypes;
1531
1532 // Pool type is the first element of the pool descriptor type...
1533 PoolTypes.push_back(getPoolType(PoolDescs[Allocs[i]].NewType));
Chris Lattner8f796d62002-04-13 19:25:57 +00001534
1535 unsigned NumPointers = countPointerTypes(OldNodeTy);
1536 while (NumPointers--) // Add a different opaque type for each pointer
1537 PoolTypes.push_back(OpaqueType::get());
1538
Chris Lattner441e16f2002-04-12 20:23:15 +00001539 assert(Allocs[i]->getNumLinks() == PoolTypes.size()-1 &&
1540 "Node should have same number of pointers as pool!");
1541
Chris Lattner8f796d62002-04-13 19:25:57 +00001542 StructType *PoolType = StructType::get(PoolTypes);
1543
1544 // Add a symbol table entry for the pooltype if possible...
1545 if (!OldName.empty()) CurModule->addTypeName(OldName+".pool", PoolType);
1546
Chris Lattner441e16f2002-04-12 20:23:15 +00001547 // Create the pool type, with opaque values for pointers...
Chris Lattner8f796d62002-04-13 19:25:57 +00001548 AbsPoolTyMap.insert(make_pair(Allocs[i], PoolType));
Chris Lattner441e16f2002-04-12 20:23:15 +00001549#ifdef DEBUG_CREATE_POOLS
1550 cerr << "POOL TY: " << AbsPoolTyMap.find(Allocs[i])->second.get() << "\n";
1551#endif
1552 }
1553
1554 // Now that we have types for all of the pool types, link them all together.
1555 for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
1556 PATypeHolder &PoolTyH = AbsPoolTyMap.find(Allocs[i])->second;
1557
1558 // Resolve all of the outgoing pointer types of this pool node...
1559 for (unsigned p = 0, pe = Allocs[i]->getNumLinks(); p != pe; ++p) {
1560 PointerValSet &PVS = Allocs[i]->getLink(p);
1561 assert(!PVS.empty() && "Outgoing edge is empty, field unused, can"
1562 " probably just leave the type opaque or something dumb.");
1563 unsigned Out;
1564 for (Out = 0; AbsPoolTyMap.count(PVS[Out].Node) == 0; ++Out)
1565 assert(Out != PVS.size() && "No edge to an outgoing allocation node!?");
1566
1567 assert(PVS[Out].Index == 0 && "Subindexing not implemented yet!");
1568
1569 // The actual struct type could change each time through the loop, so it's
1570 // NOT loop invariant.
1571 StructType *PoolTy = cast<StructType>(PoolTyH.get());
1572
1573 // Get the opaque type...
1574 DerivedType *ElTy =
1575 cast<DerivedType>(PoolTy->getElementTypes()[p+1].get());
1576
1577#ifdef DEBUG_CREATE_POOLS
1578 cerr << "Refining " << ElTy << " of " << PoolTy << " to "
1579 << AbsPoolTyMap.find(PVS[Out].Node)->second.get() << "\n";
1580#endif
1581
1582 const Type *RefPoolTy = AbsPoolTyMap.find(PVS[Out].Node)->second.get();
1583 ElTy->refineAbstractTypeTo(PointerType::get(RefPoolTy));
1584
1585#ifdef DEBUG_CREATE_POOLS
1586 cerr << "Result pool type is: " << PoolTyH.get() << "\n";
1587#endif
1588 }
1589 }
1590
1591 // Create the code that goes in the entry and exit nodes for the function...
Chris Lattnere0618ca2002-03-29 05:50:20 +00001592 vector<Instruction*> EntryNodeInsts;
1593 for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
Chris Lattner441e16f2002-04-12 20:23:15 +00001594 PoolInfo &PI = PoolDescs[Allocs[i]];
1595
1596 // Fill in the pool type for this pool...
1597 PI.PoolType = AbsPoolTyMap.find(Allocs[i])->second.get();
1598 assert(!PI.PoolType->isAbstract() &&
1599 "Pool type should not be abstract anymore!");
1600
Chris Lattnere0618ca2002-03-29 05:50:20 +00001601 // Add an allocation and a free for each pool...
Chris Lattner5da145b2002-04-13 19:52:54 +00001602 AllocaInst *PoolAlloc
1603 = new AllocaInst(PointerType::get(PI.PoolType), 0,
1604 CurModule->getTypeName(PI.PoolType));
Chris Lattner441e16f2002-04-12 20:23:15 +00001605 PI.Handle = PoolAlloc;
Chris Lattnere0618ca2002-03-29 05:50:20 +00001606 EntryNodeInsts.push_back(PoolAlloc);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001607 AllocationInst *AI = Allocs[i]->getAllocation();
1608
1609 // Initialize the pool. We need to know how big each allocation is. For
1610 // our purposes here, we assume we are allocating a scalar, or array of
1611 // constant size.
1612 //
Chris Lattneracf19022002-04-14 06:14:41 +00001613 unsigned ElSize = TargetData.getTypeSize(PI.NewType);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001614
1615 vector<Value*> Args;
Chris Lattnere0618ca2002-03-29 05:50:20 +00001616 Args.push_back(ConstantUInt::get(Type::UIntTy, ElSize));
Chris Lattner441e16f2002-04-12 20:23:15 +00001617 Args.push_back(PoolAlloc); // Pool to initialize
Chris Lattnere0618ca2002-03-29 05:50:20 +00001618 EntryNodeInsts.push_back(new CallInst(PoolInit, Args));
1619
Chris Lattner441e16f2002-04-12 20:23:15 +00001620 // Add code to destroy the pool in all of the exit nodes of the function...
Chris Lattner8f796d62002-04-13 19:25:57 +00001621 Args.clear();
1622 Args.push_back(PoolAlloc); // Pool to initialize
1623
Chris Lattnere0618ca2002-03-29 05:50:20 +00001624 for (unsigned EN = 0, ENE = ReturnNodes.size(); EN != ENE; ++EN) {
1625 Instruction *Destroy = new CallInst(PoolDestroy, Args);
1626
1627 // Insert it before the return instruction...
1628 BasicBlock *RetNode = ReturnNodes[EN];
1629 RetNode->getInstList().insert(RetNode->end()-1, Destroy);
1630 }
1631 }
1632
Chris Lattner5da145b2002-04-13 19:52:54 +00001633 // Now that all of the pool descriptors have been created, link them together
1634 // so that called functions can get links as neccesary...
1635 //
1636 for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
1637 PoolInfo &PI = PoolDescs[Allocs[i]];
1638
1639 // For every pointer in the data structure, initialize a link that
1640 // indicates which pool to access...
1641 //
1642 vector<Value*> Indices(2);
1643 Indices[0] = ConstantUInt::get(Type::UIntTy, 0);
1644 for (unsigned l = 0, le = PI.Node->getNumLinks(); l != le; ++l)
1645 // Only store an entry for the field if the field is used!
1646 if (!PI.Node->getLink(l).empty()) {
1647 assert(PI.Node->getLink(l).size() == 1 && "Should have only one link!");
1648 PointerVal PV = PI.Node->getLink(l)[0];
1649 assert(PV.Index == 0 && "Subindexing not supported yet!");
1650 PoolInfo &LinkedPool = PoolDescs[PV.Node];
1651 Indices[1] = ConstantUInt::get(Type::UByteTy, 1+l);
1652
1653 EntryNodeInsts.push_back(new StoreInst(LinkedPool.Handle, PI.Handle,
1654 Indices));
1655 }
1656 }
1657
Chris Lattnere0618ca2002-03-29 05:50:20 +00001658 // Insert the entry node code into the entry block...
1659 F->getEntryNode()->getInstList().insert(F->getEntryNode()->begin()+1,
1660 EntryNodeInsts.begin(),
1661 EntryNodeInsts.end());
Chris Lattner175f37c2002-03-29 03:40:59 +00001662}
1663
1664
Chris Lattner441e16f2002-04-12 20:23:15 +00001665// addPoolPrototypes - Add prototypes for the pool functions to the specified
Chris Lattner175f37c2002-03-29 03:40:59 +00001666// module and update the Pool* instance variables to point to them.
1667//
1668void PoolAllocate::addPoolPrototypes(Module *M) {
Chris Lattner441e16f2002-04-12 20:23:15 +00001669 // Get poolinit function...
Chris Lattnere0618ca2002-03-29 05:50:20 +00001670 vector<const Type*> Args;
Chris Lattnere0618ca2002-03-29 05:50:20 +00001671 Args.push_back(Type::UIntTy); // Num bytes per element
Chris Lattner441e16f2002-04-12 20:23:15 +00001672 FunctionType *PoolInitTy = FunctionType::get(Type::VoidTy, Args, true);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001673 PoolInit = M->getOrInsertFunction("poolinit", PoolInitTy);
Chris Lattner175f37c2002-03-29 03:40:59 +00001674
Chris Lattnere0618ca2002-03-29 05:50:20 +00001675 // Get pooldestroy function...
1676 Args.pop_back(); // Only takes a pool...
Chris Lattner441e16f2002-04-12 20:23:15 +00001677 FunctionType *PoolDestroyTy = FunctionType::get(Type::VoidTy, Args, true);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001678 PoolDestroy = M->getOrInsertFunction("pooldestroy", PoolDestroyTy);
1679
Chris Lattnere0618ca2002-03-29 05:50:20 +00001680 // Get the poolalloc function...
Chris Lattner441e16f2002-04-12 20:23:15 +00001681 FunctionType *PoolAllocTy = FunctionType::get(POINTERTYPE, Args, true);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001682 PoolAlloc = M->getOrInsertFunction("poolalloc", PoolAllocTy);
1683
1684 // Get the poolfree function...
Chris Lattner441e16f2002-04-12 20:23:15 +00001685 Args.push_back(POINTERTYPE); // Pointer to free
1686 FunctionType *PoolFreeTy = FunctionType::get(Type::VoidTy, Args, true);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001687 PoolFree = M->getOrInsertFunction("poolfree", PoolFreeTy);
1688
1689 // Add the %PoolTy type to the symbol table of the module...
Chris Lattner441e16f2002-04-12 20:23:15 +00001690 //M->addTypeName("PoolTy", PoolTy->getElementType());
Chris Lattner175f37c2002-03-29 03:40:59 +00001691}
1692
1693
1694bool PoolAllocate::run(Module *M) {
1695 addPoolPrototypes(M);
1696 CurModule = M;
1697
1698 DS = &getAnalysis<DataStructure>();
1699 bool Changed = false;
Chris Lattner291a1b12002-03-29 19:05:48 +00001700
1701 // We cannot use an iterator here because it will get invalidated when we add
1702 // functions to the module later...
1703 for (unsigned i = 0; i != M->size(); ++i)
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001704 if (!M->getFunctionList()[i]->isExternal()) {
Chris Lattner291a1b12002-03-29 19:05:48 +00001705 Changed |= processFunction(M->getFunctionList()[i]);
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001706 if (Changed) {
1707 cerr << "Only processing one function\n";
1708 break;
1709 }
1710 }
Chris Lattner175f37c2002-03-29 03:40:59 +00001711
1712 CurModule = 0;
1713 DS = 0;
1714 return false;
1715}
1716
1717
1718// createPoolAllocatePass - Global function to access the functionality of this
1719// pass...
1720//
Chris Lattner64fd9352002-03-28 18:08:31 +00001721Pass *createPoolAllocatePass() { return new PoolAllocate(); }