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