LLVM API Documentation

Main Page | Namespace List | Class Hierarchy | Alphabetical List | Class List | Directories | File List | Namespace Members | Class Members | File Members | Related Pages

LowerAllocations.cpp

Go to the documentation of this file.
00001 //===- LowerAllocations.cpp - Reduce malloc & free insts to calls ---------===//
00002 // 
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file was developed by the LLVM research group and is distributed under
00006 // the University of Illinois Open Source License. See LICENSE.TXT for details.
00007 // 
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // The LowerAllocations transformation is a target-dependent tranformation
00011 // because it depends on the size of data types and alignment constraints.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/Transforms/Scalar.h"
00016 #include "llvm/Module.h"
00017 #include "llvm/DerivedTypes.h"
00018 #include "llvm/Instructions.h"
00019 #include "llvm/Constants.h"
00020 #include "llvm/Pass.h"
00021 #include "llvm/ADT/Statistic.h"
00022 using namespace llvm;
00023 
00024 namespace {
00025   Statistic<> NumLowered("lowerallocs", "Number of allocations lowered");
00026 
00027   /// LowerAllocations - Turn malloc and free instructions into %malloc and
00028   /// %free calls.
00029   ///
00030   class LowerAllocations : public BasicBlockPass {
00031     Function *MallocFunc;   // Functions in the module we are processing
00032     Function *FreeFunc;     // Initialized by doInitialization
00033   public:
00034     LowerAllocations() : MallocFunc(0), FreeFunc(0) {}
00035 
00036     /// doPassInitialization - For the lower allocations pass, this ensures that
00037     /// a module contains a declaration for a malloc and a free function.
00038     ///
00039     bool doInitialization(Module &M);
00040     
00041     /// runOnBasicBlock - This method does the actual work of converting
00042     /// instructions over, assuming that the pass has already been initialized.
00043     ///
00044     bool runOnBasicBlock(BasicBlock &BB);
00045   };
00046 
00047   RegisterOpt<LowerAllocations>
00048   X("lowerallocs", "Lower allocations from instructions to calls");
00049 }
00050 
00051 // createLowerAllocationsPass - Interface to this file...
00052 FunctionPass *llvm::createLowerAllocationsPass() {
00053   return new LowerAllocations();
00054 }
00055 
00056 
00057 // doInitialization - For the lower allocations pass, this ensures that a
00058 // module contains a declaration for a malloc and a free function.
00059 //
00060 // This function is always successful.
00061 //
00062 bool LowerAllocations::doInitialization(Module &M) {
00063   const Type *SBPTy = PointerType::get(Type::SByteTy);
00064   MallocFunc = M.getNamedFunction("malloc");
00065   FreeFunc   = M.getNamedFunction("free");
00066 
00067   if (MallocFunc == 0)
00068     MallocFunc = M.getOrInsertFunction("malloc", SBPTy, Type::UIntTy, 0);
00069   if (FreeFunc == 0)
00070     FreeFunc   = M.getOrInsertFunction("free"  , Type::VoidTy, SBPTy, 0);
00071 
00072   return true;
00073 }
00074 
00075 static Constant *getSizeof(const Type *Ty) {
00076   Constant *Ret = ConstantPointerNull::get(PointerType::get(Ty));
00077   std::vector<Constant*> Idx;
00078   Idx.push_back(ConstantUInt::get(Type::UIntTy, 1));
00079   Ret = ConstantExpr::getGetElementPtr(Ret, Idx);
00080   return ConstantExpr::getCast(Ret, Type::UIntTy);
00081 }
00082 
00083 // runOnBasicBlock - This method does the actual work of converting
00084 // instructions over, assuming that the pass has already been initialized.
00085 //
00086 bool LowerAllocations::runOnBasicBlock(BasicBlock &BB) {
00087   bool Changed = false;
00088   assert(MallocFunc && FreeFunc && "Pass not initialized!");
00089 
00090   BasicBlock::InstListType &BBIL = BB.getInstList();
00091 
00092   // Loop over all of the instructions, looking for malloc or free instructions
00093   for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I) {
00094     if (MallocInst *MI = dyn_cast<MallocInst>(I)) {
00095       const Type *AllocTy = MI->getType()->getElementType();
00096       
00097       // malloc(type) becomes sbyte *malloc(size)
00098       Value *MallocArg = getSizeof(AllocTy);
00099       if (MI->isArrayAllocation()) {
00100         if (isa<ConstantUInt>(MallocArg) &&
00101             cast<ConstantUInt>(MallocArg)->getValue() == 1) {
00102           MallocArg = MI->getOperand(0);         // Operand * 1 = Operand
00103         } else if (Constant *CO = dyn_cast<Constant>(MI->getOperand(0))) {
00104           MallocArg = ConstantExpr::getMul(CO, cast<Constant>(MallocArg));
00105         } else {
00106           // Multiply it by the array size if necessary...
00107           MallocArg = BinaryOperator::create(Instruction::Mul,
00108                                              MI->getOperand(0),
00109                                              MallocArg, "", I);
00110         }
00111       }
00112 
00113       const FunctionType *MallocFTy = MallocFunc->getFunctionType();
00114       std::vector<Value*> MallocArgs;
00115       
00116       if (MallocFTy->getNumParams() > 0 || MallocFTy->isVarArg()) {
00117         if (MallocFTy->getNumParams() > 0 &&
00118             MallocFTy->getParamType(0) != Type::UIntTy)
00119           MallocArg = new CastInst(MallocArg, MallocFTy->getParamType(0), "",I);
00120         MallocArgs.push_back(MallocArg);
00121       }
00122 
00123       // If malloc is prototyped to take extra arguments, pass nulls.
00124       for (unsigned i = 1; i < MallocFTy->getNumParams(); ++i)
00125        MallocArgs.push_back(Constant::getNullValue(MallocFTy->getParamType(i)));
00126 
00127       // Create the call to Malloc...
00128       CallInst *MCall = new CallInst(MallocFunc, MallocArgs, "", I);
00129       
00130       // Create a cast instruction to convert to the right type...
00131       Value *MCast;
00132       if (MCall->getType() != Type::VoidTy)
00133         MCast = new CastInst(MCall, MI->getType(), "", I);
00134       else
00135         MCast = Constant::getNullValue(MI->getType());
00136       
00137       // Replace all uses of the old malloc inst with the cast inst
00138       MI->replaceAllUsesWith(MCast);
00139       I = --BBIL.erase(I);         // remove and delete the malloc instr...
00140       Changed = true;
00141       ++NumLowered;
00142     } else if (FreeInst *FI = dyn_cast<FreeInst>(I)) {
00143       const FunctionType *FreeFTy = FreeFunc->getFunctionType();
00144       std::vector<Value*> FreeArgs;
00145       
00146       if (FreeFTy->getNumParams() > 0 || FreeFTy->isVarArg()) {
00147         Value *MCast = FI->getOperand(0);
00148         if (FreeFTy->getNumParams() > 0 &&
00149             FreeFTy->getParamType(0) != MCast->getType())
00150           MCast = new CastInst(MCast, FreeFTy->getParamType(0), "", I);
00151         FreeArgs.push_back(MCast);
00152       }
00153 
00154       // If malloc is prototyped to take extra arguments, pass nulls.
00155       for (unsigned i = 1; i < FreeFTy->getNumParams(); ++i)
00156        FreeArgs.push_back(Constant::getNullValue(FreeFTy->getParamType(i)));
00157       
00158       // Insert a call to the free function...
00159       new CallInst(FreeFunc, FreeArgs, "", I);
00160       
00161       // Delete the old free instruction
00162       I = --BBIL.erase(I);
00163       Changed = true;
00164       ++NumLowered;
00165     }
00166   }
00167 
00168   return Changed;
00169 }
00170