6082780e35480e73a1dac3e518554f05cd3772df
[oota-llvm.git] / lib / Transforms / IPO / RaiseAllocations.cpp
1 //===- RaiseAllocations.cpp - Convert %malloc & %free calls to insts ------===//
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 // This file defines the RaiseAllocations pass which convert malloc and free
11 // calls to malloc and free instructions.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "raiseallocs"
16 #include "llvm/Transforms/IPO.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Module.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Pass.h"
22 #include "llvm/Support/CallSite.h"
23 #include "llvm/ADT/Statistic.h"
24 using namespace llvm;
25
26 STATISTIC(NumRaised, "Number of allocations raised");
27
28 namespace {
29   // RaiseAllocations - Turn %malloc and %free calls into the appropriate
30   // instruction.
31   //
32   class RaiseAllocations : public ModulePass {
33     Function *MallocFunc;   // Functions in the module we are processing
34     Function *FreeFunc;     // Initialized by doPassInitializationVirt
35   public:
36     RaiseAllocations() : MallocFunc(0), FreeFunc(0) {}
37
38     // doPassInitialization - For the raise allocations pass, this finds a
39     // declaration for malloc and free if they exist.
40     //
41     void doInitialization(Module &M);
42
43     // run - This method does the actual work of converting instructions over.
44     //
45     bool runOnModule(Module &M);
46   };
47
48   RegisterPass<RaiseAllocations>
49   X("raiseallocs", "Raise allocations from calls to instructions");
50 }  // end anonymous namespace
51
52
53 // createRaiseAllocationsPass - The interface to this file...
54 ModulePass *llvm::createRaiseAllocationsPass() {
55   return new RaiseAllocations();
56 }
57
58
59 // If the module has a symbol table, they might be referring to the malloc and
60 // free functions.  If this is the case, grab the method pointers that the
61 // module is using.
62 //
63 // Lookup %malloc and %free in the symbol table, for later use.  If they don't
64 // exist, or are not external, we do not worry about converting calls to that
65 // function into the appropriate instruction.
66 //
67 void RaiseAllocations::doInitialization(Module &M) {
68   const FunctionType *MallocType =   // Get the type for malloc
69     FunctionType::get(PointerType::get(Type::Int8Ty),
70                     std::vector<const Type*>(1, Type::Int64Ty), false);
71
72   const FunctionType *FreeType =     // Get the type for free
73     FunctionType::get(Type::VoidTy,
74                    std::vector<const Type*>(1, PointerType::get(Type::Int8Ty)),
75                       false);
76
77   // Get Malloc and free prototypes if they exist!
78   MallocFunc = M.getFunction("malloc", MallocType);
79   FreeFunc   = M.getFunction("free"  , FreeType);
80
81   // Check to see if the prototype is wrong, giving us sbyte*(uint) * malloc
82   // This handles the common declaration of: 'void *malloc(unsigned);'
83   if (MallocFunc == 0) {
84     MallocType = FunctionType::get(PointerType::get(Type::Int8Ty),
85                             std::vector<const Type*>(1, Type::Int32Ty), false);
86     MallocFunc = M.getFunction("malloc", MallocType);
87   }
88
89   // Check to see if the prototype is missing, giving us sbyte*(...) * malloc
90   // This handles the common declaration of: 'void *malloc();'
91   if (MallocFunc == 0) {
92     MallocType = FunctionType::get(PointerType::get(Type::Int8Ty),
93                                    std::vector<const Type*>(), true);
94     MallocFunc = M.getFunction("malloc", MallocType);
95   }
96
97   // Check to see if the prototype was forgotten, giving us void (...) * free
98   // This handles the common forward declaration of: 'void free();'
99   if (FreeFunc == 0) {
100     FreeType = FunctionType::get(Type::VoidTy, std::vector<const Type*>(),true);
101     FreeFunc = M.getFunction("free", FreeType);
102   }
103
104   // One last try, check to see if we can find free as 'int (...)* free'.  This
105   // handles the case where NOTHING was declared.
106   if (FreeFunc == 0) {
107     FreeType = FunctionType::get(Type::Int32Ty, std::vector<const Type*>(),true);
108     FreeFunc = M.getFunction("free", FreeType);
109   }
110
111   // Don't mess with locally defined versions of these functions...
112   if (MallocFunc && !MallocFunc->isDeclaration()) MallocFunc = 0;
113   if (FreeFunc && !FreeFunc->isDeclaration())     FreeFunc = 0;
114 }
115
116 // run - Transform calls into instructions...
117 //
118 bool RaiseAllocations::runOnModule(Module &M) {
119   // Find the malloc/free prototypes...
120   doInitialization(M);
121
122   bool Changed = false;
123
124   // First, process all of the malloc calls...
125   if (MallocFunc) {
126     std::vector<User*> Users(MallocFunc->use_begin(), MallocFunc->use_end());
127     std::vector<Value*> EqPointers;   // Values equal to MallocFunc
128     while (!Users.empty()) {
129       User *U = Users.back();
130       Users.pop_back();
131
132       if (Instruction *I = dyn_cast<Instruction>(U)) {
133         CallSite CS = CallSite::get(I);
134         if (CS.getInstruction() && CS.arg_begin() != CS.arg_end() &&
135             (CS.getCalledFunction() == MallocFunc ||
136              std::find(EqPointers.begin(), EqPointers.end(),
137                        CS.getCalledValue()) != EqPointers.end())) {
138
139           Value *Source = *CS.arg_begin();
140
141           // If no prototype was provided for malloc, we may need to cast the
142           // source size.
143           if (Source->getType() != Type::Int32Ty)
144             Source = 
145               CastInst::createIntegerCast(Source, Type::Int32Ty, false/*ZExt*/,
146                                           "MallocAmtCast", I);
147
148           std::string Name(I->getName()); I->setName("");
149           MallocInst *MI = new MallocInst(Type::Int8Ty, Source, Name, I);
150           I->replaceAllUsesWith(MI);
151
152           // If the old instruction was an invoke, add an unconditional branch
153           // before the invoke, which will become the new terminator.
154           if (InvokeInst *II = dyn_cast<InvokeInst>(I))
155             new BranchInst(II->getNormalDest(), I);
156
157           // Delete the old call site
158           MI->getParent()->getInstList().erase(I);
159           Changed = true;
160           ++NumRaised;
161         }
162       } else if (GlobalValue *GV = dyn_cast<GlobalValue>(U)) {
163         Users.insert(Users.end(), GV->use_begin(), GV->use_end());
164         EqPointers.push_back(GV);
165       } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
166         if (CE->isCast()) {
167           Users.insert(Users.end(), CE->use_begin(), CE->use_end());
168           EqPointers.push_back(CE);
169         }
170       }
171     }
172   }
173
174   // Next, process all free calls...
175   if (FreeFunc) {
176     std::vector<User*> Users(FreeFunc->use_begin(), FreeFunc->use_end());
177     std::vector<Value*> EqPointers;   // Values equal to FreeFunc
178
179     while (!Users.empty()) {
180       User *U = Users.back();
181       Users.pop_back();
182
183       if (Instruction *I = dyn_cast<Instruction>(U)) {
184         CallSite CS = CallSite::get(I);
185         if (CS.getInstruction() && CS.arg_begin() != CS.arg_end() &&
186             (CS.getCalledFunction() == FreeFunc ||
187              std::find(EqPointers.begin(), EqPointers.end(),
188                        CS.getCalledValue()) != EqPointers.end())) {
189
190           // If no prototype was provided for free, we may need to cast the
191           // source pointer.  This should be really uncommon, but it's necessary
192           // just in case we are dealing with weird code like this:
193           //   free((long)ptr);
194           //
195           Value *Source = *CS.arg_begin();
196           if (!isa<PointerType>(Source->getType()))
197             Source = new IntToPtrInst(Source, PointerType::get(Type::Int8Ty), 
198                                       "FreePtrCast", I);
199           new FreeInst(Source, I);
200
201           // If the old instruction was an invoke, add an unconditional branch
202           // before the invoke, which will become the new terminator.
203           if (InvokeInst *II = dyn_cast<InvokeInst>(I))
204             new BranchInst(II->getNormalDest(), I);
205
206           // Delete the old call site
207           if (I->getType() != Type::VoidTy)
208             I->replaceAllUsesWith(UndefValue::get(I->getType()));
209           I->eraseFromParent();
210           Changed = true;
211           ++NumRaised;
212         }
213       } else if (GlobalValue *GV = dyn_cast<GlobalValue>(U)) {
214         Users.insert(Users.end(), GV->use_begin(), GV->use_end());
215         EqPointers.push_back(GV);
216       } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
217         if (CE->isCast()) {
218           Users.insert(Users.end(), CE->use_begin(), CE->use_end());
219           EqPointers.push_back(CE);
220         }
221       }
222     }
223   }
224
225   return Changed;
226 }