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