blob: 62fa49b8860f358d4f119930cd951f3c4ef8516d [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 Zelenko5adb96c2017-10-26 00:55:39 +000022//
Clement Courbet65130e22017-09-01 10:56:34 +000023//===----------------------------------------------------------------------===//
24
Eugene Zelenko5adb96c2017-10-26 00:55:39 +000025#include "llvm/ADT/APInt.h"
26#include "llvm/ADT/ArrayRef.h"
Clement Courbet65130e22017-09-01 10:56:34 +000027#include "llvm/Analysis/Loads.h"
Clement Courbete2e8a5c2017-10-10 08:00:45 +000028#include "llvm/Analysis/TargetLibraryInfo.h"
29#include "llvm/Analysis/TargetTransformInfo.h"
Eugene Zelenko5adb96c2017-10-26 00:55:39 +000030#include "llvm/IR/BasicBlock.h"
31#include "llvm/IR/Constants.h"
32#include "llvm/IR/DataLayout.h"
Clement Courbet65130e22017-09-01 10:56:34 +000033#include "llvm/IR/Function.h"
34#include "llvm/IR/IRBuilder.h"
Eugene Zelenko5adb96c2017-10-26 00:55:39 +000035#include "llvm/IR/Instruction.h"
36#include "llvm/IR/Instructions.h"
37#include "llvm/IR/Module.h"
38#include "llvm/IR/PassManager.h"
39#include "llvm/IR/Type.h"
40#include "llvm/IR/Value.h"
Clement Courbet65130e22017-09-01 10:56:34 +000041#include "llvm/Pass.h"
Eugene Zelenko5adb96c2017-10-26 00:55:39 +000042#include "llvm/Support/Casting.h"
43#include "llvm/Support/Debug.h"
44#include "llvm/Support/raw_ostream.h"
Clement Courbet65130e22017-09-01 10:56:34 +000045#include "llvm/Transforms/Scalar.h"
46#include "llvm/Transforms/Utils/BuildLibCalls.h"
Eugene Zelenko5adb96c2017-10-26 00:55:39 +000047#include <algorithm>
48#include <cassert>
49#include <cstddef>
50#include <numeric>
51#include <utility>
52#include <vector>
Clement Courbet65130e22017-09-01 10:56:34 +000053
54using namespace llvm;
55
Clement Courbet65130e22017-09-01 10:56:34 +000056#define DEBUG_TYPE "mergeicmps"
57
Eugene Zelenko5adb96c2017-10-26 00:55:39 +000058namespace {
59
Clement Courbet65130e22017-09-01 10:56:34 +000060// A BCE atom.
61struct BCEAtom {
Eugene Zelenko5adb96c2017-10-26 00:55:39 +000062 BCEAtom() = default;
Clement Courbetbc0c4452017-09-01 11:51:23 +000063
Clement Courbet65130e22017-09-01 10:56:34 +000064 const Value *Base() const { return GEP ? GEP->getPointerOperand() : nullptr; }
65
66 bool operator<(const BCEAtom &O) const {
Clement Courbete2e8a5c2017-10-10 08:00:45 +000067 assert(Base() && "invalid atom");
68 assert(O.Base() && "invalid atom");
69 // Just ordering by (Base(), Offset) is sufficient. However because this
70 // means that the ordering will depend on the addresses of the base
71 // values, which are not reproducible from run to run. To guarantee
72 // stability, we use the names of the values if they exist; we sort by:
73 // (Base.getName(), Base(), Offset).
74 const int NameCmp = Base()->getName().compare(O.Base()->getName());
75 if (NameCmp == 0) {
76 if (Base() == O.Base()) {
77 return Offset.slt(O.Offset);
78 }
79 return Base() < O.Base();
80 }
81 return NameCmp < 0;
Clement Courbet65130e22017-09-01 10:56:34 +000082 }
83
Eugene Zelenko5adb96c2017-10-26 00:55:39 +000084 GetElementPtrInst *GEP = nullptr;
85 LoadInst *LoadI = nullptr;
Clement Courbet65130e22017-09-01 10:56:34 +000086 APInt Offset;
87};
88
Eugene Zelenko5adb96c2017-10-26 00:55:39 +000089} // end anonymous namespace
90
Clement Courbet65130e22017-09-01 10:56:34 +000091// If this value is a load from a constant offset w.r.t. a base address, and
92// there are no othe rusers of the load or address, returns the base address and
93// the offset.
Eugene Zelenko5adb96c2017-10-26 00:55:39 +000094static BCEAtom visitICmpLoadOperand(Value *const Val) {
Clement Courbet65130e22017-09-01 10:56:34 +000095 BCEAtom Result;
96 if (auto *const LoadI = dyn_cast<LoadInst>(Val)) {
97 DEBUG(dbgs() << "load\n");
98 if (LoadI->isUsedOutsideOfBlock(LoadI->getParent())) {
99 DEBUG(dbgs() << "used outside of block\n");
100 return {};
101 }
102 if (LoadI->isVolatile()) {
103 DEBUG(dbgs() << "volatile\n");
104 return {};
105 }
106 Value *const Addr = LoadI->getOperand(0);
107 if (auto *const GEP = dyn_cast<GetElementPtrInst>(Addr)) {
108 DEBUG(dbgs() << "GEP\n");
109 if (LoadI->isUsedOutsideOfBlock(LoadI->getParent())) {
110 DEBUG(dbgs() << "used outside of block\n");
111 return {};
112 }
113 const auto &DL = GEP->getModule()->getDataLayout();
114 if (!isDereferenceablePointer(GEP, DL)) {
115 DEBUG(dbgs() << "not dereferenceable\n");
116 // We need to make sure that we can do comparison in any order, so we
117 // require memory to be unconditionnally dereferencable.
118 return {};
119 }
120 Result.Offset = APInt(DL.getPointerTypeSizeInBits(GEP->getType()), 0);
121 if (GEP->accumulateConstantOffset(DL, Result.Offset)) {
122 Result.GEP = GEP;
123 Result.LoadI = LoadI;
124 }
125 }
126 }
127 return Result;
128}
129
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000130namespace {
131
Clement Courbet65130e22017-09-01 10:56:34 +0000132// A basic block with a comparison between two BCE atoms.
133// Note: the terminology is misleading: the comparison is symmetric, so there
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000134// is no real {l/r}hs. What we want though is to have the same base on the
135// left (resp. right), so that we can detect consecutive loads. To ensure this
136// we put the smallest atom on the left.
Clement Courbet65130e22017-09-01 10:56:34 +0000137class BCECmpBlock {
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000138public:
139 BCECmpBlock() = default;
Clement Courbet65130e22017-09-01 10:56:34 +0000140
141 BCECmpBlock(BCEAtom L, BCEAtom R, int SizeBits)
142 : Lhs_(L), Rhs_(R), SizeBits_(SizeBits) {
Clement Courbet98eaa882017-10-04 15:13:52 +0000143 if (Rhs_ < Lhs_) std::swap(Rhs_, Lhs_);
Clement Courbet65130e22017-09-01 10:56:34 +0000144 }
145
146 bool IsValid() const {
147 return Lhs_.Base() != nullptr && Rhs_.Base() != nullptr;
148 }
149
150 // Assert the the block is consistent: If valid, it should also have
151 // non-null members besides Lhs_ and Rhs_.
152 void AssertConsistent() const {
153 if (IsValid()) {
154 assert(BB);
155 assert(CmpI);
156 assert(BranchI);
157 }
158 }
159
160 const BCEAtom &Lhs() const { return Lhs_; }
161 const BCEAtom &Rhs() const { return Rhs_; }
162 int SizeBits() const { return SizeBits_; }
163
164 // Returns true if the block does other works besides comparison.
165 bool doesOtherWork() const;
166
167 // The basic block where this comparison happens.
168 BasicBlock *BB = nullptr;
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000169
Clement Courbet65130e22017-09-01 10:56:34 +0000170 // The ICMP for this comparison.
171 ICmpInst *CmpI = nullptr;
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000172
Clement Courbet65130e22017-09-01 10:56:34 +0000173 // The terminating branch.
174 BranchInst *BranchI = nullptr;
175
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000176private:
Clement Courbet65130e22017-09-01 10:56:34 +0000177 BCEAtom Lhs_;
178 BCEAtom Rhs_;
179 int SizeBits_ = 0;
180};
181
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000182} // end anonymous namespace
183
Clement Courbet65130e22017-09-01 10:56:34 +0000184bool BCECmpBlock::doesOtherWork() const {
185 AssertConsistent();
186 // TODO(courbet): Can we allow some other things ? This is very conservative.
187 // We might be able to get away with anything does does not have any side
188 // effects outside of the basic block.
189 // Note: The GEPs and/or loads are not necessarily in the same block.
190 for (const Instruction &Inst : *BB) {
191 if (const auto *const GEP = dyn_cast<GetElementPtrInst>(&Inst)) {
Clement Courbet98eaa882017-10-04 15:13:52 +0000192 if (!(Lhs_.GEP == GEP || Rhs_.GEP == GEP)) return true;
Clement Courbet65130e22017-09-01 10:56:34 +0000193 } else if (const auto *const L = dyn_cast<LoadInst>(&Inst)) {
Clement Courbet98eaa882017-10-04 15:13:52 +0000194 if (!(Lhs_.LoadI == L || Rhs_.LoadI == L)) return true;
Clement Courbet65130e22017-09-01 10:56:34 +0000195 } else if (const auto *const C = dyn_cast<ICmpInst>(&Inst)) {
Clement Courbet98eaa882017-10-04 15:13:52 +0000196 if (C != CmpI) return true;
Clement Courbet65130e22017-09-01 10:56:34 +0000197 } else if (const auto *const Br = dyn_cast<BranchInst>(&Inst)) {
Clement Courbet98eaa882017-10-04 15:13:52 +0000198 if (Br != BranchI) return true;
Clement Courbet65130e22017-09-01 10:56:34 +0000199 } else {
200 return true;
201 }
202 }
203 return false;
204}
205
206// Visit the given comparison. If this is a comparison between two valid
207// BCE atoms, returns the comparison.
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000208static BCECmpBlock visitICmp(const ICmpInst *const CmpI,
209 const ICmpInst::Predicate ExpectedPredicate) {
Clement Courbet65130e22017-09-01 10:56:34 +0000210 if (CmpI->getPredicate() == ExpectedPredicate) {
211 DEBUG(dbgs() << "cmp "
212 << (ExpectedPredicate == ICmpInst::ICMP_EQ ? "eq" : "ne")
213 << "\n");
214 auto Lhs = visitICmpLoadOperand(CmpI->getOperand(0));
Clement Courbet98eaa882017-10-04 15:13:52 +0000215 if (!Lhs.Base()) return {};
Clement Courbet65130e22017-09-01 10:56:34 +0000216 auto Rhs = visitICmpLoadOperand(CmpI->getOperand(1));
Clement Courbet98eaa882017-10-04 15:13:52 +0000217 if (!Rhs.Base()) return {};
Clement Courbet65130e22017-09-01 10:56:34 +0000218 return BCECmpBlock(std::move(Lhs), std::move(Rhs),
219 CmpI->getOperand(0)->getType()->getScalarSizeInBits());
220 }
221 return {};
222}
223
224// Visit the given comparison block. If this is a comparison between two valid
225// BCE atoms, returns the comparison.
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000226static BCECmpBlock visitCmpBlock(Value *const Val, BasicBlock *const Block,
227 const BasicBlock *const PhiBlock) {
Clement Courbet98eaa882017-10-04 15:13:52 +0000228 if (Block->empty()) return {};
Clement Courbet65130e22017-09-01 10:56:34 +0000229 auto *const BranchI = dyn_cast<BranchInst>(Block->getTerminator());
Clement Courbet98eaa882017-10-04 15:13:52 +0000230 if (!BranchI) return {};
Clement Courbet65130e22017-09-01 10:56:34 +0000231 DEBUG(dbgs() << "branch\n");
232 if (BranchI->isUnconditional()) {
233 // In this case, we expect an incoming value which is the result of the
234 // comparison. This is the last link in the chain of comparisons (note
235 // that this does not mean that this is the last incoming value, blocks
236 // can be reordered).
237 auto *const CmpI = dyn_cast<ICmpInst>(Val);
Clement Courbet98eaa882017-10-04 15:13:52 +0000238 if (!CmpI) return {};
Clement Courbet65130e22017-09-01 10:56:34 +0000239 DEBUG(dbgs() << "icmp\n");
240 auto Result = visitICmp(CmpI, ICmpInst::ICMP_EQ);
241 Result.CmpI = CmpI;
242 Result.BranchI = BranchI;
243 return Result;
244 } else {
245 // In this case, we expect a constant incoming value (the comparison is
246 // chained).
247 const auto *const Const = dyn_cast<ConstantInt>(Val);
248 DEBUG(dbgs() << "const\n");
Clement Courbet98eaa882017-10-04 15:13:52 +0000249 if (!Const->isZero()) return {};
Clement Courbet65130e22017-09-01 10:56:34 +0000250 DEBUG(dbgs() << "false\n");
251 auto *const CmpI = dyn_cast<ICmpInst>(BranchI->getCondition());
Clement Courbet98eaa882017-10-04 15:13:52 +0000252 if (!CmpI) return {};
Clement Courbet65130e22017-09-01 10:56:34 +0000253 DEBUG(dbgs() << "icmp\n");
254 assert(BranchI->getNumSuccessors() == 2 && "expecting a cond branch");
255 BasicBlock *const FalseBlock = BranchI->getSuccessor(1);
256 auto Result = visitICmp(
257 CmpI, FalseBlock == PhiBlock ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE);
258 Result.CmpI = CmpI;
259 Result.BranchI = BranchI;
260 return Result;
261 }
262 return {};
263}
264
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000265namespace {
266
Clement Courbet65130e22017-09-01 10:56:34 +0000267// A chain of comparisons.
268class BCECmpChain {
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000269public:
Clement Courbet65130e22017-09-01 10:56:34 +0000270 BCECmpChain(const std::vector<BasicBlock *> &Blocks, PHINode &Phi);
271
272 int size() const { return Comparisons_.size(); }
273
274#ifdef MERGEICMPS_DOT_ON
275 void dump() const;
276#endif // MERGEICMPS_DOT_ON
277
278 bool simplify(const TargetLibraryInfo *const TLI);
279
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000280private:
Clement Courbet65130e22017-09-01 10:56:34 +0000281 static bool IsContiguous(const BCECmpBlock &First,
282 const BCECmpBlock &Second) {
283 return First.Lhs().Base() == Second.Lhs().Base() &&
284 First.Rhs().Base() == Second.Rhs().Base() &&
285 First.Lhs().Offset + First.SizeBits() / 8 == Second.Lhs().Offset &&
286 First.Rhs().Offset + First.SizeBits() / 8 == Second.Rhs().Offset;
287 }
288
289 // Merges the given comparison blocks into one memcmp block and update
290 // branches. Comparisons are assumed to be continguous. If NextBBInChain is
291 // null, the merged block will link to the phi block.
292 static void mergeComparisons(ArrayRef<BCECmpBlock> Comparisons,
293 BasicBlock *const NextBBInChain, PHINode &Phi,
294 const TargetLibraryInfo *const TLI);
295
296 PHINode &Phi_;
297 std::vector<BCECmpBlock> Comparisons_;
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000298
Clement Courbet65130e22017-09-01 10:56:34 +0000299 // The original entry block (before sorting);
300 BasicBlock *EntryBlock_;
301};
302
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000303} // end anonymous namespace
304
Clement Courbet65130e22017-09-01 10:56:34 +0000305BCECmpChain::BCECmpChain(const std::vector<BasicBlock *> &Blocks, PHINode &Phi)
306 : Phi_(Phi) {
307 // Now look inside blocks to check for BCE comparisons.
308 std::vector<BCECmpBlock> Comparisons;
309 for (BasicBlock *Block : Blocks) {
310 BCECmpBlock Comparison = visitCmpBlock(Phi.getIncomingValueForBlock(Block),
311 Block, Phi.getParent());
312 Comparison.BB = Block;
313 if (!Comparison.IsValid()) {
314 DEBUG(dbgs() << "skip: not a valid BCECmpBlock\n");
315 return;
316 }
317 if (Comparison.doesOtherWork()) {
318 DEBUG(dbgs() << "block does extra work besides compare\n");
319 if (Comparisons.empty()) { // First block.
320 // TODO(courbet): The first block can do other things, and we should
321 // split them apart in a separate block before the comparison chain.
322 // Right now we just discard it and make the chain shorter.
323 DEBUG(dbgs()
324 << "ignoring first block that does extra work besides compare\n");
325 continue;
326 }
327 // TODO(courbet): Right now we abort the whole chain. We could be
328 // merging only the blocks that don't do other work and resume the
329 // chain from there. For example:
330 // if (a[0] == b[0]) { // bb1
331 // if (a[1] == b[1]) { // bb2
332 // some_value = 3; //bb3
333 // if (a[2] == b[2]) { //bb3
334 // do a ton of stuff //bb4
335 // }
336 // }
337 // }
338 //
339 // This is:
340 //
341 // bb1 --eq--> bb2 --eq--> bb3* -eq--> bb4 --+
342 // \ \ \ \
343 // ne ne ne \
344 // \ \ \ v
345 // +------------+-----------+----------> bb_phi
346 //
347 // We can only merge the first two comparisons, because bb3* does
348 // "other work" (setting some_value to 3).
349 // We could still merge bb1 and bb2 though.
350 return;
351 }
352 DEBUG(dbgs() << "*Found cmp of " << Comparison.SizeBits()
353 << " bits between " << Comparison.Lhs().Base() << " + "
354 << Comparison.Lhs().Offset << " and "
355 << Comparison.Rhs().Base() << " + " << Comparison.Rhs().Offset
356 << "\n");
357 DEBUG(dbgs() << "\n");
358 Comparisons.push_back(Comparison);
359 }
360 EntryBlock_ = Comparisons[0].BB;
361 Comparisons_ = std::move(Comparisons);
362#ifdef MERGEICMPS_DOT_ON
363 errs() << "BEFORE REORDERING:\n\n";
364 dump();
365#endif // MERGEICMPS_DOT_ON
366 // Reorder blocks by LHS. We can do that without changing the
367 // semantics because we are only accessing dereferencable memory.
368 std::sort(Comparisons_.begin(), Comparisons_.end(),
369 [](const BCECmpBlock &a, const BCECmpBlock &b) {
370 return a.Lhs() < b.Lhs();
371 });
372#ifdef MERGEICMPS_DOT_ON
373 errs() << "AFTER REORDERING:\n\n";
374 dump();
375#endif // MERGEICMPS_DOT_ON
376}
377
378#ifdef MERGEICMPS_DOT_ON
379void BCECmpChain::dump() const {
380 errs() << "digraph dag {\n";
381 errs() << " graph [bgcolor=transparent];\n";
382 errs() << " node [color=black,style=filled,fillcolor=lightyellow];\n";
383 errs() << " edge [color=black];\n";
384 for (size_t I = 0; I < Comparisons_.size(); ++I) {
385 const auto &Comparison = Comparisons_[I];
386 errs() << " \"" << I << "\" [label=\"%"
387 << Comparison.Lhs().Base()->getName() << " + "
388 << Comparison.Lhs().Offset << " == %"
389 << Comparison.Rhs().Base()->getName() << " + "
390 << Comparison.Rhs().Offset << " (" << (Comparison.SizeBits() / 8)
391 << " bytes)\"];\n";
392 const Value *const Val = Phi_.getIncomingValueForBlock(Comparison.BB);
Clement Courbet98eaa882017-10-04 15:13:52 +0000393 if (I > 0) errs() << " \"" << (I - 1) << "\" -> \"" << I << "\";\n";
Clement Courbet65130e22017-09-01 10:56:34 +0000394 errs() << " \"" << I << "\" -> \"Phi\" [label=\"" << *Val << "\"];\n";
395 }
396 errs() << " \"Phi\" [label=\"Phi\"];\n";
397 errs() << "}\n\n";
398}
399#endif // MERGEICMPS_DOT_ON
400
401bool BCECmpChain::simplify(const TargetLibraryInfo *const TLI) {
402 // First pass to check if there is at least one merge. If not, we don't do
403 // anything and we keep analysis passes intact.
404 {
405 bool AtLeastOneMerged = false;
406 for (size_t I = 1; I < Comparisons_.size(); ++I) {
407 if (IsContiguous(Comparisons_[I - 1], Comparisons_[I])) {
408 AtLeastOneMerged = true;
409 break;
410 }
411 }
Clement Courbet98eaa882017-10-04 15:13:52 +0000412 if (!AtLeastOneMerged) return false;
Clement Courbet65130e22017-09-01 10:56:34 +0000413 }
414
415 // Remove phi references to comparison blocks, they will be rebuilt as we
416 // merge the blocks.
417 for (const auto &Comparison : Comparisons_) {
418 Phi_.removeIncomingValue(Comparison.BB, false);
419 }
420
421 // Point the predecessors of the chain to the first comparison block (which is
422 // the new entry point).
423 if (EntryBlock_ != Comparisons_[0].BB)
424 EntryBlock_->replaceAllUsesWith(Comparisons_[0].BB);
425
426 // Effectively merge blocks.
427 int NumMerged = 1;
428 for (size_t I = 1; I < Comparisons_.size(); ++I) {
429 if (IsContiguous(Comparisons_[I - 1], Comparisons_[I])) {
430 ++NumMerged;
431 } else {
432 // Merge all previous comparisons and start a new merge block.
433 mergeComparisons(
434 makeArrayRef(Comparisons_).slice(I - NumMerged, NumMerged),
435 Comparisons_[I].BB, Phi_, TLI);
436 NumMerged = 1;
437 }
438 }
439 mergeComparisons(makeArrayRef(Comparisons_)
440 .slice(Comparisons_.size() - NumMerged, NumMerged),
441 nullptr, Phi_, TLI);
442
443 return true;
444}
445
446void BCECmpChain::mergeComparisons(ArrayRef<BCECmpBlock> Comparisons,
447 BasicBlock *const NextBBInChain,
448 PHINode &Phi,
449 const TargetLibraryInfo *const TLI) {
450 assert(!Comparisons.empty());
451 const auto &FirstComparison = *Comparisons.begin();
452 BasicBlock *const BB = FirstComparison.BB;
453 LLVMContext &Context = BB->getContext();
454
455 if (Comparisons.size() >= 2) {
456 DEBUG(dbgs() << "Merging " << Comparisons.size() << " comparisons\n");
457 const auto TotalSize =
458 std::accumulate(Comparisons.begin(), Comparisons.end(), 0,
459 [](int Size, const BCECmpBlock &C) {
460 return Size + C.SizeBits();
461 }) /
462 8;
463
464 // Incoming edges do not need to be updated, and both GEPs are already
465 // computing the right address, we just need to:
466 // - replace the two loads and the icmp with the memcmp
467 // - update the branch
468 // - update the incoming values in the phi.
469 FirstComparison.BranchI->eraseFromParent();
470 FirstComparison.CmpI->eraseFromParent();
471 FirstComparison.Lhs().LoadI->eraseFromParent();
472 FirstComparison.Rhs().LoadI->eraseFromParent();
473
474 IRBuilder<> Builder(BB);
475 const auto &DL = Phi.getModule()->getDataLayout();
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000476 Value *const MemCmpCall = emitMemCmp(
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000477 FirstComparison.Lhs().GEP, FirstComparison.Rhs().GEP,
478 ConstantInt::get(DL.getIntPtrType(Context), TotalSize),
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000479 Builder, DL, TLI);
Clement Courbet65130e22017-09-01 10:56:34 +0000480 Value *const MemCmpIsZero = Builder.CreateICmpEQ(
481 MemCmpCall, ConstantInt::get(Type::getInt32Ty(Context), 0));
482
483 // Add a branch to the next basic block in the chain.
484 if (NextBBInChain) {
485 Builder.CreateCondBr(MemCmpIsZero, NextBBInChain, Phi.getParent());
486 Phi.addIncoming(ConstantInt::getFalse(Context), BB);
487 } else {
488 Builder.CreateBr(Phi.getParent());
489 Phi.addIncoming(MemCmpIsZero, BB);
490 }
491
492 // Delete merged blocks.
493 for (size_t I = 1; I < Comparisons.size(); ++I) {
494 BasicBlock *CBB = Comparisons[I].BB;
495 CBB->replaceAllUsesWith(BB);
496 CBB->eraseFromParent();
497 }
498 } else {
499 assert(Comparisons.size() == 1);
500 // There are no blocks to merge, but we still need to update the branches.
501 DEBUG(dbgs() << "Only one comparison, updating branches\n");
502 if (NextBBInChain) {
503 if (FirstComparison.BranchI->isConditional()) {
504 DEBUG(dbgs() << "conditional -> conditional\n");
505 // Just update the "true" target, the "false" target should already be
506 // the phi block.
507 assert(FirstComparison.BranchI->getSuccessor(1) == Phi.getParent());
508 FirstComparison.BranchI->setSuccessor(0, NextBBInChain);
509 Phi.addIncoming(ConstantInt::getFalse(Context), BB);
510 } else {
511 DEBUG(dbgs() << "unconditional -> conditional\n");
512 // Replace the unconditional branch by a conditional one.
513 FirstComparison.BranchI->eraseFromParent();
514 IRBuilder<> Builder(BB);
515 Builder.CreateCondBr(FirstComparison.CmpI, NextBBInChain,
516 Phi.getParent());
517 Phi.addIncoming(FirstComparison.CmpI, BB);
518 }
519 } else {
520 if (FirstComparison.BranchI->isConditional()) {
521 DEBUG(dbgs() << "conditional -> unconditional\n");
522 // Replace the conditional branch by an unconditional one.
523 FirstComparison.BranchI->eraseFromParent();
524 IRBuilder<> Builder(BB);
525 Builder.CreateBr(Phi.getParent());
526 Phi.addIncoming(FirstComparison.CmpI, BB);
527 } else {
528 DEBUG(dbgs() << "unconditional -> unconditional\n");
529 Phi.addIncoming(FirstComparison.CmpI, BB);
530 }
531 }
532 }
533}
534
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000535static std::vector<BasicBlock *> getOrderedBlocks(PHINode &Phi,
536 BasicBlock *const LastBlock,
537 int NumBlocks) {
Clement Courbet65130e22017-09-01 10:56:34 +0000538 // Walk up from the last block to find other blocks.
539 std::vector<BasicBlock *> Blocks(NumBlocks);
540 BasicBlock *CurBlock = LastBlock;
541 for (int BlockIndex = NumBlocks - 1; BlockIndex > 0; --BlockIndex) {
542 if (CurBlock->hasAddressTaken()) {
543 // Somebody is jumping to the block through an address, all bets are
544 // off.
545 DEBUG(dbgs() << "skip: block " << BlockIndex
546 << " has its address taken\n");
547 return {};
548 }
549 Blocks[BlockIndex] = CurBlock;
550 auto *SinglePredecessor = CurBlock->getSinglePredecessor();
551 if (!SinglePredecessor) {
552 // The block has two or more predecessors.
553 DEBUG(dbgs() << "skip: block " << BlockIndex
554 << " has two or more predecessors\n");
555 return {};
556 }
557 if (Phi.getBasicBlockIndex(SinglePredecessor) < 0) {
558 // The block does not link back to the phi.
559 DEBUG(dbgs() << "skip: block " << BlockIndex
560 << " does not link back to the phi\n");
561 return {};
562 }
563 CurBlock = SinglePredecessor;
564 }
565 Blocks[0] = CurBlock;
566 return Blocks;
567}
568
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000569static bool processPhi(PHINode &Phi, const TargetLibraryInfo *const TLI) {
Clement Courbet65130e22017-09-01 10:56:34 +0000570 DEBUG(dbgs() << "processPhi()\n");
571 if (Phi.getNumIncomingValues() <= 1) {
572 DEBUG(dbgs() << "skip: only one incoming value in phi\n");
573 return false;
574 }
575 // We are looking for something that has the following structure:
576 // bb1 --eq--> bb2 --eq--> bb3 --eq--> bb4 --+
577 // \ \ \ \
578 // ne ne ne \
579 // \ \ \ v
580 // +------------+-----------+----------> bb_phi
581 //
582 // - The last basic block (bb4 here) must branch unconditionally to bb_phi.
583 // It's the only block that contributes a non-constant value to the Phi.
584 // - All other blocks (b1, b2, b3) must have exactly two successors, one of
585 // them being the the phi block.
586 // - All intermediate blocks (bb2, bb3) must have only one predecessor.
587 // - Blocks cannot do other work besides the comparison, see doesOtherWork()
588
589 // The blocks are not necessarily ordered in the phi, so we start from the
590 // last block and reconstruct the order.
591 BasicBlock *LastBlock = nullptr;
592 for (unsigned I = 0; I < Phi.getNumIncomingValues(); ++I) {
Clement Courbet98eaa882017-10-04 15:13:52 +0000593 if (isa<ConstantInt>(Phi.getIncomingValue(I))) continue;
Clement Courbet65130e22017-09-01 10:56:34 +0000594 if (LastBlock) {
595 // There are several non-constant values.
596 DEBUG(dbgs() << "skip: several non-constant values\n");
597 return false;
598 }
599 LastBlock = Phi.getIncomingBlock(I);
600 }
601 if (!LastBlock) {
602 // There is no non-constant block.
603 DEBUG(dbgs() << "skip: no non-constant block\n");
604 return false;
605 }
606 if (LastBlock->getSingleSuccessor() != Phi.getParent()) {
607 DEBUG(dbgs() << "skip: last block non-phi successor\n");
608 return false;
609 }
610
611 const auto Blocks =
612 getOrderedBlocks(Phi, LastBlock, Phi.getNumIncomingValues());
Clement Courbet98eaa882017-10-04 15:13:52 +0000613 if (Blocks.empty()) return false;
Clement Courbet65130e22017-09-01 10:56:34 +0000614 BCECmpChain CmpChain(Blocks, Phi);
615
616 if (CmpChain.size() < 2) {
617 DEBUG(dbgs() << "skip: only one compare block\n");
618 return false;
619 }
620
621 return CmpChain.simplify(TLI);
622}
623
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000624namespace {
625
Clement Courbet65130e22017-09-01 10:56:34 +0000626class MergeICmps : public FunctionPass {
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000627public:
Clement Courbet65130e22017-09-01 10:56:34 +0000628 static char ID;
629
630 MergeICmps() : FunctionPass(ID) {
631 initializeMergeICmpsPass(*PassRegistry::getPassRegistry());
632 }
633
634 bool runOnFunction(Function &F) override {
635 if (skipFunction(F)) return false;
636 const auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000637 const auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
638 auto PA = runImpl(F, &TLI, &TTI);
Clement Courbet65130e22017-09-01 10:56:34 +0000639 return !PA.areAllPreserved();
640 }
641
Clement Courbet65130e22017-09-01 10:56:34 +0000642 void getAnalysisUsage(AnalysisUsage &AU) const override {
643 AU.addRequired<TargetLibraryInfoWrapperPass>();
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000644 AU.addRequired<TargetTransformInfoWrapperPass>();
Clement Courbet65130e22017-09-01 10:56:34 +0000645 }
646
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000647private:
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000648 PreservedAnalyses runImpl(Function &F, const TargetLibraryInfo *TLI,
649 const TargetTransformInfo *TTI);
Clement Courbet65130e22017-09-01 10:56:34 +0000650};
651
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000652} // end anonymous namespace
653
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000654PreservedAnalyses MergeICmps::runImpl(Function &F, const TargetLibraryInfo *TLI,
655 const TargetTransformInfo *TTI) {
Clement Courbet65130e22017-09-01 10:56:34 +0000656 DEBUG(dbgs() << "MergeICmpsPass: " << F.getName() << "\n");
657
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000658 // We only try merging comparisons if the target wants to expand memcmp later.
659 // The rationale is to avoid turning small chains into memcmp calls.
660 unsigned MaxLoadSize;
661 if (!TTI->enableMemCmpExpansion(MaxLoadSize)) return PreservedAnalyses::all();
662
Clement Courbet65130e22017-09-01 10:56:34 +0000663 bool MadeChange = false;
664
665 for (auto BBIt = ++F.begin(); BBIt != F.end(); ++BBIt) {
666 // A Phi operation is always first in a basic block.
667 if (auto *const Phi = dyn_cast<PHINode>(&*BBIt->begin()))
668 MadeChange |= processPhi(*Phi, TLI);
669 }
670
Clement Courbet98eaa882017-10-04 15:13:52 +0000671 if (MadeChange) return PreservedAnalyses::none();
Clement Courbet65130e22017-09-01 10:56:34 +0000672 return PreservedAnalyses::all();
673}
674
Clement Courbet65130e22017-09-01 10:56:34 +0000675char MergeICmps::ID = 0;
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000676
Clement Courbet65130e22017-09-01 10:56:34 +0000677INITIALIZE_PASS_BEGIN(MergeICmps, "mergeicmps",
678 "Merge contiguous icmps into a memcmp", false, false)
679INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000680INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Clement Courbet65130e22017-09-01 10:56:34 +0000681INITIALIZE_PASS_END(MergeICmps, "mergeicmps",
682 "Merge contiguous icmps into a memcmp", false, false)
683
684Pass *llvm::createMergeICmpsPass() { return new MergeICmps(); }