Change LowerAllocations pass to 'require' TargetData instead of it being
[oota-llvm.git] / lib / Transforms / Utils / LowerAllocations.cpp
1 //===- LowerAllocations.cpp - Reduce malloc & free insts to calls ---------===//
2 //
3 // The LowerAllocations transformation is a target dependant tranformation
4 // because it depends on the size of data types and alignment constraints.
5 //
6 //===----------------------------------------------------------------------===//
7
8 #include "llvm/Transforms/Scalar.h"
9 #include "llvm/Module.h"
10 #include "llvm/DerivedTypes.h"
11 #include "llvm/iMemory.h"
12 #include "llvm/iOther.h"
13 #include "llvm/Constants.h"
14 #include "llvm/Pass.h"
15 #include "llvm/Target/TargetData.h"
16 #include "Support/StatisticReporter.h"
17
18 static Statistic<> NumLowered("lowerallocs\t- Number of allocations lowered");
19 using std::vector;
20
21 namespace {
22
23   /// LowerAllocations - Turn malloc and free instructions into %malloc and
24   /// %free calls.
25   ///
26   class LowerAllocations : public BasicBlockPass {
27     Function *MallocFunc;   // Functions in the module we are processing
28     Function *FreeFunc;     // Initialized by doInitialization
29   public:
30     LowerAllocations() : MallocFunc(0), FreeFunc(0) {}
31
32     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
33       AU.addRequired<TargetData>();
34     }
35
36     /// doPassInitialization - For the lower allocations pass, this ensures that
37     /// a module contains a declaration for a malloc and a free function.
38     ///
39     bool doInitialization(Module &M);
40     
41     /// runOnBasicBlock - This method does the actual work of converting
42     /// instructions over, assuming that the pass has already been initialized.
43     ///
44     bool runOnBasicBlock(BasicBlock &BB);
45   };
46
47   RegisterOpt<LowerAllocations>
48   X("lowerallocs", "Lower allocations from instructions to calls");
49 }
50
51 // createLowerAllocationsPass - Interface to this file...
52 Pass *createLowerAllocationsPass() {
53   return new LowerAllocations();
54 }
55
56
57 // doInitialization - For the lower allocations pass, this ensures that a
58 // module contains a declaration for a malloc and a free function.
59 //
60 // This function is always successful.
61 //
62 bool LowerAllocations::doInitialization(Module &M) {
63   const FunctionType *MallocType = 
64     FunctionType::get(PointerType::get(Type::SByteTy),
65                       vector<const Type*>(1, Type::UIntTy), false);
66   const FunctionType *FreeType = 
67     FunctionType::get(Type::VoidTy,
68                       vector<const Type*>(1, PointerType::get(Type::SByteTy)),
69                       false);
70
71   MallocFunc = M.getOrInsertFunction("malloc", MallocType);
72   FreeFunc   = M.getOrInsertFunction("free"  , FreeType);
73
74   return true;
75 }
76
77 // runOnBasicBlock - This method does the actual work of converting
78 // instructions over, assuming that the pass has already been initialized.
79 //
80 bool LowerAllocations::runOnBasicBlock(BasicBlock &BB) {
81   bool Changed = false;
82   assert(MallocFunc && FreeFunc && "Pass not initialized!");
83
84   BasicBlock::InstListType &BBIL = BB.getInstList();
85   TargetData &DataLayout = getAnalysis<TargetData>();
86
87   // Loop over all of the instructions, looking for malloc or free instructions
88   for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I) {
89     if (MallocInst *MI = dyn_cast<MallocInst>(&*I)) {
90       const Type *AllocTy = MI->getType()->getElementType();
91       
92       // Get the number of bytes to be allocated for one element of the
93       // requested type...
94       unsigned Size = DataLayout.getTypeSize(AllocTy);
95       
96       // malloc(type) becomes sbyte *malloc(constint)
97       Value *MallocArg = ConstantUInt::get(Type::UIntTy, Size);
98       if (MI->getNumOperands() && Size == 1) {
99         MallocArg = MI->getOperand(0);         // Operand * 1 = Operand
100       } else if (MI->getNumOperands()) {
101         // Multiply it by the array size if neccesary...
102         MallocArg = BinaryOperator::create(Instruction::Mul, MI->getOperand(0),
103                                            MallocArg, "", I);
104       }
105       
106       // Create the call to Malloc...
107       CallInst *MCall = new CallInst(MallocFunc,
108                                      vector<Value*>(1, MallocArg), "", I);
109       
110       // Create a cast instruction to convert to the right type...
111       CastInst *MCast = new CastInst(MCall, MI->getType(), "", I);
112       
113       // Replace all uses of the old malloc inst with the cast inst
114       MI->replaceAllUsesWith(MCast);
115       I = --BBIL.erase(I);         // remove and delete the malloc instr...
116       Changed = true;
117       ++NumLowered;
118     } else if (FreeInst *FI = dyn_cast<FreeInst>(&*I)) {
119       // Cast the argument to free into a ubyte*...
120       CastInst *MCast = new CastInst(FI->getOperand(0), 
121                                      PointerType::get(Type::UByteTy), "", I);
122       
123       // Insert a call to the free function...
124       CallInst *FCall = new CallInst(FreeFunc, vector<Value*>(1, MCast), "", I);
125       
126       // Delete the old free instruction
127       I = --BBIL.erase(I);
128       Changed = true;
129       ++NumLowered;
130     }
131   }
132
133   return Changed;
134 }