blob: 7b3c3f99f514dd05a4b9cc9fda3820fab68acd05 [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)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +000079 LLVM_DEBUG(dbgs() << "load\n");
Clement Courbet65130e22017-09-01 10:56:34 +000080 if (LoadI->isUsedOutsideOfBlock(LoadI->getParent())) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +000081 LLVM_DEBUG(dbgs() << "used outside of block\n");
Clement Courbet65130e22017-09-01 10:56:34 +000082 return {};
83 }
Christy Leec85da8b2018-09-18 17:02:42 +000084 // Do not optimize atomic loads to non-atomic memcmp
85 if (!LoadI->isSimple()) {
86 LLVM_DEBUG(dbgs() << "volatile or atomic\n");
Clement Courbet65130e22017-09-01 10:56:34 +000087 return {};
88 }
89 Value *const Addr = LoadI->getOperand(0);
90 if (auto *const GEP = dyn_cast<GetElementPtrInst>(Addr)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +000091 LLVM_DEBUG(dbgs() << "GEP\n");
Clement Courbet65130e22017-09-01 10:56:34 +000092 if (LoadI->isUsedOutsideOfBlock(LoadI->getParent())) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +000093 LLVM_DEBUG(dbgs() << "used outside of block\n");
Clement Courbet65130e22017-09-01 10:56:34 +000094 return {};
95 }
96 const auto &DL = GEP->getModule()->getDataLayout();
97 if (!isDereferenceablePointer(GEP, DL)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +000098 LLVM_DEBUG(dbgs() << "not dereferenceable\n");
Clement Courbet65130e22017-09-01 10:56:34 +000099 // We need to make sure that we can do comparison in any order, so we
100 // require memory to be unconditionnally dereferencable.
101 return {};
102 }
103 Result.Offset = APInt(DL.getPointerTypeSizeInBits(GEP->getType()), 0);
104 if (GEP->accumulateConstantOffset(DL, Result.Offset)) {
105 Result.GEP = GEP;
106 Result.LoadI = LoadI;
107 }
108 }
109 }
110 return Result;
111}
112
113// A basic block with a comparison between two BCE atoms.
Xin Tong0efadbb2018-04-09 13:14:06 +0000114// The block might do extra work besides the atom comparison, in which case
115// doesOtherWork() returns true. Under some conditions, the block can be
116// split into the atom comparison part and the "other work" part
117// (see canSplit()).
Clement Courbet65130e22017-09-01 10:56:34 +0000118// Note: the terminology is misleading: the comparison is symmetric, so there
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000119// is no real {l/r}hs. What we want though is to have the same base on the
120// left (resp. right), so that we can detect consecutive loads. To ensure this
121// we put the smallest atom on the left.
Clement Courbet65130e22017-09-01 10:56:34 +0000122class BCECmpBlock {
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000123 public:
124 BCECmpBlock() {}
Clement Courbet65130e22017-09-01 10:56:34 +0000125
126 BCECmpBlock(BCEAtom L, BCEAtom R, int SizeBits)
127 : Lhs_(L), Rhs_(R), SizeBits_(SizeBits) {
Clement Courbet98eaa882017-10-04 15:13:52 +0000128 if (Rhs_ < Lhs_) std::swap(Rhs_, Lhs_);
Clement Courbet65130e22017-09-01 10:56:34 +0000129 }
130
131 bool IsValid() const {
132 return Lhs_.Base() != nullptr && Rhs_.Base() != nullptr;
133 }
134
Hiroshi Inoued24ddcd2018-01-19 10:55:29 +0000135 // Assert the block is consistent: If valid, it should also have
Clement Courbet65130e22017-09-01 10:56:34 +0000136 // non-null members besides Lhs_ and Rhs_.
137 void AssertConsistent() const {
138 if (IsValid()) {
139 assert(BB);
140 assert(CmpI);
141 assert(BranchI);
142 }
143 }
144
145 const BCEAtom &Lhs() const { return Lhs_; }
146 const BCEAtom &Rhs() const { return Rhs_; }
147 int SizeBits() const { return SizeBits_; }
148
149 // Returns true if the block does other works besides comparison.
150 bool doesOtherWork() const;
151
Xin Tong0efadbb2018-04-09 13:14:06 +0000152 // Returns true if the non-BCE-cmp instructions can be separated from BCE-cmp
153 // instructions in the block.
154 bool canSplit() const;
155
156 // Return true if this all the relevant instructions in the BCE-cmp-block can
157 // be sunk below this instruction. By doing this, we know we can separate the
158 // BCE-cmp-block instructions from the non-BCE-cmp-block instructions in the
159 // block.
160 bool canSinkBCECmpInst(const Instruction *, DenseSet<Instruction *> &) const;
161
162 // We can separate the BCE-cmp-block instructions and the non-BCE-cmp-block
163 // instructions. Split the old block and move all non-BCE-cmp-insts into the
164 // new parent block.
165 void split(BasicBlock *NewParent) const;
166
Clement Courbet65130e22017-09-01 10:56:34 +0000167 // The basic block where this comparison happens.
168 BasicBlock *BB = nullptr;
169 // The ICMP for this comparison.
170 ICmpInst *CmpI = nullptr;
171 // The terminating branch.
172 BranchInst *BranchI = nullptr;
Xin Tong0efadbb2018-04-09 13:14:06 +0000173 // The block requires splitting.
174 bool RequireSplit = false;
Clement Courbet65130e22017-09-01 10:56:34 +0000175
Xin Tong0efadbb2018-04-09 13:14:06 +0000176private:
Clement Courbet65130e22017-09-01 10:56:34 +0000177 BCEAtom Lhs_;
178 BCEAtom Rhs_;
179 int SizeBits_ = 0;
180};
181
Xin Tong0efadbb2018-04-09 13:14:06 +0000182bool BCECmpBlock::canSinkBCECmpInst(const Instruction *Inst,
183 DenseSet<Instruction *> &BlockInsts) const {
184 // If this instruction has side effects and its in middle of the BCE cmp block
185 // instructions, then bail for now.
186 // TODO: use alias analysis to tell whether there is real interference.
187 if (Inst->mayHaveSideEffects())
188 return false;
189 // Make sure this instruction does not use any of the BCE cmp block
190 // instructions as operand.
191 for (auto BI : BlockInsts) {
192 if (is_contained(Inst->operands(), BI))
193 return false;
194 }
195 return true;
196}
197
198void BCECmpBlock::split(BasicBlock *NewParent) const {
199 DenseSet<Instruction *> BlockInsts(
200 {Lhs_.GEP, Rhs_.GEP, Lhs_.LoadI, Rhs_.LoadI, CmpI, BranchI});
201 llvm::SmallVector<Instruction *, 4> OtherInsts;
202 for (Instruction &Inst : *BB) {
203 if (BlockInsts.count(&Inst))
204 continue;
205 assert(canSinkBCECmpInst(&Inst, BlockInsts) && "Split unsplittable block");
206 // This is a non-BCE-cmp-block instruction. And it can be separated
207 // from the BCE-cmp-block instruction.
208 OtherInsts.push_back(&Inst);
209 }
210
211 // Do the actual spliting.
212 for (Instruction *Inst : reverse(OtherInsts)) {
213 Inst->moveBefore(&*NewParent->begin());
214 }
215}
216
217bool BCECmpBlock::canSplit() const {
218 DenseSet<Instruction *> BlockInsts(
219 {Lhs_.GEP, Rhs_.GEP, Lhs_.LoadI, Rhs_.LoadI, CmpI, BranchI});
220 for (Instruction &Inst : *BB) {
221 if (!BlockInsts.count(&Inst)) {
222 if (!canSinkBCECmpInst(&Inst, BlockInsts))
223 return false;
224 }
225 }
226 return true;
227}
228
Clement Courbet65130e22017-09-01 10:56:34 +0000229bool BCECmpBlock::doesOtherWork() const {
230 AssertConsistent();
Xin Tong8fd561f2018-03-06 02:24:02 +0000231 // All the instructions we care about in the BCE cmp block.
232 DenseSet<Instruction *> BlockInsts(
233 {Lhs_.GEP, Rhs_.GEP, Lhs_.LoadI, Rhs_.LoadI, CmpI, BranchI});
Clement Courbet65130e22017-09-01 10:56:34 +0000234 // TODO(courbet): Can we allow some other things ? This is very conservative.
Hiroshi Inoueae179002018-04-14 08:59:00 +0000235 // We might be able to get away with anything does not have any side
Clement Courbet65130e22017-09-01 10:56:34 +0000236 // effects outside of the basic block.
237 // Note: The GEPs and/or loads are not necessarily in the same block.
238 for (const Instruction &Inst : *BB) {
Xin Tong8fd561f2018-03-06 02:24:02 +0000239 if (!BlockInsts.count(&Inst))
Clement Courbet65130e22017-09-01 10:56:34 +0000240 return true;
Clement Courbet65130e22017-09-01 10:56:34 +0000241 }
242 return false;
243}
244
245// Visit the given comparison. If this is a comparison between two valid
246// BCE atoms, returns the comparison.
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000247BCECmpBlock visitICmp(const ICmpInst *const CmpI,
248 const ICmpInst::Predicate ExpectedPredicate) {
Clement Courbet9f0b3172018-03-13 07:05:55 +0000249 // The comparison can only be used once:
250 // - For intermediate blocks, as a branch condition.
251 // - For the final block, as an incoming value for the Phi.
252 // If there are any other uses of the comparison, we cannot merge it with
253 // other comparisons as we would create an orphan use of the value.
254 if (!CmpI->hasOneUse()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000255 LLVM_DEBUG(dbgs() << "cmp has several uses\n");
Clement Courbet9f0b3172018-03-13 07:05:55 +0000256 return {};
257 }
Clement Courbet65130e22017-09-01 10:56:34 +0000258 if (CmpI->getPredicate() == ExpectedPredicate) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000259 LLVM_DEBUG(dbgs() << "cmp "
260 << (ExpectedPredicate == ICmpInst::ICMP_EQ ? "eq" : "ne")
261 << "\n");
Clement Courbet65130e22017-09-01 10:56:34 +0000262 auto Lhs = visitICmpLoadOperand(CmpI->getOperand(0));
Clement Courbet98eaa882017-10-04 15:13:52 +0000263 if (!Lhs.Base()) return {};
Clement Courbet65130e22017-09-01 10:56:34 +0000264 auto Rhs = visitICmpLoadOperand(CmpI->getOperand(1));
Clement Courbet98eaa882017-10-04 15:13:52 +0000265 if (!Rhs.Base()) return {};
Clement Courbet65130e22017-09-01 10:56:34 +0000266 return BCECmpBlock(std::move(Lhs), std::move(Rhs),
267 CmpI->getOperand(0)->getType()->getScalarSizeInBits());
268 }
269 return {};
270}
271
272// Visit the given comparison block. If this is a comparison between two valid
273// BCE atoms, returns the comparison.
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000274BCECmpBlock visitCmpBlock(Value *const Val, BasicBlock *const Block,
275 const BasicBlock *const PhiBlock) {
Clement Courbet98eaa882017-10-04 15:13:52 +0000276 if (Block->empty()) return {};
Clement Courbet65130e22017-09-01 10:56:34 +0000277 auto *const BranchI = dyn_cast<BranchInst>(Block->getTerminator());
Clement Courbet98eaa882017-10-04 15:13:52 +0000278 if (!BranchI) return {};
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000279 LLVM_DEBUG(dbgs() << "branch\n");
Clement Courbet65130e22017-09-01 10:56:34 +0000280 if (BranchI->isUnconditional()) {
281 // In this case, we expect an incoming value which is the result of the
282 // comparison. This is the last link in the chain of comparisons (note
283 // that this does not mean that this is the last incoming value, blocks
284 // can be reordered).
285 auto *const CmpI = dyn_cast<ICmpInst>(Val);
Clement Courbet98eaa882017-10-04 15:13:52 +0000286 if (!CmpI) return {};
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000287 LLVM_DEBUG(dbgs() << "icmp\n");
Clement Courbet65130e22017-09-01 10:56:34 +0000288 auto Result = visitICmp(CmpI, ICmpInst::ICMP_EQ);
289 Result.CmpI = CmpI;
290 Result.BranchI = BranchI;
291 return Result;
292 } else {
293 // In this case, we expect a constant incoming value (the comparison is
294 // chained).
295 const auto *const Const = dyn_cast<ConstantInt>(Val);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000296 LLVM_DEBUG(dbgs() << "const\n");
Clement Courbet98eaa882017-10-04 15:13:52 +0000297 if (!Const->isZero()) return {};
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000298 LLVM_DEBUG(dbgs() << "false\n");
Clement Courbet65130e22017-09-01 10:56:34 +0000299 auto *const CmpI = dyn_cast<ICmpInst>(BranchI->getCondition());
Clement Courbet98eaa882017-10-04 15:13:52 +0000300 if (!CmpI) return {};
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000301 LLVM_DEBUG(dbgs() << "icmp\n");
Clement Courbet65130e22017-09-01 10:56:34 +0000302 assert(BranchI->getNumSuccessors() == 2 && "expecting a cond branch");
303 BasicBlock *const FalseBlock = BranchI->getSuccessor(1);
304 auto Result = visitICmp(
305 CmpI, FalseBlock == PhiBlock ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE);
306 Result.CmpI = CmpI;
307 Result.BranchI = BranchI;
308 return Result;
309 }
310 return {};
311}
312
Xin Tong0efadbb2018-04-09 13:14:06 +0000313static inline void enqueueBlock(std::vector<BCECmpBlock> &Comparisons,
314 BCECmpBlock &Comparison) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000315 LLVM_DEBUG(dbgs() << "Block '" << Comparison.BB->getName()
316 << "': Found cmp of " << Comparison.SizeBits()
317 << " bits between " << Comparison.Lhs().Base() << " + "
318 << Comparison.Lhs().Offset << " and "
319 << Comparison.Rhs().Base() << " + "
320 << Comparison.Rhs().Offset << "\n");
321 LLVM_DEBUG(dbgs() << "\n");
Xin Tong0efadbb2018-04-09 13:14:06 +0000322 Comparisons.push_back(Comparison);
323}
324
Clement Courbet65130e22017-09-01 10:56:34 +0000325// A chain of comparisons.
326class BCECmpChain {
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000327 public:
Clement Courbet65130e22017-09-01 10:56:34 +0000328 BCECmpChain(const std::vector<BasicBlock *> &Blocks, PHINode &Phi);
329
330 int size() const { return Comparisons_.size(); }
331
332#ifdef MERGEICMPS_DOT_ON
333 void dump() const;
334#endif // MERGEICMPS_DOT_ON
335
336 bool simplify(const TargetLibraryInfo *const TLI);
337
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000338 private:
Clement Courbet65130e22017-09-01 10:56:34 +0000339 static bool IsContiguous(const BCECmpBlock &First,
340 const BCECmpBlock &Second) {
341 return First.Lhs().Base() == Second.Lhs().Base() &&
342 First.Rhs().Base() == Second.Rhs().Base() &&
343 First.Lhs().Offset + First.SizeBits() / 8 == Second.Lhs().Offset &&
344 First.Rhs().Offset + First.SizeBits() / 8 == Second.Rhs().Offset;
345 }
346
347 // Merges the given comparison blocks into one memcmp block and update
348 // branches. Comparisons are assumed to be continguous. If NextBBInChain is
349 // null, the merged block will link to the phi block.
Xin Tong0efadbb2018-04-09 13:14:06 +0000350 void mergeComparisons(ArrayRef<BCECmpBlock> Comparisons,
351 BasicBlock *const NextBBInChain, PHINode &Phi,
352 const TargetLibraryInfo *const TLI);
Clement Courbet65130e22017-09-01 10:56:34 +0000353
354 PHINode &Phi_;
355 std::vector<BCECmpBlock> Comparisons_;
356 // The original entry block (before sorting);
357 BasicBlock *EntryBlock_;
358};
359
360BCECmpChain::BCECmpChain(const std::vector<BasicBlock *> &Blocks, PHINode &Phi)
361 : Phi_(Phi) {
Clement Courbetc2109c82018-02-06 09:14:00 +0000362 assert(!Blocks.empty() && "a chain should have at least one block");
Clement Courbet65130e22017-09-01 10:56:34 +0000363 // Now look inside blocks to check for BCE comparisons.
364 std::vector<BCECmpBlock> Comparisons;
Clement Courbeta7a17462018-02-06 12:25:33 +0000365 for (size_t BlockIdx = 0; BlockIdx < Blocks.size(); ++BlockIdx) {
366 BasicBlock *const Block = Blocks[BlockIdx];
Clement Courbetc2109c82018-02-06 09:14:00 +0000367 assert(Block && "invalid block");
Clement Courbet65130e22017-09-01 10:56:34 +0000368 BCECmpBlock Comparison = visitCmpBlock(Phi.getIncomingValueForBlock(Block),
369 Block, Phi.getParent());
370 Comparison.BB = Block;
371 if (!Comparison.IsValid()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000372 LLVM_DEBUG(dbgs() << "chain with invalid BCECmpBlock, no merge.\n");
Clement Courbet65130e22017-09-01 10:56:34 +0000373 return;
374 }
375 if (Comparison.doesOtherWork()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000376 LLVM_DEBUG(dbgs() << "block '" << Comparison.BB->getName()
377 << "' does extra work besides compare\n");
Xin Tong8345c0e2018-03-05 13:54:47 +0000378 if (Comparisons.empty()) {
Xin Tong0efadbb2018-04-09 13:14:06 +0000379 // This is the initial block in the chain, in case this block does other
380 // work, we can try to split the block and move the irrelevant
381 // instructions to the predecessor.
382 //
383 // If this is not the initial block in the chain, splitting it wont
384 // work.
385 //
386 // As once split, there will still be instructions before the BCE cmp
387 // instructions that do other work in program order, i.e. within the
388 // chain before sorting. Unless we can abort the chain at this point
389 // and start anew.
390 //
391 // NOTE: we only handle block with single predecessor for now.
392 if (Comparison.canSplit()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000393 LLVM_DEBUG(dbgs()
394 << "Split initial block '" << Comparison.BB->getName()
395 << "' that does extra work besides compare\n");
Xin Tong0efadbb2018-04-09 13:14:06 +0000396 Comparison.RequireSplit = true;
397 enqueueBlock(Comparisons, Comparison);
398 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000399 LLVM_DEBUG(dbgs()
400 << "ignoring initial block '" << Comparison.BB->getName()
401 << "' that does extra work besides compare\n");
Xin Tong0efadbb2018-04-09 13:14:06 +0000402 }
Clement Courbet65130e22017-09-01 10:56:34 +0000403 continue;
404 }
405 // TODO(courbet): Right now we abort the whole chain. We could be
406 // merging only the blocks that don't do other work and resume the
407 // chain from there. For example:
408 // if (a[0] == b[0]) { // bb1
409 // if (a[1] == b[1]) { // bb2
410 // some_value = 3; //bb3
411 // if (a[2] == b[2]) { //bb3
412 // do a ton of stuff //bb4
413 // }
414 // }
415 // }
416 //
417 // This is:
418 //
419 // bb1 --eq--> bb2 --eq--> bb3* -eq--> bb4 --+
420 // \ \ \ \
421 // ne ne ne \
422 // \ \ \ v
423 // +------------+-----------+----------> bb_phi
424 //
425 // We can only merge the first two comparisons, because bb3* does
426 // "other work" (setting some_value to 3).
427 // We could still merge bb1 and bb2 though.
428 return;
429 }
Xin Tong0efadbb2018-04-09 13:14:06 +0000430 enqueueBlock(Comparisons, Comparison);
Clement Courbet65130e22017-09-01 10:56:34 +0000431 }
Xin Tong8345c0e2018-03-05 13:54:47 +0000432
433 // It is possible we have no suitable comparison to merge.
434 if (Comparisons.empty()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000435 LLVM_DEBUG(dbgs() << "chain with no BCE basic blocks, no merge\n");
Xin Tong8345c0e2018-03-05 13:54:47 +0000436 return;
437 }
Clement Courbet65130e22017-09-01 10:56:34 +0000438 EntryBlock_ = Comparisons[0].BB;
439 Comparisons_ = std::move(Comparisons);
440#ifdef MERGEICMPS_DOT_ON
441 errs() << "BEFORE REORDERING:\n\n";
442 dump();
443#endif // MERGEICMPS_DOT_ON
444 // Reorder blocks by LHS. We can do that without changing the
445 // semantics because we are only accessing dereferencable memory.
Mandeep Singh Grang636d94d2018-04-13 19:47:57 +0000446 llvm::sort(Comparisons_.begin(), Comparisons_.end(),
447 [](const BCECmpBlock &a, const BCECmpBlock &b) {
448 return a.Lhs() < b.Lhs();
449 });
Clement Courbet65130e22017-09-01 10:56:34 +0000450#ifdef MERGEICMPS_DOT_ON
451 errs() << "AFTER REORDERING:\n\n";
452 dump();
453#endif // MERGEICMPS_DOT_ON
454}
455
456#ifdef MERGEICMPS_DOT_ON
457void BCECmpChain::dump() const {
458 errs() << "digraph dag {\n";
459 errs() << " graph [bgcolor=transparent];\n";
460 errs() << " node [color=black,style=filled,fillcolor=lightyellow];\n";
461 errs() << " edge [color=black];\n";
462 for (size_t I = 0; I < Comparisons_.size(); ++I) {
463 const auto &Comparison = Comparisons_[I];
464 errs() << " \"" << I << "\" [label=\"%"
465 << Comparison.Lhs().Base()->getName() << " + "
466 << Comparison.Lhs().Offset << " == %"
467 << Comparison.Rhs().Base()->getName() << " + "
468 << Comparison.Rhs().Offset << " (" << (Comparison.SizeBits() / 8)
469 << " bytes)\"];\n";
470 const Value *const Val = Phi_.getIncomingValueForBlock(Comparison.BB);
Clement Courbet98eaa882017-10-04 15:13:52 +0000471 if (I > 0) errs() << " \"" << (I - 1) << "\" -> \"" << I << "\";\n";
Clement Courbet65130e22017-09-01 10:56:34 +0000472 errs() << " \"" << I << "\" -> \"Phi\" [label=\"" << *Val << "\"];\n";
473 }
474 errs() << " \"Phi\" [label=\"Phi\"];\n";
475 errs() << "}\n\n";
476}
477#endif // MERGEICMPS_DOT_ON
478
479bool BCECmpChain::simplify(const TargetLibraryInfo *const TLI) {
480 // First pass to check if there is at least one merge. If not, we don't do
481 // anything and we keep analysis passes intact.
482 {
483 bool AtLeastOneMerged = false;
484 for (size_t I = 1; I < Comparisons_.size(); ++I) {
485 if (IsContiguous(Comparisons_[I - 1], Comparisons_[I])) {
486 AtLeastOneMerged = true;
487 break;
488 }
489 }
Clement Courbet98eaa882017-10-04 15:13:52 +0000490 if (!AtLeastOneMerged) return false;
Clement Courbet65130e22017-09-01 10:56:34 +0000491 }
492
493 // Remove phi references to comparison blocks, they will be rebuilt as we
494 // merge the blocks.
495 for (const auto &Comparison : Comparisons_) {
496 Phi_.removeIncomingValue(Comparison.BB, false);
497 }
498
Xin Tongbdbd97e2018-03-20 11:57:54 +0000499 // If entry block is part of the chain, we need to make the first block
500 // of the chain the new entry block of the function.
501 BasicBlock *Entry = &Comparisons_[0].BB->getParent()->getEntryBlock();
502 for (size_t I = 1; I < Comparisons_.size(); ++I) {
503 if (Entry == Comparisons_[I].BB) {
504 BasicBlock *NEntryBB = BasicBlock::Create(Entry->getContext(), "",
505 Entry->getParent(), Entry);
506 BranchInst::Create(Entry, NEntryBB);
Xin Tonga713ebe2018-03-20 12:03:25 +0000507 break;
Xin Tongbdbd97e2018-03-20 11:57:54 +0000508 }
509 }
510
Clement Courbet65130e22017-09-01 10:56:34 +0000511 // Point the predecessors of the chain to the first comparison block (which is
Xin Tong0efadbb2018-04-09 13:14:06 +0000512 // the new entry point) and update the entry block of the chain.
513 if (EntryBlock_ != Comparisons_[0].BB) {
Clement Courbet65130e22017-09-01 10:56:34 +0000514 EntryBlock_->replaceAllUsesWith(Comparisons_[0].BB);
Xin Tong0efadbb2018-04-09 13:14:06 +0000515 EntryBlock_ = Comparisons_[0].BB;
516 }
Clement Courbet65130e22017-09-01 10:56:34 +0000517
518 // Effectively merge blocks.
519 int NumMerged = 1;
520 for (size_t I = 1; I < Comparisons_.size(); ++I) {
521 if (IsContiguous(Comparisons_[I - 1], Comparisons_[I])) {
522 ++NumMerged;
523 } else {
524 // Merge all previous comparisons and start a new merge block.
525 mergeComparisons(
526 makeArrayRef(Comparisons_).slice(I - NumMerged, NumMerged),
527 Comparisons_[I].BB, Phi_, TLI);
528 NumMerged = 1;
529 }
530 }
531 mergeComparisons(makeArrayRef(Comparisons_)
532 .slice(Comparisons_.size() - NumMerged, NumMerged),
533 nullptr, Phi_, TLI);
534
535 return true;
536}
537
538void BCECmpChain::mergeComparisons(ArrayRef<BCECmpBlock> Comparisons,
539 BasicBlock *const NextBBInChain,
540 PHINode &Phi,
541 const TargetLibraryInfo *const TLI) {
542 assert(!Comparisons.empty());
543 const auto &FirstComparison = *Comparisons.begin();
544 BasicBlock *const BB = FirstComparison.BB;
545 LLVMContext &Context = BB->getContext();
546
547 if (Comparisons.size() >= 2) {
Xin Tong0efadbb2018-04-09 13:14:06 +0000548 // If there is one block that requires splitting, we do it now, i.e.
549 // just before we know we will collapse the chain. The instructions
550 // can be executed before any of the instructions in the chain.
551 auto C = std::find_if(Comparisons.begin(), Comparisons.end(),
552 [](const BCECmpBlock &B) { return B.RequireSplit; });
553 if (C != Comparisons.end())
554 C->split(EntryBlock_);
555
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000556 LLVM_DEBUG(dbgs() << "Merging " << Comparisons.size() << " comparisons\n");
Clement Courbet65130e22017-09-01 10:56:34 +0000557 const auto TotalSize =
558 std::accumulate(Comparisons.begin(), Comparisons.end(), 0,
559 [](int Size, const BCECmpBlock &C) {
560 return Size + C.SizeBits();
561 }) /
562 8;
563
564 // Incoming edges do not need to be updated, and both GEPs are already
565 // computing the right address, we just need to:
566 // - replace the two loads and the icmp with the memcmp
567 // - update the branch
568 // - update the incoming values in the phi.
569 FirstComparison.BranchI->eraseFromParent();
570 FirstComparison.CmpI->eraseFromParent();
571 FirstComparison.Lhs().LoadI->eraseFromParent();
572 FirstComparison.Rhs().LoadI->eraseFromParent();
573
574 IRBuilder<> Builder(BB);
575 const auto &DL = Phi.getModule()->getDataLayout();
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000576 Value *const MemCmpCall = emitMemCmp(
Xin Tong0272cb02018-03-27 19:43:02 +0000577 FirstComparison.Lhs().GEP, FirstComparison.Rhs().GEP,
578 ConstantInt::get(DL.getIntPtrType(Context), TotalSize),
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000579 Builder, DL, TLI);
Clement Courbet65130e22017-09-01 10:56:34 +0000580 Value *const MemCmpIsZero = Builder.CreateICmpEQ(
581 MemCmpCall, ConstantInt::get(Type::getInt32Ty(Context), 0));
582
583 // Add a branch to the next basic block in the chain.
584 if (NextBBInChain) {
585 Builder.CreateCondBr(MemCmpIsZero, NextBBInChain, Phi.getParent());
586 Phi.addIncoming(ConstantInt::getFalse(Context), BB);
587 } else {
588 Builder.CreateBr(Phi.getParent());
589 Phi.addIncoming(MemCmpIsZero, BB);
590 }
591
592 // Delete merged blocks.
593 for (size_t I = 1; I < Comparisons.size(); ++I) {
594 BasicBlock *CBB = Comparisons[I].BB;
595 CBB->replaceAllUsesWith(BB);
596 CBB->eraseFromParent();
597 }
598 } else {
599 assert(Comparisons.size() == 1);
600 // There are no blocks to merge, but we still need to update the branches.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000601 LLVM_DEBUG(dbgs() << "Only one comparison, updating branches\n");
Clement Courbet65130e22017-09-01 10:56:34 +0000602 if (NextBBInChain) {
603 if (FirstComparison.BranchI->isConditional()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000604 LLVM_DEBUG(dbgs() << "conditional -> conditional\n");
Clement Courbet65130e22017-09-01 10:56:34 +0000605 // Just update the "true" target, the "false" target should already be
606 // the phi block.
607 assert(FirstComparison.BranchI->getSuccessor(1) == Phi.getParent());
608 FirstComparison.BranchI->setSuccessor(0, NextBBInChain);
609 Phi.addIncoming(ConstantInt::getFalse(Context), BB);
610 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000611 LLVM_DEBUG(dbgs() << "unconditional -> conditional\n");
Clement Courbet65130e22017-09-01 10:56:34 +0000612 // Replace the unconditional branch by a conditional one.
613 FirstComparison.BranchI->eraseFromParent();
614 IRBuilder<> Builder(BB);
615 Builder.CreateCondBr(FirstComparison.CmpI, NextBBInChain,
616 Phi.getParent());
617 Phi.addIncoming(FirstComparison.CmpI, BB);
618 }
619 } else {
620 if (FirstComparison.BranchI->isConditional()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000621 LLVM_DEBUG(dbgs() << "conditional -> unconditional\n");
Clement Courbet65130e22017-09-01 10:56:34 +0000622 // Replace the conditional branch by an unconditional one.
623 FirstComparison.BranchI->eraseFromParent();
624 IRBuilder<> Builder(BB);
625 Builder.CreateBr(Phi.getParent());
626 Phi.addIncoming(FirstComparison.CmpI, BB);
627 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000628 LLVM_DEBUG(dbgs() << "unconditional -> unconditional\n");
Clement Courbet65130e22017-09-01 10:56:34 +0000629 Phi.addIncoming(FirstComparison.CmpI, BB);
630 }
631 }
632 }
633}
634
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000635std::vector<BasicBlock *> getOrderedBlocks(PHINode &Phi,
636 BasicBlock *const LastBlock,
637 int NumBlocks) {
Clement Courbet65130e22017-09-01 10:56:34 +0000638 // Walk up from the last block to find other blocks.
639 std::vector<BasicBlock *> Blocks(NumBlocks);
Clement Courbetc2109c82018-02-06 09:14:00 +0000640 assert(LastBlock && "invalid last block");
Clement Courbet65130e22017-09-01 10:56:34 +0000641 BasicBlock *CurBlock = LastBlock;
642 for (int BlockIndex = NumBlocks - 1; BlockIndex > 0; --BlockIndex) {
643 if (CurBlock->hasAddressTaken()) {
644 // Somebody is jumping to the block through an address, all bets are
645 // off.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000646 LLVM_DEBUG(dbgs() << "skip: block " << BlockIndex
647 << " has its address taken\n");
Clement Courbet65130e22017-09-01 10:56:34 +0000648 return {};
649 }
650 Blocks[BlockIndex] = CurBlock;
651 auto *SinglePredecessor = CurBlock->getSinglePredecessor();
652 if (!SinglePredecessor) {
653 // The block has two or more predecessors.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000654 LLVM_DEBUG(dbgs() << "skip: block " << BlockIndex
655 << " has two or more predecessors\n");
Clement Courbet65130e22017-09-01 10:56:34 +0000656 return {};
657 }
658 if (Phi.getBasicBlockIndex(SinglePredecessor) < 0) {
659 // The block does not link back to the phi.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000660 LLVM_DEBUG(dbgs() << "skip: block " << BlockIndex
661 << " does not link back to the phi\n");
Clement Courbet65130e22017-09-01 10:56:34 +0000662 return {};
663 }
664 CurBlock = SinglePredecessor;
665 }
666 Blocks[0] = CurBlock;
667 return Blocks;
668}
669
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000670bool processPhi(PHINode &Phi, const TargetLibraryInfo *const TLI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000671 LLVM_DEBUG(dbgs() << "processPhi()\n");
Clement Courbet65130e22017-09-01 10:56:34 +0000672 if (Phi.getNumIncomingValues() <= 1) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000673 LLVM_DEBUG(dbgs() << "skip: only one incoming value in phi\n");
Clement Courbet65130e22017-09-01 10:56:34 +0000674 return false;
675 }
676 // We are looking for something that has the following structure:
677 // bb1 --eq--> bb2 --eq--> bb3 --eq--> bb4 --+
678 // \ \ \ \
679 // ne ne ne \
680 // \ \ \ v
681 // +------------+-----------+----------> bb_phi
682 //
683 // - The last basic block (bb4 here) must branch unconditionally to bb_phi.
684 // It's the only block that contributes a non-constant value to the Phi.
685 // - All other blocks (b1, b2, b3) must have exactly two successors, one of
Hiroshi Inoued24ddcd2018-01-19 10:55:29 +0000686 // them being the phi block.
Clement Courbet65130e22017-09-01 10:56:34 +0000687 // - All intermediate blocks (bb2, bb3) must have only one predecessor.
688 // - Blocks cannot do other work besides the comparison, see doesOtherWork()
689
690 // The blocks are not necessarily ordered in the phi, so we start from the
691 // last block and reconstruct the order.
692 BasicBlock *LastBlock = nullptr;
693 for (unsigned I = 0; I < Phi.getNumIncomingValues(); ++I) {
Clement Courbet98eaa882017-10-04 15:13:52 +0000694 if (isa<ConstantInt>(Phi.getIncomingValue(I))) continue;
Clement Courbet65130e22017-09-01 10:56:34 +0000695 if (LastBlock) {
696 // There are several non-constant values.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000697 LLVM_DEBUG(dbgs() << "skip: several non-constant values\n");
Clement Courbet65130e22017-09-01 10:56:34 +0000698 return false;
699 }
Xin Tong8ba674e2018-02-28 12:08:00 +0000700 if (!isa<ICmpInst>(Phi.getIncomingValue(I)) ||
701 cast<ICmpInst>(Phi.getIncomingValue(I))->getParent() !=
702 Phi.getIncomingBlock(I)) {
703 // Non-constant incoming value is not from a cmp instruction or not
704 // produced by the last block. We could end up processing the value
705 // producing block more than once.
706 //
707 // This is an uncommon case, so we bail.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000708 LLVM_DEBUG(
Xin Tong8ba674e2018-02-28 12:08:00 +0000709 dbgs()
710 << "skip: non-constant value not from cmp or not from last block.\n");
711 return false;
712 }
Clement Courbet65130e22017-09-01 10:56:34 +0000713 LastBlock = Phi.getIncomingBlock(I);
714 }
715 if (!LastBlock) {
716 // There is no non-constant block.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000717 LLVM_DEBUG(dbgs() << "skip: no non-constant block\n");
Clement Courbet65130e22017-09-01 10:56:34 +0000718 return false;
719 }
720 if (LastBlock->getSingleSuccessor() != Phi.getParent()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000721 LLVM_DEBUG(dbgs() << "skip: last block non-phi successor\n");
Clement Courbet65130e22017-09-01 10:56:34 +0000722 return false;
723 }
724
725 const auto Blocks =
726 getOrderedBlocks(Phi, LastBlock, Phi.getNumIncomingValues());
Clement Courbet98eaa882017-10-04 15:13:52 +0000727 if (Blocks.empty()) return false;
Clement Courbet65130e22017-09-01 10:56:34 +0000728 BCECmpChain CmpChain(Blocks, Phi);
729
730 if (CmpChain.size() < 2) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000731 LLVM_DEBUG(dbgs() << "skip: only one compare block\n");
Clement Courbet65130e22017-09-01 10:56:34 +0000732 return false;
733 }
734
735 return CmpChain.simplify(TLI);
736}
737
738class MergeICmps : public FunctionPass {
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000739 public:
Clement Courbet65130e22017-09-01 10:56:34 +0000740 static char ID;
741
742 MergeICmps() : FunctionPass(ID) {
743 initializeMergeICmpsPass(*PassRegistry::getPassRegistry());
744 }
745
746 bool runOnFunction(Function &F) override {
747 if (skipFunction(F)) return false;
748 const auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000749 const auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
750 auto PA = runImpl(F, &TLI, &TTI);
Clement Courbet65130e22017-09-01 10:56:34 +0000751 return !PA.areAllPreserved();
752 }
753
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000754 private:
Clement Courbet65130e22017-09-01 10:56:34 +0000755 void getAnalysisUsage(AnalysisUsage &AU) const override {
756 AU.addRequired<TargetLibraryInfoWrapperPass>();
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000757 AU.addRequired<TargetTransformInfoWrapperPass>();
Clement Courbet65130e22017-09-01 10:56:34 +0000758 }
759
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000760 PreservedAnalyses runImpl(Function &F, const TargetLibraryInfo *TLI,
761 const TargetTransformInfo *TTI);
Clement Courbet65130e22017-09-01 10:56:34 +0000762};
763
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000764PreservedAnalyses MergeICmps::runImpl(Function &F, const TargetLibraryInfo *TLI,
765 const TargetTransformInfo *TTI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000766 LLVM_DEBUG(dbgs() << "MergeICmpsPass: " << F.getName() << "\n");
Clement Courbet65130e22017-09-01 10:56:34 +0000767
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000768 // We only try merging comparisons if the target wants to expand memcmp later.
769 // The rationale is to avoid turning small chains into memcmp calls.
Clement Courbetb2c3eb82017-10-30 14:19:33 +0000770 if (!TTI->enableMemCmpExpansion(true)) return PreservedAnalyses::all();
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000771
Benjamin Kramera76b64f2018-05-19 12:51:59 +0000772 // If we don't have memcmp avaiable we can't emit calls to it.
773 if (!TLI->has(LibFunc_memcmp))
774 return PreservedAnalyses::all();
775
Clement Courbet65130e22017-09-01 10:56:34 +0000776 bool MadeChange = false;
777
778 for (auto BBIt = ++F.begin(); BBIt != F.end(); ++BBIt) {
779 // A Phi operation is always first in a basic block.
780 if (auto *const Phi = dyn_cast<PHINode>(&*BBIt->begin()))
781 MadeChange |= processPhi(*Phi, TLI);
782 }
783
Clement Courbet98eaa882017-10-04 15:13:52 +0000784 if (MadeChange) return PreservedAnalyses::none();
Clement Courbet65130e22017-09-01 10:56:34 +0000785 return PreservedAnalyses::all();
786}
787
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000788} // namespace
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000789
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000790char MergeICmps::ID = 0;
Clement Courbet65130e22017-09-01 10:56:34 +0000791INITIALIZE_PASS_BEGIN(MergeICmps, "mergeicmps",
792 "Merge contiguous icmps into a memcmp", false, false)
793INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000794INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Clement Courbet65130e22017-09-01 10:56:34 +0000795INITIALIZE_PASS_END(MergeICmps, "mergeicmps",
796 "Merge contiguous icmps into a memcmp", false, false)
797
798Pass *llvm::createMergeICmpsPass() { return new MergeICmps(); }