LLVM 20.0.0git
LoopStrengthReduce.cpp
Go to the documentation of this file.
1//===- LoopStrengthReduce.cpp - Strength Reduce IVs in Loops --------------===//
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 transformation analyzes and transforms the induction variables (and
10// computations derived from them) into forms suitable for efficient execution
11// on the target.
12//
13// This pass performs a strength reduction on array references inside loops that
14// have as one or more of their components the loop induction variable, it
15// rewrites expressions to take advantage of scaled-index addressing modes
16// available on the target, and it performs a variety of other optimizations
17// related to loop induction variables.
18//
19// Terminology note: this code has a lot of handling for "post-increment" or
20// "post-inc" users. This is not talking about post-increment addressing modes;
21// it is instead talking about code like this:
22//
23// %i = phi [ 0, %entry ], [ %i.next, %latch ]
24// ...
25// %i.next = add %i, 1
26// %c = icmp eq %i.next, %n
27//
28// The SCEV for %i is {0,+,1}<%L>. The SCEV for %i.next is {1,+,1}<%L>, however
29// it's useful to think about these as the same register, with some uses using
30// the value of the register before the add and some using it after. In this
31// example, the icmp is a post-increment user, since it uses %i.next, which is
32// the value of the induction variable after the increment. The other common
33// case of post-increment users is users outside the loop.
34//
35// TODO: More sophistication in the way Formulae are generated and filtered.
36//
37// TODO: Handle multiple loops at a time.
38//
39// TODO: Should the addressing mode BaseGV be changed to a ConstantExpr instead
40// of a GlobalValue?
41//
42// TODO: When truncation is free, truncate ICmp users' operands to make it a
43// smaller encoding (on x86 at least).
44//
45// TODO: When a negated register is used by an add (such as in a list of
46// multiple base registers, or as the increment expression in an addrec),
47// we may not actually need both reg and (-1 * reg) in registers; the
48// negation can be implemented by using a sub instead of an add. The
49// lack of support for taking this into consideration when making
50// register pressure decisions is partly worked around by the "Special"
51// use kind.
52//
53//===----------------------------------------------------------------------===//
54
56#include "llvm/ADT/APInt.h"
57#include "llvm/ADT/DenseMap.h"
58#include "llvm/ADT/DenseSet.h"
59#include "llvm/ADT/Hashing.h"
61#include "llvm/ADT/STLExtras.h"
62#include "llvm/ADT/SetVector.h"
65#include "llvm/ADT/SmallSet.h"
67#include "llvm/ADT/Statistic.h"
84#include "llvm/Config/llvm-config.h"
85#include "llvm/IR/BasicBlock.h"
86#include "llvm/IR/Constant.h"
87#include "llvm/IR/Constants.h"
90#include "llvm/IR/Dominators.h"
91#include "llvm/IR/GlobalValue.h"
92#include "llvm/IR/IRBuilder.h"
93#include "llvm/IR/InstrTypes.h"
94#include "llvm/IR/Instruction.h"
97#include "llvm/IR/Module.h"
98#include "llvm/IR/Operator.h"
99#include "llvm/IR/Type.h"
100#include "llvm/IR/Use.h"
101#include "llvm/IR/User.h"
102#include "llvm/IR/Value.h"
103#include "llvm/IR/ValueHandle.h"
105#include "llvm/Pass.h"
106#include "llvm/Support/Casting.h"
109#include "llvm/Support/Debug.h"
119#include <algorithm>
120#include <cassert>
121#include <cstddef>
122#include <cstdint>
123#include <iterator>
124#include <limits>
125#include <map>
126#include <numeric>
127#include <optional>
128#include <utility>
129
130using namespace llvm;
131
132#define DEBUG_TYPE "loop-reduce"
133
134/// MaxIVUsers is an arbitrary threshold that provides an early opportunity for
135/// bail out. This threshold is far beyond the number of users that LSR can
136/// conceivably solve, so it should not affect generated code, but catches the
137/// worst cases before LSR burns too much compile time and stack space.
138static const unsigned MaxIVUsers = 200;
139
140/// Limit the size of expression that SCEV-based salvaging will attempt to
141/// translate into a DIExpression.
142/// Choose a maximum size such that debuginfo is not excessively increased and
143/// the salvaging is not too expensive for the compiler.
144static const unsigned MaxSCEVSalvageExpressionSize = 64;
145
146// Cleanup congruent phis after LSR phi expansion.
148 "enable-lsr-phielim", cl::Hidden, cl::init(true),
149 cl::desc("Enable LSR phi elimination"));
150
151// The flag adds instruction count to solutions cost comparison.
153 "lsr-insns-cost", cl::Hidden, cl::init(true),
154 cl::desc("Add instruction count to a LSR cost model"));
155
156// Flag to choose how to narrow complex lsr solution
158 "lsr-exp-narrow", cl::Hidden, cl::init(false),
159 cl::desc("Narrow LSR complex solution using"
160 " expectation of registers number"));
161
162// Flag to narrow search space by filtering non-optimal formulae with
163// the same ScaledReg and Scale.
165 "lsr-filter-same-scaled-reg", cl::Hidden, cl::init(true),
166 cl::desc("Narrow LSR search space by filtering non-optimal formulae"
167 " with the same ScaledReg and Scale"));
168
170 "lsr-preferred-addressing-mode", cl::Hidden, cl::init(TTI::AMK_None),
171 cl::desc("A flag that overrides the target's preferred addressing mode."),
173 "none",
174 "Don't prefer any addressing mode"),
176 "preindexed",
177 "Prefer pre-indexed addressing mode"),
179 "postindexed",
180 "Prefer post-indexed addressing mode")));
181
183 "lsr-complexity-limit", cl::Hidden,
184 cl::init(std::numeric_limits<uint16_t>::max()),
185 cl::desc("LSR search space complexity limit"));
186
188 "lsr-setupcost-depth-limit", cl::Hidden, cl::init(7),
189 cl::desc("The limit on recursion depth for LSRs setup cost"));
190
192 "lsr-drop-solution", cl::Hidden,
193 cl::desc("Attempt to drop solution if it is less profitable"));
194
196 "lsr-enable-vscale-immediates", cl::Hidden, cl::init(true),
197 cl::desc("Enable analysis of vscale-relative immediates in LSR"));
198
200 "lsr-drop-scaled-reg-for-vscale", cl::Hidden, cl::init(true),
201 cl::desc("Avoid using scaled registers with vscale-relative addressing"));
202
203#ifndef NDEBUG
204// Stress test IV chain generation.
206 "stress-ivchain", cl::Hidden, cl::init(false),
207 cl::desc("Stress test LSR IV chains"));
208#else
209static bool StressIVChain = false;
210#endif
211
212namespace {
213
214struct MemAccessTy {
215 /// Used in situations where the accessed memory type is unknown.
216 static const unsigned UnknownAddressSpace =
217 std::numeric_limits<unsigned>::max();
218
219 Type *MemTy = nullptr;
220 unsigned AddrSpace = UnknownAddressSpace;
221
222 MemAccessTy() = default;
223 MemAccessTy(Type *Ty, unsigned AS) : MemTy(Ty), AddrSpace(AS) {}
224
225 bool operator==(MemAccessTy Other) const {
226 return MemTy == Other.MemTy && AddrSpace == Other.AddrSpace;
227 }
228
229 bool operator!=(MemAccessTy Other) const { return !(*this == Other); }
230
231 static MemAccessTy getUnknown(LLVMContext &Ctx,
232 unsigned AS = UnknownAddressSpace) {
233 return MemAccessTy(Type::getVoidTy(Ctx), AS);
234 }
235
236 Type *getType() { return MemTy; }
237};
238
239/// This class holds data which is used to order reuse candidates.
240class RegSortData {
241public:
242 /// This represents the set of LSRUse indices which reference
243 /// a particular register.
244 SmallBitVector UsedByIndices;
245
246 void print(raw_ostream &OS) const;
247 void dump() const;
248};
249
250// An offset from an address that is either scalable or fixed. Used for
251// per-target optimizations of addressing modes.
252class Immediate : public details::FixedOrScalableQuantity<Immediate, int64_t> {
253 constexpr Immediate(ScalarTy MinVal, bool Scalable)
254 : FixedOrScalableQuantity(MinVal, Scalable) {}
255
256 constexpr Immediate(const FixedOrScalableQuantity<Immediate, int64_t> &V)
257 : FixedOrScalableQuantity(V) {}
258
259public:
260 constexpr Immediate() = delete;
261
262 static constexpr Immediate getFixed(ScalarTy MinVal) {
263 return {MinVal, false};
264 }
265 static constexpr Immediate getScalable(ScalarTy MinVal) {
266 return {MinVal, true};
267 }
268 static constexpr Immediate get(ScalarTy MinVal, bool Scalable) {
269 return {MinVal, Scalable};
270 }
271 static constexpr Immediate getZero() { return {0, false}; }
272 static constexpr Immediate getFixedMin() {
273 return {std::numeric_limits<int64_t>::min(), false};
274 }
275 static constexpr Immediate getFixedMax() {
276 return {std::numeric_limits<int64_t>::max(), false};
277 }
278 static constexpr Immediate getScalableMin() {
279 return {std::numeric_limits<int64_t>::min(), true};
280 }
281 static constexpr Immediate getScalableMax() {
282 return {std::numeric_limits<int64_t>::max(), true};
283 }
284
285 constexpr bool isLessThanZero() const { return Quantity < 0; }
286
287 constexpr bool isGreaterThanZero() const { return Quantity > 0; }
288
289 constexpr bool isCompatibleImmediate(const Immediate &Imm) const {
290 return isZero() || Imm.isZero() || Imm.Scalable == Scalable;
291 }
292
293 constexpr bool isMin() const {
294 return Quantity == std::numeric_limits<ScalarTy>::min();
295 }
296
297 constexpr bool isMax() const {
298 return Quantity == std::numeric_limits<ScalarTy>::max();
299 }
300
301 // Arithmetic 'operators' that cast to unsigned types first.
302 constexpr Immediate addUnsigned(const Immediate &RHS) const {
303 assert(isCompatibleImmediate(RHS) && "Incompatible Immediates");
304 ScalarTy Value = (uint64_t)Quantity + RHS.getKnownMinValue();
305 return {Value, Scalable || RHS.isScalable()};
306 }
307
308 constexpr Immediate subUnsigned(const Immediate &RHS) const {
309 assert(isCompatibleImmediate(RHS) && "Incompatible Immediates");
310 ScalarTy Value = (uint64_t)Quantity - RHS.getKnownMinValue();
311 return {Value, Scalable || RHS.isScalable()};
312 }
313
314 // Scale the quantity by a constant without caring about runtime scalability.
315 constexpr Immediate mulUnsigned(const ScalarTy RHS) const {
316 ScalarTy Value = (uint64_t)Quantity * RHS;
317 return {Value, Scalable};
318 }
319
320 // Helpers for generating SCEVs with vscale terms where needed.
321 const SCEV *getSCEV(ScalarEvolution &SE, Type *Ty) const {
322 const SCEV *S = SE.getConstant(Ty, Quantity);
323 if (Scalable)
324 S = SE.getMulExpr(S, SE.getVScale(S->getType()));
325 return S;
326 }
327
328 const SCEV *getNegativeSCEV(ScalarEvolution &SE, Type *Ty) const {
329 const SCEV *NegS = SE.getConstant(Ty, -(uint64_t)Quantity);
330 if (Scalable)
331 NegS = SE.getMulExpr(NegS, SE.getVScale(NegS->getType()));
332 return NegS;
333 }
334
335 const SCEV *getUnknownSCEV(ScalarEvolution &SE, Type *Ty) const {
336 const SCEV *SU = SE.getUnknown(ConstantInt::getSigned(Ty, Quantity));
337 if (Scalable)
338 SU = SE.getMulExpr(SU, SE.getVScale(SU->getType()));
339 return SU;
340 }
341};
342
343// This is needed for the Compare type of std::map when Immediate is used
344// as a key. We don't need it to be fully correct against any value of vscale,
345// just to make sure that vscale-related terms in the map are considered against
346// each other rather than being mixed up and potentially missing opportunities.
347struct KeyOrderTargetImmediate {
348 bool operator()(const Immediate &LHS, const Immediate &RHS) const {
349 if (LHS.isScalable() && !RHS.isScalable())
350 return false;
351 if (!LHS.isScalable() && RHS.isScalable())
352 return true;
353 return LHS.getKnownMinValue() < RHS.getKnownMinValue();
354 }
355};
356
357// This would be nicer if we could be generic instead of directly using size_t,
358// but there doesn't seem to be a type trait for is_orderable or
359// is_lessthan_comparable or similar.
360struct KeyOrderSizeTAndImmediate {
361 bool operator()(const std::pair<size_t, Immediate> &LHS,
362 const std::pair<size_t, Immediate> &RHS) const {
363 size_t LSize = LHS.first;
364 size_t RSize = RHS.first;
365 if (LSize != RSize)
366 return LSize < RSize;
367 return KeyOrderTargetImmediate()(LHS.second, RHS.second);
368 }
369};
370} // end anonymous namespace
371
372#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
373void RegSortData::print(raw_ostream &OS) const {
374 OS << "[NumUses=" << UsedByIndices.count() << ']';
375}
376
377LLVM_DUMP_METHOD void RegSortData::dump() const {
378 print(errs()); errs() << '\n';
379}
380#endif
381
382namespace {
383
384/// Map register candidates to information about how they are used.
385class RegUseTracker {
386 using RegUsesTy = DenseMap<const SCEV *, RegSortData>;
387
388 RegUsesTy RegUsesMap;
390
391public:
392 void countRegister(const SCEV *Reg, size_t LUIdx);
393 void dropRegister(const SCEV *Reg, size_t LUIdx);
394 void swapAndDropUse(size_t LUIdx, size_t LastLUIdx);
395
396 bool isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const;
397
398 const SmallBitVector &getUsedByIndices(const SCEV *Reg) const;
399
400 void clear();
401
404
405 iterator begin() { return RegSequence.begin(); }
406 iterator end() { return RegSequence.end(); }
407 const_iterator begin() const { return RegSequence.begin(); }
408 const_iterator end() const { return RegSequence.end(); }
409};
410
411} // end anonymous namespace
412
413void
414RegUseTracker::countRegister(const SCEV *Reg, size_t LUIdx) {
415 std::pair<RegUsesTy::iterator, bool> Pair =
416 RegUsesMap.insert(std::make_pair(Reg, RegSortData()));
417 RegSortData &RSD = Pair.first->second;
418 if (Pair.second)
419 RegSequence.push_back(Reg);
420 RSD.UsedByIndices.resize(std::max(RSD.UsedByIndices.size(), LUIdx + 1));
421 RSD.UsedByIndices.set(LUIdx);
422}
423
424void
425RegUseTracker::dropRegister(const SCEV *Reg, size_t LUIdx) {
426 RegUsesTy::iterator It = RegUsesMap.find(Reg);
427 assert(It != RegUsesMap.end());
428 RegSortData &RSD = It->second;
429 assert(RSD.UsedByIndices.size() > LUIdx);
430 RSD.UsedByIndices.reset(LUIdx);
431}
432
433void
434RegUseTracker::swapAndDropUse(size_t LUIdx, size_t LastLUIdx) {
435 assert(LUIdx <= LastLUIdx);
436
437 // Update RegUses. The data structure is not optimized for this purpose;
438 // we must iterate through it and update each of the bit vectors.
439 for (auto &Pair : RegUsesMap) {
440 SmallBitVector &UsedByIndices = Pair.second.UsedByIndices;
441 if (LUIdx < UsedByIndices.size())
442 UsedByIndices[LUIdx] =
443 LastLUIdx < UsedByIndices.size() ? UsedByIndices[LastLUIdx] : false;
444 UsedByIndices.resize(std::min(UsedByIndices.size(), LastLUIdx));
445 }
446}
447
448bool
449RegUseTracker::isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const {
450 RegUsesTy::const_iterator I = RegUsesMap.find(Reg);
451 if (I == RegUsesMap.end())
452 return false;
453 const SmallBitVector &UsedByIndices = I->second.UsedByIndices;
454 int i = UsedByIndices.find_first();
455 if (i == -1) return false;
456 if ((size_t)i != LUIdx) return true;
457 return UsedByIndices.find_next(i) != -1;
458}
459
460const SmallBitVector &RegUseTracker::getUsedByIndices(const SCEV *Reg) const {
461 RegUsesTy::const_iterator I = RegUsesMap.find(Reg);
462 assert(I != RegUsesMap.end() && "Unknown register!");
463 return I->second.UsedByIndices;
464}
465
466void RegUseTracker::clear() {
467 RegUsesMap.clear();
468 RegSequence.clear();
469}
470
471namespace {
472
473/// This class holds information that describes a formula for computing
474/// satisfying a use. It may include broken-out immediates and scaled registers.
475struct Formula {
476 /// Global base address used for complex addressing.
477 GlobalValue *BaseGV = nullptr;
478
479 /// Base offset for complex addressing.
480 Immediate BaseOffset = Immediate::getZero();
481
482 /// Whether any complex addressing has a base register.
483 bool HasBaseReg = false;
484
485 /// The scale of any complex addressing.
486 int64_t Scale = 0;
487
488 /// The list of "base" registers for this use. When this is non-empty. The
489 /// canonical representation of a formula is
490 /// 1. BaseRegs.size > 1 implies ScaledReg != NULL and
491 /// 2. ScaledReg != NULL implies Scale != 1 || !BaseRegs.empty().
492 /// 3. The reg containing recurrent expr related with currect loop in the
493 /// formula should be put in the ScaledReg.
494 /// #1 enforces that the scaled register is always used when at least two
495 /// registers are needed by the formula: e.g., reg1 + reg2 is reg1 + 1 * reg2.
496 /// #2 enforces that 1 * reg is reg.
497 /// #3 ensures invariant regs with respect to current loop can be combined
498 /// together in LSR codegen.
499 /// This invariant can be temporarily broken while building a formula.
500 /// However, every formula inserted into the LSRInstance must be in canonical
501 /// form.
503
504 /// The 'scaled' register for this use. This should be non-null when Scale is
505 /// not zero.
506 const SCEV *ScaledReg = nullptr;
507
508 /// An additional constant offset which added near the use. This requires a
509 /// temporary register, but the offset itself can live in an add immediate
510 /// field rather than a register.
511 Immediate UnfoldedOffset = Immediate::getZero();
512
513 Formula() = default;
514
515 void initialMatch(const SCEV *S, Loop *L, ScalarEvolution &SE);
516
517 bool isCanonical(const Loop &L) const;
518
519 void canonicalize(const Loop &L);
520
521 bool unscale();
522
523 bool hasZeroEnd() const;
524
525 size_t getNumRegs() const;
526 Type *getType() const;
527
528 void deleteBaseReg(const SCEV *&S);
529
530 bool referencesReg(const SCEV *S) const;
531 bool hasRegsUsedByUsesOtherThan(size_t LUIdx,
532 const RegUseTracker &RegUses) const;
533
534 void print(raw_ostream &OS) const;
535 void dump() const;
536};
537
538} // end anonymous namespace
539
540/// Recursion helper for initialMatch.
541static void DoInitialMatch(const SCEV *S, Loop *L,
544 ScalarEvolution &SE) {
545 // Collect expressions which properly dominate the loop header.
546 if (SE.properlyDominates(S, L->getHeader())) {
547 Good.push_back(S);
548 return;
549 }
550
551 // Look at add operands.
552 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
553 for (const SCEV *S : Add->operands())
554 DoInitialMatch(S, L, Good, Bad, SE);
555 return;
556 }
557
558 // Look at addrec operands.
559 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
560 if (!AR->getStart()->isZero() && AR->isAffine()) {
561 DoInitialMatch(AR->getStart(), L, Good, Bad, SE);
562 DoInitialMatch(SE.getAddRecExpr(SE.getConstant(AR->getType(), 0),
563 AR->getStepRecurrence(SE),
564 // FIXME: AR->getNoWrapFlags()
565 AR->getLoop(), SCEV::FlagAnyWrap),
566 L, Good, Bad, SE);
567 return;
568 }
569
570 // Handle a multiplication by -1 (negation) if it didn't fold.
571 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S))
572 if (Mul->getOperand(0)->isAllOnesValue()) {
574 const SCEV *NewMul = SE.getMulExpr(Ops);
575
578 DoInitialMatch(NewMul, L, MyGood, MyBad, SE);
579 const SCEV *NegOne = SE.getSCEV(ConstantInt::getAllOnesValue(
580 SE.getEffectiveSCEVType(NewMul->getType())));
581 for (const SCEV *S : MyGood)
582 Good.push_back(SE.getMulExpr(NegOne, S));
583 for (const SCEV *S : MyBad)
584 Bad.push_back(SE.getMulExpr(NegOne, S));
585 return;
586 }
587
588 // Ok, we can't do anything interesting. Just stuff the whole thing into a
589 // register and hope for the best.
590 Bad.push_back(S);
591}
592
593/// Incorporate loop-variant parts of S into this Formula, attempting to keep
594/// all loop-invariant and loop-computable values in a single base register.
595void Formula::initialMatch(const SCEV *S, Loop *L, ScalarEvolution &SE) {
598 DoInitialMatch(S, L, Good, Bad, SE);
599 if (!Good.empty()) {
600 const SCEV *Sum = SE.getAddExpr(Good);
601 if (!Sum->isZero())
602 BaseRegs.push_back(Sum);
603 HasBaseReg = true;
604 }
605 if (!Bad.empty()) {
606 const SCEV *Sum = SE.getAddExpr(Bad);
607 if (!Sum->isZero())
608 BaseRegs.push_back(Sum);
609 HasBaseReg = true;
610 }
611 canonicalize(*L);
612}
613
614static bool containsAddRecDependentOnLoop(const SCEV *S, const Loop &L) {
615 return SCEVExprContains(S, [&L](const SCEV *S) {
616 return isa<SCEVAddRecExpr>(S) && (cast<SCEVAddRecExpr>(S)->getLoop() == &L);
617 });
618}
619
620/// Check whether or not this formula satisfies the canonical
621/// representation.
622/// \see Formula::BaseRegs.
623bool Formula::isCanonical(const Loop &L) const {
624 assert((Scale == 0 || ScaledReg) &&
625 "ScaledReg must be non-null if Scale is non-zero");
626
627 if (!ScaledReg)
628 return BaseRegs.size() <= 1;
629
630 if (Scale != 1)
631 return true;
632
633 if (Scale == 1 && BaseRegs.empty())
634 return false;
635
636 if (containsAddRecDependentOnLoop(ScaledReg, L))
637 return true;
638
639 // If ScaledReg is not a recurrent expr, or it is but its loop is not current
640 // loop, meanwhile BaseRegs contains a recurrent expr reg related with current
641 // loop, we want to swap the reg in BaseRegs with ScaledReg.
642 return none_of(BaseRegs, [&L](const SCEV *S) {
644 });
645}
646
647/// Helper method to morph a formula into its canonical representation.
648/// \see Formula::BaseRegs.
649/// Every formula having more than one base register, must use the ScaledReg
650/// field. Otherwise, we would have to do special cases everywhere in LSR
651/// to treat reg1 + reg2 + ... the same way as reg1 + 1*reg2 + ...
652/// On the other hand, 1*reg should be canonicalized into reg.
653void Formula::canonicalize(const Loop &L) {
654 if (isCanonical(L))
655 return;
656
657 if (BaseRegs.empty()) {
658 // No base reg? Use scale reg with scale = 1 as such.
659 assert(ScaledReg && "Expected 1*reg => reg");
660 assert(Scale == 1 && "Expected 1*reg => reg");
661 BaseRegs.push_back(ScaledReg);
662 Scale = 0;
663 ScaledReg = nullptr;
664 return;
665 }
666
667 // Keep the invariant sum in BaseRegs and one of the variant sum in ScaledReg.
668 if (!ScaledReg) {
669 ScaledReg = BaseRegs.pop_back_val();
670 Scale = 1;
671 }
672
673 // If ScaledReg is an invariant with respect to L, find the reg from
674 // BaseRegs containing the recurrent expr related with Loop L. Swap the
675 // reg with ScaledReg.
676 if (!containsAddRecDependentOnLoop(ScaledReg, L)) {
677 auto I = find_if(BaseRegs, [&L](const SCEV *S) {
679 });
680 if (I != BaseRegs.end())
681 std::swap(ScaledReg, *I);
682 }
683 assert(isCanonical(L) && "Failed to canonicalize?");
684}
685
686/// Get rid of the scale in the formula.
687/// In other words, this method morphes reg1 + 1*reg2 into reg1 + reg2.
688/// \return true if it was possible to get rid of the scale, false otherwise.
689/// \note After this operation the formula may not be in the canonical form.
690bool Formula::unscale() {
691 if (Scale != 1)
692 return false;
693 Scale = 0;
694 BaseRegs.push_back(ScaledReg);
695 ScaledReg = nullptr;
696 return true;
697}
698
699bool Formula::hasZeroEnd() const {
700 if (UnfoldedOffset || BaseOffset)
701 return false;
702 if (BaseRegs.size() != 1 || ScaledReg)
703 return false;
704 return true;
705}
706
707/// Return the total number of register operands used by this formula. This does
708/// not include register uses implied by non-constant addrec strides.
709size_t Formula::getNumRegs() const {
710 return !!ScaledReg + BaseRegs.size();
711}
712
713/// Return the type of this formula, if it has one, or null otherwise. This type
714/// is meaningless except for the bit size.
715Type *Formula::getType() const {
716 return !BaseRegs.empty() ? BaseRegs.front()->getType() :
717 ScaledReg ? ScaledReg->getType() :
718 BaseGV ? BaseGV->getType() :
719 nullptr;
720}
721
722/// Delete the given base reg from the BaseRegs list.
723void Formula::deleteBaseReg(const SCEV *&S) {
724 if (&S != &BaseRegs.back())
725 std::swap(S, BaseRegs.back());
726 BaseRegs.pop_back();
727}
728
729/// Test if this formula references the given register.
730bool Formula::referencesReg(const SCEV *S) const {
731 return S == ScaledReg || is_contained(BaseRegs, S);
732}
733
734/// Test whether this formula uses registers which are used by uses other than
735/// the use with the given index.
736bool Formula::hasRegsUsedByUsesOtherThan(size_t LUIdx,
737 const RegUseTracker &RegUses) const {
738 if (ScaledReg)
739 if (RegUses.isRegUsedByUsesOtherThan(ScaledReg, LUIdx))
740 return true;
741 for (const SCEV *BaseReg : BaseRegs)
742 if (RegUses.isRegUsedByUsesOtherThan(BaseReg, LUIdx))
743 return true;
744 return false;
745}
746
747#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
748void Formula::print(raw_ostream &OS) const {
749 bool First = true;
750 if (BaseGV) {
751 if (!First) OS << " + "; else First = false;
752 BaseGV->printAsOperand(OS, /*PrintType=*/false);
753 }
754 if (BaseOffset.isNonZero()) {
755 if (!First) OS << " + "; else First = false;
756 OS << BaseOffset;
757 }
758 for (const SCEV *BaseReg : BaseRegs) {
759 if (!First) OS << " + "; else First = false;
760 OS << "reg(" << *BaseReg << ')';
761 }
762 if (HasBaseReg && BaseRegs.empty()) {
763 if (!First) OS << " + "; else First = false;
764 OS << "**error: HasBaseReg**";
765 } else if (!HasBaseReg && !BaseRegs.empty()) {
766 if (!First) OS << " + "; else First = false;
767 OS << "**error: !HasBaseReg**";
768 }
769 if (Scale != 0) {
770 if (!First) OS << " + "; else First = false;
771 OS << Scale << "*reg(";
772 if (ScaledReg)
773 OS << *ScaledReg;
774 else
775 OS << "<unknown>";
776 OS << ')';
777 }
778 if (UnfoldedOffset.isNonZero()) {
779 if (!First) OS << " + ";
780 OS << "imm(" << UnfoldedOffset << ')';
781 }
782}
783
784LLVM_DUMP_METHOD void Formula::dump() const {
785 print(errs()); errs() << '\n';
786}
787#endif
788
789/// Return true if the given addrec can be sign-extended without changing its
790/// value.
792 Type *WideTy =
794 return isa<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
795}
796
797/// Return true if the given add can be sign-extended without changing its
798/// value.
799static bool isAddSExtable(const SCEVAddExpr *A, ScalarEvolution &SE) {
800 Type *WideTy =
801 IntegerType::get(SE.getContext(), SE.getTypeSizeInBits(A->getType()) + 1);
802 return isa<SCEVAddExpr>(SE.getSignExtendExpr(A, WideTy));
803}
804
805/// Return true if the given mul can be sign-extended without changing its
806/// value.
807static bool isMulSExtable(const SCEVMulExpr *M, ScalarEvolution &SE) {
808 Type *WideTy =
810 SE.getTypeSizeInBits(M->getType()) * M->getNumOperands());
811 return isa<SCEVMulExpr>(SE.getSignExtendExpr(M, WideTy));
812}
813
814/// Return an expression for LHS /s RHS, if it can be determined and if the
815/// remainder is known to be zero, or null otherwise. If IgnoreSignificantBits
816/// is true, expressions like (X * Y) /s Y are simplified to X, ignoring that
817/// the multiplication may overflow, which is useful when the result will be
818/// used in a context where the most significant bits are ignored.
819static const SCEV *getExactSDiv(const SCEV *LHS, const SCEV *RHS,
820 ScalarEvolution &SE,
821 bool IgnoreSignificantBits = false) {
822 // Handle the trivial case, which works for any SCEV type.
823 if (LHS == RHS)
824 return SE.getConstant(LHS->getType(), 1);
825
826 // Handle a few RHS special cases.
827 const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS);
828 if (RC) {
829 const APInt &RA = RC->getAPInt();
830 // Handle x /s -1 as x * -1, to give ScalarEvolution a chance to do
831 // some folding.
832 if (RA.isAllOnes()) {
833 if (LHS->getType()->isPointerTy())
834 return nullptr;
835 return SE.getMulExpr(LHS, RC);
836 }
837 // Handle x /s 1 as x.
838 if (RA == 1)
839 return LHS;
840 }
841
842 // Check for a division of a constant by a constant.
843 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(LHS)) {
844 if (!RC)
845 return nullptr;
846 const APInt &LA = C->getAPInt();
847 const APInt &RA = RC->getAPInt();
848 if (LA.srem(RA) != 0)
849 return nullptr;
850 return SE.getConstant(LA.sdiv(RA));
851 }
852
853 // Distribute the sdiv over addrec operands, if the addrec doesn't overflow.
854 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) {
855 if ((IgnoreSignificantBits || isAddRecSExtable(AR, SE)) && AR->isAffine()) {
856 const SCEV *Step = getExactSDiv(AR->getStepRecurrence(SE), RHS, SE,
857 IgnoreSignificantBits);
858 if (!Step) return nullptr;
859 const SCEV *Start = getExactSDiv(AR->getStart(), RHS, SE,
860 IgnoreSignificantBits);
861 if (!Start) return nullptr;
862 // FlagNW is independent of the start value, step direction, and is
863 // preserved with smaller magnitude steps.
864 // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
865 return SE.getAddRecExpr(Start, Step, AR->getLoop(), SCEV::FlagAnyWrap);
866 }
867 return nullptr;
868 }
869
870 // Distribute the sdiv over add operands, if the add doesn't overflow.
871 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(LHS)) {
872 if (IgnoreSignificantBits || isAddSExtable(Add, SE)) {
874 for (const SCEV *S : Add->operands()) {
875 const SCEV *Op = getExactSDiv(S, RHS, SE, IgnoreSignificantBits);
876 if (!Op) return nullptr;
877 Ops.push_back(Op);
878 }
879 return SE.getAddExpr(Ops);
880 }
881 return nullptr;
882 }
883
884 // Check for a multiply operand that we can pull RHS out of.
885 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS)) {
886 if (IgnoreSignificantBits || isMulSExtable(Mul, SE)) {
887 // Handle special case C1*X*Y /s C2*X*Y.
888 if (const SCEVMulExpr *MulRHS = dyn_cast<SCEVMulExpr>(RHS)) {
889 if (IgnoreSignificantBits || isMulSExtable(MulRHS, SE)) {
890 const SCEVConstant *LC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
891 const SCEVConstant *RC =
892 dyn_cast<SCEVConstant>(MulRHS->getOperand(0));
893 if (LC && RC) {
895 SmallVector<const SCEV *, 4> ROps(drop_begin(MulRHS->operands()));
896 if (LOps == ROps)
897 return getExactSDiv(LC, RC, SE, IgnoreSignificantBits);
898 }
899 }
900 }
901
903 bool Found = false;
904 for (const SCEV *S : Mul->operands()) {
905 if (!Found)
906 if (const SCEV *Q = getExactSDiv(S, RHS, SE,
907 IgnoreSignificantBits)) {
908 S = Q;
909 Found = true;
910 }
911 Ops.push_back(S);
912 }
913 return Found ? SE.getMulExpr(Ops) : nullptr;
914 }
915 return nullptr;
916 }
917
918 // Otherwise we don't know.
919 return nullptr;
920}
921
922/// If S involves the addition of a constant integer value, return that integer
923/// value, and mutate S to point to a new SCEV with that value excluded.
924static Immediate ExtractImmediate(const SCEV *&S, ScalarEvolution &SE) {
925 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
926 if (C->getAPInt().getSignificantBits() <= 64) {
927 S = SE.getConstant(C->getType(), 0);
928 return Immediate::getFixed(C->getValue()->getSExtValue());
929 }
930 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
931 SmallVector<const SCEV *, 8> NewOps(Add->operands());
932 Immediate Result = ExtractImmediate(NewOps.front(), SE);
933 if (Result.isNonZero())
934 S = SE.getAddExpr(NewOps);
935 return Result;
936 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
937 SmallVector<const SCEV *, 8> NewOps(AR->operands());
938 Immediate Result = ExtractImmediate(NewOps.front(), SE);
939 if (Result.isNonZero())
940 S = SE.getAddRecExpr(NewOps, AR->getLoop(),
941 // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
943 return Result;
944 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
945 if (EnableVScaleImmediates && M->getNumOperands() == 2) {
946 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
947 if (isa<SCEVVScale>(M->getOperand(1))) {
948 S = SE.getConstant(M->getType(), 0);
949 return Immediate::getScalable(C->getValue()->getSExtValue());
950 }
951 }
952 }
953 return Immediate::getZero();
954}
955
956/// If S involves the addition of a GlobalValue address, return that symbol, and
957/// mutate S to point to a new SCEV with that value excluded.
959 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
960 if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue())) {
961 S = SE.getConstant(GV->getType(), 0);
962 return GV;
963 }
964 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
965 SmallVector<const SCEV *, 8> NewOps(Add->operands());
966 GlobalValue *Result = ExtractSymbol(NewOps.back(), SE);
967 if (Result)
968 S = SE.getAddExpr(NewOps);
969 return Result;
970 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
971 SmallVector<const SCEV *, 8> NewOps(AR->operands());
972 GlobalValue *Result = ExtractSymbol(NewOps.front(), SE);
973 if (Result)
974 S = SE.getAddRecExpr(NewOps, AR->getLoop(),
975 // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
977 return Result;
978 }
979 return nullptr;
980}
981
982/// Returns true if the specified instruction is using the specified value as an
983/// address.
985 Instruction *Inst, Value *OperandVal) {
986 bool isAddress = isa<LoadInst>(Inst);
987 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
988 if (SI->getPointerOperand() == OperandVal)
989 isAddress = true;
990 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
991 // Addressing modes can also be folded into prefetches and a variety
992 // of intrinsics.
993 switch (II->getIntrinsicID()) {
994 case Intrinsic::memset:
995 case Intrinsic::prefetch:
996 case Intrinsic::masked_load:
997 if (II->getArgOperand(0) == OperandVal)
998 isAddress = true;
999 break;
1000 case Intrinsic::masked_store:
1001 if (II->getArgOperand(1) == OperandVal)
1002 isAddress = true;
1003 break;
1004 case Intrinsic::memmove:
1005 case Intrinsic::memcpy:
1006 if (II->getArgOperand(0) == OperandVal ||
1007 II->getArgOperand(1) == OperandVal)
1008 isAddress = true;
1009 break;
1010 default: {
1011 MemIntrinsicInfo IntrInfo;
1012 if (TTI.getTgtMemIntrinsic(II, IntrInfo)) {
1013 if (IntrInfo.PtrVal == OperandVal)
1014 isAddress = true;
1015 }
1016 }
1017 }
1018 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(Inst)) {
1019 if (RMW->getPointerOperand() == OperandVal)
1020 isAddress = true;
1021 } else if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(Inst)) {
1022 if (CmpX->getPointerOperand() == OperandVal)
1023 isAddress = true;
1024 }
1025 return isAddress;
1026}
1027
1028/// Return the type of the memory being accessed.
1029static MemAccessTy getAccessType(const TargetTransformInfo &TTI,
1030 Instruction *Inst, Value *OperandVal) {
1031 MemAccessTy AccessTy = MemAccessTy::getUnknown(Inst->getContext());
1032
1033 // First get the type of memory being accessed.
1034 if (Type *Ty = Inst->getAccessType())
1035 AccessTy.MemTy = Ty;
1036
1037 // Then get the pointer address space.
1038 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1039 AccessTy.AddrSpace = SI->getPointerAddressSpace();
1040 } else if (const LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
1041 AccessTy.AddrSpace = LI->getPointerAddressSpace();
1042 } else if (const AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(Inst)) {
1043 AccessTy.AddrSpace = RMW->getPointerAddressSpace();
1044 } else if (const AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(Inst)) {
1045 AccessTy.AddrSpace = CmpX->getPointerAddressSpace();
1046 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
1047 switch (II->getIntrinsicID()) {
1048 case Intrinsic::prefetch:
1049 case Intrinsic::memset:
1050 AccessTy.AddrSpace = II->getArgOperand(0)->getType()->getPointerAddressSpace();
1051 AccessTy.MemTy = OperandVal->getType();
1052 break;
1053 case Intrinsic::memmove:
1054 case Intrinsic::memcpy:
1055 AccessTy.AddrSpace = OperandVal->getType()->getPointerAddressSpace();
1056 AccessTy.MemTy = OperandVal->getType();
1057 break;
1058 case Intrinsic::masked_load:
1059 AccessTy.AddrSpace =
1060 II->getArgOperand(0)->getType()->getPointerAddressSpace();
1061 break;
1062 case Intrinsic::masked_store:
1063 AccessTy.AddrSpace =
1064 II->getArgOperand(1)->getType()->getPointerAddressSpace();
1065 break;
1066 default: {
1067 MemIntrinsicInfo IntrInfo;
1068 if (TTI.getTgtMemIntrinsic(II, IntrInfo) && IntrInfo.PtrVal) {
1069 AccessTy.AddrSpace
1070 = IntrInfo.PtrVal->getType()->getPointerAddressSpace();
1071 }
1072
1073 break;
1074 }
1075 }
1076 }
1077
1078 return AccessTy;
1079}
1080
1081/// Return true if this AddRec is already a phi in its loop.
1082static bool isExistingPhi(const SCEVAddRecExpr *AR, ScalarEvolution &SE) {
1083 for (PHINode &PN : AR->getLoop()->getHeader()->phis()) {
1084 if (SE.isSCEVable(PN.getType()) &&
1085 (SE.getEffectiveSCEVType(PN.getType()) ==
1086 SE.getEffectiveSCEVType(AR->getType())) &&
1087 SE.getSCEV(&PN) == AR)
1088 return true;
1089 }
1090 return false;
1091}
1092
1093/// Check if expanding this expression is likely to incur significant cost. This
1094/// is tricky because SCEV doesn't track which expressions are actually computed
1095/// by the current IR.
1096///
1097/// We currently allow expansion of IV increments that involve adds,
1098/// multiplication by constants, and AddRecs from existing phis.
1099///
1100/// TODO: Allow UDivExpr if we can find an existing IV increment that is an
1101/// obvious multiple of the UDivExpr.
1102static bool isHighCostExpansion(const SCEV *S,
1104 ScalarEvolution &SE) {
1105 // Zero/One operand expressions
1106 switch (S->getSCEVType()) {
1107 case scUnknown:
1108 case scConstant:
1109 case scVScale:
1110 return false;
1111 case scTruncate:
1112 return isHighCostExpansion(cast<SCEVTruncateExpr>(S)->getOperand(),
1113 Processed, SE);
1114 case scZeroExtend:
1115 return isHighCostExpansion(cast<SCEVZeroExtendExpr>(S)->getOperand(),
1116 Processed, SE);
1117 case scSignExtend:
1118 return isHighCostExpansion(cast<SCEVSignExtendExpr>(S)->getOperand(),
1119 Processed, SE);
1120 default:
1121 break;
1122 }
1123
1124 if (!Processed.insert(S).second)
1125 return false;
1126
1127 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
1128 for (const SCEV *S : Add->operands()) {
1129 if (isHighCostExpansion(S, Processed, SE))
1130 return true;
1131 }
1132 return false;
1133 }
1134
1135 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
1136 if (Mul->getNumOperands() == 2) {
1137 // Multiplication by a constant is ok
1138 if (isa<SCEVConstant>(Mul->getOperand(0)))
1139 return isHighCostExpansion(Mul->getOperand(1), Processed, SE);
1140
1141 // If we have the value of one operand, check if an existing
1142 // multiplication already generates this expression.
1143 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Mul->getOperand(1))) {
1144 Value *UVal = U->getValue();
1145 for (User *UR : UVal->users()) {
1146 // If U is a constant, it may be used by a ConstantExpr.
1147 Instruction *UI = dyn_cast<Instruction>(UR);
1148 if (UI && UI->getOpcode() == Instruction::Mul &&
1149 SE.isSCEVable(UI->getType())) {
1150 return SE.getSCEV(UI) == Mul;
1151 }
1152 }
1153 }
1154 }
1155 }
1156
1157 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
1158 if (isExistingPhi(AR, SE))
1159 return false;
1160 }
1161
1162 // Fow now, consider any other type of expression (div/mul/min/max) high cost.
1163 return true;
1164}
1165
1166namespace {
1167
1168class LSRUse;
1169
1170} // end anonymous namespace
1171
1172/// Check if the addressing mode defined by \p F is completely
1173/// folded in \p LU at isel time.
1174/// This includes address-mode folding and special icmp tricks.
1175/// This function returns true if \p LU can accommodate what \p F
1176/// defines and up to 1 base + 1 scaled + offset.
1177/// In other words, if \p F has several base registers, this function may
1178/// still return true. Therefore, users still need to account for
1179/// additional base registers and/or unfolded offsets to derive an
1180/// accurate cost model.
1182 const LSRUse &LU, const Formula &F);
1183
1184// Get the cost of the scaling factor used in F for LU.
1186 const LSRUse &LU, const Formula &F,
1187 const Loop &L);
1188
1189namespace {
1190
1191/// This class is used to measure and compare candidate formulae.
1192class Cost {
1193 const Loop *L = nullptr;
1194 ScalarEvolution *SE = nullptr;
1195 const TargetTransformInfo *TTI = nullptr;
1198
1199public:
1200 Cost() = delete;
1201 Cost(const Loop *L, ScalarEvolution &SE, const TargetTransformInfo &TTI,
1203 L(L), SE(&SE), TTI(&TTI), AMK(AMK) {
1204 C.Insns = 0;
1205 C.NumRegs = 0;
1206 C.AddRecCost = 0;
1207 C.NumIVMuls = 0;
1208 C.NumBaseAdds = 0;
1209 C.ImmCost = 0;
1210 C.SetupCost = 0;
1211 C.ScaleCost = 0;
1212 }
1213
1214 bool isLess(const Cost &Other) const;
1215
1216 void Lose();
1217
1218#ifndef NDEBUG
1219 // Once any of the metrics loses, they must all remain losers.
1220 bool isValid() {
1221 return ((C.Insns | C.NumRegs | C.AddRecCost | C.NumIVMuls | C.NumBaseAdds
1222 | C.ImmCost | C.SetupCost | C.ScaleCost) != ~0u)
1223 || ((C.Insns & C.NumRegs & C.AddRecCost & C.NumIVMuls & C.NumBaseAdds
1224 & C.ImmCost & C.SetupCost & C.ScaleCost) == ~0u);
1225 }
1226#endif
1227
1228 bool isLoser() {
1229 assert(isValid() && "invalid cost");
1230 return C.NumRegs == ~0u;
1231 }
1232
1233 void RateFormula(const Formula &F,
1235 const DenseSet<const SCEV *> &VisitedRegs,
1236 const LSRUse &LU,
1237 SmallPtrSetImpl<const SCEV *> *LoserRegs = nullptr);
1238
1239 void print(raw_ostream &OS) const;
1240 void dump() const;
1241
1242private:
1243 void RateRegister(const Formula &F, const SCEV *Reg,
1245 void RatePrimaryRegister(const Formula &F, const SCEV *Reg,
1248};
1249
1250/// An operand value in an instruction which is to be replaced with some
1251/// equivalent, possibly strength-reduced, replacement.
1252struct LSRFixup {
1253 /// The instruction which will be updated.
1254 Instruction *UserInst = nullptr;
1255
1256 /// The operand of the instruction which will be replaced. The operand may be
1257 /// used more than once; every instance will be replaced.
1258 Value *OperandValToReplace = nullptr;
1259
1260 /// If this user is to use the post-incremented value of an induction
1261 /// variable, this set is non-empty and holds the loops associated with the
1262 /// induction variable.
1263 PostIncLoopSet PostIncLoops;
1264
1265 /// A constant offset to be added to the LSRUse expression. This allows
1266 /// multiple fixups to share the same LSRUse with different offsets, for
1267 /// example in an unrolled loop.
1268 Immediate Offset = Immediate::getZero();
1269
1270 LSRFixup() = default;
1271
1272 bool isUseFullyOutsideLoop(const Loop *L) const;
1273
1274 void print(raw_ostream &OS) const;
1275 void dump() const;
1276};
1277
1278/// A DenseMapInfo implementation for holding DenseMaps and DenseSets of sorted
1279/// SmallVectors of const SCEV*.
1280struct UniquifierDenseMapInfo {
1281 static SmallVector<const SCEV *, 4> getEmptyKey() {
1283 V.push_back(reinterpret_cast<const SCEV *>(-1));
1284 return V;
1285 }
1286
1287 static SmallVector<const SCEV *, 4> getTombstoneKey() {
1289 V.push_back(reinterpret_cast<const SCEV *>(-2));
1290 return V;
1291 }
1292
1293 static unsigned getHashValue(const SmallVector<const SCEV *, 4> &V) {
1294 return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
1295 }
1296
1297 static bool isEqual(const SmallVector<const SCEV *, 4> &LHS,
1299 return LHS == RHS;
1300 }
1301};
1302
1303/// This class holds the state that LSR keeps for each use in IVUsers, as well
1304/// as uses invented by LSR itself. It includes information about what kinds of
1305/// things can be folded into the user, information about the user itself, and
1306/// information about how the use may be satisfied. TODO: Represent multiple
1307/// users of the same expression in common?
1308class LSRUse {
1309 DenseSet<SmallVector<const SCEV *, 4>, UniquifierDenseMapInfo> Uniquifier;
1310
1311public:
1312 /// An enum for a kind of use, indicating what types of scaled and immediate
1313 /// operands it might support.
1314 enum KindType {
1315 Basic, ///< A normal use, with no folding.
1316 Special, ///< A special case of basic, allowing -1 scales.
1317 Address, ///< An address use; folding according to TargetLowering
1318 ICmpZero ///< An equality icmp with both operands folded into one.
1319 // TODO: Add a generic icmp too?
1320 };
1321
1322 using SCEVUseKindPair = PointerIntPair<const SCEV *, 2, KindType>;
1323
1324 KindType Kind;
1325 MemAccessTy AccessTy;
1326
1327 /// The list of operands which are to be replaced.
1329
1330 /// Keep track of the min and max offsets of the fixups.
1331 Immediate MinOffset = Immediate::getFixedMax();
1332 Immediate MaxOffset = Immediate::getFixedMin();
1333
1334 /// This records whether all of the fixups using this LSRUse are outside of
1335 /// the loop, in which case some special-case heuristics may be used.
1336 bool AllFixupsOutsideLoop = true;
1337
1338 /// RigidFormula is set to true to guarantee that this use will be associated
1339 /// with a single formula--the one that initially matched. Some SCEV
1340 /// expressions cannot be expanded. This allows LSR to consider the registers
1341 /// used by those expressions without the need to expand them later after
1342 /// changing the formula.
1343 bool RigidFormula = false;
1344
1345 /// This records the widest use type for any fixup using this
1346 /// LSRUse. FindUseWithSimilarFormula can't consider uses with different max
1347 /// fixup widths to be equivalent, because the narrower one may be relying on
1348 /// the implicit truncation to truncate away bogus bits.
1349 Type *WidestFixupType = nullptr;
1350
1351 /// A list of ways to build a value that can satisfy this user. After the
1352 /// list is populated, one of these is selected heuristically and used to
1353 /// formulate a replacement for OperandValToReplace in UserInst.
1354 SmallVector<Formula, 12> Formulae;
1355
1356 /// The set of register candidates used by all formulae in this LSRUse.
1358
1359 LSRUse(KindType K, MemAccessTy AT) : Kind(K), AccessTy(AT) {}
1360
1361 LSRFixup &getNewFixup() {
1362 Fixups.push_back(LSRFixup());
1363 return Fixups.back();
1364 }
1365
1366 void pushFixup(LSRFixup &f) {
1367 Fixups.push_back(f);
1368 if (Immediate::isKnownGT(f.Offset, MaxOffset))
1369 MaxOffset = f.Offset;
1370 if (Immediate::isKnownLT(f.Offset, MinOffset))
1371 MinOffset = f.Offset;
1372 }
1373
1374 bool HasFormulaWithSameRegs(const Formula &F) const;
1375 float getNotSelectedProbability(const SCEV *Reg) const;
1376 bool InsertFormula(const Formula &F, const Loop &L);
1377 void DeleteFormula(Formula &F);
1378 void RecomputeRegs(size_t LUIdx, RegUseTracker &Reguses);
1379
1380 void print(raw_ostream &OS) const;
1381 void dump() const;
1382};
1383
1384} // end anonymous namespace
1385
1387 LSRUse::KindType Kind, MemAccessTy AccessTy,
1388 GlobalValue *BaseGV, Immediate BaseOffset,
1389 bool HasBaseReg, int64_t Scale,
1390 Instruction *Fixup = nullptr);
1391
1392static unsigned getSetupCost(const SCEV *Reg, unsigned Depth) {
1393 if (isa<SCEVUnknown>(Reg) || isa<SCEVConstant>(Reg))
1394 return 1;
1395 if (Depth == 0)
1396 return 0;
1397 if (const auto *S = dyn_cast<SCEVAddRecExpr>(Reg))
1398 return getSetupCost(S->getStart(), Depth - 1);
1399 if (auto S = dyn_cast<SCEVIntegralCastExpr>(Reg))
1400 return getSetupCost(S->getOperand(), Depth - 1);
1401 if (auto S = dyn_cast<SCEVNAryExpr>(Reg))
1402 return std::accumulate(S->operands().begin(), S->operands().end(), 0,
1403 [&](unsigned i, const SCEV *Reg) {
1404 return i + getSetupCost(Reg, Depth - 1);
1405 });
1406 if (auto S = dyn_cast<SCEVUDivExpr>(Reg))
1407 return getSetupCost(S->getLHS(), Depth - 1) +
1408 getSetupCost(S->getRHS(), Depth - 1);
1409 return 0;
1410}
1411
1412/// Tally up interesting quantities from the given register.
1413void Cost::RateRegister(const Formula &F, const SCEV *Reg,
1415 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Reg)) {
1416 // If this is an addrec for another loop, it should be an invariant
1417 // with respect to L since L is the innermost loop (at least
1418 // for now LSR only handles innermost loops).
1419 if (AR->getLoop() != L) {
1420 // If the AddRec exists, consider it's register free and leave it alone.
1421 if (isExistingPhi(AR, *SE) && AMK != TTI::AMK_PostIndexed)
1422 return;
1423
1424 // It is bad to allow LSR for current loop to add induction variables
1425 // for its sibling loops.
1426 if (!AR->getLoop()->contains(L)) {
1427 Lose();
1428 return;
1429 }
1430
1431 // Otherwise, it will be an invariant with respect to Loop L.
1432 ++C.NumRegs;
1433 return;
1434 }
1435
1436 unsigned LoopCost = 1;
1437 if (TTI->isIndexedLoadLegal(TTI->MIM_PostInc, AR->getType()) ||
1438 TTI->isIndexedStoreLegal(TTI->MIM_PostInc, AR->getType())) {
1439
1440 // If the step size matches the base offset, we could use pre-indexed
1441 // addressing.
1442 if (AMK == TTI::AMK_PreIndexed && F.BaseOffset.isFixed()) {
1443 if (auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*SE)))
1444 if (Step->getAPInt() == F.BaseOffset.getFixedValue())
1445 LoopCost = 0;
1446 } else if (AMK == TTI::AMK_PostIndexed) {
1447 const SCEV *LoopStep = AR->getStepRecurrence(*SE);
1448 if (isa<SCEVConstant>(LoopStep)) {
1449 const SCEV *LoopStart = AR->getStart();
1450 if (!isa<SCEVConstant>(LoopStart) &&
1451 SE->isLoopInvariant(LoopStart, L))
1452 LoopCost = 0;
1453 }
1454 }
1455 }
1456 C.AddRecCost += LoopCost;
1457
1458 // Add the step value register, if it needs one.
1459 // TODO: The non-affine case isn't precisely modeled here.
1460 if (!AR->isAffine() || !isa<SCEVConstant>(AR->getOperand(1))) {
1461 if (!Regs.count(AR->getOperand(1))) {
1462 RateRegister(F, AR->getOperand(1), Regs);
1463 if (isLoser())
1464 return;
1465 }
1466 }
1467 }
1468 ++C.NumRegs;
1469
1470 // Rough heuristic; favor registers which don't require extra setup
1471 // instructions in the preheader.
1472 C.SetupCost += getSetupCost(Reg, SetupCostDepthLimit);
1473 // Ensure we don't, even with the recusion limit, produce invalid costs.
1474 C.SetupCost = std::min<unsigned>(C.SetupCost, 1 << 16);
1475
1476 C.NumIVMuls += isa<SCEVMulExpr>(Reg) &&
1477 SE->hasComputableLoopEvolution(Reg, L);
1478}
1479
1480/// Record this register in the set. If we haven't seen it before, rate
1481/// it. Optional LoserRegs provides a way to declare any formula that refers to
1482/// one of those regs an instant loser.
1483void Cost::RatePrimaryRegister(const Formula &F, const SCEV *Reg,
1485 SmallPtrSetImpl<const SCEV *> *LoserRegs) {
1486 if (LoserRegs && LoserRegs->count(Reg)) {
1487 Lose();
1488 return;
1489 }
1490 if (Regs.insert(Reg).second) {
1491 RateRegister(F, Reg, Regs);
1492 if (LoserRegs && isLoser())
1493 LoserRegs->insert(Reg);
1494 }
1495}
1496
1497void Cost::RateFormula(const Formula &F,
1499 const DenseSet<const SCEV *> &VisitedRegs,
1500 const LSRUse &LU,
1501 SmallPtrSetImpl<const SCEV *> *LoserRegs) {
1502 if (isLoser())
1503 return;
1504 assert(F.isCanonical(*L) && "Cost is accurate only for canonical formula");
1505 // Tally up the registers.
1506 unsigned PrevAddRecCost = C.AddRecCost;
1507 unsigned PrevNumRegs = C.NumRegs;
1508 unsigned PrevNumBaseAdds = C.NumBaseAdds;
1509 if (const SCEV *ScaledReg = F.ScaledReg) {
1510 if (VisitedRegs.count(ScaledReg)) {
1511 Lose();
1512 return;
1513 }
1514 RatePrimaryRegister(F, ScaledReg, Regs, LoserRegs);
1515 if (isLoser())
1516 return;
1517 }
1518 for (const SCEV *BaseReg : F.BaseRegs) {
1519 if (VisitedRegs.count(BaseReg)) {
1520 Lose();
1521 return;
1522 }
1523 RatePrimaryRegister(F, BaseReg, Regs, LoserRegs);
1524 if (isLoser())
1525 return;
1526 }
1527
1528 // Determine how many (unfolded) adds we'll need inside the loop.
1529 size_t NumBaseParts = F.getNumRegs();
1530 if (NumBaseParts > 1)
1531 // Do not count the base and a possible second register if the target
1532 // allows to fold 2 registers.
1533 C.NumBaseAdds +=
1534 NumBaseParts - (1 + (F.Scale && isAMCompletelyFolded(*TTI, LU, F)));
1535 C.NumBaseAdds += (F.UnfoldedOffset.isNonZero());
1536
1537 // Accumulate non-free scaling amounts.
1538 C.ScaleCost += *getScalingFactorCost(*TTI, LU, F, *L).getValue();
1539
1540 // Tally up the non-zero immediates.
1541 for (const LSRFixup &Fixup : LU.Fixups) {
1542 if (Fixup.Offset.isCompatibleImmediate(F.BaseOffset)) {
1543 Immediate Offset = Fixup.Offset.addUnsigned(F.BaseOffset);
1544 if (F.BaseGV)
1545 C.ImmCost += 64; // Handle symbolic values conservatively.
1546 // TODO: This should probably be the pointer size.
1547 else if (Offset.isNonZero())
1548 C.ImmCost +=
1549 APInt(64, Offset.getKnownMinValue(), true).getSignificantBits();
1550
1551 // Check with target if this offset with this instruction is
1552 // specifically not supported.
1553 if (LU.Kind == LSRUse::Address && Offset.isNonZero() &&
1554 !isAMCompletelyFolded(*TTI, LSRUse::Address, LU.AccessTy, F.BaseGV,
1555 Offset, F.HasBaseReg, F.Scale, Fixup.UserInst))
1556 C.NumBaseAdds++;
1557 } else {
1558 // Incompatible immediate type, increase cost to avoid using
1559 C.ImmCost += 2048;
1560 }
1561 }
1562
1563 // If we don't count instruction cost exit here.
1564 if (!InsnsCost) {
1565 assert(isValid() && "invalid cost");
1566 return;
1567 }
1568
1569 // Treat every new register that exceeds TTI.getNumberOfRegisters() - 1 as
1570 // additional instruction (at least fill).
1571 // TODO: Need distinguish register class?
1572 unsigned TTIRegNum = TTI->getNumberOfRegisters(
1573 TTI->getRegisterClassForType(false, F.getType())) - 1;
1574 if (C.NumRegs > TTIRegNum) {
1575 // Cost already exceeded TTIRegNum, then only newly added register can add
1576 // new instructions.
1577 if (PrevNumRegs > TTIRegNum)
1578 C.Insns += (C.NumRegs - PrevNumRegs);
1579 else
1580 C.Insns += (C.NumRegs - TTIRegNum);
1581 }
1582
1583 // If ICmpZero formula ends with not 0, it could not be replaced by
1584 // just add or sub. We'll need to compare final result of AddRec.
1585 // That means we'll need an additional instruction. But if the target can
1586 // macro-fuse a compare with a branch, don't count this extra instruction.
1587 // For -10 + {0, +, 1}:
1588 // i = i + 1;
1589 // cmp i, 10
1590 //
1591 // For {-10, +, 1}:
1592 // i = i + 1;
1593 if (LU.Kind == LSRUse::ICmpZero && !F.hasZeroEnd() &&
1594 !TTI->canMacroFuseCmp())
1595 C.Insns++;
1596 // Each new AddRec adds 1 instruction to calculation.
1597 C.Insns += (C.AddRecCost - PrevAddRecCost);
1598
1599 // BaseAdds adds instructions for unfolded registers.
1600 if (LU.Kind != LSRUse::ICmpZero)
1601 C.Insns += C.NumBaseAdds - PrevNumBaseAdds;
1602 assert(isValid() && "invalid cost");
1603}
1604
1605/// Set this cost to a losing value.
1606void Cost::Lose() {
1607 C.Insns = std::numeric_limits<unsigned>::max();
1608 C.NumRegs = std::numeric_limits<unsigned>::max();
1609 C.AddRecCost = std::numeric_limits<unsigned>::max();
1610 C.NumIVMuls = std::numeric_limits<unsigned>::max();
1611 C.NumBaseAdds = std::numeric_limits<unsigned>::max();
1612 C.ImmCost = std::numeric_limits<unsigned>::max();
1613 C.SetupCost = std::numeric_limits<unsigned>::max();
1614 C.ScaleCost = std::numeric_limits<unsigned>::max();
1615}
1616
1617/// Choose the lower cost.
1618bool Cost::isLess(const Cost &Other) const {
1619 if (InsnsCost.getNumOccurrences() > 0 && InsnsCost &&
1620 C.Insns != Other.C.Insns)
1621 return C.Insns < Other.C.Insns;
1622 return TTI->isLSRCostLess(C, Other.C);
1623}
1624
1625#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1626void Cost::print(raw_ostream &OS) const {
1627 if (InsnsCost)
1628 OS << C.Insns << " instruction" << (C.Insns == 1 ? " " : "s ");
1629 OS << C.NumRegs << " reg" << (C.NumRegs == 1 ? "" : "s");
1630 if (C.AddRecCost != 0)
1631 OS << ", with addrec cost " << C.AddRecCost;
1632 if (C.NumIVMuls != 0)
1633 OS << ", plus " << C.NumIVMuls << " IV mul"
1634 << (C.NumIVMuls == 1 ? "" : "s");
1635 if (C.NumBaseAdds != 0)
1636 OS << ", plus " << C.NumBaseAdds << " base add"
1637 << (C.NumBaseAdds == 1 ? "" : "s");
1638 if (C.ScaleCost != 0)
1639 OS << ", plus " << C.ScaleCost << " scale cost";
1640 if (C.ImmCost != 0)
1641 OS << ", plus " << C.ImmCost << " imm cost";
1642 if (C.SetupCost != 0)
1643 OS << ", plus " << C.SetupCost << " setup cost";
1644}
1645
1646LLVM_DUMP_METHOD void Cost::dump() const {
1647 print(errs()); errs() << '\n';
1648}
1649#endif
1650
1651/// Test whether this fixup always uses its value outside of the given loop.
1652bool LSRFixup::isUseFullyOutsideLoop(const Loop *L) const {
1653 // PHI nodes use their value in their incoming blocks.
1654 if (const PHINode *PN = dyn_cast<PHINode>(UserInst)) {
1655 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1656 if (PN->getIncomingValue(i) == OperandValToReplace &&
1657 L->contains(PN->getIncomingBlock(i)))
1658 return false;
1659 return true;
1660 }
1661
1662 return !L->contains(UserInst);
1663}
1664
1665#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1666void LSRFixup::print(raw_ostream &OS) const {
1667 OS << "UserInst=";
1668 // Store is common and interesting enough to be worth special-casing.
1669 if (StoreInst *Store = dyn_cast<StoreInst>(UserInst)) {
1670 OS << "store ";
1671 Store->getOperand(0)->printAsOperand(OS, /*PrintType=*/false);
1672 } else if (UserInst->getType()->isVoidTy())
1673 OS << UserInst->getOpcodeName();
1674 else
1675 UserInst->printAsOperand(OS, /*PrintType=*/false);
1676
1677 OS << ", OperandValToReplace=";
1678 OperandValToReplace->printAsOperand(OS, /*PrintType=*/false);
1679
1680 for (const Loop *PIL : PostIncLoops) {
1681 OS << ", PostIncLoop=";
1682 PIL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
1683 }
1684
1685 if (Offset.isNonZero())
1686 OS << ", Offset=" << Offset;
1687}
1688
1689LLVM_DUMP_METHOD void LSRFixup::dump() const {
1690 print(errs()); errs() << '\n';
1691}
1692#endif
1693
1694/// Test whether this use as a formula which has the same registers as the given
1695/// formula.
1696bool LSRUse::HasFormulaWithSameRegs(const Formula &F) const {
1698 if (F.ScaledReg) Key.push_back(F.ScaledReg);
1699 // Unstable sort by host order ok, because this is only used for uniquifying.
1700 llvm::sort(Key);
1701 return Uniquifier.count(Key);
1702}
1703
1704/// The function returns a probability of selecting formula without Reg.
1705float LSRUse::getNotSelectedProbability(const SCEV *Reg) const {
1706 unsigned FNum = 0;
1707 for (const Formula &F : Formulae)
1708 if (F.referencesReg(Reg))
1709 FNum++;
1710 return ((float)(Formulae.size() - FNum)) / Formulae.size();
1711}
1712
1713/// If the given formula has not yet been inserted, add it to the list, and
1714/// return true. Return false otherwise. The formula must be in canonical form.
1715bool LSRUse::InsertFormula(const Formula &F, const Loop &L) {
1716 assert(F.isCanonical(L) && "Invalid canonical representation");
1717
1718 if (!Formulae.empty() && RigidFormula)
1719 return false;
1720
1722 if (F.ScaledReg) Key.push_back(F.ScaledReg);
1723 // Unstable sort by host order ok, because this is only used for uniquifying.
1724 llvm::sort(Key);
1725
1726 if (!Uniquifier.insert(Key).second)
1727 return false;
1728
1729 // Using a register to hold the value of 0 is not profitable.
1730 assert((!F.ScaledReg || !F.ScaledReg->isZero()) &&
1731 "Zero allocated in a scaled register!");
1732#ifndef NDEBUG
1733 for (const SCEV *BaseReg : F.BaseRegs)
1734 assert(!BaseReg->isZero() && "Zero allocated in a base register!");
1735#endif
1736
1737 // Add the formula to the list.
1738 Formulae.push_back(F);
1739
1740 // Record registers now being used by this use.
1741 Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
1742 if (F.ScaledReg)
1743 Regs.insert(F.ScaledReg);
1744
1745 return true;
1746}
1747
1748/// Remove the given formula from this use's list.
1749void LSRUse::DeleteFormula(Formula &F) {
1750 if (&F != &Formulae.back())
1751 std::swap(F, Formulae.back());
1752 Formulae.pop_back();
1753}
1754
1755/// Recompute the Regs field, and update RegUses.
1756void LSRUse::RecomputeRegs(size_t LUIdx, RegUseTracker &RegUses) {
1757 // Now that we've filtered out some formulae, recompute the Regs set.
1758 SmallPtrSet<const SCEV *, 4> OldRegs = std::move(Regs);
1759 Regs.clear();
1760 for (const Formula &F : Formulae) {
1761 if (F.ScaledReg) Regs.insert(F.ScaledReg);
1762 Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
1763 }
1764
1765 // Update the RegTracker.
1766 for (const SCEV *S : OldRegs)
1767 if (!Regs.count(S))
1768 RegUses.dropRegister(S, LUIdx);
1769}
1770
1771#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1772void LSRUse::print(raw_ostream &OS) const {
1773 OS << "LSR Use: Kind=";
1774 switch (Kind) {
1775 case Basic: OS << "Basic"; break;
1776 case Special: OS << "Special"; break;
1777 case ICmpZero: OS << "ICmpZero"; break;
1778 case Address:
1779 OS << "Address of ";
1780 if (AccessTy.MemTy->isPointerTy())
1781 OS << "pointer"; // the full pointer type could be really verbose
1782 else {
1783 OS << *AccessTy.MemTy;
1784 }
1785
1786 OS << " in addrspace(" << AccessTy.AddrSpace << ')';
1787 }
1788
1789 OS << ", Offsets={";
1790 bool NeedComma = false;
1791 for (const LSRFixup &Fixup : Fixups) {
1792 if (NeedComma) OS << ',';
1793 OS << Fixup.Offset;
1794 NeedComma = true;
1795 }
1796 OS << '}';
1797
1798 if (AllFixupsOutsideLoop)
1799 OS << ", all-fixups-outside-loop";
1800
1801 if (WidestFixupType)
1802 OS << ", widest fixup type: " << *WidestFixupType;
1803}
1804
1805LLVM_DUMP_METHOD void LSRUse::dump() const {
1806 print(errs()); errs() << '\n';
1807}
1808#endif
1809
1811 LSRUse::KindType Kind, MemAccessTy AccessTy,
1812 GlobalValue *BaseGV, Immediate BaseOffset,
1813 bool HasBaseReg, int64_t Scale,
1814 Instruction *Fixup /* = nullptr */) {
1815 switch (Kind) {
1816 case LSRUse::Address: {
1817 int64_t FixedOffset =
1818 BaseOffset.isScalable() ? 0 : BaseOffset.getFixedValue();
1819 int64_t ScalableOffset =
1820 BaseOffset.isScalable() ? BaseOffset.getKnownMinValue() : 0;
1821 return TTI.isLegalAddressingMode(AccessTy.MemTy, BaseGV, FixedOffset,
1822 HasBaseReg, Scale, AccessTy.AddrSpace,
1823 Fixup, ScalableOffset);
1824 }
1825 case LSRUse::ICmpZero:
1826 // There's not even a target hook for querying whether it would be legal to
1827 // fold a GV into an ICmp.
1828 if (BaseGV)
1829 return false;
1830
1831 // ICmp only has two operands; don't allow more than two non-trivial parts.
1832 if (Scale != 0 && HasBaseReg && BaseOffset.isNonZero())
1833 return false;
1834
1835 // ICmp only supports no scale or a -1 scale, as we can "fold" a -1 scale by
1836 // putting the scaled register in the other operand of the icmp.
1837 if (Scale != 0 && Scale != -1)
1838 return false;
1839
1840 // If we have low-level target information, ask the target if it can fold an
1841 // integer immediate on an icmp.
1842 if (BaseOffset.isNonZero()) {
1843 // We don't have an interface to query whether the target supports
1844 // icmpzero against scalable quantities yet.
1845 if (BaseOffset.isScalable())
1846 return false;
1847
1848 // We have one of:
1849 // ICmpZero BaseReg + BaseOffset => ICmp BaseReg, -BaseOffset
1850 // ICmpZero -1*ScaleReg + BaseOffset => ICmp ScaleReg, BaseOffset
1851 // Offs is the ICmp immediate.
1852 if (Scale == 0)
1853 // The cast does the right thing with
1854 // std::numeric_limits<int64_t>::min().
1855 BaseOffset = BaseOffset.getFixed(-(uint64_t)BaseOffset.getFixedValue());
1856 return TTI.isLegalICmpImmediate(BaseOffset.getFixedValue());
1857 }
1858
1859 // ICmpZero BaseReg + -1*ScaleReg => ICmp BaseReg, ScaleReg
1860 return true;
1861
1862 case LSRUse::Basic:
1863 // Only handle single-register values.
1864 return !BaseGV && Scale == 0 && BaseOffset.isZero();
1865
1866 case LSRUse::Special:
1867 // Special case Basic to handle -1 scales.
1868 return !BaseGV && (Scale == 0 || Scale == -1) && BaseOffset.isZero();
1869 }
1870
1871 llvm_unreachable("Invalid LSRUse Kind!");
1872}
1873
1875 Immediate MinOffset, Immediate MaxOffset,
1876 LSRUse::KindType Kind, MemAccessTy AccessTy,
1877 GlobalValue *BaseGV, Immediate BaseOffset,
1878 bool HasBaseReg, int64_t Scale) {
1879 if (BaseOffset.isNonZero() &&
1880 (BaseOffset.isScalable() != MinOffset.isScalable() ||
1881 BaseOffset.isScalable() != MaxOffset.isScalable()))
1882 return false;
1883 // Check for overflow.
1884 int64_t Base = BaseOffset.getKnownMinValue();
1885 int64_t Min = MinOffset.getKnownMinValue();
1886 int64_t Max = MaxOffset.getKnownMinValue();
1887 if (((int64_t)((uint64_t)Base + Min) > Base) != (Min > 0))
1888 return false;
1889 MinOffset = Immediate::get((uint64_t)Base + Min, MinOffset.isScalable());
1890 if (((int64_t)((uint64_t)Base + Max) > Base) != (Max > 0))
1891 return false;
1892 MaxOffset = Immediate::get((uint64_t)Base + Max, MaxOffset.isScalable());
1893
1894 return isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, MinOffset,
1895 HasBaseReg, Scale) &&
1896 isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, MaxOffset,
1897 HasBaseReg, Scale);
1898}
1899
1901 Immediate MinOffset, Immediate MaxOffset,
1902 LSRUse::KindType Kind, MemAccessTy AccessTy,
1903 const Formula &F, const Loop &L) {
1904 // For the purpose of isAMCompletelyFolded either having a canonical formula
1905 // or a scale not equal to zero is correct.
1906 // Problems may arise from non canonical formulae having a scale == 0.
1907 // Strictly speaking it would best to just rely on canonical formulae.
1908 // However, when we generate the scaled formulae, we first check that the
1909 // scaling factor is profitable before computing the actual ScaledReg for
1910 // compile time sake.
1911 assert((F.isCanonical(L) || F.Scale != 0));
1912 return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy,
1913 F.BaseGV, F.BaseOffset, F.HasBaseReg, F.Scale);
1914}
1915
1916/// Test whether we know how to expand the current formula.
1917static bool isLegalUse(const TargetTransformInfo &TTI, Immediate MinOffset,
1918 Immediate MaxOffset, LSRUse::KindType Kind,
1919 MemAccessTy AccessTy, GlobalValue *BaseGV,
1920 Immediate BaseOffset, bool HasBaseReg, int64_t Scale) {
1921 // We know how to expand completely foldable formulae.
1922 return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy, BaseGV,
1923 BaseOffset, HasBaseReg, Scale) ||
1924 // Or formulae that use a base register produced by a sum of base
1925 // registers.
1926 (Scale == 1 &&
1927 isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy,
1928 BaseGV, BaseOffset, true, 0));
1929}
1930
1931static bool isLegalUse(const TargetTransformInfo &TTI, Immediate MinOffset,
1932 Immediate MaxOffset, LSRUse::KindType Kind,
1933 MemAccessTy AccessTy, const Formula &F) {
1934 return isLegalUse(TTI, MinOffset, MaxOffset, Kind, AccessTy, F.BaseGV,
1935 F.BaseOffset, F.HasBaseReg, F.Scale);
1936}
1937
1939 Immediate Offset) {
1940 if (Offset.isScalable())
1941 return TTI.isLegalAddScalableImmediate(Offset.getKnownMinValue());
1942
1943 return TTI.isLegalAddImmediate(Offset.getFixedValue());
1944}
1945
1947 const LSRUse &LU, const Formula &F) {
1948 // Target may want to look at the user instructions.
1949 if (LU.Kind == LSRUse::Address && TTI.LSRWithInstrQueries()) {
1950 for (const LSRFixup &Fixup : LU.Fixups)
1951 if (!isAMCompletelyFolded(TTI, LSRUse::Address, LU.AccessTy, F.BaseGV,
1952 (F.BaseOffset + Fixup.Offset), F.HasBaseReg,
1953 F.Scale, Fixup.UserInst))
1954 return false;
1955 return true;
1956 }
1957
1958 return isAMCompletelyFolded(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind,
1959 LU.AccessTy, F.BaseGV, F.BaseOffset, F.HasBaseReg,
1960 F.Scale);
1961}
1962
1964 const LSRUse &LU, const Formula &F,
1965 const Loop &L) {
1966 if (!F.Scale)
1967 return 0;
1968
1969 // If the use is not completely folded in that instruction, we will have to
1970 // pay an extra cost only for scale != 1.
1971 if (!isAMCompletelyFolded(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind,
1972 LU.AccessTy, F, L))
1973 return F.Scale != 1;
1974
1975 switch (LU.Kind) {
1976 case LSRUse::Address: {
1977 // Check the scaling factor cost with both the min and max offsets.
1978 int64_t ScalableMin = 0, ScalableMax = 0, FixedMin = 0, FixedMax = 0;
1979 if (F.BaseOffset.isScalable()) {
1980 ScalableMin = (F.BaseOffset + LU.MinOffset).getKnownMinValue();
1981 ScalableMax = (F.BaseOffset + LU.MaxOffset).getKnownMinValue();
1982 } else {
1983 FixedMin = (F.BaseOffset + LU.MinOffset).getFixedValue();
1984 FixedMax = (F.BaseOffset + LU.MaxOffset).getFixedValue();
1985 }
1986 InstructionCost ScaleCostMinOffset = TTI.getScalingFactorCost(
1987 LU.AccessTy.MemTy, F.BaseGV, StackOffset::get(FixedMin, ScalableMin),
1988 F.HasBaseReg, F.Scale, LU.AccessTy.AddrSpace);
1989 InstructionCost ScaleCostMaxOffset = TTI.getScalingFactorCost(
1990 LU.AccessTy.MemTy, F.BaseGV, StackOffset::get(FixedMax, ScalableMax),
1991 F.HasBaseReg, F.Scale, LU.AccessTy.AddrSpace);
1992
1993 assert(ScaleCostMinOffset.isValid() && ScaleCostMaxOffset.isValid() &&
1994 "Legal addressing mode has an illegal cost!");
1995 return std::max(ScaleCostMinOffset, ScaleCostMaxOffset);
1996 }
1997 case LSRUse::ICmpZero:
1998 case LSRUse::Basic:
1999 case LSRUse::Special:
2000 // The use is completely folded, i.e., everything is folded into the
2001 // instruction.
2002 return 0;
2003 }
2004
2005 llvm_unreachable("Invalid LSRUse Kind!");
2006}
2007
2009 LSRUse::KindType Kind, MemAccessTy AccessTy,
2010 GlobalValue *BaseGV, Immediate BaseOffset,
2011 bool HasBaseReg) {
2012 // Fast-path: zero is always foldable.
2013 if (BaseOffset.isZero() && !BaseGV)
2014 return true;
2015
2016 // Conservatively, create an address with an immediate and a
2017 // base and a scale.
2018 int64_t Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
2019
2020 // Canonicalize a scale of 1 to a base register if the formula doesn't
2021 // already have a base register.
2022 if (!HasBaseReg && Scale == 1) {
2023 Scale = 0;
2024 HasBaseReg = true;
2025 }
2026
2027 // FIXME: Try with + without a scale? Maybe based on TTI?
2028 // I think basereg + scaledreg + immediateoffset isn't a good 'conservative'
2029 // default for many architectures, not just AArch64 SVE. More investigation
2030 // needed later to determine if this should be used more widely than just
2031 // on scalable types.
2032 if (HasBaseReg && BaseOffset.isNonZero() && Kind != LSRUse::ICmpZero &&
2033 AccessTy.MemTy && AccessTy.MemTy->isScalableTy() && DropScaledForVScale)
2034 Scale = 0;
2035
2036 return isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, BaseOffset,
2037 HasBaseReg, Scale);
2038}
2039
2041 ScalarEvolution &SE, Immediate MinOffset,
2042 Immediate MaxOffset, LSRUse::KindType Kind,
2043 MemAccessTy AccessTy, const SCEV *S,
2044 bool HasBaseReg) {
2045 // Fast-path: zero is always foldable.
2046 if (S->isZero()) return true;
2047
2048 // Conservatively, create an address with an immediate and a
2049 // base and a scale.
2050 Immediate BaseOffset = ExtractImmediate(S, SE);
2051 GlobalValue *BaseGV = ExtractSymbol(S, SE);
2052
2053 // If there's anything else involved, it's not foldable.
2054 if (!S->isZero()) return false;
2055
2056 // Fast-path: zero is always foldable.
2057 if (BaseOffset.isZero() && !BaseGV)
2058 return true;
2059
2060 if (BaseOffset.isScalable())
2061 return false;
2062
2063 // Conservatively, create an address with an immediate and a
2064 // base and a scale.
2065 int64_t Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
2066
2067 return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy, BaseGV,
2068 BaseOffset, HasBaseReg, Scale);
2069}
2070
2071namespace {
2072
2073/// An individual increment in a Chain of IV increments. Relate an IV user to
2074/// an expression that computes the IV it uses from the IV used by the previous
2075/// link in the Chain.
2076///
2077/// For the head of a chain, IncExpr holds the absolute SCEV expression for the
2078/// original IVOperand. The head of the chain's IVOperand is only valid during
2079/// chain collection, before LSR replaces IV users. During chain generation,
2080/// IncExpr can be used to find the new IVOperand that computes the same
2081/// expression.
2082struct IVInc {
2083 Instruction *UserInst;
2084 Value* IVOperand;
2085 const SCEV *IncExpr;
2086
2087 IVInc(Instruction *U, Value *O, const SCEV *E)
2088 : UserInst(U), IVOperand(O), IncExpr(E) {}
2089};
2090
2091// The list of IV increments in program order. We typically add the head of a
2092// chain without finding subsequent links.
2093struct IVChain {
2095 const SCEV *ExprBase = nullptr;
2096
2097 IVChain() = default;
2098 IVChain(const IVInc &Head, const SCEV *Base)
2099 : Incs(1, Head), ExprBase(Base) {}
2100
2102
2103 // Return the first increment in the chain.
2104 const_iterator begin() const {
2105 assert(!Incs.empty());
2106 return std::next(Incs.begin());
2107 }
2108 const_iterator end() const {
2109 return Incs.end();
2110 }
2111
2112 // Returns true if this chain contains any increments.
2113 bool hasIncs() const { return Incs.size() >= 2; }
2114
2115 // Add an IVInc to the end of this chain.
2116 void add(const IVInc &X) { Incs.push_back(X); }
2117
2118 // Returns the last UserInst in the chain.
2119 Instruction *tailUserInst() const { return Incs.back().UserInst; }
2120
2121 // Returns true if IncExpr can be profitably added to this chain.
2122 bool isProfitableIncrement(const SCEV *OperExpr,
2123 const SCEV *IncExpr,
2125};
2126
2127/// Helper for CollectChains to track multiple IV increment uses. Distinguish
2128/// between FarUsers that definitely cross IV increments and NearUsers that may
2129/// be used between IV increments.
2130struct ChainUsers {
2133};
2134
2135/// This class holds state for the main loop strength reduction logic.
2136class LSRInstance {
2137 IVUsers &IU;
2138 ScalarEvolution &SE;
2139 DominatorTree &DT;
2140 LoopInfo &LI;
2141 AssumptionCache &AC;
2142 TargetLibraryInfo &TLI;
2143 const TargetTransformInfo &TTI;
2144 Loop *const L;
2145 MemorySSAUpdater *MSSAU;
2147 mutable SCEVExpander Rewriter;
2148 bool Changed = false;
2149
2150 /// This is the insert position that the current loop's induction variable
2151 /// increment should be placed. In simple loops, this is the latch block's
2152 /// terminator. But in more complicated cases, this is a position which will
2153 /// dominate all the in-loop post-increment users.
2154 Instruction *IVIncInsertPos = nullptr;
2155
2156 /// Interesting factors between use strides.
2157 ///
2158 /// We explicitly use a SetVector which contains a SmallSet, instead of the
2159 /// default, a SmallDenseSet, because we need to use the full range of
2160 /// int64_ts, and there's currently no good way of doing that with
2161 /// SmallDenseSet.
2163
2164 /// The cost of the current SCEV, the best solution by LSR will be dropped if
2165 /// the solution is not profitable.
2166 Cost BaselineCost;
2167
2168 /// Interesting use types, to facilitate truncation reuse.
2170
2171 /// The list of interesting uses.
2173
2174 /// Track which uses use which register candidates.
2175 RegUseTracker RegUses;
2176
2177 // Limit the number of chains to avoid quadratic behavior. We don't expect to
2178 // have more than a few IV increment chains in a loop. Missing a Chain falls
2179 // back to normal LSR behavior for those uses.
2180 static const unsigned MaxChains = 8;
2181
2182 /// IV users can form a chain of IV increments.
2184
2185 /// IV users that belong to profitable IVChains.
2187
2188 /// Induction variables that were generated and inserted by the SCEV Expander.
2189 SmallVector<llvm::WeakVH, 2> ScalarEvolutionIVs;
2190
2191 // Inserting instructions in the loop and using them as PHI's input could
2192 // break LCSSA in case if PHI's parent block is not a loop exit (i.e. the
2193 // corresponding incoming block is not loop exiting). So collect all such
2194 // instructions to form LCSSA for them later.
2195 SmallSetVector<Instruction *, 4> InsertedNonLCSSAInsts;
2196
2197 void OptimizeShadowIV();
2198 bool FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse);
2199 ICmpInst *OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse);
2200 void OptimizeLoopTermCond();
2201
2202 void ChainInstruction(Instruction *UserInst, Instruction *IVOper,
2203 SmallVectorImpl<ChainUsers> &ChainUsersVec);
2204 void FinalizeChain(IVChain &Chain);
2205 void CollectChains();
2206 void GenerateIVChain(const IVChain &Chain,
2208
2209 void CollectInterestingTypesAndFactors();
2210 void CollectFixupsAndInitialFormulae();
2211
2212 // Support for sharing of LSRUses between LSRFixups.
2214 UseMapTy UseMap;
2215
2216 bool reconcileNewOffset(LSRUse &LU, Immediate NewOffset, bool HasBaseReg,
2217 LSRUse::KindType Kind, MemAccessTy AccessTy);
2218
2219 std::pair<size_t, Immediate> getUse(const SCEV *&Expr, LSRUse::KindType Kind,
2220 MemAccessTy AccessTy);
2221
2222 void DeleteUse(LSRUse &LU, size_t LUIdx);
2223
2224 LSRUse *FindUseWithSimilarFormula(const Formula &F, const LSRUse &OrigLU);
2225
2226 void InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
2227 void InsertSupplementalFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
2228 void CountRegisters(const Formula &F, size_t LUIdx);
2229 bool InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F);
2230
2231 void CollectLoopInvariantFixupsAndFormulae();
2232
2233 void GenerateReassociations(LSRUse &LU, unsigned LUIdx, Formula Base,
2234 unsigned Depth = 0);
2235
2236 void GenerateReassociationsImpl(LSRUse &LU, unsigned LUIdx,
2237 const Formula &Base, unsigned Depth,
2238 size_t Idx, bool IsScaledReg = false);
2239 void GenerateCombinations(LSRUse &LU, unsigned LUIdx, Formula Base);
2240 void GenerateSymbolicOffsetsImpl(LSRUse &LU, unsigned LUIdx,
2241 const Formula &Base, size_t Idx,
2242 bool IsScaledReg = false);
2243 void GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
2244 void GenerateConstantOffsetsImpl(LSRUse &LU, unsigned LUIdx,
2245 const Formula &Base,
2246 const SmallVectorImpl<Immediate> &Worklist,
2247 size_t Idx, bool IsScaledReg = false);
2248 void GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
2249 void GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx, Formula Base);
2250 void GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base);
2251 void GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base);
2252 void GenerateCrossUseConstantOffsets();
2253 void GenerateAllReuseFormulae();
2254
2255 void FilterOutUndesirableDedicatedRegisters();
2256
2257 size_t EstimateSearchSpaceComplexity() const;
2258 void NarrowSearchSpaceByDetectingSupersets();
2259 void NarrowSearchSpaceByCollapsingUnrolledCode();
2260 void NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters();
2261 void NarrowSearchSpaceByFilterFormulaWithSameScaledReg();
2262 void NarrowSearchSpaceByFilterPostInc();
2263 void NarrowSearchSpaceByDeletingCostlyFormulas();
2264 void NarrowSearchSpaceByPickingWinnerRegs();
2265 void NarrowSearchSpaceUsingHeuristics();
2266
2267 void SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
2268 Cost &SolutionCost,
2270 const Cost &CurCost,
2271 const SmallPtrSet<const SCEV *, 16> &CurRegs,
2272 DenseSet<const SCEV *> &VisitedRegs) const;
2273 void Solve(SmallVectorImpl<const Formula *> &Solution) const;
2274
2276 HoistInsertPosition(BasicBlock::iterator IP,
2277 const SmallVectorImpl<Instruction *> &Inputs) const;
2278 BasicBlock::iterator AdjustInsertPositionForExpand(BasicBlock::iterator IP,
2279 const LSRFixup &LF,
2280 const LSRUse &LU) const;
2281
2282 Value *Expand(const LSRUse &LU, const LSRFixup &LF, const Formula &F,
2284 SmallVectorImpl<WeakTrackingVH> &DeadInsts) const;
2285 void RewriteForPHI(PHINode *PN, const LSRUse &LU, const LSRFixup &LF,
2286 const Formula &F,
2288 void Rewrite(const LSRUse &LU, const LSRFixup &LF, const Formula &F,
2290 void ImplementSolution(const SmallVectorImpl<const Formula *> &Solution);
2291
2292public:
2293 LSRInstance(Loop *L, IVUsers &IU, ScalarEvolution &SE, DominatorTree &DT,
2295 TargetLibraryInfo &TLI, MemorySSAUpdater *MSSAU);
2296
2297 bool getChanged() const { return Changed; }
2298 const SmallVectorImpl<WeakVH> &getScalarEvolutionIVs() const {
2299 return ScalarEvolutionIVs;
2300 }
2301
2302 void print_factors_and_types(raw_ostream &OS) const;
2303 void print_fixups(raw_ostream &OS) const;
2304 void print_uses(raw_ostream &OS) const;
2305 void print(raw_ostream &OS) const;
2306 void dump() const;
2307};
2308
2309} // end anonymous namespace
2310
2311/// If IV is used in a int-to-float cast inside the loop then try to eliminate
2312/// the cast operation.
2313void LSRInstance::OptimizeShadowIV() {
2314 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
2315 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
2316 return;
2317
2318 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end();
2319 UI != E; /* empty */) {
2320 IVUsers::const_iterator CandidateUI = UI;
2321 ++UI;
2322 Instruction *ShadowUse = CandidateUI->getUser();
2323 Type *DestTy = nullptr;
2324 bool IsSigned = false;
2325
2326 /* If shadow use is a int->float cast then insert a second IV
2327 to eliminate this cast.
2328
2329 for (unsigned i = 0; i < n; ++i)
2330 foo((double)i);
2331
2332 is transformed into
2333
2334 double d = 0.0;
2335 for (unsigned i = 0; i < n; ++i, ++d)
2336 foo(d);
2337 */
2338 if (UIToFPInst *UCast = dyn_cast<UIToFPInst>(CandidateUI->getUser())) {
2339 IsSigned = false;
2340 DestTy = UCast->getDestTy();
2341 }
2342 else if (SIToFPInst *SCast = dyn_cast<SIToFPInst>(CandidateUI->getUser())) {
2343 IsSigned = true;
2344 DestTy = SCast->getDestTy();
2345 }
2346 if (!DestTy) continue;
2347
2348 // If target does not support DestTy natively then do not apply
2349 // this transformation.
2350 if (!TTI.isTypeLegal(DestTy)) continue;
2351
2352 PHINode *PH = dyn_cast<PHINode>(ShadowUse->getOperand(0));
2353 if (!PH) continue;
2354 if (PH->getNumIncomingValues() != 2) continue;
2355
2356 // If the calculation in integers overflows, the result in FP type will
2357 // differ. So we only can do this transformation if we are guaranteed to not
2358 // deal with overflowing values
2359 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(PH));
2360 if (!AR) continue;
2361 if (IsSigned && !AR->hasNoSignedWrap()) continue;
2362 if (!IsSigned && !AR->hasNoUnsignedWrap()) continue;
2363
2364 Type *SrcTy = PH->getType();
2365 int Mantissa = DestTy->getFPMantissaWidth();
2366 if (Mantissa == -1) continue;
2367 if ((int)SE.getTypeSizeInBits(SrcTy) > Mantissa)
2368 continue;
2369
2370 unsigned Entry, Latch;
2371 if (PH->getIncomingBlock(0) == L->getLoopPreheader()) {
2372 Entry = 0;
2373 Latch = 1;
2374 } else {
2375 Entry = 1;
2376 Latch = 0;
2377 }
2378
2379 ConstantInt *Init = dyn_cast<ConstantInt>(PH->getIncomingValue(Entry));
2380 if (!Init) continue;
2381 Constant *NewInit = ConstantFP::get(DestTy, IsSigned ?
2382 (double)Init->getSExtValue() :
2383 (double)Init->getZExtValue());
2384
2385 BinaryOperator *Incr =
2386 dyn_cast<BinaryOperator>(PH->getIncomingValue(Latch));
2387 if (!Incr) continue;
2388 if (Incr->getOpcode() != Instruction::Add
2389 && Incr->getOpcode() != Instruction::Sub)
2390 continue;
2391
2392 /* Initialize new IV, double d = 0.0 in above example. */
2393 ConstantInt *C = nullptr;
2394 if (Incr->getOperand(0) == PH)
2395 C = dyn_cast<ConstantInt>(Incr->getOperand(1));
2396 else if (Incr->getOperand(1) == PH)
2397 C = dyn_cast<ConstantInt>(Incr->getOperand(0));
2398 else
2399 continue;
2400
2401 if (!C) continue;
2402
2403 // Ignore negative constants, as the code below doesn't handle them
2404 // correctly. TODO: Remove this restriction.
2405 if (!C->getValue().isStrictlyPositive())
2406 continue;
2407
2408 /* Add new PHINode. */
2409 PHINode *NewPH = PHINode::Create(DestTy, 2, "IV.S.", PH->getIterator());
2410 NewPH->setDebugLoc(PH->getDebugLoc());
2411
2412 /* create new increment. '++d' in above example. */
2413 Constant *CFP = ConstantFP::get(DestTy, C->getZExtValue());
2415 Incr->getOpcode() == Instruction::Add ? Instruction::FAdd
2416 : Instruction::FSub,
2417 NewPH, CFP, "IV.S.next.", Incr->getIterator());
2418 NewIncr->setDebugLoc(Incr->getDebugLoc());
2419
2420 NewPH->addIncoming(NewInit, PH->getIncomingBlock(Entry));
2421 NewPH->addIncoming(NewIncr, PH->getIncomingBlock(Latch));
2422
2423 /* Remove cast operation */
2424 ShadowUse->replaceAllUsesWith(NewPH);
2425 ShadowUse->eraseFromParent();
2426 Changed = true;
2427 break;
2428 }
2429}
2430
2431/// If Cond has an operand that is an expression of an IV, set the IV user and
2432/// stride information and return true, otherwise return false.
2433bool LSRInstance::FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse) {
2434 for (IVStrideUse &U : IU)
2435 if (U.getUser() == Cond) {
2436 // NOTE: we could handle setcc instructions with multiple uses here, but
2437 // InstCombine does it as well for simple uses, it's not clear that it
2438 // occurs enough in real life to handle.
2439 CondUse = &U;
2440 return true;
2441 }
2442 return false;
2443}
2444
2445/// Rewrite the loop's terminating condition if it uses a max computation.
2446///
2447/// This is a narrow solution to a specific, but acute, problem. For loops
2448/// like this:
2449///
2450/// i = 0;
2451/// do {
2452/// p[i] = 0.0;
2453/// } while (++i < n);
2454///
2455/// the trip count isn't just 'n', because 'n' might not be positive. And
2456/// unfortunately this can come up even for loops where the user didn't use
2457/// a C do-while loop. For example, seemingly well-behaved top-test loops
2458/// will commonly be lowered like this:
2459///
2460/// if (n > 0) {
2461/// i = 0;
2462/// do {
2463/// p[i] = 0.0;
2464/// } while (++i < n);
2465/// }
2466///
2467/// and then it's possible for subsequent optimization to obscure the if
2468/// test in such a way that indvars can't find it.
2469///
2470/// When indvars can't find the if test in loops like this, it creates a
2471/// max expression, which allows it to give the loop a canonical
2472/// induction variable:
2473///
2474/// i = 0;
2475/// max = n < 1 ? 1 : n;
2476/// do {
2477/// p[i] = 0.0;
2478/// } while (++i != max);
2479///
2480/// Canonical induction variables are necessary because the loop passes
2481/// are designed around them. The most obvious example of this is the
2482/// LoopInfo analysis, which doesn't remember trip count values. It
2483/// expects to be able to rediscover the trip count each time it is
2484/// needed, and it does this using a simple analysis that only succeeds if
2485/// the loop has a canonical induction variable.
2486///
2487/// However, when it comes time to generate code, the maximum operation
2488/// can be quite costly, especially if it's inside of an outer loop.
2489///
2490/// This function solves this problem by detecting this type of loop and
2491/// rewriting their conditions from ICMP_NE back to ICMP_SLT, and deleting
2492/// the instructions for the maximum computation.
2493ICmpInst *LSRInstance::OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse) {
2494 // Check that the loop matches the pattern we're looking for.
2495 if (Cond->getPredicate() != CmpInst::ICMP_EQ &&
2496 Cond->getPredicate() != CmpInst::ICMP_NE)
2497 return Cond;
2498
2499 SelectInst *Sel = dyn_cast<SelectInst>(Cond->getOperand(1));
2500 if (!Sel || !Sel->hasOneUse()) return Cond;
2501
2502 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
2503 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
2504 return Cond;
2505 const SCEV *One = SE.getConstant(BackedgeTakenCount->getType(), 1);
2506
2507 // Add one to the backedge-taken count to get the trip count.
2508 const SCEV *IterationCount = SE.getAddExpr(One, BackedgeTakenCount);
2509 if (IterationCount != SE.getSCEV(Sel)) return Cond;
2510
2511 // Check for a max calculation that matches the pattern. There's no check
2512 // for ICMP_ULE here because the comparison would be with zero, which
2513 // isn't interesting.
2514 CmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
2515 const SCEVNAryExpr *Max = nullptr;
2516 if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(BackedgeTakenCount)) {
2517 Pred = ICmpInst::ICMP_SLE;
2518 Max = S;
2519 } else if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(IterationCount)) {
2520 Pred = ICmpInst::ICMP_SLT;
2521 Max = S;
2522 } else if (const SCEVUMaxExpr *U = dyn_cast<SCEVUMaxExpr>(IterationCount)) {
2523 Pred = ICmpInst::ICMP_ULT;
2524 Max = U;
2525 } else {
2526 // No match; bail.
2527 return Cond;
2528 }
2529
2530 // To handle a max with more than two operands, this optimization would
2531 // require additional checking and setup.
2532 if (Max->getNumOperands() != 2)
2533 return Cond;
2534
2535 const SCEV *MaxLHS = Max->getOperand(0);
2536 const SCEV *MaxRHS = Max->getOperand(1);
2537
2538 // ScalarEvolution canonicalizes constants to the left. For < and >, look
2539 // for a comparison with 1. For <= and >=, a comparison with zero.
2540 if (!MaxLHS ||
2541 (ICmpInst::isTrueWhenEqual(Pred) ? !MaxLHS->isZero() : (MaxLHS != One)))
2542 return Cond;
2543
2544 // Check the relevant induction variable for conformance to
2545 // the pattern.
2546 const SCEV *IV = SE.getSCEV(Cond->getOperand(0));
2547 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV);
2548 if (!AR || !AR->isAffine() ||
2549 AR->getStart() != One ||
2550 AR->getStepRecurrence(SE) != One)
2551 return Cond;
2552
2553 assert(AR->getLoop() == L &&
2554 "Loop condition operand is an addrec in a different loop!");
2555
2556 // Check the right operand of the select, and remember it, as it will
2557 // be used in the new comparison instruction.
2558 Value *NewRHS = nullptr;
2559 if (ICmpInst::isTrueWhenEqual(Pred)) {
2560 // Look for n+1, and grab n.
2561 if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(1)))
2562 if (ConstantInt *BO1 = dyn_cast<ConstantInt>(BO->getOperand(1)))
2563 if (BO1->isOne() && SE.getSCEV(BO->getOperand(0)) == MaxRHS)
2564 NewRHS = BO->getOperand(0);
2565 if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(2)))
2566 if (ConstantInt *BO1 = dyn_cast<ConstantInt>(BO->getOperand(1)))
2567 if (BO1->isOne() && SE.getSCEV(BO->getOperand(0)) == MaxRHS)
2568 NewRHS = BO->getOperand(0);
2569 if (!NewRHS)
2570 return Cond;
2571 } else if (SE.getSCEV(Sel->getOperand(1)) == MaxRHS)
2572 NewRHS = Sel->getOperand(1);
2573 else if (SE.getSCEV(Sel->getOperand(2)) == MaxRHS)
2574 NewRHS = Sel->getOperand(2);
2575 else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(MaxRHS))
2576 NewRHS = SU->getValue();
2577 else
2578 // Max doesn't match expected pattern.
2579 return Cond;
2580
2581 // Determine the new comparison opcode. It may be signed or unsigned,
2582 // and the original comparison may be either equality or inequality.
2583 if (Cond->getPredicate() == CmpInst::ICMP_EQ)
2584 Pred = CmpInst::getInversePredicate(Pred);
2585
2586 // Ok, everything looks ok to change the condition into an SLT or SGE and
2587 // delete the max calculation.
2588 ICmpInst *NewCond = new ICmpInst(Cond->getIterator(), Pred,
2589 Cond->getOperand(0), NewRHS, "scmp");
2590
2591 // Delete the max calculation instructions.
2592 NewCond->setDebugLoc(Cond->getDebugLoc());
2593 Cond->replaceAllUsesWith(NewCond);
2594 CondUse->setUser(NewCond);
2595 Instruction *Cmp = cast<Instruction>(Sel->getOperand(0));
2596 Cond->eraseFromParent();
2597 Sel->eraseFromParent();
2598 if (Cmp->use_empty())
2599 Cmp->eraseFromParent();
2600 return NewCond;
2601}
2602
2603/// Change loop terminating condition to use the postinc iv when possible.
2604void
2605LSRInstance::OptimizeLoopTermCond() {
2607
2608 // We need a different set of heuristics for rotated and non-rotated loops.
2609 // If a loop is rotated then the latch is also the backedge, so inserting
2610 // post-inc expressions just before the latch is ideal. To reduce live ranges
2611 // it also makes sense to rewrite terminating conditions to use post-inc
2612 // expressions.
2613 //
2614 // If the loop is not rotated then the latch is not a backedge; the latch
2615 // check is done in the loop head. Adding post-inc expressions before the
2616 // latch will cause overlapping live-ranges of pre-inc and post-inc expressions
2617 // in the loop body. In this case we do *not* want to use post-inc expressions
2618 // in the latch check, and we want to insert post-inc expressions before
2619 // the backedge.
2620 BasicBlock *LatchBlock = L->getLoopLatch();
2621 SmallVector<BasicBlock*, 8> ExitingBlocks;
2622 L->getExitingBlocks(ExitingBlocks);
2623 if (!llvm::is_contained(ExitingBlocks, LatchBlock)) {
2624 // The backedge doesn't exit the loop; treat this as a head-tested loop.
2625 IVIncInsertPos = LatchBlock->getTerminator();
2626 return;
2627 }
2628
2629 // Otherwise treat this as a rotated loop.
2630 for (BasicBlock *ExitingBlock : ExitingBlocks) {
2631 // Get the terminating condition for the loop if possible. If we
2632 // can, we want to change it to use a post-incremented version of its
2633 // induction variable, to allow coalescing the live ranges for the IV into
2634 // one register value.
2635
2636 BranchInst *TermBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2637 if (!TermBr)
2638 continue;
2639 // FIXME: Overly conservative, termination condition could be an 'or' etc..
2640 if (TermBr->isUnconditional() || !isa<ICmpInst>(TermBr->getCondition()))
2641 continue;
2642
2643 // Search IVUsesByStride to find Cond's IVUse if there is one.
2644 IVStrideUse *CondUse = nullptr;
2645 ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
2646 if (!FindIVUserForCond(Cond, CondUse))
2647 continue;
2648
2649 // If the trip count is computed in terms of a max (due to ScalarEvolution
2650 // being unable to find a sufficient guard, for example), change the loop
2651 // comparison to use SLT or ULT instead of NE.
2652 // One consequence of doing this now is that it disrupts the count-down
2653 // optimization. That's not always a bad thing though, because in such
2654 // cases it may still be worthwhile to avoid a max.
2655 Cond = OptimizeMax(Cond, CondUse);
2656
2657 // If this exiting block dominates the latch block, it may also use
2658 // the post-inc value if it won't be shared with other uses.
2659 // Check for dominance.
2660 if (!DT.dominates(ExitingBlock, LatchBlock))
2661 continue;
2662
2663 // Conservatively avoid trying to use the post-inc value in non-latch
2664 // exits if there may be pre-inc users in intervening blocks.
2665 if (LatchBlock != ExitingBlock)
2666 for (const IVStrideUse &UI : IU)
2667 // Test if the use is reachable from the exiting block. This dominator
2668 // query is a conservative approximation of reachability.
2669 if (&UI != CondUse &&
2670 !DT.properlyDominates(UI.getUser()->getParent(), ExitingBlock)) {
2671 // Conservatively assume there may be reuse if the quotient of their
2672 // strides could be a legal scale.
2673 const SCEV *A = IU.getStride(*CondUse, L);
2674 const SCEV *B = IU.getStride(UI, L);
2675 if (!A || !B) continue;
2676 if (SE.getTypeSizeInBits(A->getType()) !=
2677 SE.getTypeSizeInBits(B->getType())) {
2678 if (SE.getTypeSizeInBits(A->getType()) >
2679 SE.getTypeSizeInBits(B->getType()))
2680 B = SE.getSignExtendExpr(B, A->getType());
2681 else
2682 A = SE.getSignExtendExpr(A, B->getType());
2683 }
2684 if (const SCEVConstant *D =
2685 dyn_cast_or_null<SCEVConstant>(getExactSDiv(B, A, SE))) {
2686 const ConstantInt *C = D->getValue();
2687 // Stride of one or negative one can have reuse with non-addresses.
2688 if (C->isOne() || C->isMinusOne())
2689 goto decline_post_inc;
2690 // Avoid weird situations.
2691 if (C->getValue().getSignificantBits() >= 64 ||
2692 C->getValue().isMinSignedValue())
2693 goto decline_post_inc;
2694 // Check for possible scaled-address reuse.
2695 if (isAddressUse(TTI, UI.getUser(), UI.getOperandValToReplace())) {
2696 MemAccessTy AccessTy =
2697 getAccessType(TTI, UI.getUser(), UI.getOperandValToReplace());
2698 int64_t Scale = C->getSExtValue();
2699 if (TTI.isLegalAddressingMode(AccessTy.MemTy, /*BaseGV=*/nullptr,
2700 /*BaseOffset=*/0,
2701 /*HasBaseReg=*/true, Scale,
2702 AccessTy.AddrSpace))
2703 goto decline_post_inc;
2704 Scale = -Scale;
2705 if (TTI.isLegalAddressingMode(AccessTy.MemTy, /*BaseGV=*/nullptr,
2706 /*BaseOffset=*/0,
2707 /*HasBaseReg=*/true, Scale,
2708 AccessTy.AddrSpace))
2709 goto decline_post_inc;
2710 }
2711 }
2712 }
2713
2714 LLVM_DEBUG(dbgs() << " Change loop exiting icmp to use postinc iv: "
2715 << *Cond << '\n');
2716
2717 // It's possible for the setcc instruction to be anywhere in the loop, and
2718 // possible for it to have multiple users. If it is not immediately before
2719 // the exiting block branch, move it.
2720 if (Cond->getNextNonDebugInstruction() != TermBr) {
2721 if (Cond->hasOneUse()) {
2722 Cond->moveBefore(TermBr);
2723 } else {
2724 // Clone the terminating condition and insert into the loopend.
2725 ICmpInst *OldCond = Cond;
2726 Cond = cast<ICmpInst>(Cond->clone());
2727 Cond->setName(L->getHeader()->getName() + ".termcond");
2728 Cond->insertInto(ExitingBlock, TermBr->getIterator());
2729
2730 // Clone the IVUse, as the old use still exists!
2731 CondUse = &IU.AddUser(Cond, CondUse->getOperandValToReplace());
2732 TermBr->replaceUsesOfWith(OldCond, Cond);
2733 }
2734 }
2735
2736 // If we get to here, we know that we can transform the setcc instruction to
2737 // use the post-incremented version of the IV, allowing us to coalesce the
2738 // live ranges for the IV correctly.
2739 CondUse->transformToPostInc(L);
2740 Changed = true;
2741
2742 PostIncs.insert(Cond);
2743 decline_post_inc:;
2744 }
2745
2746 // Determine an insertion point for the loop induction variable increment. It
2747 // must dominate all the post-inc comparisons we just set up, and it must
2748 // dominate the loop latch edge.
2749 IVIncInsertPos = L->getLoopLatch()->getTerminator();
2750 for (Instruction *Inst : PostIncs)
2751 IVIncInsertPos = DT.findNearestCommonDominator(IVIncInsertPos, Inst);
2752}
2753
2754/// Determine if the given use can accommodate a fixup at the given offset and
2755/// other details. If so, update the use and return true.
2756bool LSRInstance::reconcileNewOffset(LSRUse &LU, Immediate NewOffset,
2757 bool HasBaseReg, LSRUse::KindType Kind,
2758 MemAccessTy AccessTy) {
2759 Immediate NewMinOffset = LU.MinOffset;
2760 Immediate NewMaxOffset = LU.MaxOffset;
2761 MemAccessTy NewAccessTy = AccessTy;
2762
2763 // Check for a mismatched kind. It's tempting to collapse mismatched kinds to
2764 // something conservative, however this can pessimize in the case that one of
2765 // the uses will have all its uses outside the loop, for example.
2766 if (LU.Kind != Kind)
2767 return false;
2768
2769 // Check for a mismatched access type, and fall back conservatively as needed.
2770 // TODO: Be less conservative when the type is similar and can use the same
2771 // addressing modes.
2772 if (Kind == LSRUse::Address) {
2773 if (AccessTy.MemTy != LU.AccessTy.MemTy) {
2774 NewAccessTy = MemAccessTy::getUnknown(AccessTy.MemTy->getContext(),
2775 AccessTy.AddrSpace);
2776 }
2777 }
2778
2779 // Conservatively assume HasBaseReg is true for now.
2780 if (Immediate::isKnownLT(NewOffset, LU.MinOffset)) {
2781 if (!isAlwaysFoldable(TTI, Kind, NewAccessTy, /*BaseGV=*/nullptr,
2782 LU.MaxOffset - NewOffset, HasBaseReg))
2783 return false;
2784 NewMinOffset = NewOffset;
2785 } else if (Immediate::isKnownGT(NewOffset, LU.MaxOffset)) {
2786 if (!isAlwaysFoldable(TTI, Kind, NewAccessTy, /*BaseGV=*/nullptr,
2787 NewOffset - LU.MinOffset, HasBaseReg))
2788 return false;
2789 NewMaxOffset = NewOffset;
2790 }
2791
2792 // FIXME: We should be able to handle some level of scalable offset support
2793 // for 'void', but in order to get basic support up and running this is
2794 // being left out.
2795 if (NewAccessTy.MemTy && NewAccessTy.MemTy->isVoidTy() &&
2796 (NewMinOffset.isScalable() || NewMaxOffset.isScalable()))
2797 return false;
2798
2799 // Update the use.
2800 LU.MinOffset = NewMinOffset;
2801 LU.MaxOffset = NewMaxOffset;
2802 LU.AccessTy = NewAccessTy;
2803 return true;
2804}
2805
2806/// Return an LSRUse index and an offset value for a fixup which needs the given
2807/// expression, with the given kind and optional access type. Either reuse an
2808/// existing use or create a new one, as needed.
2809std::pair<size_t, Immediate> LSRInstance::getUse(const SCEV *&Expr,
2810 LSRUse::KindType Kind,
2811 MemAccessTy AccessTy) {
2812 const SCEV *Copy = Expr;
2813 Immediate Offset = ExtractImmediate(Expr, SE);
2814
2815 // Basic uses can't accept any offset, for example.
2816 if (!isAlwaysFoldable(TTI, Kind, AccessTy, /*BaseGV=*/ nullptr,
2817 Offset, /*HasBaseReg=*/ true)) {
2818 Expr = Copy;
2819 Offset = Immediate::getFixed(0);
2820 }
2821
2822 std::pair<UseMapTy::iterator, bool> P =
2823 UseMap.insert(std::make_pair(LSRUse::SCEVUseKindPair(Expr, Kind), 0));
2824 if (!P.second) {
2825 // A use already existed with this base.
2826 size_t LUIdx = P.first->second;
2827 LSRUse &LU = Uses[LUIdx];
2828 if (reconcileNewOffset(LU, Offset, /*HasBaseReg=*/true, Kind, AccessTy))
2829 // Reuse this use.
2830 return std::make_pair(LUIdx, Offset);
2831 }
2832
2833 // Create a new use.
2834 size_t LUIdx = Uses.size();
2835 P.first->second = LUIdx;
2836 Uses.push_back(LSRUse(Kind, AccessTy));
2837 LSRUse &LU = Uses[LUIdx];
2838
2839 LU.MinOffset = Offset;
2840 LU.MaxOffset = Offset;
2841 return std::make_pair(LUIdx, Offset);
2842}
2843
2844/// Delete the given use from the Uses list.
2845void LSRInstance::DeleteUse(LSRUse &LU, size_t LUIdx) {
2846 if (&LU != &Uses.back())
2847 std::swap(LU, Uses.back());
2848 Uses.pop_back();
2849
2850 // Update RegUses.
2851 RegUses.swapAndDropUse(LUIdx, Uses.size());
2852}
2853
2854/// Look for a use distinct from OrigLU which is has a formula that has the same
2855/// registers as the given formula.
2856LSRUse *
2857LSRInstance::FindUseWithSimilarFormula(const Formula &OrigF,
2858 const LSRUse &OrigLU) {
2859 // Search all uses for the formula. This could be more clever.
2860 for (LSRUse &LU : Uses) {
2861 // Check whether this use is close enough to OrigLU, to see whether it's
2862 // worthwhile looking through its formulae.
2863 // Ignore ICmpZero uses because they may contain formulae generated by
2864 // GenerateICmpZeroScales, in which case adding fixup offsets may
2865 // be invalid.
2866 if (&LU != &OrigLU &&
2867 LU.Kind != LSRUse::ICmpZero &&
2868 LU.Kind == OrigLU.Kind && OrigLU.AccessTy == LU.AccessTy &&
2869 LU.WidestFixupType == OrigLU.WidestFixupType &&
2870 LU.HasFormulaWithSameRegs(OrigF)) {
2871 // Scan through this use's formulae.
2872 for (const Formula &F : LU.Formulae) {
2873 // Check to see if this formula has the same registers and symbols
2874 // as OrigF.
2875 if (F.BaseRegs == OrigF.BaseRegs &&
2876 F.ScaledReg == OrigF.ScaledReg &&
2877 F.BaseGV == OrigF.BaseGV &&
2878 F.Scale == OrigF.Scale &&
2879 F.UnfoldedOffset == OrigF.UnfoldedOffset) {
2880 if (F.BaseOffset.isZero())
2881 return &LU;
2882 // This is the formula where all the registers and symbols matched;
2883 // there aren't going to be any others. Since we declined it, we
2884 // can skip the rest of the formulae and proceed to the next LSRUse.
2885 break;
2886 }
2887 }
2888 }
2889 }
2890
2891 // Nothing looked good.
2892 return nullptr;
2893}
2894
2895void LSRInstance::CollectInterestingTypesAndFactors() {
2897
2898 // Collect interesting types and strides.
2900 for (const IVStrideUse &U : IU) {
2901 const SCEV *Expr = IU.getExpr(U);
2902 if (!Expr)
2903 continue;
2904
2905 // Collect interesting types.
2906 Types.insert(SE.getEffectiveSCEVType(Expr->getType()));
2907
2908 // Add strides for mentioned loops.
2909 Worklist.push_back(Expr);
2910 do {
2911 const SCEV *S = Worklist.pop_back_val();
2912 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
2913 if (AR->getLoop() == L)
2914 Strides.insert(AR->getStepRecurrence(SE));
2915 Worklist.push_back(AR->getStart());
2916 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2917 append_range(Worklist, Add->operands());
2918 }
2919 } while (!Worklist.empty());
2920 }
2921
2922 // Compute interesting factors from the set of interesting strides.
2924 I = Strides.begin(), E = Strides.end(); I != E; ++I)
2926 std::next(I); NewStrideIter != E; ++NewStrideIter) {
2927 const SCEV *OldStride = *I;
2928 const SCEV *NewStride = *NewStrideIter;
2929
2930 if (SE.getTypeSizeInBits(OldStride->getType()) !=
2931 SE.getTypeSizeInBits(NewStride->getType())) {
2932 if (SE.getTypeSizeInBits(OldStride->getType()) >
2933 SE.getTypeSizeInBits(NewStride->getType()))
2934 NewStride = SE.getSignExtendExpr(NewStride, OldStride->getType());
2935 else
2936 OldStride = SE.getSignExtendExpr(OldStride, NewStride->getType());
2937 }
2938 if (const SCEVConstant *Factor =
2939 dyn_cast_or_null<SCEVConstant>(getExactSDiv(NewStride, OldStride,
2940 SE, true))) {
2941 if (Factor->getAPInt().getSignificantBits() <= 64 && !Factor->isZero())
2942 Factors.insert(Factor->getAPInt().getSExtValue());
2943 } else if (const SCEVConstant *Factor =
2944 dyn_cast_or_null<SCEVConstant>(getExactSDiv(OldStride,
2945 NewStride,
2946 SE, true))) {
2947 if (Factor->getAPInt().getSignificantBits() <= 64 && !Factor->isZero())
2948 Factors.insert(Factor->getAPInt().getSExtValue());
2949 }
2950 }
2951
2952 // If all uses use the same type, don't bother looking for truncation-based
2953 // reuse.
2954 if (Types.size() == 1)
2955 Types.clear();
2956
2957 LLVM_DEBUG(print_factors_and_types(dbgs()));
2958}
2959
2960/// Helper for CollectChains that finds an IV operand (computed by an AddRec in
2961/// this loop) within [OI,OE) or returns OE. If IVUsers mapped Instructions to
2962/// IVStrideUses, we could partially skip this.
2963static User::op_iterator
2965 Loop *L, ScalarEvolution &SE) {
2966 for(; OI != OE; ++OI) {
2967 if (Instruction *Oper = dyn_cast<Instruction>(*OI)) {
2968 if (!SE.isSCEVable(Oper->getType()))
2969 continue;
2970
2971 if (const SCEVAddRecExpr *AR =
2972 dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Oper))) {
2973 if (AR->getLoop() == L)
2974 break;
2975 }
2976 }
2977 }
2978 return OI;
2979}
2980
2981/// IVChain logic must consistently peek base TruncInst operands, so wrap it in
2982/// a convenient helper.
2984 if (TruncInst *Trunc = dyn_cast<TruncInst>(Oper))
2985 return Trunc->getOperand(0);
2986 return Oper;
2987}
2988
2989/// Return an approximation of this SCEV expression's "base", or NULL for any
2990/// constant. Returning the expression itself is conservative. Returning a
2991/// deeper subexpression is more precise and valid as long as it isn't less
2992/// complex than another subexpression. For expressions involving multiple
2993/// unscaled values, we need to return the pointer-type SCEVUnknown. This avoids
2994/// forming chains across objects, such as: PrevOper==a[i], IVOper==b[i],
2995/// IVInc==b-a.
2996///
2997/// Since SCEVUnknown is the rightmost type, and pointers are the rightmost
2998/// SCEVUnknown, we simply return the rightmost SCEV operand.
2999static const SCEV *getExprBase(const SCEV *S) {
3000 switch (S->getSCEVType()) {
3001 default: // including scUnknown.
3002 return S;
3003 case scConstant:
3004 case scVScale:
3005 return nullptr;
3006 case scTruncate:
3007 return getExprBase(cast<SCEVTruncateExpr>(S)->getOperand());
3008 case scZeroExtend:
3009 return getExprBase(cast<SCEVZeroExtendExpr>(S)->getOperand());
3010 case scSignExtend:
3011 return getExprBase(cast<SCEVSignExtendExpr>(S)->getOperand());
3012 case scAddExpr: {
3013 // Skip over scaled operands (scMulExpr) to follow add operands as long as
3014 // there's nothing more complex.
3015 // FIXME: not sure if we want to recognize negation.
3016 const SCEVAddExpr *Add = cast<SCEVAddExpr>(S);
3017 for (const SCEV *SubExpr : reverse(Add->operands())) {
3018 if (SubExpr->getSCEVType() == scAddExpr)
3019 return getExprBase(SubExpr);
3020
3021 if (SubExpr->getSCEVType() != scMulExpr)
3022 return SubExpr;
3023 }
3024 return S; // all operands are scaled, be conservative.
3025 }
3026 case scAddRecExpr:
3027 return getExprBase(cast<SCEVAddRecExpr>(S)->getStart());
3028 }
3029 llvm_unreachable("Unknown SCEV kind!");
3030}
3031
3032/// Return true if the chain increment is profitable to expand into a loop
3033/// invariant value, which may require its own register. A profitable chain
3034/// increment will be an offset relative to the same base. We allow such offsets
3035/// to potentially be used as chain increment as long as it's not obviously
3036/// expensive to expand using real instructions.
3037bool IVChain::isProfitableIncrement(const SCEV *OperExpr,
3038 const SCEV *IncExpr,
3039 ScalarEvolution &SE) {
3040 // Aggressively form chains when -stress-ivchain.
3041 if (StressIVChain)
3042 return true;
3043
3044 // Do not replace a constant offset from IV head with a nonconstant IV
3045 // increment.
3046 if (!isa<SCEVConstant>(IncExpr)) {
3047 const SCEV *HeadExpr = SE.getSCEV(getWideOperand(Incs[0].IVOperand));
3048 if (isa<SCEVConstant>(SE.getMinusSCEV(OperExpr, HeadExpr)))
3049 return false;
3050 }
3051
3053 return !isHighCostExpansion(IncExpr, Processed, SE);
3054}
3055
3056/// Return true if the number of registers needed for the chain is estimated to
3057/// be less than the number required for the individual IV users. First prohibit
3058/// any IV users that keep the IV live across increments (the Users set should
3059/// be empty). Next count the number and type of increments in the chain.
3060///
3061/// Chaining IVs can lead to considerable code bloat if ISEL doesn't
3062/// effectively use postinc addressing modes. Only consider it profitable it the
3063/// increments can be computed in fewer registers when chained.
3064///
3065/// TODO: Consider IVInc free if it's already used in another chains.
3066static bool isProfitableChain(IVChain &Chain,
3068 ScalarEvolution &SE,
3069 const TargetTransformInfo &TTI) {
3070 if (StressIVChain)
3071 return true;
3072
3073 if (!Chain.hasIncs())
3074 return false;
3075
3076 if (!Users.empty()) {
3077 LLVM_DEBUG(dbgs() << "Chain: " << *Chain.Incs[0].UserInst << " users:\n";
3078 for (Instruction *Inst
3079 : Users) { dbgs() << " " << *Inst << "\n"; });
3080 return false;
3081 }
3082 assert(!Chain.Incs.empty() && "empty IV chains are not allowed");
3083
3084 // The chain itself may require a register, so intialize cost to 1.
3085 int cost = 1;
3086
3087 // A complete chain likely eliminates the need for keeping the original IV in
3088 // a register. LSR does not currently know how to form a complete chain unless
3089 // the header phi already exists.
3090 if (isa<PHINode>(Chain.tailUserInst())
3091 && SE.getSCEV(Chain.tailUserInst()) == Chain.Incs[0].IncExpr) {
3092 --cost;
3093 }
3094 const SCEV *LastIncExpr = nullptr;
3095 unsigned NumConstIncrements = 0;
3096 unsigned NumVarIncrements = 0;
3097 unsigned NumReusedIncrements = 0;
3098
3099 if (TTI.isProfitableLSRChainElement(Chain.Incs[0].UserInst))
3100 return true;
3101
3102 for (const IVInc &Inc : Chain) {
3103 if (TTI.isProfitableLSRChainElement(Inc.UserInst))
3104 return true;
3105 if (Inc.IncExpr->isZero())
3106 continue;
3107
3108 // Incrementing by zero or some constant is neutral. We assume constants can
3109 // be folded into an addressing mode or an add's immediate operand.
3110 if (isa<SCEVConstant>(Inc.IncExpr)) {
3111 ++NumConstIncrements;
3112 continue;
3113 }
3114
3115 if (Inc.IncExpr == LastIncExpr)
3116 ++NumReusedIncrements;
3117 else
3118 ++NumVarIncrements;
3119
3120 LastIncExpr = Inc.IncExpr;
3121 }
3122 // An IV chain with a single increment is handled by LSR's postinc
3123 // uses. However, a chain with multiple increments requires keeping the IV's
3124 // value live longer than it needs to be if chained.
3125 if (NumConstIncrements > 1)
3126 --cost;
3127
3128 // Materializing increment expressions in the preheader that didn't exist in
3129 // the original code may cost a register. For example, sign-extended array
3130 // indices can produce ridiculous increments like this:
3131 // IV + ((sext i32 (2 * %s) to i64) + (-1 * (sext i32 %s to i64)))
3132 cost += NumVarIncrements;
3133
3134 // Reusing variable increments likely saves a register to hold the multiple of
3135 // the stride.
3136 cost -= NumReusedIncrements;
3137
3138 LLVM_DEBUG(dbgs() << "Chain: " << *Chain.Incs[0].UserInst << " Cost: " << cost
3139 << "\n");
3140
3141 return cost < 0;
3142}
3143
3144/// Add this IV user to an existing chain or make it the head of a new chain.
3145void LSRInstance::ChainInstruction(Instruction *UserInst, Instruction *IVOper,
3146 SmallVectorImpl<ChainUsers> &ChainUsersVec) {
3147 // When IVs are used as types of varying widths, they are generally converted
3148 // to a wider type with some uses remaining narrow under a (free) trunc.
3149 Value *const NextIV = getWideOperand(IVOper);
3150 const SCEV *const OperExpr = SE.getSCEV(NextIV);
3151 const SCEV *const OperExprBase = getExprBase(OperExpr);
3152
3153 // Visit all existing chains. Check if its IVOper can be computed as a
3154 // profitable loop invariant increment from the last link in the Chain.
3155 unsigned ChainIdx = 0, NChains = IVChainVec.size();
3156 const SCEV *LastIncExpr = nullptr;
3157 for (; ChainIdx < NChains; ++ChainIdx) {
3158 IVChain &Chain = IVChainVec[ChainIdx];
3159
3160 // Prune the solution space aggressively by checking that both IV operands
3161 // are expressions that operate on the same unscaled SCEVUnknown. This
3162 // "base" will be canceled by the subsequent getMinusSCEV call. Checking
3163 // first avoids creating extra SCEV expressions.
3164 if (!StressIVChain && Chain.ExprBase != OperExprBase)
3165 continue;
3166
3167 Value *PrevIV = getWideOperand(Chain.Incs.back().IVOperand);
3168 if (PrevIV->getType() != NextIV->getType())
3169 continue;
3170
3171 // A phi node terminates a chain.
3172 if (isa<PHINode>(UserInst) && isa<PHINode>(Chain.tailUserInst()))
3173 continue;
3174
3175 // The increment must be loop-invariant so it can be kept in a register.
3176 const SCEV *PrevExpr = SE.getSCEV(PrevIV);
3177 const SCEV *IncExpr = SE.getMinusSCEV(OperExpr, PrevExpr);
3178 if (isa<SCEVCouldNotCompute>(IncExpr) || !SE.isLoopInvariant(IncExpr, L))
3179 continue;
3180
3181 if (Chain.isProfitableIncrement(OperExpr, IncExpr, SE)) {
3182 LastIncExpr = IncExpr;
3183 break;
3184 }
3185 }
3186 // If we haven't found a chain, create a new one, unless we hit the max. Don't
3187 // bother for phi nodes, because they must be last in the chain.
3188 if (ChainIdx == NChains) {
3189 if (isa<PHINode>(UserInst))
3190 return;
3191 if (NChains >= MaxChains && !StressIVChain) {
3192 LLVM_DEBUG(dbgs() << "IV Chain Limit\n");
3193 return;
3194 }
3195 LastIncExpr = OperExpr;
3196 // IVUsers may have skipped over sign/zero extensions. We don't currently
3197 // attempt to form chains involving extensions unless they can be hoisted
3198 // into this loop's AddRec.
3199 if (!isa<SCEVAddRecExpr>(LastIncExpr))
3200 return;
3201 ++NChains;
3202 IVChainVec.push_back(IVChain(IVInc(UserInst, IVOper, LastIncExpr),
3203 OperExprBase));
3204 ChainUsersVec.resize(NChains);
3205 LLVM_DEBUG(dbgs() << "IV Chain#" << ChainIdx << " Head: (" << *UserInst
3206 << ") IV=" << *LastIncExpr << "\n");
3207 } else {
3208 LLVM_DEBUG(dbgs() << "IV Chain#" << ChainIdx << " Inc: (" << *UserInst
3209 << ") IV+" << *LastIncExpr << "\n");
3210 // Add this IV user to the end of the chain.
3211 IVChainVec[ChainIdx].add(IVInc(UserInst, IVOper, LastIncExpr));
3212 }
3213 IVChain &Chain = IVChainVec[ChainIdx];
3214
3215 SmallPtrSet<Instruction*,4> &NearUsers = ChainUsersVec[ChainIdx].NearUsers;
3216 // This chain's NearUsers become FarUsers.
3217 if (!LastIncExpr->isZero()) {
3218 ChainUsersVec[ChainIdx].FarUsers.insert(NearUsers.begin(),
3219 NearUsers.end());
3220 NearUsers.clear();
3221 }
3222
3223 // All other uses of IVOperand become near uses of the chain.
3224 // We currently ignore intermediate values within SCEV expressions, assuming
3225 // they will eventually be used be the current chain, or can be computed
3226 // from one of the chain increments. To be more precise we could
3227 // transitively follow its user and only add leaf IV users to the set.
3228 for (User *U : IVOper->users()) {
3229 Instruction *OtherUse = dyn_cast<Instruction>(U);
3230 if (!OtherUse)
3231 continue;
3232 // Uses in the chain will no longer be uses if the chain is formed.
3233 // Include the head of the chain in this iteration (not Chain.begin()).
3234 IVChain::const_iterator IncIter = Chain.Incs.begin();
3235 IVChain::const_iterator IncEnd = Chain.Incs.end();
3236 for( ; IncIter != IncEnd; ++IncIter) {
3237 if (IncIter->UserInst == OtherUse)
3238 break;
3239 }
3240 if (IncIter != IncEnd)
3241 continue;
3242
3243 if (SE.isSCEVable(OtherUse->getType())
3244 && !isa<SCEVUnknown>(SE.getSCEV(OtherUse))
3245 && IU.isIVUserOrOperand(OtherUse)) {
3246 continue;
3247 }
3248 NearUsers.insert(OtherUse);
3249 }
3250
3251 // Since this user is part of the chain, it's no longer considered a use
3252 // of the chain.
3253 ChainUsersVec[ChainIdx].FarUsers.erase(UserInst);
3254}
3255
3256/// Populate the vector of Chains.
3257///
3258/// This decreases ILP at the architecture level. Targets with ample registers,
3259/// multiple memory ports, and no register renaming probably don't want
3260/// this. However, such targets should probably disable LSR altogether.
3261///
3262/// The job of LSR is to make a reasonable choice of induction variables across
3263/// the loop. Subsequent passes can easily "unchain" computation exposing more
3264/// ILP *within the loop* if the target wants it.
3265///
3266/// Finding the best IV chain is potentially a scheduling problem. Since LSR
3267/// will not reorder memory operations, it will recognize this as a chain, but
3268/// will generate redundant IV increments. Ideally this would be corrected later
3269/// by a smart scheduler:
3270/// = A[i]
3271/// = A[i+x]
3272/// A[i] =
3273/// A[i+x] =
3274///
3275/// TODO: Walk the entire domtree within this loop, not just the path to the
3276/// loop latch. This will discover chains on side paths, but requires
3277/// maintaining multiple copies of the Chains state.
3278void LSRInstance::CollectChains() {
3279 LLVM_DEBUG(dbgs() << "Collecting IV Chains.\n");
3280 SmallVector<ChainUsers, 8> ChainUsersVec;
3281
3283 BasicBlock *LoopHeader = L->getHeader();
3284 for (DomTreeNode *Rung = DT.getNode(L->getLoopLatch());
3285 Rung->getBlock() != LoopHeader; Rung = Rung->getIDom()) {
3286 LatchPath.push_back(Rung->getBlock());
3287 }
3288 LatchPath.push_back(LoopHeader);
3289
3290 // Walk the instruction stream from the loop header to the loop latch.
3291 for (BasicBlock *BB : reverse(LatchPath)) {
3292 for (Instruction &I : *BB) {
3293 // Skip instructions that weren't seen by IVUsers analysis.
3294 if (isa<PHINode>(I) || !IU.isIVUserOrOperand(&I))
3295 continue;
3296
3297 // Ignore users that are part of a SCEV expression. This way we only
3298 // consider leaf IV Users. This effectively rediscovers a portion of
3299 // IVUsers analysis but in program order this time.
3300 if (SE.isSCEVable(I.getType()) && !isa<SCEVUnknown>(SE.getSCEV(&I)))
3301 continue;
3302
3303 // Remove this instruction from any NearUsers set it may be in.
3304 for (unsigned ChainIdx = 0, NChains = IVChainVec.size();
3305 ChainIdx < NChains; ++ChainIdx) {
3306 ChainUsersVec[ChainIdx].NearUsers.erase(&I);
3307 }
3308 // Search for operands that can be chained.
3309 SmallPtrSet<Instruction*, 4> UniqueOperands;
3310 User::op_iterator IVOpEnd = I.op_end();
3311 User::op_iterator IVOpIter = findIVOperand(I.op_begin(), IVOpEnd, L, SE);
3312 while (IVOpIter != IVOpEnd) {
3313 Instruction *IVOpInst = cast<Instruction>(*IVOpIter);
3314 if (UniqueOperands.insert(IVOpInst).second)
3315 ChainInstruction(&I, IVOpInst, ChainUsersVec);
3316 IVOpIter = findIVOperand(std::next(IVOpIter), IVOpEnd, L, SE);
3317 }
3318 } // Continue walking down the instructions.
3319 } // Continue walking down the domtree.
3320 // Visit phi backedges to determine if the chain can generate the IV postinc.
3321 for (PHINode &PN : L->getHeader()->phis()) {
3322 if (!SE.isSCEVable(PN.getType()))
3323 continue;
3324
3325 Instruction *IncV =
3326 dyn_cast<Instruction>(PN.getIncomingValueForBlock(L->getLoopLatch()));
3327 if (IncV)
3328 ChainInstruction(&PN, IncV, ChainUsersVec);
3329 }
3330 // Remove any unprofitable chains.
3331 unsigned ChainIdx = 0;
3332 for (unsigned UsersIdx = 0, NChains = IVChainVec.size();
3333 UsersIdx < NChains; ++UsersIdx) {
3334 if (!isProfitableChain(IVChainVec[UsersIdx],
3335 ChainUsersVec[UsersIdx].FarUsers, SE, TTI))
3336 continue;
3337 // Preserve the chain at UsesIdx.
3338 if (ChainIdx != UsersIdx)
3339 IVChainVec[ChainIdx] = IVChainVec[UsersIdx];
3340 FinalizeChain(IVChainVec[ChainIdx]);
3341 ++ChainIdx;
3342 }
3343 IVChainVec.resize(ChainIdx);
3344}
3345
3346void LSRInstance::FinalizeChain(IVChain &Chain) {
3347 assert(!Chain.Incs.empty() && "empty IV chains are not allowed");
3348 LLVM_DEBUG(dbgs() << "Final Chain: " << *Chain.Incs[0].UserInst << "\n");
3349
3350 for (const IVInc &Inc : Chain) {
3351 LLVM_DEBUG(dbgs() << " Inc: " << *Inc.UserInst << "\n");
3352 auto UseI = find(Inc.UserInst->operands(), Inc.IVOperand);
3353 assert(UseI != Inc.UserInst->op_end() && "cannot find IV operand");
3354 IVIncSet.insert(UseI);
3355 }
3356}
3357
3358/// Return true if the IVInc can be folded into an addressing mode.
3359static bool canFoldIVIncExpr(const SCEV *IncExpr, Instruction *UserInst,
3360 Value *Operand, const TargetTransformInfo &TTI) {
3361 const SCEVConstant *IncConst = dyn_cast<SCEVConstant>(IncExpr);
3362 Immediate IncOffset = Immediate::getZero();
3363 if (IncConst) {
3364 if (IncConst && IncConst->getAPInt().getSignificantBits() > 64)
3365 return false;
3366 IncOffset = Immediate::getFixed(IncConst->getValue()->getSExtValue());
3367 } else {
3368 // Look for mul(vscale, constant), to detect a scalable offset.
3369 auto *IncVScale = dyn_cast<SCEVMulExpr>(IncExpr);
3370 if (!IncVScale || IncVScale->getNumOperands() != 2 ||
3371 !isa<SCEVVScale>(IncVScale->getOperand(1)))
3372 return false;
3373 auto *Scale = dyn_cast<SCEVConstant>(IncVScale->getOperand(0));
3374 if (!Scale || Scale->getType()->getScalarSizeInBits() > 64)
3375 return false;
3376 IncOffset = Immediate::getScalable(Scale->getValue()->getSExtValue());
3377 }
3378
3379 if (!isAddressUse(TTI, UserInst, Operand))
3380 return false;
3381
3382 MemAccessTy AccessTy = getAccessType(TTI, UserInst, Operand);
3383 if (!isAlwaysFoldable(TTI, LSRUse::Address, AccessTy, /*BaseGV=*/nullptr,
3384 IncOffset, /*HasBaseReg=*/false))
3385 return false;
3386
3387 return true;
3388}
3389
3390/// Generate an add or subtract for each IVInc in a chain to materialize the IV
3391/// user's operand from the previous IV user's operand.
3392void LSRInstance::GenerateIVChain(const IVChain &Chain,
3394 // Find the new IVOperand for the head of the chain. It may have been replaced
3395 // by LSR.
3396 const IVInc &Head = Chain.Incs[0];
3397 User::op_iterator IVOpEnd = Head.UserInst->op_end();
3398 // findIVOperand returns IVOpEnd if it can no longer find a valid IV user.
3399 User::op_iterator IVOpIter = findIVOperand(Head.UserInst->op_begin(),
3400 IVOpEnd, L, SE);
3401 Value *IVSrc = nullptr;
3402 while (IVOpIter != IVOpEnd) {
3403 IVSrc = getWideOperand(*IVOpIter);
3404
3405 // If this operand computes the expression that the chain needs, we may use
3406 // it. (Check this after setting IVSrc which is used below.)
3407 //
3408 // Note that if Head.IncExpr is wider than IVSrc, then this phi is too
3409 // narrow for the chain, so we can no longer use it. We do allow using a
3410 // wider phi, assuming the LSR checked for free truncation. In that case we
3411 // should already have a truncate on this operand such that
3412 // getSCEV(IVSrc) == IncExpr.
3413 if (SE.getSCEV(*IVOpIter) == Head.IncExpr
3414 || SE.getSCEV(IVSrc) == Head.IncExpr) {
3415 break;
3416 }
3417 IVOpIter = findIVOperand(std::next(IVOpIter), IVOpEnd, L, SE);
3418 }
3419 if (IVOpIter == IVOpEnd) {
3420 // Gracefully give up on this chain.
3421 LLVM_DEBUG(dbgs() << "Concealed chain head: " << *Head.UserInst << "\n");
3422 return;
3423 }
3424 assert(IVSrc && "Failed to find IV chain source");
3425
3426 LLVM_DEBUG(dbgs() << "Generate chain at: " << *IVSrc << "\n");
3427 Type *IVTy = IVSrc->getType();
3428 Type *IntTy = SE.getEffectiveSCEVType(IVTy);
3429 const SCEV *LeftOverExpr = nullptr;
3430 const SCEV *Accum = SE.getZero(IntTy);
3432 Bases.emplace_back(Accum, IVSrc);
3433
3434 for (const IVInc &Inc : Chain) {
3435 Instruction *InsertPt = Inc.UserInst;
3436 if (isa<PHINode>(InsertPt))
3437 InsertPt = L->getLoopLatch()->getTerminator();
3438
3439 // IVOper will replace the current IV User's operand. IVSrc is the IV
3440 // value currently held in a register.
3441 Value *IVOper = IVSrc;
3442 if (!Inc.IncExpr->isZero()) {
3443 // IncExpr was the result of subtraction of two narrow values, so must
3444 // be signed.
3445 const SCEV *IncExpr = SE.getNoopOrSignExtend(Inc.IncExpr, IntTy);
3446 Accum = SE.getAddExpr(Accum, IncExpr);
3447 LeftOverExpr = LeftOverExpr ?
3448 SE.getAddExpr(LeftOverExpr, IncExpr) : IncExpr;
3449 }
3450
3451 // Look through each base to see if any can produce a nice addressing mode.
3452 bool FoundBase = false;
3453 for (auto [MapScev, MapIVOper] : reverse(Bases)) {
3454 const SCEV *Remainder = SE.getMinusSCEV(Accum, MapScev);
3455 if (canFoldIVIncExpr(Remainder, Inc.UserInst, Inc.IVOperand, TTI)) {
3456 if (!Remainder->isZero()) {
3457 Rewriter.clearPostInc();
3458 Value *IncV = Rewriter.expandCodeFor(Remainder, IntTy, InsertPt);
3459 const SCEV *IVOperExpr =
3460 SE.getAddExpr(SE.getUnknown(MapIVOper), SE.getUnknown(IncV));
3461 IVOper = Rewriter.expandCodeFor(IVOperExpr, IVTy, InsertPt);
3462 } else {
3463 IVOper = MapIVOper;
3464 }
3465
3466 FoundBase = true;
3467 break;
3468 }
3469 }
3470 if (!FoundBase && LeftOverExpr && !LeftOverExpr->isZero()) {
3471 // Expand the IV increment.
3472 Rewriter.clearPostInc();
3473 Value *IncV = Rewriter.expandCodeFor(LeftOverExpr, IntTy, InsertPt);
3474 const SCEV *IVOperExpr = SE.getAddExpr(SE.getUnknown(IVSrc),
3475 SE.getUnknown(IncV));
3476 IVOper = Rewriter.expandCodeFor(IVOperExpr, IVTy, InsertPt);
3477
3478 // If an IV increment can't be folded, use it as the next IV value.
3479 if (!canFoldIVIncExpr(LeftOverExpr, Inc.UserInst, Inc.IVOperand, TTI)) {
3480 assert(IVTy == IVOper->getType() && "inconsistent IV increment type");
3481 Bases.emplace_back(Accum, IVOper);
3482 IVSrc = IVOper;
3483 LeftOverExpr = nullptr;
3484 }
3485 }
3486 Type *OperTy = Inc.IVOperand->getType();
3487 if (IVTy != OperTy) {
3488 assert(SE.getTypeSizeInBits(IVTy) >= SE.getTypeSizeInBits(OperTy) &&
3489 "cannot extend a chained IV");
3490 IRBuilder<> Builder(InsertPt);
3491 IVOper = Builder.CreateTruncOrBitCast(IVOper, OperTy, "lsr.chain");
3492 }
3493 Inc.UserInst->replaceUsesOfWith(Inc.IVOperand, IVOper);
3494 if (auto *OperandIsInstr = dyn_cast<Instruction>(Inc.IVOperand))
3495 DeadInsts.emplace_back(OperandIsInstr);
3496 }
3497 // If LSR created a new, wider phi, we may also replace its postinc. We only
3498 // do this if we also found a wide value for the head of the chain.
3499 if (isa<PHINode>(Chain.tailUserInst())) {
3500 for (PHINode &Phi : L->getHeader()->phis()) {
3501 if (Phi.getType() != IVSrc->getType())
3502 continue;
3503 Instruction *PostIncV = dyn_cast<Instruction>(
3504 Phi.getIncomingValueForBlock(L->getLoopLatch()));
3505 if (!PostIncV || (SE.getSCEV(PostIncV) != SE.getSCEV(IVSrc)))
3506 continue;
3507 Value *IVOper = IVSrc;
3508 Type *PostIncTy = PostIncV->getType();
3509 if (IVTy != PostIncTy) {
3510 assert(PostIncTy->isPointerTy() && "mixing int/ptr IV types");
3511 IRBuilder<> Builder(L->getLoopLatch()->getTerminator());
3512 Builder.SetCurrentDebugLocation(PostIncV->getDebugLoc());
3513 IVOper = Builder.CreatePointerCast(IVSrc, PostIncTy, "lsr.chain");
3514 }
3515 Phi.replaceUsesOfWith(PostIncV, IVOper);
3516 DeadInsts.emplace_back(PostIncV);
3517 }
3518 }
3519}
3520
3521void LSRInstance::CollectFixupsAndInitialFormulae() {
3522 BranchInst *ExitBranch = nullptr;
3523 bool SaveCmp = TTI.canSaveCmp(L, &ExitBranch, &SE, &LI, &DT, &AC, &TLI);
3524
3525 // For calculating baseline cost
3527 DenseSet<const SCEV *> VisitedRegs;
3528 DenseSet<size_t> VisitedLSRUse;
3529
3530 for (const IVStrideUse &U : IU) {
3531 Instruction *UserInst = U.getUser();
3532 // Skip IV users that are part of profitable IV Chains.
3533 User::op_iterator UseI =
3534 find(UserInst->operands(), U.getOperandValToReplace());
3535 assert(UseI != UserInst->op_end() && "cannot find IV operand");
3536 if (IVIncSet.count(UseI)) {
3537 LLVM_DEBUG(dbgs() << "Use is in profitable chain: " << **UseI << '\n');
3538 continue;
3539 }
3540
3541 LSRUse::KindType Kind = LSRUse::Basic;
3542 MemAccessTy AccessTy;
3543 if (isAddressUse(TTI, UserInst, U.getOperandValToReplace())) {
3544 Kind = LSRUse::Address;
3545 AccessTy = getAccessType(TTI, UserInst, U.getOperandValToReplace());
3546 }
3547
3548 const SCEV *S = IU.getExpr(U);
3549 if (!S)
3550 continue;
3551 PostIncLoopSet TmpPostIncLoops = U.getPostIncLoops();
3552
3553 // Equality (== and !=) ICmps are special. We can rewrite (i == N) as
3554 // (N - i == 0), and this allows (N - i) to be the expression that we work
3555 // with rather than just N or i, so we can consider the register
3556 // requirements for both N and i at the same time. Limiting this code to
3557 // equality icmps is not a problem because all interesting loops use
3558 // equality icmps, thanks to IndVarSimplify.
3559 if (ICmpInst *CI = dyn_cast<ICmpInst>(UserInst)) {
3560 // If CI can be saved in some target, like replaced inside hardware loop
3561 // in PowerPC, no need to generate initial formulae for it.
3562 if (SaveCmp && CI == dyn_cast<ICmpInst>(ExitBranch->getCondition()))
3563 continue;
3564 if (CI->isEquality()) {
3565 // Swap the operands if needed to put the OperandValToReplace on the
3566 // left, for consistency.
3567 Value *NV = CI->getOperand(1);
3568 if (NV == U.getOperandValToReplace()) {
3569 CI->setOperand(1, CI->getOperand(0));
3570 CI->setOperand(0, NV);
3571 NV = CI->getOperand(1);
3572 Changed = true;
3573 }
3574
3575 // x == y --> x - y == 0
3576 const SCEV *N = SE.getSCEV(NV);
3577 if (SE.isLoopInvariant(N, L) && Rewriter.isSafeToExpand(N) &&
3578 (!NV->getType()->isPointerTy() ||
3579 SE.getPointerBase(N) == SE.getPointerBase(S))) {
3580 // S is normalized, so normalize N before folding it into S
3581 // to keep the result normalized.
3582 N = normalizeForPostIncUse(N, TmpPostIncLoops, SE);
3583 if (!N)
3584 continue;
3585 Kind = LSRUse::ICmpZero;
3586 S = SE.getMinusSCEV(N, S);
3587 } else if (L->isLoopInvariant(NV) &&
3588 (!isa<Instruction>(NV) ||
3589 DT.dominates(cast<Instruction>(NV), L->getHeader())) &&
3590 !NV->getType()->isPointerTy()) {
3591 // If we can't generally expand the expression (e.g. it contains
3592 // a divide), but it is already at a loop invariant point before the
3593 // loop, wrap it in an unknown (to prevent the expander from trying
3594 // to re-expand in a potentially unsafe way.) The restriction to
3595 // integer types is required because the unknown hides the base, and
3596 // SCEV can't compute the difference of two unknown pointers.
3597 N = SE.getUnknown(NV);
3598 N = normalizeForPostIncUse(N, TmpPostIncLoops, SE);
3599 if (!N)
3600 continue;
3601 Kind = LSRUse::ICmpZero;
3602 S = SE.getMinusSCEV(N, S);
3603 assert(!isa<SCEVCouldNotCompute>(S));
3604 }
3605
3606 // -1 and the negations of all interesting strides (except the negation
3607 // of -1) are now also interesting.
3608 for (size_t i = 0, e = Factors.size(); i != e; ++i)
3609 if (Factors[i] != -1)
3610 Factors.insert(-(uint64_t)Factors[i]);
3611 Factors.insert(-1);
3612 }
3613 }
3614
3615 // Get or create an LSRUse.
3616 std::pair<size_t, Immediate> P = getUse(S, Kind, AccessTy);
3617 size_t LUIdx = P.first;
3618 Immediate Offset = P.second;
3619 LSRUse &LU = Uses[LUIdx];
3620
3621 // Record the fixup.
3622 LSRFixup &LF = LU.getNewFixup();
3623 LF.UserInst = UserInst;
3624 LF.OperandValToReplace = U.getOperandValToReplace();
3625 LF.PostIncLoops = TmpPostIncLoops;
3626 LF.Offset = Offset;
3627 LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
3628
3629 // Create SCEV as Formula for calculating baseline cost
3630 if (!VisitedLSRUse.count(LUIdx) && !LF.isUseFullyOutsideLoop(L)) {
3631 Formula F;
3632 F.initialMatch(S, L, SE);
3633 BaselineCost.RateFormula(F, Regs, VisitedRegs, LU);
3634 VisitedLSRUse.insert(LUIdx);
3635 }
3636
3637 if (!LU.WidestFixupType ||
3638 SE.getTypeSizeInBits(LU.WidestFixupType) <
3639 SE.getTypeSizeInBits(LF.OperandValToReplace->getType()))
3640 LU.WidestFixupType = LF.OperandValToReplace->getType();
3641
3642 // If this is the first use of this LSRUse, give it a formula.
3643 if (LU.Formulae.empty()) {
3644 InsertInitialFormula(S, LU, LUIdx);
3645 CountRegisters(LU.Formulae.back(), LUIdx);
3646 }
3647 }
3648
3649 LLVM_DEBUG(print_fixups(dbgs()));
3650}
3651
3652/// Insert a formula for the given expression into the given use, separating out
3653/// loop-variant portions from loop-invariant and loop-computable portions.
3654void LSRInstance::InsertInitialFormula(const SCEV *S, LSRUse &LU,
3655 size_t LUIdx) {
3656 // Mark uses whose expressions cannot be expanded.
3657 if (!Rewriter.isSafeToExpand(S))
3658 LU.RigidFormula = true;
3659
3660 Formula F;
3661 F.initialMatch(S, L, SE);
3662 bool Inserted = InsertFormula(LU, LUIdx, F);
3663 assert(Inserted && "Initial formula already exists!"); (void)Inserted;
3664}
3665
3666/// Insert a simple single-register formula for the given expression into the
3667/// given use.
3668void
3669LSRInstance::InsertSupplementalFormula(const SCEV *S,
3670 LSRUse &LU, size_t LUIdx) {
3671 Formula F;
3672 F.BaseRegs.push_back(S);
3673 F.HasBaseReg = true;
3674 bool Inserted = InsertFormula(LU, LUIdx, F);
3675 assert(Inserted && "Supplemental formula already exists!"); (void)Inserted;
3676}
3677
3678/// Note which registers are used by the given formula, updating RegUses.
3679void LSRInstance::CountRegisters(const Formula &F, size_t LUIdx) {
3680 if (F.ScaledReg)
3681 RegUses.countRegister(F.ScaledReg, LUIdx);
3682 for (const SCEV *BaseReg : F.BaseRegs)
3683 RegUses.countRegister(BaseReg, LUIdx);
3684}
3685
3686/// If the given formula has not yet been inserted, add it to the list, and
3687/// return true. Return false otherwise.
3688bool LSRInstance::InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F) {
3689 // Do not insert formula that we will not be able to expand.
3690 assert(isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F) &&
3691 "Formula is illegal");
3692
3693 if (!LU.InsertFormula(F, *L))
3694 return false;
3695
3696 CountRegisters(F, LUIdx);
3697 return true;
3698}
3699
3700/// Check for other uses of loop-invariant values which we're tracking. These
3701/// other uses will pin these values in registers, making them less profitable
3702/// for elimination.
3703/// TODO: This currently misses non-constant addrec step registers.
3704/// TODO: Should this give more weight to users inside the loop?
3705void
3706LSRInstance::CollectLoopInvariantFixupsAndFormulae() {
3707 SmallVector<const SCEV *, 8> Worklist(RegUses.begin(), RegUses.end());
3709
3710 // Don't collect outside uses if we are favoring postinc - the instructions in
3711 // the loop are more important than the ones outside of it.
3712 if (AMK == TTI::AMK_PostIndexed)
3713 return;
3714
3715 while (!Worklist.empty()) {
3716 const SCEV *S = Worklist.pop_back_val();
3717
3718 // Don't process the same SCEV twice
3719 if (!Visited.insert(S).second)
3720 continue;
3721
3722 if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S))
3723 append_range(Worklist, N->operands());
3724 else if (const SCEVIntegralCastExpr *C = dyn_cast<SCEVIntegralCastExpr>(S))
3725 Worklist.push_back(C->getOperand());
3726 else if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
3727 Worklist.push_back(D->getLHS());
3728 Worklist.push_back(D->getRHS());
3729 } else if (const SCEVUnknown *US = dyn_cast<SCEVUnknown>(S)) {
3730 const Value *V = US->getValue();
3731 if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
3732 // Look for instructions defined outside the loop.
3733 if (L->contains(Inst)) continue;
3734 } else if (isa<Constant>(V))
3735 // Constants can be re-materialized.
3736 continue;
3737 for (const Use &U : V->uses()) {
3738 const Instruction *UserInst = dyn_cast<Instruction>(U.getUser());
3739 // Ignore non-instructions.
3740 if (!UserInst)
3741 continue;
3742 // Don't bother if the instruction is an EHPad.
3743 if (UserInst->isEHPad())
3744 continue;
3745 // Ignore instructions in other functions (as can happen with
3746 // Constants).
3747 if (UserInst->getParent()->getParent() != L->getHeader()->getParent())
3748 continue;
3749 // Ignore instructions not dominated by the loop.
3750 const BasicBlock *UseBB = !isa<PHINode>(UserInst) ?
3751 UserInst->getParent() :
3752 cast<PHINode>(UserInst)->getIncomingBlock(
3754 if (!DT.dominates(L->getHeader(), UseBB))
3755 continue;
3756 // Don't bother if the instruction is in a BB which ends in an EHPad.
3757 if (UseBB->getTerminator()->isEHPad())
3758 continue;
3759
3760 // Ignore cases in which the currently-examined value could come from
3761 // a basic block terminated with an EHPad. This checks all incoming
3762 // blocks of the phi node since it is possible that the same incoming
3763 // value comes from multiple basic blocks, only some of which may end
3764 // in an EHPad. If any of them do, a subsequent rewrite attempt by this
3765 // pass would try to insert instructions into an EHPad, hitting an
3766 // assertion.
3767 if (isa<PHINode>(UserInst)) {
3768 const auto *PhiNode = cast<PHINode>(UserInst);
3769 bool HasIncompatibleEHPTerminatedBlock = false;
3770 llvm::Value *ExpectedValue = U;
3771 for (unsigned int I = 0; I < PhiNode->getNumIncomingValues(); I++) {
3772 if (PhiNode->getIncomingValue(I) == ExpectedValue) {
3773 if (PhiNode->getIncomingBlock(I)->getTerminator()->isEHPad()) {
3774 HasIncompatibleEHPTerminatedBlock = true;
3775 break;
3776 }
3777 }
3778 }
3779 if (HasIncompatibleEHPTerminatedBlock) {
3780 continue;
3781 }
3782 }
3783
3784 // Don't bother rewriting PHIs in catchswitch blocks.
3785 if (isa<CatchSwitchInst>(UserInst->getParent()->getTerminator()))
3786 continue;
3787 // Ignore uses which are part of other SCEV expressions, to avoid
3788 // analyzing them multiple times.
3789 if (SE.isSCEVable(UserInst->getType())) {
3790 const SCEV *UserS = SE.getSCEV(const_cast<Instruction *>(UserInst));
3791 // If the user is a no-op, look through to its uses.
3792 if (!isa<SCEVUnknown>(UserS))
3793 continue;
3794 if (UserS == US) {
3795 Worklist.push_back(
3796 SE.getUnknown(const_cast<Instruction *>(UserInst)));
3797 continue;
3798 }
3799 }
3800 // Ignore icmp instructions which are already being analyzed.
3801 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(UserInst)) {
3802 unsigned OtherIdx = !U.getOperandNo();
3803 Value *OtherOp = const_cast<Value *>(ICI->getOperand(OtherIdx));
3804 if (SE.hasComputableLoopEvolution(SE.getSCEV(OtherOp), L))
3805 continue;
3806 }
3807
3808 std::pair<size_t, Immediate> P =
3809 getUse(S, LSRUse::Basic, MemAccessTy());
3810 size_t LUIdx = P.first;
3811 Immediate Offset = P.second;
3812 LSRUse &LU = Uses[LUIdx];
3813 LSRFixup &LF = LU.getNewFixup();
3814 LF.UserInst = const_cast<Instruction *>(UserInst);
3815 LF.OperandValToReplace = U;
3816 LF.Offset = Offset;
3817 LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
3818 if (!LU.WidestFixupType ||
3819 SE.getTypeSizeInBits(LU.WidestFixupType) <
3820 SE.getTypeSizeInBits(LF.OperandValToReplace->getType()))
3821 LU.WidestFixupType = LF.OperandValToReplace->getType();
3822 InsertSupplementalFormula(US, LU, LUIdx);
3823 CountRegisters(LU.Formulae.back(), Uses.size() - 1);
3824 break;
3825 }
3826 }
3827 }
3828}
3829
3830/// Split S into subexpressions which can be pulled out into separate
3831/// registers. If C is non-null, multiply each subexpression by C.
3832///
3833/// Return remainder expression after factoring the subexpressions captured by
3834/// Ops. If Ops is complete, return NULL.
3835static const SCEV *CollectSubexprs(const SCEV *S, const SCEVConstant *C,
3837 const Loop *L,
3838 ScalarEvolution &SE,
3839 unsigned Depth = 0) {
3840 // Arbitrarily cap recursion to protect compile time.
3841 if (Depth >= 3)
3842 return S;
3843
3844 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3845 // Break out add operands.
3846 for (const SCEV *S : Add->operands()) {
3847 const SCEV *Remainder = CollectSubexprs(S, C, Ops, L, SE, Depth+1);
3848 if (Remainder)
3849 Ops.push_back(C ? SE.getMulExpr(C, Remainder) : Remainder);
3850 }
3851 return nullptr;
3852 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
3853 // Split a non-zero base out of an addrec.
3854 if (AR->getStart()->isZero() || !AR->isAffine())
3855 return S;
3856
3857 const SCEV *Remainder = CollectSubexprs(AR->getStart(),
3858 C, Ops, L, SE, Depth+1);
3859 // Split the non-zero AddRec unless it is part of a nested recurrence that
3860 // does not pertain to this loop.
3861 if (Remainder && (AR->getLoop() == L || !isa<SCEVAddRecExpr>(Remainder))) {
3862 Ops.push_back(C ? SE.getMulExpr(C, Remainder) : Remainder);
3863 Remainder = nullptr;
3864 }
3865 if (Remainder != AR->getStart()) {
3866 if (!Remainder)
3867 Remainder = SE.getConstant(AR->getType(), 0);
3868 return SE.getAddRecExpr(Remainder,
3869 AR->getStepRecurrence(SE),
3870 AR->getLoop(),
3871 //FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
3873 }
3874 } else if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3875 // Break (C * (a + b + c)) into C*a + C*b + C*c.
3876 if (Mul->getNumOperands() != 2)
3877 return S;
3878 if (const SCEVConstant *Op0 =
3879 dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3880 C = C ? cast<SCEVConstant>(SE.getMulExpr(C, Op0)) : Op0;
3881 const SCEV *Remainder =
3882 CollectSubexprs(Mul->getOperand(1), C, Ops, L, SE, Depth+1);
3883 if (Remainder)
3884 Ops.push_back(SE.getMulExpr(C, Remainder));
3885 return nullptr;
3886 }
3887 }
3888 return S;
3889}
3890
3891/// Return true if the SCEV represents a value that may end up as a
3892/// post-increment operation.
3894 LSRUse &LU, const SCEV *S, const Loop *L,
3895 ScalarEvolution &SE) {
3896 if (LU.Kind != LSRUse::Address ||
3897 !LU.AccessTy.getType()->isIntOrIntVectorTy())
3898 return false;
3899 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S);
3900 if (!AR)
3901 return false;
3902 const SCEV *LoopStep = AR->getStepRecurrence(SE);
3903 if (!isa<SCEVConstant>(LoopStep))
3904 return false;
3905 // Check if a post-indexed load/store can be used.
3908 const SCEV *LoopStart = AR->getStart();
3909 if (!isa<SCEVConstant>(LoopStart) && SE.isLoopInvariant(LoopStart, L))
3910 return true;
3911 }
3912 return false;
3913}
3914
3915/// Helper function for LSRInstance::GenerateReassociations.
3916void LSRInstance::GenerateReassociationsImpl(LSRUse &LU, unsigned LUIdx,
3917 const Formula &Base,
3918 unsigned Depth, size_t Idx,
3919 bool IsScaledReg) {
3920 const SCEV *BaseReg = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];
3921 // Don't generate reassociations for the base register of a value that
3922 // may generate a post-increment operator. The reason is that the
3923 // reassociations cause extra base+register formula to be created,
3924 // and possibly chosen, but the post-increment is more efficient.
3925 if (AMK == TTI::AMK_PostIndexed && mayUsePostIncMode(TTI, LU, BaseReg, L, SE))
3926 return;
3928 const SCEV *Remainder = CollectSubexprs(BaseReg, nullptr, AddOps, L, SE);
3929 if (Remainder)
3930 AddOps.push_back(Remainder);
3931
3932 if (AddOps.size() == 1)
3933 return;
3934
3936 JE = AddOps.end();
3937 J != JE; ++J) {
3938 // Loop-variant "unknown" values are uninteresting; we won't be able to
3939 // do anything meaningful with them.
3940 if (isa<SCEVUnknown>(*J) && !SE.isLoopInvariant(*J, L))
3941 continue;
3942
3943 // Don't pull a constant into a register if the constant could be folded
3944 // into an immediate field.
3945 if (isAlwaysFoldable(TTI, SE, LU.MinOffset, LU.MaxOffset, LU.Kind,
3946 LU.AccessTy, *J, Base.getNumRegs() > 1))
3947 continue;
3948
3949 // Collect all operands except *J.
3950 SmallVector<const SCEV *, 8> InnerAddOps(
3951 ((const SmallVector<const SCEV *, 8> &)AddOps).begin(), J);
3952 InnerAddOps.append(std::next(J),
3953 ((const SmallVector<const SCEV *, 8> &)AddOps).end());
3954
3955 // Don't leave just a constant behind in a register if the constant could
3956 // be folded into an immediate field.
3957 if (InnerAddOps.size() == 1 &&
3958 isAlwaysFoldable(TTI, SE, LU.MinOffset, LU.MaxOffset, LU.Kind,
3959 LU.AccessTy, InnerAddOps[0], Base.getNumRegs() > 1))
3960 continue;
3961
3962 const SCEV *InnerSum = SE.getAddExpr(InnerAddOps);
3963 if (InnerSum->isZero())
3964 continue;
3965 Formula F = Base;
3966
3967 if (F.UnfoldedOffset.isNonZero() && F.UnfoldedOffset.isScalable())
3968 continue;
3969
3970 // Add the remaining pieces of the add back into the new formula.
3971 const SCEVConstant *InnerSumSC = dyn_cast<SCEVConstant>(InnerSum);
3972 if (InnerSumSC && SE.getTypeSizeInBits(InnerSumSC->getType()) <= 64 &&
3973 TTI.isLegalAddImmediate((uint64_t)F.UnfoldedOffset.getFixedValue() +
3974 InnerSumSC->getValue()->getZExtValue())) {
3975 F.UnfoldedOffset =
3976 Immediate::getFixed((uint64_t)F.UnfoldedOffset.getFixedValue() +
3977 InnerSumSC->getValue()->getZExtValue());
3978 if (IsScaledReg) {
3979 F.ScaledReg = nullptr;
3980 F.Scale = 0;
3981 } else
3982 F.BaseRegs.erase(F.BaseRegs.begin() + Idx);
3983 } else if (IsScaledReg)
3984 F.ScaledReg = InnerSum;
3985 else
3986 F.BaseRegs[Idx] = InnerSum;
3987
3988 // Add J as its own register, or an unfolded immediate.
3989 const SCEVConstant *SC = dyn_cast<SCEVConstant>(*J);
3990 if (SC && SE.getTypeSizeInBits(SC->getType()) <= 64 &&
3991 TTI.isLegalAddImmediate((uint64_t)F.UnfoldedOffset.getFixedValue() +
3992 SC->getValue()->getZExtValue()))
3993 F.UnfoldedOffset =
3994 Immediate::getFixed((uint64_t)F.UnfoldedOffset.getFixedValue() +
3995 SC->getValue()->getZExtValue());
3996 else
3997 F.BaseRegs.push_back(*J);
3998 // We may have changed the number of register in base regs, adjust the
3999 // formula accordingly.
4000 F.canonicalize(*L);
4001
4002 if (InsertFormula(LU, LUIdx, F))
4003 // If that formula hadn't been seen before, recurse to find more like
4004 // it.
4005 // Add check on Log16(AddOps.size()) - same as Log2_32(AddOps.size()) >> 2)
4006 // Because just Depth is not enough to bound compile time.
4007 // This means that every time AddOps.size() is greater 16^x we will add
4008 // x to Depth.
4009 GenerateReassociations(LU, LUIdx, LU.Formulae.back(),
4010 Depth + 1 + (Log2_32(AddOps.size()) >> 2));
4011 }
4012}
4013
4014/// Split out subexpressions from adds and the bases of addrecs.
4015void LSRInstance::GenerateReassociations(LSRUse &LU, unsigned LUIdx,
4016 Formula Base, unsigned Depth) {
4017 assert(Base.isCanonical(*L) && "Input must be in the canonical form");
4018 // Arbitrarily cap recursion to protect compile time.
4019 if (Depth >= 3)
4020 return;
4021
4022 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
4023 GenerateReassociationsImpl(LU, LUIdx, Base, Depth, i);
4024
4025 if (Base.Scale == 1)
4026 GenerateReassociationsImpl(LU, LUIdx, Base, Depth,
4027 /* Idx */ -1, /* IsScaledReg */ true);
4028}
4029
4030/// Generate a formula consisting of all of the loop-dominating registers added
4031/// into a single register.
4032void LSRInstance::GenerateCombinations(LSRUse &LU, unsigned LUIdx,
4033 Formula Base) {
4034 // This method is only interesting on a plurality of registers.
4035 if (Base.BaseRegs.size() + (Base.Scale == 1) +
4036 (Base.UnfoldedOffset.isNonZero()) <=
4037 1)
4038 return;
4039
4040 // Flatten the representation, i.e., reg1 + 1*reg2 => reg1 + reg2, before
4041 // processing the formula.
4042 Base.unscale();
4044 Formula NewBase = Base;
4045 NewBase.BaseRegs.clear();
4046 Type *CombinedIntegerType = nullptr;
4047 for (const SCEV *BaseReg : Base.BaseRegs) {
4048 if (SE.properlyDominates(BaseReg, L->getHeader()) &&
4049 !SE.hasComputableLoopEvolution(BaseReg, L)) {
4050 if (!CombinedIntegerType)
4051 CombinedIntegerType = SE.getEffectiveSCEVType(BaseReg->getType());
4052 Ops.push_back(BaseReg);
4053 }
4054 else
4055 NewBase.BaseRegs.push_back(BaseReg);
4056 }
4057
4058 // If no register is relevant, we're done.
4059 if (Ops.size() == 0)
4060 return;
4061
4062 // Utility function for generating the required variants of the combined
4063 // registers.
4064 auto GenerateFormula = [&](const SCEV *Sum) {
4065 Formula F = NewBase;
4066
4067 // TODO: If Sum is zero, it probably means ScalarEvolution missed an
4068 // opportunity to fold something. For now, just ignore such cases
4069 // rather than proceed with zero in a register.
4070 if (Sum->isZero())
4071 return;
4072
4073 F.BaseRegs.push_back(Sum);
4074 F.canonicalize(*L);
4075 (void)InsertFormula(LU, LUIdx, F);
4076 };
4077
4078 // If we collected at least two registers, generate a formula combining them.
4079 if (Ops.size() > 1) {
4080 SmallVector<const SCEV *, 4> OpsCopy(Ops); // Don't let SE modify Ops.
4081 GenerateFormula(SE.getAddExpr(OpsCopy));
4082 }
4083
4084 // If we have an unfolded offset, generate a formula combining it with the
4085 // registers collected.
4086 if (NewBase.UnfoldedOffset.isNonZero() && NewBase.UnfoldedOffset.isFixed()) {
4087 assert(CombinedIntegerType && "Missing a type for the unfolded offset");
4088 Ops.push_back(SE.getConstant(CombinedIntegerType,
4089 NewBase.UnfoldedOffset.getFixedValue(), true));
4090 NewBase.UnfoldedOffset = Immediate::getFixed(0);
4091 GenerateFormula(SE.getAddExpr(Ops));
4092 }
4093}
4094
4095/// Helper function for LSRInstance::GenerateSymbolicOffsets.
4096void LSRInstance::GenerateSymbolicOffsetsImpl(LSRUse &LU, unsigned LUIdx,
4097 const Formula &Base, size_t Idx,
4098 bool IsScaledReg) {
4099 const SCEV *G = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];
4100 GlobalValue *GV = ExtractSymbol(G, SE);
4101 if (G->isZero() || !GV)
4102 return;
4103 Formula F = Base;
4104 F.BaseGV = GV;
4105 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F))
4106 return;
4107 if (IsScaledReg)
4108 F.ScaledReg = G;
4109 else
4110 F.BaseRegs[Idx] = G;
4111 (void)InsertFormula(LU, LUIdx, F);
4112}
4113
4114/// Generate reuse formulae using symbolic offsets.
4115void LSRInstance::GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx,
4116 Formula Base) {
4117 // We can't add a symbolic offset if the address already contains one.
4118 if (Base.BaseGV) return;
4119
4120 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
4121 GenerateSymbolicOffsetsImpl(LU, LUIdx, Base, i);
4122 if (Base.Scale == 1)
4123 GenerateSymbolicOffsetsImpl(LU, LUIdx, Base, /* Idx */ -1,
4124 /* IsScaledReg */ true);
4125}
4126
4127/// Helper function for LSRInstance::GenerateConstantOffsets.
4128void LSRInstance::GenerateConstantOffsetsImpl(
4129 LSRUse &LU, unsigned LUIdx, const Formula &Base,
4130 const SmallVectorImpl<Immediate> &Worklist, size_t Idx, bool IsScaledReg) {
4131
4132 auto GenerateOffset = [&](const SCEV *G, Immediate Offset) {
4133 Formula F = Base;
4134 if (!Base.BaseOffset.isCompatibleImmediate(Offset))
4135 return;
4136 F.BaseOffset = Base.BaseOffset.subUnsigned(Offset);
4137
4138 if (isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F)) {
4139 // Add the offset to the base register.
4140 const SCEV *NewOffset = Offset.getSCEV(SE, G->getType());
4141 const SCEV *NewG = SE.getAddExpr(NewOffset, G);
4142 // If it cancelled out, drop the base register, otherwise update it.
4143 if (NewG->isZero()) {
4144 if (IsScaledReg) {
4145 F.Scale = 0;
4146 F.ScaledReg = nullptr;
4147 } else
4148 F.deleteBaseReg(F.BaseRegs[Idx]);
4149 F.canonicalize(*L);
4150 } else if (IsScaledReg)
4151 F.ScaledReg = NewG;
4152 else
4153 F.BaseRegs[Idx] = NewG;
4154
4155 (void)InsertFormula(LU, LUIdx, F);
4156 }
4157 };
4158
4159 const SCEV *G = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];
4160
4161 // With constant offsets and constant steps, we can generate pre-inc
4162 // accesses by having the offset equal the step. So, for access #0 with a
4163 // step of 8, we generate a G - 8 base which would require the first access
4164 // to be ((G - 8) + 8),+,8. The pre-indexed access then updates the pointer
4165 // for itself and hopefully becomes the base for other accesses. This means
4166 // means that a single pre-indexed access can be generated to become the new
4167 // base pointer for each iteration of the loop, resulting in no extra add/sub
4168 // instructions for pointer updating.
4169 if (AMK == TTI::AMK_PreIndexed && LU.Kind == LSRUse::Address) {
4170 if (auto *GAR = dyn_cast<SCEVAddRecExpr>(G)) {
4171 if (auto *StepRec =
4172 dyn_cast<SCEVConstant>(GAR->getStepRecurrence(SE))) {
4173 const APInt &StepInt = StepRec->getAPInt();
4174 int64_t Step = StepInt.isNegative() ?
4175 StepInt.getSExtValue() : StepInt.getZExtValue();
4176
4177 for (Immediate Offset : Worklist) {
4178 if (Offset.isFixed()) {
4179 Offset = Immediate::getFixed(Offset.getFixedValue() - Step);
4180 GenerateOffset(G, Offset);
4181 }
4182 }
4183 }
4184 }
4185 }
4186 for (Immediate Offset : Worklist)
4187 GenerateOffset(G, Offset);
4188
4189 Immediate Imm = ExtractImmediate(G, SE);
4190 if (G->isZero() || Imm.isZero() ||
4191 !Base.BaseOffset.isCompatibleImmediate(Imm))
4192 return;
4193 Formula F = Base;
4194 F.BaseOffset = F.BaseOffset.addUnsigned(Imm);
4195 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F))
4196 return;
4197 if (IsScaledReg) {
4198 F.ScaledReg = G;
4199 } else {
4200 F.BaseRegs[Idx] = G;
4201 // We may generate non canonical Formula if G is a recurrent expr reg
4202 // related with current loop while F.ScaledReg is not.
4203 F.canonicalize(*L);
4204 }
4205 (void)InsertFormula(LU, LUIdx, F);
4206}
4207
4208/// GenerateConstantOffsets - Generate reuse formulae using symbolic offsets.
4209void LSRInstance::GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx,
4210 Formula Base) {
4211 // TODO: For now, just add the min and max offset, because it usually isn't
4212 // worthwhile looking at everything inbetween.
4214 Worklist.push_back(LU.MinOffset);
4215 if (LU.MaxOffset != LU.MinOffset)
4216 Worklist.push_back(LU.MaxOffset);
4217
4218 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
4219 GenerateConstantOffsetsImpl(LU, LUIdx, Base, Worklist, i);
4220 if (Base.Scale == 1)
4221 GenerateConstantOffsetsImpl(LU, LUIdx, Base, Worklist, /* Idx */ -1,
4222 /* IsScaledReg */ true);
4223}
4224
4225/// For ICmpZero, check to see if we can scale up the comparison. For example, x
4226/// == y -> x*c == y*c.
4227void LSRInstance::GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx,
4228 Formula Base) {
4229 if (LU.Kind != LSRUse::ICmpZero) return;
4230
4231 // Determine the integer type for the base formula.
4232 Type *IntTy = Base.getType();
4233 if (!IntTy) return;
4234 if (SE.getTypeSizeInBits(IntTy) > 64) return;
4235
4236 // Don't do this if there is more than one offset.
4237 if (LU.MinOffset != LU.MaxOffset) return;
4238
4239 // Check if transformation is valid. It is illegal to multiply pointer.
4240 if (Base.ScaledReg && Base.ScaledReg->getType()->isPointerTy())
4241 return;
4242 for (const SCEV *BaseReg : Base.BaseRegs)
4243 if (BaseReg->getType()->isPointerTy())
4244 return;
4245 assert(!Base.BaseGV && "ICmpZero use is not legal!");
4246
4247 // Check each interesting stride.
4248 for (int64_t Factor : Factors) {
4249 // Check that Factor can be represented by IntTy
4250 if (!ConstantInt::isValueValidForType(IntTy, Factor))
4251 continue;
4252 // Check that the multiplication doesn't overflow.
4253 if (Base.BaseOffset.isMin() && Factor == -1)
4254 continue;
4255 // Not supporting scalable immediates.
4256 if (Base.BaseOffset.isNonZero() && Base.BaseOffset.isScalable())
4257 continue;
4258 Immediate NewBaseOffset = Base.BaseOffset.mulUnsigned(Factor);
4259 assert(Factor != 0 && "Zero factor not expected!");
4260 if (NewBaseOffset.getFixedValue() / Factor !=
4261 Base.BaseOffset.getFixedValue())
4262 continue;
4263 // If the offset will be truncated at this use, check that it is in bounds.
4264 if (!IntTy->isPointerTy() &&
4265 !ConstantInt::isValueValidForType(IntTy, NewBaseOffset.getFixedValue()))
4266 continue;
4267
4268 // Check that multiplying with the use offset doesn't overflow.
4269 Immediate Offset = LU.MinOffset;
4270 if (Offset.isMin() && Factor == -1)
4271 continue;
4272 Offset = Offset.mulUnsigned(Factor);
4273 if (Offset.getFixedValue() / Factor != LU.MinOffset.getFixedValue())
4274 continue;
4275 // If the offset will be truncated at this use, check that it is in bounds.
4276 if (!IntTy->isPointerTy() &&
4277 !ConstantInt::isValueValidForType(IntTy, Offset.getFixedValue()))
4278 continue;
4279
4280 Formula F = Base;
4281 F.BaseOffset = NewBaseOffset;
4282
4283 // Check that this scale is legal.
4284 if (!isLegalUse(TTI, Offset, Offset, LU.Kind, LU.AccessTy, F))
4285 continue;
4286
4287 // Compensate for the use having MinOffset built into it.
4288 F.BaseOffset = F.BaseOffset.addUnsigned(Offset).subUnsigned(LU.MinOffset);
4289
4290 const SCEV *FactorS = SE.getConstant(IntTy, Factor);
4291
4292 // Check that multiplying with each base register doesn't overflow.
4293 for (size_t i = 0, e = F.BaseRegs.size(); i != e; ++i) {
4294 F.BaseRegs[i] = SE.getMulExpr(F.BaseRegs[i], FactorS);
4295 if (getExactSDiv(F.BaseRegs[i], FactorS, SE) != Base.BaseRegs[i])
4296 goto next;
4297 }
4298
4299 // Check that multiplying with the scaled register doesn't overflow.
4300 if (F.ScaledReg) {
4301 F.ScaledReg = SE.getMulExpr(F.ScaledReg, FactorS);
4302 if (getExactSDiv(F.ScaledReg, FactorS, SE) != Base.ScaledReg)
4303 continue;
4304 }
4305
4306 // Check that multiplying with the unfolded offset doesn't overflow.
4307 if (F.UnfoldedOffset.isNonZero()) {
4308 if (F.UnfoldedOffset.isMin() && Factor == -1)
4309 continue;
4310 F.UnfoldedOffset = F.UnfoldedOffset.mulUnsigned(Factor);
4311 if (F.UnfoldedOffset.getFixedValue() / Factor !=
4312 Base.UnfoldedOffset.getFixedValue())
4313 continue;
4314 // If the offset will be truncated, check that it is in bounds.
4316 IntTy, F.UnfoldedOffset.getFixedValue()))
4317 continue;
4318 }
4319
4320 // If we make it here and it's legal, add it.
4321 (void)InsertFormula(LU, LUIdx, F);
4322 next:;
4323 }
4324}
4325
4326/// Generate stride factor reuse formulae by making use of scaled-offset address
4327/// modes, for example.
4328void LSRInstance::GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base) {
4329 // Determine the integer type for the base formula.
4330 Type *IntTy = Base.getType();
4331 if (!IntTy) return;
4332
4333 // If this Formula already has a scaled register, we can't add another one.
4334 // Try to unscale the formula to generate a better scale.
4335 if (Base.Scale != 0 && !Base.unscale())
4336 return;
4337
4338 assert(Base.Scale == 0 && "unscale did not did its job!");
4339
4340 // Check each interesting stride.
4341 for (int64_t Factor : Factors) {
4342 Base.Scale = Factor;
4343 Base.HasBaseReg = Base.BaseRegs.size() > 1;
4344 // Check whether this scale is going to be legal.
4345 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy,
4346 Base)) {
4347 // As a special-case, handle special out-of-loop Basic users specially.
4348 // TODO: Reconsider this special case.
4349 if (LU.Kind == LSRUse::Basic &&
4350 isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LSRUse::Special,
4351 LU.AccessTy, Base) &&
4352 LU.AllFixupsOutsideLoop)
4353 LU.Kind = LSRUse::Special;
4354 else
4355 continue;
4356 }
4357 // For an ICmpZero, negating a solitary base register won't lead to
4358 // new solutions.
4359 if (LU.Kind == LSRUse::ICmpZero && !Base.HasBaseReg &&
4360 Base.BaseOffset.isZero() && !Base.BaseGV)
4361 continue;
4362 // For each addrec base reg, if its loop is current loop, apply the scale.
4363 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
4364 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Base.BaseRegs[i]);
4365 if (AR && (AR->getLoop() == L || LU.AllFixupsOutsideLoop)) {
4366 const SCEV *FactorS = SE.getConstant(IntTy, Factor);
4367 if (FactorS->isZero())
4368 continue;
4369 // Divide out the factor, ignoring high bits, since we'll be
4370 // scaling the value back up in the end.
4371 if (const SCEV *Quotient = getExactSDiv(AR, FactorS, SE, true))
4372 if (!Quotient->isZero()) {
4373 // TODO: This could be optimized to avoid all the copying.
4374 Formula F = Base;
4375 F.ScaledReg = Quotient;
4376 F.deleteBaseReg(F.BaseRegs[i]);
4377 // The canonical representation of 1*reg is reg, which is already in
4378 // Base. In that case, do not try to insert the formula, it will be
4379 // rejected anyway.
4380 if (F.Scale == 1 && (F.BaseRegs.empty() ||
4381 (AR->getLoop() != L && LU.AllFixupsOutsideLoop)))
4382 continue;
4383 // If AllFixupsOutsideLoop is true and F.Scale is 1, we may generate
4384 // non canonical Formula with ScaledReg's loop not being L.
4385 if (F.Scale == 1 && LU.AllFixupsOutsideLoop)
4386 F.canonicalize(*L);
4387 (void)InsertFormula(LU, LUIdx, F);
4388 }
4389 }
4390 }
4391 }
4392}
4393
4394/// Extend/Truncate \p Expr to \p ToTy considering post-inc uses in \p Loops.
4395/// For all PostIncLoopSets in \p Loops, first de-normalize \p Expr, then
4396/// perform the extension/truncate and normalize again, as the normalized form
4397/// can result in folds that are not valid in the post-inc use contexts. The
4398/// expressions for all PostIncLoopSets must match, otherwise return nullptr.
4399static const SCEV *
4401 const SCEV *Expr, Type *ToTy,
4402 ScalarEvolution &SE) {
4403 const SCEV *Result = nullptr;
4404 for (auto &L : Loops) {
4405 auto *DenormExpr = denormalizeForPostIncUse(Expr, L, SE);
4406 const SCEV *NewDenormExpr = SE.getAnyExtendExpr(DenormExpr, ToTy);
4407 const SCEV *New = normalizeForPostIncUse(NewDenormExpr, L, SE);
4408 if (!New || (Result && New != Result))
4409 return nullptr;
4410 Result = New;
4411 }
4412
4413 assert(Result && "failed to create expression");
4414 return Result;
4415}
4416
4417/// Generate reuse formulae from different IV types.
4418void LSRInstance::GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base) {
4419 // Don't bother truncating symbolic values.
4420 if (Base.BaseGV) return;
4421
4422 // Determine the integer type for the base formula.
4423 Type *DstTy = Base.getType();
4424 if (!DstTy) return;
4425 if (DstTy->isPointerTy())
4426 return;
4427
4428 // It is invalid to extend a pointer type so exit early if ScaledReg or
4429 // any of the BaseRegs are pointers.
4430 if (Base.ScaledReg && Base.ScaledReg->getType()->isPointerTy())
4431 return;
4432 if (any_of(Base.BaseRegs,
4433 [](const SCEV *S) { return S->getType()->isPointerTy(); }))
4434 return;
4435
4437 for (auto &LF : LU.Fixups)
4438 Loops.push_back(LF.PostIncLoops);
4439
4440 for (Type *SrcTy : Types) {
4441 if (SrcTy != DstTy && TTI.isTruncateFree(SrcTy, DstTy)) {
4442 Formula F = Base;
4443
4444 // Sometimes SCEV is able to prove zero during ext transform. It may
4445 // happen if SCEV did not do all possible transforms while creating the
4446 // initial node (maybe due to depth limitations), but it can do them while
4447 // taking ext.
4448 if (F.ScaledReg) {
4449 const SCEV *NewScaledReg =
4450 getAnyExtendConsideringPostIncUses(Loops, F.ScaledReg, SrcTy, SE);
4451 if (!NewScaledReg || NewScaledReg->isZero())
4452 continue;
4453 F.ScaledReg = NewScaledReg;
4454 }
4455 bool HasZeroBaseReg = false;
4456 for (const SCEV *&BaseReg : F.BaseRegs) {
4457 const SCEV *NewBaseReg =
4458 getAnyExtendConsideringPostIncUses(Loops, BaseReg, SrcTy, SE);
4459 if (!NewBaseReg || NewBaseReg->isZero()) {
4460 HasZeroBaseReg = true;
4461 break;
4462 }
4463 BaseReg = NewBaseReg;
4464 }
4465 if (HasZeroBaseReg)
4466 continue;
4467
4468 // TODO: This assumes we've done basic processing on all uses and
4469 // have an idea what the register usage is.
4470 if (!F.hasRegsUsedByUsesOtherThan(LUIdx, RegUses))
4471 continue;
4472
4473 F.canonicalize(*L);
4474 (void)InsertFormula(LU, LUIdx, F);
4475 }
4476 }
4477}
4478
4479namespace {
4480
4481/// Helper class for GenerateCrossUseConstantOffsets. It's used to defer
4482/// modifications so that the search phase doesn't have to worry about the data
4483/// structures moving underneath it.
4484struct WorkItem {
4485 size_t LUIdx;
4486 Immediate Imm;
4487 const SCEV *OrigReg;
4488
4489 WorkItem(size_t LI, Immediate I, const SCEV *R)
4490 : LUIdx(LI), Imm(I), OrigReg(R) {}
4491
4492 void print(raw_ostream &OS) const;
4493 void dump() const;
4494};
4495
4496} // end anonymous namespace
4497
4498#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4499void WorkItem::print(raw_ostream &OS) const {
4500 OS << "in formulae referencing " << *OrigReg << " in use " << LUIdx
4501 << " , add offset " << Imm;
4502}
4503
4504LLVM_DUMP_METHOD void WorkItem::dump() const {
4505 print(errs()); errs() << '\n';
4506}
4507#endif
4508
4509/// Look for registers which are a constant distance apart and try to form reuse
4510/// opportunities between them.
4511void LSRInstance::GenerateCrossUseConstantOffsets() {
4512 // Group the registers by their value without any added constant offset.
4513 using ImmMapTy = std::map<Immediate, const SCEV *, KeyOrderTargetImmediate>;
4514
4518 for (const SCEV *Use : RegUses) {
4519 const SCEV *Reg = Use; // Make a copy for ExtractImmediate to modify.
4520 Immediate Imm = ExtractImmediate(Reg, SE);
4521 auto Pair = Map.insert(std::make_pair(Reg, ImmMapTy()));
4522 if (Pair.second)
4523 Sequence.push_back(Reg);
4524 Pair.first->second.insert(std::make_pair(Imm, Use));
4525 UsedByIndicesMap[Reg] |= RegUses.getUsedByIndices(Use);
4526 }
4527
4528 // Now examine each set of registers with the same base value. Build up
4529 // a list of work to do and do the work in a separate step so that we're
4530 // not adding formulae and register counts while we're searching.
4531 SmallVector<WorkItem, 32> WorkItems;
4532 SmallSet<std::pair<size_t, Immediate>, 32, KeyOrderSizeTAndImmediate>
4533 UniqueItems;
4534 for (const SCEV *Reg : Sequence) {
4535 const ImmMapTy &Imms = Map.find(Reg)->second;
4536
4537 // It's not worthwhile looking for reuse if there's only one offset.
4538 if (Imms.size() == 1)
4539 continue;
4540
4541 LLVM_DEBUG(dbgs() << "Generating cross-use offsets for " << *Reg << ':';
4542 for (const auto &Entry
4543 : Imms) dbgs()
4544 << ' ' << Entry.first;
4545 dbgs() << '\n');
4546
4547 // Examine each offset.
4548 for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end();
4549 J != JE; ++J) {
4550 const SCEV *OrigReg = J->second;
4551
4552 Immediate JImm = J->first;
4553 const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(OrigReg);
4554
4555 if (!isa<SCEVConstant>(OrigReg) &&
4556 UsedByIndicesMap[Reg].count() == 1) {
4557 LLVM_DEBUG(dbgs() << "Skipping cross-use reuse for " << *OrigReg
4558 << '\n');
4559 continue;
4560 }
4561
4562 // Conservatively examine offsets between this orig reg a few selected
4563 // other orig regs.
4564 Immediate First = Imms.begin()->first;
4565 Immediate Last = std::prev(Imms.end())->first;
4566 if (!First.isCompatibleImmediate(Last)) {
4567 LLVM_DEBUG(dbgs() << "Skipping cross-use reuse for " << *OrigReg
4568 << "\n");
4569 continue;
4570 }
4571 // Only scalable if both terms are scalable, or if one is scalable and
4572 // the other is 0.
4573 bool Scalable = First.isScalable() || Last.isScalable();
4574 int64_t FI = First.getKnownMinValue();
4575 int64_t LI = Last.getKnownMinValue();
4576 // Compute (First + Last) / 2 without overflow using the fact that
4577 // First + Last = 2 * (First + Last) + (First ^ Last).
4578 int64_t Avg = (FI & LI) + ((FI ^ LI) >> 1);
4579 // If the result is negative and FI is odd and LI even (or vice versa),
4580 // we rounded towards -inf. Add 1 in that case, to round towards 0.
4581 Avg = Avg + ((FI ^ LI) & ((uint64_t)Avg >> 63));
4582 ImmMapTy::const_iterator OtherImms[] = {
4583 Imms.begin(), std::prev(Imms.end()),
4584 Imms.lower_bound(Immediate::get(Avg, Scalable))};
4585 for (const auto &M : OtherImms) {
4586 if (M == J || M == JE) continue;
4587 if (!JImm.isCompatibleImmediate(M->first))
4588 continue;
4589
4590 // Compute the difference between the two.
4591 Immediate Imm = JImm.subUnsigned(M->first);
4592 for (unsigned LUIdx : UsedByIndices.set_bits())
4593 // Make a memo of this use, offset, and register tuple.
4594 if (UniqueItems.insert(std::make_pair(LUIdx, Imm)).second)
4595 WorkItems.push_back(WorkItem(LUIdx, Imm, OrigReg));
4596 }
4597 }
4598 }
4599
4600 Map.clear();
4601 Sequence.clear();
4602 UsedByIndicesMap.clear();
4603 UniqueItems.clear();
4604
4605 // Now iterate through the worklist and add new formulae.
4606 for (const WorkItem &WI : WorkItems) {
4607 size_t LUIdx = WI.LUIdx;
4608 LSRUse &LU = Uses[LUIdx];
4609 Immediate Imm = WI.Imm;
4610 const SCEV *OrigReg = WI.OrigReg;
4611
4612 Type *IntTy = SE.getEffectiveSCEVType(OrigReg->getType());
4613 const SCEV *NegImmS = Imm.getNegativeSCEV(SE, IntTy);
4614 unsigned BitWidth = SE.getTypeSizeInBits(IntTy);
4615
4616 // TODO: Use a more targeted data structure.
4617 for (size_t L = 0, LE = LU.Formulae.size(); L != LE; ++L) {
4618 Formula F = LU.Formulae[L];
4619 // FIXME: The code for the scaled and unscaled registers looks
4620 // very similar but slightly different. Investigate if they
4621 // could be merged. That way, we would not have to unscale the
4622 // Formula.
4623 F.unscale();
4624 // Use the immediate in the scaled register.
4625 if (F.ScaledReg == OrigReg) {
4626 if (!F.BaseOffset.isCompatibleImmediate(Imm))
4627 continue;
4628 Immediate Offset = F.BaseOffset.addUnsigned(Imm.mulUnsigned(F.Scale));
4629 // Don't create 50 + reg(-50).
4630 const SCEV *S = Offset.getNegativeSCEV(SE, IntTy);
4631 if (F.referencesReg(S))
4632 continue;
4633 Formula NewF = F;
4634 NewF.BaseOffset = Offset;
4635 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy,
4636 NewF))
4637 continue;
4638 NewF.ScaledReg = SE.getAddExpr(NegImmS, NewF.ScaledReg);
4639
4640 // If the new scale is a constant in a register, and adding the constant
4641 // value to the immediate would produce a value closer to zero than the
4642 // immediate itself, then the formula isn't worthwhile.
4643 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(NewF.ScaledReg)) {
4644 // FIXME: Do we need to do something for scalable immediates here?
4645 // A scalable SCEV won't be constant, but we might still have
4646 // something in the offset? Bail out for now to be safe.
4647 if (NewF.BaseOffset.isNonZero() && NewF.BaseOffset.isScalable())
4648 continue;
4649 if (C->getValue()->isNegative() !=
4650 (NewF.BaseOffset.isLessThanZero()) &&
4651 (C->getAPInt().abs() * APInt(BitWidth, F.Scale))
4652 .ule(std::abs(NewF.BaseOffset.getFixedValue())))
4653 continue;
4654 }
4655
4656 // OK, looks good.
4657 NewF.canonicalize(*this->L);
4658 (void)InsertFormula(LU, LUIdx, NewF);
4659 } else {
4660 // Use the immediate in a base register.
4661 for (size_t N = 0, NE = F.BaseRegs.size(); N != NE; ++N) {
4662 const SCEV *BaseReg = F.BaseRegs[N];
4663 if (BaseReg != OrigReg)
4664 continue;
4665 Formula NewF = F;
4666 if (!NewF.BaseOffset.isCompatibleImmediate(Imm) ||
4667 !NewF.UnfoldedOffset.isCompatibleImmediate(Imm) ||
4668 !NewF.BaseOffset.isCompatibleImmediate(NewF.UnfoldedOffset))
4669 continue;
4670 NewF.BaseOffset = NewF.BaseOffset.addUnsigned(Imm);
4671 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset,
4672 LU.Kind, LU.AccessTy, NewF)) {
4673 if (AMK == TTI::AMK_PostIndexed &&
4674 mayUsePostIncMode(TTI, LU, OrigReg, this->L, SE))
4675 continue;
4676 Immediate NewUnfoldedOffset = NewF.UnfoldedOffset.addUnsigned(Imm);
4677 if (!isLegalAddImmediate(TTI, NewUnfoldedOffset))
4678 continue;
4679 NewF = F;
4680 NewF.UnfoldedOffset = NewUnfoldedOffset;
4681 }
4682 NewF.BaseRegs[N] = SE.getAddExpr(NegImmS, BaseReg);
4683
4684 // If the new formula has a constant in a register, and adding the
4685 // constant value to the immediate would produce a value closer to
4686 // zero than the immediate itself, then the formula isn't worthwhile.
4687 for (const SCEV *NewReg : NewF.BaseRegs)
4688 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(NewReg)) {
4689 if (NewF.BaseOffset.isNonZero() && NewF.BaseOffset.isScalable())
4690 goto skip_formula;
4691 if ((C->getAPInt() + NewF.BaseOffset.getFixedValue())
4692 .abs()
4693 .slt(std::abs(NewF.BaseOffset.getFixedValue())) &&
4694 (C->getAPInt() + NewF.BaseOffset.getFixedValue())
4695 .countr_zero() >=
4696 (unsigned)llvm::countr_zero<uint64_t>(
4697 NewF.BaseOffset.getFixedValue()))
4698 goto skip_formula;
4699 }
4700
4701 // Ok, looks good.
4702 NewF.canonicalize(*this->L);
4703 (void)InsertFormula(LU, LUIdx, NewF);
4704 break;
4705 skip_formula:;
4706 }
4707 }
4708 }
4709 }
4710}
4711
4712/// Generate formulae for each use.
4713void
4714LSRInstance::GenerateAllReuseFormulae() {
4715 // This is split into multiple loops so that hasRegsUsedByUsesOtherThan
4716 // queries are more precise.
4717 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4718 LSRUse &LU = Uses[LUIdx];
4719 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4720 GenerateReassociations(LU, LUIdx, LU.Formulae[i]);
4721 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4722 GenerateCombinations(LU, LUIdx, LU.Formulae[i]);
4723 }
4724 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4725 LSRUse &LU = Uses[LUIdx];
4726 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4727 GenerateSymbolicOffsets(LU, LUIdx, LU.Formulae[i]);
4728 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4729 GenerateConstantOffsets(LU, LUIdx, LU.Formulae[i]);
4730 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4731 GenerateICmpZeroScales(LU, LUIdx, LU.Formulae[i]);
4732 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4733 GenerateScales(LU, LUIdx, LU.Formulae[i]);
4734 }
4735 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4736 LSRUse &LU = Uses[LUIdx];
4737 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4738 GenerateTruncates(LU, LUIdx, LU.Formulae[i]);
4739 }
4740
4741 GenerateCrossUseConstantOffsets();
4742
4743 LLVM_DEBUG(dbgs() << "\n"
4744 "After generating reuse formulae:\n";
4745 print_uses(dbgs()));
4746}
4747
4748/// If there are multiple formulae with the same set of registers used
4749/// by other uses, pick the best one and delete the others.
4750void LSRInstance::FilterOutUndesirableDedicatedRegisters() {
4751 DenseSet<const SCEV *> VisitedRegs;
4754#ifndef NDEBUG
4755 bool ChangedFormulae = false;
4756#endif
4757
4758 // Collect the best formula for each unique set of shared registers. This
4759 // is reset for each use.
4760 using BestFormulaeTy =
4761 DenseMap<SmallVector<const SCEV *, 4>, size_t, UniquifierDenseMapInfo>;
4762
4763 BestFormulaeTy BestFormulae;
4764
4765 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4766 LSRUse &LU = Uses[LUIdx];
4767 LLVM_DEBUG(dbgs() << "Filtering for use "; LU.print(dbgs());
4768 dbgs() << '\n');
4769
4770 bool Any = false;
4771 for (size_t FIdx = 0, NumForms = LU.Formulae.size();
4772 FIdx != NumForms; ++FIdx) {
4773 Formula &F = LU.Formulae[FIdx];
4774
4775 // Some formulas are instant losers. For example, they may depend on
4776 // nonexistent AddRecs from other loops. These need to be filtered
4777 // immediately, otherwise heuristics could choose them over others leading
4778 // to an unsatisfactory solution. Passing LoserRegs into RateFormula here
4779 // avoids the need to recompute this information across formulae using the
4780 // same bad AddRec. Passing LoserRegs is also essential unless we remove
4781 // the corresponding bad register from the Regs set.
4782 Cost CostF(L, SE, TTI, AMK);
4783 Regs.clear();
4784 CostF.RateFormula(F, Regs, VisitedRegs, LU, &LoserRegs);
4785 if (CostF.isLoser()) {
4786 // During initial formula generation, undesirable formulae are generated
4787 // by uses within other loops that have some non-trivial address mode or
4788 // use the postinc form of the IV. LSR needs to provide these formulae
4789 // as the basis of rediscovering the desired formula that uses an AddRec
4790 // corresponding to the existing phi. Once all formulae have been
4791 // generated, these initial losers may be pruned.
4792 LLVM_DEBUG(dbgs() << " Filtering loser "; F.print(dbgs());
4793 dbgs() << "\n");
4794 }
4795 else {
4797 for (const SCEV *Reg : F.BaseRegs) {
4798 if (RegUses.isRegUsedByUsesOtherThan(Reg, LUIdx))
4799 Key.push_back(Reg);
4800 }
4801 if (F.ScaledReg &&
4802 RegUses.isRegUsedByUsesOtherThan(F.ScaledReg, LUIdx))
4803 Key.push_back(F.ScaledReg);
4804 // Unstable sort by host order ok, because this is only used for
4805 // uniquifying.
4806 llvm::sort(Key);
4807
4808 std::pair<BestFormulaeTy::const_iterator, bool> P =
4809 BestFormulae.insert(std::make_pair(Key, FIdx));
4810 if (P.second)
4811 continue;
4812
4813 Formula &Best = LU.Formulae[P.first->second];
4814
4815 Cost CostBest(L, SE, TTI, AMK);
4816 Regs.clear();
4817 CostBest.RateFormula(Best, Regs, VisitedRegs, LU);
4818 if (CostF.isLess(CostBest))
4819 std::swap(F, Best);
4820 LLVM_DEBUG(dbgs() << " Filtering out formula "; F.print(dbgs());
4821 dbgs() << "\n"
4822 " in favor of formula ";
4823 Best.print(dbgs()); dbgs() << '\n');
4824 }
4825#ifndef NDEBUG
4826 ChangedFormulae = true;
4827#endif
4828 LU.DeleteFormula(F);
4829 --FIdx;
4830 --NumForms;
4831 Any = true;
4832 }
4833
4834 // Now that we've filtered out some formulae, recompute the Regs set.
4835 if (Any)
4836 LU.RecomputeRegs(LUIdx, RegUses);
4837
4838 // Reset this to prepare for the next use.
4839 BestFormulae.clear();
4840 }
4841
4842 LLVM_DEBUG(if (ChangedFormulae) {
4843 dbgs() << "\n"
4844 "After filtering out undesirable candidates:\n";
4845 print_uses(dbgs());
4846 });
4847}
4848
4849/// Estimate the worst-case number of solutions the solver might have to
4850/// consider. It almost never considers this many solutions because it prune the
4851/// search space, but the pruning isn't always sufficient.
4852size_t LSRInstance::EstimateSearchSpaceComplexity() const {
4853 size_t Power = 1;
4854 for (const LSRUse &LU : Uses) {
4855 size_t FSize = LU.Formulae.size();
4856 if (FSize >= ComplexityLimit) {
4857 Power = ComplexityLimit;
4858 break;
4859 }
4860 Power *= FSize;
4861 if (Power >= ComplexityLimit)
4862 break;
4863 }
4864 return Power;
4865}
4866
4867/// When one formula uses a superset of the registers of another formula, it
4868/// won't help reduce register pressure (though it may not necessarily hurt
4869/// register pressure); remove it to simplify the system.
4870void LSRInstance::NarrowSearchSpaceByDetectingSupersets() {
4871 if (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
4872 LLVM_DEBUG(dbgs() << "The search space is too complex.\n");
4873
4874 LLVM_DEBUG(dbgs() << "Narrowing the search space by eliminating formulae "
4875 "which use a superset of registers used by other "
4876 "formulae.\n");
4877
4878 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4879 LSRUse &LU = Uses[LUIdx];
4880 bool Any = false;
4881 for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
4882 Formula &F = LU.Formulae[i];
4883 if (F.BaseOffset.isNonZero() && F.BaseOffset.isScalable())
4884 continue;
4885 // Look for a formula with a constant or GV in a register. If the use
4886 // also has a formula with that same value in an immediate field,
4887 // delete the one that uses a register.
4889 I = F.BaseRegs.begin(), E = F.BaseRegs.end(); I != E; ++I) {
4890 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(*I)) {
4891 Formula NewF = F;
4892 //FIXME: Formulas should store bitwidth to do wrapping properly.
4893 // See PR41034.
4894 NewF.BaseOffset =
4895 Immediate::getFixed(NewF.BaseOffset.getFixedValue() +
4896 (uint64_t)C->getValue()->getSExtValue());
4897 NewF.BaseRegs.erase(NewF.BaseRegs.begin() +
4898 (I - F.BaseRegs.begin()));
4899 if (LU.HasFormulaWithSameRegs(NewF)) {
4900 LLVM_DEBUG(dbgs() << " Deleting "; F.print(dbgs());
4901 dbgs() << '\n');
4902 LU.DeleteFormula(F);
4903 --i;
4904 --e;
4905 Any = true;
4906 break;
4907 }
4908 } else if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(*I)) {
4909 if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue()))
4910 if (!F.BaseGV) {
4911 Formula NewF = F;
4912 NewF.BaseGV = GV;
4913 NewF.BaseRegs.erase(NewF.BaseRegs.begin() +
4914 (I - F.BaseRegs.begin()));
4915 if (LU.HasFormulaWithSameRegs(NewF)) {
4916 LLVM_DEBUG(dbgs() << " Deleting "; F.print(dbgs());
4917 dbgs() << '\n');
4918 LU.DeleteFormula(F);
4919 --i;
4920 --e;
4921 Any = true;
4922 break;
4923 }
4924 }
4925 }
4926 }
4927 }
4928 if (Any)
4929 LU.RecomputeRegs(LUIdx, RegUses);
4930 }
4931
4932 LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs()));
4933 }