LLVM API Documentation

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 is distributed under the University of Illinois Open Source
00006 // 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 #define DEBUG_TYPE "lowerallocs"
00016 #include "llvm/Transforms/Scalar.h"
00017 #include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
00018 #include "llvm/Module.h"
00019 #include "llvm/DerivedTypes.h"
00020 #include "llvm/Instructions.h"
00021 #include "llvm/Constants.h"
00022 #include "llvm/LLVMContext.h"
00023 #include "llvm/Pass.h"
00024 #include "llvm/ADT/Statistic.h"
00025 #include "llvm/Target/TargetData.h"
00026 #include "llvm/Support/Compiler.h"
00027 using namespace llvm;
00028 
00029 STATISTIC(NumLowered, "Number of allocations lowered");
00030 
00031 namespace {
00032   /// LowerAllocations - Turn malloc and free instructions into @malloc and
00033   /// @free calls.
00034   ///
00035   class VISIBILITY_HIDDEN LowerAllocations : public BasicBlockPass {
00036     Constant *MallocFunc;   // Functions in the module we are processing
00037     Constant *FreeFunc;     // Initialized by doInitialization
00038     bool LowerMallocArgToInteger;
00039   public:
00040     static char ID; // Pass ID, replacement for typeid
00041     explicit LowerAllocations(bool LowerToInt = false)
00042       : BasicBlockPass(&ID), MallocFunc(0), FreeFunc(0), 
00043         LowerMallocArgToInteger(LowerToInt) {}
00044 
00045     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
00046       AU.addRequired<TargetData>();
00047       AU.setPreservesCFG();
00048 
00049       // This is a cluster of orthogonal Transforms:
00050       AU.addPreserved<UnifyFunctionExitNodes>();
00051       AU.addPreservedID(PromoteMemoryToRegisterID);
00052       AU.addPreservedID(LowerSwitchID);
00053       AU.addPreservedID(LowerInvokePassID);
00054     }
00055 
00056     /// doPassInitialization - For the lower allocations pass, this ensures that
00057     /// a module contains a declaration for a malloc and a free function.
00058     ///
00059     bool doInitialization(Module &M);
00060 
00061     virtual bool doInitialization(Function &F) {
00062       return doInitialization(*F.getParent());
00063     }
00064 
00065     /// runOnBasicBlock - This method does the actual work of converting
00066     /// instructions over, assuming that the pass has already been initialized.
00067     ///
00068     bool runOnBasicBlock(BasicBlock &BB);
00069   };
00070 }
00071 
00072 char LowerAllocations::ID = 0;
00073 static RegisterPass<LowerAllocations>
00074 X("lowerallocs", "Lower allocations from instructions to calls");
00075 
00076 // Publically exposed interface to pass...
00077 const PassInfo *const llvm::LowerAllocationsID = &X;
00078 // createLowerAllocationsPass - Interface to this file...
00079 Pass *llvm::createLowerAllocationsPass(bool LowerMallocArgToInteger) {
00080   return new LowerAllocations(LowerMallocArgToInteger);
00081 }
00082 
00083 
00084 // doInitialization - For the lower allocations pass, this ensures that a
00085 // module contains a declaration for a malloc and a free function.
00086 //
00087 // This function is always successful.
00088 //
00089 bool LowerAllocations::doInitialization(Module &M) {
00090   const Type *BPTy = PointerType::getUnqual(Type::getInt8Ty(M.getContext()));
00091   // Prototype malloc as "char* malloc(...)", because we don't know in
00092   // doInitialization whether size_t is int or long.
00093   FunctionType *FT = FunctionType::get(BPTy, true);
00094   MallocFunc = M.getOrInsertFunction("malloc", FT);
00095   FreeFunc = M.getOrInsertFunction("free"  , Type::getVoidTy(M.getContext()),
00096                                    BPTy, (Type *)0);
00097   return true;
00098 }
00099 
00100 // runOnBasicBlock - This method does the actual work of converting
00101 // instructions over, assuming that the pass has already been initialized.
00102 //
00103 bool LowerAllocations::runOnBasicBlock(BasicBlock &BB) {
00104   bool Changed = false;
00105   assert(MallocFunc && FreeFunc && "Pass not initialized!");
00106 
00107   BasicBlock::InstListType &BBIL = BB.getInstList();
00108 
00109   const TargetData &TD = getAnalysis<TargetData>();
00110   const Type *IntPtrTy = TD.getIntPtrType(BB.getContext());
00111 
00112   // Loop over all of the instructions, looking for malloc or free instructions
00113   for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I) {
00114     if (MallocInst *MI = dyn_cast<MallocInst>(I)) {
00115       const Type *AllocTy = MI->getType()->getElementType();
00116 
00117       // malloc(type) becomes i8 *malloc(size)
00118       Value *MallocArg;
00119       if (LowerMallocArgToInteger)
00120         MallocArg = ConstantInt::get(Type::getInt64Ty(BB.getContext()),
00121                                      TD.getTypeAllocSize(AllocTy));
00122       else
00123         MallocArg = ConstantExpr::getSizeOf(AllocTy);
00124       MallocArg =
00125            ConstantExpr::getTruncOrBitCast(cast<Constant>(MallocArg), 
00126                                                   IntPtrTy);
00127 
00128       if (MI->isArrayAllocation()) {
00129         if (isa<ConstantInt>(MallocArg) &&
00130             cast<ConstantInt>(MallocArg)->isOne()) {
00131           MallocArg = MI->getOperand(0);         // Operand * 1 = Operand
00132         } else if (Constant *CO = dyn_cast<Constant>(MI->getOperand(0))) {
00133           CO =
00134               ConstantExpr::getIntegerCast(CO, IntPtrTy, false /*ZExt*/);
00135           MallocArg = ConstantExpr::getMul(CO, 
00136                                                   cast<Constant>(MallocArg));
00137         } else {
00138           Value *Scale = MI->getOperand(0);
00139           if (Scale->getType() != IntPtrTy)
00140             Scale = CastInst::CreateIntegerCast(Scale, IntPtrTy, false /*ZExt*/,
00141                                                 "", I);
00142 
00143           // Multiply it by the array size if necessary...
00144           MallocArg = BinaryOperator::Create(Instruction::Mul, Scale,
00145                                              MallocArg, "", I);
00146         }
00147       }
00148 
00149       // Create the call to Malloc.
00150       CallInst *MCall = CallInst::Create(MallocFunc, MallocArg, "", I);
00151       MCall->setTailCall();
00152 
00153       // Create a cast instruction to convert to the right type...
00154       Value *MCast;
00155       if (MCall->getType() != Type::getVoidTy(BB.getContext()))
00156         MCast = new BitCastInst(MCall, MI->getType(), "", I);
00157       else
00158         MCast = Constant::getNullValue(MI->getType());
00159 
00160       // Replace all uses of the old malloc inst with the cast inst
00161       MI->replaceAllUsesWith(MCast);
00162       I = --BBIL.erase(I);         // remove and delete the malloc instr...
00163       Changed = true;
00164       ++NumLowered;
00165     } else if (FreeInst *FI = dyn_cast<FreeInst>(I)) {
00166       Value *PtrCast = 
00167         new BitCastInst(FI->getOperand(0),
00168                PointerType::getUnqual(Type::getInt8Ty(BB.getContext())), "", I);
00169 
00170       // Insert a call to the free function...
00171       CallInst::Create(FreeFunc, PtrCast, "", I)->setTailCall();
00172 
00173       // Delete the old free instruction
00174       I = --BBIL.erase(I);
00175       Changed = true;
00176       ++NumLowered;
00177     }
00178   }
00179 
00180   return Changed;
00181 }
00182