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