blob: 522166d6f2da5d17578d2dea3b0179e31d13c0ac [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- LowerAllocations.cpp - Reduce malloc & free insts to calls ---------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
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#define DEBUG_TYPE "lowerallocs"
16#include "llvm/Transforms/Scalar.h"
17#include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
18#include "llvm/Module.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/Instructions.h"
21#include "llvm/Constants.h"
Owen Andersona09d2342009-07-05 22:41:43 +000022#include "llvm/LLVMContext.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000023#include "llvm/Pass.h"
24#include "llvm/ADT/Statistic.h"
25#include "llvm/Target/TargetData.h"
26#include "llvm/Support/Compiler.h"
27using namespace llvm;
28
29STATISTIC(NumLowered, "Number of allocations lowered");
30
31namespace {
32 /// LowerAllocations - Turn malloc and free instructions into %malloc and
33 /// %free calls.
34 ///
35 class VISIBILITY_HIDDEN LowerAllocations : public BasicBlockPass {
36 Constant *MallocFunc; // Functions in the module we are processing
37 Constant *FreeFunc; // Initialized by doInitialization
38 bool LowerMallocArgToInteger;
39 public:
40 static char ID; // Pass ID, replacement for typeid
Dan Gohman34c280e2007-08-01 15:32:29 +000041 explicit LowerAllocations(bool LowerToInt = false)
Dan Gohman26f8c272008-09-04 17:05:41 +000042 : BasicBlockPass(&ID), MallocFunc(0), FreeFunc(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000043 LowerMallocArgToInteger(LowerToInt) {}
44
45 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
46 AU.addRequired<TargetData>();
47 AU.setPreservesCFG();
48
49 // This is a cluster of orthogonal Transforms:
50 AU.addPreserved<UnifyFunctionExitNodes>();
51 AU.addPreservedID(PromoteMemoryToRegisterID);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000052 AU.addPreservedID(LowerSwitchID);
53 AU.addPreservedID(LowerInvokePassID);
54 }
55
56 /// doPassInitialization - For the lower allocations pass, this ensures that
57 /// a module contains a declaration for a malloc and a free function.
58 ///
59 bool doInitialization(Module &M);
60
61 virtual bool doInitialization(Function &F) {
Devang Patel35d69b02008-11-18 18:43:07 +000062 return doInitialization(*F.getParent());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000063 }
64
65 /// runOnBasicBlock - This method does the actual work of converting
66 /// instructions over, assuming that the pass has already been initialized.
67 ///
68 bool runOnBasicBlock(BasicBlock &BB);
69 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +000070}
71
Dan Gohman089efff2008-05-13 00:00:25 +000072char LowerAllocations::ID = 0;
73static RegisterPass<LowerAllocations>
74X("lowerallocs", "Lower allocations from instructions to calls");
75
Dan Gohmanf17a25c2007-07-18 16:29:46 +000076// Publically exposed interface to pass...
Dan Gohman66a636e2008-05-13 02:05:11 +000077const PassInfo *const llvm::LowerAllocationsID = &X;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000078// createLowerAllocationsPass - Interface to this file...
79Pass *llvm::createLowerAllocationsPass(bool LowerMallocArgToInteger) {
80 return new LowerAllocations(LowerMallocArgToInteger);
81}
82
83
84// doInitialization - For the lower allocations pass, this ensures that a
85// module contains a declaration for a malloc and a free function.
86//
87// This function is always successful.
88//
89bool LowerAllocations::doInitialization(Module &M) {
Owen Anderson175b6542009-07-22 00:24:57 +000090 const Type *BPTy = M.getContext().getPointerTypeUnqual(Type::Int8Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000091 // Prototype malloc as "char* malloc(...)", because we don't know in
92 // doInitialization whether size_t is int or long.
Owen Anderson175b6542009-07-22 00:24:57 +000093 FunctionType *FT = M.getContext().getFunctionType(BPTy, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000094 MallocFunc = M.getOrInsertFunction("malloc", FT);
95 FreeFunc = M.getOrInsertFunction("free" , Type::VoidTy, BPTy, (Type *)0);
96 return true;
97}
98
99// runOnBasicBlock - This method does the actual work of converting
100// instructions over, assuming that the pass has already been initialized.
101//
102bool LowerAllocations::runOnBasicBlock(BasicBlock &BB) {
103 bool Changed = false;
104 assert(MallocFunc && FreeFunc && "Pass not initialized!");
105
Owen Anderson175b6542009-07-22 00:24:57 +0000106 LLVMContext &Context = BB.getContext();
107
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000108 BasicBlock::InstListType &BBIL = BB.getInstList();
109
110 const TargetData &TD = getAnalysis<TargetData>();
111 const Type *IntPtrTy = TD.getIntPtrType();
112
113 // Loop over all of the instructions, looking for malloc or free instructions
114 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I) {
115 if (MallocInst *MI = dyn_cast<MallocInst>(I)) {
116 const Type *AllocTy = MI->getType()->getElementType();
117
Dan Gohman9e1657f2009-06-14 23:30:43 +0000118 // malloc(type) becomes i8 *malloc(size)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000119 Value *MallocArg;
120 if (LowerMallocArgToInteger)
Owen Andersoneacb44d2009-07-24 23:12:02 +0000121 MallocArg = ConstantInt::get(Type::Int64Ty,
Duncan Sandsec4f97d2009-05-09 07:06:46 +0000122 TD.getTypeAllocSize(AllocTy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000123 else
Owen Anderson02b48c32009-07-29 18:55:55 +0000124 MallocArg = ConstantExpr::getSizeOf(AllocTy);
Owen Andersona09d2342009-07-05 22:41:43 +0000125 MallocArg =
Owen Anderson02b48c32009-07-29 18:55:55 +0000126 ConstantExpr::getTruncOrBitCast(cast<Constant>(MallocArg),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000127 IntPtrTy);
128
129 if (MI->isArrayAllocation()) {
130 if (isa<ConstantInt>(MallocArg) &&
131 cast<ConstantInt>(MallocArg)->isOne()) {
132 MallocArg = MI->getOperand(0); // Operand * 1 = Operand
133 } else if (Constant *CO = dyn_cast<Constant>(MI->getOperand(0))) {
Owen Andersona09d2342009-07-05 22:41:43 +0000134 CO =
Owen Anderson02b48c32009-07-29 18:55:55 +0000135 ConstantExpr::getIntegerCast(CO, IntPtrTy, false /*ZExt*/);
136 MallocArg = ConstantExpr::getMul(CO,
Owen Andersona09d2342009-07-05 22:41:43 +0000137 cast<Constant>(MallocArg));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000138 } else {
139 Value *Scale = MI->getOperand(0);
140 if (Scale->getType() != IntPtrTy)
Gabor Greifa645dd32008-05-16 19:29:10 +0000141 Scale = CastInst::CreateIntegerCast(Scale, IntPtrTy, false /*ZExt*/,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000142 "", I);
143
144 // Multiply it by the array size if necessary...
Gabor Greifa645dd32008-05-16 19:29:10 +0000145 MallocArg = BinaryOperator::Create(Instruction::Mul, Scale,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000146 MallocArg, "", I);
147 }
148 }
149
150 // Create the call to Malloc.
Gabor Greifd6da1d02008-04-06 20:25:17 +0000151 CallInst *MCall = CallInst::Create(MallocFunc, MallocArg, "", I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000152 MCall->setTailCall();
153
154 // Create a cast instruction to convert to the right type...
155 Value *MCast;
156 if (MCall->getType() != Type::VoidTy)
157 MCast = new BitCastInst(MCall, MI->getType(), "", I);
158 else
Owen Anderson175b6542009-07-22 00:24:57 +0000159 MCast = Context.getNullValue(MI->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000160
161 // Replace all uses of the old malloc inst with the cast inst
162 MI->replaceAllUsesWith(MCast);
163 I = --BBIL.erase(I); // remove and delete the malloc instr...
164 Changed = true;
165 ++NumLowered;
166 } else if (FreeInst *FI = dyn_cast<FreeInst>(I)) {
Christopher Lambbb2f2222007-12-17 01:12:55 +0000167 Value *PtrCast =
168 new BitCastInst(FI->getOperand(0),
Owen Anderson175b6542009-07-22 00:24:57 +0000169 Context.getPointerTypeUnqual(Type::Int8Ty), "", I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000170
171 // Insert a call to the free function...
Gabor Greifd6da1d02008-04-06 20:25:17 +0000172 CallInst::Create(FreeFunc, PtrCast, "", I)->setTailCall();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000173
174 // Delete the old free instruction
175 I = --BBIL.erase(I);
176 Changed = true;
177 ++NumLowered;
178 }
179 }
180
181 return Changed;
182}
183