1 //===- LowerAllocations.cpp - Reduce malloc & free insts to calls ---------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // The LowerAllocations transformation is a target-dependent tranformation
11 // because it depends on the size of data types and alignment constraints.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Transforms/Scalar.h"
16 #include "llvm/Module.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Constants.h"
20 #include "llvm/Pass.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Target/TargetData.h"
26 Statistic<> NumLowered("lowerallocs", "Number of allocations lowered");
28 /// LowerAllocations - Turn malloc and free instructions into %malloc and
31 class LowerAllocations : public BasicBlockPass {
32 Function *MallocFunc; // Functions in the module we are processing
33 Function *FreeFunc; // Initialized by doInitialization
34 bool LowerMallocArgToInteger;
36 LowerAllocations(bool LowerToInt = false)
37 : MallocFunc(0), FreeFunc(0), LowerMallocArgToInteger(LowerToInt) {}
39 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
40 AU.addRequired<TargetData>();
44 /// doPassInitialization - For the lower allocations pass, this ensures that
45 /// a module contains a declaration for a malloc and a free function.
47 bool doInitialization(Module &M);
49 virtual bool doInitialization(Function &F) {
50 return BasicBlockPass::doInitialization(F);
53 /// runOnBasicBlock - This method does the actual work of converting
54 /// instructions over, assuming that the pass has already been initialized.
56 bool runOnBasicBlock(BasicBlock &BB);
59 RegisterOpt<LowerAllocations>
60 X("lowerallocs", "Lower allocations from instructions to calls");
63 // Publically exposed interface to pass...
64 const PassInfo *llvm::LowerAllocationsID = X.getPassInfo();
65 // createLowerAllocationsPass - Interface to this file...
66 FunctionPass *llvm::createLowerAllocationsPass(bool LowerMallocArgToInteger) {
67 return new LowerAllocations(LowerMallocArgToInteger);
71 // doInitialization - For the lower allocations pass, this ensures that a
72 // module contains a declaration for a malloc and a free function.
74 // This function is always successful.
76 bool LowerAllocations::doInitialization(Module &M) {
77 const Type *SBPTy = PointerType::get(Type::SByteTy);
78 MallocFunc = M.getNamedFunction("malloc");
79 FreeFunc = M.getNamedFunction("free");
81 if (MallocFunc == 0) {
82 // Prototype malloc as "void* malloc(...)", because we don't know in
83 // doInitialization whether size_t is int or long.
84 FunctionType *FT = FunctionType::get(SBPTy,std::vector<const Type*>(),true);
85 MallocFunc = M.getOrInsertFunction("malloc", FT);
88 FreeFunc = M.getOrInsertFunction("free" , Type::VoidTy, SBPTy, (Type *)0);
93 // runOnBasicBlock - This method does the actual work of converting
94 // instructions over, assuming that the pass has already been initialized.
96 bool LowerAllocations::runOnBasicBlock(BasicBlock &BB) {
98 assert(MallocFunc && FreeFunc && "Pass not initialized!");
100 BasicBlock::InstListType &BBIL = BB.getInstList();
102 const TargetData &TD = getAnalysis<TargetData>();
103 const Type *IntPtrTy = TD.getIntPtrType();
105 // Loop over all of the instructions, looking for malloc or free instructions
106 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I) {
107 if (MallocInst *MI = dyn_cast<MallocInst>(I)) {
108 const Type *AllocTy = MI->getType()->getElementType();
110 // malloc(type) becomes sbyte *malloc(size)
112 if (LowerMallocArgToInteger)
113 MallocArg = ConstantUInt::get(Type::ULongTy, TD.getTypeSize(AllocTy));
115 MallocArg = ConstantExpr::getSizeOf(AllocTy);
116 MallocArg = ConstantExpr::getCast(cast<Constant>(MallocArg), IntPtrTy);
118 if (MI->isArrayAllocation()) {
119 if (isa<ConstantInt>(MallocArg) &&
120 cast<ConstantInt>(MallocArg)->getRawValue() == 1) {
121 MallocArg = MI->getOperand(0); // Operand * 1 = Operand
122 } else if (Constant *CO = dyn_cast<Constant>(MI->getOperand(0))) {
123 CO = ConstantExpr::getCast(CO, IntPtrTy);
124 MallocArg = ConstantExpr::getMul(CO, cast<Constant>(MallocArg));
126 Value *Scale = MI->getOperand(0);
127 if (Scale->getType() != IntPtrTy)
128 Scale = new CastInst(Scale, IntPtrTy, "", I);
130 // Multiply it by the array size if necessary...
131 MallocArg = BinaryOperator::create(Instruction::Mul, Scale,
136 const FunctionType *MallocFTy = MallocFunc->getFunctionType();
137 std::vector<Value*> MallocArgs;
139 if (MallocFTy->getNumParams() > 0 || MallocFTy->isVarArg()) {
140 if (MallocFTy->isVarArg()) {
141 if (MallocArg->getType() != IntPtrTy)
142 MallocArg = new CastInst(MallocArg, IntPtrTy, "", I);
143 } else if (MallocFTy->getNumParams() > 0 &&
144 MallocFTy->getParamType(0) != Type::UIntTy)
145 MallocArg = new CastInst(MallocArg, MallocFTy->getParamType(0), "",I);
146 MallocArgs.push_back(MallocArg);
149 // If malloc is prototyped to take extra arguments, pass nulls.
150 for (unsigned i = 1; i < MallocFTy->getNumParams(); ++i)
151 MallocArgs.push_back(Constant::getNullValue(MallocFTy->getParamType(i)));
153 // Create the call to Malloc...
154 CallInst *MCall = new CallInst(MallocFunc, MallocArgs, "", I);
155 MCall->setTailCall();
157 // Create a cast instruction to convert to the right type...
159 if (MCall->getType() != Type::VoidTy)
160 MCast = new CastInst(MCall, MI->getType(), "", I);
162 MCast = Constant::getNullValue(MI->getType());
164 // Replace all uses of the old malloc inst with the cast inst
165 MI->replaceAllUsesWith(MCast);
166 I = --BBIL.erase(I); // remove and delete the malloc instr...
169 } else if (FreeInst *FI = dyn_cast<FreeInst>(I)) {
170 const FunctionType *FreeFTy = FreeFunc->getFunctionType();
171 std::vector<Value*> FreeArgs;
173 if (FreeFTy->getNumParams() > 0 || FreeFTy->isVarArg()) {
174 Value *MCast = FI->getOperand(0);
175 if (FreeFTy->getNumParams() > 0 &&
176 FreeFTy->getParamType(0) != MCast->getType())
177 MCast = new CastInst(MCast, FreeFTy->getParamType(0), "", I);
178 FreeArgs.push_back(MCast);
181 // If malloc is prototyped to take extra arguments, pass nulls.
182 for (unsigned i = 1; i < FreeFTy->getNumParams(); ++i)
183 FreeArgs.push_back(Constant::getNullValue(FreeFTy->getParamType(i)));
185 // Insert a call to the free function...
186 (new CallInst(FreeFunc, FreeArgs, "", I))->setTailCall();
188 // Delete the old free instruction