blob: 1244a9776fac254df785c292bb79c0df5077e258 [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.
22
23//===----------------------------------------------------------------------===//
24
Clement Courbet98eaa882017-10-04 15:13:52 +000025#include <algorithm>
26#include <numeric>
27#include <utility>
28#include <vector>
Clement Courbet65130e22017-09-01 10:56:34 +000029#include "llvm/ADT/APSInt.h"
30#include "llvm/Analysis/Loads.h"
Clement Courbet4e1bae82017-10-06 12:12:35 +000031#include "llvm/Analysis/TargetLibraryInfo.h"
32#include "llvm/Analysis/TargetTransformInfo.h"
Clement Courbet65130e22017-09-01 10:56:34 +000033#include "llvm/IR/Function.h"
34#include "llvm/IR/IRBuilder.h"
35#include "llvm/IR/IntrinsicInst.h"
36#include "llvm/Pass.h"
37#include "llvm/Transforms/Scalar.h"
38#include "llvm/Transforms/Utils/BuildLibCalls.h"
Clement Courbet65130e22017-09-01 10:56:34 +000039
40using namespace llvm;
41
42namespace {
43
44#define DEBUG_TYPE "mergeicmps"
45
Clement Courbet65130e22017-09-01 10:56:34 +000046// A BCE atom.
47struct BCEAtom {
Clement Courbetbc0c4452017-09-01 11:51:23 +000048 BCEAtom() : GEP(nullptr), LoadI(nullptr), Offset() {}
49
Clement Courbet65130e22017-09-01 10:56:34 +000050 const Value *Base() const { return GEP ? GEP->getPointerOperand() : nullptr; }
51
52 bool operator<(const BCEAtom &O) const {
Clement Courbet4e1bae82017-10-06 12:12:35 +000053 assert(Base() && "invalid atom");
54 assert(O.Base() && "invalid atom");
55 // Just ordering by (Base(), Offset) is sufficient. However because this
56 // means that the ordering will depend on the addresses of the base
57 // values, which are not reproducible from run to run. To guarantee
58 // stability, we use the names of the values if they exist; we sort by:
59 // (Base.getName(), Base(), Offset).
60 const int NameCmp = Base()->getName().compare(O.Base()->getName());
61 if (NameCmp == 0) {
62 if (Base() == O.Base()) {
63 return Offset.slt(O.Offset);
64 }
65 return Base() < O.Base();
66 }
67 return NameCmp < 0;
Clement Courbet65130e22017-09-01 10:56:34 +000068 }
69
Clement Courbetbc0c4452017-09-01 11:51:23 +000070 GetElementPtrInst *GEP;
71 LoadInst *LoadI;
Clement Courbet65130e22017-09-01 10:56:34 +000072 APInt Offset;
73};
74
75// If this value is a load from a constant offset w.r.t. a base address, and
76// there are no othe rusers of the load or address, returns the base address and
77// the offset.
78BCEAtom visitICmpLoadOperand(Value *const Val) {
79 BCEAtom Result;
80 if (auto *const LoadI = dyn_cast<LoadInst>(Val)) {
81 DEBUG(dbgs() << "load\n");
82 if (LoadI->isUsedOutsideOfBlock(LoadI->getParent())) {
83 DEBUG(dbgs() << "used outside of block\n");
84 return {};
85 }
86 if (LoadI->isVolatile()) {
87 DEBUG(dbgs() << "volatile\n");
88 return {};
89 }
90 Value *const Addr = LoadI->getOperand(0);
91 if (auto *const GEP = dyn_cast<GetElementPtrInst>(Addr)) {
92 DEBUG(dbgs() << "GEP\n");
93 if (LoadI->isUsedOutsideOfBlock(LoadI->getParent())) {
94 DEBUG(dbgs() << "used outside of block\n");
95 return {};
96 }
97 const auto &DL = GEP->getModule()->getDataLayout();
98 if (!isDereferenceablePointer(GEP, DL)) {
99 DEBUG(dbgs() << "not dereferenceable\n");
100 // We need to make sure that we can do comparison in any order, so we
101 // require memory to be unconditionnally dereferencable.
102 return {};
103 }
104 Result.Offset = APInt(DL.getPointerTypeSizeInBits(GEP->getType()), 0);
105 if (GEP->accumulateConstantOffset(DL, Result.Offset)) {
106 Result.GEP = GEP;
107 Result.LoadI = LoadI;
108 }
109 }
110 }
111 return Result;
112}
113
114// A basic block with a comparison between two BCE atoms.
115// Note: the terminology is misleading: the comparison is symmetric, so there
Clement Courbet4e1bae82017-10-06 12:12:35 +0000116// is no real {l/r}hs. What we want though is to have the same base on the
117// left (resp. right), so that we can detect consecutive loads. To ensure this
118// we put the smallest atom on the left.
Clement Courbet65130e22017-09-01 10:56:34 +0000119class BCECmpBlock {
120 public:
121 BCECmpBlock() {}
122
123 BCECmpBlock(BCEAtom L, BCEAtom R, int SizeBits)
124 : Lhs_(L), Rhs_(R), SizeBits_(SizeBits) {
Clement Courbet98eaa882017-10-04 15:13:52 +0000125 if (Rhs_ < Lhs_) std::swap(Rhs_, Lhs_);
Clement Courbet65130e22017-09-01 10:56:34 +0000126 }
127
128 bool IsValid() const {
129 return Lhs_.Base() != nullptr && Rhs_.Base() != nullptr;
130 }
131
132 // Assert the the block is consistent: If valid, it should also have
133 // non-null members besides Lhs_ and Rhs_.
134 void AssertConsistent() const {
135 if (IsValid()) {
136 assert(BB);
137 assert(CmpI);
138 assert(BranchI);
139 }
140 }
141
142 const BCEAtom &Lhs() const { return Lhs_; }
143 const BCEAtom &Rhs() const { return Rhs_; }
144 int SizeBits() const { return SizeBits_; }
145
146 // Returns true if the block does other works besides comparison.
147 bool doesOtherWork() const;
148
149 // The basic block where this comparison happens.
150 BasicBlock *BB = nullptr;
151 // The ICMP for this comparison.
152 ICmpInst *CmpI = nullptr;
153 // The terminating branch.
154 BranchInst *BranchI = nullptr;
155
156 private:
157 BCEAtom Lhs_;
158 BCEAtom Rhs_;
159 int SizeBits_ = 0;
160};
161
162bool BCECmpBlock::doesOtherWork() const {
163 AssertConsistent();
164 // TODO(courbet): Can we allow some other things ? This is very conservative.
165 // We might be able to get away with anything does does not have any side
166 // effects outside of the basic block.
167 // Note: The GEPs and/or loads are not necessarily in the same block.
168 for (const Instruction &Inst : *BB) {
169 if (const auto *const GEP = dyn_cast<GetElementPtrInst>(&Inst)) {
Clement Courbet98eaa882017-10-04 15:13:52 +0000170 if (!(Lhs_.GEP == GEP || Rhs_.GEP == GEP)) return true;
Clement Courbet65130e22017-09-01 10:56:34 +0000171 } else if (const auto *const L = dyn_cast<LoadInst>(&Inst)) {
Clement Courbet98eaa882017-10-04 15:13:52 +0000172 if (!(Lhs_.LoadI == L || Rhs_.LoadI == L)) return true;
Clement Courbet65130e22017-09-01 10:56:34 +0000173 } else if (const auto *const C = dyn_cast<ICmpInst>(&Inst)) {
Clement Courbet98eaa882017-10-04 15:13:52 +0000174 if (C != CmpI) return true;
Clement Courbet65130e22017-09-01 10:56:34 +0000175 } else if (const auto *const Br = dyn_cast<BranchInst>(&Inst)) {
Clement Courbet98eaa882017-10-04 15:13:52 +0000176 if (Br != BranchI) return true;
Clement Courbet65130e22017-09-01 10:56:34 +0000177 } else {
178 return true;
179 }
180 }
181 return false;
182}
183
184// Visit the given comparison. If this is a comparison between two valid
185// BCE atoms, returns the comparison.
186BCECmpBlock visitICmp(const ICmpInst *const CmpI,
187 const ICmpInst::Predicate ExpectedPredicate) {
188 if (CmpI->getPredicate() == ExpectedPredicate) {
189 DEBUG(dbgs() << "cmp "
190 << (ExpectedPredicate == ICmpInst::ICMP_EQ ? "eq" : "ne")
191 << "\n");
192 auto Lhs = visitICmpLoadOperand(CmpI->getOperand(0));
Clement Courbet98eaa882017-10-04 15:13:52 +0000193 if (!Lhs.Base()) return {};
Clement Courbet65130e22017-09-01 10:56:34 +0000194 auto Rhs = visitICmpLoadOperand(CmpI->getOperand(1));
Clement Courbet98eaa882017-10-04 15:13:52 +0000195 if (!Rhs.Base()) return {};
Clement Courbet65130e22017-09-01 10:56:34 +0000196 return BCECmpBlock(std::move(Lhs), std::move(Rhs),
197 CmpI->getOperand(0)->getType()->getScalarSizeInBits());
198 }
199 return {};
200}
201
202// Visit the given comparison block. If this is a comparison between two valid
203// BCE atoms, returns the comparison.
204BCECmpBlock visitCmpBlock(Value *const Val, BasicBlock *const Block,
205 const BasicBlock *const PhiBlock) {
Clement Courbet98eaa882017-10-04 15:13:52 +0000206 if (Block->empty()) return {};
Clement Courbet65130e22017-09-01 10:56:34 +0000207 auto *const BranchI = dyn_cast<BranchInst>(Block->getTerminator());
Clement Courbet98eaa882017-10-04 15:13:52 +0000208 if (!BranchI) return {};
Clement Courbet65130e22017-09-01 10:56:34 +0000209 DEBUG(dbgs() << "branch\n");
210 if (BranchI->isUnconditional()) {
211 // In this case, we expect an incoming value which is the result of the
212 // comparison. This is the last link in the chain of comparisons (note
213 // that this does not mean that this is the last incoming value, blocks
214 // can be reordered).
215 auto *const CmpI = dyn_cast<ICmpInst>(Val);
Clement Courbet98eaa882017-10-04 15:13:52 +0000216 if (!CmpI) return {};
Clement Courbet65130e22017-09-01 10:56:34 +0000217 DEBUG(dbgs() << "icmp\n");
218 auto Result = visitICmp(CmpI, ICmpInst::ICMP_EQ);
219 Result.CmpI = CmpI;
220 Result.BranchI = BranchI;
221 return Result;
222 } else {
223 // In this case, we expect a constant incoming value (the comparison is
224 // chained).
225 const auto *const Const = dyn_cast<ConstantInt>(Val);
226 DEBUG(dbgs() << "const\n");
Clement Courbet98eaa882017-10-04 15:13:52 +0000227 if (!Const->isZero()) return {};
Clement Courbet65130e22017-09-01 10:56:34 +0000228 DEBUG(dbgs() << "false\n");
229 auto *const CmpI = dyn_cast<ICmpInst>(BranchI->getCondition());
Clement Courbet98eaa882017-10-04 15:13:52 +0000230 if (!CmpI) return {};
Clement Courbet65130e22017-09-01 10:56:34 +0000231 DEBUG(dbgs() << "icmp\n");
232 assert(BranchI->getNumSuccessors() == 2 && "expecting a cond branch");
233 BasicBlock *const FalseBlock = BranchI->getSuccessor(1);
234 auto Result = visitICmp(
235 CmpI, FalseBlock == PhiBlock ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE);
236 Result.CmpI = CmpI;
237 Result.BranchI = BranchI;
238 return Result;
239 }
240 return {};
241}
242
243// A chain of comparisons.
244class BCECmpChain {
245 public:
246 BCECmpChain(const std::vector<BasicBlock *> &Blocks, PHINode &Phi);
247
248 int size() const { return Comparisons_.size(); }
249
250#ifdef MERGEICMPS_DOT_ON
251 void dump() const;
252#endif // MERGEICMPS_DOT_ON
253
254 bool simplify(const TargetLibraryInfo *const TLI);
255
256 private:
257 static bool IsContiguous(const BCECmpBlock &First,
258 const BCECmpBlock &Second) {
259 return First.Lhs().Base() == Second.Lhs().Base() &&
260 First.Rhs().Base() == Second.Rhs().Base() &&
261 First.Lhs().Offset + First.SizeBits() / 8 == Second.Lhs().Offset &&
262 First.Rhs().Offset + First.SizeBits() / 8 == Second.Rhs().Offset;
263 }
264
265 // Merges the given comparison blocks into one memcmp block and update
266 // branches. Comparisons are assumed to be continguous. If NextBBInChain is
267 // null, the merged block will link to the phi block.
268 static void mergeComparisons(ArrayRef<BCECmpBlock> Comparisons,
269 BasicBlock *const NextBBInChain, PHINode &Phi,
270 const TargetLibraryInfo *const TLI);
271
272 PHINode &Phi_;
273 std::vector<BCECmpBlock> Comparisons_;
274 // The original entry block (before sorting);
275 BasicBlock *EntryBlock_;
276};
277
278BCECmpChain::BCECmpChain(const std::vector<BasicBlock *> &Blocks, PHINode &Phi)
279 : Phi_(Phi) {
280 // Now look inside blocks to check for BCE comparisons.
281 std::vector<BCECmpBlock> Comparisons;
282 for (BasicBlock *Block : Blocks) {
283 BCECmpBlock Comparison = visitCmpBlock(Phi.getIncomingValueForBlock(Block),
284 Block, Phi.getParent());
285 Comparison.BB = Block;
286 if (!Comparison.IsValid()) {
287 DEBUG(dbgs() << "skip: not a valid BCECmpBlock\n");
288 return;
289 }
290 if (Comparison.doesOtherWork()) {
291 DEBUG(dbgs() << "block does extra work besides compare\n");
292 if (Comparisons.empty()) { // First block.
293 // TODO(courbet): The first block can do other things, and we should
294 // split them apart in a separate block before the comparison chain.
295 // Right now we just discard it and make the chain shorter.
296 DEBUG(dbgs()
297 << "ignoring first block that does extra work besides compare\n");
298 continue;
299 }
300 // TODO(courbet): Right now we abort the whole chain. We could be
301 // merging only the blocks that don't do other work and resume the
302 // chain from there. For example:
303 // if (a[0] == b[0]) { // bb1
304 // if (a[1] == b[1]) { // bb2
305 // some_value = 3; //bb3
306 // if (a[2] == b[2]) { //bb3
307 // do a ton of stuff //bb4
308 // }
309 // }
310 // }
311 //
312 // This is:
313 //
314 // bb1 --eq--> bb2 --eq--> bb3* -eq--> bb4 --+
315 // \ \ \ \
316 // ne ne ne \
317 // \ \ \ v
318 // +------------+-----------+----------> bb_phi
319 //
320 // We can only merge the first two comparisons, because bb3* does
321 // "other work" (setting some_value to 3).
322 // We could still merge bb1 and bb2 though.
323 return;
324 }
325 DEBUG(dbgs() << "*Found cmp of " << Comparison.SizeBits()
326 << " bits between " << Comparison.Lhs().Base() << " + "
327 << Comparison.Lhs().Offset << " and "
328 << Comparison.Rhs().Base() << " + " << Comparison.Rhs().Offset
329 << "\n");
330 DEBUG(dbgs() << "\n");
331 Comparisons.push_back(Comparison);
332 }
333 EntryBlock_ = Comparisons[0].BB;
334 Comparisons_ = std::move(Comparisons);
335#ifdef MERGEICMPS_DOT_ON
336 errs() << "BEFORE REORDERING:\n\n";
337 dump();
338#endif // MERGEICMPS_DOT_ON
339 // Reorder blocks by LHS. We can do that without changing the
340 // semantics because we are only accessing dereferencable memory.
341 std::sort(Comparisons_.begin(), Comparisons_.end(),
342 [](const BCECmpBlock &a, const BCECmpBlock &b) {
343 return a.Lhs() < b.Lhs();
344 });
345#ifdef MERGEICMPS_DOT_ON
346 errs() << "AFTER REORDERING:\n\n";
347 dump();
348#endif // MERGEICMPS_DOT_ON
349}
350
351#ifdef MERGEICMPS_DOT_ON
352void BCECmpChain::dump() const {
353 errs() << "digraph dag {\n";
354 errs() << " graph [bgcolor=transparent];\n";
355 errs() << " node [color=black,style=filled,fillcolor=lightyellow];\n";
356 errs() << " edge [color=black];\n";
357 for (size_t I = 0; I < Comparisons_.size(); ++I) {
358 const auto &Comparison = Comparisons_[I];
359 errs() << " \"" << I << "\" [label=\"%"
360 << Comparison.Lhs().Base()->getName() << " + "
361 << Comparison.Lhs().Offset << " == %"
362 << Comparison.Rhs().Base()->getName() << " + "
363 << Comparison.Rhs().Offset << " (" << (Comparison.SizeBits() / 8)
364 << " bytes)\"];\n";
365 const Value *const Val = Phi_.getIncomingValueForBlock(Comparison.BB);
Clement Courbet98eaa882017-10-04 15:13:52 +0000366 if (I > 0) errs() << " \"" << (I - 1) << "\" -> \"" << I << "\";\n";
Clement Courbet65130e22017-09-01 10:56:34 +0000367 errs() << " \"" << I << "\" -> \"Phi\" [label=\"" << *Val << "\"];\n";
368 }
369 errs() << " \"Phi\" [label=\"Phi\"];\n";
370 errs() << "}\n\n";
371}
372#endif // MERGEICMPS_DOT_ON
373
374bool BCECmpChain::simplify(const TargetLibraryInfo *const TLI) {
375 // First pass to check if there is at least one merge. If not, we don't do
376 // anything and we keep analysis passes intact.
377 {
378 bool AtLeastOneMerged = false;
379 for (size_t I = 1; I < Comparisons_.size(); ++I) {
380 if (IsContiguous(Comparisons_[I - 1], Comparisons_[I])) {
381 AtLeastOneMerged = true;
382 break;
383 }
384 }
Clement Courbet98eaa882017-10-04 15:13:52 +0000385 if (!AtLeastOneMerged) return false;
Clement Courbet65130e22017-09-01 10:56:34 +0000386 }
387
388 // Remove phi references to comparison blocks, they will be rebuilt as we
389 // merge the blocks.
390 for (const auto &Comparison : Comparisons_) {
391 Phi_.removeIncomingValue(Comparison.BB, false);
392 }
393
394 // Point the predecessors of the chain to the first comparison block (which is
395 // the new entry point).
396 if (EntryBlock_ != Comparisons_[0].BB)
397 EntryBlock_->replaceAllUsesWith(Comparisons_[0].BB);
398
399 // Effectively merge blocks.
400 int NumMerged = 1;
401 for (size_t I = 1; I < Comparisons_.size(); ++I) {
402 if (IsContiguous(Comparisons_[I - 1], Comparisons_[I])) {
403 ++NumMerged;
404 } else {
405 // Merge all previous comparisons and start a new merge block.
406 mergeComparisons(
407 makeArrayRef(Comparisons_).slice(I - NumMerged, NumMerged),
408 Comparisons_[I].BB, Phi_, TLI);
409 NumMerged = 1;
410 }
411 }
412 mergeComparisons(makeArrayRef(Comparisons_)
413 .slice(Comparisons_.size() - NumMerged, NumMerged),
414 nullptr, Phi_, TLI);
415
416 return true;
417}
418
419void BCECmpChain::mergeComparisons(ArrayRef<BCECmpBlock> Comparisons,
420 BasicBlock *const NextBBInChain,
421 PHINode &Phi,
422 const TargetLibraryInfo *const TLI) {
423 assert(!Comparisons.empty());
424 const auto &FirstComparison = *Comparisons.begin();
425 BasicBlock *const BB = FirstComparison.BB;
426 LLVMContext &Context = BB->getContext();
427
428 if (Comparisons.size() >= 2) {
429 DEBUG(dbgs() << "Merging " << Comparisons.size() << " comparisons\n");
430 const auto TotalSize =
431 std::accumulate(Comparisons.begin(), Comparisons.end(), 0,
432 [](int Size, const BCECmpBlock &C) {
433 return Size + C.SizeBits();
434 }) /
435 8;
436
437 // Incoming edges do not need to be updated, and both GEPs are already
438 // computing the right address, we just need to:
439 // - replace the two loads and the icmp with the memcmp
440 // - update the branch
441 // - update the incoming values in the phi.
442 FirstComparison.BranchI->eraseFromParent();
443 FirstComparison.CmpI->eraseFromParent();
444 FirstComparison.Lhs().LoadI->eraseFromParent();
445 FirstComparison.Rhs().LoadI->eraseFromParent();
446
447 IRBuilder<> Builder(BB);
448 const auto &DL = Phi.getModule()->getDataLayout();
Clement Courbet4e1bae82017-10-06 12:12:35 +0000449 Value *const MemCmpCall = emitMemCmp(
450 FirstComparison.Lhs().GEP, FirstComparison.Rhs().GEP, ConstantInt::get(DL.getIntPtrType(Context), TotalSize),
451 Builder, DL, TLI);
Clement Courbet65130e22017-09-01 10:56:34 +0000452 Value *const MemCmpIsZero = Builder.CreateICmpEQ(
453 MemCmpCall, ConstantInt::get(Type::getInt32Ty(Context), 0));
454
455 // Add a branch to the next basic block in the chain.
456 if (NextBBInChain) {
457 Builder.CreateCondBr(MemCmpIsZero, NextBBInChain, Phi.getParent());
458 Phi.addIncoming(ConstantInt::getFalse(Context), BB);
459 } else {
460 Builder.CreateBr(Phi.getParent());
461 Phi.addIncoming(MemCmpIsZero, BB);
462 }
463
464 // Delete merged blocks.
465 for (size_t I = 1; I < Comparisons.size(); ++I) {
466 BasicBlock *CBB = Comparisons[I].BB;
467 CBB->replaceAllUsesWith(BB);
468 CBB->eraseFromParent();
469 }
470 } else {
471 assert(Comparisons.size() == 1);
472 // There are no blocks to merge, but we still need to update the branches.
473 DEBUG(dbgs() << "Only one comparison, updating branches\n");
474 if (NextBBInChain) {
475 if (FirstComparison.BranchI->isConditional()) {
476 DEBUG(dbgs() << "conditional -> conditional\n");
477 // Just update the "true" target, the "false" target should already be
478 // the phi block.
479 assert(FirstComparison.BranchI->getSuccessor(1) == Phi.getParent());
480 FirstComparison.BranchI->setSuccessor(0, NextBBInChain);
481 Phi.addIncoming(ConstantInt::getFalse(Context), BB);
482 } else {
483 DEBUG(dbgs() << "unconditional -> conditional\n");
484 // Replace the unconditional branch by a conditional one.
485 FirstComparison.BranchI->eraseFromParent();
486 IRBuilder<> Builder(BB);
487 Builder.CreateCondBr(FirstComparison.CmpI, NextBBInChain,
488 Phi.getParent());
489 Phi.addIncoming(FirstComparison.CmpI, BB);
490 }
491 } else {
492 if (FirstComparison.BranchI->isConditional()) {
493 DEBUG(dbgs() << "conditional -> unconditional\n");
494 // Replace the conditional branch by an unconditional one.
495 FirstComparison.BranchI->eraseFromParent();
496 IRBuilder<> Builder(BB);
497 Builder.CreateBr(Phi.getParent());
498 Phi.addIncoming(FirstComparison.CmpI, BB);
499 } else {
500 DEBUG(dbgs() << "unconditional -> unconditional\n");
501 Phi.addIncoming(FirstComparison.CmpI, BB);
502 }
503 }
504 }
505}
506
507std::vector<BasicBlock *> getOrderedBlocks(PHINode &Phi,
508 BasicBlock *const LastBlock,
509 int NumBlocks) {
510 // Walk up from the last block to find other blocks.
511 std::vector<BasicBlock *> Blocks(NumBlocks);
512 BasicBlock *CurBlock = LastBlock;
513 for (int BlockIndex = NumBlocks - 1; BlockIndex > 0; --BlockIndex) {
514 if (CurBlock->hasAddressTaken()) {
515 // Somebody is jumping to the block through an address, all bets are
516 // off.
517 DEBUG(dbgs() << "skip: block " << BlockIndex
518 << " has its address taken\n");
519 return {};
520 }
521 Blocks[BlockIndex] = CurBlock;
522 auto *SinglePredecessor = CurBlock->getSinglePredecessor();
523 if (!SinglePredecessor) {
524 // The block has two or more predecessors.
525 DEBUG(dbgs() << "skip: block " << BlockIndex
526 << " has two or more predecessors\n");
527 return {};
528 }
529 if (Phi.getBasicBlockIndex(SinglePredecessor) < 0) {
530 // The block does not link back to the phi.
531 DEBUG(dbgs() << "skip: block " << BlockIndex
532 << " does not link back to the phi\n");
533 return {};
534 }
535 CurBlock = SinglePredecessor;
536 }
537 Blocks[0] = CurBlock;
538 return Blocks;
539}
540
541bool processPhi(PHINode &Phi, const TargetLibraryInfo *const TLI) {
542 DEBUG(dbgs() << "processPhi()\n");
543 if (Phi.getNumIncomingValues() <= 1) {
544 DEBUG(dbgs() << "skip: only one incoming value in phi\n");
545 return false;
546 }
547 // We are looking for something that has the following structure:
548 // bb1 --eq--> bb2 --eq--> bb3 --eq--> bb4 --+
549 // \ \ \ \
550 // ne ne ne \
551 // \ \ \ v
552 // +------------+-----------+----------> bb_phi
553 //
554 // - The last basic block (bb4 here) must branch unconditionally to bb_phi.
555 // It's the only block that contributes a non-constant value to the Phi.
556 // - All other blocks (b1, b2, b3) must have exactly two successors, one of
557 // them being the the phi block.
558 // - All intermediate blocks (bb2, bb3) must have only one predecessor.
559 // - Blocks cannot do other work besides the comparison, see doesOtherWork()
560
561 // The blocks are not necessarily ordered in the phi, so we start from the
562 // last block and reconstruct the order.
563 BasicBlock *LastBlock = nullptr;
564 for (unsigned I = 0; I < Phi.getNumIncomingValues(); ++I) {
Clement Courbet98eaa882017-10-04 15:13:52 +0000565 if (isa<ConstantInt>(Phi.getIncomingValue(I))) continue;
Clement Courbet65130e22017-09-01 10:56:34 +0000566 if (LastBlock) {
567 // There are several non-constant values.
568 DEBUG(dbgs() << "skip: several non-constant values\n");
569 return false;
570 }
571 LastBlock = Phi.getIncomingBlock(I);
572 }
573 if (!LastBlock) {
574 // There is no non-constant block.
575 DEBUG(dbgs() << "skip: no non-constant block\n");
576 return false;
577 }
578 if (LastBlock->getSingleSuccessor() != Phi.getParent()) {
579 DEBUG(dbgs() << "skip: last block non-phi successor\n");
580 return false;
581 }
582
583 const auto Blocks =
584 getOrderedBlocks(Phi, LastBlock, Phi.getNumIncomingValues());
Clement Courbet98eaa882017-10-04 15:13:52 +0000585 if (Blocks.empty()) return false;
Clement Courbet65130e22017-09-01 10:56:34 +0000586 BCECmpChain CmpChain(Blocks, Phi);
587
588 if (CmpChain.size() < 2) {
589 DEBUG(dbgs() << "skip: only one compare block\n");
590 return false;
591 }
592
593 return CmpChain.simplify(TLI);
594}
595
596class MergeICmps : public FunctionPass {
597 public:
598 static char ID;
599
600 MergeICmps() : FunctionPass(ID) {
601 initializeMergeICmpsPass(*PassRegistry::getPassRegistry());
602 }
603
604 bool runOnFunction(Function &F) override {
605 if (skipFunction(F)) return false;
606 const auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Clement Courbet4e1bae82017-10-06 12:12:35 +0000607 const auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
608 auto PA = runImpl(F, &TLI, &TTI);
Clement Courbet65130e22017-09-01 10:56:34 +0000609 return !PA.areAllPreserved();
610 }
611
612 private:
613 void getAnalysisUsage(AnalysisUsage &AU) const override {
614 AU.addRequired<TargetLibraryInfoWrapperPass>();
Clement Courbet4e1bae82017-10-06 12:12:35 +0000615 AU.addRequired<TargetTransformInfoWrapperPass>();
Clement Courbet65130e22017-09-01 10:56:34 +0000616 }
617
Clement Courbet4e1bae82017-10-06 12:12:35 +0000618 PreservedAnalyses runImpl(Function &F, const TargetLibraryInfo *TLI,
619 const TargetTransformInfo *TTI);
Clement Courbet65130e22017-09-01 10:56:34 +0000620};
621
Clement Courbet4e1bae82017-10-06 12:12:35 +0000622PreservedAnalyses MergeICmps::runImpl(Function &F, const TargetLibraryInfo *TLI,
623 const TargetTransformInfo *TTI) {
Clement Courbet65130e22017-09-01 10:56:34 +0000624 DEBUG(dbgs() << "MergeICmpsPass: " << F.getName() << "\n");
625
Clement Courbet4e1bae82017-10-06 12:12:35 +0000626 // We only try merging comparisons if the target wants to expand memcmp later.
627 // The rationale is to avoid turning small chains into memcmp calls.
628 unsigned MaxLoadSize;
629 if (!TTI->enableMemCmpExpansion(MaxLoadSize)) return PreservedAnalyses::all();
630
Clement Courbet65130e22017-09-01 10:56:34 +0000631 bool MadeChange = false;
632
633 for (auto BBIt = ++F.begin(); BBIt != F.end(); ++BBIt) {
634 // A Phi operation is always first in a basic block.
635 if (auto *const Phi = dyn_cast<PHINode>(&*BBIt->begin()))
636 MadeChange |= processPhi(*Phi, TLI);
637 }
638
Clement Courbet98eaa882017-10-04 15:13:52 +0000639 if (MadeChange) return PreservedAnalyses::none();
Clement Courbet65130e22017-09-01 10:56:34 +0000640 return PreservedAnalyses::all();
641}
642
643} // namespace
644
645char MergeICmps::ID = 0;
646INITIALIZE_PASS_BEGIN(MergeICmps, "mergeicmps",
647 "Merge contiguous icmps into a memcmp", false, false)
648INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Clement Courbet4e1bae82017-10-06 12:12:35 +0000649INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Clement Courbet65130e22017-09-01 10:56:34 +0000650INITIALIZE_PASS_END(MergeICmps, "mergeicmps",
651 "Merge contiguous icmps into a memcmp", false, false)
652
653Pass *llvm::createMergeICmpsPass() { return new MergeICmps(); }