1 //===- RaiseAllocations.cpp - Convert @malloc & @free calls to insts ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the RaiseAllocations pass which convert malloc and free
11 // calls to malloc and free instructions.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "raiseallocs"
16 #include "llvm/Transforms/IPO.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/LLVMContext.h"
20 #include "llvm/Module.h"
21 #include "llvm/Instructions.h"
22 #include "llvm/Pass.h"
23 #include "llvm/Support/CallSite.h"
24 #include "llvm/Support/Compiler.h"
25 #include "llvm/ADT/Statistic.h"
29 STATISTIC(NumRaised, "Number of allocations raised");
32 // RaiseAllocations - Turn @malloc and @free calls into the appropriate
35 class VISIBILITY_HIDDEN RaiseAllocations : public ModulePass {
36 Function *MallocFunc; // Functions in the module we are processing
37 Function *FreeFunc; // Initialized by doPassInitializationVirt
39 static char ID; // Pass identification, replacement for typeid
41 : ModulePass(&ID), MallocFunc(0), FreeFunc(0) {}
43 // doPassInitialization - For the raise allocations pass, this finds a
44 // declaration for malloc and free if they exist.
46 void doInitialization(Module &M);
48 // run - This method does the actual work of converting instructions over.
50 bool runOnModule(Module &M);
52 } // end anonymous namespace
54 char RaiseAllocations::ID = 0;
55 static RegisterPass<RaiseAllocations>
56 X("raiseallocs", "Raise allocations from calls to instructions");
58 // createRaiseAllocationsPass - The interface to this file...
59 ModulePass *llvm::createRaiseAllocationsPass() {
60 return new RaiseAllocations();
64 // If the module has a symbol table, they might be referring to the malloc and
65 // free functions. If this is the case, grab the method pointers that the
68 // Lookup @malloc and @free in the symbol table, for later use. If they don't
69 // exist, or are not external, we do not worry about converting calls to that
70 // function into the appropriate instruction.
72 void RaiseAllocations::doInitialization(Module &M) {
73 Context = &M.getContext();
75 // Get Malloc and free prototypes if they exist!
76 MallocFunc = M.getFunction("malloc");
78 const FunctionType* TyWeHave = MallocFunc->getFunctionType();
80 // Get the expected prototype for malloc
81 const FunctionType *Malloc1Type =
82 Context->getFunctionType(Context->getPointerTypeUnqual(Type::Int8Ty),
83 std::vector<const Type*>(1, Type::Int64Ty), false);
85 // Chck to see if we got the expected malloc
86 if (TyWeHave != Malloc1Type) {
87 // Check to see if the prototype is wrong, giving us i8*(i32) * malloc
88 // This handles the common declaration of: 'void *malloc(unsigned);'
89 const FunctionType *Malloc2Type =
90 Context->getFunctionType(Context->getPointerTypeUnqual(Type::Int8Ty),
91 std::vector<const Type*>(1, Type::Int32Ty), false);
92 if (TyWeHave != Malloc2Type) {
93 // Check to see if the prototype is missing, giving us
95 // This handles the common declaration of: 'void *malloc();'
96 const FunctionType *Malloc3Type =
97 Context->getFunctionType(Context->getPointerTypeUnqual(Type::Int8Ty),
99 if (TyWeHave != Malloc3Type)
106 FreeFunc = M.getFunction("free");
108 const FunctionType* TyWeHave = FreeFunc->getFunctionType();
110 // Get the expected prototype for void free(i8*)
111 const FunctionType *Free1Type = Context->getFunctionType(Type::VoidTy,
112 std::vector<const Type*>(1, Context->getPointerTypeUnqual(Type::Int8Ty)),
115 if (TyWeHave != Free1Type) {
116 // Check to see if the prototype was forgotten, giving us
118 // This handles the common forward declaration of: 'void free();'
119 const FunctionType* Free2Type = Context->getFunctionType(Type::VoidTy,
122 if (TyWeHave != Free2Type) {
123 // One last try, check to see if we can find free as
124 // int (...)* free. This handles the case where NOTHING was declared.
125 const FunctionType* Free3Type = Context->getFunctionType(Type::Int32Ty,
128 if (TyWeHave != Free3Type) {
136 // Don't mess with locally defined versions of these functions...
137 if (MallocFunc && !MallocFunc->isDeclaration()) MallocFunc = 0;
138 if (FreeFunc && !FreeFunc->isDeclaration()) FreeFunc = 0;
141 // run - Transform calls into instructions...
143 bool RaiseAllocations::runOnModule(Module &M) {
144 // Find the malloc/free prototypes...
147 bool Changed = false;
149 // First, process all of the malloc calls...
151 std::vector<User*> Users(MallocFunc->use_begin(), MallocFunc->use_end());
152 std::vector<Value*> EqPointers; // Values equal to MallocFunc
153 while (!Users.empty()) {
154 User *U = Users.back();
157 if (Instruction *I = dyn_cast<Instruction>(U)) {
158 CallSite CS = CallSite::get(I);
159 if (CS.getInstruction() && !CS.arg_empty() &&
160 (CS.getCalledFunction() == MallocFunc ||
161 std::find(EqPointers.begin(), EqPointers.end(),
162 CS.getCalledValue()) != EqPointers.end())) {
164 Value *Source = *CS.arg_begin();
166 // If no prototype was provided for malloc, we may need to cast the
168 if (Source->getType() != Type::Int32Ty)
170 CastInst::CreateIntegerCast(Source, Type::Int32Ty, false/*ZExt*/,
173 MallocInst *MI = new MallocInst(Type::Int8Ty, Source, "", I);
175 I->replaceAllUsesWith(MI);
177 // If the old instruction was an invoke, add an unconditional branch
178 // before the invoke, which will become the new terminator.
179 if (InvokeInst *II = dyn_cast<InvokeInst>(I))
180 BranchInst::Create(II->getNormalDest(), I);
182 // Delete the old call site
183 I->eraseFromParent();
187 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(U)) {
188 Users.insert(Users.end(), GV->use_begin(), GV->use_end());
189 EqPointers.push_back(GV);
190 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
192 Users.insert(Users.end(), CE->use_begin(), CE->use_end());
193 EqPointers.push_back(CE);
199 // Next, process all free calls...
201 std::vector<User*> Users(FreeFunc->use_begin(), FreeFunc->use_end());
202 std::vector<Value*> EqPointers; // Values equal to FreeFunc
204 while (!Users.empty()) {
205 User *U = Users.back();
208 if (Instruction *I = dyn_cast<Instruction>(U)) {
209 if (isa<InvokeInst>(I))
211 CallSite CS = CallSite::get(I);
212 if (CS.getInstruction() && !CS.arg_empty() &&
213 (CS.getCalledFunction() == FreeFunc ||
214 std::find(EqPointers.begin(), EqPointers.end(),
215 CS.getCalledValue()) != EqPointers.end())) {
217 // If no prototype was provided for free, we may need to cast the
218 // source pointer. This should be really uncommon, but it's necessary
219 // just in case we are dealing with weird code like this:
222 Value *Source = *CS.arg_begin();
223 if (!isa<PointerType>(Source->getType()))
224 Source = new IntToPtrInst(Source,
225 Context->getPointerTypeUnqual(Type::Int8Ty),
227 new FreeInst(Source, I);
229 // If the old instruction was an invoke, add an unconditional branch
230 // before the invoke, which will become the new terminator.
231 if (InvokeInst *II = dyn_cast<InvokeInst>(I))
232 BranchInst::Create(II->getNormalDest(), I);
234 // Delete the old call site
235 if (I->getType() != Type::VoidTy)
236 I->replaceAllUsesWith(Context->getUndef(I->getType()));
237 I->eraseFromParent();
241 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(U)) {
242 Users.insert(Users.end(), GV->use_begin(), GV->use_end());
243 EqPointers.push_back(GV);
244 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
246 Users.insert(Users.end(), CE->use_begin(), CE->use_end());
247 EqPointers.push_back(CE);