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