Convert xforms over to new pass structure.
[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 "TransformInternals.h"
19 using std::vector;
20
21
22 // doInitialization - For the lower allocations pass, this ensures that a
23 // module contains a declaration for a malloc and a free function.
24 //
25 // This function is always successful.
26 //
27 bool LowerAllocations::doInitialization(Module *M) {
28   bool Changed = false;
29   const MethodType *MallocType = 
30     MethodType::get(PointerType::get(Type::SByteTy),
31                     vector<const Type*>(1, Type::UIntTy), false);
32
33   SymbolTable *SymTab = M->getSymbolTableSure();
34   
35   // Check for a definition of malloc
36   if (Value *V = SymTab->lookup(PointerType::get(MallocType), "malloc")) {
37     MallocMeth = cast<Method>(V);      // Yup, got it
38   } else {                             // Nope, add one
39     M->getMethodList().push_back(MallocMeth = new Method(MallocType, false, 
40                                                          "malloc"));
41     Changed = true;
42   }
43
44   const MethodType *FreeType = 
45     MethodType::get(Type::VoidTy,
46                     vector<const Type*>(1, PointerType::get(Type::SByteTy)),
47                     false);
48
49   // Check for a definition of free
50   if (Value *V = SymTab->lookup(PointerType::get(FreeType), "free")) {
51     FreeMeth = cast<Method>(V);      // Yup, got it
52   } else {                             // Nope, add one
53     M->getMethodList().push_back(FreeMeth = new Method(FreeType, false,"free"));
54     Changed = true;
55   }
56
57   return Changed;
58 }
59
60 // runOnBasicBlock - This method does the actual work of converting
61 // instructions over, assuming that the pass has already been initialized.
62 //
63 bool LowerAllocations::runOnBasicBlock(BasicBlock *BB) {
64   bool Changed = false;
65   assert(MallocMeth && FreeMeth && BB && "Pass not initialized!");
66
67   // Loop over all of the instructions, looking for malloc or free instructions
68   for (unsigned i = 0; i < BB->size(); ++i) {
69     BasicBlock::InstListType &BBIL = BB->getInstList();
70     if (MallocInst *MI = dyn_cast<MallocInst>(*(BBIL.begin()+i))) {
71       BBIL.remove(BBIL.begin()+i);   // remove the malloc instr...
72         
73       const Type *AllocTy =cast<PointerType>(MI->getType())->getElementType();
74       
75       // Get the number of bytes to be allocated for one element of the
76       // requested type...
77       unsigned Size = DataLayout.getTypeSize(AllocTy);
78       
79       // malloc(type) becomes sbyte *malloc(constint)
80       Value *MallocArg = ConstantUInt::get(Type::UIntTy, Size);
81       if (MI->getNumOperands() && Size == 1) {
82         MallocArg = MI->getOperand(0);         // Operand * 1 = Operand
83       } else if (MI->getNumOperands()) {
84         // Multiply it by the array size if neccesary...
85         MallocArg = BinaryOperator::create(Instruction::Mul,MI->getOperand(0),
86                                            MallocArg);
87         BBIL.insert(BBIL.begin()+i++, cast<Instruction>(MallocArg));
88       }
89       
90       // Create the call to Malloc...
91       CallInst *MCall = new CallInst(MallocMeth,
92                                      vector<Value*>(1, MallocArg));
93       BBIL.insert(BBIL.begin()+i, MCall);
94       
95       // Create a cast instruction to convert to the right type...
96       CastInst *MCast = new CastInst(MCall, MI->getType());
97       BBIL.insert(BBIL.begin()+i+1, MCast);
98       
99       // Replace all uses of the old malloc inst with the cast inst
100       MI->replaceAllUsesWith(MCast);
101       delete MI;                          // Delete the malloc inst
102       Changed = true;
103     } else if (FreeInst *FI = dyn_cast<FreeInst>(*(BBIL.begin()+i))) {
104       BBIL.remove(BB->getInstList().begin()+i);
105       
106       // Cast the argument to free into a ubyte*...
107       CastInst *MCast = new CastInst(FI->getOperand(0), 
108                                      PointerType::get(Type::UByteTy));
109       BBIL.insert(BBIL.begin()+i, MCast);
110       
111       // Insert a call to the free function...
112       CallInst *FCall = new CallInst(FreeMeth,
113                                      vector<Value*>(1, MCast));
114       BBIL.insert(BBIL.begin()+i+1, FCall);
115       
116       // Delete the old free instruction
117       delete FI;
118       Changed = true;
119     }
120   }
121
122   return Changed;
123 }
124
125 bool RaiseAllocations::doInitialization(Module *M) {
126   SymbolTable *ST = M->getSymbolTable();
127   if (!ST) return false;
128
129   // If the module has a symbol table, they might be referring to the malloc
130   // and free functions.  If this is the case, grab the method pointers that 
131   // the module is using.
132   //
133   // Lookup %malloc and %free in the symbol table, for later use.  If they
134   // don't exist, or are not external, we do not worry about converting calls
135   // to that function into the appropriate instruction.
136   //
137   const PointerType *MallocType =   // Get the type for malloc
138     PointerType::get(MethodType::get(PointerType::get(Type::SByteTy),
139                                   vector<const Type*>(1, Type::UIntTy), false));
140   MallocMeth = cast_or_null<Method>(ST->lookup(MallocType, "malloc"));
141   if (MallocMeth && !MallocMeth->isExternal())
142     MallocMeth = 0;  // Don't mess with locally defined versions of the fn
143
144   const PointerType *FreeType =     // Get the type for free
145     PointerType::get(MethodType::get(Type::VoidTy,
146             vector<const Type*>(1, PointerType::get(Type::SByteTy)), false));
147   FreeMeth = cast_or_null<Method>(ST->lookup(FreeType, "free"));
148   if (FreeMeth && !FreeMeth->isExternal())
149     FreeMeth = 0;  // Don't mess with locally defined versions of the fn
150
151   return false;
152 }
153
154 // doOneCleanupPass - Do one pass over the input method, fixing stuff up.
155 //
156 bool RaiseAllocations::runOnBasicBlock(BasicBlock *BB) {
157   bool Changed = false;
158   BasicBlock::InstListType &BIL = BB->getInstList();
159
160   for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
161     Instruction *I = *BI;
162
163     if (CallInst *CI = dyn_cast<CallInst>(I)) {
164       if (CI->getCalledValue() == MallocMeth) {      // Replace call to malloc?
165         const Type *PtrSByte = PointerType::get(Type::SByteTy);
166         MallocInst *MallocI = new MallocInst(PtrSByte, CI->getOperand(1),
167                                              CI->getName());
168         CI->setName("");
169         ReplaceInstWithInst(BIL, BI, MallocI);
170         Changed = true;
171         continue;  // Skip the ++BI
172       } else if (CI->getCalledValue() == FreeMeth) { // Replace call to free?
173         ReplaceInstWithInst(BIL, BI, new FreeInst(CI->getOperand(1)));
174         Changed = true;
175         continue;  // Skip the ++BI
176       }
177     }
178
179     ++BI;
180   }
181
182   return Changed;
183 }