2017-09-01 12:56:34 +02:00
|
|
|
//===- MergeICmps.cpp - Optimize chains of integer comparisons ------------===//
|
|
|
|
//
|
2019-01-19 09:50:56 +01:00
|
|
|
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
|
|
|
|
// See https://llvm.org/LICENSE.txt for license information.
|
|
|
|
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
|
2017-09-01 12:56:34 +02:00
|
|
|
//
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
//
|
|
|
|
// This pass turns chains of integer comparisons into memcmp (the memcmp is
|
|
|
|
// later typically inlined as a chain of efficient hardware comparisons). This
|
|
|
|
// typically benefits c++ member or nonmember operator==().
|
|
|
|
//
|
2019-02-15 13:58:06 +01:00
|
|
|
// The basic idea is to replace a longer chain of integer comparisons loaded
|
|
|
|
// from contiguous memory locations into a shorter chain of larger integer
|
2017-09-01 12:56:34 +02:00
|
|
|
// comparisons. Benefits are double:
|
|
|
|
// - There are less jumps, and therefore less opportunities for mispredictions
|
|
|
|
// and I-cache misses.
|
|
|
|
// - Code size is smaller, both because jumps are removed and because the
|
|
|
|
// encoding of a 2*n byte compare is smaller than that of two n-byte
|
|
|
|
// compares.
|
2019-02-15 13:58:06 +01:00
|
|
|
//
|
|
|
|
// Example:
|
|
|
|
//
|
|
|
|
// struct S {
|
|
|
|
// int a;
|
|
|
|
// char b;
|
|
|
|
// char c;
|
|
|
|
// uint16_t d;
|
|
|
|
// bool operator==(const S& o) const {
|
|
|
|
// return a == o.a && b == o.b && c == o.c && d == o.d;
|
|
|
|
// }
|
|
|
|
// };
|
|
|
|
//
|
|
|
|
// Is optimized as :
|
|
|
|
//
|
|
|
|
// bool S::operator==(const S& o) const {
|
|
|
|
// return memcmp(this, &o, 8) == 0;
|
|
|
|
// }
|
|
|
|
//
|
|
|
|
// Which will later be expanded (ExpandMemCmp) as a single 8-bytes icmp.
|
|
|
|
//
|
2017-09-01 12:56:34 +02:00
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
2019-05-23 14:35:26 +02:00
|
|
|
#include "llvm/Transforms/Scalar/MergeICmps.h"
|
2019-05-21 13:02:23 +02:00
|
|
|
#include "llvm/Analysis/DomTreeUpdater.h"
|
|
|
|
#include "llvm/Analysis/GlobalsModRef.h"
|
2017-09-01 12:56:34 +02:00
|
|
|
#include "llvm/Analysis/Loads.h"
|
2017-10-10 10:00:45 +02:00
|
|
|
#include "llvm/Analysis/TargetLibraryInfo.h"
|
|
|
|
#include "llvm/Analysis/TargetTransformInfo.h"
|
2019-05-21 13:02:23 +02:00
|
|
|
#include "llvm/IR/Dominators.h"
|
2017-09-01 12:56:34 +02:00
|
|
|
#include "llvm/IR/Function.h"
|
|
|
|
#include "llvm/IR/IRBuilder.h"
|
|
|
|
#include "llvm/Pass.h"
|
|
|
|
#include "llvm/Transforms/Scalar.h"
|
2019-05-17 11:43:45 +02:00
|
|
|
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
|
2017-09-01 12:56:34 +02:00
|
|
|
#include "llvm/Transforms/Utils/BuildLibCalls.h"
|
2019-02-15 15:17:17 +01:00
|
|
|
#include <algorithm>
|
|
|
|
#include <numeric>
|
|
|
|
#include <utility>
|
|
|
|
#include <vector>
|
2017-09-01 12:56:34 +02:00
|
|
|
|
|
|
|
using namespace llvm;
|
|
|
|
|
2017-10-26 02:55:39 +02:00
|
|
|
namespace {
|
|
|
|
|
2017-10-26 03:25:14 +02:00
|
|
|
#define DEBUG_TYPE "mergeicmps"
|
|
|
|
|
2018-09-24 22:47:12 +02:00
|
|
|
// Returns true if the instruction is a simple load or a simple store
|
|
|
|
static bool isSimpleLoadOrStore(const Instruction *I) {
|
|
|
|
if (const LoadInst *LI = dyn_cast<LoadInst>(I))
|
|
|
|
return LI->isSimple();
|
|
|
|
if (const StoreInst *SI = dyn_cast<StoreInst>(I))
|
|
|
|
return SI->isSimple();
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2019-02-15 13:58:06 +01:00
|
|
|
// A BCE atom "Binary Compare Expression Atom" represents an integer load
|
|
|
|
// that is a constant offset from a base value, e.g. `a` or `o.c` in the example
|
|
|
|
// at the top.
|
2017-09-01 12:56:34 +02:00
|
|
|
struct BCEAtom {
|
2019-02-15 15:17:17 +01:00
|
|
|
BCEAtom() = default;
|
|
|
|
BCEAtom(GetElementPtrInst *GEP, LoadInst *LoadI, int BaseId, APInt Offset)
|
|
|
|
: GEP(GEP), LoadI(LoadI), BaseId(BaseId), Offset(Offset) {}
|
|
|
|
|
2019-05-22 11:45:40 +02:00
|
|
|
BCEAtom(const BCEAtom &) = delete;
|
|
|
|
BCEAtom &operator=(const BCEAtom &) = delete;
|
|
|
|
|
|
|
|
BCEAtom(BCEAtom &&that) = default;
|
|
|
|
BCEAtom &operator=(BCEAtom &&that) {
|
|
|
|
if (this == &that)
|
|
|
|
return *this;
|
|
|
|
GEP = that.GEP;
|
|
|
|
LoadI = that.LoadI;
|
|
|
|
BaseId = that.BaseId;
|
|
|
|
Offset = std::move(that.Offset);
|
|
|
|
return *this;
|
|
|
|
}
|
|
|
|
|
2019-02-15 15:17:17 +01:00
|
|
|
// We want to order BCEAtoms by (Base, Offset). However we cannot use
|
|
|
|
// the pointer values for Base because these are non-deterministic.
|
|
|
|
// To make sure that the sort order is stable, we first assign to each atom
|
|
|
|
// base value an index based on its order of appearance in the chain of
|
|
|
|
// comparisons. We call this index `BaseOrdering`. For example, for:
|
|
|
|
// b[3] == c[2] && a[1] == d[1] && b[4] == c[3]
|
|
|
|
// | block 1 | | block 2 | | block 3 |
|
|
|
|
// b gets assigned index 0 and a index 1, because b appears as LHS in block 1,
|
|
|
|
// which is before block 2.
|
|
|
|
// We then sort by (BaseOrdering[LHS.Base()], LHS.Offset), which is stable.
|
2017-09-01 12:56:34 +02:00
|
|
|
bool operator<(const BCEAtom &O) const {
|
2019-02-15 15:17:17 +01:00
|
|
|
return BaseId != O.BaseId ? BaseId < O.BaseId : Offset.slt(O.Offset);
|
2017-09-01 12:56:34 +02:00
|
|
|
}
|
|
|
|
|
2019-02-15 15:17:17 +01:00
|
|
|
GetElementPtrInst *GEP = nullptr;
|
|
|
|
LoadInst *LoadI = nullptr;
|
|
|
|
unsigned BaseId = 0;
|
2017-09-01 12:56:34 +02:00
|
|
|
APInt Offset;
|
|
|
|
};
|
|
|
|
|
2019-02-15 15:17:17 +01:00
|
|
|
// A class that assigns increasing ids to values in the order in which they are
|
|
|
|
// seen. See comment in `BCEAtom::operator<()``.
|
|
|
|
class BaseIdentifier {
|
|
|
|
public:
|
|
|
|
// Returns the id for value `Base`, after assigning one if `Base` has not been
|
|
|
|
// seen before.
|
|
|
|
int getBaseId(const Value *Base) {
|
|
|
|
assert(Base && "invalid base");
|
|
|
|
const auto Insertion = BaseToIndex.try_emplace(Base, Order);
|
|
|
|
if (Insertion.second)
|
|
|
|
++Order;
|
|
|
|
return Insertion.first->second;
|
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
|
|
|
unsigned Order = 1;
|
|
|
|
DenseMap<const Value*, int> BaseToIndex;
|
|
|
|
};
|
|
|
|
|
2017-09-01 12:56:34 +02:00
|
|
|
// If this value is a load from a constant offset w.r.t. a base address, and
|
2018-02-28 13:09:53 +01:00
|
|
|
// there are no other users of the load or address, returns the base address and
|
2017-09-01 12:56:34 +02:00
|
|
|
// the offset.
|
2019-02-15 15:17:17 +01:00
|
|
|
BCEAtom visitICmpLoadOperand(Value *const Val, BaseIdentifier &BaseId) {
|
|
|
|
auto *const LoadI = dyn_cast<LoadInst>(Val);
|
|
|
|
if (!LoadI)
|
|
|
|
return {};
|
|
|
|
LLVM_DEBUG(dbgs() << "load\n");
|
|
|
|
if (LoadI->isUsedOutsideOfBlock(LoadI->getParent())) {
|
|
|
|
LLVM_DEBUG(dbgs() << "used outside of block\n");
|
|
|
|
return {};
|
|
|
|
}
|
|
|
|
// Do not optimize atomic loads to non-atomic memcmp
|
|
|
|
if (!LoadI->isSimple()) {
|
|
|
|
LLVM_DEBUG(dbgs() << "volatile or atomic\n");
|
|
|
|
return {};
|
|
|
|
}
|
|
|
|
Value *const Addr = LoadI->getOperand(0);
|
|
|
|
auto *const GEP = dyn_cast<GetElementPtrInst>(Addr);
|
|
|
|
if (!GEP)
|
|
|
|
return {};
|
|
|
|
LLVM_DEBUG(dbgs() << "GEP\n");
|
|
|
|
if (GEP->isUsedOutsideOfBlock(LoadI->getParent())) {
|
|
|
|
LLVM_DEBUG(dbgs() << "used outside of block\n");
|
|
|
|
return {};
|
2017-09-01 12:56:34 +02:00
|
|
|
}
|
2019-02-15 15:17:17 +01:00
|
|
|
const auto &DL = GEP->getModule()->getDataLayout();
|
2019-07-09 13:35:35 +02:00
|
|
|
if (!isDereferenceablePointer(GEP, LoadI->getType(), DL)) {
|
2019-02-15 15:17:17 +01:00
|
|
|
LLVM_DEBUG(dbgs() << "not dereferenceable\n");
|
|
|
|
// We need to make sure that we can do comparison in any order, so we
|
|
|
|
// require memory to be unconditionnally dereferencable.
|
|
|
|
return {};
|
|
|
|
}
|
|
|
|
APInt Offset = APInt(DL.getPointerTypeSizeInBits(GEP->getType()), 0);
|
|
|
|
if (!GEP->accumulateConstantOffset(DL, Offset))
|
|
|
|
return {};
|
|
|
|
return BCEAtom(GEP, LoadI, BaseId.getBaseId(GEP->getPointerOperand()),
|
|
|
|
Offset);
|
2017-09-01 12:56:34 +02:00
|
|
|
}
|
|
|
|
|
2019-02-15 13:58:06 +01:00
|
|
|
// A basic block with a comparison between two BCE atoms, e.g. `a == o.a` in the
|
|
|
|
// example at the top.
|
2018-04-09 15:14:06 +02:00
|
|
|
// The block might do extra work besides the atom comparison, in which case
|
|
|
|
// doesOtherWork() returns true. Under some conditions, the block can be
|
|
|
|
// split into the atom comparison part and the "other work" part
|
|
|
|
// (see canSplit()).
|
2017-09-01 12:56:34 +02:00
|
|
|
// Note: the terminology is misleading: the comparison is symmetric, so there
|
2017-10-10 10:00:45 +02:00
|
|
|
// is no real {l/r}hs. What we want though is to have the same base on the
|
|
|
|
// left (resp. right), so that we can detect consecutive loads. To ensure this
|
|
|
|
// we put the smallest atom on the left.
|
2017-09-01 12:56:34 +02:00
|
|
|
class BCECmpBlock {
|
2017-10-26 03:25:14 +02:00
|
|
|
public:
|
|
|
|
BCECmpBlock() {}
|
2017-09-01 12:56:34 +02:00
|
|
|
|
|
|
|
BCECmpBlock(BCEAtom L, BCEAtom R, int SizeBits)
|
2019-05-22 11:45:40 +02:00
|
|
|
: Lhs_(std::move(L)), Rhs_(std::move(R)), SizeBits_(SizeBits) {
|
2017-10-04 17:13:52 +02:00
|
|
|
if (Rhs_ < Lhs_) std::swap(Rhs_, Lhs_);
|
2017-09-01 12:56:34 +02:00
|
|
|
}
|
|
|
|
|
2019-02-15 15:17:17 +01:00
|
|
|
bool IsValid() const { return Lhs_.BaseId != 0 && Rhs_.BaseId != 0; }
|
2017-09-01 12:56:34 +02:00
|
|
|
|
2018-01-19 11:55:29 +01:00
|
|
|
// Assert the block is consistent: If valid, it should also have
|
2017-09-01 12:56:34 +02:00
|
|
|
// non-null members besides Lhs_ and Rhs_.
|
|
|
|
void AssertConsistent() const {
|
|
|
|
if (IsValid()) {
|
|
|
|
assert(BB);
|
|
|
|
assert(CmpI);
|
|
|
|
assert(BranchI);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const BCEAtom &Lhs() const { return Lhs_; }
|
|
|
|
const BCEAtom &Rhs() const { return Rhs_; }
|
|
|
|
int SizeBits() const { return SizeBits_; }
|
|
|
|
|
|
|
|
// Returns true if the block does other works besides comparison.
|
|
|
|
bool doesOtherWork() const;
|
|
|
|
|
2018-04-09 15:14:06 +02:00
|
|
|
// Returns true if the non-BCE-cmp instructions can be separated from BCE-cmp
|
|
|
|
// instructions in the block.
|
2019-05-23 14:35:26 +02:00
|
|
|
bool canSplit(AliasAnalysis &AA) const;
|
2018-04-09 15:14:06 +02:00
|
|
|
|
|
|
|
// Return true if this all the relevant instructions in the BCE-cmp-block can
|
|
|
|
// be sunk below this instruction. By doing this, we know we can separate the
|
|
|
|
// BCE-cmp-block instructions from the non-BCE-cmp-block instructions in the
|
|
|
|
// block.
|
2018-09-24 22:47:12 +02:00
|
|
|
bool canSinkBCECmpInst(const Instruction *, DenseSet<Instruction *> &,
|
2019-05-23 14:35:26 +02:00
|
|
|
AliasAnalysis &AA) const;
|
2018-04-09 15:14:06 +02:00
|
|
|
|
|
|
|
// We can separate the BCE-cmp-block instructions and the non-BCE-cmp-block
|
|
|
|
// instructions. Split the old block and move all non-BCE-cmp-insts into the
|
|
|
|
// new parent block.
|
2019-05-23 14:35:26 +02:00
|
|
|
void split(BasicBlock *NewParent, AliasAnalysis &AA) const;
|
2018-04-09 15:14:06 +02:00
|
|
|
|
2017-09-01 12:56:34 +02:00
|
|
|
// The basic block where this comparison happens.
|
|
|
|
BasicBlock *BB = nullptr;
|
|
|
|
// The ICMP for this comparison.
|
|
|
|
ICmpInst *CmpI = nullptr;
|
|
|
|
// The terminating branch.
|
|
|
|
BranchInst *BranchI = nullptr;
|
2018-04-09 15:14:06 +02:00
|
|
|
// The block requires splitting.
|
|
|
|
bool RequireSplit = false;
|
2017-09-01 12:56:34 +02:00
|
|
|
|
2018-04-09 15:14:06 +02:00
|
|
|
private:
|
2017-09-01 12:56:34 +02:00
|
|
|
BCEAtom Lhs_;
|
|
|
|
BCEAtom Rhs_;
|
|
|
|
int SizeBits_ = 0;
|
|
|
|
};
|
|
|
|
|
2018-04-09 15:14:06 +02:00
|
|
|
bool BCECmpBlock::canSinkBCECmpInst(const Instruction *Inst,
|
2018-09-24 22:47:12 +02:00
|
|
|
DenseSet<Instruction *> &BlockInsts,
|
2019-05-23 14:35:26 +02:00
|
|
|
AliasAnalysis &AA) const {
|
2018-04-09 15:14:06 +02:00
|
|
|
// If this instruction has side effects and its in middle of the BCE cmp block
|
|
|
|
// instructions, then bail for now.
|
2018-09-24 22:47:12 +02:00
|
|
|
if (Inst->mayHaveSideEffects()) {
|
|
|
|
// Bail if this is not a simple load or store
|
|
|
|
if (!isSimpleLoadOrStore(Inst))
|
|
|
|
return false;
|
|
|
|
// Disallow stores that might alias the BCE operands
|
|
|
|
MemoryLocation LLoc = MemoryLocation::get(Lhs_.LoadI);
|
|
|
|
MemoryLocation RLoc = MemoryLocation::get(Rhs_.LoadI);
|
2019-05-23 14:35:26 +02:00
|
|
|
if (isModSet(AA.getModRefInfo(Inst, LLoc)) ||
|
|
|
|
isModSet(AA.getModRefInfo(Inst, RLoc)))
|
|
|
|
return false;
|
2018-09-24 22:47:12 +02:00
|
|
|
}
|
2018-04-09 15:14:06 +02:00
|
|
|
// Make sure this instruction does not use any of the BCE cmp block
|
|
|
|
// instructions as operand.
|
|
|
|
for (auto BI : BlockInsts) {
|
|
|
|
if (is_contained(Inst->operands(), BI))
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2019-05-23 14:35:26 +02:00
|
|
|
void BCECmpBlock::split(BasicBlock *NewParent, AliasAnalysis &AA) const {
|
2018-04-09 15:14:06 +02:00
|
|
|
DenseSet<Instruction *> BlockInsts(
|
|
|
|
{Lhs_.GEP, Rhs_.GEP, Lhs_.LoadI, Rhs_.LoadI, CmpI, BranchI});
|
|
|
|
llvm::SmallVector<Instruction *, 4> OtherInsts;
|
|
|
|
for (Instruction &Inst : *BB) {
|
|
|
|
if (BlockInsts.count(&Inst))
|
|
|
|
continue;
|
2018-09-24 22:47:12 +02:00
|
|
|
assert(canSinkBCECmpInst(&Inst, BlockInsts, AA) &&
|
|
|
|
"Split unsplittable block");
|
2018-04-09 15:14:06 +02:00
|
|
|
// This is a non-BCE-cmp-block instruction. And it can be separated
|
|
|
|
// from the BCE-cmp-block instruction.
|
|
|
|
OtherInsts.push_back(&Inst);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Do the actual spliting.
|
|
|
|
for (Instruction *Inst : reverse(OtherInsts)) {
|
|
|
|
Inst->moveBefore(&*NewParent->begin());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-05-23 14:35:26 +02:00
|
|
|
bool BCECmpBlock::canSplit(AliasAnalysis &AA) const {
|
2018-04-09 15:14:06 +02:00
|
|
|
DenseSet<Instruction *> BlockInsts(
|
|
|
|
{Lhs_.GEP, Rhs_.GEP, Lhs_.LoadI, Rhs_.LoadI, CmpI, BranchI});
|
|
|
|
for (Instruction &Inst : *BB) {
|
|
|
|
if (!BlockInsts.count(&Inst)) {
|
2018-09-24 22:47:12 +02:00
|
|
|
if (!canSinkBCECmpInst(&Inst, BlockInsts, AA))
|
2018-04-09 15:14:06 +02:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2017-09-01 12:56:34 +02:00
|
|
|
bool BCECmpBlock::doesOtherWork() const {
|
|
|
|
AssertConsistent();
|
2018-03-06 03:24:02 +01:00
|
|
|
// All the instructions we care about in the BCE cmp block.
|
|
|
|
DenseSet<Instruction *> BlockInsts(
|
|
|
|
{Lhs_.GEP, Rhs_.GEP, Lhs_.LoadI, Rhs_.LoadI, CmpI, BranchI});
|
2017-09-01 12:56:34 +02:00
|
|
|
// TODO(courbet): Can we allow some other things ? This is very conservative.
|
2018-04-14 10:59:00 +02:00
|
|
|
// We might be able to get away with anything does not have any side
|
2017-09-01 12:56:34 +02:00
|
|
|
// effects outside of the basic block.
|
|
|
|
// Note: The GEPs and/or loads are not necessarily in the same block.
|
|
|
|
for (const Instruction &Inst : *BB) {
|
2018-03-06 03:24:02 +01:00
|
|
|
if (!BlockInsts.count(&Inst))
|
2017-09-01 12:56:34 +02:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Visit the given comparison. If this is a comparison between two valid
|
|
|
|
// BCE atoms, returns the comparison.
|
2017-10-26 03:25:14 +02:00
|
|
|
BCECmpBlock visitICmp(const ICmpInst *const CmpI,
|
2019-02-15 15:17:17 +01:00
|
|
|
const ICmpInst::Predicate ExpectedPredicate,
|
|
|
|
BaseIdentifier &BaseId) {
|
2018-03-13 08:05:55 +01:00
|
|
|
// The comparison can only be used once:
|
|
|
|
// - For intermediate blocks, as a branch condition.
|
|
|
|
// - For the final block, as an incoming value for the Phi.
|
|
|
|
// If there are any other uses of the comparison, we cannot merge it with
|
|
|
|
// other comparisons as we would create an orphan use of the value.
|
|
|
|
if (!CmpI->hasOneUse()) {
|
2018-05-14 14:53:11 +02:00
|
|
|
LLVM_DEBUG(dbgs() << "cmp has several uses\n");
|
2018-03-13 08:05:55 +01:00
|
|
|
return {};
|
|
|
|
}
|
2019-02-15 15:17:17 +01:00
|
|
|
if (CmpI->getPredicate() != ExpectedPredicate)
|
|
|
|
return {};
|
|
|
|
LLVM_DEBUG(dbgs() << "cmp "
|
|
|
|
<< (ExpectedPredicate == ICmpInst::ICMP_EQ ? "eq" : "ne")
|
|
|
|
<< "\n");
|
|
|
|
auto Lhs = visitICmpLoadOperand(CmpI->getOperand(0), BaseId);
|
|
|
|
if (!Lhs.BaseId)
|
|
|
|
return {};
|
|
|
|
auto Rhs = visitICmpLoadOperand(CmpI->getOperand(1), BaseId);
|
|
|
|
if (!Rhs.BaseId)
|
|
|
|
return {};
|
|
|
|
const auto &DL = CmpI->getModule()->getDataLayout();
|
|
|
|
return BCECmpBlock(std::move(Lhs), std::move(Rhs),
|
|
|
|
DL.getTypeSizeInBits(CmpI->getOperand(0)->getType()));
|
2017-09-01 12:56:34 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Visit the given comparison block. If this is a comparison between two valid
|
|
|
|
// BCE atoms, returns the comparison.
|
2017-10-26 03:25:14 +02:00
|
|
|
BCECmpBlock visitCmpBlock(Value *const Val, BasicBlock *const Block,
|
2019-02-15 15:17:17 +01:00
|
|
|
const BasicBlock *const PhiBlock,
|
|
|
|
BaseIdentifier &BaseId) {
|
2017-10-04 17:13:52 +02:00
|
|
|
if (Block->empty()) return {};
|
2017-09-01 12:56:34 +02:00
|
|
|
auto *const BranchI = dyn_cast<BranchInst>(Block->getTerminator());
|
2017-10-04 17:13:52 +02:00
|
|
|
if (!BranchI) return {};
|
2018-05-14 14:53:11 +02:00
|
|
|
LLVM_DEBUG(dbgs() << "branch\n");
|
2017-09-01 12:56:34 +02:00
|
|
|
if (BranchI->isUnconditional()) {
|
|
|
|
// In this case, we expect an incoming value which is the result of the
|
|
|
|
// comparison. This is the last link in the chain of comparisons (note
|
|
|
|
// that this does not mean that this is the last incoming value, blocks
|
|
|
|
// can be reordered).
|
|
|
|
auto *const CmpI = dyn_cast<ICmpInst>(Val);
|
2017-10-04 17:13:52 +02:00
|
|
|
if (!CmpI) return {};
|
2018-05-14 14:53:11 +02:00
|
|
|
LLVM_DEBUG(dbgs() << "icmp\n");
|
2019-02-15 15:17:17 +01:00
|
|
|
auto Result = visitICmp(CmpI, ICmpInst::ICMP_EQ, BaseId);
|
2017-09-01 12:56:34 +02:00
|
|
|
Result.CmpI = CmpI;
|
|
|
|
Result.BranchI = BranchI;
|
|
|
|
return Result;
|
|
|
|
} else {
|
|
|
|
// In this case, we expect a constant incoming value (the comparison is
|
|
|
|
// chained).
|
|
|
|
const auto *const Const = dyn_cast<ConstantInt>(Val);
|
2018-05-14 14:53:11 +02:00
|
|
|
LLVM_DEBUG(dbgs() << "const\n");
|
2017-10-04 17:13:52 +02:00
|
|
|
if (!Const->isZero()) return {};
|
2018-05-14 14:53:11 +02:00
|
|
|
LLVM_DEBUG(dbgs() << "false\n");
|
2017-09-01 12:56:34 +02:00
|
|
|
auto *const CmpI = dyn_cast<ICmpInst>(BranchI->getCondition());
|
2017-10-04 17:13:52 +02:00
|
|
|
if (!CmpI) return {};
|
2018-05-14 14:53:11 +02:00
|
|
|
LLVM_DEBUG(dbgs() << "icmp\n");
|
2017-09-01 12:56:34 +02:00
|
|
|
assert(BranchI->getNumSuccessors() == 2 && "expecting a cond branch");
|
|
|
|
BasicBlock *const FalseBlock = BranchI->getSuccessor(1);
|
|
|
|
auto Result = visitICmp(
|
2019-02-15 15:17:17 +01:00
|
|
|
CmpI, FalseBlock == PhiBlock ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE,
|
|
|
|
BaseId);
|
2017-09-01 12:56:34 +02:00
|
|
|
Result.CmpI = CmpI;
|
|
|
|
Result.BranchI = BranchI;
|
|
|
|
return Result;
|
|
|
|
}
|
|
|
|
return {};
|
|
|
|
}
|
|
|
|
|
2018-04-09 15:14:06 +02:00
|
|
|
static inline void enqueueBlock(std::vector<BCECmpBlock> &Comparisons,
|
2019-05-22 11:45:40 +02:00
|
|
|
BCECmpBlock &&Comparison) {
|
2018-05-14 14:53:11 +02:00
|
|
|
LLVM_DEBUG(dbgs() << "Block '" << Comparison.BB->getName()
|
|
|
|
<< "': Found cmp of " << Comparison.SizeBits()
|
2019-02-15 15:17:17 +01:00
|
|
|
<< " bits between " << Comparison.Lhs().BaseId << " + "
|
2018-05-14 14:53:11 +02:00
|
|
|
<< Comparison.Lhs().Offset << " and "
|
2019-02-15 15:17:17 +01:00
|
|
|
<< Comparison.Rhs().BaseId << " + "
|
2018-05-14 14:53:11 +02:00
|
|
|
<< Comparison.Rhs().Offset << "\n");
|
|
|
|
LLVM_DEBUG(dbgs() << "\n");
|
2019-05-22 11:45:40 +02:00
|
|
|
Comparisons.push_back(std::move(Comparison));
|
2018-04-09 15:14:06 +02:00
|
|
|
}
|
|
|
|
|
2017-09-01 12:56:34 +02:00
|
|
|
// A chain of comparisons.
|
|
|
|
class BCECmpChain {
|
2017-10-26 03:25:14 +02:00
|
|
|
public:
|
2019-05-23 14:35:26 +02:00
|
|
|
BCECmpChain(const std::vector<BasicBlock *> &Blocks, PHINode &Phi,
|
|
|
|
AliasAnalysis &AA);
|
2017-09-01 12:56:34 +02:00
|
|
|
|
2019-05-23 14:35:26 +02:00
|
|
|
int size() const { return Comparisons_.size(); }
|
2017-09-01 12:56:34 +02:00
|
|
|
|
|
|
|
#ifdef MERGEICMPS_DOT_ON
|
|
|
|
void dump() const;
|
|
|
|
#endif // MERGEICMPS_DOT_ON
|
|
|
|
|
2019-05-23 14:35:26 +02:00
|
|
|
bool simplify(const TargetLibraryInfo &TLI, AliasAnalysis &AA,
|
2019-05-21 13:02:23 +02:00
|
|
|
DomTreeUpdater &DTU);
|
2017-09-01 12:56:34 +02:00
|
|
|
|
2019-05-21 13:02:23 +02:00
|
|
|
private:
|
2017-09-01 12:56:34 +02:00
|
|
|
static bool IsContiguous(const BCECmpBlock &First,
|
|
|
|
const BCECmpBlock &Second) {
|
2019-02-15 15:17:17 +01:00
|
|
|
return First.Lhs().BaseId == Second.Lhs().BaseId &&
|
|
|
|
First.Rhs().BaseId == Second.Rhs().BaseId &&
|
2017-09-01 12:56:34 +02:00
|
|
|
First.Lhs().Offset + First.SizeBits() / 8 == Second.Lhs().Offset &&
|
|
|
|
First.Rhs().Offset + First.SizeBits() / 8 == Second.Rhs().Offset;
|
|
|
|
}
|
|
|
|
|
|
|
|
PHINode &Phi_;
|
|
|
|
std::vector<BCECmpBlock> Comparisons_;
|
|
|
|
// The original entry block (before sorting);
|
|
|
|
BasicBlock *EntryBlock_;
|
|
|
|
};
|
|
|
|
|
2018-09-24 22:47:12 +02:00
|
|
|
BCECmpChain::BCECmpChain(const std::vector<BasicBlock *> &Blocks, PHINode &Phi,
|
2019-05-23 14:35:26 +02:00
|
|
|
AliasAnalysis &AA)
|
2017-09-01 12:56:34 +02:00
|
|
|
: Phi_(Phi) {
|
2018-02-06 10:14:00 +01:00
|
|
|
assert(!Blocks.empty() && "a chain should have at least one block");
|
2017-09-01 12:56:34 +02:00
|
|
|
// Now look inside blocks to check for BCE comparisons.
|
|
|
|
std::vector<BCECmpBlock> Comparisons;
|
2019-02-15 15:17:17 +01:00
|
|
|
BaseIdentifier BaseId;
|
2018-02-06 13:25:33 +01:00
|
|
|
for (size_t BlockIdx = 0; BlockIdx < Blocks.size(); ++BlockIdx) {
|
|
|
|
BasicBlock *const Block = Blocks[BlockIdx];
|
2018-02-06 10:14:00 +01:00
|
|
|
assert(Block && "invalid block");
|
2017-09-01 12:56:34 +02:00
|
|
|
BCECmpBlock Comparison = visitCmpBlock(Phi.getIncomingValueForBlock(Block),
|
2019-02-15 15:17:17 +01:00
|
|
|
Block, Phi.getParent(), BaseId);
|
2017-09-01 12:56:34 +02:00
|
|
|
Comparison.BB = Block;
|
|
|
|
if (!Comparison.IsValid()) {
|
2018-05-14 14:53:11 +02:00
|
|
|
LLVM_DEBUG(dbgs() << "chain with invalid BCECmpBlock, no merge.\n");
|
2017-09-01 12:56:34 +02:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
if (Comparison.doesOtherWork()) {
|
2018-05-14 14:53:11 +02:00
|
|
|
LLVM_DEBUG(dbgs() << "block '" << Comparison.BB->getName()
|
|
|
|
<< "' does extra work besides compare\n");
|
2018-03-05 14:54:47 +01:00
|
|
|
if (Comparisons.empty()) {
|
2018-04-09 15:14:06 +02:00
|
|
|
// This is the initial block in the chain, in case this block does other
|
|
|
|
// work, we can try to split the block and move the irrelevant
|
|
|
|
// instructions to the predecessor.
|
|
|
|
//
|
|
|
|
// If this is not the initial block in the chain, splitting it wont
|
|
|
|
// work.
|
|
|
|
//
|
|
|
|
// As once split, there will still be instructions before the BCE cmp
|
|
|
|
// instructions that do other work in program order, i.e. within the
|
|
|
|
// chain before sorting. Unless we can abort the chain at this point
|
|
|
|
// and start anew.
|
|
|
|
//
|
2019-05-17 11:43:45 +02:00
|
|
|
// NOTE: we only handle blocks a with single predecessor for now.
|
2018-09-24 22:47:12 +02:00
|
|
|
if (Comparison.canSplit(AA)) {
|
2018-05-14 14:53:11 +02:00
|
|
|
LLVM_DEBUG(dbgs()
|
|
|
|
<< "Split initial block '" << Comparison.BB->getName()
|
|
|
|
<< "' that does extra work besides compare\n");
|
2018-04-09 15:14:06 +02:00
|
|
|
Comparison.RequireSplit = true;
|
2019-05-22 11:45:40 +02:00
|
|
|
enqueueBlock(Comparisons, std::move(Comparison));
|
2018-04-09 15:14:06 +02:00
|
|
|
} else {
|
2018-05-14 14:53:11 +02:00
|
|
|
LLVM_DEBUG(dbgs()
|
|
|
|
<< "ignoring initial block '" << Comparison.BB->getName()
|
|
|
|
<< "' that does extra work besides compare\n");
|
2018-04-09 15:14:06 +02:00
|
|
|
}
|
2017-09-01 12:56:34 +02:00
|
|
|
continue;
|
|
|
|
}
|
|
|
|
// TODO(courbet): Right now we abort the whole chain. We could be
|
|
|
|
// merging only the blocks that don't do other work and resume the
|
|
|
|
// chain from there. For example:
|
|
|
|
// if (a[0] == b[0]) { // bb1
|
|
|
|
// if (a[1] == b[1]) { // bb2
|
|
|
|
// some_value = 3; //bb3
|
|
|
|
// if (a[2] == b[2]) { //bb3
|
|
|
|
// do a ton of stuff //bb4
|
|
|
|
// }
|
|
|
|
// }
|
|
|
|
// }
|
|
|
|
//
|
|
|
|
// This is:
|
|
|
|
//
|
|
|
|
// bb1 --eq--> bb2 --eq--> bb3* -eq--> bb4 --+
|
|
|
|
// \ \ \ \
|
|
|
|
// ne ne ne \
|
|
|
|
// \ \ \ v
|
|
|
|
// +------------+-----------+----------> bb_phi
|
|
|
|
//
|
|
|
|
// We can only merge the first two comparisons, because bb3* does
|
|
|
|
// "other work" (setting some_value to 3).
|
|
|
|
// We could still merge bb1 and bb2 though.
|
|
|
|
return;
|
|
|
|
}
|
2019-05-22 11:45:40 +02:00
|
|
|
enqueueBlock(Comparisons, std::move(Comparison));
|
2017-09-01 12:56:34 +02:00
|
|
|
}
|
2018-03-05 14:54:47 +01:00
|
|
|
|
|
|
|
// It is possible we have no suitable comparison to merge.
|
|
|
|
if (Comparisons.empty()) {
|
2018-05-14 14:53:11 +02:00
|
|
|
LLVM_DEBUG(dbgs() << "chain with no BCE basic blocks, no merge\n");
|
2018-03-05 14:54:47 +01:00
|
|
|
return;
|
|
|
|
}
|
2017-09-01 12:56:34 +02:00
|
|
|
EntryBlock_ = Comparisons[0].BB;
|
|
|
|
Comparisons_ = std::move(Comparisons);
|
|
|
|
#ifdef MERGEICMPS_DOT_ON
|
|
|
|
errs() << "BEFORE REORDERING:\n\n";
|
|
|
|
dump();
|
|
|
|
#endif // MERGEICMPS_DOT_ON
|
|
|
|
// Reorder blocks by LHS. We can do that without changing the
|
|
|
|
// semantics because we are only accessing dereferencable memory.
|
2019-02-15 15:17:17 +01:00
|
|
|
llvm::sort(Comparisons_,
|
|
|
|
[](const BCECmpBlock &LhsBlock, const BCECmpBlock &RhsBlock) {
|
2019-05-21 19:58:42 +02:00
|
|
|
return std::tie(LhsBlock.Lhs(), LhsBlock.Rhs()) <
|
|
|
|
std::tie(RhsBlock.Lhs(), RhsBlock.Rhs());
|
2019-02-15 15:17:17 +01:00
|
|
|
});
|
2017-09-01 12:56:34 +02:00
|
|
|
#ifdef MERGEICMPS_DOT_ON
|
|
|
|
errs() << "AFTER REORDERING:\n\n";
|
|
|
|
dump();
|
|
|
|
#endif // MERGEICMPS_DOT_ON
|
|
|
|
}
|
|
|
|
|
|
|
|
#ifdef MERGEICMPS_DOT_ON
|
|
|
|
void BCECmpChain::dump() const {
|
|
|
|
errs() << "digraph dag {\n";
|
|
|
|
errs() << " graph [bgcolor=transparent];\n";
|
|
|
|
errs() << " node [color=black,style=filled,fillcolor=lightyellow];\n";
|
|
|
|
errs() << " edge [color=black];\n";
|
|
|
|
for (size_t I = 0; I < Comparisons_.size(); ++I) {
|
|
|
|
const auto &Comparison = Comparisons_[I];
|
|
|
|
errs() << " \"" << I << "\" [label=\"%"
|
|
|
|
<< Comparison.Lhs().Base()->getName() << " + "
|
|
|
|
<< Comparison.Lhs().Offset << " == %"
|
|
|
|
<< Comparison.Rhs().Base()->getName() << " + "
|
|
|
|
<< Comparison.Rhs().Offset << " (" << (Comparison.SizeBits() / 8)
|
|
|
|
<< " bytes)\"];\n";
|
|
|
|
const Value *const Val = Phi_.getIncomingValueForBlock(Comparison.BB);
|
2017-10-04 17:13:52 +02:00
|
|
|
if (I > 0) errs() << " \"" << (I - 1) << "\" -> \"" << I << "\";\n";
|
2017-09-01 12:56:34 +02:00
|
|
|
errs() << " \"" << I << "\" -> \"Phi\" [label=\"" << *Val << "\"];\n";
|
|
|
|
}
|
|
|
|
errs() << " \"Phi\" [label=\"Phi\"];\n";
|
|
|
|
errs() << "}\n\n";
|
|
|
|
}
|
|
|
|
#endif // MERGEICMPS_DOT_ON
|
|
|
|
|
2019-05-17 11:43:45 +02:00
|
|
|
namespace {
|
2017-09-01 12:56:34 +02:00
|
|
|
|
2019-05-17 11:43:45 +02:00
|
|
|
// A class to compute the name of a set of merged basic blocks.
|
|
|
|
// This is optimized for the common case of no block names.
|
|
|
|
class MergedBlockName {
|
|
|
|
// Storage for the uncommon case of several named blocks.
|
|
|
|
SmallString<16> Scratch;
|
2019-05-15 16:21:59 +02:00
|
|
|
|
2019-05-17 11:43:45 +02:00
|
|
|
public:
|
|
|
|
explicit MergedBlockName(ArrayRef<BCECmpBlock> Comparisons)
|
|
|
|
: Name(makeName(Comparisons)) {}
|
|
|
|
const StringRef Name;
|
2019-05-17 02:43:53 +02:00
|
|
|
|
2019-05-17 11:43:45 +02:00
|
|
|
private:
|
|
|
|
StringRef makeName(ArrayRef<BCECmpBlock> Comparisons) {
|
|
|
|
assert(!Comparisons.empty() && "no basic block");
|
|
|
|
// Fast path: only one block, or no names at all.
|
|
|
|
if (Comparisons.size() == 1)
|
|
|
|
return Comparisons[0].BB->getName();
|
|
|
|
const int size = std::accumulate(Comparisons.begin(), Comparisons.end(), 0,
|
|
|
|
[](int i, const BCECmpBlock &Cmp) {
|
|
|
|
return i + Cmp.BB->getName().size();
|
|
|
|
});
|
|
|
|
if (size == 0)
|
|
|
|
return StringRef("", 0);
|
|
|
|
|
|
|
|
// Slow path: at least two blocks, at least one block with a name.
|
|
|
|
Scratch.clear();
|
|
|
|
// We'll have `size` bytes for name and `Comparisons.size() - 1` bytes for
|
|
|
|
// separators.
|
|
|
|
Scratch.reserve(size + Comparisons.size() - 1);
|
|
|
|
const auto append = [this](StringRef str) {
|
|
|
|
Scratch.append(str.begin(), str.end());
|
|
|
|
};
|
|
|
|
append(Comparisons[0].BB->getName());
|
|
|
|
for (int I = 1, E = Comparisons.size(); I < E; ++I) {
|
|
|
|
const BasicBlock *const BB = Comparisons[I].BB;
|
|
|
|
if (!BB->getName().empty()) {
|
|
|
|
append("+");
|
|
|
|
append(BB->getName());
|
|
|
|
}
|
2017-09-01 12:56:34 +02:00
|
|
|
}
|
2019-05-17 11:43:45 +02:00
|
|
|
return StringRef(Scratch);
|
2017-09-01 12:56:34 +02:00
|
|
|
}
|
2019-05-17 11:43:45 +02:00
|
|
|
};
|
|
|
|
} // namespace
|
|
|
|
|
|
|
|
// Merges the given contiguous comparison blocks into one memcmp block.
|
|
|
|
static BasicBlock *mergeComparisons(ArrayRef<BCECmpBlock> Comparisons,
|
2019-05-21 13:02:23 +02:00
|
|
|
BasicBlock *const InsertBefore,
|
2019-05-17 11:43:45 +02:00
|
|
|
BasicBlock *const NextCmpBlock,
|
2019-05-23 14:35:26 +02:00
|
|
|
PHINode &Phi, const TargetLibraryInfo &TLI,
|
|
|
|
AliasAnalysis &AA, DomTreeUpdater &DTU) {
|
2019-05-17 11:43:45 +02:00
|
|
|
assert(!Comparisons.empty() && "merging zero comparisons");
|
|
|
|
LLVMContext &Context = NextCmpBlock->getContext();
|
|
|
|
const BCECmpBlock &FirstCmp = Comparisons[0];
|
|
|
|
|
|
|
|
// Create a new cmp block before next cmp block.
|
|
|
|
BasicBlock *const BB =
|
|
|
|
BasicBlock::Create(Context, MergedBlockName(Comparisons).Name,
|
2019-05-21 13:02:23 +02:00
|
|
|
NextCmpBlock->getParent(), InsertBefore);
|
2019-05-17 11:43:45 +02:00
|
|
|
IRBuilder<> Builder(BB);
|
|
|
|
// Add the GEPs from the first BCECmpBlock.
|
|
|
|
Value *const Lhs = Builder.Insert(FirstCmp.Lhs().GEP->clone());
|
|
|
|
Value *const Rhs = Builder.Insert(FirstCmp.Rhs().GEP->clone());
|
|
|
|
|
|
|
|
Value *IsEqual = nullptr;
|
2019-05-21 13:02:23 +02:00
|
|
|
LLVM_DEBUG(dbgs() << "Merging " << Comparisons.size() << " comparisons -> "
|
|
|
|
<< BB->getName() << "\n");
|
2019-05-17 11:43:45 +02:00
|
|
|
if (Comparisons.size() == 1) {
|
|
|
|
LLVM_DEBUG(dbgs() << "Only one comparison, updating branches\n");
|
|
|
|
Value *const LhsLoad =
|
|
|
|
Builder.CreateLoad(FirstCmp.Lhs().LoadI->getType(), Lhs);
|
|
|
|
Value *const RhsLoad =
|
|
|
|
Builder.CreateLoad(FirstCmp.Rhs().LoadI->getType(), Rhs);
|
|
|
|
// There are no blocks to merge, just do the comparison.
|
|
|
|
IsEqual = Builder.CreateICmpEQ(LhsLoad, RhsLoad);
|
|
|
|
} else {
|
2018-04-09 15:14:06 +02:00
|
|
|
// If there is one block that requires splitting, we do it now, i.e.
|
|
|
|
// just before we know we will collapse the chain. The instructions
|
|
|
|
// can be executed before any of the instructions in the chain.
|
2019-05-17 11:43:45 +02:00
|
|
|
const auto ToSplit =
|
|
|
|
std::find_if(Comparisons.begin(), Comparisons.end(),
|
|
|
|
[](const BCECmpBlock &B) { return B.RequireSplit; });
|
|
|
|
if (ToSplit != Comparisons.end()) {
|
|
|
|
LLVM_DEBUG(dbgs() << "Splitting non_BCE work to header\n");
|
|
|
|
ToSplit->split(BB, AA);
|
|
|
|
}
|
2018-04-09 15:14:06 +02:00
|
|
|
|
2019-05-17 11:43:45 +02:00
|
|
|
const unsigned TotalSizeBits = std::accumulate(
|
|
|
|
Comparisons.begin(), Comparisons.end(), 0u,
|
|
|
|
[](int Size, const BCECmpBlock &C) { return Size + C.SizeBits(); });
|
|
|
|
|
|
|
|
// Create memcmp() == 0.
|
2017-09-01 12:56:34 +02:00
|
|
|
const auto &DL = Phi.getModule()->getDataLayout();
|
2017-10-10 10:00:45 +02:00
|
|
|
Value *const MemCmpCall = emitMemCmp(
|
2019-05-17 11:43:45 +02:00
|
|
|
Lhs, Rhs,
|
|
|
|
ConstantInt::get(DL.getIntPtrType(Context), TotalSizeBits / 8), Builder,
|
2019-05-23 14:35:26 +02:00
|
|
|
DL, &TLI);
|
2019-05-17 11:43:45 +02:00
|
|
|
IsEqual = Builder.CreateICmpEQ(
|
2017-09-01 12:56:34 +02:00
|
|
|
MemCmpCall, ConstantInt::get(Type::getInt32Ty(Context), 0));
|
2019-05-17 11:43:45 +02:00
|
|
|
}
|
2017-09-01 12:56:34 +02:00
|
|
|
|
2019-05-17 11:43:45 +02:00
|
|
|
BasicBlock *const PhiBB = Phi.getParent();
|
|
|
|
// Add a branch to the next basic block in the chain.
|
|
|
|
if (NextCmpBlock == PhiBB) {
|
|
|
|
// Continue to phi, passing it the comparison result.
|
2019-05-21 13:02:23 +02:00
|
|
|
Builder.CreateBr(PhiBB);
|
2019-05-17 11:43:45 +02:00
|
|
|
Phi.addIncoming(IsEqual, BB);
|
2019-05-21 13:02:23 +02:00
|
|
|
DTU.applyUpdates({{DominatorTree::Insert, BB, PhiBB}});
|
2019-05-17 11:43:45 +02:00
|
|
|
} else {
|
|
|
|
// Continue to next block if equal, exit to phi else.
|
|
|
|
Builder.CreateCondBr(IsEqual, NextCmpBlock, PhiBB);
|
|
|
|
Phi.addIncoming(ConstantInt::getFalse(Context), BB);
|
2019-05-21 13:02:23 +02:00
|
|
|
DTU.applyUpdates({{DominatorTree::Insert, BB, NextCmpBlock},
|
|
|
|
{DominatorTree::Insert, BB, PhiBB}});
|
2019-05-17 11:43:45 +02:00
|
|
|
}
|
|
|
|
return BB;
|
|
|
|
}
|
2017-09-01 12:56:34 +02:00
|
|
|
|
2019-05-23 14:35:26 +02:00
|
|
|
bool BCECmpChain::simplify(const TargetLibraryInfo &TLI, AliasAnalysis &AA,
|
|
|
|
DomTreeUpdater &DTU) {
|
2019-05-17 11:43:45 +02:00
|
|
|
assert(Comparisons_.size() >= 2 && "simplifying trivial BCECmpChain");
|
|
|
|
// First pass to check if there is at least one merge. If not, we don't do
|
|
|
|
// anything and we keep analysis passes intact.
|
|
|
|
const auto AtLeastOneMerged = [this]() {
|
|
|
|
for (size_t I = 1; I < Comparisons_.size(); ++I) {
|
|
|
|
if (IsContiguous(Comparisons_[I - 1], Comparisons_[I]))
|
|
|
|
return true;
|
2017-09-01 12:56:34 +02:00
|
|
|
}
|
2019-05-17 11:43:45 +02:00
|
|
|
return false;
|
|
|
|
};
|
|
|
|
if (!AtLeastOneMerged())
|
|
|
|
return false;
|
|
|
|
|
2019-05-17 14:07:51 +02:00
|
|
|
LLVM_DEBUG(dbgs() << "Simplifying comparison chain starting at block "
|
|
|
|
<< EntryBlock_->getName() << "\n");
|
|
|
|
|
2019-05-17 11:43:45 +02:00
|
|
|
// Effectively merge blocks. We go in the reverse direction from the phi block
|
|
|
|
// so that the next block is always available to branch to.
|
2019-05-23 14:35:26 +02:00
|
|
|
const auto mergeRange = [this, &TLI, &AA, &DTU](int I, int Num,
|
|
|
|
BasicBlock *InsertBefore,
|
|
|
|
BasicBlock *Next) {
|
2019-05-21 13:02:23 +02:00
|
|
|
return mergeComparisons(makeArrayRef(Comparisons_).slice(I, Num),
|
|
|
|
InsertBefore, Next, Phi_, TLI, AA, DTU);
|
2019-05-17 11:43:45 +02:00
|
|
|
};
|
|
|
|
int NumMerged = 1;
|
|
|
|
BasicBlock *NextCmpBlock = Phi_.getParent();
|
|
|
|
for (int I = static_cast<int>(Comparisons_.size()) - 2; I >= 0; --I) {
|
|
|
|
if (IsContiguous(Comparisons_[I], Comparisons_[I + 1])) {
|
2019-05-17 14:07:51 +02:00
|
|
|
LLVM_DEBUG(dbgs() << "Merging block " << Comparisons_[I].BB->getName()
|
|
|
|
<< " into " << Comparisons_[I + 1].BB->getName()
|
|
|
|
<< "\n");
|
2019-05-17 11:43:45 +02:00
|
|
|
++NumMerged;
|
2017-09-01 12:56:34 +02:00
|
|
|
} else {
|
2019-05-21 13:02:23 +02:00
|
|
|
NextCmpBlock = mergeRange(I + 1, NumMerged, NextCmpBlock, NextCmpBlock);
|
2019-05-17 11:43:45 +02:00
|
|
|
NumMerged = 1;
|
2017-09-01 12:56:34 +02:00
|
|
|
}
|
|
|
|
}
|
2019-05-21 13:02:23 +02:00
|
|
|
// Insert the entry block for the new chain before the old entry block.
|
|
|
|
// If the old entry block was the function entry, this ensures that the new
|
|
|
|
// entry can become the function entry.
|
|
|
|
NextCmpBlock = mergeRange(0, NumMerged, EntryBlock_, NextCmpBlock);
|
2019-05-17 11:43:45 +02:00
|
|
|
|
|
|
|
// Replace the original cmp chain with the new cmp chain by pointing all
|
|
|
|
// predecessors of EntryBlock_ to NextCmpBlock instead. This makes all cmp
|
|
|
|
// blocks in the old chain unreachable.
|
|
|
|
while (!pred_empty(EntryBlock_)) {
|
|
|
|
BasicBlock* const Pred = *pred_begin(EntryBlock_);
|
2019-05-17 14:07:51 +02:00
|
|
|
LLVM_DEBUG(dbgs() << "Updating jump into old chain from " << Pred->getName()
|
|
|
|
<< "\n");
|
2019-05-17 11:43:45 +02:00
|
|
|
Pred->getTerminator()->replaceUsesOfWith(EntryBlock_, NextCmpBlock);
|
2019-05-21 13:02:23 +02:00
|
|
|
DTU.applyUpdates({{DominatorTree::Delete, Pred, EntryBlock_},
|
|
|
|
{DominatorTree::Insert, Pred, NextCmpBlock}});
|
|
|
|
}
|
|
|
|
|
|
|
|
// If the old cmp chain was the function entry, we need to update the function
|
|
|
|
// entry.
|
|
|
|
const bool ChainEntryIsFnEntry =
|
|
|
|
(EntryBlock_ == &EntryBlock_->getParent()->getEntryBlock());
|
|
|
|
if (ChainEntryIsFnEntry && DTU.hasDomTree()) {
|
|
|
|
LLVM_DEBUG(dbgs() << "Changing function entry from "
|
|
|
|
<< EntryBlock_->getName() << " to "
|
|
|
|
<< NextCmpBlock->getName() << "\n");
|
|
|
|
DTU.getDomTree().setNewRoot(NextCmpBlock);
|
|
|
|
DTU.applyUpdates({{DominatorTree::Delete, NextCmpBlock, EntryBlock_}});
|
2019-05-17 11:43:45 +02:00
|
|
|
}
|
|
|
|
EntryBlock_ = nullptr;
|
|
|
|
|
|
|
|
// Delete merged blocks. This also removes incoming values in phi.
|
|
|
|
SmallVector<BasicBlock *, 16> DeadBlocks;
|
|
|
|
for (auto &Cmp : Comparisons_) {
|
2019-05-17 14:07:51 +02:00
|
|
|
LLVM_DEBUG(dbgs() << "Deleting merged block " << Cmp.BB->getName() << "\n");
|
2019-05-17 11:43:45 +02:00
|
|
|
DeadBlocks.push_back(Cmp.BB);
|
|
|
|
}
|
2019-05-21 13:02:23 +02:00
|
|
|
DeleteDeadBlocks(DeadBlocks, &DTU);
|
2019-05-17 11:43:45 +02:00
|
|
|
|
|
|
|
Comparisons_.clear();
|
|
|
|
return true;
|
2017-09-01 12:56:34 +02:00
|
|
|
}
|
|
|
|
|
2017-10-26 03:25:14 +02:00
|
|
|
std::vector<BasicBlock *> getOrderedBlocks(PHINode &Phi,
|
|
|
|
BasicBlock *const LastBlock,
|
|
|
|
int NumBlocks) {
|
2017-09-01 12:56:34 +02:00
|
|
|
// Walk up from the last block to find other blocks.
|
|
|
|
std::vector<BasicBlock *> Blocks(NumBlocks);
|
2018-02-06 10:14:00 +01:00
|
|
|
assert(LastBlock && "invalid last block");
|
2017-09-01 12:56:34 +02:00
|
|
|
BasicBlock *CurBlock = LastBlock;
|
|
|
|
for (int BlockIndex = NumBlocks - 1; BlockIndex > 0; --BlockIndex) {
|
|
|
|
if (CurBlock->hasAddressTaken()) {
|
|
|
|
// Somebody is jumping to the block through an address, all bets are
|
|
|
|
// off.
|
2018-05-14 14:53:11 +02:00
|
|
|
LLVM_DEBUG(dbgs() << "skip: block " << BlockIndex
|
|
|
|
<< " has its address taken\n");
|
2017-09-01 12:56:34 +02:00
|
|
|
return {};
|
|
|
|
}
|
|
|
|
Blocks[BlockIndex] = CurBlock;
|
|
|
|
auto *SinglePredecessor = CurBlock->getSinglePredecessor();
|
|
|
|
if (!SinglePredecessor) {
|
|
|
|
// The block has two or more predecessors.
|
2018-05-14 14:53:11 +02:00
|
|
|
LLVM_DEBUG(dbgs() << "skip: block " << BlockIndex
|
|
|
|
<< " has two or more predecessors\n");
|
2017-09-01 12:56:34 +02:00
|
|
|
return {};
|
|
|
|
}
|
|
|
|
if (Phi.getBasicBlockIndex(SinglePredecessor) < 0) {
|
|
|
|
// The block does not link back to the phi.
|
2018-05-14 14:53:11 +02:00
|
|
|
LLVM_DEBUG(dbgs() << "skip: block " << BlockIndex
|
|
|
|
<< " does not link back to the phi\n");
|
2017-09-01 12:56:34 +02:00
|
|
|
return {};
|
|
|
|
}
|
|
|
|
CurBlock = SinglePredecessor;
|
|
|
|
}
|
|
|
|
Blocks[0] = CurBlock;
|
|
|
|
return Blocks;
|
|
|
|
}
|
|
|
|
|
2019-05-23 14:35:26 +02:00
|
|
|
bool processPhi(PHINode &Phi, const TargetLibraryInfo &TLI, AliasAnalysis &AA,
|
|
|
|
DomTreeUpdater &DTU) {
|
2018-05-14 14:53:11 +02:00
|
|
|
LLVM_DEBUG(dbgs() << "processPhi()\n");
|
2017-09-01 12:56:34 +02:00
|
|
|
if (Phi.getNumIncomingValues() <= 1) {
|
2018-05-14 14:53:11 +02:00
|
|
|
LLVM_DEBUG(dbgs() << "skip: only one incoming value in phi\n");
|
2017-09-01 12:56:34 +02:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
// We are looking for something that has the following structure:
|
|
|
|
// bb1 --eq--> bb2 --eq--> bb3 --eq--> bb4 --+
|
|
|
|
// \ \ \ \
|
|
|
|
// ne ne ne \
|
|
|
|
// \ \ \ v
|
|
|
|
// +------------+-----------+----------> bb_phi
|
|
|
|
//
|
|
|
|
// - The last basic block (bb4 here) must branch unconditionally to bb_phi.
|
|
|
|
// It's the only block that contributes a non-constant value to the Phi.
|
|
|
|
// - All other blocks (b1, b2, b3) must have exactly two successors, one of
|
2018-01-19 11:55:29 +01:00
|
|
|
// them being the phi block.
|
2017-09-01 12:56:34 +02:00
|
|
|
// - All intermediate blocks (bb2, bb3) must have only one predecessor.
|
|
|
|
// - Blocks cannot do other work besides the comparison, see doesOtherWork()
|
|
|
|
|
|
|
|
// The blocks are not necessarily ordered in the phi, so we start from the
|
|
|
|
// last block and reconstruct the order.
|
|
|
|
BasicBlock *LastBlock = nullptr;
|
|
|
|
for (unsigned I = 0; I < Phi.getNumIncomingValues(); ++I) {
|
2017-10-04 17:13:52 +02:00
|
|
|
if (isa<ConstantInt>(Phi.getIncomingValue(I))) continue;
|
2017-09-01 12:56:34 +02:00
|
|
|
if (LastBlock) {
|
|
|
|
// There are several non-constant values.
|
2018-05-14 14:53:11 +02:00
|
|
|
LLVM_DEBUG(dbgs() << "skip: several non-constant values\n");
|
2017-09-01 12:56:34 +02:00
|
|
|
return false;
|
|
|
|
}
|
2018-02-28 13:08:00 +01:00
|
|
|
if (!isa<ICmpInst>(Phi.getIncomingValue(I)) ||
|
|
|
|
cast<ICmpInst>(Phi.getIncomingValue(I))->getParent() !=
|
|
|
|
Phi.getIncomingBlock(I)) {
|
|
|
|
// Non-constant incoming value is not from a cmp instruction or not
|
|
|
|
// produced by the last block. We could end up processing the value
|
|
|
|
// producing block more than once.
|
|
|
|
//
|
|
|
|
// This is an uncommon case, so we bail.
|
2018-05-14 14:53:11 +02:00
|
|
|
LLVM_DEBUG(
|
2018-02-28 13:08:00 +01:00
|
|
|
dbgs()
|
|
|
|
<< "skip: non-constant value not from cmp or not from last block.\n");
|
|
|
|
return false;
|
|
|
|
}
|
2017-09-01 12:56:34 +02:00
|
|
|
LastBlock = Phi.getIncomingBlock(I);
|
|
|
|
}
|
|
|
|
if (!LastBlock) {
|
|
|
|
// There is no non-constant block.
|
2018-05-14 14:53:11 +02:00
|
|
|
LLVM_DEBUG(dbgs() << "skip: no non-constant block\n");
|
2017-09-01 12:56:34 +02:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
if (LastBlock->getSingleSuccessor() != Phi.getParent()) {
|
2018-05-14 14:53:11 +02:00
|
|
|
LLVM_DEBUG(dbgs() << "skip: last block non-phi successor\n");
|
2017-09-01 12:56:34 +02:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
const auto Blocks =
|
|
|
|
getOrderedBlocks(Phi, LastBlock, Phi.getNumIncomingValues());
|
2017-10-04 17:13:52 +02:00
|
|
|
if (Blocks.empty()) return false;
|
2018-09-24 22:47:12 +02:00
|
|
|
BCECmpChain CmpChain(Blocks, Phi, AA);
|
2017-09-01 12:56:34 +02:00
|
|
|
|
|
|
|
if (CmpChain.size() < 2) {
|
2018-05-14 14:53:11 +02:00
|
|
|
LLVM_DEBUG(dbgs() << "skip: only one compare block\n");
|
2017-09-01 12:56:34 +02:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2019-05-21 13:02:23 +02:00
|
|
|
return CmpChain.simplify(TLI, AA, DTU);
|
2017-09-01 12:56:34 +02:00
|
|
|
}
|
|
|
|
|
2019-05-23 14:35:26 +02:00
|
|
|
static bool runImpl(Function &F, const TargetLibraryInfo &TLI,
|
|
|
|
const TargetTransformInfo &TTI, AliasAnalysis &AA,
|
|
|
|
DominatorTree *DT) {
|
|
|
|
LLVM_DEBUG(dbgs() << "MergeICmpsLegacyPass: " << F.getName() << "\n");
|
|
|
|
|
|
|
|
// We only try merging comparisons if the target wants to expand memcmp later.
|
|
|
|
// The rationale is to avoid turning small chains into memcmp calls.
|
2019-09-10 12:39:09 +02:00
|
|
|
if (!TTI.enableMemCmpExpansion(F.hasOptSize(), true))
|
2019-05-23 14:35:26 +02:00
|
|
|
return false;
|
|
|
|
|
|
|
|
// If we don't have memcmp avaiable we can't emit calls to it.
|
|
|
|
if (!TLI.has(LibFunc_memcmp))
|
|
|
|
return false;
|
|
|
|
|
|
|
|
DomTreeUpdater DTU(DT, /*PostDominatorTree*/ nullptr,
|
|
|
|
DomTreeUpdater::UpdateStrategy::Eager);
|
|
|
|
|
|
|
|
bool MadeChange = false;
|
|
|
|
|
|
|
|
for (auto BBIt = ++F.begin(); BBIt != F.end(); ++BBIt) {
|
|
|
|
// A Phi operation is always first in a basic block.
|
|
|
|
if (auto *const Phi = dyn_cast<PHINode>(&*BBIt->begin()))
|
|
|
|
MadeChange |= processPhi(*Phi, TLI, AA, DTU);
|
|
|
|
}
|
|
|
|
|
|
|
|
return MadeChange;
|
|
|
|
}
|
|
|
|
|
|
|
|
class MergeICmpsLegacyPass : public FunctionPass {
|
|
|
|
public:
|
2017-09-01 12:56:34 +02:00
|
|
|
static char ID;
|
|
|
|
|
2019-05-23 14:35:26 +02:00
|
|
|
MergeICmpsLegacyPass() : FunctionPass(ID) {
|
|
|
|
initializeMergeICmpsLegacyPassPass(*PassRegistry::getPassRegistry());
|
2017-09-01 12:56:34 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
bool runOnFunction(Function &F) override {
|
|
|
|
if (skipFunction(F)) return false;
|
Change TargetLibraryInfo analysis passes to always require Function
Summary:
This is the first change to enable the TLI to be built per-function so
that -fno-builtin* handling can be migrated to use function attributes.
See discussion on D61634 for background. This is an enabler for fixing
handling of these options for LTO, for example.
This change should not affect behavior, as the provided function is not
yet used to build a specifically per-function TLI, but rather enables
that migration.
Most of the changes were very mechanical, e.g. passing a Function to the
legacy analysis pass's getTLI interface, or in Module level cases,
adding a callback. This is similar to the way the per-function TTI
analysis works.
There was one place where we were looking for builtins but not in the
context of a specific function. See FindCXAAtExit in
lib/Transforms/IPO/GlobalOpt.cpp. I'm somewhat concerned my workaround
could provide the wrong behavior in some corner cases. Suggestions
welcome.
Reviewers: chandlerc, hfinkel
Subscribers: arsenm, dschuff, jvesely, nhaehnle, mehdi_amini, javed.absar, sbc100, jgravelle-google, eraman, aheejin, steven_wu, george.burgess.iv, dexonsmith, jfb, asbirlea, gchatelet, llvm-commits
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D66428
llvm-svn: 371284
2019-09-07 05:09:36 +02:00
|
|
|
const auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
|
2017-10-10 10:00:45 +02:00
|
|
|
const auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
|
2019-05-21 13:02:23 +02:00
|
|
|
// MergeICmps does not need the DominatorTree, but we update it if it's
|
|
|
|
// already available.
|
|
|
|
auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
|
2019-05-23 14:35:26 +02:00
|
|
|
auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
|
|
|
|
return runImpl(F, TLI, TTI, AA, DTWP ? &DTWP->getDomTree() : nullptr);
|
2017-09-01 12:56:34 +02:00
|
|
|
}
|
|
|
|
|
2017-10-26 03:25:14 +02:00
|
|
|
private:
|
2017-09-01 12:56:34 +02:00
|
|
|
void getAnalysisUsage(AnalysisUsage &AU) const override {
|
|
|
|
AU.addRequired<TargetLibraryInfoWrapperPass>();
|
2017-10-10 10:00:45 +02:00
|
|
|
AU.addRequired<TargetTransformInfoWrapperPass>();
|
2018-09-24 22:47:12 +02:00
|
|
|
AU.addRequired<AAResultsWrapperPass>();
|
2019-05-21 13:02:23 +02:00
|
|
|
AU.addPreserved<GlobalsAAWrapperPass>();
|
|
|
|
AU.addPreserved<DominatorTreeWrapperPass>();
|
2017-09-01 12:56:34 +02:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2019-05-23 14:35:26 +02:00
|
|
|
} // namespace
|
2017-10-10 10:00:45 +02:00
|
|
|
|
2019-05-23 14:35:26 +02:00
|
|
|
char MergeICmpsLegacyPass::ID = 0;
|
|
|
|
INITIALIZE_PASS_BEGIN(MergeICmpsLegacyPass, "mergeicmps",
|
|
|
|
"Merge contiguous icmps into a memcmp", false, false)
|
|
|
|
INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
|
|
|
|
INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
|
|
|
|
INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
|
|
|
|
INITIALIZE_PASS_END(MergeICmpsLegacyPass, "mergeicmps",
|
|
|
|
"Merge contiguous icmps into a memcmp", false, false)
|
2018-05-19 14:51:59 +02:00
|
|
|
|
2019-05-23 14:35:26 +02:00
|
|
|
Pass *llvm::createMergeICmpsLegacyPass() { return new MergeICmpsLegacyPass(); }
|
2017-09-01 12:56:34 +02:00
|
|
|
|
2019-05-23 14:35:26 +02:00
|
|
|
PreservedAnalyses MergeICmpsPass::run(Function &F,
|
|
|
|
FunctionAnalysisManager &AM) {
|
|
|
|
auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
|
|
|
|
auto &TTI = AM.getResult<TargetIRAnalysis>(F);
|
|
|
|
auto &AA = AM.getResult<AAManager>(F);
|
|
|
|
auto *DT = AM.getCachedResult<DominatorTreeAnalysis>(F);
|
|
|
|
const bool MadeChanges = runImpl(F, TLI, TTI, AA, DT);
|
|
|
|
if (!MadeChanges)
|
2019-05-21 13:02:23 +02:00
|
|
|
return PreservedAnalyses::all();
|
|
|
|
PreservedAnalyses PA;
|
|
|
|
PA.preserve<GlobalsAA>();
|
|
|
|
PA.preserve<DominatorTreeAnalysis>();
|
|
|
|
return PA;
|
2017-09-01 12:56:34 +02:00
|
|
|
}
|