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 "llvm/Transforms/Scalar/MergeICmps.h"
45 #include "llvm/Analysis/DomTreeUpdater.h"
46 #include "llvm/Analysis/GlobalsModRef.h"
47 #include "llvm/Analysis/Loads.h"
48 #include "llvm/Analysis/TargetLibraryInfo.h"
49 #include "llvm/Analysis/TargetTransformInfo.h"
50 #include "llvm/IR/Dominators.h"
51 #include "llvm/IR/Function.h"
52 #include "llvm/IR/IRBuilder.h"
53 #include "llvm/InitializePasses.h"
54 #include "llvm/Pass.h"
55 #include "llvm/Transforms/Scalar.h"
56 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
57 #include "llvm/Transforms/Utils/BuildLibCalls.h"
58 #include <algorithm>
59 #include <numeric>
60 #include <utility>
61 #include <vector>
62 
63 using namespace llvm;
64 
65 namespace {
66 
67 #define DEBUG_TYPE "mergeicmps"
68 
69 // A BCE atom "Binary Compare Expression Atom" represents an integer load
70 // that is a constant offset from a base value, e.g. `a` or `o.c` in the example
71 // at the top.
72 struct BCEAtom {
73   BCEAtom() = default;
74   BCEAtom(GetElementPtrInst *GEP, LoadInst *LoadI, int BaseId, APInt Offset)
75       : GEP(GEP), LoadI(LoadI), BaseId(BaseId), Offset(Offset) {}
76 
77   BCEAtom(const BCEAtom &) = delete;
78   BCEAtom &operator=(const BCEAtom &) = delete;
79 
80   BCEAtom(BCEAtom &&that) = default;
81   BCEAtom &operator=(BCEAtom &&that) {
82     if (this == &that)
83       return *this;
84     GEP = that.GEP;
85     LoadI = that.LoadI;
86     BaseId = that.BaseId;
87     Offset = std::move(that.Offset);
88     return *this;
89   }
90 
91   // We want to order BCEAtoms by (Base, Offset). However we cannot use
92   // the pointer values for Base because these are non-deterministic.
93   // To make sure that the sort order is stable, we first assign to each atom
94   // base value an index based on its order of appearance in the chain of
95   // comparisons. We call this index `BaseOrdering`. For example, for:
96   //    b[3] == c[2] && a[1] == d[1] && b[4] == c[3]
97   //    |  block 1 |    |  block 2 |    |  block 3 |
98   // b gets assigned index 0 and a index 1, because b appears as LHS in block 1,
99   // which is before block 2.
100   // We then sort by (BaseOrdering[LHS.Base()], LHS.Offset), which is stable.
101   bool operator<(const BCEAtom &O) const {
102     return BaseId != O.BaseId ? BaseId < O.BaseId : Offset.slt(O.Offset);
103   }
104 
105   GetElementPtrInst *GEP = nullptr;
106   LoadInst *LoadI = nullptr;
107   unsigned BaseId = 0;
108   APInt Offset;
109 };
110 
111 // A class that assigns increasing ids to values in the order in which they are
112 // seen. See comment in `BCEAtom::operator<()``.
113 class BaseIdentifier {
114 public:
115   // Returns the id for value `Base`, after assigning one if `Base` has not been
116   // seen before.
117   int getBaseId(const Value *Base) {
118     assert(Base && "invalid base");
119     const auto Insertion = BaseToIndex.try_emplace(Base, Order);
120     if (Insertion.second)
121       ++Order;
122     return Insertion.first->second;
123   }
124 
125 private:
126   unsigned Order = 1;
127   DenseMap<const Value*, int> BaseToIndex;
128 };
129 
130 // If this value is a load from a constant offset w.r.t. a base address, and
131 // there are no other users of the load or address, returns the base address and
132 // the offset.
133 BCEAtom visitICmpLoadOperand(Value *const Val, BaseIdentifier &BaseId) {
134   auto *const LoadI = dyn_cast<LoadInst>(Val);
135   if (!LoadI)
136     return {};
137   LLVM_DEBUG(dbgs() << "load\n");
138   if (LoadI->isUsedOutsideOfBlock(LoadI->getParent())) {
139     LLVM_DEBUG(dbgs() << "used outside of block\n");
140     return {};
141   }
142   // Do not optimize atomic loads to non-atomic memcmp
143   if (!LoadI->isSimple()) {
144     LLVM_DEBUG(dbgs() << "volatile or atomic\n");
145     return {};
146   }
147   Value *const Addr = LoadI->getOperand(0);
148   if (Addr->getType()->getPointerAddressSpace() != 0) {
149     LLVM_DEBUG(dbgs() << "from non-zero AddressSpace\n");
150     return {};
151   }
152   auto *const GEP = dyn_cast<GetElementPtrInst>(Addr);
153   if (!GEP)
154     return {};
155   LLVM_DEBUG(dbgs() << "GEP\n");
156   if (GEP->isUsedOutsideOfBlock(LoadI->getParent())) {
157     LLVM_DEBUG(dbgs() << "used outside of block\n");
158     return {};
159   }
160   const auto &DL = GEP->getModule()->getDataLayout();
161   if (!isDereferenceablePointer(GEP, LoadI->getType(), DL)) {
162     LLVM_DEBUG(dbgs() << "not dereferenceable\n");
163     // We need to make sure that we can do comparison in any order, so we
164     // require memory to be unconditionnally dereferencable.
165     return {};
166   }
167   APInt Offset = APInt(DL.getPointerTypeSizeInBits(GEP->getType()), 0);
168   if (!GEP->accumulateConstantOffset(DL, Offset))
169     return {};
170   return BCEAtom(GEP, LoadI, BaseId.getBaseId(GEP->getPointerOperand()),
171                  Offset);
172 }
173 
174 // A comparison between two BCE atoms, e.g. `a == o.a` in the example at the
175 // top.
176 // Note: the terminology is misleading: the comparison is symmetric, so there
177 // is no real {l/r}hs. What we want though is to have the same base on the
178 // left (resp. right), so that we can detect consecutive loads. To ensure this
179 // we put the smallest atom on the left.
180 struct BCECmp {
181   BCEAtom Lhs;
182   BCEAtom Rhs;
183   int SizeBits;
184   const ICmpInst *CmpI;
185 
186   BCECmp(BCEAtom L, BCEAtom R, int SizeBits, const ICmpInst *CmpI)
187       : Lhs(std::move(L)), Rhs(std::move(R)), SizeBits(SizeBits), CmpI(CmpI) {
188     if (Rhs < Lhs) std::swap(Rhs, Lhs);
189   }
190 };
191 
192 // A basic block with a comparison between two BCE atoms.
193 // The block might do extra work besides the atom comparison, in which case
194 // doesOtherWork() returns true. Under some conditions, the block can be
195 // split into the atom comparison part and the "other work" part
196 // (see canSplit()).
197 class BCECmpBlock {
198  public:
199   typedef SmallDenseSet<const Instruction *, 8> InstructionSet;
200 
201   BCECmpBlock(BCECmp Cmp, BasicBlock *BB, InstructionSet BlockInsts)
202       : BB(BB), BlockInsts(std::move(BlockInsts)), Cmp(std::move(Cmp)) {}
203 
204   const BCEAtom &Lhs() const { return Cmp.Lhs; }
205   const BCEAtom &Rhs() const { return Cmp.Rhs; }
206   int SizeBits() const { return Cmp.SizeBits; }
207 
208   // Returns true if the block does other works besides comparison.
209   bool doesOtherWork() const;
210 
211   // Returns true if the non-BCE-cmp instructions can be separated from BCE-cmp
212   // instructions in the block.
213   bool canSplit(AliasAnalysis &AA) const;
214 
215   // Return true if this all the relevant instructions in the BCE-cmp-block can
216   // be sunk below this instruction. By doing this, we know we can separate the
217   // BCE-cmp-block instructions from the non-BCE-cmp-block instructions in the
218   // block.
219   bool canSinkBCECmpInst(const Instruction *, AliasAnalysis &AA) const;
220 
221   // We can separate the BCE-cmp-block instructions and the non-BCE-cmp-block
222   // instructions. Split the old block and move all non-BCE-cmp-insts into the
223   // new parent block.
224   void split(BasicBlock *NewParent, AliasAnalysis &AA) const;
225 
226   // The basic block where this comparison happens.
227   BasicBlock *BB;
228   // Instructions relating to the BCECmp and branch.
229   InstructionSet BlockInsts;
230   // The block requires splitting.
231   bool RequireSplit = false;
232 
233 private:
234   BCECmp Cmp;
235 };
236 
237 bool BCECmpBlock::canSinkBCECmpInst(const Instruction *Inst,
238                                     AliasAnalysis &AA) const {
239   // If this instruction may clobber the loads and is in middle of the BCE cmp
240   // block instructions, then bail for now.
241   if (Inst->mayWriteToMemory()) {
242     auto MayClobber = [&](LoadInst *LI) {
243       // If a potentially clobbering instruction comes before the load,
244       // we can still safely sink the load.
245       return !Inst->comesBefore(LI) &&
246              isModSet(AA.getModRefInfo(Inst, MemoryLocation::get(LI)));
247     };
248     if (MayClobber(Cmp.Lhs.LoadI) || MayClobber(Cmp.Rhs.LoadI))
249       return false;
250   }
251   // Make sure this instruction does not use any of the BCE cmp block
252   // instructions as operand.
253   return llvm::none_of(Inst->operands(), [&](const Value *Op) {
254     const Instruction *OpI = dyn_cast<Instruction>(Op);
255     return OpI && BlockInsts.contains(OpI);
256   });
257 }
258 
259 void BCECmpBlock::split(BasicBlock *NewParent, AliasAnalysis &AA) const {
260   llvm::SmallVector<Instruction *, 4> OtherInsts;
261   for (Instruction &Inst : *BB) {
262     if (BlockInsts.count(&Inst))
263       continue;
264     assert(canSinkBCECmpInst(&Inst, AA) && "Split unsplittable block");
265     // This is a non-BCE-cmp-block instruction. And it can be separated
266     // from the BCE-cmp-block instruction.
267     OtherInsts.push_back(&Inst);
268   }
269 
270   // Do the actual spliting.
271   for (Instruction *Inst : reverse(OtherInsts)) {
272     Inst->moveBefore(&*NewParent->begin());
273   }
274 }
275 
276 bool BCECmpBlock::canSplit(AliasAnalysis &AA) const {
277   for (Instruction &Inst : *BB) {
278     if (!BlockInsts.count(&Inst)) {
279       if (!canSinkBCECmpInst(&Inst, AA))
280         return false;
281     }
282   }
283   return true;
284 }
285 
286 bool BCECmpBlock::doesOtherWork() const {
287   // TODO(courbet): Can we allow some other things ? This is very conservative.
288   // We might be able to get away with anything does not have any side
289   // effects outside of the basic block.
290   // Note: The GEPs and/or loads are not necessarily in the same block.
291   for (const Instruction &Inst : *BB) {
292     if (!BlockInsts.count(&Inst))
293       return true;
294   }
295   return false;
296 }
297 
298 // Visit the given comparison. If this is a comparison between two valid
299 // BCE atoms, returns the comparison.
300 Optional<BCECmp> visitICmp(const ICmpInst *const CmpI,
301                            const ICmpInst::Predicate ExpectedPredicate,
302                            BaseIdentifier &BaseId) {
303   // The comparison can only be used once:
304   //  - For intermediate blocks, as a branch condition.
305   //  - For the final block, as an incoming value for the Phi.
306   // If there are any other uses of the comparison, we cannot merge it with
307   // other comparisons as we would create an orphan use of the value.
308   if (!CmpI->hasOneUse()) {
309     LLVM_DEBUG(dbgs() << "cmp has several uses\n");
310     return None;
311   }
312   if (CmpI->getPredicate() != ExpectedPredicate)
313     return None;
314   LLVM_DEBUG(dbgs() << "cmp "
315                     << (ExpectedPredicate == ICmpInst::ICMP_EQ ? "eq" : "ne")
316                     << "\n");
317   auto Lhs = visitICmpLoadOperand(CmpI->getOperand(0), BaseId);
318   if (!Lhs.BaseId)
319     return None;
320   auto Rhs = visitICmpLoadOperand(CmpI->getOperand(1), BaseId);
321   if (!Rhs.BaseId)
322     return None;
323   const auto &DL = CmpI->getModule()->getDataLayout();
324   return BCECmp(std::move(Lhs), std::move(Rhs),
325                 DL.getTypeSizeInBits(CmpI->getOperand(0)->getType()), CmpI);
326 }
327 
328 // Visit the given comparison block. If this is a comparison between two valid
329 // BCE atoms, returns the comparison.
330 Optional<BCECmpBlock> visitCmpBlock(Value *const Val, BasicBlock *const Block,
331                                     const BasicBlock *const PhiBlock,
332                                     BaseIdentifier &BaseId) {
333   if (Block->empty()) return None;
334   auto *const BranchI = dyn_cast<BranchInst>(Block->getTerminator());
335   if (!BranchI) return None;
336   LLVM_DEBUG(dbgs() << "branch\n");
337   Value *Cond;
338   ICmpInst::Predicate ExpectedPredicate;
339   if (BranchI->isUnconditional()) {
340     // In this case, we expect an incoming value which is the result of the
341     // comparison. This is the last link in the chain of comparisons (note
342     // that this does not mean that this is the last incoming value, blocks
343     // can be reordered).
344     Cond = Val;
345     ExpectedPredicate = ICmpInst::ICMP_EQ;
346   } else {
347     // In this case, we expect a constant incoming value (the comparison is
348     // chained).
349     const auto *const Const = cast<ConstantInt>(Val);
350     LLVM_DEBUG(dbgs() << "const\n");
351     if (!Const->isZero()) return None;
352     LLVM_DEBUG(dbgs() << "false\n");
353     assert(BranchI->getNumSuccessors() == 2 && "expecting a cond branch");
354     BasicBlock *const FalseBlock = BranchI->getSuccessor(1);
355     Cond = BranchI->getCondition();
356     ExpectedPredicate =
357         FalseBlock == PhiBlock ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
358   }
359 
360   auto *CmpI = dyn_cast<ICmpInst>(Cond);
361   if (!CmpI) return None;
362   LLVM_DEBUG(dbgs() << "icmp\n");
363 
364   Optional<BCECmp> Result = visitICmp(CmpI, ExpectedPredicate, BaseId);
365   if (!Result)
366     return None;
367 
368   BCECmpBlock::InstructionSet BlockInsts(
369       {Result->Lhs.GEP, Result->Rhs.GEP, Result->Lhs.LoadI, Result->Rhs.LoadI,
370        Result->CmpI, BranchI});
371   return BCECmpBlock(std::move(*Result), Block, BlockInsts);
372 }
373 
374 static inline void enqueueBlock(std::vector<BCECmpBlock> &Comparisons,
375                                 BCECmpBlock &&Comparison) {
376   LLVM_DEBUG(dbgs() << "Block '" << Comparison.BB->getName()
377                     << "': Found cmp of " << Comparison.SizeBits()
378                     << " bits between " << Comparison.Lhs().BaseId << " + "
379                     << Comparison.Lhs().Offset << " and "
380                     << Comparison.Rhs().BaseId << " + "
381                     << Comparison.Rhs().Offset << "\n");
382   LLVM_DEBUG(dbgs() << "\n");
383   Comparisons.push_back(std::move(Comparison));
384 }
385 
386 // A chain of comparisons.
387 class BCECmpChain {
388  public:
389    BCECmpChain(const std::vector<BasicBlock *> &Blocks, PHINode &Phi,
390                AliasAnalysis &AA);
391 
392    int size() const { return Comparisons_.size(); }
393 
394 #ifdef MERGEICMPS_DOT_ON
395   void dump() const;
396 #endif  // MERGEICMPS_DOT_ON
397 
398   bool simplify(const TargetLibraryInfo &TLI, AliasAnalysis &AA,
399                 DomTreeUpdater &DTU);
400 
401 private:
402   static bool IsContiguous(const BCECmpBlock &First,
403                            const BCECmpBlock &Second) {
404     return First.Lhs().BaseId == Second.Lhs().BaseId &&
405            First.Rhs().BaseId == Second.Rhs().BaseId &&
406            First.Lhs().Offset + First.SizeBits() / 8 == Second.Lhs().Offset &&
407            First.Rhs().Offset + First.SizeBits() / 8 == Second.Rhs().Offset;
408   }
409 
410   PHINode &Phi_;
411   std::vector<BCECmpBlock> Comparisons_;
412   // The original entry block (before sorting);
413   BasicBlock *EntryBlock_;
414 };
415 
416 BCECmpChain::BCECmpChain(const std::vector<BasicBlock *> &Blocks, PHINode &Phi,
417                          AliasAnalysis &AA)
418     : Phi_(Phi) {
419   assert(!Blocks.empty() && "a chain should have at least one block");
420   // Now look inside blocks to check for BCE comparisons.
421   std::vector<BCECmpBlock> Comparisons;
422   BaseIdentifier BaseId;
423   for (BasicBlock *const Block : Blocks) {
424     assert(Block && "invalid block");
425     Optional<BCECmpBlock> Comparison = visitCmpBlock(
426         Phi.getIncomingValueForBlock(Block), Block, Phi.getParent(), BaseId);
427     if (!Comparison) {
428       LLVM_DEBUG(dbgs() << "chain with invalid BCECmpBlock, no merge.\n");
429       return;
430     }
431     if (Comparison->doesOtherWork()) {
432       LLVM_DEBUG(dbgs() << "block '" << Comparison->BB->getName()
433                         << "' does extra work besides compare\n");
434       if (Comparisons.empty()) {
435         // This is the initial block in the chain, in case this block does other
436         // work, we can try to split the block and move the irrelevant
437         // instructions to the predecessor.
438         //
439         // If this is not the initial block in the chain, splitting it wont
440         // work.
441         //
442         // As once split, there will still be instructions before the BCE cmp
443         // instructions that do other work in program order, i.e. within the
444         // chain before sorting. Unless we can abort the chain at this point
445         // and start anew.
446         //
447         // NOTE: we only handle blocks a with single predecessor for now.
448         if (Comparison->canSplit(AA)) {
449           LLVM_DEBUG(dbgs()
450                      << "Split initial block '" << Comparison->BB->getName()
451                      << "' that does extra work besides compare\n");
452           Comparison->RequireSplit = true;
453           enqueueBlock(Comparisons, std::move(*Comparison));
454         } else {
455           LLVM_DEBUG(dbgs()
456                      << "ignoring initial block '" << Comparison->BB->getName()
457                      << "' that does extra work besides compare\n");
458         }
459         continue;
460       }
461       // TODO(courbet): Right now we abort the whole chain. We could be
462       // merging only the blocks that don't do other work and resume the
463       // chain from there. For example:
464       //  if (a[0] == b[0]) {  // bb1
465       //    if (a[1] == b[1]) {  // bb2
466       //      some_value = 3; //bb3
467       //      if (a[2] == b[2]) { //bb3
468       //        do a ton of stuff  //bb4
469       //      }
470       //    }
471       //  }
472       //
473       // This is:
474       //
475       // bb1 --eq--> bb2 --eq--> bb3* -eq--> bb4 --+
476       //  \            \           \               \
477       //   ne           ne          ne              \
478       //    \            \           \               v
479       //     +------------+-----------+----------> bb_phi
480       //
481       // We can only merge the first two comparisons, because bb3* does
482       // "other work" (setting some_value to 3).
483       // We could still merge bb1 and bb2 though.
484       return;
485     }
486     enqueueBlock(Comparisons, std::move(*Comparison));
487   }
488 
489   // It is possible we have no suitable comparison to merge.
490   if (Comparisons.empty()) {
491     LLVM_DEBUG(dbgs() << "chain with no BCE basic blocks, no merge\n");
492     return;
493   }
494   EntryBlock_ = Comparisons[0].BB;
495   Comparisons_ = std::move(Comparisons);
496 #ifdef MERGEICMPS_DOT_ON
497   errs() << "BEFORE REORDERING:\n\n";
498   dump();
499 #endif  // MERGEICMPS_DOT_ON
500   // Reorder blocks by LHS. We can do that without changing the
501   // semantics because we are only accessing dereferencable memory.
502   llvm::sort(Comparisons_,
503              [](const BCECmpBlock &LhsBlock, const BCECmpBlock &RhsBlock) {
504                return std::tie(LhsBlock.Lhs(), LhsBlock.Rhs()) <
505                       std::tie(RhsBlock.Lhs(), RhsBlock.Rhs());
506              });
507 #ifdef MERGEICMPS_DOT_ON
508   errs() << "AFTER REORDERING:\n\n";
509   dump();
510 #endif  // MERGEICMPS_DOT_ON
511 }
512 
513 #ifdef MERGEICMPS_DOT_ON
514 void BCECmpChain::dump() const {
515   errs() << "digraph dag {\n";
516   errs() << " graph [bgcolor=transparent];\n";
517   errs() << " node [color=black,style=filled,fillcolor=lightyellow];\n";
518   errs() << " edge [color=black];\n";
519   for (size_t I = 0; I < Comparisons_.size(); ++I) {
520     const auto &Comparison = Comparisons_[I];
521     errs() << " \"" << I << "\" [label=\"%"
522            << Comparison.Lhs().Base()->getName() << " + "
523            << Comparison.Lhs().Offset << " == %"
524            << Comparison.Rhs().Base()->getName() << " + "
525            << Comparison.Rhs().Offset << " (" << (Comparison.SizeBits() / 8)
526            << " bytes)\"];\n";
527     const Value *const Val = Phi_.getIncomingValueForBlock(Comparison.BB);
528     if (I > 0) errs() << " \"" << (I - 1) << "\" -> \"" << I << "\";\n";
529     errs() << " \"" << I << "\" -> \"Phi\" [label=\"" << *Val << "\"];\n";
530   }
531   errs() << " \"Phi\" [label=\"Phi\"];\n";
532   errs() << "}\n\n";
533 }
534 #endif  // MERGEICMPS_DOT_ON
535 
536 namespace {
537 
538 // A class to compute the name of a set of merged basic blocks.
539 // This is optimized for the common case of no block names.
540 class MergedBlockName {
541   // Storage for the uncommon case of several named blocks.
542   SmallString<16> Scratch;
543 
544 public:
545   explicit MergedBlockName(ArrayRef<BCECmpBlock> Comparisons)
546       : Name(makeName(Comparisons)) {}
547   const StringRef Name;
548 
549 private:
550   StringRef makeName(ArrayRef<BCECmpBlock> Comparisons) {
551     assert(!Comparisons.empty() && "no basic block");
552     // Fast path: only one block, or no names at all.
553     if (Comparisons.size() == 1)
554       return Comparisons[0].BB->getName();
555     const int size = std::accumulate(Comparisons.begin(), Comparisons.end(), 0,
556                                      [](int i, const BCECmpBlock &Cmp) {
557                                        return i + Cmp.BB->getName().size();
558                                      });
559     if (size == 0)
560       return StringRef("", 0);
561 
562     // Slow path: at least two blocks, at least one block with a name.
563     Scratch.clear();
564     // We'll have `size` bytes for name and `Comparisons.size() - 1` bytes for
565     // separators.
566     Scratch.reserve(size + Comparisons.size() - 1);
567     const auto append = [this](StringRef str) {
568       Scratch.append(str.begin(), str.end());
569     };
570     append(Comparisons[0].BB->getName());
571     for (int I = 1, E = Comparisons.size(); I < E; ++I) {
572       const BasicBlock *const BB = Comparisons[I].BB;
573       if (!BB->getName().empty()) {
574         append("+");
575         append(BB->getName());
576       }
577     }
578     return Scratch.str();
579   }
580 };
581 } // namespace
582 
583 // Merges the given contiguous comparison blocks into one memcmp block.
584 static BasicBlock *mergeComparisons(ArrayRef<BCECmpBlock> Comparisons,
585                                     BasicBlock *const InsertBefore,
586                                     BasicBlock *const NextCmpBlock,
587                                     PHINode &Phi, const TargetLibraryInfo &TLI,
588                                     AliasAnalysis &AA, DomTreeUpdater &DTU) {
589   assert(!Comparisons.empty() && "merging zero comparisons");
590   LLVMContext &Context = NextCmpBlock->getContext();
591   const BCECmpBlock &FirstCmp = Comparisons[0];
592 
593   // Create a new cmp block before next cmp block.
594   BasicBlock *const BB =
595       BasicBlock::Create(Context, MergedBlockName(Comparisons).Name,
596                          NextCmpBlock->getParent(), InsertBefore);
597   IRBuilder<> Builder(BB);
598   // Add the GEPs from the first BCECmpBlock.
599   Value *const Lhs = Builder.Insert(FirstCmp.Lhs().GEP->clone());
600   Value *const Rhs = Builder.Insert(FirstCmp.Rhs().GEP->clone());
601 
602   Value *IsEqual = nullptr;
603   LLVM_DEBUG(dbgs() << "Merging " << Comparisons.size() << " comparisons -> "
604                     << BB->getName() << "\n");
605 
606   // If there is one block that requires splitting, we do it now, i.e.
607   // just before we know we will collapse the chain. The instructions
608   // can be executed before any of the instructions in the chain.
609   const auto ToSplit = llvm::find_if(
610       Comparisons, [](const BCECmpBlock &B) { return B.RequireSplit; });
611   if (ToSplit != Comparisons.end()) {
612     LLVM_DEBUG(dbgs() << "Splitting non_BCE work to header\n");
613     ToSplit->split(BB, AA);
614   }
615 
616   if (Comparisons.size() == 1) {
617     LLVM_DEBUG(dbgs() << "Only one comparison, updating branches\n");
618     Value *const LhsLoad =
619         Builder.CreateLoad(FirstCmp.Lhs().LoadI->getType(), Lhs);
620     Value *const RhsLoad =
621         Builder.CreateLoad(FirstCmp.Rhs().LoadI->getType(), Rhs);
622     // There are no blocks to merge, just do the comparison.
623     IsEqual = Builder.CreateICmpEQ(LhsLoad, RhsLoad);
624   } else {
625     const unsigned TotalSizeBits = std::accumulate(
626         Comparisons.begin(), Comparisons.end(), 0u,
627         [](int Size, const BCECmpBlock &C) { return Size + C.SizeBits(); });
628 
629     // Create memcmp() == 0.
630     const auto &DL = Phi.getModule()->getDataLayout();
631     Value *const MemCmpCall = emitMemCmp(
632         Lhs, Rhs,
633         ConstantInt::get(DL.getIntPtrType(Context), TotalSizeBits / 8), Builder,
634         DL, &TLI);
635     IsEqual = Builder.CreateICmpEQ(
636         MemCmpCall, ConstantInt::get(Type::getInt32Ty(Context), 0));
637   }
638 
639   BasicBlock *const PhiBB = Phi.getParent();
640   // Add a branch to the next basic block in the chain.
641   if (NextCmpBlock == PhiBB) {
642     // Continue to phi, passing it the comparison result.
643     Builder.CreateBr(PhiBB);
644     Phi.addIncoming(IsEqual, BB);
645     DTU.applyUpdates({{DominatorTree::Insert, BB, PhiBB}});
646   } else {
647     // Continue to next block if equal, exit to phi else.
648     Builder.CreateCondBr(IsEqual, NextCmpBlock, PhiBB);
649     Phi.addIncoming(ConstantInt::getFalse(Context), BB);
650     DTU.applyUpdates({{DominatorTree::Insert, BB, NextCmpBlock},
651                       {DominatorTree::Insert, BB, PhiBB}});
652   }
653   return BB;
654 }
655 
656 bool BCECmpChain::simplify(const TargetLibraryInfo &TLI, AliasAnalysis &AA,
657                            DomTreeUpdater &DTU) {
658   assert(Comparisons_.size() >= 2 && "simplifying trivial BCECmpChain");
659   // First pass to check if there is at least one merge. If not, we don't do
660   // anything and we keep analysis passes intact.
661   const auto AtLeastOneMerged = [this]() {
662     for (size_t I = 1; I < Comparisons_.size(); ++I) {
663       if (IsContiguous(Comparisons_[I - 1], Comparisons_[I]))
664         return true;
665     }
666     return false;
667   };
668   if (!AtLeastOneMerged())
669     return false;
670 
671   LLVM_DEBUG(dbgs() << "Simplifying comparison chain starting at block "
672                     << EntryBlock_->getName() << "\n");
673 
674   // Effectively merge blocks. We go in the reverse direction from the phi block
675   // so that the next block is always available to branch to.
676   const auto mergeRange = [this, &TLI, &AA, &DTU](int I, int Num,
677                                                   BasicBlock *InsertBefore,
678                                                   BasicBlock *Next) {
679     return mergeComparisons(makeArrayRef(Comparisons_).slice(I, Num),
680                             InsertBefore, Next, Phi_, TLI, AA, DTU);
681   };
682   int NumMerged = 1;
683   BasicBlock *NextCmpBlock = Phi_.getParent();
684   for (int I = static_cast<int>(Comparisons_.size()) - 2; I >= 0; --I) {
685     if (IsContiguous(Comparisons_[I], Comparisons_[I + 1])) {
686       LLVM_DEBUG(dbgs() << "Merging block " << Comparisons_[I].BB->getName()
687                         << " into " << Comparisons_[I + 1].BB->getName()
688                         << "\n");
689       ++NumMerged;
690     } else {
691       NextCmpBlock = mergeRange(I + 1, NumMerged, NextCmpBlock, NextCmpBlock);
692       NumMerged = 1;
693     }
694   }
695   // Insert the entry block for the new chain before the old entry block.
696   // If the old entry block was the function entry, this ensures that the new
697   // entry can become the function entry.
698   NextCmpBlock = mergeRange(0, NumMerged, EntryBlock_, NextCmpBlock);
699 
700   // Replace the original cmp chain with the new cmp chain by pointing all
701   // predecessors of EntryBlock_ to NextCmpBlock instead. This makes all cmp
702   // blocks in the old chain unreachable.
703   while (!pred_empty(EntryBlock_)) {
704     BasicBlock* const Pred = *pred_begin(EntryBlock_);
705     LLVM_DEBUG(dbgs() << "Updating jump into old chain from " << Pred->getName()
706                       << "\n");
707     Pred->getTerminator()->replaceUsesOfWith(EntryBlock_, NextCmpBlock);
708     DTU.applyUpdates({{DominatorTree::Delete, Pred, EntryBlock_},
709                       {DominatorTree::Insert, Pred, NextCmpBlock}});
710   }
711 
712   // If the old cmp chain was the function entry, we need to update the function
713   // entry.
714   const bool ChainEntryIsFnEntry = EntryBlock_->isEntryBlock();
715   if (ChainEntryIsFnEntry && DTU.hasDomTree()) {
716     LLVM_DEBUG(dbgs() << "Changing function entry from "
717                       << EntryBlock_->getName() << " to "
718                       << NextCmpBlock->getName() << "\n");
719     DTU.getDomTree().setNewRoot(NextCmpBlock);
720     DTU.applyUpdates({{DominatorTree::Delete, NextCmpBlock, EntryBlock_}});
721   }
722   EntryBlock_ = nullptr;
723 
724   // Delete merged blocks. This also removes incoming values in phi.
725   SmallVector<BasicBlock *, 16> DeadBlocks;
726   for (auto &Cmp : Comparisons_) {
727     LLVM_DEBUG(dbgs() << "Deleting merged block " << Cmp.BB->getName() << "\n");
728     DeadBlocks.push_back(Cmp.BB);
729   }
730   DeleteDeadBlocks(DeadBlocks, &DTU);
731 
732   Comparisons_.clear();
733   return true;
734 }
735 
736 std::vector<BasicBlock *> getOrderedBlocks(PHINode &Phi,
737                                            BasicBlock *const LastBlock,
738                                            int NumBlocks) {
739   // Walk up from the last block to find other blocks.
740   std::vector<BasicBlock *> Blocks(NumBlocks);
741   assert(LastBlock && "invalid last block");
742   BasicBlock *CurBlock = LastBlock;
743   for (int BlockIndex = NumBlocks - 1; BlockIndex > 0; --BlockIndex) {
744     if (CurBlock->hasAddressTaken()) {
745       // Somebody is jumping to the block through an address, all bets are
746       // off.
747       LLVM_DEBUG(dbgs() << "skip: block " << BlockIndex
748                         << " has its address taken\n");
749       return {};
750     }
751     Blocks[BlockIndex] = CurBlock;
752     auto *SinglePredecessor = CurBlock->getSinglePredecessor();
753     if (!SinglePredecessor) {
754       // The block has two or more predecessors.
755       LLVM_DEBUG(dbgs() << "skip: block " << BlockIndex
756                         << " has two or more predecessors\n");
757       return {};
758     }
759     if (Phi.getBasicBlockIndex(SinglePredecessor) < 0) {
760       // The block does not link back to the phi.
761       LLVM_DEBUG(dbgs() << "skip: block " << BlockIndex
762                         << " does not link back to the phi\n");
763       return {};
764     }
765     CurBlock = SinglePredecessor;
766   }
767   Blocks[0] = CurBlock;
768   return Blocks;
769 }
770 
771 bool processPhi(PHINode &Phi, const TargetLibraryInfo &TLI, AliasAnalysis &AA,
772                 DomTreeUpdater &DTU) {
773   LLVM_DEBUG(dbgs() << "processPhi()\n");
774   if (Phi.getNumIncomingValues() <= 1) {
775     LLVM_DEBUG(dbgs() << "skip: only one incoming value in phi\n");
776     return false;
777   }
778   // We are looking for something that has the following structure:
779   //   bb1 --eq--> bb2 --eq--> bb3 --eq--> bb4 --+
780   //     \            \           \               \
781   //      ne           ne          ne              \
782   //       \            \           \               v
783   //        +------------+-----------+----------> bb_phi
784   //
785   //  - The last basic block (bb4 here) must branch unconditionally to bb_phi.
786   //    It's the only block that contributes a non-constant value to the Phi.
787   //  - All other blocks (b1, b2, b3) must have exactly two successors, one of
788   //    them being the phi block.
789   //  - All intermediate blocks (bb2, bb3) must have only one predecessor.
790   //  - Blocks cannot do other work besides the comparison, see doesOtherWork()
791 
792   // The blocks are not necessarily ordered in the phi, so we start from the
793   // last block and reconstruct the order.
794   BasicBlock *LastBlock = nullptr;
795   for (unsigned I = 0; I < Phi.getNumIncomingValues(); ++I) {
796     if (isa<ConstantInt>(Phi.getIncomingValue(I))) continue;
797     if (LastBlock) {
798       // There are several non-constant values.
799       LLVM_DEBUG(dbgs() << "skip: several non-constant values\n");
800       return false;
801     }
802     if (!isa<ICmpInst>(Phi.getIncomingValue(I)) ||
803         cast<ICmpInst>(Phi.getIncomingValue(I))->getParent() !=
804             Phi.getIncomingBlock(I)) {
805       // Non-constant incoming value is not from a cmp instruction or not
806       // produced by the last block. We could end up processing the value
807       // producing block more than once.
808       //
809       // This is an uncommon case, so we bail.
810       LLVM_DEBUG(
811           dbgs()
812           << "skip: non-constant value not from cmp or not from last block.\n");
813       return false;
814     }
815     LastBlock = Phi.getIncomingBlock(I);
816   }
817   if (!LastBlock) {
818     // There is no non-constant block.
819     LLVM_DEBUG(dbgs() << "skip: no non-constant block\n");
820     return false;
821   }
822   if (LastBlock->getSingleSuccessor() != Phi.getParent()) {
823     LLVM_DEBUG(dbgs() << "skip: last block non-phi successor\n");
824     return false;
825   }
826 
827   const auto Blocks =
828       getOrderedBlocks(Phi, LastBlock, Phi.getNumIncomingValues());
829   if (Blocks.empty()) return false;
830   BCECmpChain CmpChain(Blocks, Phi, AA);
831 
832   if (CmpChain.size() < 2) {
833     LLVM_DEBUG(dbgs() << "skip: only one compare block\n");
834     return false;
835   }
836 
837   return CmpChain.simplify(TLI, AA, DTU);
838 }
839 
840 static bool runImpl(Function &F, const TargetLibraryInfo &TLI,
841                     const TargetTransformInfo &TTI, AliasAnalysis &AA,
842                     DominatorTree *DT) {
843   LLVM_DEBUG(dbgs() << "MergeICmpsLegacyPass: " << F.getName() << "\n");
844 
845   // We only try merging comparisons if the target wants to expand memcmp later.
846   // The rationale is to avoid turning small chains into memcmp calls.
847   if (!TTI.enableMemCmpExpansion(F.hasOptSize(), true))
848     return false;
849 
850   // If we don't have memcmp avaiable we can't emit calls to it.
851   if (!TLI.has(LibFunc_memcmp))
852     return false;
853 
854   DomTreeUpdater DTU(DT, /*PostDominatorTree*/ nullptr,
855                      DomTreeUpdater::UpdateStrategy::Eager);
856 
857   bool MadeChange = false;
858 
859   for (auto BBIt = ++F.begin(); BBIt != F.end(); ++BBIt) {
860     // A Phi operation is always first in a basic block.
861     if (auto *const Phi = dyn_cast<PHINode>(&*BBIt->begin()))
862       MadeChange |= processPhi(*Phi, TLI, AA, DTU);
863   }
864 
865   return MadeChange;
866 }
867 
868 class MergeICmpsLegacyPass : public FunctionPass {
869 public:
870   static char ID;
871 
872   MergeICmpsLegacyPass() : FunctionPass(ID) {
873     initializeMergeICmpsLegacyPassPass(*PassRegistry::getPassRegistry());
874   }
875 
876   bool runOnFunction(Function &F) override {
877     if (skipFunction(F)) return false;
878     const auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
879     const auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
880     // MergeICmps does not need the DominatorTree, but we update it if it's
881     // already available.
882     auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
883     auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
884     return runImpl(F, TLI, TTI, AA, DTWP ? &DTWP->getDomTree() : nullptr);
885   }
886 
887  private:
888   void getAnalysisUsage(AnalysisUsage &AU) const override {
889     AU.addRequired<TargetLibraryInfoWrapperPass>();
890     AU.addRequired<TargetTransformInfoWrapperPass>();
891     AU.addRequired<AAResultsWrapperPass>();
892     AU.addPreserved<GlobalsAAWrapperPass>();
893     AU.addPreserved<DominatorTreeWrapperPass>();
894   }
895 };
896 
897 } // namespace
898 
899 char MergeICmpsLegacyPass::ID = 0;
900 INITIALIZE_PASS_BEGIN(MergeICmpsLegacyPass, "mergeicmps",
901                       "Merge contiguous icmps into a memcmp", false, false)
902 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
903 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
904 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
905 INITIALIZE_PASS_END(MergeICmpsLegacyPass, "mergeicmps",
906                     "Merge contiguous icmps into a memcmp", false, false)
907 
908 Pass *llvm::createMergeICmpsLegacyPass() { return new MergeICmpsLegacyPass(); }
909 
910 PreservedAnalyses MergeICmpsPass::run(Function &F,
911                                       FunctionAnalysisManager &AM) {
912   auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
913   auto &TTI = AM.getResult<TargetIRAnalysis>(F);
914   auto &AA = AM.getResult<AAManager>(F);
915   auto *DT = AM.getCachedResult<DominatorTreeAnalysis>(F);
916   const bool MadeChanges = runImpl(F, TLI, TTI, AA, DT);
917   if (!MadeChanges)
918     return PreservedAnalyses::all();
919   PreservedAnalyses PA;
920   PA.preserve<DominatorTreeAnalysis>();
921   return PA;
922 }
923