Change over to use new style pass mechanism, now passes only expose small
[oota-llvm.git] / lib / Transforms / Utils / LowerAllocations.cpp
1 //===- ChangeAllocations.cpp - Modify %malloc & %free calls -----------------=//
2 //
3 // This file defines two passes that convert malloc and free instructions to
4 // calls to and from %malloc & %free function calls.  The LowerAllocations
5 // transformation is a target dependant tranformation because it depends on the
6 // size of data types and alignment constraints.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "llvm/Transforms/ChangeAllocations.h"
11 #include "llvm/Target/TargetData.h"
12 #include "llvm/Module.h"
13 #include "llvm/DerivedTypes.h"
14 #include "llvm/iMemory.h"
15 #include "llvm/iOther.h"
16 #include "llvm/SymbolTable.h"
17 #include "llvm/ConstantVals.h"
18 #include "llvm/Pass.h"
19 #include "TransformInternals.h"
20 using std::vector;
21
22 namespace {
23
24 // LowerAllocations - Turn malloc and free instructions into %malloc and %free
25 // calls.
26 //
27 class LowerAllocations : public BasicBlockPass {
28   Method *MallocMeth;   // Methods in the module we are processing
29   Method *FreeMeth;     // Initialized by doInitialization
30
31   const TargetData &DataLayout;
32 public:
33   inline LowerAllocations(const TargetData &TD) : DataLayout(TD) {
34     MallocMeth = FreeMeth = 0;
35   }
36
37   // doPassInitialization - For the lower allocations pass, this ensures that a
38   // module contains a declaration for a malloc and a free function.
39   //
40   bool doInitialization(Module *M);
41
42   // runOnBasicBlock - This method does the actual work of converting
43   // instructions over, assuming that the pass has already been initialized.
44   //
45   bool runOnBasicBlock(BasicBlock *BB);
46 };
47
48 // RaiseAllocations - Turn %malloc and %free calls into the appropriate
49 // instruction.
50 //
51 class RaiseAllocations : public BasicBlockPass {
52   Method *MallocMeth;   // Methods in the module we are processing
53   Method *FreeMeth;     // Initialized by doPassInitializationVirt
54 public:
55   inline RaiseAllocations() : MallocMeth(0), FreeMeth(0) {}
56
57   // doPassInitialization - For the raise allocations pass, this finds a
58   // declaration for malloc and free if they exist.
59   //
60   bool doInitialization(Module *M);
61
62   // runOnBasicBlock - This method does the actual work of converting
63   // instructions over, assuming that the pass has already been initialized.
64   //
65   bool runOnBasicBlock(BasicBlock *BB);
66 };
67
68 }  // end anonymous namespace
69
70 // doInitialization - For the lower allocations pass, this ensures that a
71 // module contains a declaration for a malloc and a free function.
72 //
73 // This function is always successful.
74 //
75 bool LowerAllocations::doInitialization(Module *M) {
76   bool Changed = false;
77   const MethodType *MallocType = 
78     MethodType::get(PointerType::get(Type::SByteTy),
79                     vector<const Type*>(1, Type::UIntTy), false);
80
81   SymbolTable *SymTab = M->getSymbolTableSure();
82   
83   // Check for a definition of malloc
84   if (Value *V = SymTab->lookup(PointerType::get(MallocType), "malloc")) {
85     MallocMeth = cast<Method>(V);      // Yup, got it
86   } else {                             // Nope, add one
87     M->getMethodList().push_back(MallocMeth = new Method(MallocType, false, 
88                                                          "malloc"));
89     Changed = true;
90   }
91
92   const MethodType *FreeType = 
93     MethodType::get(Type::VoidTy,
94                     vector<const Type*>(1, PointerType::get(Type::SByteTy)),
95                     false);
96
97   // Check for a definition of free
98   if (Value *V = SymTab->lookup(PointerType::get(FreeType), "free")) {
99     FreeMeth = cast<Method>(V);      // Yup, got it
100   } else {                             // Nope, add one
101     M->getMethodList().push_back(FreeMeth = new Method(FreeType, false,"free"));
102     Changed = true;
103   }
104
105   return Changed;
106 }
107
108 // runOnBasicBlock - This method does the actual work of converting
109 // instructions over, assuming that the pass has already been initialized.
110 //
111 bool LowerAllocations::runOnBasicBlock(BasicBlock *BB) {
112   bool Changed = false;
113   assert(MallocMeth && FreeMeth && BB && "Pass not initialized!");
114
115   // Loop over all of the instructions, looking for malloc or free instructions
116   for (unsigned i = 0; i < BB->size(); ++i) {
117     BasicBlock::InstListType &BBIL = BB->getInstList();
118     if (MallocInst *MI = dyn_cast<MallocInst>(*(BBIL.begin()+i))) {
119       BBIL.remove(BBIL.begin()+i);   // remove the malloc instr...
120         
121       const Type *AllocTy =cast<PointerType>(MI->getType())->getElementType();
122       
123       // Get the number of bytes to be allocated for one element of the
124       // requested type...
125       unsigned Size = DataLayout.getTypeSize(AllocTy);
126       
127       // malloc(type) becomes sbyte *malloc(constint)
128       Value *MallocArg = ConstantUInt::get(Type::UIntTy, Size);
129       if (MI->getNumOperands() && Size == 1) {
130         MallocArg = MI->getOperand(0);         // Operand * 1 = Operand
131       } else if (MI->getNumOperands()) {
132         // Multiply it by the array size if neccesary...
133         MallocArg = BinaryOperator::create(Instruction::Mul,MI->getOperand(0),
134                                            MallocArg);
135         BBIL.insert(BBIL.begin()+i++, cast<Instruction>(MallocArg));
136       }
137       
138       // Create the call to Malloc...
139       CallInst *MCall = new CallInst(MallocMeth,
140                                      vector<Value*>(1, MallocArg));
141       BBIL.insert(BBIL.begin()+i, MCall);
142       
143       // Create a cast instruction to convert to the right type...
144       CastInst *MCast = new CastInst(MCall, MI->getType());
145       BBIL.insert(BBIL.begin()+i+1, MCast);
146       
147       // Replace all uses of the old malloc inst with the cast inst
148       MI->replaceAllUsesWith(MCast);
149       delete MI;                          // Delete the malloc inst
150       Changed = true;
151     } else if (FreeInst *FI = dyn_cast<FreeInst>(*(BBIL.begin()+i))) {
152       BBIL.remove(BB->getInstList().begin()+i);
153       
154       // Cast the argument to free into a ubyte*...
155       CastInst *MCast = new CastInst(FI->getOperand(0), 
156                                      PointerType::get(Type::UByteTy));
157       BBIL.insert(BBIL.begin()+i, MCast);
158       
159       // Insert a call to the free function...
160       CallInst *FCall = new CallInst(FreeMeth,
161                                      vector<Value*>(1, MCast));
162       BBIL.insert(BBIL.begin()+i+1, FCall);
163       
164       // Delete the old free instruction
165       delete FI;
166       Changed = true;
167     }
168   }
169
170   return Changed;
171 }
172
173 bool RaiseAllocations::doInitialization(Module *M) {
174   SymbolTable *ST = M->getSymbolTable();
175   if (!ST) return false;
176
177   // If the module has a symbol table, they might be referring to the malloc
178   // and free functions.  If this is the case, grab the method pointers that 
179   // the module is using.
180   //
181   // Lookup %malloc and %free in the symbol table, for later use.  If they
182   // don't exist, or are not external, we do not worry about converting calls
183   // to that function into the appropriate instruction.
184   //
185   const PointerType *MallocType =   // Get the type for malloc
186     PointerType::get(MethodType::get(PointerType::get(Type::SByteTy),
187                                   vector<const Type*>(1, Type::UIntTy), false));
188   MallocMeth = cast_or_null<Method>(ST->lookup(MallocType, "malloc"));
189   if (MallocMeth && !MallocMeth->isExternal())
190     MallocMeth = 0;  // Don't mess with locally defined versions of the fn
191
192   const PointerType *FreeType =     // Get the type for free
193     PointerType::get(MethodType::get(Type::VoidTy,
194             vector<const Type*>(1, PointerType::get(Type::SByteTy)), false));
195   FreeMeth = cast_or_null<Method>(ST->lookup(FreeType, "free"));
196   if (FreeMeth && !FreeMeth->isExternal())
197     FreeMeth = 0;  // Don't mess with locally defined versions of the fn
198
199   return false;
200 }
201
202 // doOneCleanupPass - Do one pass over the input method, fixing stuff up.
203 //
204 bool RaiseAllocations::runOnBasicBlock(BasicBlock *BB) {
205   bool Changed = false;
206   BasicBlock::InstListType &BIL = BB->getInstList();
207
208   for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
209     Instruction *I = *BI;
210
211     if (CallInst *CI = dyn_cast<CallInst>(I)) {
212       if (CI->getCalledValue() == MallocMeth) {      // Replace call to malloc?
213         const Type *PtrSByte = PointerType::get(Type::SByteTy);
214         MallocInst *MallocI = new MallocInst(PtrSByte, CI->getOperand(1),
215                                              CI->getName());
216         CI->setName("");
217         ReplaceInstWithInst(BIL, BI, MallocI);
218         Changed = true;
219         continue;  // Skip the ++BI
220       } else if (CI->getCalledValue() == FreeMeth) { // Replace call to free?
221         ReplaceInstWithInst(BIL, BI, new FreeInst(CI->getOperand(1)));
222         Changed = true;
223         continue;  // Skip the ++BI
224       }
225     }
226
227     ++BI;
228   }
229
230   return Changed;
231 }
232
233 Pass *createLowerAllocationsPass(const TargetData &TD) {
234   return new LowerAllocations(TD);
235 }
236 Pass *createRaiseAllocationsPass() {
237   return new RaiseAllocations();
238 }
239
240