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