This is effectively a complete rewrite of the globaldce algorithm, resulting
[oota-llvm.git] / lib / Transforms / IPO / RaiseAllocations.cpp
1 //===- RaiseAllocations.cpp - Convert %malloc & %free calls to insts ------===//
2 //
3 // This file defines the RaiseAllocations pass which convert malloc and free
4 // calls to malloc and free instructions.
5 //
6 //===----------------------------------------------------------------------===//
7
8 #include "llvm/Transforms/IPO.h"
9 #include "llvm/Module.h"
10 #include "llvm/DerivedTypes.h"
11 #include "llvm/iMemory.h"
12 #include "llvm/iOther.h"
13 #include "llvm/Pass.h"
14 #include "llvm/Support/CallSite.h"
15 #include "Support/Statistic.h"
16
17 namespace {
18   Statistic<> NumRaised("raiseallocs", "Number of allocations raised");
19
20   // RaiseAllocations - Turn %malloc and %free calls into the appropriate
21   // instruction.
22   //
23   class RaiseAllocations : public Pass {
24     Function *MallocFunc;   // Functions in the module we are processing
25     Function *FreeFunc;     // Initialized by doPassInitializationVirt
26   public:
27     RaiseAllocations() : MallocFunc(0), FreeFunc(0) {}
28     
29     // doPassInitialization - For the raise allocations pass, this finds a
30     // declaration for malloc and free if they exist.
31     //
32     void doInitialization(Module &M);
33     
34     // run - This method does the actual work of converting instructions over.
35     //
36     bool run(Module &M);
37   };
38   
39   RegisterOpt<RaiseAllocations>
40   X("raiseallocs", "Raise allocations from calls to instructions");
41 }  // end anonymous namespace
42
43
44 // createRaiseAllocationsPass - The interface to this file...
45 Pass *createRaiseAllocationsPass() {
46   return new RaiseAllocations();
47 }
48
49
50 // If the module has a symbol table, they might be referring to the malloc and
51 // free functions.  If this is the case, grab the method pointers that the
52 // module is using.
53 //
54 // Lookup %malloc and %free in the symbol table, for later use.  If they don't
55 // exist, or are not external, we do not worry about converting calls to that
56 // function into the appropriate instruction.
57 //
58 void RaiseAllocations::doInitialization(Module &M) {
59   const FunctionType *MallocType =   // Get the type for malloc
60     FunctionType::get(PointerType::get(Type::SByteTy),
61                     std::vector<const Type*>(1, Type::ULongTy), false);
62
63   const FunctionType *FreeType =     // Get the type for free
64     FunctionType::get(Type::VoidTy,
65                    std::vector<const Type*>(1, PointerType::get(Type::SByteTy)),
66                       false);
67
68   // Get Malloc and free prototypes if they exist!
69   MallocFunc = M.getFunction("malloc", MallocType);
70   FreeFunc   = M.getFunction("free"  , FreeType);
71
72   // Check to see if the prototype is wrong, giving us sbyte*(uint) * malloc
73   // This handles the common declaration of: 'void *malloc(unsigned);'
74   if (MallocFunc == 0) {
75     MallocType = FunctionType::get(PointerType::get(Type::SByteTy),
76                             std::vector<const Type*>(1, Type::UIntTy), false);
77     MallocFunc = M.getFunction("malloc", MallocType);
78   }
79
80   // Check to see if the prototype is missing, giving us sbyte*(...) * malloc
81   // This handles the common declaration of: 'void *malloc();'
82   if (MallocFunc == 0) {
83     MallocType = FunctionType::get(PointerType::get(Type::SByteTy),
84                                    std::vector<const Type*>(), true);
85     MallocFunc = M.getFunction("malloc", MallocType);
86   }
87
88   // Check to see if the prototype was forgotten, giving us void (...) * free
89   // This handles the common forward declaration of: 'void free();'
90   if (FreeFunc == 0) {
91     FreeType = FunctionType::get(Type::VoidTy, std::vector<const Type*>(),true);
92     FreeFunc = M.getFunction("free", FreeType);
93   }
94
95   // One last try, check to see if we can find free as 'int (...)* free'.  This
96   // handles the case where NOTHING was declared.
97   if (FreeFunc == 0) {
98     FreeType = FunctionType::get(Type::IntTy, std::vector<const Type*>(),true);
99     FreeFunc = M.getFunction("free", FreeType);
100   }
101
102   // Don't mess with locally defined versions of these functions...
103   if (MallocFunc && !MallocFunc->isExternal()) MallocFunc = 0;
104   if (FreeFunc && !FreeFunc->isExternal())     FreeFunc = 0;
105 }
106
107 // run - Transform calls into instructions...
108 //
109 bool RaiseAllocations::run(Module &M) {
110   // Find the malloc/free prototypes...
111   doInitialization(M);
112
113   bool Changed = false;
114
115   // First, process all of the malloc calls...
116   if (MallocFunc) {
117     std::vector<User*> Users(MallocFunc->use_begin(), MallocFunc->use_end());
118     while (!Users.empty()) {
119       if (Instruction *I = dyn_cast<Instruction>(Users.back())) {
120         CallSite CS = CallSite::get(I);
121         if (CS.getInstruction() && CS.getCalledFunction() == MallocFunc &&
122             CS.arg_begin() != CS.arg_end()) {
123           Value *Source = *CS.arg_begin();
124           
125           // If no prototype was provided for malloc, we may need to cast the
126           // source size.
127           if (Source->getType() != Type::UIntTy)
128             Source = new CastInst(Source, Type::UIntTy, "MallocAmtCast", I);
129           
130           std::string Name(I->getName()); I->setName("");
131           MallocInst *MI = new MallocInst(Type::SByteTy, Source, Name, I);
132           I->replaceAllUsesWith(MI);
133           MI->getParent()->getInstList().erase(I);
134           Changed = true;
135           ++NumRaised;
136         }
137       }
138
139       Users.pop_back();
140     }
141   }
142
143   // Next, process all free calls...
144   if (FreeFunc) {
145     std::vector<User*> Users(FreeFunc->use_begin(), FreeFunc->use_end());
146
147     while (!Users.empty()) {
148       if (Instruction *I = dyn_cast<Instruction>(Users.back())) {
149         CallSite CS = CallSite::get(I);
150         if (CS.getInstruction() && CS.getCalledFunction() == FreeFunc &&
151             CS.arg_begin() != CS.arg_end()) {
152           
153           // If no prototype was provided for free, we may need to cast the
154           // source pointer.  This should be really uncommon, but it's necessary
155           // just in case we are dealing with wierd code like this:
156           //   free((long)ptr);
157           //
158           Value *Source = *CS.arg_begin();
159           if (!isa<PointerType>(Source->getType()))
160             Source = new CastInst(Source, PointerType::get(Type::SByteTy),
161                                   "FreePtrCast", I);
162           new FreeInst(Source, I);
163           I->getParent()->getInstList().erase(I);
164           Changed = true;
165           ++NumRaised;
166         }
167       }
168       
169       Users.pop_back();
170     }
171   }
172
173   return Changed;
174 }