1//===- StraightLineStrengthReduce.cpp - -----------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements straight-line strength reduction (SLSR). Unlike loop
10// strength reduction, this algorithm is designed to reduce arithmetic
11// redundancy in straight-line code instead of loops. It has proven to be
12// effective in simplifying arithmetic statements derived from an unrolled loop.
13// It can also simplify the logic of SeparateConstOffsetFromGEP.
14//
15// There are many optimizations we can perform in the domain of SLSR.
16// We look for strength reduction candidates in the following forms:
17//
18// Form Add: B + i * S
19// Form Mul: (B + i) * S
20// Form GEP: &B[i * S]
21//
22// where S is an integer variable, and i is a constant integer. If we found two
23// candidates S1 and S2 in the same form and S1 dominates S2, we may rewrite S2
24// in a simpler way with respect to S1 (index delta). For example,
25//
26// S1: X = B + i * S
27// S2: Y = B + i' * S => X + (i' - i) * S
28//
29// S1: X = (B + i) * S
30// S2: Y = (B + i') * S => X + (i' - i) * S
31//
32// S1: X = &B[i * S]
33// S2: Y = &B[i' * S] => &X[(i' - i) * S]
34//
35// Note: (i' - i) * S is folded to the extent possible.
36//
37// For Add and GEP forms, we can also rewrite a candidate in a simpler way
38// with respect to other dominating candidates if their B or S are different
39// but other parts are the same. For example,
40//
41// Base Delta:
42// S1: X = B + i * S
43// S2: Y = B' + i * S => X + (B' - B)
44//
45// S1: X = &B [i * S]
46// S2: Y = &B'[i * S] => X + (B' - B)
47//
48// Stride Delta:
49// S1: X = B + i * S
50// S2: Y = B + i * S' => X + i * (S' - S)
51//
52// S1: X = &B[i * S]
53// S2: Y = &B[i * S'] => X + i * (S' - S)
54//
55// PS: Stride delta rewrite on Mul form is usually non-profitable, and Base
56// delta rewrite sometimes is profitable, so we do not support them on Mul.
57//
58// This rewriting is in general a good idea. The code patterns we focus on
59// usually come from loop unrolling, so the delta is likely the same
60// across iterations and can be reused. When that happens, the optimized form
61// takes only one add starting from the second iteration.
62//
63// When such rewriting is possible, we call S1 a "basis" of S2. When S2 has
64// multiple bases, we choose to rewrite S2 with respect to its "immediate"
65// basis, the basis that is the closest ancestor in the dominator tree.
66//
67// TODO:
68//
69// - Floating point arithmetics when fast math is enabled.
70
71#include "llvm/Transforms/Scalar/StraightLineStrengthReduce.h"
72#include "llvm/ADT/APInt.h"
73#include "llvm/ADT/DepthFirstIterator.h"
74#include "llvm/ADT/SetVector.h"
75#include "llvm/ADT/SmallPtrSet.h"
76#include "llvm/ADT/SmallVector.h"
77#include "llvm/ADT/Statistic.h"
78#include "llvm/Analysis/ScalarEvolution.h"
79#include "llvm/Analysis/ScalarEvolutionExpressions.h"
80#include "llvm/Analysis/TargetTransformInfo.h"
81#include "llvm/Analysis/ValueTracking.h"
82#include "llvm/IR/Constants.h"
83#include "llvm/IR/DataLayout.h"
84#include "llvm/IR/DerivedTypes.h"
85#include "llvm/IR/Dominators.h"
86#include "llvm/IR/GetElementPtrTypeIterator.h"
87#include "llvm/IR/IRBuilder.h"
88#include "llvm/IR/Instruction.h"
89#include "llvm/IR/Instructions.h"
90#include "llvm/IR/Module.h"
91#include "llvm/IR/Operator.h"
92#include "llvm/IR/PatternMatch.h"
93#include "llvm/IR/Type.h"
94#include "llvm/IR/Value.h"
95#include "llvm/InitializePasses.h"
96#include "llvm/Pass.h"
97#include "llvm/Support/Casting.h"
98#include "llvm/Support/DebugCounter.h"
99#include "llvm/Support/ErrorHandling.h"
100#include "llvm/Transforms/Scalar.h"
101#include "llvm/Transforms/Utils/Local.h"
102#include <cassert>
103#include <cstdint>
104#include <limits>
105#include <list>
106#include <queue>
107#include <vector>
108
109using namespace llvm;
110using namespace PatternMatch;
111
112#define DEBUG_TYPE "slsr"
113
114static const unsigned UnknownAddressSpace =
115 std::numeric_limits<unsigned>::max();
116
117DEBUG_COUNTER(StraightLineStrengthReduceCounter, "slsr-counter",
118 "Controls whether rewriteCandidate is executed.");
119
120// Only for testing.
121static cl::opt<bool>
122 EnablePoisonReuseGuard("enable-poison-reuse-guard", cl::init(Val: true),
123 cl::desc("Enable poison-reuse guard"));
124
125STATISTIC(NumSCEVCandidateBasisDifferences,
126 "Number of candidate-basis SCEV differences computed by SLSR");
127
128namespace {
129
130class StraightLineStrengthReduceLegacyPass : public FunctionPass {
131 const DataLayout *DL = nullptr;
132
133public:
134 static char ID;
135
136 StraightLineStrengthReduceLegacyPass() : FunctionPass(ID) {
137 initializeStraightLineStrengthReduceLegacyPassPass(
138 *PassRegistry::getPassRegistry());
139 }
140
141 void getAnalysisUsage(AnalysisUsage &AU) const override {
142 AU.addRequired<DominatorTreeWrapperPass>();
143 AU.addRequired<ScalarEvolutionWrapperPass>();
144 AU.addRequired<TargetTransformInfoWrapperPass>();
145 // We do not modify the shape of the CFG.
146 AU.setPreservesCFG();
147 }
148
149 bool doInitialization(Module &M) override {
150 DL = &M.getDataLayout();
151 return false;
152 }
153
154 bool runOnFunction(Function &F) override;
155};
156
157class StraightLineStrengthReduce {
158public:
159 StraightLineStrengthReduce(const DataLayout *DL, DominatorTree *DT,
160 ScalarEvolution *SE, TargetTransformInfo *TTI)
161 : DL(DL), DT(DT), SE(SE), TTI(TTI) {}
162
163 // SLSR candidate. Such a candidate must be in one of the forms described in
164 // the header comments.
165 struct Candidate {
166 enum Kind {
167 Invalid, // reserved for the default constructor
168 Add, // B + i * S
169 Mul, // (B + i) * S
170 GEP, // &B[..][i * S][..]
171 };
172
173 enum DKind {
174 InvalidDelta, // reserved for the default constructor
175 IndexDelta, // Delta is a constant from Index
176 BaseDelta, // Delta is a constant or variable from Base
177 StrideDelta, // Delta is a constant or variable from Stride
178 };
179
180 Candidate() = default;
181 Candidate(Kind CT, const SCEV *B, ConstantInt *Idx, Value *S,
182 Instruction *I, const SCEV *StrideSCEV)
183 : CandidateKind(CT), Base(B), Index(Idx), Stride(S), Ins(I),
184 StrideSCEV(StrideSCEV) {}
185
186 Kind CandidateKind = Invalid;
187
188 const SCEV *Base = nullptr;
189 // TODO: Swap Index and Stride's name.
190 // Note that Index and Stride of a GEP candidate do not necessarily have the
191 // same integer type. In that case, during rewriting, Stride will be
192 // sign-extended or truncated to Index's type.
193 ConstantInt *Index = nullptr;
194
195 Value *Stride = nullptr;
196
197 // The instruction this candidate corresponds to. It helps us to rewrite a
198 // candidate with respect to its immediate basis. Note that one instruction
199 // can correspond to multiple candidates depending on how you associate the
200 // expression. For instance,
201 //
202 // (a + 1) * (b + 2)
203 //
204 // can be treated as
205 //
206 // <Base: a, Index: 1, Stride: b + 2>
207 //
208 // or
209 //
210 // <Base: b, Index: 2, Stride: a + 1>
211 Instruction *Ins = nullptr;
212
213 // Points to the immediate basis of this candidate, or nullptr if we cannot
214 // find any basis for this candidate.
215 Candidate *Basis = nullptr;
216
217 DKind DeltaKind = InvalidDelta;
218
219 // Store SCEV of Stride to compute delta from different strides
220 const SCEV *StrideSCEV = nullptr;
221
222 // Points to (Y - X) that will be used to rewrite this candidate.
223 Value *Delta = nullptr;
224
225 // List of instructions we need to drop poison generating annotations from.
226 // This is used so we can defer dropping until the candidate is evaluated.
227 SmallVector<Instruction *> DropList;
228
229 /// Cost model: Evaluate the computational efficiency of the candidate.
230 ///
231 /// Efficiency levels (higher is better):
232 /// ZeroInst (5) - [Variable] or [Const]
233 /// OneInstOneVar (4) - [Variable + Const] or [Variable * Const]
234 /// OneInstTwoVar (3) - [Variable + Variable] or [Variable * Variable]
235 /// TwoInstOneVar (2) - [Const + Const * Variable]
236 /// TwoInstTwoVar (1) - [Variable + Const * Variable]
237 enum EfficiencyLevel : unsigned {
238 Unknown = 0,
239 TwoInstTwoVar = 1,
240 TwoInstOneVar = 2,
241 OneInstTwoVar = 3,
242 OneInstOneVar = 4,
243 ZeroInst = 5
244 };
245
246 static EfficiencyLevel
247 getComputationEfficiency(Kind CandidateKind, const ConstantInt *Index,
248 const Value *Stride, const SCEV *Base = nullptr) {
249 bool IsConstantBase = false;
250 bool IsZeroBase = false;
251 // When evaluating the efficiency of a rewrite, if the Base's SCEV is
252 // not available, conservatively assume the base is not constant.
253 if (auto *ConstBase = dyn_cast_or_null<SCEVConstant>(Val: Base)) {
254 IsConstantBase = true;
255 IsZeroBase = ConstBase->getValue()->isZero();
256 }
257
258 bool IsConstantStride = isa<ConstantInt>(Val: Stride);
259 bool IsZeroStride =
260 IsConstantStride && cast<ConstantInt>(Val: Stride)->isZero();
261 // All constants
262 if (IsConstantBase && IsConstantStride)
263 return ZeroInst;
264
265 // (Base + Index) * Stride
266 if (CandidateKind == Mul) {
267 if (IsZeroStride)
268 return ZeroInst;
269 if (Index->isZero())
270 return (IsConstantStride || IsConstantBase) ? OneInstOneVar
271 : OneInstTwoVar;
272
273 if (IsConstantBase)
274 return IsZeroBase && (Index->isOne() || Index->isMinusOne())
275 ? ZeroInst
276 : OneInstOneVar;
277
278 if (IsConstantStride) {
279 auto *CI = cast<ConstantInt>(Val: Stride);
280 return (CI->isOne() || CI->isMinusOne()) ? OneInstOneVar
281 : TwoInstOneVar;
282 }
283 return TwoInstTwoVar;
284 }
285
286 // Base + Index * Stride
287 assert(CandidateKind == Add || CandidateKind == GEP);
288 if (Index->isZero() || IsZeroStride)
289 return ZeroInst;
290
291 bool IsSimpleIndex = Index->isOne() || Index->isMinusOne();
292
293 if (IsConstantBase)
294 return IsZeroBase ? (IsSimpleIndex ? ZeroInst : OneInstOneVar)
295 : (IsSimpleIndex ? OneInstOneVar : TwoInstOneVar);
296
297 if (IsConstantStride)
298 return IsZeroStride ? ZeroInst : OneInstOneVar;
299
300 if (IsSimpleIndex)
301 return OneInstTwoVar;
302
303 return TwoInstTwoVar;
304 }
305
306 // Evaluate if the given delta is profitable to rewrite this candidate.
307 bool isProfitableRewrite(const Value &Delta, const DKind DeltaKind) const {
308 // This function cannot accurately evaluate the profit of whole expression
309 // with context. A candidate (B + I * S) cannot express whether this
310 // instruction needs to compute on its own (I * S), which may be shared
311 // with other candidates or may need instructions to compute.
312 // If the rewritten form has the same strength, still rewrite to
313 // (X + Delta) since it may expose more CSE opportunities on Delta, as
314 // unrolled loops usually have identical Delta for each unrolled body.
315 //
316 // Note, this function should only be used on Index Delta rewrite.
317 // Base and Stride delta need context info to evaluate the register
318 // pressure impact from variable delta.
319 return getComputationEfficiency(CandidateKind, Index, Stride, Base) <=
320 getRewriteEfficiency(Delta, DeltaKind);
321 }
322
323 // Evaluate the rewrite efficiency of this candidate with its Basis
324 EfficiencyLevel getRewriteEfficiency() const {
325 return Basis ? getRewriteEfficiency(Delta: *Delta, DeltaKind) : Unknown;
326 }
327
328 // Evaluate the rewrite efficiency of this candidate with a given delta
329 EfficiencyLevel getRewriteEfficiency(const Value &Delta,
330 const DKind DeltaKind) const {
331 switch (DeltaKind) {
332 case BaseDelta: // [X + Delta]
333 return getComputationEfficiency(
334 CandidateKind,
335 Index: ConstantInt::get(Ty: cast<IntegerType>(Val: Delta.getType()), V: 1), Stride: &Delta);
336 case StrideDelta: // [X + Index * Delta]
337 return getComputationEfficiency(CandidateKind, Index, Stride: &Delta);
338 case IndexDelta: // [X + Delta * Stride]
339 return getComputationEfficiency(CandidateKind,
340 Index: cast<ConstantInt>(Val: &Delta), Stride);
341 default:
342 return Unknown;
343 }
344 }
345
346 bool isHighEfficiency() const {
347 return getComputationEfficiency(CandidateKind, Index, Stride, Base) >=
348 OneInstOneVar;
349 }
350
351 // Verify that this candidate has valid delta components relative to the
352 // basis
353 bool hasValidDelta(const Candidate &Basis) const {
354 switch (DeltaKind) {
355 case IndexDelta:
356 // Index differs, Base and Stride must match
357 return Base == Basis.Base && StrideSCEV == Basis.StrideSCEV;
358 case StrideDelta:
359 // Stride differs, Base and Index must match
360 return Base == Basis.Base && Index == Basis.Index;
361 case BaseDelta:
362 // Base differs, Stride and Index must match
363 return StrideSCEV == Basis.StrideSCEV && Index == Basis.Index;
364 default:
365 return false;
366 }
367 }
368 };
369
370 bool runOnFunction(Function &F);
371
372private:
373 // Fetch straight-line basis for rewriting C, update C.Basis to point to it,
374 // and store the delta between C and its Basis in C.Delta.
375 void setBasisAndDeltaFor(Candidate &C);
376 // Returns whether the candidate can be folded into an addressing mode.
377 bool isFoldable(const Candidate &C, TargetTransformInfo *TTI);
378
379 // Checks whether I is in a candidate form. If so, adds all the matching forms
380 // to Candidates, and tries to find the immediate basis for each of them.
381 void allocateCandidatesAndFindBasis(Instruction *I);
382
383 // Allocate candidates and find bases for Add instructions.
384 void allocateCandidatesAndFindBasisForAdd(Instruction *I);
385
386 // Given I = LHS + RHS, factors RHS into i * S and makes (LHS + i * S) a
387 // candidate.
388 void allocateCandidatesAndFindBasisForAdd(Value *LHS, Value *RHS,
389 Instruction *I);
390 // Allocate candidates and find bases for Mul instructions.
391 void allocateCandidatesAndFindBasisForMul(Instruction *I);
392
393 // Splits LHS into Base + Index and, if succeeds, calls
394 // allocateCandidatesAndFindBasis.
395 void allocateCandidatesAndFindBasisForMul(Value *LHS, Value *RHS,
396 Instruction *I);
397
398 // Allocate candidates and find bases for GetElementPtr instructions.
399 void allocateCandidatesAndFindBasisForGEP(GetElementPtrInst *GEP);
400
401 // Adds the given form <CT, B, Idx, S> to Candidates, and finds its immediate
402 // basis.
403 void allocateCandidatesAndFindBasis(Candidate::Kind CT, const SCEV *B,
404 ConstantInt *Idx, Value *S,
405 Instruction *I);
406
407 // Rewrites candidate C with respect to Basis.
408 void rewriteCandidate(const Candidate &C);
409
410 // Emit code that computes the "bump" from Basis to C.
411 static Value *emitBump(const Candidate &Basis, const Candidate &C,
412 IRBuilder<> &Builder, const DataLayout *DL);
413
414 const DataLayout *DL = nullptr;
415 DominatorTree *DT = nullptr;
416 ScalarEvolution *SE;
417 TargetTransformInfo *TTI = nullptr;
418 std::list<Candidate> Candidates;
419
420 // Map from SCEV to instructions that represent the value,
421 // instructions are sorted in depth-first order.
422 DenseMap<const SCEV *, SmallSetVector<Instruction *, 2>> SCEVToInsts;
423
424 using SCEVUnknownSet = SmallPtrSet<const SCEVUnknown *, 4>;
425 DenseMap<const SCEV *, SCEVUnknownSet> SCEVUnknownsCache;
426
427 // Record the dependency between instructions. If C.Basis == B, we would have
428 // {B.Ins -> {C.Ins, ...}}.
429 MapVector<Instruction *, std::vector<Instruction *>> DependencyGraph;
430
431 // Map between each instruction and its possible candidates.
432 DenseMap<Instruction *, SmallVector<Candidate *, 3>> RewriteCandidates;
433
434 // All instructions that have candidates sort in topological order based on
435 // dependency graph, from roots to leaves.
436 std::vector<Instruction *> SortedCandidateInsts;
437
438 // Record all instructions that are already rewritten and will be removed
439 // later.
440 std::vector<Instruction *> DeadInstructions;
441
442 // Classify candidates against Delta kind
443 class CandidateDictTy {
444 public:
445 using CandsTy = SmallVector<Candidate *, 8>;
446 using BBToCandsTy = DenseMap<const BasicBlock *, CandsTy>;
447
448 private:
449 // Index delta Basis must have the same (Base, StrideSCEV, Inst.Type)
450 using IndexDeltaKeyTy = std::tuple<const SCEV *, const SCEV *, Type *>;
451 DenseMap<IndexDeltaKeyTy, BBToCandsTy> IndexDeltaCandidates;
452
453 // Base delta Basis must have the same (StrideSCEV, Index, Inst.Type)
454 using BaseDeltaKeyTy = std::tuple<const SCEV *, ConstantInt *, Type *>;
455 DenseMap<BaseDeltaKeyTy, BBToCandsTy> BaseDeltaCandidates;
456
457 // Stride delta Basis must have the same (Base, Index, Inst.Type)
458 using StrideDeltaKeyTy = std::tuple<const SCEV *, ConstantInt *, Type *>;
459 DenseMap<StrideDeltaKeyTy, BBToCandsTy> StrideDeltaCandidates;
460
461 public:
462 // TODO: Disable index delta on GEP after we completely move
463 // from typed GEP to PtrAdd.
464 const BBToCandsTy *getCandidatesWithDeltaKind(const Candidate &C,
465 Candidate::DKind K) const {
466 assert(K != Candidate::InvalidDelta);
467 if (K == Candidate::IndexDelta) {
468 IndexDeltaKeyTy IndexDeltaKey(C.Base, C.StrideSCEV, C.Ins->getType());
469 auto It = IndexDeltaCandidates.find(Val: IndexDeltaKey);
470 if (It != IndexDeltaCandidates.end())
471 return &It->second;
472 } else if (K == Candidate::BaseDelta) {
473 BaseDeltaKeyTy BaseDeltaKey(C.StrideSCEV, C.Index, C.Ins->getType());
474 auto It = BaseDeltaCandidates.find(Val: BaseDeltaKey);
475 if (It != BaseDeltaCandidates.end())
476 return &It->second;
477 } else {
478 assert(K == Candidate::StrideDelta);
479 StrideDeltaKeyTy StrideDeltaKey(C.Base, C.Index, C.Ins->getType());
480 auto It = StrideDeltaCandidates.find(Val: StrideDeltaKey);
481 if (It != StrideDeltaCandidates.end())
482 return &It->second;
483 }
484 return nullptr;
485 }
486
487 // Pointers to C must remain valid until CandidateDict is cleared.
488 void add(Candidate &C) {
489 Type *ValueType = C.Ins->getType();
490 BasicBlock *BB = C.Ins->getParent();
491 IndexDeltaKeyTy IndexDeltaKey(C.Base, C.StrideSCEV, ValueType);
492 BaseDeltaKeyTy BaseDeltaKey(C.StrideSCEV, C.Index, ValueType);
493 StrideDeltaKeyTy StrideDeltaKey(C.Base, C.Index, ValueType);
494 IndexDeltaCandidates[IndexDeltaKey][BB].push_back(Elt: &C);
495 BaseDeltaCandidates[BaseDeltaKey][BB].push_back(Elt: &C);
496 StrideDeltaCandidates[StrideDeltaKey][BB].push_back(Elt: &C);
497 }
498 // Remove all mappings from set
499 void clear() {
500 IndexDeltaCandidates.clear();
501 BaseDeltaCandidates.clear();
502 StrideDeltaCandidates.clear();
503 }
504 } CandidateDict;
505
506 const SCEV *getAndRecordSCEV(Value *V) {
507 auto *S = SE->getSCEV(V);
508 if (isa<Instruction>(Val: V) && !(isa<SCEVCouldNotCompute>(Val: S) ||
509 isa<SCEVUnknown>(Val: S) || isa<SCEVConstant>(Val: S)))
510 SCEVToInsts[S].insert(X: cast<Instruction>(Val: V));
511
512 return S;
513 }
514
515 bool candidatePredicate(Candidate *Basis, Candidate &C, Candidate::DKind K);
516
517 bool hasSameSCEVUnknowns(const SCEV *A, const SCEV *B);
518
519 bool searchFrom(const CandidateDictTy::BBToCandsTy &BBToCands, Candidate &C,
520 Candidate::DKind K);
521
522 // Get the nearest instruction before CI that represents the value of S,
523 // return nullptr if no instruction is associated with S or S is not a
524 // reusable expression.
525 Value *getNearestValueOfSCEV(const SCEV *S, const Instruction *CI) const {
526 if (isa<SCEVCouldNotCompute>(Val: S))
527 return nullptr;
528
529 if (auto *SU = dyn_cast<SCEVUnknown>(Val: S))
530 return SU->getValue();
531 if (auto *SC = dyn_cast<SCEVConstant>(Val: S))
532 return SC->getValue();
533
534 auto It = SCEVToInsts.find(Val: S);
535 if (It == SCEVToInsts.end())
536 return nullptr;
537
538 // Instructions are sorted in depth-first order, so search for the nearest
539 // instruction by walking the list in reverse order.
540 for (Instruction *I : reverse(C: It->second))
541 if (DT->dominates(Def: I, User: CI))
542 return I;
543
544 return nullptr;
545 }
546
547 struct DeltaInfo {
548 Candidate *Cand;
549 Candidate::DKind DeltaKind;
550 Value *Delta;
551
552 DeltaInfo()
553 : Cand(nullptr), DeltaKind(Candidate::InvalidDelta), Delta(nullptr) {}
554 DeltaInfo(Candidate *Cand, Candidate::DKind DeltaKind, Value *Delta)
555 : Cand(Cand), DeltaKind(DeltaKind), Delta(Delta) {}
556 operator bool() const { return Cand != nullptr; }
557 };
558
559 friend raw_ostream &operator<<(raw_ostream &OS, const DeltaInfo &DI);
560
561 DeltaInfo compressPath(Candidate &C, Candidate *Basis) const;
562
563 Candidate *pickRewriteCandidate(Instruction *I) const;
564 void sortCandidateInstructions();
565 Value *getDelta(const Candidate &C, const Candidate &Basis,
566 Candidate::DKind K) const;
567 static bool isSimilar(Candidate &C, Candidate &Basis, Candidate::DKind K);
568
569 // Add Basis -> C in DependencyGraph and propagate
570 // C.Stride and C.Delta's dependency to C
571 void addDependency(Candidate &C, Candidate *Basis) {
572 if (Basis)
573 DependencyGraph[Basis->Ins].emplace_back(args&: C.Ins);
574
575 // If any candidate of Inst has a basis, then Inst will be rewritten,
576 // C must be rewritten after rewriting Inst, so we need to propagate
577 // the dependency to C
578 auto PropagateDependency = [&](Instruction *Inst) {
579 if (auto CandsIt = RewriteCandidates.find(Val: Inst);
580 CandsIt != RewriteCandidates.end() &&
581 llvm::any_of(Range&: CandsIt->second,
582 P: [](Candidate *Cand) { return Cand->Basis; }))
583 DependencyGraph[Inst].emplace_back(args&: C.Ins);
584 };
585
586 // If C has a variable delta and the delta is a candidate,
587 // propagate its dependency to C
588 if (auto *DeltaInst = dyn_cast_or_null<Instruction>(Val: C.Delta))
589 PropagateDependency(DeltaInst);
590
591 // If the stride is a candidate, propagate its dependency to C
592 if (auto *StrideInst = dyn_cast<Instruction>(Val: C.Stride))
593 PropagateDependency(StrideInst);
594 };
595};
596
597inline raw_ostream &operator<<(raw_ostream &OS,
598 const StraightLineStrengthReduce::Candidate &C) {
599 OS << "Ins: " << *C.Ins << "\n Base: " << *C.Base
600 << "\n Index: " << *C.Index << "\n Stride: " << *C.Stride
601 << "\n StrideSCEV: " << *C.StrideSCEV;
602 if (C.Basis)
603 OS << "\n Delta: " << *C.Delta << "\n Basis: \n [ " << *C.Basis << " ]";
604 return OS;
605}
606
607[[maybe_unused]] LLVM_DUMP_METHOD inline raw_ostream &
608operator<<(raw_ostream &OS, const StraightLineStrengthReduce::DeltaInfo &DI) {
609 OS << "Cand: " << *DI.Cand << "\n";
610 OS << "Delta Kind: ";
611 switch (DI.DeltaKind) {
612 case StraightLineStrengthReduce::Candidate::IndexDelta:
613 OS << "Index";
614 break;
615 case StraightLineStrengthReduce::Candidate::BaseDelta:
616 OS << "Base";
617 break;
618 case StraightLineStrengthReduce::Candidate::StrideDelta:
619 OS << "Stride";
620 break;
621 default:
622 break;
623 }
624 OS << "\nDelta: " << *DI.Delta;
625 return OS;
626}
627
628} // end anonymous namespace
629
630char StraightLineStrengthReduceLegacyPass::ID = 0;
631
632INITIALIZE_PASS_BEGIN(StraightLineStrengthReduceLegacyPass, "slsr",
633 "Straight line strength reduction", false, false)
634INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
635INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
636INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
637INITIALIZE_PASS_END(StraightLineStrengthReduceLegacyPass, "slsr",
638 "Straight line strength reduction", false, false)
639
640FunctionPass *llvm::createStraightLineStrengthReducePass() {
641 return new StraightLineStrengthReduceLegacyPass();
642}
643
644// A helper function that unifies the bitwidth of A and B.
645static void unifyBitWidth(APInt &A, APInt &B) {
646 if (A.getBitWidth() < B.getBitWidth())
647 A = A.sext(width: B.getBitWidth());
648 else if (A.getBitWidth() > B.getBitWidth())
649 B = B.sext(width: A.getBitWidth());
650}
651
652// Whether sign-extending V to a wider type may not distribute over arithmetic,
653// i.e. the narrow value does not sign-extend linearly. Only an add/sub/mul/shl
654// carrying the `nsw` flag is known to sign-extend linearly; anything else is
655// treated conservatively as possibly wrapping. This notably covers
656// `xor X, signmask`, which merely flips the sign bit but ScalarEvolution models
657// as a non-nsw `add X, signmask` (so sext does not distribute over it).
658static bool mayHaveSignedWrap(const Value *V) {
659 // OverflowingBinaryOperator covers exactly add/sub/mul/shl.
660 const auto *OBO = dyn_cast<OverflowingBinaryOperator>(Val: V);
661 return !OBO || !OBO->hasNoSignedWrap();
662}
663
664// True when the GEP index is narrower than the index width, i.e. it is
665// implicitly sign-extended to the index width (not the pointer width) of the
666// address space before the address computation. A value already at or wider
667// than the index width is not sign-extended (it is used as-is or truncated), so
668// it cannot trigger the non-distributing-sext problem.
669static bool isSignExtendedGepIndex(const Value *Idx, GetElementPtrInst *GEP,
670 const DataLayout *DL) {
671 return Idx->getType()->getIntegerBitWidth() <
672 DL->getIndexSizeInBits(AS: GEP->getAddressSpace());
673}
674
675// A narrow GEP index is sign-extended to the index width before the address
676// computation. SLSR's Stride-delta rewrite turns two such GEPs into
677// Basis + Index * (Sc - Sb), so the stride difference Sc - Sb is reconstructed
678// in the sign-extended domain. This requires sext(Sc) == sext(Sb) +
679// sext(Delta).
680//
681// This screens the rewritten candidate's stride Sc = Sb + Delta: if Sc is
682// computed by a possibly-wrapping op, sext(Sc) does not equal sext(Sb) +
683// sext(Delta) and the rewrite would produce a wrong pointer.
684static bool isSafeToFactorGepIndex(const Value *Idx, GetElementPtrInst *GEP,
685 const DataLayout *DL) {
686 return !isSignExtendedGepIndex(Idx, GEP, DL) || !mayHaveSignedWrap(V: Idx);
687}
688
689Value *StraightLineStrengthReduce::getDelta(const Candidate &C,
690 const Candidate &Basis,
691 Candidate::DKind K) const {
692 if (K == Candidate::IndexDelta) {
693 APInt Idx = C.Index->getValue();
694 APInt BasisIdx = Basis.Index->getValue();
695 unifyBitWidth(A&: Idx, B&: BasisIdx);
696 APInt IndexDelta = Idx - BasisIdx;
697 IntegerType *DeltaType =
698 IntegerType::get(C&: C.Ins->getContext(), NumBits: IndexDelta.getBitWidth());
699 return ConstantInt::get(Ty: DeltaType, V: IndexDelta);
700 } else if (K == Candidate::BaseDelta || K == Candidate::StrideDelta) {
701 const SCEV *BasisPart =
702 (K == Candidate::BaseDelta) ? Basis.Base : Basis.StrideSCEV;
703 const SCEV *CandPart = (K == Candidate::BaseDelta) ? C.Base : C.StrideSCEV;
704 ++NumSCEVCandidateBasisDifferences;
705 const SCEV *Diff = SE->getMinusSCEV(LHS: CandPart, RHS: BasisPart);
706 return getNearestValueOfSCEV(S: Diff, CI: C.Ins);
707 }
708 return nullptr;
709}
710
711bool StraightLineStrengthReduce::isSimilar(Candidate &C, Candidate &Basis,
712 Candidate::DKind K) {
713 bool SameType = false;
714 switch (K) {
715 case Candidate::StrideDelta:
716 SameType = C.StrideSCEV->getType() == Basis.StrideSCEV->getType();
717 break;
718 case Candidate::BaseDelta:
719 SameType = C.Base->getType() == Basis.Base->getType();
720 break;
721 case Candidate::IndexDelta:
722 SameType = true;
723 break;
724 default:;
725 }
726 return SameType && Basis.Ins != C.Ins &&
727 Basis.CandidateKind == C.CandidateKind;
728}
729
730bool StraightLineStrengthReduce::hasSameSCEVUnknowns(const SCEV *A,
731 const SCEV *B) {
732 auto CacheUnknowns = [&](const SCEV *Root) {
733 auto [It, Inserted] = SCEVUnknownsCache.try_emplace(Key: Root);
734 if (!Inserted)
735 return;
736
737 struct Collector {
738 SCEVUnknownSet &Unknowns;
739
740 bool follow(const SCEV *S) {
741 if (auto *Unknown = dyn_cast<SCEVUnknown>(Val: S))
742 Unknowns.insert(Ptr: Unknown);
743 return true;
744 }
745 bool isDone() const { return false; }
746 } C{.Unknowns: It->second};
747 visitAll(Root, Visitor&: C);
748 };
749 CacheUnknowns(A);
750 CacheUnknowns(B);
751
752 return SCEVUnknownsCache.find(Val: A)->second == SCEVUnknownsCache.find(Val: B)->second;
753}
754
755// Try to find a Delta that C can reuse Basis to rewrite.
756// Set C.Delta, C.Basis, and C.DeltaKind if found.
757// Return true if found a constant delta.
758// Return false if not found or the delta is not a constant.
759bool StraightLineStrengthReduce::candidatePredicate(Candidate *Basis,
760 Candidate &C,
761 Candidate::DKind K) {
762 if (!isSimilar(C, Basis&: *Basis, K))
763 return false;
764
765 // Once a reusable delta is found, only a constant delta can improve it.
766 // Different symbolic leaves cannot cancel to a constant, so such a basis
767 // cannot improve C. Skip it and continue searching older candidates.
768 if (C.Delta && K != Candidate::IndexDelta) {
769 const SCEV *CandidateSCEV =
770 K == Candidate::BaseDelta ? C.Base : C.StrideSCEV;
771 const SCEV *BasisSCEV =
772 K == Candidate::BaseDelta ? Basis->Base : Basis->StrideSCEV;
773 if (!hasSameSCEVUnknowns(A: CandidateSCEV, B: BasisSCEV))
774 return false;
775 }
776
777 assert(DT->dominates(Basis->Ins, C.Ins));
778 Value *Delta = getDelta(C, Basis: *Basis, K);
779 if (!Delta)
780 return false;
781
782 // For a GEP Stride-delta rewrite g2 = g1 + Index * Delta, the addresses are
783 // computed from the sign-extended strides, so this requires
784 // sext(Sc) == sext(Sb) + sext(Delta).
785 //
786 // The rewritten candidate's stride Sc = Sb + Delta is already screened
787 // broadly at allocation time (allocateCandidatesAndFindBasis): a wrapping Sc
788 // breaks the identity for any Delta. The basis's stride Sb = Sc - Delta only
789 // needs screening when Delta folds to a *constant*: then sext(Sb) + C can
790 // differ from sext(Sc) if Sb wraps. For a *variable* Delta the basis may wrap
791 // and still be sound, because the candidate stride carries the no-wrap
792 // guarantee (e.g. Sc is an `add nsw`, as in stride_var); rejecting it would
793 // pessimize those.
794 if (K == Candidate::StrideDelta && C.CandidateKind == Candidate::GEP &&
795 isa<ConstantInt>(Val: Delta)) {
796 auto *BasisGEP = cast<GetElementPtrInst>(Val: Basis->Ins);
797 if (!isSafeToFactorGepIndex(Idx: Basis->Stride, GEP: BasisGEP, DL))
798 return false;
799 }
800
801 // IndexDelta rewrite is not always profitable, e.g.,
802 // X = B + 8 * S
803 // Y = B + S,
804 // rewriting Y to X - 7 * S is probably a bad idea.
805 // So, we need to check if the rewrite form's computation efficiency
806 // is better than the original form.
807 if (K == Candidate::IndexDelta &&
808 !C.isProfitableRewrite(Delta: *Delta, DeltaKind: Candidate::IndexDelta))
809 return false;
810
811 // If there is a Delta that we can reuse Basis to rewrite C, clean up
812 // previously collected poison generating instructions.
813 for (Instruction *I : Basis->DropList)
814 I->dropPoisonGeneratingAnnotations();
815
816 // Record delta if none has been found yet, or the new delta is
817 // a constant that is better than the existing delta.
818 if (!C.Delta || isa<ConstantInt>(Val: Delta)) {
819 C.Delta = Delta;
820 C.Basis = Basis;
821 C.DeltaKind = K;
822 }
823 return isa<ConstantInt>(Val: C.Delta);
824}
825
826// return true if find a Basis with constant delta and stop searching,
827// return false if did not find a Basis or the delta is not a constant
828// and continue searching for a Basis with constant delta
829bool StraightLineStrengthReduce::searchFrom(
830 const CandidateDictTy::BBToCandsTy &BBToCands, Candidate &C,
831 Candidate::DKind K) {
832
833 // Stride delta rewrite on Mul form is usually non-profitable, and Base
834 // delta rewrite sometimes is profitable, so we do not support them on Mul.
835 if (C.CandidateKind == Candidate::Mul && K != Candidate::IndexDelta)
836 return false;
837
838 // Search dominating candidates by walking the immediate-dominator chain
839 // from the candidate's defining block upward. Visiting blocks in this
840 // order ensures we prefer the closest dominating basis.
841 const BasicBlock *BB = C.Ins->getParent();
842 while (BB) {
843 auto It = BBToCands.find(Val: BB);
844 if (It != BBToCands.end())
845 for (Candidate *Basis : reverse(C: It->second))
846 if (candidatePredicate(Basis, C, K))
847 return true;
848
849 const DomTreeNode *Node = DT->getNode(BB);
850 if (!Node)
851 break;
852 Node = Node->getIDom();
853 BB = Node ? Node->getBlock() : nullptr;
854 }
855 return false;
856}
857
858void StraightLineStrengthReduce::setBasisAndDeltaFor(Candidate &C) {
859 if (const auto *BaseDeltaCandidates =
860 CandidateDict.getCandidatesWithDeltaKind(C, K: Candidate::BaseDelta))
861 if (searchFrom(BBToCands: *BaseDeltaCandidates, C, K: Candidate::BaseDelta)) {
862 LLVM_DEBUG(dbgs() << "Found delta from Base: " << *C.Delta << "\n");
863 return;
864 }
865
866 if (const auto *StrideDeltaCandidates =
867 CandidateDict.getCandidatesWithDeltaKind(C, K: Candidate::StrideDelta))
868 if (searchFrom(BBToCands: *StrideDeltaCandidates, C, K: Candidate::StrideDelta)) {
869 LLVM_DEBUG(dbgs() << "Found delta from Stride: " << *C.Delta << "\n");
870 return;
871 }
872
873 if (const auto *IndexDeltaCandidates =
874 CandidateDict.getCandidatesWithDeltaKind(C, K: Candidate::IndexDelta))
875 if (searchFrom(BBToCands: *IndexDeltaCandidates, C, K: Candidate::IndexDelta)) {
876 LLVM_DEBUG(dbgs() << "Found delta from Index: " << *C.Delta << "\n");
877 return;
878 }
879
880 // If we did not find a constant delta, we might have found a variable delta
881 if (C.Delta) {
882 LLVM_DEBUG({
883 dbgs() << "Found delta from ";
884 if (C.DeltaKind == Candidate::BaseDelta)
885 dbgs() << "Base: ";
886 else
887 dbgs() << "Stride: ";
888 dbgs() << *C.Delta << "\n";
889 });
890 assert(C.DeltaKind != Candidate::InvalidDelta && C.Basis);
891 }
892}
893
894// Compress the path from `Basis` to the deepest Basis in the Basis chain
895// to avoid non-profitable data dependency and improve ILP.
896// X = A + 1
897// Y = X + 1
898// Z = Y + 1
899// ->
900// X = A + 1
901// Y = A + 2
902// Z = A + 3
903// Return the delta info for C aginst the new Basis
904auto StraightLineStrengthReduce::compressPath(Candidate &C,
905 Candidate *Basis) const
906 -> DeltaInfo {
907 if (!Basis || !Basis->Basis || C.CandidateKind == Candidate::Mul)
908 return {};
909 Candidate *Root = Basis;
910 Value *NewDelta = nullptr;
911 auto NewKind = Candidate::InvalidDelta;
912
913 while (Root->Basis) {
914 Candidate *NextRoot = Root->Basis;
915 if (C.Base == NextRoot->Base && C.StrideSCEV == NextRoot->StrideSCEV &&
916 isSimilar(C, Basis&: *NextRoot, K: Candidate::IndexDelta)) {
917 ConstantInt *CI =
918 cast<ConstantInt>(Val: getDelta(C, Basis: *NextRoot, K: Candidate::IndexDelta));
919 if (CI->isZero() || CI->isOne() || isa<SCEVConstant>(Val: C.StrideSCEV)) {
920 Root = NextRoot;
921 NewKind = Candidate::IndexDelta;
922 NewDelta = CI;
923 continue;
924 }
925 }
926
927 const SCEV *CandPart = nullptr;
928 const SCEV *BasisPart = nullptr;
929 auto CurrKind = Candidate::InvalidDelta;
930 if (C.Base == NextRoot->Base && C.Index == NextRoot->Index) {
931 CandPart = C.StrideSCEV;
932 BasisPart = NextRoot->StrideSCEV;
933 CurrKind = Candidate::StrideDelta;
934 } else if (C.StrideSCEV == NextRoot->StrideSCEV &&
935 C.Index == NextRoot->Index) {
936 CandPart = C.Base;
937 BasisPart = NextRoot->Base;
938 CurrKind = Candidate::BaseDelta;
939 } else
940 break;
941
942 assert(CandPart && BasisPart);
943 if (!isSimilar(C, Basis&: *NextRoot, K: CurrKind))
944 break;
945
946 // Path compression folds a constant Stride-delta directly against the
947 // deeper basis NextRoot, bypassing candidatePredicate's wrap guard. With a
948 // constant delta sext(Sb) + C can differ from sext(Sc) if the deeper
949 // basis's stride wraps, so do not compress past such a basis (mirrors the
950 // check in candidatePredicate).
951 if (CurrKind == Candidate::StrideDelta &&
952 C.CandidateKind == Candidate::GEP &&
953 !isSafeToFactorGepIndex(Idx: NextRoot->Stride,
954 GEP: cast<GetElementPtrInst>(Val: NextRoot->Ins), DL))
955 break;
956
957 ++NumSCEVCandidateBasisDifferences;
958 if (auto DeltaVal =
959 dyn_cast<SCEVConstant>(Val: SE->getMinusSCEV(LHS: CandPart, RHS: BasisPart))) {
960 Root = NextRoot;
961 NewDelta = DeltaVal->getValue();
962 NewKind = CurrKind;
963 } else
964 break;
965 }
966
967 if (Root != Basis) {
968 assert(NewKind != Candidate::InvalidDelta && NewDelta);
969 LLVM_DEBUG(dbgs() << "Found new Basis with " << *NewDelta
970 << " from path compression.\n");
971 return {Root, NewKind, NewDelta};
972 }
973
974 return {};
975}
976
977// Topologically sort candidate instructions based on their relationship in
978// dependency graph.
979void StraightLineStrengthReduce::sortCandidateInstructions() {
980 SortedCandidateInsts.clear();
981 // An instruction may have multiple candidates that get different Basis
982 // instructions, and each candidate can get dependencies from Basis and
983 // Stride when Stride will also be rewritten by SLSR. Hence, an instruction
984 // may have multiple dependencies. Use InDegree to ensure all dependencies
985 // processed before processing itself.
986 DenseMap<Instruction *, int> InDegree;
987 for (auto &KV : DependencyGraph) {
988 InDegree.try_emplace(Key: KV.first, Args: 0);
989
990 for (auto *Child : KV.second) {
991 InDegree[Child]++;
992 }
993 }
994 std::queue<Instruction *> WorkList;
995 DenseSet<Instruction *> Visited;
996
997 for (auto &KV : DependencyGraph)
998 if (InDegree[KV.first] == 0)
999 WorkList.push(x: KV.first);
1000
1001 while (!WorkList.empty()) {
1002 Instruction *I = WorkList.front();
1003 WorkList.pop();
1004 if (!Visited.insert(V: I).second)
1005 continue;
1006
1007 SortedCandidateInsts.push_back(x: I);
1008
1009 for (auto *Next : DependencyGraph[I]) {
1010 auto &Degree = InDegree[Next];
1011 if (--Degree == 0)
1012 WorkList.push(x: Next);
1013 }
1014 }
1015
1016 assert(SortedCandidateInsts.size() == DependencyGraph.size() &&
1017 "Dependency graph should not have cycles");
1018}
1019
1020auto StraightLineStrengthReduce::pickRewriteCandidate(Instruction *I) const
1021 -> Candidate * {
1022 // Return the candidate of instruction I that has the highest profit.
1023 auto It = RewriteCandidates.find(Val: I);
1024 if (It == RewriteCandidates.end())
1025 return nullptr;
1026
1027 Candidate *BestC = nullptr;
1028 auto BestEfficiency = Candidate::Unknown;
1029 for (Candidate *C : reverse(C: It->second))
1030 if (C->Basis) {
1031 auto Efficiency = C->getRewriteEfficiency();
1032 if (Efficiency > BestEfficiency) {
1033 BestEfficiency = Efficiency;
1034 BestC = C;
1035 }
1036 }
1037
1038 return BestC;
1039}
1040
1041static bool isGEPFoldable(GetElementPtrInst *GEP,
1042 const TargetTransformInfo *TTI) {
1043 SmallVector<const Value *, 4> Indices(GEP->indices());
1044 return TTI->getGEPCost(
1045 PointeeType: GEP->getSourceElementType(), Ptr: GEP->getPointerOperand(), Operands: Indices,
1046 /*CostKind*/ TTI::TargetCostKind::TCK_SizeAndLatency) ==
1047 TargetTransformInfo::TCC_Free;
1048}
1049
1050// Returns whether (Base + Index * Stride) can be folded to an addressing mode.
1051static bool isAddFoldable(const SCEV *Base, ConstantInt *Index, Value *Stride,
1052 TargetTransformInfo *TTI) {
1053 // Index->getSExtValue() may crash if Index is wider than 64-bit.
1054 return Index->getBitWidth() <= 64 &&
1055 TTI->isLegalAddressingMode(Ty: Base->getType(), BaseGV: nullptr, BaseOffset: 0, HasBaseReg: true,
1056 Scale: Index->getSExtValue(), AddrSpace: UnknownAddressSpace);
1057}
1058
1059bool StraightLineStrengthReduce::isFoldable(const Candidate &C,
1060 TargetTransformInfo *TTI) {
1061 if (C.CandidateKind == Candidate::Add)
1062 return isAddFoldable(Base: C.Base, Index: C.Index, Stride: C.Stride, TTI);
1063 if (C.CandidateKind == Candidate::GEP)
1064 return isGEPFoldable(GEP: cast<GetElementPtrInst>(Val: C.Ins), TTI);
1065 return false;
1066}
1067
1068void StraightLineStrengthReduce::allocateCandidatesAndFindBasis(
1069 Candidate::Kind CT, const SCEV *B, ConstantInt *Idx, Value *S,
1070 Instruction *I) {
1071 bool IsSafe = CT != Candidate::GEP ||
1072 isSafeToFactorGepIndex(Idx: S, GEP: cast<GetElementPtrInst>(Val: I), DL);
1073 // Record the SCEV of S that we may use it as a variable delta.
1074 // Ensure that we rewrite C with a existing IR that reproduces delta value.
1075
1076 Candidate C(CT, B, Idx, S, I, getAndRecordSCEV(V: S));
1077 // If we can fold I into an addressing mode, computing I is likely free or
1078 // takes only one instruction. So, we don't need to analyze or rewrite it.
1079 //
1080 // Currently, this algorithm can at best optimize complex computations into
1081 // a `variable +/* constant` form. However, some targets have stricter
1082 // constraints on the their addressing mode.
1083 // For example, a `variable + constant` can only be folded to an addressing
1084 // mode if the constant falls within a certain range.
1085 // So, we also check if the instruction is already high efficient enough
1086 // for the strength reduction algorithm.
1087 if (IsSafe && !isFoldable(C, TTI) && !C.isHighEfficiency()) {
1088 setBasisAndDeltaFor(C);
1089
1090 // Compress unnecessary rewrite to improve ILP
1091 if (auto Res = compressPath(C, Basis: C.Basis)) {
1092 C.Basis = Res.Cand;
1093 C.DeltaKind = Res.DeltaKind;
1094 C.Delta = Res.Delta;
1095 }
1096 }
1097 // Regardless of whether we find a basis for C, we need to push C to the
1098 // candidate list so that it can be the basis of other candidates.
1099 LLVM_DEBUG(dbgs() << "Allocated Candidate: " << C << "\n");
1100 Candidates.push_back(x: C);
1101 RewriteCandidates[C.Ins].push_back(Elt: &Candidates.back());
1102 // Only add to the dict if this instruction is safe to reuse as a basis. By
1103 // doing this early we avoid calling canReuseInstruction repeatedly for the
1104 // same instruction. The DropList is stored on the Candidate so
1105 // candidatePredicate can drop the flags when a rewrite is being done.
1106 if (!EnablePoisonReuseGuard ||
1107 SE->canReuseInstruction(S: SE->getSCEV(V: I), I, DropPoisonGeneratingInsts&: Candidates.back().DropList)) {
1108 CandidateDict.add(C&: Candidates.back());
1109 }
1110}
1111
1112void StraightLineStrengthReduce::allocateCandidatesAndFindBasis(
1113 Instruction *I) {
1114 switch (I->getOpcode()) {
1115 case Instruction::Add:
1116 allocateCandidatesAndFindBasisForAdd(I);
1117 break;
1118 case Instruction::Mul:
1119 allocateCandidatesAndFindBasisForMul(I);
1120 break;
1121 case Instruction::GetElementPtr:
1122 allocateCandidatesAndFindBasisForGEP(GEP: cast<GetElementPtrInst>(Val: I));
1123 break;
1124 }
1125}
1126
1127void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForAdd(
1128 Instruction *I) {
1129 // Try matching B + i * S.
1130 if (!isa<IntegerType>(Val: I->getType()))
1131 return;
1132
1133 assert(I->getNumOperands() == 2 && "isn't I an add?");
1134 Value *LHS = I->getOperand(i: 0), *RHS = I->getOperand(i: 1);
1135 allocateCandidatesAndFindBasisForAdd(LHS, RHS, I);
1136 if (LHS != RHS)
1137 allocateCandidatesAndFindBasisForAdd(LHS: RHS, RHS: LHS, I);
1138}
1139
1140void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForAdd(
1141 Value *LHS, Value *RHS, Instruction *I) {
1142 Value *S = nullptr;
1143 ConstantInt *Idx = nullptr;
1144 if (match(V: RHS, P: m_Mul(L: m_Value(V&: S), R: m_ConstantInt(CI&: Idx)))) {
1145 // I = LHS + RHS = LHS + Idx * S
1146 allocateCandidatesAndFindBasis(CT: Candidate::Add, B: SE->getSCEV(V: LHS), Idx, S, I);
1147 } else if (match(V: RHS, P: m_Shl(L: m_Value(V&: S), R: m_ConstantInt(CI&: Idx)))) {
1148 // I = LHS + RHS = LHS + (S << Idx) = LHS + S * (1 << Idx)
1149 APInt One(Idx->getBitWidth(), 1);
1150 Idx = ConstantInt::get(Context&: Idx->getContext(), V: One << Idx->getValue());
1151 allocateCandidatesAndFindBasis(CT: Candidate::Add, B: SE->getSCEV(V: LHS), Idx, S, I);
1152 } else {
1153 // At least, I = LHS + 1 * RHS
1154 ConstantInt *One = ConstantInt::get(Ty: cast<IntegerType>(Val: I->getType()), V: 1);
1155 allocateCandidatesAndFindBasis(CT: Candidate::Add, B: SE->getSCEV(V: LHS), Idx: One, S: RHS,
1156 I);
1157 }
1158}
1159
1160// Returns true if A matches B + C where C is constant.
1161static bool matchesAdd(Value *A, Value *&B, ConstantInt *&C) {
1162 return match(V: A, P: m_c_Add(L: m_Value(V&: B), R: m_ConstantInt(CI&: C)));
1163}
1164
1165// Returns true if A matches B | C where C is constant.
1166static bool matchesOr(Value *A, Value *&B, ConstantInt *&C) {
1167 return match(V: A, P: m_c_Or(L: m_Value(V&: B), R: m_ConstantInt(CI&: C)));
1168}
1169
1170void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForMul(
1171 Value *LHS, Value *RHS, Instruction *I) {
1172 Value *B = nullptr;
1173 ConstantInt *Idx = nullptr;
1174 if (matchesAdd(A: LHS, B, C&: Idx)) {
1175 // If LHS is in the form of "Base + Index", then I is in the form of
1176 // "(Base + Index) * RHS".
1177 allocateCandidatesAndFindBasis(CT: Candidate::Mul, B: SE->getSCEV(V: B), Idx, S: RHS, I);
1178 } else if (matchesOr(A: LHS, B, C&: Idx) && haveNoCommonBitsSet(LHSCache: B, RHSCache: Idx, SQ: *DL)) {
1179 // If LHS is in the form of "Base | Index" and Base and Index have no common
1180 // bits set, then
1181 // Base | Index = Base + Index
1182 // and I is thus in the form of "(Base + Index) * RHS".
1183 allocateCandidatesAndFindBasis(CT: Candidate::Mul, B: SE->getSCEV(V: B), Idx, S: RHS, I);
1184 } else {
1185 // Otherwise, at least try the form (LHS + 0) * RHS.
1186 ConstantInt *Zero = ConstantInt::get(Ty: cast<IntegerType>(Val: I->getType()), V: 0);
1187 allocateCandidatesAndFindBasis(CT: Candidate::Mul, B: SE->getSCEV(V: LHS), Idx: Zero, S: RHS,
1188 I);
1189 }
1190}
1191
1192void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForMul(
1193 Instruction *I) {
1194 // Try matching (B + i) * S.
1195 // TODO: we could extend SLSR to float and vector types.
1196 if (!isa<IntegerType>(Val: I->getType()))
1197 return;
1198
1199 assert(I->getNumOperands() == 2 && "isn't I a mul?");
1200 Value *LHS = I->getOperand(i: 0), *RHS = I->getOperand(i: 1);
1201 allocateCandidatesAndFindBasisForMul(LHS, RHS, I);
1202 if (LHS != RHS) {
1203 // Symmetrically, try to split RHS to Base + Index.
1204 allocateCandidatesAndFindBasisForMul(LHS: RHS, RHS: LHS, I);
1205 }
1206}
1207
1208void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForGEP(
1209 GetElementPtrInst *GEP) {
1210 // TODO: handle vector GEPs
1211 if (GEP->getType()->isVectorTy())
1212 return;
1213
1214 SmallVector<SCEVUse, 4> IndexExprs;
1215 for (Use &Idx : GEP->indices())
1216 IndexExprs.push_back(Elt: SE->getSCEV(V: Idx));
1217
1218 gep_type_iterator GTI = gep_type_begin(GEP);
1219 for (unsigned I = 1, E = GEP->getNumOperands(); I != E; ++I, ++GTI) {
1220 if (GTI.isStruct())
1221 continue;
1222
1223 SCEVUse OrigIndexExpr = IndexExprs[I - 1];
1224 IndexExprs[I - 1] = SE->getZero(Ty: OrigIndexExpr.getPointer()->getType());
1225
1226 // The base of this candidate is GEP's base plus the offsets of all
1227 // indices except this current one.
1228 SCEVUse BaseExpr = SE->getGEPExpr(GEP: cast<GEPOperator>(Val: GEP), IndexExprs);
1229 Value *ArrayIdx = GEP->getOperand(i_nocapture: I);
1230 uint64_t ElementSize = GTI.getSequentialElementStride(DL: *DL);
1231 IntegerType *PtrIdxTy = cast<IntegerType>(Val: DL->getIndexType(PtrTy: GEP->getType()));
1232 // If the element size overflows the type, truncate.
1233 ConstantInt *ElementSizeIdx =
1234 ConstantInt::getSigned(Ty: PtrIdxTy, V: ElementSize, /*ImplicitTrunc=*/true);
1235 if (ArrayIdx->getType()->getIntegerBitWidth() <=
1236 DL->getIndexSizeInBits(AS: GEP->getAddressSpace())) {
1237 // Skip factoring if ArrayIdx is wider than the index size, because
1238 // ArrayIdx is implicitly truncated to the index size.
1239 allocateCandidatesAndFindBasis(CT: Candidate::GEP, B: BaseExpr, Idx: ElementSizeIdx,
1240 S: ArrayIdx, I: GEP);
1241 }
1242 // When ArrayIdx is the sext of a value, we try to factor that value as
1243 // well. Handling this case is important because array indices are
1244 // typically sign-extended to the pointer index size.
1245 Value *TruncatedArrayIdx = nullptr;
1246 if (match(V: ArrayIdx, P: m_SExt(Op: m_Value(V&: TruncatedArrayIdx))) &&
1247 TruncatedArrayIdx->getType()->getIntegerBitWidth() <=
1248 DL->getIndexSizeInBits(AS: GEP->getAddressSpace())) {
1249 // Skip factoring if TruncatedArrayIdx is wider than the pointer size,
1250 // because TruncatedArrayIdx is implicitly truncated to the pointer size.
1251 allocateCandidatesAndFindBasis(CT: Candidate::GEP, B: BaseExpr, Idx: ElementSizeIdx,
1252 S: TruncatedArrayIdx, I: GEP);
1253 }
1254
1255 IndexExprs[I - 1] = OrigIndexExpr;
1256 }
1257}
1258
1259Value *StraightLineStrengthReduce::emitBump(const Candidate &Basis,
1260 const Candidate &C,
1261 IRBuilder<> &Builder,
1262 const DataLayout *DL) {
1263 auto CreateMul = [&](Value *LHS, Value *RHS) {
1264 if (ConstantInt *CR = dyn_cast<ConstantInt>(Val: RHS)) {
1265 const APInt &ConstRHS = CR->getValue();
1266 IntegerType *DeltaType =
1267 IntegerType::get(C&: C.Ins->getContext(), NumBits: ConstRHS.getBitWidth());
1268 if (ConstRHS.isPowerOf2()) {
1269 ConstantInt *Exponent =
1270 ConstantInt::get(Ty: DeltaType, V: ConstRHS.logBase2());
1271 return Builder.CreateShl(LHS, RHS: Exponent);
1272 }
1273 if (ConstRHS.isNegatedPowerOf2()) {
1274 ConstantInt *Exponent =
1275 ConstantInt::get(Ty: DeltaType, V: (-ConstRHS).logBase2());
1276 return Builder.CreateNeg(V: Builder.CreateShl(LHS, RHS: Exponent));
1277 }
1278 }
1279
1280 return Builder.CreateMul(LHS, RHS);
1281 };
1282
1283 Value *Delta = C.Delta;
1284 // If Delta is 0, C is a fully redundant of C.Basis,
1285 // just replace C.Ins with Basis.Ins
1286 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val: Delta);
1287 CI && CI->getValue().isZero())
1288 return nullptr;
1289
1290 if (C.DeltaKind == Candidate::IndexDelta) {
1291 APInt IndexDelta = cast<ConstantInt>(Val: C.Delta)->getValue();
1292 // IndexDelta
1293 // X = B + i * S
1294 // Y = B + i` * S
1295 // = B + (i + IndexDelta) * S
1296 // = B + i * S + IndexDelta * S
1297 // = X + IndexDelta * S
1298 // Bump = (i' - i) * S
1299
1300 // Common case 1: if (i' - i) is 1, Bump = S.
1301 if (IndexDelta == 1)
1302 return C.Stride;
1303 // Common case 2: if (i' - i) is -1, Bump = -S.
1304 if (IndexDelta.isAllOnes())
1305 return Builder.CreateNeg(V: C.Stride);
1306
1307 IntegerType *DeltaType =
1308 IntegerType::get(C&: Basis.Ins->getContext(), NumBits: IndexDelta.getBitWidth());
1309 Value *ExtendedStride = Builder.CreateSExtOrTrunc(V: C.Stride, DestTy: DeltaType);
1310
1311 return CreateMul(ExtendedStride, C.Delta);
1312 }
1313
1314 assert(C.DeltaKind == Candidate::StrideDelta ||
1315 C.DeltaKind == Candidate::BaseDelta);
1316 assert(C.CandidateKind != Candidate::Mul);
1317 // StrideDelta
1318 // X = B + i * S
1319 // Y = B + i * S'
1320 // = B + i * (S + StrideDelta)
1321 // = B + i * S + i * StrideDelta
1322 // = X + i * StrideDelta
1323 // Bump = i * (S' - S)
1324 //
1325 // BaseDelta
1326 // X = B + i * S
1327 // Y = B' + i * S
1328 // = (B + BaseDelta) + i * S
1329 // = X + BaseDelta
1330 // Bump = (B' - B).
1331 Value *Bump = C.Delta;
1332 if (C.DeltaKind == Candidate::StrideDelta) {
1333 // If this value is consumed by a GEP, promote StrideDelta before doing
1334 // StrideDelta * Index to ensure the same semantics as the original GEP.
1335 if (C.CandidateKind == Candidate::GEP) {
1336 auto *GEP = cast<GetElementPtrInst>(Val: C.Ins);
1337 Type *NewScalarIndexTy =
1338 DL->getIndexType(PtrTy: GEP->getPointerOperandType()->getScalarType());
1339 Bump = Builder.CreateSExtOrTrunc(V: Bump, DestTy: NewScalarIndexTy);
1340 }
1341 if (!C.Index->isOne()) {
1342 Value *ExtendedIndex =
1343 Builder.CreateSExtOrTrunc(V: C.Index, DestTy: Bump->getType());
1344 Bump = CreateMul(Bump, ExtendedIndex);
1345 }
1346 }
1347 return Bump;
1348}
1349
1350void StraightLineStrengthReduce::rewriteCandidate(const Candidate &C) {
1351 if (!DebugCounter::shouldExecute(Counter&: StraightLineStrengthReduceCounter))
1352 return;
1353
1354 const Candidate &Basis = *C.Basis;
1355 assert(C.Delta && C.CandidateKind == Basis.CandidateKind &&
1356 C.hasValidDelta(Basis));
1357
1358 IRBuilder<> Builder(C.Ins);
1359 Value *Bump = emitBump(Basis, C, Builder, DL);
1360 Value *Reduced = nullptr; // equivalent to but weaker than C.Ins
1361 // If delta is 0, C is a fully redundant of Basis, and Bump is nullptr,
1362 // just replace C.Ins with Basis.Ins
1363 if (!Bump)
1364 Reduced = Basis.Ins;
1365 else {
1366 switch (C.CandidateKind) {
1367 case Candidate::Add:
1368 case Candidate::Mul: {
1369 // C = Basis + Bump
1370 Value *NegBump;
1371 if (match(V: Bump, P: m_Neg(V: m_Value(V&: NegBump)))) {
1372 // If Bump is a neg instruction, emit C = Basis - (-Bump).
1373 Reduced = Builder.CreateSub(LHS: Basis.Ins, RHS: NegBump);
1374 // We only use the negative argument of Bump, and Bump itself may be
1375 // trivially dead.
1376 RecursivelyDeleteTriviallyDeadInstructions(V: Bump);
1377 } else {
1378 // It's tempting to preserve nsw on Bump and/or Reduced. However, it's
1379 // usually unsound, e.g.,
1380 //
1381 // X = (-2 +nsw 1) *nsw INT_MAX
1382 // Y = (-2 +nsw 3) *nsw INT_MAX
1383 // =>
1384 // Y = X + 2 * INT_MAX
1385 //
1386 // Neither + and * in the resultant expression are nsw.
1387 Reduced = Builder.CreateAdd(LHS: Basis.Ins, RHS: Bump);
1388 }
1389 break;
1390 }
1391 case Candidate::GEP: {
1392 bool InBounds = cast<GetElementPtrInst>(Val: C.Ins)->isInBounds();
1393 // C = (char *)Basis + Bump
1394 Reduced = Builder.CreatePtrAdd(Ptr: Basis.Ins, Offset: Bump, Name: "", NW: InBounds);
1395 break;
1396 }
1397 default:
1398 llvm_unreachable("C.CandidateKind is invalid");
1399 };
1400 Reduced->takeName(V: C.Ins);
1401 }
1402 C.Ins->replaceAllUsesWith(V: Reduced);
1403 DeadInstructions.push_back(x: C.Ins);
1404}
1405
1406bool StraightLineStrengthReduceLegacyPass::runOnFunction(Function &F) {
1407 if (skipFunction(F))
1408 return false;
1409
1410 auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1411 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1412 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1413 return StraightLineStrengthReduce(DL, DT, SE, TTI).runOnFunction(F);
1414}
1415
1416bool StraightLineStrengthReduce::runOnFunction(Function &F) {
1417 LLVM_DEBUG(dbgs() << "SLSR on Function: " << F.getName() << "\n");
1418 // Traverse the dominator tree in the depth-first order. This order makes sure
1419 // all bases of a candidate are in Candidates when we process it.
1420 for (const auto Node : depth_first(G: DT))
1421 for (auto &I : *(Node->getBlock()))
1422 allocateCandidatesAndFindBasis(I: &I);
1423
1424 // Build the dependency graph and sort candidate instructions from dependency
1425 // roots to leaves
1426 for (auto &C : Candidates) {
1427 DependencyGraph.try_emplace(Key: C.Ins);
1428 addDependency(C, Basis: C.Basis);
1429 }
1430 sortCandidateInstructions();
1431
1432 // Rewrite candidates in the topological order that rewrites a Candidate
1433 // always before rewriting its Basis
1434 for (Instruction *I : reverse(C&: SortedCandidateInsts))
1435 if (Candidate *C = pickRewriteCandidate(I))
1436 rewriteCandidate(C: *C);
1437
1438 for (auto *DeadIns : DeadInstructions)
1439 // A dead instruction may be another dead instruction's op,
1440 // don't delete an instruction twice
1441 if (DeadIns->getParent())
1442 RecursivelyDeleteTriviallyDeadInstructions(V: DeadIns);
1443
1444 bool Ret = !DeadInstructions.empty();
1445 DeadInstructions.clear();
1446 DependencyGraph.clear();
1447 RewriteCandidates.clear();
1448 SortedCandidateInsts.clear();
1449 // First clear all references to candidates in the list
1450 CandidateDict.clear();
1451 // Then destroy the list
1452 Candidates.clear();
1453 return Ret;
1454}
1455
1456PreservedAnalyses
1457StraightLineStrengthReducePass::run(Function &F, FunctionAnalysisManager &AM) {
1458 const DataLayout *DL = &F.getDataLayout();
1459 auto *DT = &AM.getResult<DominatorTreeAnalysis>(IR&: F);
1460 auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(IR&: F);
1461 auto *TTI = &AM.getResult<TargetIRAnalysis>(IR&: F);
1462
1463 if (!StraightLineStrengthReduce(DL, DT, SE, TTI).runOnFunction(F))
1464 return PreservedAnalyses::all();
1465
1466 PreservedAnalyses PA;
1467 PA.preserveSet<CFGAnalyses>();
1468 PA.preserve<ScalarEvolutionAnalysis>();
1469 PA.preserve<TargetIRAnalysis>();
1470 return PA;
1471}
1472