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