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