mallocs_nonnull.cpp 6.31 KB
Newer Older
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1
// Copyright (c) 2014 Dropbox, Inc.
Kevin Modzelewski's avatar
Kevin Modzelewski committed
2
//
Kevin Modzelewski's avatar
Kevin Modzelewski committed
3 4 5
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
Kevin Modzelewski's avatar
Kevin Modzelewski committed
6
//
Kevin Modzelewski's avatar
Kevin Modzelewski committed
7
//    http://www.apache.org/licenses/LICENSE-2.0
Kevin Modzelewski's avatar
Kevin Modzelewski committed
8
//
Kevin Modzelewski's avatar
Kevin Modzelewski committed
9 10 11 12 13 14 15 16 17 18 19 20 21
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <map>
#include <queue>
#include <set>

#include "llvm/ADT/Statistic.h"
#include "llvm/Pass.h"
#include "llvm/Analysis/MemoryBuiltins.h"
22 23 24
#include "llvm/Analysis/Passes.h"
#include "llvm/Analysis/PostDominators.h"
#include "llvm/IR/InstIterator.h"
Kevin Modzelewski's avatar
Kevin Modzelewski committed
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"

#include "core/common.h"
#include "core/options.h"

using namespace llvm;

namespace pyston {

// TODO Copy-paste
static bool isMallocCall(const CallInst *CI) {
    if (!CI)
        return false;

    Function *Callee = CI->getCalledFunction();
    if (Callee == 0 || !Callee->isDeclaration())
        return false;
    if (Callee->getName() != "malloc" /*&&
            Callee->getName() != "my_malloc" &&
            Callee->getName() != "_Znwj" && // operator new(unsigned int)
            Callee->getName() != "_Znwm" && // operator new(unsigned long)
            Callee->getName() != "_Znaj" && // operator new[](unsigned int)
            Callee->getName() != "_Znam"*/)   // operator new[](unsigned long)
            return false;

    // Check malloc prototype.
    // FIXME: workaround for PR5130, this will be obsolete when a nobuiltin 
    // attribute will exist.
    FunctionType *FTy = Callee->getFunctionType();
    return FTy->getReturnType() == Type::getInt8PtrTy(FTy->getContext()) &&
        FTy->getNumParams() == 1 &&
        (FTy->getParamType(0)->isIntegerTy(32) ||
         FTy->getParamType(0)->isIntegerTy(64));
}

/// isFreeCall - Returns non-null if the value is a call to the builtin free()
static const CallInst *isFreeCall(const Value *I) {
    const CallInst *CI = dyn_cast<CallInst>(I);
    if (!CI)
        return 0;
    Function *Callee = CI->getCalledFunction();
    if (Callee == 0 || !Callee->isDeclaration())
        return 0;

    if (Callee->getName() != "free" /*&&
            Callee->getName() != "my_free" &&
            Callee->getName() != "_ZdlPv" && // operator delete(void*)
            Callee->getName() != "_ZdaPv"*/)   // operator delete[](void*)
            return 0;

    // Check free prototype.
    // FIXME: workaround for PR5130, this will be obsolete when a nobuiltin 
    // attribute will exist.
    FunctionType *FTy = Callee->getFunctionType();
    if (!FTy->getReturnType()->isVoidTy())
        return 0;
    if (FTy->getNumParams() != 1)
        return 0;
    if (FTy->getParamType(0) != Type::getInt8PtrTy(Callee->getContext()))
        return 0;

    return CI;
}

class ComparisonFinder : public InstVisitor<ComparisonFinder, bool> {
private:
    bool any_changes;
    std::deque<Instruction*> to_process;
    Instruction* processing;

public:
    ComparisonFinder(CallInst* malloc) : any_changes(false) {
        to_process.push_back(malloc);
    }

    bool elide_comparisons() {
        while (to_process.size()) {
            processing = to_process.front();
            to_process.pop_front();

            //errs() << "processing: " << *processing << '\n';
            bool changed = false;
            do {
                changed = false;
                for (Value::use_iterator use_it = processing->use_begin(), use_end = processing->use_end(); use_it != use_end; ++use_it) {
                    //errs() << "looking at: " << **use_it << '\n';
                    changed = visit(cast<Instruction>(*use_it));
                    if (changed)
                        break;
                }
            } while (changed);
        }
        return any_changes;
    }

    bool visitBitCastInst(BitCastInst &inst) {
        to_process.push_back(&inst);
        return false;
    }

    bool visitICmpInst(ICmpInst &inst) {
        //errs() << "got icmp instruction!  " << inst << '\n';

        bool changed = false;
        if (inst.getPredicate() == CmpInst::ICMP_EQ) {
            assert(inst.getNumOperands() == 2);

            if (inst.getOperand(1) == processing) {
                inst.swapOperands();
                changed = true;
                any_changes = true;
            }
            assert(dyn_cast<Instruction>(inst.getOperand(0)) == processing);
            Value* other = inst.getOperand(1);
            if (isa<ConstantPointerNull>(other)) {
                if (VERBOSITY("opt") >= 2) {
                    errs() << inst << '\n';
                    errs() << "replacing with false!\n";
                }

                Value* new_value = ConstantInt::getFalse(other->getContext());
                inst.replaceAllUsesWith(new_value);
                inst.eraseFromParent();
                changed = true;
                any_changes = true;
            }
        }
        return changed;
    }

    bool visitInstruction(Instruction &inst) {
        //errs() << "got misc instruction: " << inst << '\n';
        return false;
    }
};

class MallocsNonNullPass : public FunctionPass {
    public:
        static char ID;
        MallocsNonNullPass() : FunctionPass(ID) {}

        virtual void getAnalysisUsage(AnalysisUsage &info) const {
            info.setPreservesCFG();
        }

        virtual bool runOnFunction(Function &F) {
            int num_changed = 0;
            for (inst_iterator inst_it = inst_begin(F), _inst_end = inst_end(F); inst_it != _inst_end; ++inst_it) {
                if (!isMallocCall(dyn_cast<CallInst>(&*inst_it)))
                    continue;

                if (VERBOSITY("opt") >= 2) {
                    errs() << "\nFound malloc call:\n" << *inst_it << '\n';
                }
                num_changed += ComparisonFinder(cast<CallInst>(&*inst_it)).elide_comparisons();
            }

            return num_changed > 0;
        }
};
char MallocsNonNullPass::ID = 0;

FunctionPass* createMallocsNonNullPass() {
    return new MallocsNonNullPass();
}

}

static RegisterPass<pyston::MallocsNonNullPass> X("mallocs_nonnull", "Use the fact that malloc() doesnt return NULL", true, false);