Patch to make some xforms preserve each other. Patch contributed by
[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/Transforms/Utils/UnifyFunctionExitNodes.h"
17 #include "llvm/Module.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Constants.h"
21 #include "llvm/Pass.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Target/TargetData.h"
24 using namespace llvm;
25
26 namespace {
27   Statistic<> NumLowered("lowerallocs", "Number of allocations lowered");
28
29   /// LowerAllocations - Turn malloc and free instructions into %malloc and
30   /// %free calls.
31   ///
32   class LowerAllocations : public BasicBlockPass {
33     Function *MallocFunc;   // Functions in the module we are processing
34     Function *FreeFunc;     // Initialized by doInitialization
35     bool LowerMallocArgToInteger;
36   public:
37     LowerAllocations(bool LowerToInt = false)
38       : MallocFunc(0), FreeFunc(0), LowerMallocArgToInteger(LowerToInt) {}
39
40     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
41       AU.addRequired<TargetData>();
42       AU.setPreservesCFG();
43
44       // This is a cluster of orthogonal Transforms:
45       AU.addPreserved<UnifyFunctionExitNodes>();
46       AU.addPreservedID(PromoteMemoryToRegisterID);
47       AU.addPreservedID(LowerSelectID);
48       AU.addPreservedID(LowerSwitchID);
49     }
50
51     /// doPassInitialization - For the lower allocations pass, this ensures that
52     /// a module contains a declaration for a malloc and a free function.
53     ///
54     bool doInitialization(Module &M);
55
56     virtual bool doInitialization(Function &F) {
57       return BasicBlockPass::doInitialization(F);
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 runOnBasicBlock(BasicBlock &BB);
64   };
65
66   RegisterOpt<LowerAllocations>
67   X("lowerallocs", "Lower allocations from instructions to calls");
68 }
69
70 // Publically exposed interface to pass...
71 const PassInfo *llvm::LowerAllocationsID = X.getPassInfo();
72 // createLowerAllocationsPass - Interface to this file...
73 FunctionPass *llvm::createLowerAllocationsPass(bool LowerMallocArgToInteger) {
74   return new LowerAllocations(LowerMallocArgToInteger);
75 }
76
77
78 // doInitialization - For the lower allocations pass, this ensures that a
79 // module contains a declaration for a malloc and a free function.
80 //
81 // This function is always successful.
82 //
83 bool LowerAllocations::doInitialization(Module &M) {
84   const Type *SBPTy = PointerType::get(Type::SByteTy);
85   MallocFunc = M.getNamedFunction("malloc");
86   FreeFunc   = M.getNamedFunction("free");
87
88   if (MallocFunc == 0) {
89     // Prototype malloc as "void* malloc(...)", because we don't know in
90     // doInitialization whether size_t is int or long.
91     FunctionType *FT = FunctionType::get(SBPTy,std::vector<const Type*>(),true);
92     MallocFunc = M.getOrInsertFunction("malloc", FT);
93   }
94   if (FreeFunc == 0)
95     FreeFunc = M.getOrInsertFunction("free"  , Type::VoidTy, SBPTy, (Type *)0);
96
97   return true;
98 }
99
100 // runOnBasicBlock - This method does the actual work of converting
101 // instructions over, assuming that the pass has already been initialized.
102 //
103 bool LowerAllocations::runOnBasicBlock(BasicBlock &BB) {
104   bool Changed = false;
105   assert(MallocFunc && FreeFunc && "Pass not initialized!");
106
107   BasicBlock::InstListType &BBIL = BB.getInstList();
108
109   const TargetData &TD = getAnalysis<TargetData>();
110   const Type *IntPtrTy = TD.getIntPtrType();
111
112   // Loop over all of the instructions, looking for malloc or free instructions
113   for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I) {
114     if (MallocInst *MI = dyn_cast<MallocInst>(I)) {
115       const Type *AllocTy = MI->getType()->getElementType();
116
117       // malloc(type) becomes sbyte *malloc(size)
118       Value *MallocArg;
119       if (LowerMallocArgToInteger)
120         MallocArg = ConstantUInt::get(Type::ULongTy, TD.getTypeSize(AllocTy));
121       else
122         MallocArg = ConstantExpr::getSizeOf(AllocTy);
123       MallocArg = ConstantExpr::getCast(cast<Constant>(MallocArg), IntPtrTy);
124
125       if (MI->isArrayAllocation()) {
126         if (isa<ConstantInt>(MallocArg) &&
127             cast<ConstantInt>(MallocArg)->getRawValue() == 1) {
128           MallocArg = MI->getOperand(0);         // Operand * 1 = Operand
129         } else if (Constant *CO = dyn_cast<Constant>(MI->getOperand(0))) {
130           CO = ConstantExpr::getCast(CO, IntPtrTy);
131           MallocArg = ConstantExpr::getMul(CO, cast<Constant>(MallocArg));
132         } else {
133           Value *Scale = MI->getOperand(0);
134           if (Scale->getType() != IntPtrTy)
135             Scale = new CastInst(Scale, IntPtrTy, "", I);
136
137           // Multiply it by the array size if necessary...
138           MallocArg = BinaryOperator::create(Instruction::Mul, Scale,
139                                              MallocArg, "", I);
140         }
141       }
142
143       const FunctionType *MallocFTy = MallocFunc->getFunctionType();
144       std::vector<Value*> MallocArgs;
145
146       if (MallocFTy->getNumParams() > 0 || MallocFTy->isVarArg()) {
147         if (MallocFTy->isVarArg()) {
148           if (MallocArg->getType() != IntPtrTy)
149             MallocArg = new CastInst(MallocArg, IntPtrTy, "", I);
150         } else if (MallocFTy->getNumParams() > 0 &&
151                    MallocFTy->getParamType(0) != Type::UIntTy)
152           MallocArg = new CastInst(MallocArg, MallocFTy->getParamType(0), "",I);
153         MallocArgs.push_back(MallocArg);
154       }
155
156       // If malloc is prototyped to take extra arguments, pass nulls.
157       for (unsigned i = 1; i < MallocFTy->getNumParams(); ++i)
158        MallocArgs.push_back(Constant::getNullValue(MallocFTy->getParamType(i)));
159
160       // Create the call to Malloc...
161       CallInst *MCall = new CallInst(MallocFunc, MallocArgs, "", I);
162       MCall->setTailCall();
163
164       // Create a cast instruction to convert to the right type...
165       Value *MCast;
166       if (MCall->getType() != Type::VoidTy)
167         MCast = new CastInst(MCall, MI->getType(), "", I);
168       else
169         MCast = Constant::getNullValue(MI->getType());
170
171       // Replace all uses of the old malloc inst with the cast inst
172       MI->replaceAllUsesWith(MCast);
173       I = --BBIL.erase(I);         // remove and delete the malloc instr...
174       Changed = true;
175       ++NumLowered;
176     } else if (FreeInst *FI = dyn_cast<FreeInst>(I)) {
177       const FunctionType *FreeFTy = FreeFunc->getFunctionType();
178       std::vector<Value*> FreeArgs;
179
180       if (FreeFTy->getNumParams() > 0 || FreeFTy->isVarArg()) {
181         Value *MCast = FI->getOperand(0);
182         if (FreeFTy->getNumParams() > 0 &&
183             FreeFTy->getParamType(0) != MCast->getType())
184           MCast = new CastInst(MCast, FreeFTy->getParamType(0), "", I);
185         FreeArgs.push_back(MCast);
186       }
187
188       // If malloc is prototyped to take extra arguments, pass nulls.
189       for (unsigned i = 1; i < FreeFTy->getNumParams(); ++i)
190        FreeArgs.push_back(Constant::getNullValue(FreeFTy->getParamType(i)));
191
192       // Insert a call to the free function...
193       (new CallInst(FreeFunc, FreeArgs, "", I))->setTailCall();
194
195       // Delete the old free instruction
196       I = --BBIL.erase(I);
197       Changed = true;
198       ++NumLowered;
199     }
200   }
201
202   return Changed;
203 }
204