1 //===-- IndMemRemoval.cpp - Remove indirect allocations and frees ----------===//
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 // This pass finds places where memory allocation functions may escape into
11 // indirect land. Some transforms are much easier (aka possible) only if free
12 // or malloc are not called indirectly.
13 // Thus find places where the address of memory functions are taken and construct
14 // bounce functions with direct calls of those functions.
16 //===----------------------------------------------------------------------===//
18 #define DEBUG_TYPE "indmemrem"
19 #include "llvm/Transforms/IPO.h"
20 #include "llvm/Pass.h"
21 #include "llvm/Module.h"
22 #include "llvm/Instructions.h"
23 #include "llvm/Type.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/ADT/Statistic.h"
28 STATISTIC(NumBounceSites, "Number of sites modified");
29 STATISTIC(NumBounce , "Number of bounce functions created");
32 class IndMemRemPass : public ModulePass {
34 virtual bool runOnModule(Module &M);
36 RegisterPass<IndMemRemPass> X("indmemrem","Indirect Malloc and Free Removal");
37 } // end anonymous namespace
40 bool IndMemRemPass::runOnModule(Module &M) {
41 //in Theory, all direct calls of malloc and free should be promoted
42 //to intrinsics. Therefor, this goes through and finds where the
43 //address of free or malloc are taken and replaces those with bounce
44 //functions, ensuring that all malloc and free that might happen
45 //happen through intrinsics.
47 if (Function* F = M.getNamedFunction("free")) {
48 assert(F->isDeclaration() && "free not external?");
49 if (!F->use_empty()) {
50 Function* FN = new Function(F->getFunctionType(),
51 GlobalValue::LinkOnceLinkage,
52 "free_llvm_bounce", &M);
53 BasicBlock* bb = new BasicBlock("entry",FN);
54 Instruction* R = new ReturnInst(bb);
55 new FreeInst(FN->arg_begin(), R);
57 NumBounceSites += F->getNumUses();
58 F->replaceAllUsesWith(FN);
62 if (Function* F = M.getNamedFunction("malloc")) {
63 assert(F->isDeclaration() && "malloc not external?");
64 if (!F->use_empty()) {
65 Function* FN = new Function(F->getFunctionType(),
66 GlobalValue::LinkOnceLinkage,
67 "malloc_llvm_bounce", &M);
68 BasicBlock* bb = new BasicBlock("entry",FN);
69 Instruction* c = CastInst::createIntegerCast(
70 FN->arg_begin(), Type::Int32Ty, false, "c", bb);
71 Instruction* a = new MallocInst(Type::Int8Ty, c, "m", bb);
72 new ReturnInst(a, bb);
74 NumBounceSites += F->getNumUses();
75 F->replaceAllUsesWith(FN);
82 ModulePass *llvm::createIndMemRemPass() {
83 return new IndMemRemPass();