blob: 420a41e83fe8b9656b2dffdce2e607161671fd59 [file] [log] [blame]
Jingyue Wud7966ff2015-02-03 19:37:06 +00001//===-- StraightLineStrengthReduce.cpp - ------------------------*- C++ -*-===//
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 file implements straight-line strength reduction (SLSR). Unlike loop
11// strength reduction, this algorithm is designed to reduce arithmetic
12// redundancy in straight-line code instead of loops. It has proven to be
13// effective in simplifying arithmetic statements derived from an unrolled loop.
14// It can also simplify the logic of SeparateConstOffsetFromGEP.
15//
16// There are many optimizations we can perform in the domain of SLSR. This file
17// for now contains only an initial step. Specifically, we look for strength
Jingyue Wu43885eb2015-04-15 16:46:13 +000018// reduction candidates in the following forms:
Jingyue Wud7966ff2015-02-03 19:37:06 +000019//
Jingyue Wu43885eb2015-04-15 16:46:13 +000020// Form 1: B + i * S
21// Form 2: (B + i) * S
22// Form 3: &B[i * S]
Jingyue Wud7966ff2015-02-03 19:37:06 +000023//
Jingyue Wu177a8152015-03-26 16:49:24 +000024// where S is an integer variable, and i is a constant integer. If we found two
Jingyue Wu43885eb2015-04-15 16:46:13 +000025// candidates S1 and S2 in the same form and S1 dominates S2, we may rewrite S2
26// in a simpler way with respect to S1. For example,
27//
28// S1: X = B + i * S
29// S2: Y = B + i' * S => X + (i' - i) * S
Jingyue Wud7966ff2015-02-03 19:37:06 +000030//
Jingyue Wu177a8152015-03-26 16:49:24 +000031// S1: X = (B + i) * S
Jingyue Wu43885eb2015-04-15 16:46:13 +000032// S2: Y = (B + i') * S => X + (i' - i) * S
Jingyue Wu177a8152015-03-26 16:49:24 +000033//
34// S1: X = &B[i * S]
Jingyue Wu43885eb2015-04-15 16:46:13 +000035// S2: Y = &B[i' * S] => &X[(i' - i) * S]
Jingyue Wud7966ff2015-02-03 19:37:06 +000036//
Jingyue Wu43885eb2015-04-15 16:46:13 +000037// Note: (i' - i) * S is folded to the extent possible.
Jingyue Wud7966ff2015-02-03 19:37:06 +000038//
Jingyue Wu43885eb2015-04-15 16:46:13 +000039// This rewriting is in general a good idea. The code patterns we focus on
40// usually come from loop unrolling, so (i' - i) * S is likely the same
41// across iterations and can be reused. When that happens, the optimized form
42// takes only one add starting from the second iteration.
Jingyue Wud7966ff2015-02-03 19:37:06 +000043//
Jingyue Wu43885eb2015-04-15 16:46:13 +000044// When such rewriting is possible, we call S1 a "basis" of S2. When S2 has
45// multiple bases, we choose to rewrite S2 with respect to its "immediate"
46// basis, the basis that is the closest ancestor in the dominator tree.
Jingyue Wud7966ff2015-02-03 19:37:06 +000047//
48// TODO:
49//
Jingyue Wud7966ff2015-02-03 19:37:06 +000050// - Floating point arithmetics when fast math is enabled.
51//
52// - SLSR may decrease ILP at the architecture level. Targets that are very
53// sensitive to ILP may want to disable it. Having SLSR to consider ILP is
54// left as future work.
Jingyue Wu43885eb2015-04-15 16:46:13 +000055//
56// - When (i' - i) is constant but i and i' are not, we could still perform
57// SLSR.
Jingyue Wu177a8152015-03-26 16:49:24 +000058#include "llvm/Analysis/ScalarEvolution.h"
59#include "llvm/Analysis/TargetTransformInfo.h"
Jingyue Wu80a96d292015-05-15 17:07:48 +000060#include "llvm/Analysis/ValueTracking.h"
Jingyue Wu177a8152015-03-26 16:49:24 +000061#include "llvm/IR/DataLayout.h"
Jingyue Wud7966ff2015-02-03 19:37:06 +000062#include "llvm/IR/Dominators.h"
63#include "llvm/IR/IRBuilder.h"
64#include "llvm/IR/Module.h"
65#include "llvm/IR/PatternMatch.h"
66#include "llvm/Support/raw_ostream.h"
67#include "llvm/Transforms/Scalar.h"
Jingyue Wuf1edf3e2015-04-21 19:56:18 +000068#include "llvm/Transforms/Utils/Local.h"
Duncan P. N. Exon Smith077f5b42016-09-11 21:04:36 +000069#include <vector>
Jingyue Wud7966ff2015-02-03 19:37:06 +000070
71using namespace llvm;
72using namespace PatternMatch;
73
74namespace {
75
Matt Arsenaultba437c62016-04-27 00:32:09 +000076static const unsigned UnknownAddressSpace = ~0u;
77
Jingyue Wud7966ff2015-02-03 19:37:06 +000078class StraightLineStrengthReduce : public FunctionPass {
Jingyue Wu177a8152015-03-26 16:49:24 +000079public:
Jingyue Wu43885eb2015-04-15 16:46:13 +000080 // SLSR candidate. Such a candidate must be in one of the forms described in
81 // the header comments.
Jingyue Wud7966ff2015-02-03 19:37:06 +000082 struct Candidate : public ilist_node<Candidate> {
Jingyue Wu177a8152015-03-26 16:49:24 +000083 enum Kind {
84 Invalid, // reserved for the default constructor
Jingyue Wu43885eb2015-04-15 16:46:13 +000085 Add, // B + i * S
Jingyue Wu177a8152015-03-26 16:49:24 +000086 Mul, // (B + i) * S
87 GEP, // &B[..][i * S][..]
88 };
89
90 Candidate()
91 : CandidateKind(Invalid), Base(nullptr), Index(nullptr),
92 Stride(nullptr), Ins(nullptr), Basis(nullptr) {}
93 Candidate(Kind CT, const SCEV *B, ConstantInt *Idx, Value *S,
94 Instruction *I)
95 : CandidateKind(CT), Base(B), Index(Idx), Stride(S), Ins(I),
96 Basis(nullptr) {}
97 Kind CandidateKind;
98 const SCEV *Base;
Jingyue Wu43885eb2015-04-15 16:46:13 +000099 // Note that Index and Stride of a GEP candidate do not necessarily have the
100 // same integer type. In that case, during rewriting, Stride will be
Jingyue Wu177a8152015-03-26 16:49:24 +0000101 // sign-extended or truncated to Index's type.
Jingyue Wud7966ff2015-02-03 19:37:06 +0000102 ConstantInt *Index;
103 Value *Stride;
104 // The instruction this candidate corresponds to. It helps us to rewrite a
105 // candidate with respect to its immediate basis. Note that one instruction
Jingyue Wu43885eb2015-04-15 16:46:13 +0000106 // can correspond to multiple candidates depending on how you associate the
Jingyue Wud7966ff2015-02-03 19:37:06 +0000107 // expression. For instance,
108 //
109 // (a + 1) * (b + 2)
110 //
111 // can be treated as
112 //
113 // <Base: a, Index: 1, Stride: b + 2>
114 //
115 // or
116 //
117 // <Base: b, Index: 2, Stride: a + 1>
118 Instruction *Ins;
119 // Points to the immediate basis of this candidate, or nullptr if we cannot
120 // find any basis for this candidate.
121 Candidate *Basis;
122 };
123
124 static char ID;
125
Jingyue Wu177a8152015-03-26 16:49:24 +0000126 StraightLineStrengthReduce()
127 : FunctionPass(ID), DL(nullptr), DT(nullptr), TTI(nullptr) {
Jingyue Wud7966ff2015-02-03 19:37:06 +0000128 initializeStraightLineStrengthReducePass(*PassRegistry::getPassRegistry());
129 }
130
131 void getAnalysisUsage(AnalysisUsage &AU) const override {
132 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000133 AU.addRequired<ScalarEvolutionWrapperPass>();
Jingyue Wu177a8152015-03-26 16:49:24 +0000134 AU.addRequired<TargetTransformInfoWrapperPass>();
Jingyue Wud7966ff2015-02-03 19:37:06 +0000135 // We do not modify the shape of the CFG.
136 AU.setPreservesCFG();
137 }
138
Jingyue Wu177a8152015-03-26 16:49:24 +0000139 bool doInitialization(Module &M) override {
140 DL = &M.getDataLayout();
141 return false;
142 }
143
Jingyue Wud7966ff2015-02-03 19:37:06 +0000144 bool runOnFunction(Function &F) override;
145
Jingyue Wu177a8152015-03-26 16:49:24 +0000146private:
Jingyue Wud7966ff2015-02-03 19:37:06 +0000147 // Returns true if Basis is a basis for C, i.e., Basis dominates C and they
148 // share the same base and stride.
149 bool isBasisFor(const Candidate &Basis, const Candidate &C);
Jingyue Wu43885eb2015-04-15 16:46:13 +0000150 // Returns whether the candidate can be folded into an addressing mode.
151 bool isFoldable(const Candidate &C, TargetTransformInfo *TTI,
152 const DataLayout *DL);
153 // Returns true if C is already in a simplest form and not worth being
154 // rewritten.
155 bool isSimplestForm(const Candidate &C);
Jingyue Wud7966ff2015-02-03 19:37:06 +0000156 // Checks whether I is in a candidate form. If so, adds all the matching forms
157 // to Candidates, and tries to find the immediate basis for each of them.
Jingyue Wu43885eb2015-04-15 16:46:13 +0000158 void allocateCandidatesAndFindBasis(Instruction *I);
159 // Allocate candidates and find bases for Add instructions.
160 void allocateCandidatesAndFindBasisForAdd(Instruction *I);
161 // Given I = LHS + RHS, factors RHS into i * S and makes (LHS + i * S) a
162 // candidate.
163 void allocateCandidatesAndFindBasisForAdd(Value *LHS, Value *RHS,
164 Instruction *I);
Jingyue Wu177a8152015-03-26 16:49:24 +0000165 // Allocate candidates and find bases for Mul instructions.
Jingyue Wu43885eb2015-04-15 16:46:13 +0000166 void allocateCandidatesAndFindBasisForMul(Instruction *I);
Jingyue Wu177a8152015-03-26 16:49:24 +0000167 // Splits LHS into Base + Index and, if succeeds, calls
Jingyue Wu43885eb2015-04-15 16:46:13 +0000168 // allocateCandidatesAndFindBasis.
169 void allocateCandidatesAndFindBasisForMul(Value *LHS, Value *RHS,
170 Instruction *I);
Jingyue Wu177a8152015-03-26 16:49:24 +0000171 // Allocate candidates and find bases for GetElementPtr instructions.
Jingyue Wu43885eb2015-04-15 16:46:13 +0000172 void allocateCandidatesAndFindBasisForGEP(GetElementPtrInst *GEP);
Jingyue Wu177a8152015-03-26 16:49:24 +0000173 // A helper function that scales Idx with ElementSize before invoking
Jingyue Wu43885eb2015-04-15 16:46:13 +0000174 // allocateCandidatesAndFindBasis.
175 void allocateCandidatesAndFindBasisForGEP(const SCEV *B, ConstantInt *Idx,
176 Value *S, uint64_t ElementSize,
177 Instruction *I);
Jingyue Wu177a8152015-03-26 16:49:24 +0000178 // Adds the given form <CT, B, Idx, S> to Candidates, and finds its immediate
179 // basis.
Jingyue Wu43885eb2015-04-15 16:46:13 +0000180 void allocateCandidatesAndFindBasis(Candidate::Kind CT, const SCEV *B,
181 ConstantInt *Idx, Value *S,
182 Instruction *I);
Jingyue Wud7966ff2015-02-03 19:37:06 +0000183 // Rewrites candidate C with respect to Basis.
184 void rewriteCandidateWithBasis(const Candidate &C, const Candidate &Basis);
Jingyue Wu177a8152015-03-26 16:49:24 +0000185 // A helper function that factors ArrayIdx to a product of a stride and a
Jingyue Wu43885eb2015-04-15 16:46:13 +0000186 // constant index, and invokes allocateCandidatesAndFindBasis with the
Jingyue Wu177a8152015-03-26 16:49:24 +0000187 // factorings.
188 void factorArrayIndex(Value *ArrayIdx, const SCEV *Base, uint64_t ElementSize,
189 GetElementPtrInst *GEP);
190 // Emit code that computes the "bump" from Basis to C. If the candidate is a
191 // GEP and the bump is not divisible by the element size of the GEP, this
192 // function sets the BumpWithUglyGEP flag to notify its caller to bump the
193 // basis using an ugly GEP.
194 static Value *emitBump(const Candidate &Basis, const Candidate &C,
195 IRBuilder<> &Builder, const DataLayout *DL,
196 bool &BumpWithUglyGEP);
Jingyue Wud7966ff2015-02-03 19:37:06 +0000197
Jingyue Wu177a8152015-03-26 16:49:24 +0000198 const DataLayout *DL;
Jingyue Wud7966ff2015-02-03 19:37:06 +0000199 DominatorTree *DT;
Jingyue Wu177a8152015-03-26 16:49:24 +0000200 ScalarEvolution *SE;
201 TargetTransformInfo *TTI;
Jingyue Wud7966ff2015-02-03 19:37:06 +0000202 ilist<Candidate> Candidates;
203 // Temporarily holds all instructions that are unlinked (but not deleted) by
204 // rewriteCandidateWithBasis. These instructions will be actually removed
205 // after all rewriting finishes.
Jingyue Wu43885eb2015-04-15 16:46:13 +0000206 std::vector<Instruction *> UnlinkedInstructions;
Jingyue Wud7966ff2015-02-03 19:37:06 +0000207};
208} // anonymous namespace
209
210char StraightLineStrengthReduce::ID = 0;
211INITIALIZE_PASS_BEGIN(StraightLineStrengthReduce, "slsr",
212 "Straight line strength reduction", false, false)
213INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000214INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Jingyue Wu177a8152015-03-26 16:49:24 +0000215INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Jingyue Wud7966ff2015-02-03 19:37:06 +0000216INITIALIZE_PASS_END(StraightLineStrengthReduce, "slsr",
217 "Straight line strength reduction", false, false)
218
219FunctionPass *llvm::createStraightLineStrengthReducePass() {
220 return new StraightLineStrengthReduce();
221}
222
223bool StraightLineStrengthReduce::isBasisFor(const Candidate &Basis,
224 const Candidate &C) {
225 return (Basis.Ins != C.Ins && // skip the same instruction
Jingyue Wu3abde7b2015-06-28 17:45:05 +0000226 // They must have the same type too. Basis.Base == C.Base doesn't
227 // guarantee their types are the same (PR23975).
228 Basis.Ins->getType() == C.Ins->getType() &&
Jingyue Wud7966ff2015-02-03 19:37:06 +0000229 // Basis must dominate C in order to rewrite C with respect to Basis.
230 DT->dominates(Basis.Ins->getParent(), C.Ins->getParent()) &&
Jingyue Wu177a8152015-03-26 16:49:24 +0000231 // They share the same base, stride, and candidate kind.
Jingyue Wu3abde7b2015-06-28 17:45:05 +0000232 Basis.Base == C.Base && Basis.Stride == C.Stride &&
Jingyue Wu177a8152015-03-26 16:49:24 +0000233 Basis.CandidateKind == C.CandidateKind);
234}
235
Jingyue Wu43885eb2015-04-15 16:46:13 +0000236static bool isGEPFoldable(GetElementPtrInst *GEP,
Jingyue Wu15f3e822016-07-08 21:48:05 +0000237 const TargetTransformInfo *TTI) {
238 SmallVector<const Value*, 4> Indices;
239 for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I)
240 Indices.push_back(*I);
241 return TTI->getGEPCost(GEP->getSourceElementType(), GEP->getPointerOperand(),
242 Indices) == TargetTransformInfo::TCC_Free;
Jingyue Wud7966ff2015-02-03 19:37:06 +0000243}
244
Jingyue Wu43885eb2015-04-15 16:46:13 +0000245// Returns whether (Base + Index * Stride) can be folded to an addressing mode.
246static bool isAddFoldable(const SCEV *Base, ConstantInt *Index, Value *Stride,
247 TargetTransformInfo *TTI) {
Jingyue Wudebce552016-07-09 19:13:18 +0000248 // Index->getSExtValue() may crash if Index is wider than 64-bit.
249 return Index->getBitWidth() <= 64 &&
250 TTI->isLegalAddressingMode(Base->getType(), nullptr, 0, true,
Matt Arsenaultba437c62016-04-27 00:32:09 +0000251 Index->getSExtValue(), UnknownAddressSpace);
Jingyue Wu43885eb2015-04-15 16:46:13 +0000252}
253
254bool StraightLineStrengthReduce::isFoldable(const Candidate &C,
255 TargetTransformInfo *TTI,
256 const DataLayout *DL) {
257 if (C.CandidateKind == Candidate::Add)
258 return isAddFoldable(C.Base, C.Index, C.Stride, TTI);
259 if (C.CandidateKind == Candidate::GEP)
Jingyue Wu15f3e822016-07-08 21:48:05 +0000260 return isGEPFoldable(cast<GetElementPtrInst>(C.Ins), TTI);
Jingyue Wu43885eb2015-04-15 16:46:13 +0000261 return false;
262}
263
264// Returns true if GEP has zero or one non-zero index.
265static bool hasOnlyOneNonZeroIndex(GetElementPtrInst *GEP) {
266 unsigned NumNonZeroIndices = 0;
267 for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I) {
268 ConstantInt *ConstIdx = dyn_cast<ConstantInt>(*I);
269 if (ConstIdx == nullptr || !ConstIdx->isZero())
270 ++NumNonZeroIndices;
271 }
272 return NumNonZeroIndices <= 1;
273}
274
275bool StraightLineStrengthReduce::isSimplestForm(const Candidate &C) {
276 if (C.CandidateKind == Candidate::Add) {
277 // B + 1 * S or B + (-1) * S
278 return C.Index->isOne() || C.Index->isMinusOne();
279 }
280 if (C.CandidateKind == Candidate::Mul) {
281 // (B + 0) * S
282 return C.Index->isZero();
283 }
284 if (C.CandidateKind == Candidate::GEP) {
285 // (char*)B + S or (char*)B - S
286 return ((C.Index->isOne() || C.Index->isMinusOne()) &&
287 hasOnlyOneNonZeroIndex(cast<GetElementPtrInst>(C.Ins)));
288 }
289 return false;
290}
291
292// TODO: We currently implement an algorithm whose time complexity is linear in
293// the number of existing candidates. However, we could do better by using
294// ScopedHashTable. Specifically, while traversing the dominator tree, we could
295// maintain all the candidates that dominate the basic block being traversed in
296// a ScopedHashTable. This hash table is indexed by the base and the stride of
297// a candidate. Therefore, finding the immediate basis of a candidate boils down
298// to one hash-table look up.
299void StraightLineStrengthReduce::allocateCandidatesAndFindBasis(
Jingyue Wu177a8152015-03-26 16:49:24 +0000300 Candidate::Kind CT, const SCEV *B, ConstantInt *Idx, Value *S,
301 Instruction *I) {
Jingyue Wu177a8152015-03-26 16:49:24 +0000302 Candidate C(CT, B, Idx, S, I);
Jingyue Wu43885eb2015-04-15 16:46:13 +0000303 // SLSR can complicate an instruction in two cases:
304 //
305 // 1. If we can fold I into an addressing mode, computing I is likely free or
306 // takes only one instruction.
307 //
308 // 2. I is already in a simplest form. For example, when
309 // X = B + 8 * S
310 // Y = B + S,
311 // rewriting Y to X - 7 * S is probably a bad idea.
312 //
313 // In the above cases, we still add I to the candidate list so that I can be
314 // the basis of other candidates, but we leave I's basis blank so that I
315 // won't be rewritten.
316 if (!isFoldable(C, TTI, DL) && !isSimplestForm(C)) {
317 // Try to compute the immediate basis of C.
318 unsigned NumIterations = 0;
319 // Limit the scan radius to avoid running in quadratice time.
320 static const unsigned MaxNumIterations = 50;
321 for (auto Basis = Candidates.rbegin();
322 Basis != Candidates.rend() && NumIterations < MaxNumIterations;
323 ++Basis, ++NumIterations) {
324 if (isBasisFor(*Basis, C)) {
325 C.Basis = &(*Basis);
326 break;
327 }
Jingyue Wud7966ff2015-02-03 19:37:06 +0000328 }
329 }
330 // Regardless of whether we find a basis for C, we need to push C to the
Jingyue Wu43885eb2015-04-15 16:46:13 +0000331 // candidate list so that it can be the basis of other candidates.
Jingyue Wud7966ff2015-02-03 19:37:06 +0000332 Candidates.push_back(C);
333}
334
Jingyue Wu43885eb2015-04-15 16:46:13 +0000335void StraightLineStrengthReduce::allocateCandidatesAndFindBasis(
336 Instruction *I) {
Jingyue Wu177a8152015-03-26 16:49:24 +0000337 switch (I->getOpcode()) {
Jingyue Wu43885eb2015-04-15 16:46:13 +0000338 case Instruction::Add:
339 allocateCandidatesAndFindBasisForAdd(I);
340 break;
Jingyue Wu177a8152015-03-26 16:49:24 +0000341 case Instruction::Mul:
Jingyue Wu43885eb2015-04-15 16:46:13 +0000342 allocateCandidatesAndFindBasisForMul(I);
Jingyue Wu177a8152015-03-26 16:49:24 +0000343 break;
344 case Instruction::GetElementPtr:
Jingyue Wu43885eb2015-04-15 16:46:13 +0000345 allocateCandidatesAndFindBasisForGEP(cast<GetElementPtrInst>(I));
Jingyue Wu177a8152015-03-26 16:49:24 +0000346 break;
347 }
348}
349
Jingyue Wu43885eb2015-04-15 16:46:13 +0000350void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForAdd(
351 Instruction *I) {
352 // Try matching B + i * S.
353 if (!isa<IntegerType>(I->getType()))
354 return;
355
356 assert(I->getNumOperands() == 2 && "isn't I an add?");
357 Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
358 allocateCandidatesAndFindBasisForAdd(LHS, RHS, I);
359 if (LHS != RHS)
360 allocateCandidatesAndFindBasisForAdd(RHS, LHS, I);
361}
362
363void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForAdd(
364 Value *LHS, Value *RHS, Instruction *I) {
365 Value *S = nullptr;
366 ConstantInt *Idx = nullptr;
367 if (match(RHS, m_Mul(m_Value(S), m_ConstantInt(Idx)))) {
368 // I = LHS + RHS = LHS + Idx * S
369 allocateCandidatesAndFindBasis(Candidate::Add, SE->getSCEV(LHS), Idx, S, I);
370 } else if (match(RHS, m_Shl(m_Value(S), m_ConstantInt(Idx)))) {
371 // I = LHS + RHS = LHS + (S << Idx) = LHS + S * (1 << Idx)
372 APInt One(Idx->getBitWidth(), 1);
373 Idx = ConstantInt::get(Idx->getContext(), One << Idx->getValue());
374 allocateCandidatesAndFindBasis(Candidate::Add, SE->getSCEV(LHS), Idx, S, I);
375 } else {
376 // At least, I = LHS + 1 * RHS
377 ConstantInt *One = ConstantInt::get(cast<IntegerType>(I->getType()), 1);
378 allocateCandidatesAndFindBasis(Candidate::Add, SE->getSCEV(LHS), One, RHS,
379 I);
380 }
381}
382
Jingyue Wu80a96d292015-05-15 17:07:48 +0000383// Returns true if A matches B + C where C is constant.
384static bool matchesAdd(Value *A, Value *&B, ConstantInt *&C) {
385 return (match(A, m_Add(m_Value(B), m_ConstantInt(C))) ||
386 match(A, m_Add(m_ConstantInt(C), m_Value(B))));
387}
388
389// Returns true if A matches B | C where C is constant.
390static bool matchesOr(Value *A, Value *&B, ConstantInt *&C) {
391 return (match(A, m_Or(m_Value(B), m_ConstantInt(C))) ||
392 match(A, m_Or(m_ConstantInt(C), m_Value(B))));
393}
394
Jingyue Wu43885eb2015-04-15 16:46:13 +0000395void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForMul(
Jingyue Wu177a8152015-03-26 16:49:24 +0000396 Value *LHS, Value *RHS, Instruction *I) {
Jingyue Wud7966ff2015-02-03 19:37:06 +0000397 Value *B = nullptr;
398 ConstantInt *Idx = nullptr;
Jingyue Wu80a96d292015-05-15 17:07:48 +0000399 if (matchesAdd(LHS, B, Idx)) {
Jingyue Wu177a8152015-03-26 16:49:24 +0000400 // If LHS is in the form of "Base + Index", then I is in the form of
401 // "(Base + Index) * RHS".
Jingyue Wu43885eb2015-04-15 16:46:13 +0000402 allocateCandidatesAndFindBasis(Candidate::Mul, SE->getSCEV(B), Idx, RHS, I);
Jingyue Wu80a96d292015-05-15 17:07:48 +0000403 } else if (matchesOr(LHS, B, Idx) && haveNoCommonBitsSet(B, Idx, *DL)) {
404 // If LHS is in the form of "Base | Index" and Base and Index have no common
405 // bits set, then
406 // Base | Index = Base + Index
407 // and I is thus in the form of "(Base + Index) * RHS".
408 allocateCandidatesAndFindBasis(Candidate::Mul, SE->getSCEV(B), Idx, RHS, I);
Jingyue Wu177a8152015-03-26 16:49:24 +0000409 } else {
410 // Otherwise, at least try the form (LHS + 0) * RHS.
411 ConstantInt *Zero = ConstantInt::get(cast<IntegerType>(I->getType()), 0);
Jingyue Wu43885eb2015-04-15 16:46:13 +0000412 allocateCandidatesAndFindBasis(Candidate::Mul, SE->getSCEV(LHS), Zero, RHS,
Jingyue Wu80a96d292015-05-15 17:07:48 +0000413 I);
Jingyue Wud7966ff2015-02-03 19:37:06 +0000414 }
415}
416
Jingyue Wu43885eb2015-04-15 16:46:13 +0000417void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForMul(
Jingyue Wu177a8152015-03-26 16:49:24 +0000418 Instruction *I) {
419 // Try matching (B + i) * S.
420 // TODO: we could extend SLSR to float and vector types.
421 if (!isa<IntegerType>(I->getType()))
422 return;
423
Jingyue Wu43885eb2015-04-15 16:46:13 +0000424 assert(I->getNumOperands() == 2 && "isn't I a mul?");
Jingyue Wu177a8152015-03-26 16:49:24 +0000425 Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
Jingyue Wu43885eb2015-04-15 16:46:13 +0000426 allocateCandidatesAndFindBasisForMul(LHS, RHS, I);
Jingyue Wu177a8152015-03-26 16:49:24 +0000427 if (LHS != RHS) {
428 // Symmetrically, try to split RHS to Base + Index.
Jingyue Wu43885eb2015-04-15 16:46:13 +0000429 allocateCandidatesAndFindBasisForMul(RHS, LHS, I);
Jingyue Wu177a8152015-03-26 16:49:24 +0000430 }
431}
432
Jingyue Wu43885eb2015-04-15 16:46:13 +0000433void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForGEP(
Jingyue Wu177a8152015-03-26 16:49:24 +0000434 const SCEV *B, ConstantInt *Idx, Value *S, uint64_t ElementSize,
435 Instruction *I) {
Jingyue Wu99a6bed2015-04-02 21:18:32 +0000436 // I = B + sext(Idx *nsw S) * ElementSize
437 // = B + (sext(Idx) * sext(S)) * ElementSize
Jingyue Wu177a8152015-03-26 16:49:24 +0000438 // = B + (sext(Idx) * ElementSize) * sext(S)
439 // Casting to IntegerType is safe because we skipped vector GEPs.
440 IntegerType *IntPtrTy = cast<IntegerType>(DL->getIntPtrType(I->getType()));
441 ConstantInt *ScaledIdx = ConstantInt::get(
442 IntPtrTy, Idx->getSExtValue() * (int64_t)ElementSize, true);
Jingyue Wu43885eb2015-04-15 16:46:13 +0000443 allocateCandidatesAndFindBasis(Candidate::GEP, B, ScaledIdx, S, I);
Jingyue Wu177a8152015-03-26 16:49:24 +0000444}
445
446void StraightLineStrengthReduce::factorArrayIndex(Value *ArrayIdx,
447 const SCEV *Base,
448 uint64_t ElementSize,
449 GetElementPtrInst *GEP) {
Jingyue Wu43885eb2015-04-15 16:46:13 +0000450 // At least, ArrayIdx = ArrayIdx *nsw 1.
451 allocateCandidatesAndFindBasisForGEP(
Jingyue Wu177a8152015-03-26 16:49:24 +0000452 Base, ConstantInt::get(cast<IntegerType>(ArrayIdx->getType()), 1),
453 ArrayIdx, ElementSize, GEP);
454 Value *LHS = nullptr;
455 ConstantInt *RHS = nullptr;
Jingyue Wu177a8152015-03-26 16:49:24 +0000456 // One alternative is matching the SCEV of ArrayIdx instead of ArrayIdx
457 // itself. This would allow us to handle the shl case for free. However,
458 // matching SCEVs has two issues:
459 //
460 // 1. this would complicate rewriting because the rewriting procedure
461 // would have to translate SCEVs back to IR instructions. This translation
462 // is difficult when LHS is further evaluated to a composite SCEV.
463 //
464 // 2. ScalarEvolution is designed to be control-flow oblivious. It tends
465 // to strip nsw/nuw flags which are critical for SLSR to trace into
466 // sext'ed multiplication.
467 if (match(ArrayIdx, m_NSWMul(m_Value(LHS), m_ConstantInt(RHS)))) {
468 // SLSR is currently unsafe if i * S may overflow.
Jingyue Wu99a6bed2015-04-02 21:18:32 +0000469 // GEP = Base + sext(LHS *nsw RHS) * ElementSize
Jingyue Wu43885eb2015-04-15 16:46:13 +0000470 allocateCandidatesAndFindBasisForGEP(Base, RHS, LHS, ElementSize, GEP);
Jingyue Wu96d74002015-04-06 17:15:48 +0000471 } else if (match(ArrayIdx, m_NSWShl(m_Value(LHS), m_ConstantInt(RHS)))) {
472 // GEP = Base + sext(LHS <<nsw RHS) * ElementSize
473 // = Base + sext(LHS *nsw (1 << RHS)) * ElementSize
474 APInt One(RHS->getBitWidth(), 1);
475 ConstantInt *PowerOf2 =
476 ConstantInt::get(RHS->getContext(), One << RHS->getValue());
Jingyue Wu43885eb2015-04-15 16:46:13 +0000477 allocateCandidatesAndFindBasisForGEP(Base, PowerOf2, LHS, ElementSize, GEP);
Jingyue Wu177a8152015-03-26 16:49:24 +0000478 }
479}
480
Jingyue Wu43885eb2015-04-15 16:46:13 +0000481void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForGEP(
Jingyue Wu177a8152015-03-26 16:49:24 +0000482 GetElementPtrInst *GEP) {
483 // TODO: handle vector GEPs
484 if (GEP->getType()->isVectorTy())
485 return;
486
Jingyue Wu2982d4d2015-05-18 17:03:25 +0000487 SmallVector<const SCEV *, 4> IndexExprs;
488 for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I)
489 IndexExprs.push_back(SE->getSCEV(*I));
Jingyue Wu177a8152015-03-26 16:49:24 +0000490
491 gep_type_iterator GTI = gep_type_begin(GEP);
Jingyue Wu2982d4d2015-05-18 17:03:25 +0000492 for (unsigned I = 1, E = GEP->getNumOperands(); I != E; ++I) {
Jingyue Wu177a8152015-03-26 16:49:24 +0000493 if (!isa<SequentialType>(*GTI++))
494 continue;
Jingyue Wu2982d4d2015-05-18 17:03:25 +0000495
496 const SCEV *OrigIndexExpr = IndexExprs[I - 1];
Sanjoy Das2aacc0e2015-09-23 01:59:04 +0000497 IndexExprs[I - 1] = SE->getZero(OrigIndexExpr->getType());
Jingyue Wu2982d4d2015-05-18 17:03:25 +0000498
499 // The base of this candidate is GEP's base plus the offsets of all
500 // indices except this current one.
501 const SCEV *BaseExpr = SE->getGEPExpr(GEP->getSourceElementType(),
502 SE->getSCEV(GEP->getPointerOperand()),
503 IndexExprs, GEP->isInBounds());
504 Value *ArrayIdx = GEP->getOperand(I);
Jingyue Wu177a8152015-03-26 16:49:24 +0000505 uint64_t ElementSize = DL->getTypeAllocSize(*GTI);
Jingyue Wudebce552016-07-09 19:13:18 +0000506 if (ArrayIdx->getType()->getIntegerBitWidth() <=
Jingyue Wu641cfee2016-07-11 18:13:28 +0000507 DL->getPointerSizeInBits(GEP->getAddressSpace())) {
Jingyue Wudebce552016-07-09 19:13:18 +0000508 // Skip factoring if ArrayIdx is wider than the pointer size, because
509 // ArrayIdx is implicitly truncated to the pointer size.
510 factorArrayIndex(ArrayIdx, BaseExpr, ElementSize, GEP);
511 }
Jingyue Wu177a8152015-03-26 16:49:24 +0000512 // When ArrayIdx is the sext of a value, we try to factor that value as
513 // well. Handling this case is important because array indices are
514 // typically sign-extended to the pointer size.
515 Value *TruncatedArrayIdx = nullptr;
Jingyue Wudebce552016-07-09 19:13:18 +0000516 if (match(ArrayIdx, m_SExt(m_Value(TruncatedArrayIdx))) &&
517 TruncatedArrayIdx->getType()->getIntegerBitWidth() <=
Jingyue Wu641cfee2016-07-11 18:13:28 +0000518 DL->getPointerSizeInBits(GEP->getAddressSpace())) {
Jingyue Wudebce552016-07-09 19:13:18 +0000519 // Skip factoring if TruncatedArrayIdx is wider than the pointer size,
520 // because TruncatedArrayIdx is implicitly truncated to the pointer size.
Jingyue Wu2982d4d2015-05-18 17:03:25 +0000521 factorArrayIndex(TruncatedArrayIdx, BaseExpr, ElementSize, GEP);
Jingyue Wudebce552016-07-09 19:13:18 +0000522 }
Jingyue Wu2982d4d2015-05-18 17:03:25 +0000523
524 IndexExprs[I - 1] = OrigIndexExpr;
Jingyue Wu177a8152015-03-26 16:49:24 +0000525 }
526}
527
528// A helper function that unifies the bitwidth of A and B.
529static void unifyBitWidth(APInt &A, APInt &B) {
530 if (A.getBitWidth() < B.getBitWidth())
531 A = A.sext(B.getBitWidth());
532 else if (A.getBitWidth() > B.getBitWidth())
533 B = B.sext(A.getBitWidth());
534}
535
536Value *StraightLineStrengthReduce::emitBump(const Candidate &Basis,
537 const Candidate &C,
538 IRBuilder<> &Builder,
539 const DataLayout *DL,
540 bool &BumpWithUglyGEP) {
541 APInt Idx = C.Index->getValue(), BasisIdx = Basis.Index->getValue();
542 unifyBitWidth(Idx, BasisIdx);
543 APInt IndexOffset = Idx - BasisIdx;
544
545 BumpWithUglyGEP = false;
546 if (Basis.CandidateKind == Candidate::GEP) {
547 APInt ElementSize(
548 IndexOffset.getBitWidth(),
Jingyue Wudebce552016-07-09 19:13:18 +0000549 DL->getTypeAllocSize(
550 cast<GetElementPtrInst>(Basis.Ins)->getResultElementType()));
Jingyue Wu177a8152015-03-26 16:49:24 +0000551 APInt Q, R;
552 APInt::sdivrem(IndexOffset, ElementSize, Q, R);
Jingyue Wudebce552016-07-09 19:13:18 +0000553 if (R == 0)
Jingyue Wu177a8152015-03-26 16:49:24 +0000554 IndexOffset = Q;
555 else
556 BumpWithUglyGEP = true;
557 }
Jingyue Wu43885eb2015-04-15 16:46:13 +0000558
Jingyue Wu177a8152015-03-26 16:49:24 +0000559 // Compute Bump = C - Basis = (i' - i) * S.
560 // Common case 1: if (i' - i) is 1, Bump = S.
Jingyue Wudebce552016-07-09 19:13:18 +0000561 if (IndexOffset == 1)
Jingyue Wu177a8152015-03-26 16:49:24 +0000562 return C.Stride;
563 // Common case 2: if (i' - i) is -1, Bump = -S.
Jingyue Wudebce552016-07-09 19:13:18 +0000564 if (IndexOffset.isAllOnesValue())
Jingyue Wu177a8152015-03-26 16:49:24 +0000565 return Builder.CreateNeg(C.Stride);
Jingyue Wu43885eb2015-04-15 16:46:13 +0000566
567 // Otherwise, Bump = (i' - i) * sext/trunc(S). Note that (i' - i) and S may
568 // have different bit widths.
569 IntegerType *DeltaType =
570 IntegerType::get(Basis.Ins->getContext(), IndexOffset.getBitWidth());
571 Value *ExtendedStride = Builder.CreateSExtOrTrunc(C.Stride, DeltaType);
572 if (IndexOffset.isPowerOf2()) {
573 // If (i' - i) is a power of 2, Bump = sext/trunc(S) << log(i' - i).
574 ConstantInt *Exponent = ConstantInt::get(DeltaType, IndexOffset.logBase2());
575 return Builder.CreateShl(ExtendedStride, Exponent);
576 }
577 if ((-IndexOffset).isPowerOf2()) {
578 // If (i - i') is a power of 2, Bump = -sext/trunc(S) << log(i' - i).
579 ConstantInt *Exponent =
580 ConstantInt::get(DeltaType, (-IndexOffset).logBase2());
581 return Builder.CreateNeg(Builder.CreateShl(ExtendedStride, Exponent));
582 }
583 Constant *Delta = ConstantInt::get(DeltaType, IndexOffset);
Jingyue Wu177a8152015-03-26 16:49:24 +0000584 return Builder.CreateMul(ExtendedStride, Delta);
585}
586
Jingyue Wud7966ff2015-02-03 19:37:06 +0000587void StraightLineStrengthReduce::rewriteCandidateWithBasis(
588 const Candidate &C, const Candidate &Basis) {
Jingyue Wu177a8152015-03-26 16:49:24 +0000589 assert(C.CandidateKind == Basis.CandidateKind && C.Base == Basis.Base &&
590 C.Stride == Basis.Stride);
Jingyue Wu43885eb2015-04-15 16:46:13 +0000591 // We run rewriteCandidateWithBasis on all candidates in a post-order, so the
592 // basis of a candidate cannot be unlinked before the candidate.
593 assert(Basis.Ins->getParent() != nullptr && "the basis is unlinked");
Jingyue Wu177a8152015-03-26 16:49:24 +0000594
Jingyue Wud7966ff2015-02-03 19:37:06 +0000595 // An instruction can correspond to multiple candidates. Therefore, instead of
596 // simply deleting an instruction when we rewrite it, we mark its parent as
597 // nullptr (i.e. unlink it) so that we can skip the candidates whose
598 // instruction is already rewritten.
599 if (!C.Ins->getParent())
600 return;
Jingyue Wu177a8152015-03-26 16:49:24 +0000601
Jingyue Wud7966ff2015-02-03 19:37:06 +0000602 IRBuilder<> Builder(C.Ins);
Jingyue Wu177a8152015-03-26 16:49:24 +0000603 bool BumpWithUglyGEP;
604 Value *Bump = emitBump(Basis, C, Builder, DL, BumpWithUglyGEP);
605 Value *Reduced = nullptr; // equivalent to but weaker than C.Ins
606 switch (C.CandidateKind) {
Jingyue Wu43885eb2015-04-15 16:46:13 +0000607 case Candidate::Add:
Jingyue Wu177a8152015-03-26 16:49:24 +0000608 case Candidate::Mul:
Jingyue Wuf1edf3e2015-04-21 19:56:18 +0000609 // C = Basis + Bump
Jingyue Wu43885eb2015-04-15 16:46:13 +0000610 if (BinaryOperator::isNeg(Bump)) {
Jingyue Wuf1edf3e2015-04-21 19:56:18 +0000611 // If Bump is a neg instruction, emit C = Basis - (-Bump).
Jingyue Wu43885eb2015-04-15 16:46:13 +0000612 Reduced =
613 Builder.CreateSub(Basis.Ins, BinaryOperator::getNegArgument(Bump));
Jingyue Wuf1edf3e2015-04-21 19:56:18 +0000614 // We only use the negative argument of Bump, and Bump itself may be
615 // trivially dead.
616 RecursivelyDeleteTriviallyDeadInstructions(Bump);
Jingyue Wu43885eb2015-04-15 16:46:13 +0000617 } else {
Jingyue Wua9411292015-06-18 03:35:57 +0000618 // It's tempting to preserve nsw on Bump and/or Reduced. However, it's
619 // usually unsound, e.g.,
620 //
621 // X = (-2 +nsw 1) *nsw INT_MAX
622 // Y = (-2 +nsw 3) *nsw INT_MAX
623 // =>
624 // Y = X + 2 * INT_MAX
625 //
626 // Neither + and * in the resultant expression are nsw.
Jingyue Wu43885eb2015-04-15 16:46:13 +0000627 Reduced = Builder.CreateAdd(Basis.Ins, Bump);
628 }
Jingyue Wu177a8152015-03-26 16:49:24 +0000629 break;
630 case Candidate::GEP:
631 {
632 Type *IntPtrTy = DL->getIntPtrType(C.Ins->getType());
Jingyue Wu99a6bed2015-04-02 21:18:32 +0000633 bool InBounds = cast<GetElementPtrInst>(C.Ins)->isInBounds();
Jingyue Wu177a8152015-03-26 16:49:24 +0000634 if (BumpWithUglyGEP) {
635 // C = (char *)Basis + Bump
636 unsigned AS = Basis.Ins->getType()->getPointerAddressSpace();
637 Type *CharTy = Type::getInt8PtrTy(Basis.Ins->getContext(), AS);
638 Reduced = Builder.CreateBitCast(Basis.Ins, CharTy);
Jingyue Wu99a6bed2015-04-02 21:18:32 +0000639 if (InBounds)
David Blaikieaa41cd52015-04-03 21:33:42 +0000640 Reduced =
641 Builder.CreateInBoundsGEP(Builder.getInt8Ty(), Reduced, Bump);
Jingyue Wu99a6bed2015-04-02 21:18:32 +0000642 else
David Blaikie93c54442015-04-03 19:41:44 +0000643 Reduced = Builder.CreateGEP(Builder.getInt8Ty(), Reduced, Bump);
Jingyue Wu177a8152015-03-26 16:49:24 +0000644 Reduced = Builder.CreateBitCast(Reduced, C.Ins->getType());
645 } else {
646 // C = gep Basis, Bump
647 // Canonicalize bump to pointer size.
648 Bump = Builder.CreateSExtOrTrunc(Bump, IntPtrTy);
Jingyue Wu99a6bed2015-04-02 21:18:32 +0000649 if (InBounds)
David Blaikieaa41cd52015-04-03 21:33:42 +0000650 Reduced = Builder.CreateInBoundsGEP(nullptr, Basis.Ins, Bump);
Jingyue Wu99a6bed2015-04-02 21:18:32 +0000651 else
David Blaikie93c54442015-04-03 19:41:44 +0000652 Reduced = Builder.CreateGEP(nullptr, Basis.Ins, Bump);
Jingyue Wu177a8152015-03-26 16:49:24 +0000653 }
654 }
655 break;
656 default:
657 llvm_unreachable("C.CandidateKind is invalid");
658 };
Jingyue Wud7966ff2015-02-03 19:37:06 +0000659 Reduced->takeName(C.Ins);
660 C.Ins->replaceAllUsesWith(Reduced);
Jingyue Wud7966ff2015-02-03 19:37:06 +0000661 // Unlink C.Ins so that we can skip other candidates also corresponding to
662 // C.Ins. The actual deletion is postponed to the end of runOnFunction.
663 C.Ins->removeFromParent();
Jingyue Wu43885eb2015-04-15 16:46:13 +0000664 UnlinkedInstructions.push_back(C.Ins);
Jingyue Wud7966ff2015-02-03 19:37:06 +0000665}
666
667bool StraightLineStrengthReduce::runOnFunction(Function &F) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000668 if (skipFunction(F))
Jingyue Wud7966ff2015-02-03 19:37:06 +0000669 return false;
670
Jingyue Wu177a8152015-03-26 16:49:24 +0000671 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Jingyue Wud7966ff2015-02-03 19:37:06 +0000672 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000673 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Jingyue Wud7966ff2015-02-03 19:37:06 +0000674 // Traverse the dominator tree in the depth-first order. This order makes sure
675 // all bases of a candidate are in Candidates when we process it.
Daniel Berlina36f4632016-08-19 22:06:23 +0000676 for (const auto Node : depth_first(DT))
677 for (auto &I : *(Node->getBlock()))
Jingyue Wu43885eb2015-04-15 16:46:13 +0000678 allocateCandidatesAndFindBasis(&I);
Jingyue Wud7966ff2015-02-03 19:37:06 +0000679
680 // Rewrite candidates in the reverse depth-first order. This order makes sure
681 // a candidate being rewritten is not a basis for any other candidate.
682 while (!Candidates.empty()) {
683 const Candidate &C = Candidates.back();
684 if (C.Basis != nullptr) {
685 rewriteCandidateWithBasis(C, *C.Basis);
686 }
687 Candidates.pop_back();
688 }
689
690 // Delete all unlink instructions.
Jingyue Wuf1edf3e2015-04-21 19:56:18 +0000691 for (auto *UnlinkedInst : UnlinkedInstructions) {
692 for (unsigned I = 0, E = UnlinkedInst->getNumOperands(); I != E; ++I) {
693 Value *Op = UnlinkedInst->getOperand(I);
694 UnlinkedInst->setOperand(I, nullptr);
695 RecursivelyDeleteTriviallyDeadInstructions(Op);
696 }
697 delete UnlinkedInst;
Jingyue Wud7966ff2015-02-03 19:37:06 +0000698 }
699 bool Ret = !UnlinkedInstructions.empty();
700 UnlinkedInstructions.clear();
701 return Ret;
702}