Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 1 | //===- MergeICmps.cpp - Optimize chains of integer comparisons ------------===// |
| 2 | // |
Chandler Carruth | 2946cd7 | 2019-01-19 08:50:56 +0000 | [diff] [blame] | 3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 | // See https://llvm.org/LICENSE.txt for license information. |
| 5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 6 | // |
| 7 | //===----------------------------------------------------------------------===// |
| 8 | // |
| 9 | // This pass turns chains of integer comparisons into memcmp (the memcmp is |
| 10 | // later typically inlined as a chain of efficient hardware comparisons). This |
| 11 | // typically benefits c++ member or nonmember operator==(). |
| 12 | // |
| 13 | // The basic idea is to replace a larger chain of integer comparisons loaded |
| 14 | // from contiguous memory locations into a smaller chain of such integer |
| 15 | // comparisons. Benefits are double: |
| 16 | // - There are less jumps, and therefore less opportunities for mispredictions |
| 17 | // and I-cache misses. |
| 18 | // - Code size is smaller, both because jumps are removed and because the |
| 19 | // encoding of a 2*n byte compare is smaller than that of two n-byte |
| 20 | // compares. |
Eugene Zelenko | 5c2aece | 2017-10-26 01:25:14 +0000 | [diff] [blame] | 21 | |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 22 | //===----------------------------------------------------------------------===// |
| 23 | |
Eugene Zelenko | 5adb96c | 2017-10-26 00:55:39 +0000 | [diff] [blame] | 24 | #include <algorithm> |
Eugene Zelenko | 5adb96c | 2017-10-26 00:55:39 +0000 | [diff] [blame] | 25 | #include <numeric> |
| 26 | #include <utility> |
| 27 | #include <vector> |
Eugene Zelenko | 5c2aece | 2017-10-26 01:25:14 +0000 | [diff] [blame] | 28 | #include "llvm/Analysis/Loads.h" |
| 29 | #include "llvm/Analysis/TargetLibraryInfo.h" |
| 30 | #include "llvm/Analysis/TargetTransformInfo.h" |
| 31 | #include "llvm/IR/Function.h" |
| 32 | #include "llvm/IR/IRBuilder.h" |
Eugene Zelenko | 5c2aece | 2017-10-26 01:25:14 +0000 | [diff] [blame] | 33 | #include "llvm/Pass.h" |
| 34 | #include "llvm/Transforms/Scalar.h" |
| 35 | #include "llvm/Transforms/Utils/BuildLibCalls.h" |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 36 | |
| 37 | using namespace llvm; |
| 38 | |
Eugene Zelenko | 5adb96c | 2017-10-26 00:55:39 +0000 | [diff] [blame] | 39 | namespace { |
| 40 | |
Eugene Zelenko | 5c2aece | 2017-10-26 01:25:14 +0000 | [diff] [blame] | 41 | #define DEBUG_TYPE "mergeicmps" |
| 42 | |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame] | 43 | // Returns true if the instruction is a simple load or a simple store |
| 44 | static bool isSimpleLoadOrStore(const Instruction *I) { |
| 45 | if (const LoadInst *LI = dyn_cast<LoadInst>(I)) |
| 46 | return LI->isSimple(); |
| 47 | if (const StoreInst *SI = dyn_cast<StoreInst>(I)) |
| 48 | return SI->isSimple(); |
| 49 | return false; |
| 50 | } |
| 51 | |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 52 | // A BCE atom. |
| 53 | struct BCEAtom { |
Eugene Zelenko | 5c2aece | 2017-10-26 01:25:14 +0000 | [diff] [blame] | 54 | BCEAtom() : GEP(nullptr), LoadI(nullptr), Offset() {} |
Clement Courbet | bc0c445 | 2017-09-01 11:51:23 +0000 | [diff] [blame] | 55 | |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 56 | const Value *Base() const { return GEP ? GEP->getPointerOperand() : nullptr; } |
| 57 | |
| 58 | bool operator<(const BCEAtom &O) const { |
Clement Courbet | e2e8a5c | 2017-10-10 08:00:45 +0000 | [diff] [blame] | 59 | assert(Base() && "invalid atom"); |
| 60 | assert(O.Base() && "invalid atom"); |
| 61 | // Just ordering by (Base(), Offset) is sufficient. However because this |
| 62 | // means that the ordering will depend on the addresses of the base |
| 63 | // values, which are not reproducible from run to run. To guarantee |
| 64 | // stability, we use the names of the values if they exist; we sort by: |
| 65 | // (Base.getName(), Base(), Offset). |
| 66 | const int NameCmp = Base()->getName().compare(O.Base()->getName()); |
| 67 | if (NameCmp == 0) { |
| 68 | if (Base() == O.Base()) { |
| 69 | return Offset.slt(O.Offset); |
| 70 | } |
| 71 | return Base() < O.Base(); |
| 72 | } |
| 73 | return NameCmp < 0; |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 74 | } |
| 75 | |
Eugene Zelenko | 5c2aece | 2017-10-26 01:25:14 +0000 | [diff] [blame] | 76 | GetElementPtrInst *GEP; |
| 77 | LoadInst *LoadI; |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 78 | APInt Offset; |
| 79 | }; |
| 80 | |
| 81 | // If this value is a load from a constant offset w.r.t. a base address, and |
Xin Tong | 256869d | 2018-02-28 12:09:53 +0000 | [diff] [blame] | 82 | // there are no other users of the load or address, returns the base address and |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 83 | // the offset. |
Eugene Zelenko | 5c2aece | 2017-10-26 01:25:14 +0000 | [diff] [blame] | 84 | BCEAtom visitICmpLoadOperand(Value *const Val) { |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 85 | BCEAtom Result; |
| 86 | if (auto *const LoadI = dyn_cast<LoadInst>(Val)) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 87 | LLVM_DEBUG(dbgs() << "load\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 88 | if (LoadI->isUsedOutsideOfBlock(LoadI->getParent())) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 89 | LLVM_DEBUG(dbgs() << "used outside of block\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 90 | return {}; |
| 91 | } |
Christy Lee | c85da8b | 2018-09-18 17:02:42 +0000 | [diff] [blame] | 92 | // Do not optimize atomic loads to non-atomic memcmp |
| 93 | if (!LoadI->isSimple()) { |
| 94 | LLVM_DEBUG(dbgs() << "volatile or atomic\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 95 | return {}; |
| 96 | } |
| 97 | Value *const Addr = LoadI->getOperand(0); |
| 98 | if (auto *const GEP = dyn_cast<GetElementPtrInst>(Addr)) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 99 | LLVM_DEBUG(dbgs() << "GEP\n"); |
Taewook Oh | 2b7ae47 | 2018-11-05 18:16:32 +0000 | [diff] [blame] | 100 | if (GEP->isUsedOutsideOfBlock(LoadI->getParent())) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 101 | LLVM_DEBUG(dbgs() << "used outside of block\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 102 | return {}; |
| 103 | } |
| 104 | const auto &DL = GEP->getModule()->getDataLayout(); |
| 105 | if (!isDereferenceablePointer(GEP, DL)) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 106 | LLVM_DEBUG(dbgs() << "not dereferenceable\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 107 | // We need to make sure that we can do comparison in any order, so we |
| 108 | // require memory to be unconditionnally dereferencable. |
| 109 | return {}; |
| 110 | } |
| 111 | Result.Offset = APInt(DL.getPointerTypeSizeInBits(GEP->getType()), 0); |
| 112 | if (GEP->accumulateConstantOffset(DL, Result.Offset)) { |
| 113 | Result.GEP = GEP; |
| 114 | Result.LoadI = LoadI; |
| 115 | } |
| 116 | } |
| 117 | } |
| 118 | return Result; |
| 119 | } |
| 120 | |
| 121 | // A basic block with a comparison between two BCE atoms. |
Xin Tong | 0efadbb | 2018-04-09 13:14:06 +0000 | [diff] [blame] | 122 | // The block might do extra work besides the atom comparison, in which case |
| 123 | // doesOtherWork() returns true. Under some conditions, the block can be |
| 124 | // split into the atom comparison part and the "other work" part |
| 125 | // (see canSplit()). |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 126 | // Note: the terminology is misleading: the comparison is symmetric, so there |
Clement Courbet | e2e8a5c | 2017-10-10 08:00:45 +0000 | [diff] [blame] | 127 | // is no real {l/r}hs. What we want though is to have the same base on the |
| 128 | // left (resp. right), so that we can detect consecutive loads. To ensure this |
| 129 | // we put the smallest atom on the left. |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 130 | class BCECmpBlock { |
Eugene Zelenko | 5c2aece | 2017-10-26 01:25:14 +0000 | [diff] [blame] | 131 | public: |
| 132 | BCECmpBlock() {} |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 133 | |
| 134 | BCECmpBlock(BCEAtom L, BCEAtom R, int SizeBits) |
| 135 | : Lhs_(L), Rhs_(R), SizeBits_(SizeBits) { |
Clement Courbet | 98eaa88 | 2017-10-04 15:13:52 +0000 | [diff] [blame] | 136 | if (Rhs_ < Lhs_) std::swap(Rhs_, Lhs_); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 137 | } |
| 138 | |
| 139 | bool IsValid() const { |
| 140 | return Lhs_.Base() != nullptr && Rhs_.Base() != nullptr; |
| 141 | } |
| 142 | |
Hiroshi Inoue | d24ddcd | 2018-01-19 10:55:29 +0000 | [diff] [blame] | 143 | // Assert the block is consistent: If valid, it should also have |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 144 | // non-null members besides Lhs_ and Rhs_. |
| 145 | void AssertConsistent() const { |
| 146 | if (IsValid()) { |
| 147 | assert(BB); |
| 148 | assert(CmpI); |
| 149 | assert(BranchI); |
| 150 | } |
| 151 | } |
| 152 | |
| 153 | const BCEAtom &Lhs() const { return Lhs_; } |
| 154 | const BCEAtom &Rhs() const { return Rhs_; } |
| 155 | int SizeBits() const { return SizeBits_; } |
| 156 | |
| 157 | // Returns true if the block does other works besides comparison. |
| 158 | bool doesOtherWork() const; |
| 159 | |
Xin Tong | 0efadbb | 2018-04-09 13:14:06 +0000 | [diff] [blame] | 160 | // Returns true if the non-BCE-cmp instructions can be separated from BCE-cmp |
| 161 | // instructions in the block. |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame] | 162 | bool canSplit(AliasAnalysis *AA) const; |
Xin Tong | 0efadbb | 2018-04-09 13:14:06 +0000 | [diff] [blame] | 163 | |
| 164 | // Return true if this all the relevant instructions in the BCE-cmp-block can |
| 165 | // be sunk below this instruction. By doing this, we know we can separate the |
| 166 | // BCE-cmp-block instructions from the non-BCE-cmp-block instructions in the |
| 167 | // block. |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame] | 168 | bool canSinkBCECmpInst(const Instruction *, DenseSet<Instruction *> &, |
| 169 | AliasAnalysis *AA) const; |
Xin Tong | 0efadbb | 2018-04-09 13:14:06 +0000 | [diff] [blame] | 170 | |
| 171 | // We can separate the BCE-cmp-block instructions and the non-BCE-cmp-block |
| 172 | // instructions. Split the old block and move all non-BCE-cmp-insts into the |
| 173 | // new parent block. |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame] | 174 | void split(BasicBlock *NewParent, AliasAnalysis *AA) const; |
Xin Tong | 0efadbb | 2018-04-09 13:14:06 +0000 | [diff] [blame] | 175 | |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 176 | // The basic block where this comparison happens. |
| 177 | BasicBlock *BB = nullptr; |
| 178 | // The ICMP for this comparison. |
| 179 | ICmpInst *CmpI = nullptr; |
| 180 | // The terminating branch. |
| 181 | BranchInst *BranchI = nullptr; |
Xin Tong | 0efadbb | 2018-04-09 13:14:06 +0000 | [diff] [blame] | 182 | // The block requires splitting. |
| 183 | bool RequireSplit = false; |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 184 | |
Xin Tong | 0efadbb | 2018-04-09 13:14:06 +0000 | [diff] [blame] | 185 | private: |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 186 | BCEAtom Lhs_; |
| 187 | BCEAtom Rhs_; |
| 188 | int SizeBits_ = 0; |
| 189 | }; |
| 190 | |
Xin Tong | 0efadbb | 2018-04-09 13:14:06 +0000 | [diff] [blame] | 191 | bool BCECmpBlock::canSinkBCECmpInst(const Instruction *Inst, |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame] | 192 | DenseSet<Instruction *> &BlockInsts, |
| 193 | AliasAnalysis *AA) const { |
Xin Tong | 0efadbb | 2018-04-09 13:14:06 +0000 | [diff] [blame] | 194 | // If this instruction has side effects and its in middle of the BCE cmp block |
| 195 | // instructions, then bail for now. |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame] | 196 | if (Inst->mayHaveSideEffects()) { |
| 197 | // Bail if this is not a simple load or store |
| 198 | if (!isSimpleLoadOrStore(Inst)) |
| 199 | return false; |
| 200 | // Disallow stores that might alias the BCE operands |
| 201 | MemoryLocation LLoc = MemoryLocation::get(Lhs_.LoadI); |
| 202 | MemoryLocation RLoc = MemoryLocation::get(Rhs_.LoadI); |
| 203 | if (isModSet(AA->getModRefInfo(Inst, LLoc)) || |
| 204 | isModSet(AA->getModRefInfo(Inst, RLoc))) |
| 205 | return false; |
| 206 | } |
Xin Tong | 0efadbb | 2018-04-09 13:14:06 +0000 | [diff] [blame] | 207 | // Make sure this instruction does not use any of the BCE cmp block |
| 208 | // instructions as operand. |
| 209 | for (auto BI : BlockInsts) { |
| 210 | if (is_contained(Inst->operands(), BI)) |
| 211 | return false; |
| 212 | } |
| 213 | return true; |
| 214 | } |
| 215 | |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame] | 216 | void BCECmpBlock::split(BasicBlock *NewParent, AliasAnalysis *AA) const { |
Xin Tong | 0efadbb | 2018-04-09 13:14:06 +0000 | [diff] [blame] | 217 | DenseSet<Instruction *> BlockInsts( |
| 218 | {Lhs_.GEP, Rhs_.GEP, Lhs_.LoadI, Rhs_.LoadI, CmpI, BranchI}); |
| 219 | llvm::SmallVector<Instruction *, 4> OtherInsts; |
| 220 | for (Instruction &Inst : *BB) { |
| 221 | if (BlockInsts.count(&Inst)) |
| 222 | continue; |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame] | 223 | assert(canSinkBCECmpInst(&Inst, BlockInsts, AA) && |
| 224 | "Split unsplittable block"); |
Xin Tong | 0efadbb | 2018-04-09 13:14:06 +0000 | [diff] [blame] | 225 | // This is a non-BCE-cmp-block instruction. And it can be separated |
| 226 | // from the BCE-cmp-block instruction. |
| 227 | OtherInsts.push_back(&Inst); |
| 228 | } |
| 229 | |
| 230 | // Do the actual spliting. |
| 231 | for (Instruction *Inst : reverse(OtherInsts)) { |
| 232 | Inst->moveBefore(&*NewParent->begin()); |
| 233 | } |
| 234 | } |
| 235 | |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame] | 236 | bool BCECmpBlock::canSplit(AliasAnalysis *AA) const { |
Xin Tong | 0efadbb | 2018-04-09 13:14:06 +0000 | [diff] [blame] | 237 | DenseSet<Instruction *> BlockInsts( |
| 238 | {Lhs_.GEP, Rhs_.GEP, Lhs_.LoadI, Rhs_.LoadI, CmpI, BranchI}); |
| 239 | for (Instruction &Inst : *BB) { |
| 240 | if (!BlockInsts.count(&Inst)) { |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame] | 241 | if (!canSinkBCECmpInst(&Inst, BlockInsts, AA)) |
Xin Tong | 0efadbb | 2018-04-09 13:14:06 +0000 | [diff] [blame] | 242 | return false; |
| 243 | } |
| 244 | } |
| 245 | return true; |
| 246 | } |
| 247 | |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 248 | bool BCECmpBlock::doesOtherWork() const { |
| 249 | AssertConsistent(); |
Xin Tong | 8fd561f | 2018-03-06 02:24:02 +0000 | [diff] [blame] | 250 | // All the instructions we care about in the BCE cmp block. |
| 251 | DenseSet<Instruction *> BlockInsts( |
| 252 | {Lhs_.GEP, Rhs_.GEP, Lhs_.LoadI, Rhs_.LoadI, CmpI, BranchI}); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 253 | // TODO(courbet): Can we allow some other things ? This is very conservative. |
Hiroshi Inoue | ae17900 | 2018-04-14 08:59:00 +0000 | [diff] [blame] | 254 | // We might be able to get away with anything does not have any side |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 255 | // effects outside of the basic block. |
| 256 | // Note: The GEPs and/or loads are not necessarily in the same block. |
| 257 | for (const Instruction &Inst : *BB) { |
Xin Tong | 8fd561f | 2018-03-06 02:24:02 +0000 | [diff] [blame] | 258 | if (!BlockInsts.count(&Inst)) |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 259 | return true; |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 260 | } |
| 261 | return false; |
| 262 | } |
| 263 | |
| 264 | // Visit the given comparison. If this is a comparison between two valid |
| 265 | // BCE atoms, returns the comparison. |
Eugene Zelenko | 5c2aece | 2017-10-26 01:25:14 +0000 | [diff] [blame] | 266 | BCECmpBlock visitICmp(const ICmpInst *const CmpI, |
| 267 | const ICmpInst::Predicate ExpectedPredicate) { |
Clement Courbet | 9f0b317 | 2018-03-13 07:05:55 +0000 | [diff] [blame] | 268 | // The comparison can only be used once: |
| 269 | // - For intermediate blocks, as a branch condition. |
| 270 | // - For the final block, as an incoming value for the Phi. |
| 271 | // If there are any other uses of the comparison, we cannot merge it with |
| 272 | // other comparisons as we would create an orphan use of the value. |
| 273 | if (!CmpI->hasOneUse()) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 274 | LLVM_DEBUG(dbgs() << "cmp has several uses\n"); |
Clement Courbet | 9f0b317 | 2018-03-13 07:05:55 +0000 | [diff] [blame] | 275 | return {}; |
| 276 | } |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 277 | if (CmpI->getPredicate() == ExpectedPredicate) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 278 | LLVM_DEBUG(dbgs() << "cmp " |
| 279 | << (ExpectedPredicate == ICmpInst::ICMP_EQ ? "eq" : "ne") |
| 280 | << "\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 281 | auto Lhs = visitICmpLoadOperand(CmpI->getOperand(0)); |
Clement Courbet | 98eaa88 | 2017-10-04 15:13:52 +0000 | [diff] [blame] | 282 | if (!Lhs.Base()) return {}; |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 283 | auto Rhs = visitICmpLoadOperand(CmpI->getOperand(1)); |
Clement Courbet | 98eaa88 | 2017-10-04 15:13:52 +0000 | [diff] [blame] | 284 | if (!Rhs.Base()) return {}; |
Christy Lee | 3cc0e93 | 2018-10-26 18:02:06 +0000 | [diff] [blame] | 285 | const auto &DL = CmpI->getModule()->getDataLayout(); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 286 | return BCECmpBlock(std::move(Lhs), std::move(Rhs), |
Christy Lee | 3cc0e93 | 2018-10-26 18:02:06 +0000 | [diff] [blame] | 287 | DL.getTypeSizeInBits(CmpI->getOperand(0)->getType())); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 288 | } |
| 289 | return {}; |
| 290 | } |
| 291 | |
| 292 | // Visit the given comparison block. If this is a comparison between two valid |
| 293 | // BCE atoms, returns the comparison. |
Eugene Zelenko | 5c2aece | 2017-10-26 01:25:14 +0000 | [diff] [blame] | 294 | BCECmpBlock visitCmpBlock(Value *const Val, BasicBlock *const Block, |
| 295 | const BasicBlock *const PhiBlock) { |
Clement Courbet | 98eaa88 | 2017-10-04 15:13:52 +0000 | [diff] [blame] | 296 | if (Block->empty()) return {}; |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 297 | auto *const BranchI = dyn_cast<BranchInst>(Block->getTerminator()); |
Clement Courbet | 98eaa88 | 2017-10-04 15:13:52 +0000 | [diff] [blame] | 298 | if (!BranchI) return {}; |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 299 | LLVM_DEBUG(dbgs() << "branch\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 300 | if (BranchI->isUnconditional()) { |
| 301 | // In this case, we expect an incoming value which is the result of the |
| 302 | // comparison. This is the last link in the chain of comparisons (note |
| 303 | // that this does not mean that this is the last incoming value, blocks |
| 304 | // can be reordered). |
| 305 | auto *const CmpI = dyn_cast<ICmpInst>(Val); |
Clement Courbet | 98eaa88 | 2017-10-04 15:13:52 +0000 | [diff] [blame] | 306 | if (!CmpI) return {}; |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 307 | LLVM_DEBUG(dbgs() << "icmp\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 308 | auto Result = visitICmp(CmpI, ICmpInst::ICMP_EQ); |
| 309 | Result.CmpI = CmpI; |
| 310 | Result.BranchI = BranchI; |
| 311 | return Result; |
| 312 | } else { |
| 313 | // In this case, we expect a constant incoming value (the comparison is |
| 314 | // chained). |
| 315 | const auto *const Const = dyn_cast<ConstantInt>(Val); |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 316 | LLVM_DEBUG(dbgs() << "const\n"); |
Clement Courbet | 98eaa88 | 2017-10-04 15:13:52 +0000 | [diff] [blame] | 317 | if (!Const->isZero()) return {}; |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 318 | LLVM_DEBUG(dbgs() << "false\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 319 | auto *const CmpI = dyn_cast<ICmpInst>(BranchI->getCondition()); |
Clement Courbet | 98eaa88 | 2017-10-04 15:13:52 +0000 | [diff] [blame] | 320 | if (!CmpI) return {}; |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 321 | LLVM_DEBUG(dbgs() << "icmp\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 322 | assert(BranchI->getNumSuccessors() == 2 && "expecting a cond branch"); |
| 323 | BasicBlock *const FalseBlock = BranchI->getSuccessor(1); |
| 324 | auto Result = visitICmp( |
| 325 | CmpI, FalseBlock == PhiBlock ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE); |
| 326 | Result.CmpI = CmpI; |
| 327 | Result.BranchI = BranchI; |
| 328 | return Result; |
| 329 | } |
| 330 | return {}; |
| 331 | } |
| 332 | |
Xin Tong | 0efadbb | 2018-04-09 13:14:06 +0000 | [diff] [blame] | 333 | static inline void enqueueBlock(std::vector<BCECmpBlock> &Comparisons, |
| 334 | BCECmpBlock &Comparison) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 335 | LLVM_DEBUG(dbgs() << "Block '" << Comparison.BB->getName() |
| 336 | << "': Found cmp of " << Comparison.SizeBits() |
| 337 | << " bits between " << Comparison.Lhs().Base() << " + " |
| 338 | << Comparison.Lhs().Offset << " and " |
| 339 | << Comparison.Rhs().Base() << " + " |
| 340 | << Comparison.Rhs().Offset << "\n"); |
| 341 | LLVM_DEBUG(dbgs() << "\n"); |
Xin Tong | 0efadbb | 2018-04-09 13:14:06 +0000 | [diff] [blame] | 342 | Comparisons.push_back(Comparison); |
| 343 | } |
| 344 | |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 345 | // A chain of comparisons. |
| 346 | class BCECmpChain { |
Eugene Zelenko | 5c2aece | 2017-10-26 01:25:14 +0000 | [diff] [blame] | 347 | public: |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame] | 348 | BCECmpChain(const std::vector<BasicBlock *> &Blocks, PHINode &Phi, |
| 349 | AliasAnalysis *AA); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 350 | |
| 351 | int size() const { return Comparisons_.size(); } |
| 352 | |
| 353 | #ifdef MERGEICMPS_DOT_ON |
| 354 | void dump() const; |
| 355 | #endif // MERGEICMPS_DOT_ON |
| 356 | |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame] | 357 | bool simplify(const TargetLibraryInfo *const TLI, AliasAnalysis *AA); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 358 | |
Eugene Zelenko | 5c2aece | 2017-10-26 01:25:14 +0000 | [diff] [blame] | 359 | private: |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 360 | static bool IsContiguous(const BCECmpBlock &First, |
| 361 | const BCECmpBlock &Second) { |
| 362 | return First.Lhs().Base() == Second.Lhs().Base() && |
| 363 | First.Rhs().Base() == Second.Rhs().Base() && |
| 364 | First.Lhs().Offset + First.SizeBits() / 8 == Second.Lhs().Offset && |
| 365 | First.Rhs().Offset + First.SizeBits() / 8 == Second.Rhs().Offset; |
| 366 | } |
| 367 | |
| 368 | // Merges the given comparison blocks into one memcmp block and update |
| 369 | // branches. Comparisons are assumed to be continguous. If NextBBInChain is |
| 370 | // null, the merged block will link to the phi block. |
Xin Tong | 0efadbb | 2018-04-09 13:14:06 +0000 | [diff] [blame] | 371 | void mergeComparisons(ArrayRef<BCECmpBlock> Comparisons, |
| 372 | BasicBlock *const NextBBInChain, PHINode &Phi, |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame] | 373 | const TargetLibraryInfo *const TLI, AliasAnalysis *AA); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 374 | |
| 375 | PHINode &Phi_; |
| 376 | std::vector<BCECmpBlock> Comparisons_; |
| 377 | // The original entry block (before sorting); |
| 378 | BasicBlock *EntryBlock_; |
| 379 | }; |
| 380 | |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame] | 381 | BCECmpChain::BCECmpChain(const std::vector<BasicBlock *> &Blocks, PHINode &Phi, |
| 382 | AliasAnalysis *AA) |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 383 | : Phi_(Phi) { |
Clement Courbet | c2109c8 | 2018-02-06 09:14:00 +0000 | [diff] [blame] | 384 | assert(!Blocks.empty() && "a chain should have at least one block"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 385 | // Now look inside blocks to check for BCE comparisons. |
| 386 | std::vector<BCECmpBlock> Comparisons; |
Clement Courbet | a7a1746 | 2018-02-06 12:25:33 +0000 | [diff] [blame] | 387 | for (size_t BlockIdx = 0; BlockIdx < Blocks.size(); ++BlockIdx) { |
| 388 | BasicBlock *const Block = Blocks[BlockIdx]; |
Clement Courbet | c2109c8 | 2018-02-06 09:14:00 +0000 | [diff] [blame] | 389 | assert(Block && "invalid block"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 390 | BCECmpBlock Comparison = visitCmpBlock(Phi.getIncomingValueForBlock(Block), |
| 391 | Block, Phi.getParent()); |
| 392 | Comparison.BB = Block; |
| 393 | if (!Comparison.IsValid()) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 394 | LLVM_DEBUG(dbgs() << "chain with invalid BCECmpBlock, no merge.\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 395 | return; |
| 396 | } |
| 397 | if (Comparison.doesOtherWork()) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 398 | LLVM_DEBUG(dbgs() << "block '" << Comparison.BB->getName() |
| 399 | << "' does extra work besides compare\n"); |
Xin Tong | 8345c0e | 2018-03-05 13:54:47 +0000 | [diff] [blame] | 400 | if (Comparisons.empty()) { |
Xin Tong | 0efadbb | 2018-04-09 13:14:06 +0000 | [diff] [blame] | 401 | // This is the initial block in the chain, in case this block does other |
| 402 | // work, we can try to split the block and move the irrelevant |
| 403 | // instructions to the predecessor. |
| 404 | // |
| 405 | // If this is not the initial block in the chain, splitting it wont |
| 406 | // work. |
| 407 | // |
| 408 | // As once split, there will still be instructions before the BCE cmp |
| 409 | // instructions that do other work in program order, i.e. within the |
| 410 | // chain before sorting. Unless we can abort the chain at this point |
| 411 | // and start anew. |
| 412 | // |
| 413 | // NOTE: we only handle block with single predecessor for now. |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame] | 414 | if (Comparison.canSplit(AA)) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 415 | LLVM_DEBUG(dbgs() |
| 416 | << "Split initial block '" << Comparison.BB->getName() |
| 417 | << "' that does extra work besides compare\n"); |
Xin Tong | 0efadbb | 2018-04-09 13:14:06 +0000 | [diff] [blame] | 418 | Comparison.RequireSplit = true; |
| 419 | enqueueBlock(Comparisons, Comparison); |
| 420 | } else { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 421 | LLVM_DEBUG(dbgs() |
| 422 | << "ignoring initial block '" << Comparison.BB->getName() |
| 423 | << "' that does extra work besides compare\n"); |
Xin Tong | 0efadbb | 2018-04-09 13:14:06 +0000 | [diff] [blame] | 424 | } |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 425 | continue; |
| 426 | } |
| 427 | // TODO(courbet): Right now we abort the whole chain. We could be |
| 428 | // merging only the blocks that don't do other work and resume the |
| 429 | // chain from there. For example: |
| 430 | // if (a[0] == b[0]) { // bb1 |
| 431 | // if (a[1] == b[1]) { // bb2 |
| 432 | // some_value = 3; //bb3 |
| 433 | // if (a[2] == b[2]) { //bb3 |
| 434 | // do a ton of stuff //bb4 |
| 435 | // } |
| 436 | // } |
| 437 | // } |
| 438 | // |
| 439 | // This is: |
| 440 | // |
| 441 | // bb1 --eq--> bb2 --eq--> bb3* -eq--> bb4 --+ |
| 442 | // \ \ \ \ |
| 443 | // ne ne ne \ |
| 444 | // \ \ \ v |
| 445 | // +------------+-----------+----------> bb_phi |
| 446 | // |
| 447 | // We can only merge the first two comparisons, because bb3* does |
| 448 | // "other work" (setting some_value to 3). |
| 449 | // We could still merge bb1 and bb2 though. |
| 450 | return; |
| 451 | } |
Xin Tong | 0efadbb | 2018-04-09 13:14:06 +0000 | [diff] [blame] | 452 | enqueueBlock(Comparisons, Comparison); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 453 | } |
Xin Tong | 8345c0e | 2018-03-05 13:54:47 +0000 | [diff] [blame] | 454 | |
| 455 | // It is possible we have no suitable comparison to merge. |
| 456 | if (Comparisons.empty()) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 457 | LLVM_DEBUG(dbgs() << "chain with no BCE basic blocks, no merge\n"); |
Xin Tong | 8345c0e | 2018-03-05 13:54:47 +0000 | [diff] [blame] | 458 | return; |
| 459 | } |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 460 | EntryBlock_ = Comparisons[0].BB; |
| 461 | Comparisons_ = std::move(Comparisons); |
| 462 | #ifdef MERGEICMPS_DOT_ON |
| 463 | errs() << "BEFORE REORDERING:\n\n"; |
| 464 | dump(); |
| 465 | #endif // MERGEICMPS_DOT_ON |
| 466 | // Reorder blocks by LHS. We can do that without changing the |
| 467 | // semantics because we are only accessing dereferencable memory. |
Fangrui Song | 0cac726 | 2018-09-27 02:13:45 +0000 | [diff] [blame] | 468 | llvm::sort(Comparisons_, [](const BCECmpBlock &a, const BCECmpBlock &b) { |
| 469 | return a.Lhs() < b.Lhs(); |
| 470 | }); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 471 | #ifdef MERGEICMPS_DOT_ON |
| 472 | errs() << "AFTER REORDERING:\n\n"; |
| 473 | dump(); |
| 474 | #endif // MERGEICMPS_DOT_ON |
| 475 | } |
| 476 | |
| 477 | #ifdef MERGEICMPS_DOT_ON |
| 478 | void BCECmpChain::dump() const { |
| 479 | errs() << "digraph dag {\n"; |
| 480 | errs() << " graph [bgcolor=transparent];\n"; |
| 481 | errs() << " node [color=black,style=filled,fillcolor=lightyellow];\n"; |
| 482 | errs() << " edge [color=black];\n"; |
| 483 | for (size_t I = 0; I < Comparisons_.size(); ++I) { |
| 484 | const auto &Comparison = Comparisons_[I]; |
| 485 | errs() << " \"" << I << "\" [label=\"%" |
| 486 | << Comparison.Lhs().Base()->getName() << " + " |
| 487 | << Comparison.Lhs().Offset << " == %" |
| 488 | << Comparison.Rhs().Base()->getName() << " + " |
| 489 | << Comparison.Rhs().Offset << " (" << (Comparison.SizeBits() / 8) |
| 490 | << " bytes)\"];\n"; |
| 491 | const Value *const Val = Phi_.getIncomingValueForBlock(Comparison.BB); |
Clement Courbet | 98eaa88 | 2017-10-04 15:13:52 +0000 | [diff] [blame] | 492 | if (I > 0) errs() << " \"" << (I - 1) << "\" -> \"" << I << "\";\n"; |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 493 | errs() << " \"" << I << "\" -> \"Phi\" [label=\"" << *Val << "\"];\n"; |
| 494 | } |
| 495 | errs() << " \"Phi\" [label=\"Phi\"];\n"; |
| 496 | errs() << "}\n\n"; |
| 497 | } |
| 498 | #endif // MERGEICMPS_DOT_ON |
| 499 | |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame] | 500 | bool BCECmpChain::simplify(const TargetLibraryInfo *const TLI, |
| 501 | AliasAnalysis *AA) { |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 502 | // First pass to check if there is at least one merge. If not, we don't do |
| 503 | // anything and we keep analysis passes intact. |
| 504 | { |
| 505 | bool AtLeastOneMerged = false; |
| 506 | for (size_t I = 1; I < Comparisons_.size(); ++I) { |
| 507 | if (IsContiguous(Comparisons_[I - 1], Comparisons_[I])) { |
| 508 | AtLeastOneMerged = true; |
| 509 | break; |
| 510 | } |
| 511 | } |
Clement Courbet | 98eaa88 | 2017-10-04 15:13:52 +0000 | [diff] [blame] | 512 | if (!AtLeastOneMerged) return false; |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 513 | } |
| 514 | |
| 515 | // Remove phi references to comparison blocks, they will be rebuilt as we |
| 516 | // merge the blocks. |
| 517 | for (const auto &Comparison : Comparisons_) { |
| 518 | Phi_.removeIncomingValue(Comparison.BB, false); |
| 519 | } |
| 520 | |
Xin Tong | bdbd97e | 2018-03-20 11:57:54 +0000 | [diff] [blame] | 521 | // If entry block is part of the chain, we need to make the first block |
| 522 | // of the chain the new entry block of the function. |
| 523 | BasicBlock *Entry = &Comparisons_[0].BB->getParent()->getEntryBlock(); |
| 524 | for (size_t I = 1; I < Comparisons_.size(); ++I) { |
| 525 | if (Entry == Comparisons_[I].BB) { |
| 526 | BasicBlock *NEntryBB = BasicBlock::Create(Entry->getContext(), "", |
| 527 | Entry->getParent(), Entry); |
| 528 | BranchInst::Create(Entry, NEntryBB); |
Xin Tong | a713ebe | 2018-03-20 12:03:25 +0000 | [diff] [blame] | 529 | break; |
Xin Tong | bdbd97e | 2018-03-20 11:57:54 +0000 | [diff] [blame] | 530 | } |
| 531 | } |
| 532 | |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 533 | // Point the predecessors of the chain to the first comparison block (which is |
Xin Tong | 0efadbb | 2018-04-09 13:14:06 +0000 | [diff] [blame] | 534 | // the new entry point) and update the entry block of the chain. |
| 535 | if (EntryBlock_ != Comparisons_[0].BB) { |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 536 | EntryBlock_->replaceAllUsesWith(Comparisons_[0].BB); |
Xin Tong | 0efadbb | 2018-04-09 13:14:06 +0000 | [diff] [blame] | 537 | EntryBlock_ = Comparisons_[0].BB; |
| 538 | } |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 539 | |
| 540 | // Effectively merge blocks. |
| 541 | int NumMerged = 1; |
| 542 | for (size_t I = 1; I < Comparisons_.size(); ++I) { |
| 543 | if (IsContiguous(Comparisons_[I - 1], Comparisons_[I])) { |
| 544 | ++NumMerged; |
| 545 | } else { |
| 546 | // Merge all previous comparisons and start a new merge block. |
| 547 | mergeComparisons( |
| 548 | makeArrayRef(Comparisons_).slice(I - NumMerged, NumMerged), |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame] | 549 | Comparisons_[I].BB, Phi_, TLI, AA); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 550 | NumMerged = 1; |
| 551 | } |
| 552 | } |
| 553 | mergeComparisons(makeArrayRef(Comparisons_) |
| 554 | .slice(Comparisons_.size() - NumMerged, NumMerged), |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame] | 555 | nullptr, Phi_, TLI, AA); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 556 | |
| 557 | return true; |
| 558 | } |
| 559 | |
| 560 | void BCECmpChain::mergeComparisons(ArrayRef<BCECmpBlock> Comparisons, |
| 561 | BasicBlock *const NextBBInChain, |
| 562 | PHINode &Phi, |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame] | 563 | const TargetLibraryInfo *const TLI, |
| 564 | AliasAnalysis *AA) { |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 565 | assert(!Comparisons.empty()); |
| 566 | const auto &FirstComparison = *Comparisons.begin(); |
| 567 | BasicBlock *const BB = FirstComparison.BB; |
| 568 | LLVMContext &Context = BB->getContext(); |
| 569 | |
| 570 | if (Comparisons.size() >= 2) { |
Xin Tong | 0efadbb | 2018-04-09 13:14:06 +0000 | [diff] [blame] | 571 | // If there is one block that requires splitting, we do it now, i.e. |
| 572 | // just before we know we will collapse the chain. The instructions |
| 573 | // can be executed before any of the instructions in the chain. |
| 574 | auto C = std::find_if(Comparisons.begin(), Comparisons.end(), |
| 575 | [](const BCECmpBlock &B) { return B.RequireSplit; }); |
| 576 | if (C != Comparisons.end()) |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame] | 577 | C->split(EntryBlock_, AA); |
Xin Tong | 0efadbb | 2018-04-09 13:14:06 +0000 | [diff] [blame] | 578 | |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 579 | LLVM_DEBUG(dbgs() << "Merging " << Comparisons.size() << " comparisons\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 580 | const auto TotalSize = |
| 581 | std::accumulate(Comparisons.begin(), Comparisons.end(), 0, |
| 582 | [](int Size, const BCECmpBlock &C) { |
| 583 | return Size + C.SizeBits(); |
| 584 | }) / |
| 585 | 8; |
| 586 | |
| 587 | // Incoming edges do not need to be updated, and both GEPs are already |
| 588 | // computing the right address, we just need to: |
| 589 | // - replace the two loads and the icmp with the memcmp |
| 590 | // - update the branch |
| 591 | // - update the incoming values in the phi. |
| 592 | FirstComparison.BranchI->eraseFromParent(); |
| 593 | FirstComparison.CmpI->eraseFromParent(); |
| 594 | FirstComparison.Lhs().LoadI->eraseFromParent(); |
| 595 | FirstComparison.Rhs().LoadI->eraseFromParent(); |
| 596 | |
| 597 | IRBuilder<> Builder(BB); |
| 598 | const auto &DL = Phi.getModule()->getDataLayout(); |
Clement Courbet | e2e8a5c | 2017-10-10 08:00:45 +0000 | [diff] [blame] | 599 | Value *const MemCmpCall = emitMemCmp( |
Xin Tong | 0272cb0 | 2018-03-27 19:43:02 +0000 | [diff] [blame] | 600 | FirstComparison.Lhs().GEP, FirstComparison.Rhs().GEP, |
| 601 | ConstantInt::get(DL.getIntPtrType(Context), TotalSize), |
Clement Courbet | e2e8a5c | 2017-10-10 08:00:45 +0000 | [diff] [blame] | 602 | Builder, DL, TLI); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 603 | Value *const MemCmpIsZero = Builder.CreateICmpEQ( |
| 604 | MemCmpCall, ConstantInt::get(Type::getInt32Ty(Context), 0)); |
| 605 | |
| 606 | // Add a branch to the next basic block in the chain. |
| 607 | if (NextBBInChain) { |
| 608 | Builder.CreateCondBr(MemCmpIsZero, NextBBInChain, Phi.getParent()); |
| 609 | Phi.addIncoming(ConstantInt::getFalse(Context), BB); |
| 610 | } else { |
| 611 | Builder.CreateBr(Phi.getParent()); |
| 612 | Phi.addIncoming(MemCmpIsZero, BB); |
| 613 | } |
| 614 | |
| 615 | // Delete merged blocks. |
| 616 | for (size_t I = 1; I < Comparisons.size(); ++I) { |
| 617 | BasicBlock *CBB = Comparisons[I].BB; |
| 618 | CBB->replaceAllUsesWith(BB); |
| 619 | CBB->eraseFromParent(); |
| 620 | } |
| 621 | } else { |
| 622 | assert(Comparisons.size() == 1); |
| 623 | // There are no blocks to merge, but we still need to update the branches. |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 624 | LLVM_DEBUG(dbgs() << "Only one comparison, updating branches\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 625 | if (NextBBInChain) { |
| 626 | if (FirstComparison.BranchI->isConditional()) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 627 | LLVM_DEBUG(dbgs() << "conditional -> conditional\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 628 | // Just update the "true" target, the "false" target should already be |
| 629 | // the phi block. |
| 630 | assert(FirstComparison.BranchI->getSuccessor(1) == Phi.getParent()); |
| 631 | FirstComparison.BranchI->setSuccessor(0, NextBBInChain); |
| 632 | Phi.addIncoming(ConstantInt::getFalse(Context), BB); |
| 633 | } else { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 634 | LLVM_DEBUG(dbgs() << "unconditional -> conditional\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 635 | // Replace the unconditional branch by a conditional one. |
| 636 | FirstComparison.BranchI->eraseFromParent(); |
| 637 | IRBuilder<> Builder(BB); |
| 638 | Builder.CreateCondBr(FirstComparison.CmpI, NextBBInChain, |
| 639 | Phi.getParent()); |
| 640 | Phi.addIncoming(FirstComparison.CmpI, BB); |
| 641 | } |
| 642 | } else { |
| 643 | if (FirstComparison.BranchI->isConditional()) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 644 | LLVM_DEBUG(dbgs() << "conditional -> unconditional\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 645 | // Replace the conditional branch by an unconditional one. |
| 646 | FirstComparison.BranchI->eraseFromParent(); |
| 647 | IRBuilder<> Builder(BB); |
| 648 | Builder.CreateBr(Phi.getParent()); |
| 649 | Phi.addIncoming(FirstComparison.CmpI, BB); |
| 650 | } else { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 651 | LLVM_DEBUG(dbgs() << "unconditional -> unconditional\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 652 | Phi.addIncoming(FirstComparison.CmpI, BB); |
| 653 | } |
| 654 | } |
| 655 | } |
| 656 | } |
| 657 | |
Eugene Zelenko | 5c2aece | 2017-10-26 01:25:14 +0000 | [diff] [blame] | 658 | std::vector<BasicBlock *> getOrderedBlocks(PHINode &Phi, |
| 659 | BasicBlock *const LastBlock, |
| 660 | int NumBlocks) { |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 661 | // Walk up from the last block to find other blocks. |
| 662 | std::vector<BasicBlock *> Blocks(NumBlocks); |
Clement Courbet | c2109c8 | 2018-02-06 09:14:00 +0000 | [diff] [blame] | 663 | assert(LastBlock && "invalid last block"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 664 | BasicBlock *CurBlock = LastBlock; |
| 665 | for (int BlockIndex = NumBlocks - 1; BlockIndex > 0; --BlockIndex) { |
| 666 | if (CurBlock->hasAddressTaken()) { |
| 667 | // Somebody is jumping to the block through an address, all bets are |
| 668 | // off. |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 669 | LLVM_DEBUG(dbgs() << "skip: block " << BlockIndex |
| 670 | << " has its address taken\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 671 | return {}; |
| 672 | } |
| 673 | Blocks[BlockIndex] = CurBlock; |
| 674 | auto *SinglePredecessor = CurBlock->getSinglePredecessor(); |
| 675 | if (!SinglePredecessor) { |
| 676 | // The block has two or more predecessors. |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 677 | LLVM_DEBUG(dbgs() << "skip: block " << BlockIndex |
| 678 | << " has two or more predecessors\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 679 | return {}; |
| 680 | } |
| 681 | if (Phi.getBasicBlockIndex(SinglePredecessor) < 0) { |
| 682 | // The block does not link back to the phi. |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 683 | LLVM_DEBUG(dbgs() << "skip: block " << BlockIndex |
| 684 | << " does not link back to the phi\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 685 | return {}; |
| 686 | } |
| 687 | CurBlock = SinglePredecessor; |
| 688 | } |
| 689 | Blocks[0] = CurBlock; |
| 690 | return Blocks; |
| 691 | } |
| 692 | |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame] | 693 | bool processPhi(PHINode &Phi, const TargetLibraryInfo *const TLI, |
| 694 | AliasAnalysis *AA) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 695 | LLVM_DEBUG(dbgs() << "processPhi()\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 696 | if (Phi.getNumIncomingValues() <= 1) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 697 | LLVM_DEBUG(dbgs() << "skip: only one incoming value in phi\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 698 | return false; |
| 699 | } |
| 700 | // We are looking for something that has the following structure: |
| 701 | // bb1 --eq--> bb2 --eq--> bb3 --eq--> bb4 --+ |
| 702 | // \ \ \ \ |
| 703 | // ne ne ne \ |
| 704 | // \ \ \ v |
| 705 | // +------------+-----------+----------> bb_phi |
| 706 | // |
| 707 | // - The last basic block (bb4 here) must branch unconditionally to bb_phi. |
| 708 | // It's the only block that contributes a non-constant value to the Phi. |
| 709 | // - All other blocks (b1, b2, b3) must have exactly two successors, one of |
Hiroshi Inoue | d24ddcd | 2018-01-19 10:55:29 +0000 | [diff] [blame] | 710 | // them being the phi block. |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 711 | // - All intermediate blocks (bb2, bb3) must have only one predecessor. |
| 712 | // - Blocks cannot do other work besides the comparison, see doesOtherWork() |
| 713 | |
| 714 | // The blocks are not necessarily ordered in the phi, so we start from the |
| 715 | // last block and reconstruct the order. |
| 716 | BasicBlock *LastBlock = nullptr; |
| 717 | for (unsigned I = 0; I < Phi.getNumIncomingValues(); ++I) { |
Clement Courbet | 98eaa88 | 2017-10-04 15:13:52 +0000 | [diff] [blame] | 718 | if (isa<ConstantInt>(Phi.getIncomingValue(I))) continue; |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 719 | if (LastBlock) { |
| 720 | // There are several non-constant values. |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 721 | LLVM_DEBUG(dbgs() << "skip: several non-constant values\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 722 | return false; |
| 723 | } |
Xin Tong | 8ba674e | 2018-02-28 12:08:00 +0000 | [diff] [blame] | 724 | if (!isa<ICmpInst>(Phi.getIncomingValue(I)) || |
| 725 | cast<ICmpInst>(Phi.getIncomingValue(I))->getParent() != |
| 726 | Phi.getIncomingBlock(I)) { |
| 727 | // Non-constant incoming value is not from a cmp instruction or not |
| 728 | // produced by the last block. We could end up processing the value |
| 729 | // producing block more than once. |
| 730 | // |
| 731 | // This is an uncommon case, so we bail. |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 732 | LLVM_DEBUG( |
Xin Tong | 8ba674e | 2018-02-28 12:08:00 +0000 | [diff] [blame] | 733 | dbgs() |
| 734 | << "skip: non-constant value not from cmp or not from last block.\n"); |
| 735 | return false; |
| 736 | } |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 737 | LastBlock = Phi.getIncomingBlock(I); |
| 738 | } |
| 739 | if (!LastBlock) { |
| 740 | // There is no non-constant block. |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 741 | LLVM_DEBUG(dbgs() << "skip: no non-constant block\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 742 | return false; |
| 743 | } |
| 744 | if (LastBlock->getSingleSuccessor() != Phi.getParent()) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 745 | LLVM_DEBUG(dbgs() << "skip: last block non-phi successor\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 746 | return false; |
| 747 | } |
| 748 | |
| 749 | const auto Blocks = |
| 750 | getOrderedBlocks(Phi, LastBlock, Phi.getNumIncomingValues()); |
Clement Courbet | 98eaa88 | 2017-10-04 15:13:52 +0000 | [diff] [blame] | 751 | if (Blocks.empty()) return false; |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame] | 752 | BCECmpChain CmpChain(Blocks, Phi, AA); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 753 | |
| 754 | if (CmpChain.size() < 2) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 755 | LLVM_DEBUG(dbgs() << "skip: only one compare block\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 756 | return false; |
| 757 | } |
| 758 | |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame] | 759 | return CmpChain.simplify(TLI, AA); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 760 | } |
| 761 | |
| 762 | class MergeICmps : public FunctionPass { |
Eugene Zelenko | 5c2aece | 2017-10-26 01:25:14 +0000 | [diff] [blame] | 763 | public: |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 764 | static char ID; |
| 765 | |
| 766 | MergeICmps() : FunctionPass(ID) { |
| 767 | initializeMergeICmpsPass(*PassRegistry::getPassRegistry()); |
| 768 | } |
| 769 | |
| 770 | bool runOnFunction(Function &F) override { |
| 771 | if (skipFunction(F)) return false; |
| 772 | const auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); |
Clement Courbet | e2e8a5c | 2017-10-10 08:00:45 +0000 | [diff] [blame] | 773 | const auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame] | 774 | AliasAnalysis *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); |
| 775 | auto PA = runImpl(F, &TLI, &TTI, AA); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 776 | return !PA.areAllPreserved(); |
| 777 | } |
| 778 | |
Eugene Zelenko | 5c2aece | 2017-10-26 01:25:14 +0000 | [diff] [blame] | 779 | private: |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 780 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
| 781 | AU.addRequired<TargetLibraryInfoWrapperPass>(); |
Clement Courbet | e2e8a5c | 2017-10-10 08:00:45 +0000 | [diff] [blame] | 782 | AU.addRequired<TargetTransformInfoWrapperPass>(); |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame] | 783 | AU.addRequired<AAResultsWrapperPass>(); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 784 | } |
| 785 | |
Clement Courbet | e2e8a5c | 2017-10-10 08:00:45 +0000 | [diff] [blame] | 786 | PreservedAnalyses runImpl(Function &F, const TargetLibraryInfo *TLI, |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame] | 787 | const TargetTransformInfo *TTI, AliasAnalysis *AA); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 788 | }; |
| 789 | |
Clement Courbet | e2e8a5c | 2017-10-10 08:00:45 +0000 | [diff] [blame] | 790 | PreservedAnalyses MergeICmps::runImpl(Function &F, const TargetLibraryInfo *TLI, |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame] | 791 | const TargetTransformInfo *TTI, |
| 792 | AliasAnalysis *AA) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 793 | LLVM_DEBUG(dbgs() << "MergeICmpsPass: " << F.getName() << "\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 794 | |
Clement Courbet | e2e8a5c | 2017-10-10 08:00:45 +0000 | [diff] [blame] | 795 | // We only try merging comparisons if the target wants to expand memcmp later. |
| 796 | // The rationale is to avoid turning small chains into memcmp calls. |
Clement Courbet | b2c3eb8 | 2017-10-30 14:19:33 +0000 | [diff] [blame] | 797 | if (!TTI->enableMemCmpExpansion(true)) return PreservedAnalyses::all(); |
Clement Courbet | e2e8a5c | 2017-10-10 08:00:45 +0000 | [diff] [blame] | 798 | |
Benjamin Kramer | a76b64f | 2018-05-19 12:51:59 +0000 | [diff] [blame] | 799 | // If we don't have memcmp avaiable we can't emit calls to it. |
| 800 | if (!TLI->has(LibFunc_memcmp)) |
| 801 | return PreservedAnalyses::all(); |
| 802 | |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 803 | bool MadeChange = false; |
| 804 | |
| 805 | for (auto BBIt = ++F.begin(); BBIt != F.end(); ++BBIt) { |
| 806 | // A Phi operation is always first in a basic block. |
| 807 | if (auto *const Phi = dyn_cast<PHINode>(&*BBIt->begin())) |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame] | 808 | MadeChange |= processPhi(*Phi, TLI, AA); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 809 | } |
| 810 | |
Clement Courbet | 98eaa88 | 2017-10-04 15:13:52 +0000 | [diff] [blame] | 811 | if (MadeChange) return PreservedAnalyses::none(); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 812 | return PreservedAnalyses::all(); |
| 813 | } |
| 814 | |
Eugene Zelenko | 5c2aece | 2017-10-26 01:25:14 +0000 | [diff] [blame] | 815 | } // namespace |
Eugene Zelenko | 5adb96c | 2017-10-26 00:55:39 +0000 | [diff] [blame] | 816 | |
Eugene Zelenko | 5c2aece | 2017-10-26 01:25:14 +0000 | [diff] [blame] | 817 | char MergeICmps::ID = 0; |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 818 | INITIALIZE_PASS_BEGIN(MergeICmps, "mergeicmps", |
| 819 | "Merge contiguous icmps into a memcmp", false, false) |
| 820 | INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) |
Clement Courbet | e2e8a5c | 2017-10-10 08:00:45 +0000 | [diff] [blame] | 821 | INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame] | 822 | INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 823 | INITIALIZE_PASS_END(MergeICmps, "mergeicmps", |
| 824 | "Merge contiguous icmps into a memcmp", false, false) |
| 825 | |
| 826 | Pass *llvm::createMergeICmpsPass() { return new MergeICmps(); } |