Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 1 | //===- MergeICmps.cpp - Optimize chains of integer comparisons ------------===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // This pass turns chains of integer comparisons into memcmp (the memcmp is |
| 11 | // later typically inlined as a chain of efficient hardware comparisons). This |
| 12 | // typically benefits c++ member or nonmember operator==(). |
| 13 | // |
| 14 | // The basic idea is to replace a larger chain of integer comparisons loaded |
| 15 | // from contiguous memory locations into a smaller chain of such integer |
| 16 | // comparisons. Benefits are double: |
| 17 | // - There are less jumps, and therefore less opportunities for mispredictions |
| 18 | // and I-cache misses. |
| 19 | // - Code size is smaller, both because jumps are removed and because the |
| 20 | // encoding of a 2*n byte compare is smaller than that of two n-byte |
| 21 | // compares. |
Eugene Zelenko | 5adb96c | 2017-10-26 00:55:39 +0000 | [diff] [blame^] | 22 | // |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 23 | //===----------------------------------------------------------------------===// |
| 24 | |
Eugene Zelenko | 5adb96c | 2017-10-26 00:55:39 +0000 | [diff] [blame^] | 25 | #include "llvm/ADT/APInt.h" |
| 26 | #include "llvm/ADT/ArrayRef.h" |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 27 | #include "llvm/Analysis/Loads.h" |
Clement Courbet | e2e8a5c | 2017-10-10 08:00:45 +0000 | [diff] [blame] | 28 | #include "llvm/Analysis/TargetLibraryInfo.h" |
| 29 | #include "llvm/Analysis/TargetTransformInfo.h" |
Eugene Zelenko | 5adb96c | 2017-10-26 00:55:39 +0000 | [diff] [blame^] | 30 | #include "llvm/IR/BasicBlock.h" |
| 31 | #include "llvm/IR/Constants.h" |
| 32 | #include "llvm/IR/DataLayout.h" |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 33 | #include "llvm/IR/Function.h" |
| 34 | #include "llvm/IR/IRBuilder.h" |
Eugene Zelenko | 5adb96c | 2017-10-26 00:55:39 +0000 | [diff] [blame^] | 35 | #include "llvm/IR/Instruction.h" |
| 36 | #include "llvm/IR/Instructions.h" |
| 37 | #include "llvm/IR/Module.h" |
| 38 | #include "llvm/IR/PassManager.h" |
| 39 | #include "llvm/IR/Type.h" |
| 40 | #include "llvm/IR/Value.h" |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 41 | #include "llvm/Pass.h" |
Eugene Zelenko | 5adb96c | 2017-10-26 00:55:39 +0000 | [diff] [blame^] | 42 | #include "llvm/Support/Casting.h" |
| 43 | #include "llvm/Support/Debug.h" |
| 44 | #include "llvm/Support/raw_ostream.h" |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 45 | #include "llvm/Transforms/Scalar.h" |
| 46 | #include "llvm/Transforms/Utils/BuildLibCalls.h" |
Eugene Zelenko | 5adb96c | 2017-10-26 00:55:39 +0000 | [diff] [blame^] | 47 | #include <algorithm> |
| 48 | #include <cassert> |
| 49 | #include <cstddef> |
| 50 | #include <numeric> |
| 51 | #include <utility> |
| 52 | #include <vector> |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 53 | |
| 54 | using namespace llvm; |
| 55 | |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 56 | #define DEBUG_TYPE "mergeicmps" |
| 57 | |
Eugene Zelenko | 5adb96c | 2017-10-26 00:55:39 +0000 | [diff] [blame^] | 58 | namespace { |
| 59 | |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 60 | // A BCE atom. |
| 61 | struct BCEAtom { |
Eugene Zelenko | 5adb96c | 2017-10-26 00:55:39 +0000 | [diff] [blame^] | 62 | BCEAtom() = default; |
Clement Courbet | bc0c445 | 2017-09-01 11:51:23 +0000 | [diff] [blame] | 63 | |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 64 | const Value *Base() const { return GEP ? GEP->getPointerOperand() : nullptr; } |
| 65 | |
| 66 | bool operator<(const BCEAtom &O) const { |
Clement Courbet | e2e8a5c | 2017-10-10 08:00:45 +0000 | [diff] [blame] | 67 | assert(Base() && "invalid atom"); |
| 68 | assert(O.Base() && "invalid atom"); |
| 69 | // Just ordering by (Base(), Offset) is sufficient. However because this |
| 70 | // means that the ordering will depend on the addresses of the base |
| 71 | // values, which are not reproducible from run to run. To guarantee |
| 72 | // stability, we use the names of the values if they exist; we sort by: |
| 73 | // (Base.getName(), Base(), Offset). |
| 74 | const int NameCmp = Base()->getName().compare(O.Base()->getName()); |
| 75 | if (NameCmp == 0) { |
| 76 | if (Base() == O.Base()) { |
| 77 | return Offset.slt(O.Offset); |
| 78 | } |
| 79 | return Base() < O.Base(); |
| 80 | } |
| 81 | return NameCmp < 0; |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 82 | } |
| 83 | |
Eugene Zelenko | 5adb96c | 2017-10-26 00:55:39 +0000 | [diff] [blame^] | 84 | GetElementPtrInst *GEP = nullptr; |
| 85 | LoadInst *LoadI = nullptr; |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 86 | APInt Offset; |
| 87 | }; |
| 88 | |
Eugene Zelenko | 5adb96c | 2017-10-26 00:55:39 +0000 | [diff] [blame^] | 89 | } // end anonymous namespace |
| 90 | |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 91 | // If this value is a load from a constant offset w.r.t. a base address, and |
| 92 | // there are no othe rusers of the load or address, returns the base address and |
| 93 | // the offset. |
Eugene Zelenko | 5adb96c | 2017-10-26 00:55:39 +0000 | [diff] [blame^] | 94 | static BCEAtom visitICmpLoadOperand(Value *const Val) { |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 95 | BCEAtom Result; |
| 96 | if (auto *const LoadI = dyn_cast<LoadInst>(Val)) { |
| 97 | DEBUG(dbgs() << "load\n"); |
| 98 | if (LoadI->isUsedOutsideOfBlock(LoadI->getParent())) { |
| 99 | DEBUG(dbgs() << "used outside of block\n"); |
| 100 | return {}; |
| 101 | } |
| 102 | if (LoadI->isVolatile()) { |
| 103 | DEBUG(dbgs() << "volatile\n"); |
| 104 | return {}; |
| 105 | } |
| 106 | Value *const Addr = LoadI->getOperand(0); |
| 107 | if (auto *const GEP = dyn_cast<GetElementPtrInst>(Addr)) { |
| 108 | DEBUG(dbgs() << "GEP\n"); |
| 109 | if (LoadI->isUsedOutsideOfBlock(LoadI->getParent())) { |
| 110 | DEBUG(dbgs() << "used outside of block\n"); |
| 111 | return {}; |
| 112 | } |
| 113 | const auto &DL = GEP->getModule()->getDataLayout(); |
| 114 | if (!isDereferenceablePointer(GEP, DL)) { |
| 115 | DEBUG(dbgs() << "not dereferenceable\n"); |
| 116 | // We need to make sure that we can do comparison in any order, so we |
| 117 | // require memory to be unconditionnally dereferencable. |
| 118 | return {}; |
| 119 | } |
| 120 | Result.Offset = APInt(DL.getPointerTypeSizeInBits(GEP->getType()), 0); |
| 121 | if (GEP->accumulateConstantOffset(DL, Result.Offset)) { |
| 122 | Result.GEP = GEP; |
| 123 | Result.LoadI = LoadI; |
| 124 | } |
| 125 | } |
| 126 | } |
| 127 | return Result; |
| 128 | } |
| 129 | |
Eugene Zelenko | 5adb96c | 2017-10-26 00:55:39 +0000 | [diff] [blame^] | 130 | namespace { |
| 131 | |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 132 | // A basic block with a comparison between two BCE atoms. |
| 133 | // Note: the terminology is misleading: the comparison is symmetric, so there |
Clement Courbet | e2e8a5c | 2017-10-10 08:00:45 +0000 | [diff] [blame] | 134 | // is no real {l/r}hs. What we want though is to have the same base on the |
| 135 | // left (resp. right), so that we can detect consecutive loads. To ensure this |
| 136 | // we put the smallest atom on the left. |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 137 | class BCECmpBlock { |
Eugene Zelenko | 5adb96c | 2017-10-26 00:55:39 +0000 | [diff] [blame^] | 138 | public: |
| 139 | BCECmpBlock() = default; |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 140 | |
| 141 | BCECmpBlock(BCEAtom L, BCEAtom R, int SizeBits) |
| 142 | : Lhs_(L), Rhs_(R), SizeBits_(SizeBits) { |
Clement Courbet | 98eaa88 | 2017-10-04 15:13:52 +0000 | [diff] [blame] | 143 | if (Rhs_ < Lhs_) std::swap(Rhs_, Lhs_); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 144 | } |
| 145 | |
| 146 | bool IsValid() const { |
| 147 | return Lhs_.Base() != nullptr && Rhs_.Base() != nullptr; |
| 148 | } |
| 149 | |
| 150 | // Assert the the block is consistent: If valid, it should also have |
| 151 | // non-null members besides Lhs_ and Rhs_. |
| 152 | void AssertConsistent() const { |
| 153 | if (IsValid()) { |
| 154 | assert(BB); |
| 155 | assert(CmpI); |
| 156 | assert(BranchI); |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | const BCEAtom &Lhs() const { return Lhs_; } |
| 161 | const BCEAtom &Rhs() const { return Rhs_; } |
| 162 | int SizeBits() const { return SizeBits_; } |
| 163 | |
| 164 | // Returns true if the block does other works besides comparison. |
| 165 | bool doesOtherWork() const; |
| 166 | |
| 167 | // The basic block where this comparison happens. |
| 168 | BasicBlock *BB = nullptr; |
Eugene Zelenko | 5adb96c | 2017-10-26 00:55:39 +0000 | [diff] [blame^] | 169 | |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 170 | // The ICMP for this comparison. |
| 171 | ICmpInst *CmpI = nullptr; |
Eugene Zelenko | 5adb96c | 2017-10-26 00:55:39 +0000 | [diff] [blame^] | 172 | |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 173 | // The terminating branch. |
| 174 | BranchInst *BranchI = nullptr; |
| 175 | |
Eugene Zelenko | 5adb96c | 2017-10-26 00:55:39 +0000 | [diff] [blame^] | 176 | private: |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 177 | BCEAtom Lhs_; |
| 178 | BCEAtom Rhs_; |
| 179 | int SizeBits_ = 0; |
| 180 | }; |
| 181 | |
Eugene Zelenko | 5adb96c | 2017-10-26 00:55:39 +0000 | [diff] [blame^] | 182 | } // end anonymous namespace |
| 183 | |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 184 | bool BCECmpBlock::doesOtherWork() const { |
| 185 | AssertConsistent(); |
| 186 | // TODO(courbet): Can we allow some other things ? This is very conservative. |
| 187 | // We might be able to get away with anything does does not have any side |
| 188 | // effects outside of the basic block. |
| 189 | // Note: The GEPs and/or loads are not necessarily in the same block. |
| 190 | for (const Instruction &Inst : *BB) { |
| 191 | if (const auto *const GEP = dyn_cast<GetElementPtrInst>(&Inst)) { |
Clement Courbet | 98eaa88 | 2017-10-04 15:13:52 +0000 | [diff] [blame] | 192 | if (!(Lhs_.GEP == GEP || Rhs_.GEP == GEP)) return true; |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 193 | } else if (const auto *const L = dyn_cast<LoadInst>(&Inst)) { |
Clement Courbet | 98eaa88 | 2017-10-04 15:13:52 +0000 | [diff] [blame] | 194 | if (!(Lhs_.LoadI == L || Rhs_.LoadI == L)) return true; |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 195 | } else if (const auto *const C = dyn_cast<ICmpInst>(&Inst)) { |
Clement Courbet | 98eaa88 | 2017-10-04 15:13:52 +0000 | [diff] [blame] | 196 | if (C != CmpI) return true; |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 197 | } else if (const auto *const Br = dyn_cast<BranchInst>(&Inst)) { |
Clement Courbet | 98eaa88 | 2017-10-04 15:13:52 +0000 | [diff] [blame] | 198 | if (Br != BranchI) return true; |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 199 | } else { |
| 200 | return true; |
| 201 | } |
| 202 | } |
| 203 | return false; |
| 204 | } |
| 205 | |
| 206 | // Visit the given comparison. If this is a comparison between two valid |
| 207 | // BCE atoms, returns the comparison. |
Eugene Zelenko | 5adb96c | 2017-10-26 00:55:39 +0000 | [diff] [blame^] | 208 | static BCECmpBlock visitICmp(const ICmpInst *const CmpI, |
| 209 | const ICmpInst::Predicate ExpectedPredicate) { |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 210 | if (CmpI->getPredicate() == ExpectedPredicate) { |
| 211 | DEBUG(dbgs() << "cmp " |
| 212 | << (ExpectedPredicate == ICmpInst::ICMP_EQ ? "eq" : "ne") |
| 213 | << "\n"); |
| 214 | auto Lhs = visitICmpLoadOperand(CmpI->getOperand(0)); |
Clement Courbet | 98eaa88 | 2017-10-04 15:13:52 +0000 | [diff] [blame] | 215 | if (!Lhs.Base()) return {}; |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 216 | auto Rhs = visitICmpLoadOperand(CmpI->getOperand(1)); |
Clement Courbet | 98eaa88 | 2017-10-04 15:13:52 +0000 | [diff] [blame] | 217 | if (!Rhs.Base()) return {}; |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 218 | return BCECmpBlock(std::move(Lhs), std::move(Rhs), |
| 219 | CmpI->getOperand(0)->getType()->getScalarSizeInBits()); |
| 220 | } |
| 221 | return {}; |
| 222 | } |
| 223 | |
| 224 | // Visit the given comparison block. If this is a comparison between two valid |
| 225 | // BCE atoms, returns the comparison. |
Eugene Zelenko | 5adb96c | 2017-10-26 00:55:39 +0000 | [diff] [blame^] | 226 | static BCECmpBlock visitCmpBlock(Value *const Val, BasicBlock *const Block, |
| 227 | const BasicBlock *const PhiBlock) { |
Clement Courbet | 98eaa88 | 2017-10-04 15:13:52 +0000 | [diff] [blame] | 228 | if (Block->empty()) return {}; |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 229 | auto *const BranchI = dyn_cast<BranchInst>(Block->getTerminator()); |
Clement Courbet | 98eaa88 | 2017-10-04 15:13:52 +0000 | [diff] [blame] | 230 | if (!BranchI) return {}; |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 231 | DEBUG(dbgs() << "branch\n"); |
| 232 | if (BranchI->isUnconditional()) { |
| 233 | // In this case, we expect an incoming value which is the result of the |
| 234 | // comparison. This is the last link in the chain of comparisons (note |
| 235 | // that this does not mean that this is the last incoming value, blocks |
| 236 | // can be reordered). |
| 237 | auto *const CmpI = dyn_cast<ICmpInst>(Val); |
Clement Courbet | 98eaa88 | 2017-10-04 15:13:52 +0000 | [diff] [blame] | 238 | if (!CmpI) return {}; |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 239 | DEBUG(dbgs() << "icmp\n"); |
| 240 | auto Result = visitICmp(CmpI, ICmpInst::ICMP_EQ); |
| 241 | Result.CmpI = CmpI; |
| 242 | Result.BranchI = BranchI; |
| 243 | return Result; |
| 244 | } else { |
| 245 | // In this case, we expect a constant incoming value (the comparison is |
| 246 | // chained). |
| 247 | const auto *const Const = dyn_cast<ConstantInt>(Val); |
| 248 | DEBUG(dbgs() << "const\n"); |
Clement Courbet | 98eaa88 | 2017-10-04 15:13:52 +0000 | [diff] [blame] | 249 | if (!Const->isZero()) return {}; |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 250 | DEBUG(dbgs() << "false\n"); |
| 251 | auto *const CmpI = dyn_cast<ICmpInst>(BranchI->getCondition()); |
Clement Courbet | 98eaa88 | 2017-10-04 15:13:52 +0000 | [diff] [blame] | 252 | if (!CmpI) return {}; |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 253 | DEBUG(dbgs() << "icmp\n"); |
| 254 | assert(BranchI->getNumSuccessors() == 2 && "expecting a cond branch"); |
| 255 | BasicBlock *const FalseBlock = BranchI->getSuccessor(1); |
| 256 | auto Result = visitICmp( |
| 257 | CmpI, FalseBlock == PhiBlock ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE); |
| 258 | Result.CmpI = CmpI; |
| 259 | Result.BranchI = BranchI; |
| 260 | return Result; |
| 261 | } |
| 262 | return {}; |
| 263 | } |
| 264 | |
Eugene Zelenko | 5adb96c | 2017-10-26 00:55:39 +0000 | [diff] [blame^] | 265 | namespace { |
| 266 | |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 267 | // A chain of comparisons. |
| 268 | class BCECmpChain { |
Eugene Zelenko | 5adb96c | 2017-10-26 00:55:39 +0000 | [diff] [blame^] | 269 | public: |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 270 | BCECmpChain(const std::vector<BasicBlock *> &Blocks, PHINode &Phi); |
| 271 | |
| 272 | int size() const { return Comparisons_.size(); } |
| 273 | |
| 274 | #ifdef MERGEICMPS_DOT_ON |
| 275 | void dump() const; |
| 276 | #endif // MERGEICMPS_DOT_ON |
| 277 | |
| 278 | bool simplify(const TargetLibraryInfo *const TLI); |
| 279 | |
Eugene Zelenko | 5adb96c | 2017-10-26 00:55:39 +0000 | [diff] [blame^] | 280 | private: |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 281 | static bool IsContiguous(const BCECmpBlock &First, |
| 282 | const BCECmpBlock &Second) { |
| 283 | return First.Lhs().Base() == Second.Lhs().Base() && |
| 284 | First.Rhs().Base() == Second.Rhs().Base() && |
| 285 | First.Lhs().Offset + First.SizeBits() / 8 == Second.Lhs().Offset && |
| 286 | First.Rhs().Offset + First.SizeBits() / 8 == Second.Rhs().Offset; |
| 287 | } |
| 288 | |
| 289 | // Merges the given comparison blocks into one memcmp block and update |
| 290 | // branches. Comparisons are assumed to be continguous. If NextBBInChain is |
| 291 | // null, the merged block will link to the phi block. |
| 292 | static void mergeComparisons(ArrayRef<BCECmpBlock> Comparisons, |
| 293 | BasicBlock *const NextBBInChain, PHINode &Phi, |
| 294 | const TargetLibraryInfo *const TLI); |
| 295 | |
| 296 | PHINode &Phi_; |
| 297 | std::vector<BCECmpBlock> Comparisons_; |
Eugene Zelenko | 5adb96c | 2017-10-26 00:55:39 +0000 | [diff] [blame^] | 298 | |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 299 | // The original entry block (before sorting); |
| 300 | BasicBlock *EntryBlock_; |
| 301 | }; |
| 302 | |
Eugene Zelenko | 5adb96c | 2017-10-26 00:55:39 +0000 | [diff] [blame^] | 303 | } // end anonymous namespace |
| 304 | |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 305 | BCECmpChain::BCECmpChain(const std::vector<BasicBlock *> &Blocks, PHINode &Phi) |
| 306 | : Phi_(Phi) { |
| 307 | // Now look inside blocks to check for BCE comparisons. |
| 308 | std::vector<BCECmpBlock> Comparisons; |
| 309 | for (BasicBlock *Block : Blocks) { |
| 310 | BCECmpBlock Comparison = visitCmpBlock(Phi.getIncomingValueForBlock(Block), |
| 311 | Block, Phi.getParent()); |
| 312 | Comparison.BB = Block; |
| 313 | if (!Comparison.IsValid()) { |
| 314 | DEBUG(dbgs() << "skip: not a valid BCECmpBlock\n"); |
| 315 | return; |
| 316 | } |
| 317 | if (Comparison.doesOtherWork()) { |
| 318 | DEBUG(dbgs() << "block does extra work besides compare\n"); |
| 319 | if (Comparisons.empty()) { // First block. |
| 320 | // TODO(courbet): The first block can do other things, and we should |
| 321 | // split them apart in a separate block before the comparison chain. |
| 322 | // Right now we just discard it and make the chain shorter. |
| 323 | DEBUG(dbgs() |
| 324 | << "ignoring first block that does extra work besides compare\n"); |
| 325 | continue; |
| 326 | } |
| 327 | // TODO(courbet): Right now we abort the whole chain. We could be |
| 328 | // merging only the blocks that don't do other work and resume the |
| 329 | // chain from there. For example: |
| 330 | // if (a[0] == b[0]) { // bb1 |
| 331 | // if (a[1] == b[1]) { // bb2 |
| 332 | // some_value = 3; //bb3 |
| 333 | // if (a[2] == b[2]) { //bb3 |
| 334 | // do a ton of stuff //bb4 |
| 335 | // } |
| 336 | // } |
| 337 | // } |
| 338 | // |
| 339 | // This is: |
| 340 | // |
| 341 | // bb1 --eq--> bb2 --eq--> bb3* -eq--> bb4 --+ |
| 342 | // \ \ \ \ |
| 343 | // ne ne ne \ |
| 344 | // \ \ \ v |
| 345 | // +------------+-----------+----------> bb_phi |
| 346 | // |
| 347 | // We can only merge the first two comparisons, because bb3* does |
| 348 | // "other work" (setting some_value to 3). |
| 349 | // We could still merge bb1 and bb2 though. |
| 350 | return; |
| 351 | } |
| 352 | DEBUG(dbgs() << "*Found cmp of " << Comparison.SizeBits() |
| 353 | << " bits between " << Comparison.Lhs().Base() << " + " |
| 354 | << Comparison.Lhs().Offset << " and " |
| 355 | << Comparison.Rhs().Base() << " + " << Comparison.Rhs().Offset |
| 356 | << "\n"); |
| 357 | DEBUG(dbgs() << "\n"); |
| 358 | Comparisons.push_back(Comparison); |
| 359 | } |
| 360 | EntryBlock_ = Comparisons[0].BB; |
| 361 | Comparisons_ = std::move(Comparisons); |
| 362 | #ifdef MERGEICMPS_DOT_ON |
| 363 | errs() << "BEFORE REORDERING:\n\n"; |
| 364 | dump(); |
| 365 | #endif // MERGEICMPS_DOT_ON |
| 366 | // Reorder blocks by LHS. We can do that without changing the |
| 367 | // semantics because we are only accessing dereferencable memory. |
| 368 | std::sort(Comparisons_.begin(), Comparisons_.end(), |
| 369 | [](const BCECmpBlock &a, const BCECmpBlock &b) { |
| 370 | return a.Lhs() < b.Lhs(); |
| 371 | }); |
| 372 | #ifdef MERGEICMPS_DOT_ON |
| 373 | errs() << "AFTER REORDERING:\n\n"; |
| 374 | dump(); |
| 375 | #endif // MERGEICMPS_DOT_ON |
| 376 | } |
| 377 | |
| 378 | #ifdef MERGEICMPS_DOT_ON |
| 379 | void BCECmpChain::dump() const { |
| 380 | errs() << "digraph dag {\n"; |
| 381 | errs() << " graph [bgcolor=transparent];\n"; |
| 382 | errs() << " node [color=black,style=filled,fillcolor=lightyellow];\n"; |
| 383 | errs() << " edge [color=black];\n"; |
| 384 | for (size_t I = 0; I < Comparisons_.size(); ++I) { |
| 385 | const auto &Comparison = Comparisons_[I]; |
| 386 | errs() << " \"" << I << "\" [label=\"%" |
| 387 | << Comparison.Lhs().Base()->getName() << " + " |
| 388 | << Comparison.Lhs().Offset << " == %" |
| 389 | << Comparison.Rhs().Base()->getName() << " + " |
| 390 | << Comparison.Rhs().Offset << " (" << (Comparison.SizeBits() / 8) |
| 391 | << " bytes)\"];\n"; |
| 392 | const Value *const Val = Phi_.getIncomingValueForBlock(Comparison.BB); |
Clement Courbet | 98eaa88 | 2017-10-04 15:13:52 +0000 | [diff] [blame] | 393 | if (I > 0) errs() << " \"" << (I - 1) << "\" -> \"" << I << "\";\n"; |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 394 | errs() << " \"" << I << "\" -> \"Phi\" [label=\"" << *Val << "\"];\n"; |
| 395 | } |
| 396 | errs() << " \"Phi\" [label=\"Phi\"];\n"; |
| 397 | errs() << "}\n\n"; |
| 398 | } |
| 399 | #endif // MERGEICMPS_DOT_ON |
| 400 | |
| 401 | bool BCECmpChain::simplify(const TargetLibraryInfo *const TLI) { |
| 402 | // First pass to check if there is at least one merge. If not, we don't do |
| 403 | // anything and we keep analysis passes intact. |
| 404 | { |
| 405 | bool AtLeastOneMerged = false; |
| 406 | for (size_t I = 1; I < Comparisons_.size(); ++I) { |
| 407 | if (IsContiguous(Comparisons_[I - 1], Comparisons_[I])) { |
| 408 | AtLeastOneMerged = true; |
| 409 | break; |
| 410 | } |
| 411 | } |
Clement Courbet | 98eaa88 | 2017-10-04 15:13:52 +0000 | [diff] [blame] | 412 | if (!AtLeastOneMerged) return false; |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 413 | } |
| 414 | |
| 415 | // Remove phi references to comparison blocks, they will be rebuilt as we |
| 416 | // merge the blocks. |
| 417 | for (const auto &Comparison : Comparisons_) { |
| 418 | Phi_.removeIncomingValue(Comparison.BB, false); |
| 419 | } |
| 420 | |
| 421 | // Point the predecessors of the chain to the first comparison block (which is |
| 422 | // the new entry point). |
| 423 | if (EntryBlock_ != Comparisons_[0].BB) |
| 424 | EntryBlock_->replaceAllUsesWith(Comparisons_[0].BB); |
| 425 | |
| 426 | // Effectively merge blocks. |
| 427 | int NumMerged = 1; |
| 428 | for (size_t I = 1; I < Comparisons_.size(); ++I) { |
| 429 | if (IsContiguous(Comparisons_[I - 1], Comparisons_[I])) { |
| 430 | ++NumMerged; |
| 431 | } else { |
| 432 | // Merge all previous comparisons and start a new merge block. |
| 433 | mergeComparisons( |
| 434 | makeArrayRef(Comparisons_).slice(I - NumMerged, NumMerged), |
| 435 | Comparisons_[I].BB, Phi_, TLI); |
| 436 | NumMerged = 1; |
| 437 | } |
| 438 | } |
| 439 | mergeComparisons(makeArrayRef(Comparisons_) |
| 440 | .slice(Comparisons_.size() - NumMerged, NumMerged), |
| 441 | nullptr, Phi_, TLI); |
| 442 | |
| 443 | return true; |
| 444 | } |
| 445 | |
| 446 | void BCECmpChain::mergeComparisons(ArrayRef<BCECmpBlock> Comparisons, |
| 447 | BasicBlock *const NextBBInChain, |
| 448 | PHINode &Phi, |
| 449 | const TargetLibraryInfo *const TLI) { |
| 450 | assert(!Comparisons.empty()); |
| 451 | const auto &FirstComparison = *Comparisons.begin(); |
| 452 | BasicBlock *const BB = FirstComparison.BB; |
| 453 | LLVMContext &Context = BB->getContext(); |
| 454 | |
| 455 | if (Comparisons.size() >= 2) { |
| 456 | DEBUG(dbgs() << "Merging " << Comparisons.size() << " comparisons\n"); |
| 457 | const auto TotalSize = |
| 458 | std::accumulate(Comparisons.begin(), Comparisons.end(), 0, |
| 459 | [](int Size, const BCECmpBlock &C) { |
| 460 | return Size + C.SizeBits(); |
| 461 | }) / |
| 462 | 8; |
| 463 | |
| 464 | // Incoming edges do not need to be updated, and both GEPs are already |
| 465 | // computing the right address, we just need to: |
| 466 | // - replace the two loads and the icmp with the memcmp |
| 467 | // - update the branch |
| 468 | // - update the incoming values in the phi. |
| 469 | FirstComparison.BranchI->eraseFromParent(); |
| 470 | FirstComparison.CmpI->eraseFromParent(); |
| 471 | FirstComparison.Lhs().LoadI->eraseFromParent(); |
| 472 | FirstComparison.Rhs().LoadI->eraseFromParent(); |
| 473 | |
| 474 | IRBuilder<> Builder(BB); |
| 475 | const auto &DL = Phi.getModule()->getDataLayout(); |
Clement Courbet | e2e8a5c | 2017-10-10 08:00:45 +0000 | [diff] [blame] | 476 | Value *const MemCmpCall = emitMemCmp( |
Eugene Zelenko | 5adb96c | 2017-10-26 00:55:39 +0000 | [diff] [blame^] | 477 | FirstComparison.Lhs().GEP, FirstComparison.Rhs().GEP, |
| 478 | ConstantInt::get(DL.getIntPtrType(Context), TotalSize), |
Clement Courbet | e2e8a5c | 2017-10-10 08:00:45 +0000 | [diff] [blame] | 479 | Builder, DL, TLI); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 480 | Value *const MemCmpIsZero = Builder.CreateICmpEQ( |
| 481 | MemCmpCall, ConstantInt::get(Type::getInt32Ty(Context), 0)); |
| 482 | |
| 483 | // Add a branch to the next basic block in the chain. |
| 484 | if (NextBBInChain) { |
| 485 | Builder.CreateCondBr(MemCmpIsZero, NextBBInChain, Phi.getParent()); |
| 486 | Phi.addIncoming(ConstantInt::getFalse(Context), BB); |
| 487 | } else { |
| 488 | Builder.CreateBr(Phi.getParent()); |
| 489 | Phi.addIncoming(MemCmpIsZero, BB); |
| 490 | } |
| 491 | |
| 492 | // Delete merged blocks. |
| 493 | for (size_t I = 1; I < Comparisons.size(); ++I) { |
| 494 | BasicBlock *CBB = Comparisons[I].BB; |
| 495 | CBB->replaceAllUsesWith(BB); |
| 496 | CBB->eraseFromParent(); |
| 497 | } |
| 498 | } else { |
| 499 | assert(Comparisons.size() == 1); |
| 500 | // There are no blocks to merge, but we still need to update the branches. |
| 501 | DEBUG(dbgs() << "Only one comparison, updating branches\n"); |
| 502 | if (NextBBInChain) { |
| 503 | if (FirstComparison.BranchI->isConditional()) { |
| 504 | DEBUG(dbgs() << "conditional -> conditional\n"); |
| 505 | // Just update the "true" target, the "false" target should already be |
| 506 | // the phi block. |
| 507 | assert(FirstComparison.BranchI->getSuccessor(1) == Phi.getParent()); |
| 508 | FirstComparison.BranchI->setSuccessor(0, NextBBInChain); |
| 509 | Phi.addIncoming(ConstantInt::getFalse(Context), BB); |
| 510 | } else { |
| 511 | DEBUG(dbgs() << "unconditional -> conditional\n"); |
| 512 | // Replace the unconditional branch by a conditional one. |
| 513 | FirstComparison.BranchI->eraseFromParent(); |
| 514 | IRBuilder<> Builder(BB); |
| 515 | Builder.CreateCondBr(FirstComparison.CmpI, NextBBInChain, |
| 516 | Phi.getParent()); |
| 517 | Phi.addIncoming(FirstComparison.CmpI, BB); |
| 518 | } |
| 519 | } else { |
| 520 | if (FirstComparison.BranchI->isConditional()) { |
| 521 | DEBUG(dbgs() << "conditional -> unconditional\n"); |
| 522 | // Replace the conditional branch by an unconditional one. |
| 523 | FirstComparison.BranchI->eraseFromParent(); |
| 524 | IRBuilder<> Builder(BB); |
| 525 | Builder.CreateBr(Phi.getParent()); |
| 526 | Phi.addIncoming(FirstComparison.CmpI, BB); |
| 527 | } else { |
| 528 | DEBUG(dbgs() << "unconditional -> unconditional\n"); |
| 529 | Phi.addIncoming(FirstComparison.CmpI, BB); |
| 530 | } |
| 531 | } |
| 532 | } |
| 533 | } |
| 534 | |
Eugene Zelenko | 5adb96c | 2017-10-26 00:55:39 +0000 | [diff] [blame^] | 535 | static std::vector<BasicBlock *> getOrderedBlocks(PHINode &Phi, |
| 536 | BasicBlock *const LastBlock, |
| 537 | int NumBlocks) { |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 538 | // Walk up from the last block to find other blocks. |
| 539 | std::vector<BasicBlock *> Blocks(NumBlocks); |
| 540 | BasicBlock *CurBlock = LastBlock; |
| 541 | for (int BlockIndex = NumBlocks - 1; BlockIndex > 0; --BlockIndex) { |
| 542 | if (CurBlock->hasAddressTaken()) { |
| 543 | // Somebody is jumping to the block through an address, all bets are |
| 544 | // off. |
| 545 | DEBUG(dbgs() << "skip: block " << BlockIndex |
| 546 | << " has its address taken\n"); |
| 547 | return {}; |
| 548 | } |
| 549 | Blocks[BlockIndex] = CurBlock; |
| 550 | auto *SinglePredecessor = CurBlock->getSinglePredecessor(); |
| 551 | if (!SinglePredecessor) { |
| 552 | // The block has two or more predecessors. |
| 553 | DEBUG(dbgs() << "skip: block " << BlockIndex |
| 554 | << " has two or more predecessors\n"); |
| 555 | return {}; |
| 556 | } |
| 557 | if (Phi.getBasicBlockIndex(SinglePredecessor) < 0) { |
| 558 | // The block does not link back to the phi. |
| 559 | DEBUG(dbgs() << "skip: block " << BlockIndex |
| 560 | << " does not link back to the phi\n"); |
| 561 | return {}; |
| 562 | } |
| 563 | CurBlock = SinglePredecessor; |
| 564 | } |
| 565 | Blocks[0] = CurBlock; |
| 566 | return Blocks; |
| 567 | } |
| 568 | |
Eugene Zelenko | 5adb96c | 2017-10-26 00:55:39 +0000 | [diff] [blame^] | 569 | static bool processPhi(PHINode &Phi, const TargetLibraryInfo *const TLI) { |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 570 | DEBUG(dbgs() << "processPhi()\n"); |
| 571 | if (Phi.getNumIncomingValues() <= 1) { |
| 572 | DEBUG(dbgs() << "skip: only one incoming value in phi\n"); |
| 573 | return false; |
| 574 | } |
| 575 | // We are looking for something that has the following structure: |
| 576 | // bb1 --eq--> bb2 --eq--> bb3 --eq--> bb4 --+ |
| 577 | // \ \ \ \ |
| 578 | // ne ne ne \ |
| 579 | // \ \ \ v |
| 580 | // +------------+-----------+----------> bb_phi |
| 581 | // |
| 582 | // - The last basic block (bb4 here) must branch unconditionally to bb_phi. |
| 583 | // It's the only block that contributes a non-constant value to the Phi. |
| 584 | // - All other blocks (b1, b2, b3) must have exactly two successors, one of |
| 585 | // them being the the phi block. |
| 586 | // - All intermediate blocks (bb2, bb3) must have only one predecessor. |
| 587 | // - Blocks cannot do other work besides the comparison, see doesOtherWork() |
| 588 | |
| 589 | // The blocks are not necessarily ordered in the phi, so we start from the |
| 590 | // last block and reconstruct the order. |
| 591 | BasicBlock *LastBlock = nullptr; |
| 592 | for (unsigned I = 0; I < Phi.getNumIncomingValues(); ++I) { |
Clement Courbet | 98eaa88 | 2017-10-04 15:13:52 +0000 | [diff] [blame] | 593 | if (isa<ConstantInt>(Phi.getIncomingValue(I))) continue; |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 594 | if (LastBlock) { |
| 595 | // There are several non-constant values. |
| 596 | DEBUG(dbgs() << "skip: several non-constant values\n"); |
| 597 | return false; |
| 598 | } |
| 599 | LastBlock = Phi.getIncomingBlock(I); |
| 600 | } |
| 601 | if (!LastBlock) { |
| 602 | // There is no non-constant block. |
| 603 | DEBUG(dbgs() << "skip: no non-constant block\n"); |
| 604 | return false; |
| 605 | } |
| 606 | if (LastBlock->getSingleSuccessor() != Phi.getParent()) { |
| 607 | DEBUG(dbgs() << "skip: last block non-phi successor\n"); |
| 608 | return false; |
| 609 | } |
| 610 | |
| 611 | const auto Blocks = |
| 612 | getOrderedBlocks(Phi, LastBlock, Phi.getNumIncomingValues()); |
Clement Courbet | 98eaa88 | 2017-10-04 15:13:52 +0000 | [diff] [blame] | 613 | if (Blocks.empty()) return false; |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 614 | BCECmpChain CmpChain(Blocks, Phi); |
| 615 | |
| 616 | if (CmpChain.size() < 2) { |
| 617 | DEBUG(dbgs() << "skip: only one compare block\n"); |
| 618 | return false; |
| 619 | } |
| 620 | |
| 621 | return CmpChain.simplify(TLI); |
| 622 | } |
| 623 | |
Eugene Zelenko | 5adb96c | 2017-10-26 00:55:39 +0000 | [diff] [blame^] | 624 | namespace { |
| 625 | |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 626 | class MergeICmps : public FunctionPass { |
Eugene Zelenko | 5adb96c | 2017-10-26 00:55:39 +0000 | [diff] [blame^] | 627 | public: |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 628 | static char ID; |
| 629 | |
| 630 | MergeICmps() : FunctionPass(ID) { |
| 631 | initializeMergeICmpsPass(*PassRegistry::getPassRegistry()); |
| 632 | } |
| 633 | |
| 634 | bool runOnFunction(Function &F) override { |
| 635 | if (skipFunction(F)) return false; |
| 636 | const auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); |
Clement Courbet | e2e8a5c | 2017-10-10 08:00:45 +0000 | [diff] [blame] | 637 | const auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); |
| 638 | auto PA = runImpl(F, &TLI, &TTI); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 639 | return !PA.areAllPreserved(); |
| 640 | } |
| 641 | |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 642 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
| 643 | AU.addRequired<TargetLibraryInfoWrapperPass>(); |
Clement Courbet | e2e8a5c | 2017-10-10 08:00:45 +0000 | [diff] [blame] | 644 | AU.addRequired<TargetTransformInfoWrapperPass>(); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 645 | } |
| 646 | |
Eugene Zelenko | 5adb96c | 2017-10-26 00:55:39 +0000 | [diff] [blame^] | 647 | private: |
Clement Courbet | e2e8a5c | 2017-10-10 08:00:45 +0000 | [diff] [blame] | 648 | PreservedAnalyses runImpl(Function &F, const TargetLibraryInfo *TLI, |
| 649 | const TargetTransformInfo *TTI); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 650 | }; |
| 651 | |
Eugene Zelenko | 5adb96c | 2017-10-26 00:55:39 +0000 | [diff] [blame^] | 652 | } // end anonymous namespace |
| 653 | |
Clement Courbet | e2e8a5c | 2017-10-10 08:00:45 +0000 | [diff] [blame] | 654 | PreservedAnalyses MergeICmps::runImpl(Function &F, const TargetLibraryInfo *TLI, |
| 655 | const TargetTransformInfo *TTI) { |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 656 | DEBUG(dbgs() << "MergeICmpsPass: " << F.getName() << "\n"); |
| 657 | |
Clement Courbet | e2e8a5c | 2017-10-10 08:00:45 +0000 | [diff] [blame] | 658 | // We only try merging comparisons if the target wants to expand memcmp later. |
| 659 | // The rationale is to avoid turning small chains into memcmp calls. |
| 660 | unsigned MaxLoadSize; |
| 661 | if (!TTI->enableMemCmpExpansion(MaxLoadSize)) return PreservedAnalyses::all(); |
| 662 | |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 663 | bool MadeChange = false; |
| 664 | |
| 665 | for (auto BBIt = ++F.begin(); BBIt != F.end(); ++BBIt) { |
| 666 | // A Phi operation is always first in a basic block. |
| 667 | if (auto *const Phi = dyn_cast<PHINode>(&*BBIt->begin())) |
| 668 | MadeChange |= processPhi(*Phi, TLI); |
| 669 | } |
| 670 | |
Clement Courbet | 98eaa88 | 2017-10-04 15:13:52 +0000 | [diff] [blame] | 671 | if (MadeChange) return PreservedAnalyses::none(); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 672 | return PreservedAnalyses::all(); |
| 673 | } |
| 674 | |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 675 | char MergeICmps::ID = 0; |
Eugene Zelenko | 5adb96c | 2017-10-26 00:55:39 +0000 | [diff] [blame^] | 676 | |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 677 | INITIALIZE_PASS_BEGIN(MergeICmps, "mergeicmps", |
| 678 | "Merge contiguous icmps into a memcmp", false, false) |
| 679 | INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) |
Clement Courbet | e2e8a5c | 2017-10-10 08:00:45 +0000 | [diff] [blame] | 680 | INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 681 | INITIALIZE_PASS_END(MergeICmps, "mergeicmps", |
| 682 | "Merge contiguous icmps into a memcmp", false, false) |
| 683 | |
| 684 | Pass *llvm::createMergeICmpsPass() { return new MergeICmps(); } |