Push LLVMContexts through the IntegerType APIs.
[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 is distributed under the University of Illinois Open Source
6 // 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/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"
26 #include <algorithm>
27 using namespace llvm;
28
29 STATISTIC(NumRaised, "Number of allocations raised");
30
31 namespace {
32   // RaiseAllocations - Turn @malloc and @free calls into the appropriate
33   // instruction.
34   //
35   class VISIBILITY_HIDDEN RaiseAllocations : public ModulePass {
36     Function *MallocFunc;   // Functions in the module we are processing
37     Function *FreeFunc;     // Initialized by doPassInitializationVirt
38   public:
39     static char ID; // Pass identification, replacement for typeid
40     RaiseAllocations() 
41       : ModulePass(&ID), MallocFunc(0), FreeFunc(0) {}
42
43     // doPassInitialization - For the raise allocations pass, this finds a
44     // declaration for malloc and free if they exist.
45     //
46     void doInitialization(Module &M);
47
48     // run - This method does the actual work of converting instructions over.
49     //
50     bool runOnModule(Module &M);
51   };
52 }  // end anonymous namespace
53
54 char RaiseAllocations::ID = 0;
55 static RegisterPass<RaiseAllocations>
56 X("raiseallocs", "Raise allocations from calls to instructions");
57
58 // createRaiseAllocationsPass - The interface to this file...
59 ModulePass *llvm::createRaiseAllocationsPass() {
60   return new RaiseAllocations();
61 }
62
63
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
66 // module is using.
67 //
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.
71 //
72 void RaiseAllocations::doInitialization(Module &M) {
73   // Get Malloc and free prototypes if they exist!
74   MallocFunc = M.getFunction("malloc");
75   if (MallocFunc) {
76     const FunctionType* TyWeHave = MallocFunc->getFunctionType();
77
78     // Get the expected prototype for malloc
79     const FunctionType *Malloc1Type = 
80       FunctionType::get(PointerType::getUnqual(Type::getInt8Ty(M.getContext())),
81                       std::vector<const Type*>(1,
82                                       Type::getInt64Ty(M.getContext())), false);
83
84     // Chck to see if we got the expected malloc
85     if (TyWeHave != Malloc1Type) {
86       // Check to see if the prototype is wrong, giving us i8*(i32) * malloc
87       // This handles the common declaration of: 'void *malloc(unsigned);'
88       const FunctionType *Malloc2Type = 
89         FunctionType::get(PointerType::getUnqual(
90                           Type::getInt8Ty(M.getContext())),
91                           std::vector<const Type*>(1, 
92                                       Type::getInt32Ty(M.getContext())), false);
93       if (TyWeHave != Malloc2Type) {
94         // Check to see if the prototype is missing, giving us 
95         // i8*(...) * malloc
96         // This handles the common declaration of: 'void *malloc();'
97         const FunctionType *Malloc3Type = 
98           FunctionType::get(PointerType::getUnqual(
99                                     Type::getInt8Ty(M.getContext())), 
100                                     true);
101         if (TyWeHave != Malloc3Type)
102           // Give up
103           MallocFunc = 0;
104       }
105     }
106   }
107
108   FreeFunc = M.getFunction("free");
109   if (FreeFunc) {
110     const FunctionType* TyWeHave = FreeFunc->getFunctionType();
111     
112     // Get the expected prototype for void free(i8*)
113     const FunctionType *Free1Type =
114       FunctionType::get(Type::getVoidTy(M.getContext()),
115         std::vector<const Type*>(1, PointerType::getUnqual(
116                                  Type::getInt8Ty(M.getContext()))), 
117                                  false);
118
119     if (TyWeHave != Free1Type) {
120       // Check to see if the prototype was forgotten, giving us 
121       // void (...) * free
122       // This handles the common forward declaration of: 'void free();'
123       const FunctionType* Free2Type =
124                     FunctionType::get(Type::getVoidTy(M.getContext()), true);
125
126       if (TyWeHave != Free2Type) {
127         // One last try, check to see if we can find free as 
128         // int (...)* free.  This handles the case where NOTHING was declared.
129         const FunctionType* Free3Type =
130                     FunctionType::get(Type::getInt32Ty(M.getContext()), true);
131         
132         if (TyWeHave != Free3Type) {
133           // Give up.
134           FreeFunc = 0;
135         }
136       }
137     }
138   }
139
140   // Don't mess with locally defined versions of these functions...
141   if (MallocFunc && !MallocFunc->isDeclaration()) MallocFunc = 0;
142   if (FreeFunc && !FreeFunc->isDeclaration())     FreeFunc = 0;
143 }
144
145 // run - Transform calls into instructions...
146 //
147 bool RaiseAllocations::runOnModule(Module &M) {
148   // Find the malloc/free prototypes...
149   doInitialization(M);
150   
151   bool Changed = false;
152
153   // First, process all of the malloc calls...
154   if (MallocFunc) {
155     std::vector<User*> Users(MallocFunc->use_begin(), MallocFunc->use_end());
156     std::vector<Value*> EqPointers;   // Values equal to MallocFunc
157     while (!Users.empty()) {
158       User *U = Users.back();
159       Users.pop_back();
160
161       if (Instruction *I = dyn_cast<Instruction>(U)) {
162         CallSite CS = CallSite::get(I);
163         if (CS.getInstruction() && !CS.arg_empty() &&
164             (CS.getCalledFunction() == MallocFunc ||
165              std::find(EqPointers.begin(), EqPointers.end(),
166                        CS.getCalledValue()) != EqPointers.end())) {
167
168           Value *Source = *CS.arg_begin();
169
170           // If no prototype was provided for malloc, we may need to cast the
171           // source size.
172           if (Source->getType() != Type::getInt32Ty(M.getContext()))
173             Source = 
174               CastInst::CreateIntegerCast(Source, 
175                                           Type::getInt32Ty(M.getContext()), 
176                                           false/*ZExt*/,
177                                           "MallocAmtCast", I);
178
179           MallocInst *MI = new MallocInst(Type::getInt8Ty(M.getContext()),
180                                           Source, "", I);
181           MI->takeName(I);
182           I->replaceAllUsesWith(MI);
183
184           // If the old instruction was an invoke, add an unconditional branch
185           // before the invoke, which will become the new terminator.
186           if (InvokeInst *II = dyn_cast<InvokeInst>(I))
187             BranchInst::Create(II->getNormalDest(), I);
188
189           // Delete the old call site
190           I->eraseFromParent();
191           Changed = true;
192           ++NumRaised;
193         }
194       } else if (GlobalValue *GV = dyn_cast<GlobalValue>(U)) {
195         Users.insert(Users.end(), GV->use_begin(), GV->use_end());
196         EqPointers.push_back(GV);
197       } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
198         if (CE->isCast()) {
199           Users.insert(Users.end(), CE->use_begin(), CE->use_end());
200           EqPointers.push_back(CE);
201         }
202       }
203     }
204   }
205
206   // Next, process all free calls...
207   if (FreeFunc) {
208     std::vector<User*> Users(FreeFunc->use_begin(), FreeFunc->use_end());
209     std::vector<Value*> EqPointers;   // Values equal to FreeFunc
210
211     while (!Users.empty()) {
212       User *U = Users.back();
213       Users.pop_back();
214
215       if (Instruction *I = dyn_cast<Instruction>(U)) {
216         if (isa<InvokeInst>(I))
217           continue;
218         CallSite CS = CallSite::get(I);
219         if (CS.getInstruction() && !CS.arg_empty() &&
220             (CS.getCalledFunction() == FreeFunc ||
221              std::find(EqPointers.begin(), EqPointers.end(),
222                        CS.getCalledValue()) != EqPointers.end())) {
223
224           // If no prototype was provided for free, we may need to cast the
225           // source pointer.  This should be really uncommon, but it's necessary
226           // just in case we are dealing with weird code like this:
227           //   free((long)ptr);
228           //
229           Value *Source = *CS.arg_begin();
230           if (!isa<PointerType>(Source->getType()))
231             Source = new IntToPtrInst(Source,           
232                         PointerType::getUnqual(Type::getInt8Ty(M.getContext())), 
233                                       "FreePtrCast", I);
234           new FreeInst(Source, I);
235
236           // If the old instruction was an invoke, add an unconditional branch
237           // before the invoke, which will become the new terminator.
238           if (InvokeInst *II = dyn_cast<InvokeInst>(I))
239             BranchInst::Create(II->getNormalDest(), I);
240
241           // Delete the old call site
242           if (I->getType() != Type::getVoidTy(M.getContext()))
243             I->replaceAllUsesWith(UndefValue::get(I->getType()));
244           I->eraseFromParent();
245           Changed = true;
246           ++NumRaised;
247         }
248       } else if (GlobalValue *GV = dyn_cast<GlobalValue>(U)) {
249         Users.insert(Users.end(), GV->use_begin(), GV->use_end());
250         EqPointers.push_back(GV);
251       } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
252         if (CE->isCast()) {
253           Users.insert(Users.end(), CE->use_begin(), CE->use_end());
254           EqPointers.push_back(CE);
255         }
256       }
257     }
258   }
259
260   return Changed;
261 }