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