blob: 7ce247909c5379c42e54445f19d06a5365df3f5c [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//
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#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"
22#include "llvm/Pass.h"
23#include "llvm/ADT/Statistic.h"
24#include "llvm/Target/TargetData.h"
25#include "llvm/Support/Compiler.h"
26using namespace llvm;
27
28STATISTIC(NumLowered, "Number of allocations lowered");
29
30namespace {
31 /// LowerAllocations - Turn malloc and free instructions into %malloc and
32 /// %free calls.
33 ///
34 class VISIBILITY_HIDDEN LowerAllocations : public BasicBlockPass {
35 Constant *MallocFunc; // Functions in the module we are processing
36 Constant *FreeFunc; // Initialized by doInitialization
37 bool LowerMallocArgToInteger;
38 public:
39 static char ID; // Pass ID, replacement for typeid
40 LowerAllocations(bool LowerToInt = false)
41 : BasicBlockPass((intptr_t)&ID), MallocFunc(0), FreeFunc(0),
42 LowerMallocArgToInteger(LowerToInt) {}
43
44 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
45 AU.addRequired<TargetData>();
46 AU.setPreservesCFG();
47
48 // This is a cluster of orthogonal Transforms:
49 AU.addPreserved<UnifyFunctionExitNodes>();
50 AU.addPreservedID(PromoteMemoryToRegisterID);
51 AU.addPreservedID(LowerSelectID);
52 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) {
62 return BasicBlockPass::doInitialization(F);
63 }
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 };
70
71 char LowerAllocations::ID = 0;
72 RegisterPass<LowerAllocations>
73 X("lowerallocs", "Lower allocations from instructions to calls");
74}
75
76// Publically exposed interface to pass...
77const PassInfo *llvm::LowerAllocationsID = X.getPassInfo();
78// 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) {
90 const Type *BPTy = PointerType::get(Type::Int8Ty);
91 // Prototype malloc as "char* malloc(...)", because we don't know in
92 // doInitialization whether size_t is int or long.
93 FunctionType *FT = FunctionType::get(BPTy, std::vector<const Type*>(), true);
94 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
106 BasicBlock::InstListType &BBIL = BB.getInstList();
107
108 const TargetData &TD = getAnalysis<TargetData>();
109 const Type *IntPtrTy = TD.getIntPtrType();
110
111 // Loop over all of the instructions, looking for malloc or free instructions
112 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I) {
113 if (MallocInst *MI = dyn_cast<MallocInst>(I)) {
114 const Type *AllocTy = MI->getType()->getElementType();
115
116 // malloc(type) becomes sbyte *malloc(size)
117 Value *MallocArg;
118 if (LowerMallocArgToInteger)
119 MallocArg = ConstantInt::get(Type::Int64Ty, TD.getTypeSize(AllocTy));
120 else
121 MallocArg = ConstantExpr::getSizeOf(AllocTy);
122 MallocArg = ConstantExpr::getTruncOrBitCast(cast<Constant>(MallocArg),
123 IntPtrTy);
124
125 if (MI->isArrayAllocation()) {
126 if (isa<ConstantInt>(MallocArg) &&
127 cast<ConstantInt>(MallocArg)->isOne()) {
128 MallocArg = MI->getOperand(0); // Operand * 1 = Operand
129 } else if (Constant *CO = dyn_cast<Constant>(MI->getOperand(0))) {
130 CO = ConstantExpr::getIntegerCast(CO, IntPtrTy, false /*ZExt*/);
131 MallocArg = ConstantExpr::getMul(CO, cast<Constant>(MallocArg));
132 } else {
133 Value *Scale = MI->getOperand(0);
134 if (Scale->getType() != IntPtrTy)
135 Scale = CastInst::createIntegerCast(Scale, IntPtrTy, false /*ZExt*/,
136 "", I);
137
138 // Multiply it by the array size if necessary...
139 MallocArg = BinaryOperator::create(Instruction::Mul, Scale,
140 MallocArg, "", I);
141 }
142 }
143
144 // Create the call to Malloc.
145 CallInst *MCall = new CallInst(MallocFunc, MallocArg, "", I);
146 MCall->setTailCall();
147
148 // Create a cast instruction to convert to the right type...
149 Value *MCast;
150 if (MCall->getType() != Type::VoidTy)
151 MCast = new BitCastInst(MCall, MI->getType(), "", I);
152 else
153 MCast = Constant::getNullValue(MI->getType());
154
155 // Replace all uses of the old malloc inst with the cast inst
156 MI->replaceAllUsesWith(MCast);
157 I = --BBIL.erase(I); // remove and delete the malloc instr...
158 Changed = true;
159 ++NumLowered;
160 } else if (FreeInst *FI = dyn_cast<FreeInst>(I)) {
161 Value *PtrCast = new BitCastInst(FI->getOperand(0),
162 PointerType::get(Type::Int8Ty), "", I);
163
164 // Insert a call to the free function...
165 (new CallInst(FreeFunc, PtrCast, "", I))->setTailCall();
166
167 // Delete the old free instruction
168 I = --BBIL.erase(I);
169 Changed = true;
170 ++NumLowered;
171 }
172 }
173
174 return Changed;
175}
176