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