blob: 4e54f1e47e75887649dad40f222ad62f98fd57ff [file] [log] [blame]
Clement Courbet65130e22017-09-01 10:56:34 +00001//===- MergeICmps.cpp - Optimize chains of integer comparisons ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass turns chains of integer comparisons into memcmp (the memcmp is
11// later typically inlined as a chain of efficient hardware comparisons). This
12// typically benefits c++ member or nonmember operator==().
13//
14// The basic idea is to replace a larger chain of integer comparisons loaded
15// from contiguous memory locations into a smaller chain of such integer
16// comparisons. Benefits are double:
17// - There are less jumps, and therefore less opportunities for mispredictions
18// and I-cache misses.
19// - Code size is smaller, both because jumps are removed and because the
20// encoding of a 2*n byte compare is smaller than that of two n-byte
21// compares.
Eugene Zelenko5c2aece2017-10-26 01:25:14 +000022
Clement Courbet65130e22017-09-01 10:56:34 +000023//===----------------------------------------------------------------------===//
24
Eugene Zelenko5adb96c2017-10-26 00:55:39 +000025#include <algorithm>
Eugene Zelenko5adb96c2017-10-26 00:55:39 +000026#include <numeric>
27#include <utility>
28#include <vector>
Eugene Zelenko5c2aece2017-10-26 01:25:14 +000029#include "llvm/Analysis/Loads.h"
30#include "llvm/Analysis/TargetLibraryInfo.h"
31#include "llvm/Analysis/TargetTransformInfo.h"
32#include "llvm/IR/Function.h"
33#include "llvm/IR/IRBuilder.h"
Eugene Zelenko5c2aece2017-10-26 01:25:14 +000034#include "llvm/Pass.h"
35#include "llvm/Transforms/Scalar.h"
36#include "llvm/Transforms/Utils/BuildLibCalls.h"
Clement Courbet65130e22017-09-01 10:56:34 +000037
38using namespace llvm;
39
Eugene Zelenko5adb96c2017-10-26 00:55:39 +000040namespace {
41
Eugene Zelenko5c2aece2017-10-26 01:25:14 +000042#define DEBUG_TYPE "mergeicmps"
43
Clement Courbet65130e22017-09-01 10:56:34 +000044// A BCE atom.
45struct BCEAtom {
Eugene Zelenko5c2aece2017-10-26 01:25:14 +000046 BCEAtom() : GEP(nullptr), LoadI(nullptr), Offset() {}
Clement Courbetbc0c4452017-09-01 11:51:23 +000047
Clement Courbet65130e22017-09-01 10:56:34 +000048 const Value *Base() const { return GEP ? GEP->getPointerOperand() : nullptr; }
49
50 bool operator<(const BCEAtom &O) const {
Clement Courbete2e8a5c2017-10-10 08:00:45 +000051 assert(Base() && "invalid atom");
52 assert(O.Base() && "invalid atom");
53 // Just ordering by (Base(), Offset) is sufficient. However because this
54 // means that the ordering will depend on the addresses of the base
55 // values, which are not reproducible from run to run. To guarantee
56 // stability, we use the names of the values if they exist; we sort by:
57 // (Base.getName(), Base(), Offset).
58 const int NameCmp = Base()->getName().compare(O.Base()->getName());
59 if (NameCmp == 0) {
60 if (Base() == O.Base()) {
61 return Offset.slt(O.Offset);
62 }
63 return Base() < O.Base();
64 }
65 return NameCmp < 0;
Clement Courbet65130e22017-09-01 10:56:34 +000066 }
67
Eugene Zelenko5c2aece2017-10-26 01:25:14 +000068 GetElementPtrInst *GEP;
69 LoadInst *LoadI;
Clement Courbet65130e22017-09-01 10:56:34 +000070 APInt Offset;
71};
72
73// If this value is a load from a constant offset w.r.t. a base address, and
Xin Tong256869d2018-02-28 12:09:53 +000074// there are no other users of the load or address, returns the base address and
Clement Courbet65130e22017-09-01 10:56:34 +000075// the offset.
Eugene Zelenko5c2aece2017-10-26 01:25:14 +000076BCEAtom visitICmpLoadOperand(Value *const Val) {
Clement Courbet65130e22017-09-01 10:56:34 +000077 BCEAtom Result;
78 if (auto *const LoadI = dyn_cast<LoadInst>(Val)) {
79 DEBUG(dbgs() << "load\n");
80 if (LoadI->isUsedOutsideOfBlock(LoadI->getParent())) {
81 DEBUG(dbgs() << "used outside of block\n");
82 return {};
83 }
84 if (LoadI->isVolatile()) {
85 DEBUG(dbgs() << "volatile\n");
86 return {};
87 }
88 Value *const Addr = LoadI->getOperand(0);
89 if (auto *const GEP = dyn_cast<GetElementPtrInst>(Addr)) {
90 DEBUG(dbgs() << "GEP\n");
91 if (LoadI->isUsedOutsideOfBlock(LoadI->getParent())) {
92 DEBUG(dbgs() << "used outside of block\n");
93 return {};
94 }
95 const auto &DL = GEP->getModule()->getDataLayout();
96 if (!isDereferenceablePointer(GEP, DL)) {
97 DEBUG(dbgs() << "not dereferenceable\n");
98 // We need to make sure that we can do comparison in any order, so we
99 // require memory to be unconditionnally dereferencable.
100 return {};
101 }
102 Result.Offset = APInt(DL.getPointerTypeSizeInBits(GEP->getType()), 0);
103 if (GEP->accumulateConstantOffset(DL, Result.Offset)) {
104 Result.GEP = GEP;
105 Result.LoadI = LoadI;
106 }
107 }
108 }
109 return Result;
110}
111
112// A basic block with a comparison between two BCE atoms.
113// Note: the terminology is misleading: the comparison is symmetric, so there
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000114// is no real {l/r}hs. What we want though is to have the same base on the
115// left (resp. right), so that we can detect consecutive loads. To ensure this
116// we put the smallest atom on the left.
Clement Courbet65130e22017-09-01 10:56:34 +0000117class BCECmpBlock {
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000118 public:
119 BCECmpBlock() {}
Clement Courbet65130e22017-09-01 10:56:34 +0000120
121 BCECmpBlock(BCEAtom L, BCEAtom R, int SizeBits)
122 : Lhs_(L), Rhs_(R), SizeBits_(SizeBits) {
Clement Courbet98eaa882017-10-04 15:13:52 +0000123 if (Rhs_ < Lhs_) std::swap(Rhs_, Lhs_);
Clement Courbet65130e22017-09-01 10:56:34 +0000124 }
125
126 bool IsValid() const {
127 return Lhs_.Base() != nullptr && Rhs_.Base() != nullptr;
128 }
129
Hiroshi Inoued24ddcd2018-01-19 10:55:29 +0000130 // Assert the block is consistent: If valid, it should also have
Clement Courbet65130e22017-09-01 10:56:34 +0000131 // non-null members besides Lhs_ and Rhs_.
132 void AssertConsistent() const {
133 if (IsValid()) {
134 assert(BB);
135 assert(CmpI);
136 assert(BranchI);
137 }
138 }
139
140 const BCEAtom &Lhs() const { return Lhs_; }
141 const BCEAtom &Rhs() const { return Rhs_; }
142 int SizeBits() const { return SizeBits_; }
143
144 // Returns true if the block does other works besides comparison.
145 bool doesOtherWork() const;
146
147 // The basic block where this comparison happens.
148 BasicBlock *BB = nullptr;
149 // The ICMP for this comparison.
150 ICmpInst *CmpI = nullptr;
151 // The terminating branch.
152 BranchInst *BranchI = nullptr;
153
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000154 private:
Clement Courbet65130e22017-09-01 10:56:34 +0000155 BCEAtom Lhs_;
156 BCEAtom Rhs_;
157 int SizeBits_ = 0;
158};
159
160bool BCECmpBlock::doesOtherWork() const {
161 AssertConsistent();
Xin Tong8fd561f2018-03-06 02:24:02 +0000162 // All the instructions we care about in the BCE cmp block.
163 DenseSet<Instruction *> BlockInsts(
164 {Lhs_.GEP, Rhs_.GEP, Lhs_.LoadI, Rhs_.LoadI, CmpI, BranchI});
Clement Courbet65130e22017-09-01 10:56:34 +0000165 // TODO(courbet): Can we allow some other things ? This is very conservative.
166 // We might be able to get away with anything does does not have any side
167 // effects outside of the basic block.
168 // Note: The GEPs and/or loads are not necessarily in the same block.
169 for (const Instruction &Inst : *BB) {
Xin Tong8fd561f2018-03-06 02:24:02 +0000170 if (!BlockInsts.count(&Inst))
Clement Courbet65130e22017-09-01 10:56:34 +0000171 return true;
Clement Courbet65130e22017-09-01 10:56:34 +0000172 }
173 return false;
174}
175
176// Visit the given comparison. If this is a comparison between two valid
177// BCE atoms, returns the comparison.
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000178BCECmpBlock visitICmp(const ICmpInst *const CmpI,
179 const ICmpInst::Predicate ExpectedPredicate) {
Clement Courbet65130e22017-09-01 10:56:34 +0000180 if (CmpI->getPredicate() == ExpectedPredicate) {
181 DEBUG(dbgs() << "cmp "
182 << (ExpectedPredicate == ICmpInst::ICMP_EQ ? "eq" : "ne")
183 << "\n");
184 auto Lhs = visitICmpLoadOperand(CmpI->getOperand(0));
Clement Courbet98eaa882017-10-04 15:13:52 +0000185 if (!Lhs.Base()) return {};
Clement Courbet65130e22017-09-01 10:56:34 +0000186 auto Rhs = visitICmpLoadOperand(CmpI->getOperand(1));
Clement Courbet98eaa882017-10-04 15:13:52 +0000187 if (!Rhs.Base()) return {};
Clement Courbet65130e22017-09-01 10:56:34 +0000188 return BCECmpBlock(std::move(Lhs), std::move(Rhs),
189 CmpI->getOperand(0)->getType()->getScalarSizeInBits());
190 }
191 return {};
192}
193
194// Visit the given comparison block. If this is a comparison between two valid
195// BCE atoms, returns the comparison.
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000196BCECmpBlock visitCmpBlock(Value *const Val, BasicBlock *const Block,
197 const BasicBlock *const PhiBlock) {
Clement Courbet98eaa882017-10-04 15:13:52 +0000198 if (Block->empty()) return {};
Clement Courbet65130e22017-09-01 10:56:34 +0000199 auto *const BranchI = dyn_cast<BranchInst>(Block->getTerminator());
Clement Courbet98eaa882017-10-04 15:13:52 +0000200 if (!BranchI) return {};
Clement Courbet65130e22017-09-01 10:56:34 +0000201 DEBUG(dbgs() << "branch\n");
202 if (BranchI->isUnconditional()) {
203 // In this case, we expect an incoming value which is the result of the
204 // comparison. This is the last link in the chain of comparisons (note
205 // that this does not mean that this is the last incoming value, blocks
206 // can be reordered).
207 auto *const CmpI = dyn_cast<ICmpInst>(Val);
Clement Courbet98eaa882017-10-04 15:13:52 +0000208 if (!CmpI) return {};
Clement Courbet65130e22017-09-01 10:56:34 +0000209 DEBUG(dbgs() << "icmp\n");
210 auto Result = visitICmp(CmpI, ICmpInst::ICMP_EQ);
211 Result.CmpI = CmpI;
212 Result.BranchI = BranchI;
213 return Result;
214 } else {
215 // In this case, we expect a constant incoming value (the comparison is
216 // chained).
217 const auto *const Const = dyn_cast<ConstantInt>(Val);
218 DEBUG(dbgs() << "const\n");
Clement Courbet98eaa882017-10-04 15:13:52 +0000219 if (!Const->isZero()) return {};
Clement Courbet65130e22017-09-01 10:56:34 +0000220 DEBUG(dbgs() << "false\n");
221 auto *const CmpI = dyn_cast<ICmpInst>(BranchI->getCondition());
Clement Courbet98eaa882017-10-04 15:13:52 +0000222 if (!CmpI) return {};
Clement Courbet65130e22017-09-01 10:56:34 +0000223 DEBUG(dbgs() << "icmp\n");
224 assert(BranchI->getNumSuccessors() == 2 && "expecting a cond branch");
225 BasicBlock *const FalseBlock = BranchI->getSuccessor(1);
226 auto Result = visitICmp(
227 CmpI, FalseBlock == PhiBlock ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE);
228 Result.CmpI = CmpI;
229 Result.BranchI = BranchI;
230 return Result;
231 }
232 return {};
233}
234
235// A chain of comparisons.
236class BCECmpChain {
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000237 public:
Clement Courbet65130e22017-09-01 10:56:34 +0000238 BCECmpChain(const std::vector<BasicBlock *> &Blocks, PHINode &Phi);
239
240 int size() const { return Comparisons_.size(); }
241
242#ifdef MERGEICMPS_DOT_ON
243 void dump() const;
244#endif // MERGEICMPS_DOT_ON
245
246 bool simplify(const TargetLibraryInfo *const TLI);
247
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000248 private:
Clement Courbet65130e22017-09-01 10:56:34 +0000249 static bool IsContiguous(const BCECmpBlock &First,
250 const BCECmpBlock &Second) {
251 return First.Lhs().Base() == Second.Lhs().Base() &&
252 First.Rhs().Base() == Second.Rhs().Base() &&
253 First.Lhs().Offset + First.SizeBits() / 8 == Second.Lhs().Offset &&
254 First.Rhs().Offset + First.SizeBits() / 8 == Second.Rhs().Offset;
255 }
256
257 // Merges the given comparison blocks into one memcmp block and update
258 // branches. Comparisons are assumed to be continguous. If NextBBInChain is
259 // null, the merged block will link to the phi block.
260 static void mergeComparisons(ArrayRef<BCECmpBlock> Comparisons,
261 BasicBlock *const NextBBInChain, PHINode &Phi,
262 const TargetLibraryInfo *const TLI);
263
264 PHINode &Phi_;
265 std::vector<BCECmpBlock> Comparisons_;
266 // The original entry block (before sorting);
267 BasicBlock *EntryBlock_;
268};
269
270BCECmpChain::BCECmpChain(const std::vector<BasicBlock *> &Blocks, PHINode &Phi)
271 : Phi_(Phi) {
Clement Courbetc2109c82018-02-06 09:14:00 +0000272 assert(!Blocks.empty() && "a chain should have at least one block");
Clement Courbet65130e22017-09-01 10:56:34 +0000273 // Now look inside blocks to check for BCE comparisons.
274 std::vector<BCECmpBlock> Comparisons;
Clement Courbeta7a17462018-02-06 12:25:33 +0000275 for (size_t BlockIdx = 0; BlockIdx < Blocks.size(); ++BlockIdx) {
276 BasicBlock *const Block = Blocks[BlockIdx];
Clement Courbetc2109c82018-02-06 09:14:00 +0000277 assert(Block && "invalid block");
Clement Courbet65130e22017-09-01 10:56:34 +0000278 BCECmpBlock Comparison = visitCmpBlock(Phi.getIncomingValueForBlock(Block),
279 Block, Phi.getParent());
280 Comparison.BB = Block;
281 if (!Comparison.IsValid()) {
282 DEBUG(dbgs() << "skip: not a valid BCECmpBlock\n");
283 return;
284 }
285 if (Comparison.doesOtherWork()) {
Clement Courbet34be1b02018-03-05 08:21:47 +0000286 DEBUG(dbgs() << "block '" << Comparison.BB->getName()
287 << "' does extra work besides compare\n");
Xin Tong8345c0e2018-03-05 13:54:47 +0000288 if (Comparisons.empty()) {
289 // TODO(courbet): The initial block can do other things, and we should
Clement Courbet65130e22017-09-01 10:56:34 +0000290 // split them apart in a separate block before the comparison chain.
291 // Right now we just discard it and make the chain shorter.
292 DEBUG(dbgs()
Xin Tong98af9ef2018-03-06 02:04:57 +0000293 << "ignoring initial block '" << Comparison.BB->getName()
Clement Courbet34be1b02018-03-05 08:21:47 +0000294 << "' that does extra work besides compare\n");
Clement Courbet65130e22017-09-01 10:56:34 +0000295 continue;
296 }
297 // TODO(courbet): Right now we abort the whole chain. We could be
298 // merging only the blocks that don't do other work and resume the
299 // chain from there. For example:
300 // if (a[0] == b[0]) { // bb1
301 // if (a[1] == b[1]) { // bb2
302 // some_value = 3; //bb3
303 // if (a[2] == b[2]) { //bb3
304 // do a ton of stuff //bb4
305 // }
306 // }
307 // }
308 //
309 // This is:
310 //
311 // bb1 --eq--> bb2 --eq--> bb3* -eq--> bb4 --+
312 // \ \ \ \
313 // ne ne ne \
314 // \ \ \ v
315 // +------------+-----------+----------> bb_phi
316 //
317 // We can only merge the first two comparisons, because bb3* does
318 // "other work" (setting some_value to 3).
319 // We could still merge bb1 and bb2 though.
320 return;
321 }
Clement Courbet34be1b02018-03-05 08:21:47 +0000322 DEBUG(dbgs() << "Block '" << Comparison.BB->getName()<< "': Found cmp of "
323 << Comparison.SizeBits() << " bits between "
324 << Comparison.Lhs().Base() << " + " << Comparison.Lhs().Offset
325 << " and " << Comparison.Rhs().Base() << " + "
326 << Comparison.Rhs().Offset << "\n");
Clement Courbet65130e22017-09-01 10:56:34 +0000327 DEBUG(dbgs() << "\n");
328 Comparisons.push_back(Comparison);
329 }
Xin Tong8345c0e2018-03-05 13:54:47 +0000330
331 // It is possible we have no suitable comparison to merge.
332 if (Comparisons.empty()) {
333 DEBUG(dbgs() << "chain with no BCE basic blocks, no merge\n");
334 return;
335 }
Clement Courbet65130e22017-09-01 10:56:34 +0000336 EntryBlock_ = Comparisons[0].BB;
337 Comparisons_ = std::move(Comparisons);
338#ifdef MERGEICMPS_DOT_ON
339 errs() << "BEFORE REORDERING:\n\n";
340 dump();
341#endif // MERGEICMPS_DOT_ON
342 // Reorder blocks by LHS. We can do that without changing the
343 // semantics because we are only accessing dereferencable memory.
344 std::sort(Comparisons_.begin(), Comparisons_.end(),
345 [](const BCECmpBlock &a, const BCECmpBlock &b) {
346 return a.Lhs() < b.Lhs();
347 });
348#ifdef MERGEICMPS_DOT_ON
349 errs() << "AFTER REORDERING:\n\n";
350 dump();
351#endif // MERGEICMPS_DOT_ON
352}
353
354#ifdef MERGEICMPS_DOT_ON
355void BCECmpChain::dump() const {
356 errs() << "digraph dag {\n";
357 errs() << " graph [bgcolor=transparent];\n";
358 errs() << " node [color=black,style=filled,fillcolor=lightyellow];\n";
359 errs() << " edge [color=black];\n";
360 for (size_t I = 0; I < Comparisons_.size(); ++I) {
361 const auto &Comparison = Comparisons_[I];
362 errs() << " \"" << I << "\" [label=\"%"
363 << Comparison.Lhs().Base()->getName() << " + "
364 << Comparison.Lhs().Offset << " == %"
365 << Comparison.Rhs().Base()->getName() << " + "
366 << Comparison.Rhs().Offset << " (" << (Comparison.SizeBits() / 8)
367 << " bytes)\"];\n";
368 const Value *const Val = Phi_.getIncomingValueForBlock(Comparison.BB);
Clement Courbet98eaa882017-10-04 15:13:52 +0000369 if (I > 0) errs() << " \"" << (I - 1) << "\" -> \"" << I << "\";\n";
Clement Courbet65130e22017-09-01 10:56:34 +0000370 errs() << " \"" << I << "\" -> \"Phi\" [label=\"" << *Val << "\"];\n";
371 }
372 errs() << " \"Phi\" [label=\"Phi\"];\n";
373 errs() << "}\n\n";
374}
375#endif // MERGEICMPS_DOT_ON
376
377bool BCECmpChain::simplify(const TargetLibraryInfo *const TLI) {
378 // First pass to check if there is at least one merge. If not, we don't do
379 // anything and we keep analysis passes intact.
380 {
381 bool AtLeastOneMerged = false;
382 for (size_t I = 1; I < Comparisons_.size(); ++I) {
383 if (IsContiguous(Comparisons_[I - 1], Comparisons_[I])) {
384 AtLeastOneMerged = true;
385 break;
386 }
387 }
Clement Courbet98eaa882017-10-04 15:13:52 +0000388 if (!AtLeastOneMerged) return false;
Clement Courbet65130e22017-09-01 10:56:34 +0000389 }
390
391 // Remove phi references to comparison blocks, they will be rebuilt as we
392 // merge the blocks.
393 for (const auto &Comparison : Comparisons_) {
394 Phi_.removeIncomingValue(Comparison.BB, false);
395 }
396
397 // Point the predecessors of the chain to the first comparison block (which is
398 // the new entry point).
399 if (EntryBlock_ != Comparisons_[0].BB)
400 EntryBlock_->replaceAllUsesWith(Comparisons_[0].BB);
401
402 // Effectively merge blocks.
403 int NumMerged = 1;
404 for (size_t I = 1; I < Comparisons_.size(); ++I) {
405 if (IsContiguous(Comparisons_[I - 1], Comparisons_[I])) {
406 ++NumMerged;
407 } else {
408 // Merge all previous comparisons and start a new merge block.
409 mergeComparisons(
410 makeArrayRef(Comparisons_).slice(I - NumMerged, NumMerged),
411 Comparisons_[I].BB, Phi_, TLI);
412 NumMerged = 1;
413 }
414 }
415 mergeComparisons(makeArrayRef(Comparisons_)
416 .slice(Comparisons_.size() - NumMerged, NumMerged),
417 nullptr, Phi_, TLI);
418
419 return true;
420}
421
422void BCECmpChain::mergeComparisons(ArrayRef<BCECmpBlock> Comparisons,
423 BasicBlock *const NextBBInChain,
424 PHINode &Phi,
425 const TargetLibraryInfo *const TLI) {
426 assert(!Comparisons.empty());
427 const auto &FirstComparison = *Comparisons.begin();
428 BasicBlock *const BB = FirstComparison.BB;
429 LLVMContext &Context = BB->getContext();
430
431 if (Comparisons.size() >= 2) {
432 DEBUG(dbgs() << "Merging " << Comparisons.size() << " comparisons\n");
433 const auto TotalSize =
434 std::accumulate(Comparisons.begin(), Comparisons.end(), 0,
435 [](int Size, const BCECmpBlock &C) {
436 return Size + C.SizeBits();
437 }) /
438 8;
439
440 // Incoming edges do not need to be updated, and both GEPs are already
441 // computing the right address, we just need to:
442 // - replace the two loads and the icmp with the memcmp
443 // - update the branch
444 // - update the incoming values in the phi.
445 FirstComparison.BranchI->eraseFromParent();
446 FirstComparison.CmpI->eraseFromParent();
447 FirstComparison.Lhs().LoadI->eraseFromParent();
448 FirstComparison.Rhs().LoadI->eraseFromParent();
449
450 IRBuilder<> Builder(BB);
451 const auto &DL = Phi.getModule()->getDataLayout();
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000452 Value *const MemCmpCall = emitMemCmp(
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000453 FirstComparison.Lhs().GEP, FirstComparison.Rhs().GEP, ConstantInt::get(DL.getIntPtrType(Context), TotalSize),
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000454 Builder, DL, TLI);
Clement Courbet65130e22017-09-01 10:56:34 +0000455 Value *const MemCmpIsZero = Builder.CreateICmpEQ(
456 MemCmpCall, ConstantInt::get(Type::getInt32Ty(Context), 0));
457
458 // Add a branch to the next basic block in the chain.
459 if (NextBBInChain) {
460 Builder.CreateCondBr(MemCmpIsZero, NextBBInChain, Phi.getParent());
461 Phi.addIncoming(ConstantInt::getFalse(Context), BB);
462 } else {
463 Builder.CreateBr(Phi.getParent());
464 Phi.addIncoming(MemCmpIsZero, BB);
465 }
466
467 // Delete merged blocks.
468 for (size_t I = 1; I < Comparisons.size(); ++I) {
469 BasicBlock *CBB = Comparisons[I].BB;
470 CBB->replaceAllUsesWith(BB);
471 CBB->eraseFromParent();
472 }
473 } else {
474 assert(Comparisons.size() == 1);
475 // There are no blocks to merge, but we still need to update the branches.
476 DEBUG(dbgs() << "Only one comparison, updating branches\n");
477 if (NextBBInChain) {
478 if (FirstComparison.BranchI->isConditional()) {
479 DEBUG(dbgs() << "conditional -> conditional\n");
480 // Just update the "true" target, the "false" target should already be
481 // the phi block.
482 assert(FirstComparison.BranchI->getSuccessor(1) == Phi.getParent());
483 FirstComparison.BranchI->setSuccessor(0, NextBBInChain);
484 Phi.addIncoming(ConstantInt::getFalse(Context), BB);
485 } else {
486 DEBUG(dbgs() << "unconditional -> conditional\n");
487 // Replace the unconditional branch by a conditional one.
488 FirstComparison.BranchI->eraseFromParent();
489 IRBuilder<> Builder(BB);
490 Builder.CreateCondBr(FirstComparison.CmpI, NextBBInChain,
491 Phi.getParent());
492 Phi.addIncoming(FirstComparison.CmpI, BB);
493 }
494 } else {
495 if (FirstComparison.BranchI->isConditional()) {
496 DEBUG(dbgs() << "conditional -> unconditional\n");
497 // Replace the conditional branch by an unconditional one.
498 FirstComparison.BranchI->eraseFromParent();
499 IRBuilder<> Builder(BB);
500 Builder.CreateBr(Phi.getParent());
501 Phi.addIncoming(FirstComparison.CmpI, BB);
502 } else {
503 DEBUG(dbgs() << "unconditional -> unconditional\n");
504 Phi.addIncoming(FirstComparison.CmpI, BB);
505 }
506 }
507 }
508}
509
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000510std::vector<BasicBlock *> getOrderedBlocks(PHINode &Phi,
511 BasicBlock *const LastBlock,
512 int NumBlocks) {
Clement Courbet65130e22017-09-01 10:56:34 +0000513 // Walk up from the last block to find other blocks.
514 std::vector<BasicBlock *> Blocks(NumBlocks);
Clement Courbetc2109c82018-02-06 09:14:00 +0000515 assert(LastBlock && "invalid last block");
Clement Courbet65130e22017-09-01 10:56:34 +0000516 BasicBlock *CurBlock = LastBlock;
517 for (int BlockIndex = NumBlocks - 1; BlockIndex > 0; --BlockIndex) {
518 if (CurBlock->hasAddressTaken()) {
519 // Somebody is jumping to the block through an address, all bets are
520 // off.
521 DEBUG(dbgs() << "skip: block " << BlockIndex
522 << " has its address taken\n");
523 return {};
524 }
525 Blocks[BlockIndex] = CurBlock;
526 auto *SinglePredecessor = CurBlock->getSinglePredecessor();
527 if (!SinglePredecessor) {
528 // The block has two or more predecessors.
529 DEBUG(dbgs() << "skip: block " << BlockIndex
530 << " has two or more predecessors\n");
531 return {};
532 }
533 if (Phi.getBasicBlockIndex(SinglePredecessor) < 0) {
534 // The block does not link back to the phi.
535 DEBUG(dbgs() << "skip: block " << BlockIndex
536 << " does not link back to the phi\n");
537 return {};
538 }
539 CurBlock = SinglePredecessor;
540 }
541 Blocks[0] = CurBlock;
542 return Blocks;
543}
544
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000545bool processPhi(PHINode &Phi, const TargetLibraryInfo *const TLI) {
Clement Courbet65130e22017-09-01 10:56:34 +0000546 DEBUG(dbgs() << "processPhi()\n");
547 if (Phi.getNumIncomingValues() <= 1) {
548 DEBUG(dbgs() << "skip: only one incoming value in phi\n");
549 return false;
550 }
551 // We are looking for something that has the following structure:
552 // bb1 --eq--> bb2 --eq--> bb3 --eq--> bb4 --+
553 // \ \ \ \
554 // ne ne ne \
555 // \ \ \ v
556 // +------------+-----------+----------> bb_phi
557 //
558 // - The last basic block (bb4 here) must branch unconditionally to bb_phi.
559 // It's the only block that contributes a non-constant value to the Phi.
560 // - All other blocks (b1, b2, b3) must have exactly two successors, one of
Hiroshi Inoued24ddcd2018-01-19 10:55:29 +0000561 // them being the phi block.
Clement Courbet65130e22017-09-01 10:56:34 +0000562 // - All intermediate blocks (bb2, bb3) must have only one predecessor.
563 // - Blocks cannot do other work besides the comparison, see doesOtherWork()
564
565 // The blocks are not necessarily ordered in the phi, so we start from the
566 // last block and reconstruct the order.
567 BasicBlock *LastBlock = nullptr;
568 for (unsigned I = 0; I < Phi.getNumIncomingValues(); ++I) {
Clement Courbet98eaa882017-10-04 15:13:52 +0000569 if (isa<ConstantInt>(Phi.getIncomingValue(I))) continue;
Clement Courbet65130e22017-09-01 10:56:34 +0000570 if (LastBlock) {
571 // There are several non-constant values.
572 DEBUG(dbgs() << "skip: several non-constant values\n");
573 return false;
574 }
Xin Tong8ba674e2018-02-28 12:08:00 +0000575 if (!isa<ICmpInst>(Phi.getIncomingValue(I)) ||
576 cast<ICmpInst>(Phi.getIncomingValue(I))->getParent() !=
577 Phi.getIncomingBlock(I)) {
578 // Non-constant incoming value is not from a cmp instruction or not
579 // produced by the last block. We could end up processing the value
580 // producing block more than once.
581 //
582 // This is an uncommon case, so we bail.
583 DEBUG(
584 dbgs()
585 << "skip: non-constant value not from cmp or not from last block.\n");
586 return false;
587 }
Clement Courbet65130e22017-09-01 10:56:34 +0000588 LastBlock = Phi.getIncomingBlock(I);
589 }
590 if (!LastBlock) {
591 // There is no non-constant block.
592 DEBUG(dbgs() << "skip: no non-constant block\n");
593 return false;
594 }
595 if (LastBlock->getSingleSuccessor() != Phi.getParent()) {
596 DEBUG(dbgs() << "skip: last block non-phi successor\n");
597 return false;
598 }
599
600 const auto Blocks =
601 getOrderedBlocks(Phi, LastBlock, Phi.getNumIncomingValues());
Clement Courbet98eaa882017-10-04 15:13:52 +0000602 if (Blocks.empty()) return false;
Clement Courbet65130e22017-09-01 10:56:34 +0000603 BCECmpChain CmpChain(Blocks, Phi);
604
605 if (CmpChain.size() < 2) {
606 DEBUG(dbgs() << "skip: only one compare block\n");
607 return false;
608 }
609
610 return CmpChain.simplify(TLI);
611}
612
613class MergeICmps : public FunctionPass {
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000614 public:
Clement Courbet65130e22017-09-01 10:56:34 +0000615 static char ID;
616
617 MergeICmps() : FunctionPass(ID) {
618 initializeMergeICmpsPass(*PassRegistry::getPassRegistry());
619 }
620
621 bool runOnFunction(Function &F) override {
622 if (skipFunction(F)) return false;
623 const auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000624 const auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
625 auto PA = runImpl(F, &TLI, &TTI);
Clement Courbet65130e22017-09-01 10:56:34 +0000626 return !PA.areAllPreserved();
627 }
628
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000629 private:
Clement Courbet65130e22017-09-01 10:56:34 +0000630 void getAnalysisUsage(AnalysisUsage &AU) const override {
631 AU.addRequired<TargetLibraryInfoWrapperPass>();
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000632 AU.addRequired<TargetTransformInfoWrapperPass>();
Clement Courbet65130e22017-09-01 10:56:34 +0000633 }
634
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000635 PreservedAnalyses runImpl(Function &F, const TargetLibraryInfo *TLI,
636 const TargetTransformInfo *TTI);
Clement Courbet65130e22017-09-01 10:56:34 +0000637};
638
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000639PreservedAnalyses MergeICmps::runImpl(Function &F, const TargetLibraryInfo *TLI,
640 const TargetTransformInfo *TTI) {
Clement Courbet65130e22017-09-01 10:56:34 +0000641 DEBUG(dbgs() << "MergeICmpsPass: " << F.getName() << "\n");
642
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000643 // We only try merging comparisons if the target wants to expand memcmp later.
644 // The rationale is to avoid turning small chains into memcmp calls.
Clement Courbetb2c3eb82017-10-30 14:19:33 +0000645 if (!TTI->enableMemCmpExpansion(true)) return PreservedAnalyses::all();
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000646
Clement Courbet65130e22017-09-01 10:56:34 +0000647 bool MadeChange = false;
648
649 for (auto BBIt = ++F.begin(); BBIt != F.end(); ++BBIt) {
650 // A Phi operation is always first in a basic block.
651 if (auto *const Phi = dyn_cast<PHINode>(&*BBIt->begin()))
652 MadeChange |= processPhi(*Phi, TLI);
653 }
654
Clement Courbet98eaa882017-10-04 15:13:52 +0000655 if (MadeChange) return PreservedAnalyses::none();
Clement Courbet65130e22017-09-01 10:56:34 +0000656 return PreservedAnalyses::all();
657}
658
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000659} // namespace
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000660
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000661char MergeICmps::ID = 0;
Clement Courbet65130e22017-09-01 10:56:34 +0000662INITIALIZE_PASS_BEGIN(MergeICmps, "mergeicmps",
663 "Merge contiguous icmps into a memcmp", false, false)
664INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000665INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Clement Courbet65130e22017-09-01 10:56:34 +0000666INITIALIZE_PASS_END(MergeICmps, "mergeicmps",
667 "Merge contiguous icmps into a memcmp", false, false)
668
669Pass *llvm::createMergeICmpsPass() { return new MergeICmps(); }