Move FunctionArgument out of iOther.h into Argument.h and rename class to
[oota-llvm.git] / lib / Transforms / IPO / OldPoolAllocate.cpp
1 //===-- PoolAllocate.cpp - Pool Allocation Pass ---------------------------===//
2 //
3 // This transform changes programs so that disjoint data structures are
4 // allocated out of different pools of memory, increasing locality and shrinking
5 // pointer size.
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "llvm/Transforms/IPO/PoolAllocate.h"
10 #include "llvm/Transforms/CloneFunction.h"
11 #include "llvm/Analysis/DataStructure.h"
12 #include "llvm/Analysis/DataStructureGraph.h"
13 #include "llvm/Pass.h"
14 #include "llvm/Module.h"
15 #include "llvm/Function.h"
16 #include "llvm/BasicBlock.h"
17 #include "llvm/iMemory.h"
18 #include "llvm/iTerminators.h"
19 #include "llvm/iOther.h"
20 #include "llvm/ConstantVals.h"
21 #include "llvm/Target/TargetData.h"
22 #include "llvm/Support/InstVisitor.h"
23 #include "llvm/Argument.h"
24 #include "Support/DepthFirstIterator.h"
25 #include "Support/STLExtras.h"
26 #include <algorithm>
27
28
29 // FIXME: This is dependant on the sparc backend layout conventions!!
30 static TargetData TargetData("test");
31
32 namespace {
33   // ScalarInfo - Information about an LLVM value that we know points to some
34   // datastructure we are processing.
35   //
36   struct ScalarInfo {
37     Value  *Val;            // Scalar value in Current Function
38     DSNode *Node;           // DataStructure node it points to
39     Value  *PoolHandle;     // PoolTy* LLVM value
40     
41     ScalarInfo(Value *V, DSNode *N, Value *PH)
42       : Val(V), Node(N), PoolHandle(PH) {
43       assert(V && N && PH && "Null value passed to ScalarInfo ctor!");
44     }
45   };
46
47   // CallArgInfo - Information on one operand for a call that got expanded.
48   struct CallArgInfo {
49     int ArgNo;          // Call argument number this corresponds to
50     DSNode *Node;       // The graph node for the pool
51     Value *PoolHandle;  // The LLVM value that is the pool pointer
52
53     CallArgInfo(int Arg, DSNode *N, Value *PH)
54       : ArgNo(Arg), Node(N), PoolHandle(PH) {
55       assert(Arg >= -1 && N && PH && "Illegal values to CallArgInfo ctor!");
56     }
57
58     // operator< when sorting, sort by argument number.
59     bool operator<(const CallArgInfo &CAI) const {
60       return ArgNo < CAI.ArgNo;
61     }
62   };
63
64   // TransformFunctionInfo - Information about how a function eeds to be
65   // transformed.
66   //
67   struct TransformFunctionInfo {
68     // ArgInfo - Maintain information about the arguments that need to be
69     // processed.  Each pair corresponds to an argument (whose number is the
70     // first element) that needs to have a pool pointer (the second element)
71     // passed into the transformed function with it.
72     //
73     // As a special case, "argument" number -1 corresponds to the return value.
74     //
75     vector<CallArgInfo> ArgInfo;
76
77     // Func - The function to be transformed...
78     Function *Func;
79
80     // The call instruction that is used to map CallArgInfo PoolHandle values
81     // into the new function values.
82     CallInst *Call;
83
84     // default ctor...
85     TransformFunctionInfo() : Func(0), Call(0) {}
86     
87     bool operator<(const TransformFunctionInfo &TFI) const {
88       if (Func < TFI.Func) return true;
89       if (Func > TFI.Func) return false;
90       if (ArgInfo.size() < TFI.ArgInfo.size()) return true;
91       if (ArgInfo.size() > TFI.ArgInfo.size()) return false;
92       return ArgInfo < TFI.ArgInfo;
93     }
94
95     void finalizeConstruction() {
96       // Sort the vector so that the return value is first, followed by the
97       // argument records, in order.  Note that this must be a stable sort so
98       // that the entries with the same sorting criteria (ie they are multiple
99       // pool entries for the same argument) are kept in depth first order.
100       stable_sort(ArgInfo.begin(), ArgInfo.end());
101     }
102   };
103
104
105   // Define the pass class that we implement...
106   class PoolAllocate : public Pass {
107     // PoolTy - The type of a scalar value that contains a pool pointer.
108     PointerType *PoolTy;
109   public:
110
111     PoolAllocate() {
112       // Initialize the PoolTy instance variable, since the type never changes.
113       vector<const Type*> PoolElements;
114       PoolElements.push_back(PointerType::get(Type::SByteTy));
115       PoolElements.push_back(Type::UIntTy);
116       PoolTy = PointerType::get(StructType::get(PoolElements));
117       // PoolTy = { sbyte*, uint }*
118
119       CurModule = 0; DS = 0;
120       PoolInit = PoolDestroy = PoolAlloc = PoolFree = 0;
121     }
122
123     bool run(Module *M);
124
125     // getAnalysisUsageInfo - This function requires data structure information
126     // to be able to see what is pool allocatable.
127     //
128     virtual void getAnalysisUsageInfo(Pass::AnalysisSet &Required,
129                                       Pass::AnalysisSet &,Pass::AnalysisSet &) {
130       Required.push_back(DataStructure::ID);
131     }
132
133   public:
134     // CurModule - The module being processed.
135     Module *CurModule;
136
137     // DS - The data structure graph for the module being processed.
138     DataStructure *DS;
139
140     // Prototypes that we add to support pool allocation...
141     Function *PoolInit, *PoolDestroy, *PoolAlloc, *PoolFree;
142
143     // The map of already transformed functions... note that the keys of this
144     // map do not have meaningful values for 'Call' or the 'PoolHandle' elements
145     // of the ArgInfo elements.
146     //
147     map<TransformFunctionInfo, Function*> TransformedFunctions;
148
149     // getTransformedFunction - Get a transformed function, or return null if
150     // the function specified hasn't been transformed yet.
151     //
152     Function *getTransformedFunction(TransformFunctionInfo &TFI) const {
153       map<TransformFunctionInfo, Function*>::const_iterator I =
154         TransformedFunctions.find(TFI);
155       if (I != TransformedFunctions.end()) return I->second;
156       return 0;
157     }
158
159
160     // addPoolPrototypes - Add prototypes for the pool methods to the specified
161     // module and update the Pool* instance variables to point to them.
162     //
163     void addPoolPrototypes(Module *M);
164
165
166     // CreatePools - Insert instructions into the function we are processing to
167     // create all of the memory pool objects themselves.  This also inserts
168     // destruction code.  Add an alloca for each pool that is allocated to the
169     // PoolDescriptors map.
170     //
171     void CreatePools(Function *F, const vector<AllocDSNode*> &Allocs,
172                      map<DSNode*, Value*> &PoolDescriptors);
173
174     // processFunction - Convert a function to use pool allocation where
175     // available.
176     //
177     bool processFunction(Function *F);
178
179     // transformFunctionBody - This transforms the instruction in 'F' to use the
180     // pools specified in PoolDescriptors when modifying data structure nodes
181     // specified in the PoolDescriptors map.  IPFGraph is the closed data
182     // structure graph for F, of which the PoolDescriptor nodes come from.
183     //
184     void transformFunctionBody(Function *F, FunctionDSGraph &IPFGraph,
185                                map<DSNode*, Value*> &PoolDescriptors);
186
187     // transformFunction - Transform the specified function the specified way.
188     // It we have already transformed that function that way, don't do anything.
189     // The nodes in the TransformFunctionInfo come out of callers data structure
190     // graph.
191     //
192     void transformFunction(TransformFunctionInfo &TFI,
193                            FunctionDSGraph &CallerIPGraph);
194
195   };
196 }
197
198
199
200 // isNotPoolableAlloc - This is a predicate that returns true if the specified
201 // allocation node in a data structure graph is eligable for pool allocation.
202 //
203 static bool isNotPoolableAlloc(const AllocDSNode *DS) {
204   if (DS->isAllocaNode()) return true;  // Do not pool allocate alloca's.
205
206   MallocInst *MI = cast<MallocInst>(DS->getAllocation());
207   if (MI->isArrayAllocation() && !isa<Constant>(MI->getArraySize()))
208     return true;   // Do not allow variable size allocations...
209
210   return false;
211 }
212
213 // processFunction - Convert a function to use pool allocation where
214 // available.
215 //
216 bool PoolAllocate::processFunction(Function *F) {
217   // Get the closed datastructure graph for the current function... if there are
218   // any allocations in this graph that are not escaping, we need to pool
219   // allocate them here!
220   //
221   FunctionDSGraph &IPGraph = DS->getClosedDSGraph(F);
222
223   // Get all of the allocations that do not escape the current function.  Since
224   // they are still live (they exist in the graph at all), this means we must
225   // have scalar references to these nodes, but the scalars are never returned.
226   // 
227   vector<AllocDSNode*> Allocs;
228   IPGraph.getNonEscapingAllocations(Allocs);
229
230   // Filter out allocations that we cannot handle.  Currently, this includes
231   // variable sized array allocations and alloca's (which we do not want to
232   // pool allocate)
233   //
234   Allocs.erase(remove_if(Allocs.begin(), Allocs.end(), isNotPoolableAlloc),
235                Allocs.end());
236
237
238   if (Allocs.empty()) return false;  // Nothing to do.
239
240   // Insert instructions into the function we are processing to create all of
241   // the memory pool objects themselves.  This also inserts destruction code.
242   // This fills in the PoolDescriptors map to associate the alloc node with the
243   // allocation of the memory pool corresponding to it.
244   // 
245   map<DSNode*, Value*> PoolDescriptors;
246   CreatePools(F, Allocs, PoolDescriptors);
247
248   // Now we need to figure out what called methods we need to transform, and
249   // how.  To do this, we look at all of the scalars, seeing which functions are
250   // either used as a scalar value (so they return a data structure), or are
251   // passed one of our scalar values.
252   //
253   transformFunctionBody(F, IPGraph, PoolDescriptors);
254
255   return true;
256 }
257
258
259 class FunctionBodyTransformer : public InstVisitor<FunctionBodyTransformer> {
260   PoolAllocate &PoolAllocator;
261   vector<ScalarInfo> &Scalars;
262   map<CallInst*, TransformFunctionInfo> &CallMap;
263
264   const ScalarInfo &getScalar(const Value *V) {
265     for (unsigned i = 0, e = Scalars.size(); i != e; ++i)
266       if (Scalars[i].Val == V) return Scalars[i];
267     assert(0 && "Scalar not found in getScalar!");
268     abort();
269     return Scalars[0];
270   }
271
272   // updateScalars - Map the scalars array entries that look like 'From' to look
273   // like 'To'.
274   //
275   void updateScalars(Value *From, Value *To) {
276     for (unsigned i = 0, e = Scalars.size(); i != e; ++i)
277       if (Scalars[i].Val == From) Scalars[i].Val = To;
278   }
279
280 public:
281   FunctionBodyTransformer(PoolAllocate &PA, vector<ScalarInfo> &S,
282                           map<CallInst*, TransformFunctionInfo> &C)
283     : PoolAllocator(PA), Scalars(S), CallMap(C) {}
284
285   void visitMemAccessInst(MemAccessInst *MAI) {
286     // Don't do anything to load, store, or GEP yet...
287   }
288
289   // Convert a malloc instruction into a call to poolalloc
290   void visitMallocInst(MallocInst *I) {
291     const ScalarInfo &SC = getScalar(I);
292     BasicBlock *BB = I->getParent();
293     BasicBlock::iterator MI = find(BB->begin(), BB->end(), I);
294     BB->getInstList().remove(MI);  // Remove the Malloc instruction from the BB
295
296     // Create a new call to poolalloc before the malloc instruction
297     vector<Value*> Args;
298     Args.push_back(SC.PoolHandle);
299     CallInst *Call = new CallInst(PoolAllocator.PoolAlloc, Args, I->getName());
300     MI = BB->getInstList().insert(MI, Call)+1;
301
302     // If the type desired is not void*, cast it now...
303     Value *Ptr = Call;
304     if (Call->getType() != I->getType()) {
305       CastInst *CI = new CastInst(Ptr, I->getType(), I->getName());
306       BB->getInstList().insert(MI, CI);
307       Ptr = CI;
308     }
309
310     // Change everything that used the malloc to now use the pool alloc...
311     I->replaceAllUsesWith(Ptr);
312
313     // Update the scalars array...
314     updateScalars(I, Ptr);
315
316     // Delete the instruction now.
317     delete I;
318   }
319
320   // Convert the free instruction into a call to poolfree
321   void visitFreeInst(FreeInst *I) {
322     Value *Ptr = I->getOperand(0);
323     const ScalarInfo &SC = getScalar(Ptr);
324     BasicBlock *BB = I->getParent();
325     BasicBlock::iterator FI = find(BB->begin(), BB->end(), I);
326
327     // If the value is not an sbyte*, convert it now!
328     if (Ptr->getType() != PointerType::get(Type::SByteTy)) {
329       CastInst *CI = new CastInst(Ptr, PointerType::get(Type::SByteTy),
330                                   Ptr->getName());
331       FI = BB->getInstList().insert(FI, CI)+1;
332       Ptr = CI;
333     }
334
335     // Create a new call to poolfree before the free instruction
336     vector<Value*> Args;
337     Args.push_back(SC.PoolHandle);
338     Args.push_back(Ptr);
339     CallInst *Call = new CallInst(PoolAllocator.PoolFree, Args);
340     FI = BB->getInstList().insert(FI, Call)+1;
341
342     // Remove the old free instruction...
343     delete BB->getInstList().remove(FI);
344   }
345
346   // visitCallInst - Create a new call instruction with the extra arguments for
347   // all of the memory pools that the call needs.
348   //
349   void visitCallInst(CallInst *I) {
350     TransformFunctionInfo &TI = CallMap[I];
351     BasicBlock *BB = I->getParent();
352     BasicBlock::iterator CI = find(BB->begin(), BB->end(), I);
353     BB->getInstList().remove(CI);  // Remove the old call instruction
354
355     // Start with all of the old arguments...
356     vector<Value*> Args(I->op_begin()+1, I->op_end());
357
358     // Add all of the pool arguments...
359     for (unsigned i = 0, e = TI.ArgInfo.size(); i != e; ++i)
360       Args.push_back(TI.ArgInfo[i].PoolHandle);
361     
362     Function *NF = PoolAllocator.getTransformedFunction(TI);
363     CallInst *NewCall = new CallInst(NF, Args, I->getName());
364     BB->getInstList().insert(CI, NewCall);
365
366     // Change everything that used the malloc to now use the pool alloc...
367     if (I->getType() != Type::VoidTy) {
368       I->replaceAllUsesWith(NewCall);
369
370       // Update the scalars array...
371       updateScalars(I, NewCall);
372     }
373
374     delete I;  // Delete the old call instruction now...
375   }
376
377   void visitPHINode(PHINode *PN) {
378     // Handle PHI Node
379   }
380
381   void visitReturnInst(ReturnInst *I) {
382     // Nothing of interest
383   }
384
385   void visitSetCondInst(SetCondInst *SCI) {
386     // hrm, notice a pattern?
387   }
388
389   void visitInstruction(Instruction *I) {
390     cerr << "Unknown instruction to FunctionBodyTransformer:\n";
391     I->dump();
392   }
393
394 };
395
396
397 static void addCallInfo(DataStructure *DS,
398                         TransformFunctionInfo &TFI, CallInst *CI, int Arg, 
399                         DSNode *GraphNode,
400                         map<DSNode*, Value*> &PoolDescriptors) {
401   assert(CI->getCalledFunction() && "Cannot handle indirect calls yet!");
402   assert(TFI.Func == 0 || TFI.Func == CI->getCalledFunction() &&
403          "Function call record should always call the same function!");
404   assert(TFI.Call == 0 || TFI.Call == CI &&
405          "Call element already filled in with different value!");
406   TFI.Func = CI->getCalledFunction();
407   TFI.Call = CI;
408   //FunctionDSGraph &CalledGraph = DS->getClosedDSGraph(TFI.Func);
409
410   // For now, add the entire graph that is pointed to by the call argument.
411   // This graph can and should be pruned to only what the function itself will
412   // use, because often this will be a dramatically smaller subset of what we
413   // are providing.
414   //
415   for (df_iterator<DSNode*> I = df_begin(GraphNode), E = df_end(GraphNode);
416        I != E; ++I) {
417     TFI.ArgInfo.push_back(CallArgInfo(Arg, *I, PoolDescriptors[*I]));
418   }
419 }
420
421
422 // transformFunctionBody - This transforms the instruction in 'F' to use the
423 // pools specified in PoolDescriptors when modifying data structure nodes
424 // specified in the PoolDescriptors map.  Specifically, scalar values specified
425 // in the Scalars vector must be remapped.  IPFGraph is the closed data
426 // structure graph for F, of which the PoolDescriptor nodes come from.
427 //
428 void PoolAllocate::transformFunctionBody(Function *F, FunctionDSGraph &IPFGraph,
429                                        map<DSNode*, Value*> &PoolDescriptors) {
430
431   // Loop through the value map looking for scalars that refer to nonescaping
432   // allocations.  Add them to the Scalars vector.  Note that we may have
433   // multiple entries in the Scalars vector for each value if it points to more
434   // than one object.
435   //
436   map<Value*, PointerValSet> &ValMap = IPFGraph.getValueMap();
437   vector<ScalarInfo> Scalars;
438
439   cerr << "Building scalar map:\n";
440
441   for (map<Value*, PointerValSet>::iterator I = ValMap.begin(),
442          E = ValMap.end(); I != E; ++I) {
443     const PointerValSet &PVS = I->second;  // Set of things pointed to by scalar
444
445     cerr << "Scalar Mapping from:"; I->first->dump();
446     cerr << "\nScalar Mapping to: "; PVS.print(cerr);
447
448     // Check to see if the scalar points to a data structure node...
449     for (unsigned i = 0, e = PVS.size(); i != e; ++i) {
450       assert(PVS[i].Index == 0 && "Nonzero not handled yet!");
451         
452       // If the allocation is in the nonescaping set...
453       map<DSNode*, Value*>::iterator AI = PoolDescriptors.find(PVS[i].Node);
454       if (AI != PoolDescriptors.end()) // Add it to the list of scalars
455         Scalars.push_back(ScalarInfo(I->first, PVS[i].Node, AI->second));
456     }
457   }
458
459
460
461   cerr << "\nIn '" << F->getName()
462        << "': Found the following values that point to poolable nodes:\n";
463
464   for (unsigned i = 0, e = Scalars.size(); i != e; ++i)
465     Scalars[i].Val->dump();
466
467   // CallMap - Contain an entry for every call instruction that needs to be
468   // transformed.  Each entry in the map contains information about what we need
469   // to do to each call site to change it to work.
470   //
471   map<CallInst*, TransformFunctionInfo> CallMap;
472
473   // Now we need to figure out what called methods we need to transform, and
474   // how.  To do this, we look at all of the scalars, seeing which functions are
475   // either used as a scalar value (so they return a data structure), or are
476   // passed one of our scalar values.
477   //
478   for (unsigned i = 0, e = Scalars.size(); i != e; ++i) {
479     Value *ScalarVal = Scalars[i].Val;
480
481     // Check to see if the scalar _IS_ a call...
482     if (CallInst *CI = dyn_cast<CallInst>(ScalarVal))
483       // If so, add information about the pool it will be returning...
484       addCallInfo(DS, CallMap[CI], CI, -1, Scalars[i].Node, PoolDescriptors);
485
486     // Check to see if the scalar is an operand to a call...
487     for (Value::use_iterator UI = ScalarVal->use_begin(),
488            UE = ScalarVal->use_end(); UI != UE; ++UI) {
489       if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
490         // Find out which operand this is to the call instruction...
491         User::op_iterator OI = find(CI->op_begin(), CI->op_end(), ScalarVal);
492         assert(OI != CI->op_end() && "Call on use list but not an operand!?");
493         assert(OI != CI->op_begin() && "Pointer operand is call destination?");
494
495         // FIXME: This is broken if the same pointer is passed to a call more
496         // than once!  It will get multiple entries for the first pointer.
497
498         // Add the operand number and pool handle to the call table...
499         addCallInfo(DS, CallMap[CI], CI, OI-CI->op_begin()-1, Scalars[i].Node,
500                     PoolDescriptors);
501       }
502     }
503   }
504
505   // Print out call map...
506   for (map<CallInst*, TransformFunctionInfo>::iterator I = CallMap.begin();
507        I != CallMap.end(); ++I) {
508     cerr << "\nFor call: ";
509     I->first->dump();
510     I->second.finalizeConstruction();
511     cerr << I->second.Func->getName() << " must pass pool pointer for args #";
512     for (unsigned i = 0; i < I->second.ArgInfo.size(); ++i)
513       cerr << I->second.ArgInfo[i].ArgNo << ", ";
514     cerr << "\n";
515   }
516
517   // Loop through all of the call nodes, recursively creating the new functions
518   // that we want to call...  This uses a map to prevent infinite recursion and
519   // to avoid duplicating functions unneccesarily.
520   //
521   for (map<CallInst*, TransformFunctionInfo>::iterator I = CallMap.begin(),
522          E = CallMap.end(); I != E; ++I) {
523     // Make sure the entries are sorted.
524     I->second.finalizeConstruction();
525
526     // Transform all of the functions we need, or at least ensure there is a
527     // cached version available.
528     transformFunction(I->second, IPFGraph);
529   }
530
531   // Now that all of the functions that we want to call are available, transform
532   // the local method so that it uses the pools locally and passes them to the
533   // functions that we just hacked up.
534   //
535
536   // First step, find the instructions to be modified.
537   vector<Instruction*> InstToFix;
538   for (unsigned i = 0, e = Scalars.size(); i != e; ++i) {
539     Value *ScalarVal = Scalars[i].Val;
540
541     // Check to see if the scalar _IS_ an instruction.  If so, it is involved.
542     if (Instruction *Inst = dyn_cast<Instruction>(ScalarVal))
543       InstToFix.push_back(Inst);
544
545     // All all of the instructions that use the scalar as an operand...
546     for (Value::use_iterator UI = ScalarVal->use_begin(),
547            UE = ScalarVal->use_end(); UI != UE; ++UI)
548       InstToFix.push_back(dyn_cast<Instruction>(*UI));
549   }
550
551   // Eliminate duplicates by sorting, then removing equal neighbors.
552   sort(InstToFix.begin(), InstToFix.end());
553   InstToFix.erase(unique(InstToFix.begin(), InstToFix.end()), InstToFix.end());
554
555   // Use a FunctionBodyTransformer to transform all of the involved instructions
556   FunctionBodyTransformer FBT(*this, Scalars, CallMap);
557   for (unsigned i = 0, e = InstToFix.size(); i != e; ++i)
558     FBT.visit(InstToFix[i]);
559
560
561   // Since we have liberally hacked the function to pieces, we want to inform
562   // the datastructure pass that its internal representation is out of date.
563   //
564   DS->invalidateFunction(F);
565 }
566
567 static void addNodeMapping(DSNode *SrcNode, const PointerValSet &PVS,
568                            map<DSNode*, PointerValSet> &NodeMapping) {
569   for (unsigned i = 0, e = PVS.size(); i != e; ++i)
570     if (NodeMapping[SrcNode].add(PVS[i])) {  // Not in map yet?
571       assert(PVS[i].Index == 0 && "Node indexing not supported yet!");
572       DSNode *DestNode = PVS[i].Node;
573
574       // Loop over all of the outgoing links in the mapped graph
575       for (unsigned l = 0, le = DestNode->getNumOutgoingLinks(); l != le; ++l) {
576         PointerValSet &SrcSet = SrcNode->getOutgoingLink(l);
577         const PointerValSet &DestSet = DestNode->getOutgoingLink(l);
578
579         // Add all of the node mappings now!
580         for (unsigned si = 0, se = SrcSet.size(); si != se; ++si) {
581           assert(SrcSet[si].Index == 0 && "Can't handle node offset!");
582           addNodeMapping(SrcSet[si].Node, DestSet, NodeMapping);
583         }
584       }
585     }
586 }
587
588 // CalculateNodeMapping - There is a partial isomorphism between the graph
589 // passed in and the graph that is actually used by the function.  We need to
590 // figure out what this mapping is so that we can transformFunctionBody the
591 // instructions in the function itself.  Note that every node in the graph that
592 // we are interested in must be both in the local graph of the called function,
593 // and in the local graph of the calling function.  Because of this, we only
594 // define the mapping for these nodes [conveniently these are the only nodes we
595 // CAN define a mapping for...]
596 //
597 // The roots of the graph that we are transforming is rooted in the arguments
598 // passed into the function from the caller.  This is where we start our
599 // mapping calculation.
600 //
601 // The NodeMapping calculated maps from the callers graph to the called graph.
602 //
603 static void CalculateNodeMapping(Function *F, TransformFunctionInfo &TFI,
604                                  FunctionDSGraph &CallerGraph,
605                                  FunctionDSGraph &CalledGraph, 
606                                  map<DSNode*, PointerValSet> &NodeMapping) {
607   int LastArgNo = -2;
608   for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i) {
609     // Figure out what nodes in the called graph the TFI.ArgInfo[i].Node node
610     // corresponds to...
611     //
612     // Only consider first node of sequence.  Extra nodes may may be added
613     // to the TFI if the data structure requires more nodes than just the
614     // one the argument points to.  We are only interested in the one the
615     // argument points to though.
616     //
617     if (TFI.ArgInfo[i].ArgNo != LastArgNo) {
618       if (TFI.ArgInfo[i].ArgNo == -1) {
619         addNodeMapping(TFI.ArgInfo[i].Node, CalledGraph.getRetNodes(),
620                        NodeMapping);
621       } else {
622         // Figure out which node argument # ArgNo points to in the called graph.
623         Value *Arg = F->getArgumentList()[TFI.ArgInfo[i].ArgNo];     
624         addNodeMapping(TFI.ArgInfo[i].Node, CalledGraph.getValueMap()[Arg],
625                        NodeMapping);
626       }
627       LastArgNo = TFI.ArgInfo[i].ArgNo;
628     }
629   }
630 }
631
632
633 // transformFunction - Transform the specified function the specified way.  It
634 // we have already transformed that function that way, don't do anything.  The
635 // nodes in the TransformFunctionInfo come out of callers data structure graph.
636 //
637 void PoolAllocate::transformFunction(TransformFunctionInfo &TFI,
638                                      FunctionDSGraph &CallerIPGraph) {
639   if (getTransformedFunction(TFI)) return;  // Function xformation already done?
640
641   cerr << "**********\nEntering transformFunction for "
642        << TFI.Func->getName() << ":\n";
643   for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i)
644     cerr << "  ArgInfo[" << i << "] = " << TFI.ArgInfo[i].ArgNo << "\n";
645   cerr << "\n";
646
647
648   const FunctionType *OldFuncType = TFI.Func->getFunctionType();
649
650   assert(!OldFuncType->isVarArg() && "Vararg functions not handled yet!");
651
652   // Build the type for the new function that we are transforming
653   vector<const Type*> ArgTys;
654   for (unsigned i = 0, e = OldFuncType->getNumParams(); i != e; ++i)
655     ArgTys.push_back(OldFuncType->getParamType(i));
656
657   // Add one pool pointer for every argument that needs to be supplemented.
658   ArgTys.insert(ArgTys.end(), TFI.ArgInfo.size(), PoolTy);
659
660   // Build the new function type...
661   const // FIXME when types are not const
662   FunctionType *NewFuncType = FunctionType::get(OldFuncType->getReturnType(),
663                                                 ArgTys,OldFuncType->isVarArg());
664
665   // The new function is internal, because we know that only we can call it.
666   // This also helps subsequent IP transformations to eliminate duplicated pool
667   // pointers. [in the future when they are implemented].
668   //
669   Function *NewFunc = new Function(NewFuncType, true,
670                                    TFI.Func->getName()+".poolxform");
671   CurModule->getFunctionList().push_back(NewFunc);
672
673   // Add the newly formed function to the TransformedFunctions table so that
674   // infinite recursion does not occur!
675   //
676   TransformedFunctions[TFI] = NewFunc;
677
678   // Add arguments to the function... starting with all of the old arguments
679   vector<Value*> ArgMap;
680   for (unsigned i = 0, e = TFI.Func->getArgumentList().size(); i != e; ++i) {
681     const Argument *OFA = TFI.Func->getArgumentList()[i];
682     Argument *NFA = new Argument(OFA->getType(), OFA->getName());
683     NewFunc->getArgumentList().push_back(NFA);
684     ArgMap.push_back(NFA);  // Keep track of the arguments 
685   }
686
687   // Now add all of the arguments corresponding to pools passed in...
688   for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i) {
689     string Name;
690     if (TFI.ArgInfo[i].ArgNo == -1)
691       Name = "retpool";
692     else
693       Name = ArgMap[TFI.ArgInfo[i].ArgNo]->getName();  // Get the arg name
694     Argument *NFA = new Argument(PoolTy, Name+".pool");
695     NewFunc->getArgumentList().push_back(NFA);
696   }
697
698   // Now clone the body of the old function into the new function...
699   CloneFunctionInto(NewFunc, TFI.Func, ArgMap);
700   
701   // Okay, now we have a function that is identical to the old one, except that
702   // it has extra arguments for the pools coming in.  Now we have to get the 
703   // data structure graph for the function we are replacing, and figure out how
704   // our graph nodes map to the graph nodes in the dest function.
705   //
706   FunctionDSGraph &DSGraph = DS->getClosedDSGraph(NewFunc);  
707
708   // NodeMapping - Multimap from callers graph to called graph.
709   //
710   map<DSNode*, PointerValSet> NodeMapping;
711
712   CalculateNodeMapping(NewFunc, TFI, CallerIPGraph, DSGraph, 
713                        NodeMapping);
714
715   // Print out the node mapping...
716   cerr << "\nNode mapping for call of " << NewFunc->getName() << "\n";
717   for (map<DSNode*, PointerValSet>::iterator I = NodeMapping.begin();
718        I != NodeMapping.end(); ++I) {
719     cerr << "Map: "; I->first->print(cerr);
720     cerr << "To:  "; I->second.print(cerr);
721     cerr << "\n";
722   }
723
724   // Fill in the PoolDescriptor information for the transformed function so that
725   // it can determine which value holds the pool descriptor for each data
726   // structure node that it accesses.
727   //
728   map<DSNode*, Value*> PoolDescriptors;
729
730   cerr << "\nCalculating the pool descriptor map:\n";
731
732   // All of the pool descriptors must be passed in as arguments...
733   for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i) {
734     DSNode *CallerNode = TFI.ArgInfo[i].Node;
735     Value  *CallerPool = TFI.ArgInfo[i].PoolHandle;
736
737     cerr << "Mapped caller node: "; CallerNode->print(cerr);
738     cerr << "Mapped caller pool: "; CallerPool->dump();
739
740     // Calculate the argument number that the pool is to the function call...
741     // The call instruction should not have the pool operands added yet.
742     unsigned ArgNo = TFI.Call->getNumOperands()-1+i;
743     cerr << "Should be argument #: " << ArgNo << "[i = " << i << "]\n";
744     assert(ArgNo < NewFunc->getArgumentList().size() &&
745            "Call already has pool arguments added??");
746
747     // Map the pool argument into the called function...
748     Value *CalleePool = NewFunc->getArgumentList()[ArgNo];
749
750     // Map the DSNode into the callee's DSGraph
751     const PointerValSet &CalleeNodes = NodeMapping[CallerNode];
752     for (unsigned n = 0, ne = CalleeNodes.size(); n != ne; ++n) {
753       assert(CalleeNodes[n].Index == 0 && "Indexed node not handled yet!");
754       DSNode *CalleeNode = CalleeNodes[n].Node;
755
756       cerr << "*** to callee node: "; CalleeNode->print(cerr);
757       cerr << "*** to callee pool: "; CalleePool->dump();
758       cerr << "\n";
759       
760       assert(CalleeNode && CalleePool && "Invalid nodes!");
761       Value *&PV = PoolDescriptors[CalleeNode];
762       //assert((PV == 0 || PV == CalleePool) && "Invalid node remapping!");
763       PV = CalleePool;         // Update the pool descriptor map!
764     }
765   }
766
767   // We must destroy the node mapping so that we don't have latent references
768   // into the data structure graph for the new function.  Otherwise we get
769   // assertion failures when transformFunctionBody tries to invalidate the
770   // graph.
771   //
772   NodeMapping.clear();
773
774   // Now that we know everything we need about the function, transform the body
775   // now!
776   //
777   transformFunctionBody(NewFunc, DSGraph, PoolDescriptors);
778
779   cerr << "Function after transformation:\n";
780   NewFunc->dump();
781 }
782
783
784 // CreatePools - Insert instructions into the function we are processing to
785 // create all of the memory pool objects themselves.  This also inserts
786 // destruction code.  Add an alloca for each pool that is allocated to the
787 // PoolDescriptors vector.
788 //
789 void PoolAllocate::CreatePools(Function *F, const vector<AllocDSNode*> &Allocs,
790                                map<DSNode*, Value*> &PoolDescriptors) {
791   // FIXME: This should use an IP version of the UnifyAllExits pass!
792   vector<BasicBlock*> ReturnNodes;
793   for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
794     if (isa<ReturnInst>((*I)->getTerminator()))
795       ReturnNodes.push_back(*I);
796   
797
798   // Create the code that goes in the entry and exit nodes for the method...
799   vector<Instruction*> EntryNodeInsts;
800   for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
801     // Add an allocation and a free for each pool...
802     AllocaInst *PoolAlloc = new AllocaInst(PoolTy, 0, "pool");
803     EntryNodeInsts.push_back(PoolAlloc);
804     PoolDescriptors[Allocs[i]] = PoolAlloc;   // Keep track of pool allocas
805     AllocationInst *AI = Allocs[i]->getAllocation();
806
807     // Initialize the pool.  We need to know how big each allocation is.  For
808     // our purposes here, we assume we are allocating a scalar, or array of
809     // constant size.
810     //
811     unsigned ElSize = TargetData.getTypeSize(AI->getAllocatedType());
812     ElSize *= cast<ConstantUInt>(AI->getArraySize())->getValue();
813
814     vector<Value*> Args;
815     Args.push_back(PoolAlloc);    // Pool to initialize
816     Args.push_back(ConstantUInt::get(Type::UIntTy, ElSize));
817     EntryNodeInsts.push_back(new CallInst(PoolInit, Args));
818
819     // Destroy the pool...
820     Args.pop_back();
821
822     for (unsigned EN = 0, ENE = ReturnNodes.size(); EN != ENE; ++EN) {
823       Instruction *Destroy = new CallInst(PoolDestroy, Args);
824
825       // Insert it before the return instruction...
826       BasicBlock *RetNode = ReturnNodes[EN];
827       RetNode->getInstList().insert(RetNode->end()-1, Destroy);
828     }
829   }
830
831   // Insert the entry node code into the entry block...
832   F->getEntryNode()->getInstList().insert(F->getEntryNode()->begin()+1,
833                                           EntryNodeInsts.begin(),
834                                           EntryNodeInsts.end());
835 }
836
837
838 // addPoolPrototypes - Add prototypes for the pool methods to the specified
839 // module and update the Pool* instance variables to point to them.
840 //
841 void PoolAllocate::addPoolPrototypes(Module *M) {
842   // Get PoolInit function...
843   vector<const Type*> Args;
844   Args.push_back(PoolTy);           // Pool to initialize
845   Args.push_back(Type::UIntTy);     // Num bytes per element
846   FunctionType *PoolInitTy = FunctionType::get(Type::VoidTy, Args, false);
847   PoolInit = M->getOrInsertFunction("poolinit", PoolInitTy);
848
849   // Get pooldestroy function...
850   Args.pop_back();  // Only takes a pool...
851   FunctionType *PoolDestroyTy = FunctionType::get(Type::VoidTy, Args, false);
852   PoolDestroy = M->getOrInsertFunction("pooldestroy", PoolDestroyTy);
853
854   const Type *PtrVoid = PointerType::get(Type::SByteTy);
855
856   // Get the poolalloc function...
857   FunctionType *PoolAllocTy = FunctionType::get(PtrVoid, Args, false);
858   PoolAlloc = M->getOrInsertFunction("poolalloc", PoolAllocTy);
859
860   // Get the poolfree function...
861   Args.push_back(PtrVoid);
862   FunctionType *PoolFreeTy = FunctionType::get(Type::VoidTy, Args, false);
863   PoolFree = M->getOrInsertFunction("poolfree", PoolFreeTy);
864
865   // Add the %PoolTy type to the symbol table of the module...
866   M->addTypeName("PoolTy", PoolTy->getElementType());
867 }
868
869
870 bool PoolAllocate::run(Module *M) {
871   addPoolPrototypes(M);
872   CurModule = M;
873   
874   DS = &getAnalysis<DataStructure>();
875   bool Changed = false;
876
877   // We cannot use an iterator here because it will get invalidated when we add
878   // functions to the module later...
879   for (unsigned i = 0; i != M->size(); ++i)
880     if (!M->getFunctionList()[i]->isExternal()) {
881       Changed |= processFunction(M->getFunctionList()[i]);
882       if (Changed) {
883         cerr << "Only processing one function\n";
884         break;
885       }
886     }
887
888   CurModule = 0;
889   DS = 0;
890   return false;
891 }
892
893
894 // createPoolAllocatePass - Global function to access the functionality of this
895 // pass...
896 //
897 Pass *createPoolAllocatePass() { return new PoolAllocate(); }