LLVM API Documentation

RaiseAllocations.cpp

Go to the documentation of this file.
00001 //===- RaiseAllocations.cpp - Convert @malloc & @free calls to insts ------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file defines the RaiseAllocations pass which convert malloc and free
00011 // calls to malloc and free instructions.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #define DEBUG_TYPE "raiseallocs"
00016 #include "llvm/Transforms/IPO.h"
00017 #include "llvm/Constants.h"
00018 #include "llvm/DerivedTypes.h"
00019 #include "llvm/Module.h"
00020 #include "llvm/Instructions.h"
00021 #include "llvm/Pass.h"
00022 #include "llvm/Support/CallSite.h"
00023 #include "llvm/Support/Compiler.h"
00024 #include "llvm/ADT/Statistic.h"
00025 #include <algorithm>
00026 using namespace llvm;
00027 
00028 STATISTIC(NumRaised, "Number of allocations raised");
00029 
00030 namespace {
00031   // RaiseAllocations - Turn @malloc and @free calls into the appropriate
00032   // instruction.
00033   //
00034   class VISIBILITY_HIDDEN RaiseAllocations : public ModulePass {
00035     Function *MallocFunc;   // Functions in the module we are processing
00036     Function *FreeFunc;     // Initialized by doPassInitializationVirt
00037   public:
00038     static char ID; // Pass identification, replacement for typeid
00039     RaiseAllocations() 
00040       : ModulePass(&ID), MallocFunc(0), FreeFunc(0) {}
00041 
00042     // doPassInitialization - For the raise allocations pass, this finds a
00043     // declaration for malloc and free if they exist.
00044     //
00045     void doInitialization(Module &M);
00046 
00047     // run - This method does the actual work of converting instructions over.
00048     //
00049     bool runOnModule(Module &M);
00050   };
00051 }  // end anonymous namespace
00052 
00053 char RaiseAllocations::ID = 0;
00054 static RegisterPass<RaiseAllocations>
00055 X("raiseallocs", "Raise allocations from calls to instructions");
00056 
00057 // createRaiseAllocationsPass - The interface to this file...
00058 ModulePass *llvm::createRaiseAllocationsPass() {
00059   return new RaiseAllocations();
00060 }
00061 
00062 
00063 // If the module has a symbol table, they might be referring to the malloc and
00064 // free functions.  If this is the case, grab the method pointers that the
00065 // module is using.
00066 //
00067 // Lookup @malloc and @free in the symbol table, for later use.  If they don't
00068 // exist, or are not external, we do not worry about converting calls to that
00069 // function into the appropriate instruction.
00070 //
00071 void RaiseAllocations::doInitialization(Module &M) {
00072 
00073   // Get Malloc and free prototypes if they exist!
00074   MallocFunc = M.getFunction("malloc");
00075   if (MallocFunc) {
00076     const FunctionType* TyWeHave = MallocFunc->getFunctionType();
00077 
00078     // Get the expected prototype for malloc
00079     const FunctionType *Malloc1Type = 
00080       FunctionType::get(PointerType::getUnqual(Type::Int8Ty),
00081                       std::vector<const Type*>(1, Type::Int64Ty), false);
00082 
00083     // Chck to see if we got the expected malloc
00084     if (TyWeHave != Malloc1Type) {
00085       // Check to see if the prototype is wrong, giving us sbyte*(uint) * malloc
00086       // This handles the common declaration of: 'void *malloc(unsigned);'
00087       const FunctionType *Malloc2Type = 
00088         FunctionType::get(PointerType::getUnqual(Type::Int8Ty),
00089                           std::vector<const Type*>(1, Type::Int32Ty), false);
00090       if (TyWeHave != Malloc2Type) {
00091         // Check to see if the prototype is missing, giving us 
00092         // sbyte*(...) * malloc
00093         // This handles the common declaration of: 'void *malloc();'
00094         const FunctionType *Malloc3Type = 
00095           FunctionType::get(PointerType::getUnqual(Type::Int8Ty),
00096                             std::vector<const Type*>(), true);
00097         if (TyWeHave != Malloc3Type)
00098           // Give up
00099           MallocFunc = 0;
00100       }
00101     }
00102   }
00103 
00104   FreeFunc = M.getFunction("free");
00105   if (FreeFunc) {
00106     const FunctionType* TyWeHave = FreeFunc->getFunctionType();
00107     
00108     // Get the expected prototype for void free(i8*)
00109     const FunctionType *Free1Type = FunctionType::get(Type::VoidTy,
00110       std::vector<const Type*>(1, PointerType::getUnqual(Type::Int8Ty)), false);
00111 
00112     if (TyWeHave != Free1Type) {
00113       // Check to see if the prototype was forgotten, giving us 
00114       // void (...) * free
00115       // This handles the common forward declaration of: 'void free();'
00116       const FunctionType* Free2Type = FunctionType::get(Type::VoidTy, 
00117         std::vector<const Type*>(),true);
00118 
00119       if (TyWeHave != Free2Type) {
00120         // One last try, check to see if we can find free as 
00121         // int (...)* free.  This handles the case where NOTHING was declared.
00122         const FunctionType* Free3Type = FunctionType::get(Type::Int32Ty, 
00123           std::vector<const Type*>(),true);
00124         
00125         if (TyWeHave != Free3Type) {
00126           // Give up.
00127           FreeFunc = 0;
00128         }
00129       }
00130     }
00131   }
00132 
00133   // Don't mess with locally defined versions of these functions...
00134   if (MallocFunc && !MallocFunc->isDeclaration()) MallocFunc = 0;
00135   if (FreeFunc && !FreeFunc->isDeclaration())     FreeFunc = 0;
00136 }
00137 
00138 // run - Transform calls into instructions...
00139 //
00140 bool RaiseAllocations::runOnModule(Module &M) {
00141   // Find the malloc/free prototypes...
00142   doInitialization(M);
00143 
00144   bool Changed = false;
00145 
00146   // First, process all of the malloc calls...
00147   if (MallocFunc) {
00148     std::vector<User*> Users(MallocFunc->use_begin(), MallocFunc->use_end());
00149     std::vector<Value*> EqPointers;   // Values equal to MallocFunc
00150     while (!Users.empty()) {
00151       User *U = Users.back();
00152       Users.pop_back();
00153 
00154       if (Instruction *I = dyn_cast<Instruction>(U)) {
00155         CallSite CS = CallSite::get(I);
00156         if (CS.getInstruction() && !CS.arg_empty() &&
00157             (CS.getCalledFunction() == MallocFunc ||
00158              std::find(EqPointers.begin(), EqPointers.end(),
00159                        CS.getCalledValue()) != EqPointers.end())) {
00160 
00161           Value *Source = *CS.arg_begin();
00162 
00163           // If no prototype was provided for malloc, we may need to cast the
00164           // source size.
00165           if (Source->getType() != Type::Int32Ty)
00166             Source = 
00167               CastInst::CreateIntegerCast(Source, Type::Int32Ty, false/*ZExt*/,
00168                                           "MallocAmtCast", I);
00169 
00170           MallocInst *MI = new MallocInst(Type::Int8Ty, Source, "", I);
00171           MI->takeName(I);
00172           I->replaceAllUsesWith(MI);
00173 
00174           // If the old instruction was an invoke, add an unconditional branch
00175           // before the invoke, which will become the new terminator.
00176           if (InvokeInst *II = dyn_cast<InvokeInst>(I))
00177             BranchInst::Create(II->getNormalDest(), I);
00178 
00179           // Delete the old call site
00180           I->eraseFromParent();
00181           Changed = true;
00182           ++NumRaised;
00183         }
00184       } else if (GlobalValue *GV = dyn_cast<GlobalValue>(U)) {
00185         Users.insert(Users.end(), GV->use_begin(), GV->use_end());
00186         EqPointers.push_back(GV);
00187       } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
00188         if (CE->isCast()) {
00189           Users.insert(Users.end(), CE->use_begin(), CE->use_end());
00190           EqPointers.push_back(CE);
00191         }
00192       }
00193     }
00194   }
00195 
00196   // Next, process all free calls...
00197   if (FreeFunc) {
00198     std::vector<User*> Users(FreeFunc->use_begin(), FreeFunc->use_end());
00199     std::vector<Value*> EqPointers;   // Values equal to FreeFunc
00200 
00201     while (!Users.empty()) {
00202       User *U = Users.back();
00203       Users.pop_back();
00204 
00205       if (Instruction *I = dyn_cast<Instruction>(U)) {
00206         if (isa<InvokeInst>(I))
00207           continue;
00208         CallSite CS = CallSite::get(I);
00209         if (CS.getInstruction() && !CS.arg_empty() &&
00210             (CS.getCalledFunction() == FreeFunc ||
00211              std::find(EqPointers.begin(), EqPointers.end(),
00212                        CS.getCalledValue()) != EqPointers.end())) {
00213 
00214           // If no prototype was provided for free, we may need to cast the
00215           // source pointer.  This should be really uncommon, but it's necessary
00216           // just in case we are dealing with weird code like this:
00217           //   free((long)ptr);
00218           //
00219           Value *Source = *CS.arg_begin();
00220           if (!isa<PointerType>(Source->getType()))
00221             Source = new IntToPtrInst(Source,           
00222                                       PointerType::getUnqual(Type::Int8Ty), 
00223                                       "FreePtrCast", I);
00224           new FreeInst(Source, I);
00225 
00226           // If the old instruction was an invoke, add an unconditional branch
00227           // before the invoke, which will become the new terminator.
00228           if (InvokeInst *II = dyn_cast<InvokeInst>(I))
00229             BranchInst::Create(II->getNormalDest(), I);
00230 
00231           // Delete the old call site
00232           if (I->getType() != Type::VoidTy)
00233             I->replaceAllUsesWith(UndefValue::get(I->getType()));
00234           I->eraseFromParent();
00235           Changed = true;
00236           ++NumRaised;
00237         }
00238       } else if (GlobalValue *GV = dyn_cast<GlobalValue>(U)) {
00239         Users.insert(Users.end(), GV->use_begin(), GV->use_end());
00240         EqPointers.push_back(GV);
00241       } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
00242         if (CE->isCast()) {
00243           Users.insert(Users.end(), CE->use_begin(), CE->use_end());
00244           EqPointers.push_back(CE);
00245         }
00246       }
00247     }
00248   }
00249 
00250   return Changed;
00251 }