llvm.org GIT mirror llvm / 7979b72
Revert LoopStrengthReduce.cpp to pre-r94061 for now. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@94123 91177308-0d34-0410-b5e6-96231b3b80d8 Dan Gohman 9 years ago
17 changed file(s) with 2451 addition(s) and 2744 deletion(s). Raw diff Collapse all Expand all
2626 /// and destroy it when finished to allow the release of the associated
2727 /// memory.
2828 class SCEVExpander : public SCEVVisitor {
29 public:
2930 ScalarEvolution &SE;
31
32 private:
3033 std::map, AssertingVH >
3134 InsertedExpressions;
3235 std::set InsertedValues;
1616 // available on the target, and it performs a variety of other optimizations
1717 // related to loop induction variables.
1818 //
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.
36 //
37 // TODO: Handle multiple loops at a time.
38 //
39 // TODO: test/CodeGen/X86/full-lsr.ll should get full lsr. The problem is
40 // that {0,+,1}<%bb> is getting picked first because all 7 uses can
41 // use it, and while it's a pretty good solution, it means that LSR
42 // doesn't look further to find an even better solution.
43 //
44 // TODO: Should TargetLowering::AddrMode::BaseGV be changed to a ConstantExpr
45 // instead of a GlobalValue?
46 //
47 // TODO: When truncation is free, truncate ICmp users' operands to make it a
48 // smaller encoding (on x86 at least).
49 //
50 // TODO: When a negated register is used by an add (such as in a list of
51 // multiple base registers, or as the increment expression in an addrec),
52 // we may not actually need both reg and (-1 * reg) in registers; the
53 // negation can be implemented by using a sub instead of an add. The
54 // lack of support for taking this into consideration when making
55 // register pressure decisions is partly worked around by the "Special"
56 // use kind.
57 //
5819 //===----------------------------------------------------------------------===//
5920
6021 #define DEBUG_TYPE "loop-reduce"
6425 #include "llvm/IntrinsicInst.h"
6526 #include "llvm/DerivedTypes.h"
6627 #include "llvm/Analysis/IVUsers.h"
67 #include "llvm/Analysis/Dominators.h"
6828 #include "llvm/Analysis/LoopPass.h"
6929 #include "llvm/Analysis/ScalarEvolutionExpander.h"
30 #include "llvm/Transforms/Utils/AddrModeMatcher.h"
7031 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
7132 #include "llvm/Transforms/Utils/Local.h"
72 #include "llvm/ADT/SmallBitVector.h"
73 #include "llvm/ADT/SetVector.h"
33 #include "llvm/ADT/Statistic.h"
7434 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/CommandLine.h"
7536 #include "llvm/Support/ValueHandle.h"
7637 #include "llvm/Support/raw_ostream.h"
7738 #include "llvm/Target/TargetLowering.h"
7839 #include
7940 using namespace llvm;
8041
42 STATISTIC(NumReduced , "Number of IV uses strength reduced");
43 STATISTIC(NumInserted, "Number of PHIs inserted");
44 STATISTIC(NumVariable, "Number of PHIs with variable strides");
45 STATISTIC(NumEliminated, "Number of strides eliminated");
46 STATISTIC(NumShadow, "Number of Shadow IVs optimized");
47 STATISTIC(NumImmSunk, "Number of common expr immediates sunk into uses");
48 STATISTIC(NumLoopCond, "Number of loop terminating conds optimized");
49 STATISTIC(NumCountZero, "Number of count iv optimized to count toward zero");
50
51 static cl::opt EnableFullLSRMode("enable-full-lsr",
52 cl::init(false),
53 cl::Hidden);
54
8155 namespace {
8256
83 // Constant strides come first which in turns are sorted by their absolute
84 // values. If absolute values are the same, then positive strides comes first.
85 // e.g.
86 // 4, -1, X, 1, 2 ==> 1, -1, 2, 4, X
87 struct StrideCompare {
88 const ScalarEvolution &SE;
89 explicit StrideCompare(const ScalarEvolution &se) : SE(se) {}
90
91 bool operator()(const SCEV *const &LHS, const SCEV *const &RHS) const {
92 const SCEVConstant *LHSC = dyn_cast(LHS);
93 const SCEVConstant *RHSC = dyn_cast(RHS);
94 if (LHSC && RHSC) {
95 unsigned BitWidth = std::max(SE.getTypeSizeInBits(LHS->getType()),
96 SE.getTypeSizeInBits(RHS->getType()));
97 APInt LV = LHSC->getValue()->getValue();
98 APInt RV = RHSC->getValue()->getValue();
99 LV.sextOrTrunc(BitWidth);
100 RV.sextOrTrunc(BitWidth);
101 APInt ALV = LV.abs();
102 APInt ARV = RV.abs();
103 if (ALV == ARV) {
104 if (LV != RV)
105 return LV.sgt(RV);
106 } else {
107 return ALV.ult(ARV);
108 }
109
110 // If it's the same value but different type, sort by bit width so
111 // that we emit larger induction variables before smaller
112 // ones, letting the smaller be re-written in terms of larger ones.
113 return SE.getTypeSizeInBits(RHS->getType()) <
114 SE.getTypeSizeInBits(LHS->getType());
115 }
116 return LHSC && !RHSC;
117 }
118 };
119
120 /// RegSortData - This class holds data which is used to order reuse
121 /// candidates.
122 class RegSortData {
123 public:
124 /// Bits - This represents the set of LSRUses (by index) which reference a
125 /// particular register.
126 SmallBitVector Bits;
127
128 /// MaxComplexity - This represents the greatest complexity (see the comments
129 /// on Formula::getComplexity) seen with a particular register.
130 uint32_t MaxComplexity;
131
132 /// Index - This holds an arbitrary value used as a last-resort tie breaker
133 /// to ensure deterministic behavior.
134 unsigned Index;
135
136 RegSortData() {}
137
138 void print(raw_ostream &OS) const;
139 void dump() const;
140 };
141
142 }
143
144 void RegSortData::print(raw_ostream &OS) const {
145 OS << "[NumUses=" << Bits.count()
146 << ", MaxComplexity=";
147 OS.write_hex(MaxComplexity);
148 OS << ", Index=" << Index << ']';
149 }
150
151 void RegSortData::dump() const {
152 print(errs()); errs() << '\n';
153 }
154
155 namespace {
156
157 /// RegCount - This is a helper class to sort a given set of registers
158 /// according to associated RegSortData values.
159 class RegCount {
160 public:
161 const SCEV *Reg;
162 RegSortData Sort;
163
164 RegCount(const SCEV *R, const RegSortData &RSD)
165 : Reg(R), Sort(RSD) {}
166
167 // Sort by count. Returning true means the register is preferred.
168 bool operator<(const RegCount &Other) const {
169 // Sort by the number of unique uses of this register.
170 unsigned A = Sort.Bits.count();
171 unsigned B = Other.Sort.Bits.count();
172 if (A != B) return A > B;
173
174 if (const SCEVAddRecExpr *AR = dyn_cast(Reg)) {
175 const SCEVAddRecExpr *BR = dyn_cast(Other.Reg);
176 // AddRecs have higher priority than other things.
177 if (!BR) return true;
178
179 // Prefer affine values.
180 if (AR->isAffine() != BR->isAffine())
181 return AR->isAffine();
182
183 const Loop *AL = AR->getLoop();
184 const Loop *BL = BR->getLoop();
185 if (AL != BL) {
186 unsigned ADepth = AL->getLoopDepth();
187 unsigned BDepth = BL->getLoopDepth();
188 // Prefer a less deeply nested addrec.
189 if (ADepth != BDepth)
190 return ADepth < BDepth;
191
192 // Different loops at the same depth; do something arbitrary.
193 BasicBlock *AH = AL->getHeader();
194 BasicBlock *BH = BL->getHeader();
195 for (Function::iterator I = AH, E = AH->getParent()->end(); I != E; ++I)
196 if (&*I == BH) return true;
197 return false;
198 }
199
200 // Sort addrecs by stride.
201 const SCEV *AStep = AR->getOperand(1);
202 const SCEV *BStep = BR->getOperand(1);
203 if (AStep != BStep) {
204 if (const SCEVConstant *AC = dyn_cast(AStep)) {
205 const SCEVConstant *BC = dyn_cast(BStep);
206 if (!BC) return true;
207 // Arbitrarily prefer wider registers.
208 if (AC->getValue()->getValue().getBitWidth() !=
209 BC->getValue()->getValue().getBitWidth())
210 return AC->getValue()->getValue().getBitWidth() >
211 BC->getValue()->getValue().getBitWidth();
212 // Ignore the sign bit, assuming that striding by a negative value
213 // is just as easy as by a positive value.
214 // Prefer the addrec with the lesser absolute value stride, as it
215 // will allow uses to have simpler addressing modes.
216 return AC->getValue()->getValue().abs()
217 .ult(BC->getValue()->getValue().abs());
218 }
219 }
220
221 // Then sort by the register which will permit the simplest uses.
222 // This is a heuristic; currently we only track the most complex use as a
223 // representative.
224 if (Sort.MaxComplexity != Other.Sort.MaxComplexity)
225 return Sort.MaxComplexity < Other.Sort.MaxComplexity;
226
227 // Then sort them by their start values.
228 const SCEV *AStart = AR->getStart();
229 const SCEV *BStart = BR->getStart();
230 if (AStart != BStart) {
231 if (const SCEVConstant *AC = dyn_cast(AStart)) {
232 const SCEVConstant *BC = dyn_cast(BStart);
233 if (!BC) return true;
234 // Arbitrarily prefer wider registers.
235 if (AC->getValue()->getValue().getBitWidth() !=
236 BC->getValue()->getValue().getBitWidth())
237 return AC->getValue()->getValue().getBitWidth() >
238 BC->getValue()->getValue().getBitWidth();
239 // Prefer positive over negative if the absolute values are the same.
240 if (AC->getValue()->getValue().abs() ==
241 BC->getValue()->getValue().abs())
242 return AC->getValue()->getValue().isStrictlyPositive();
243 // Prefer the addrec with the lesser absolute value start.
244 return AC->getValue()->getValue().abs()
245 .ult(BC->getValue()->getValue().abs());
246 }
247 }
248 } else {
249 // AddRecs have higher priority than other things.
250 if (isa(Other.Reg)) return false;
251 // Sort by the register which will permit the simplest uses.
252 // This is a heuristic; currently we only track the most complex use as a
253 // representative.
254 if (Sort.MaxComplexity != Other.Sort.MaxComplexity)
255 return Sort.MaxComplexity < Other.Sort.MaxComplexity;
256 }
257
258
259 // Tie-breaker: the arbitrary index, to ensure a reliable ordering.
260 return Sort.Index < Other.Sort.Index;
261 }
262
263 void print(raw_ostream &OS) const;
264 void dump() const;
265 };
266
267 }
268
269 void RegCount::print(raw_ostream &OS) const {
270 OS << *Reg << ':';
271 Sort.print(OS);
272 }
273
274 void RegCount::dump() const {
275 print(errs()); errs() << '\n';
276 }
277
278 namespace {
279
280 /// Formula - This class holds information that describes a formula for
281 /// satisfying a use. It may include broken-out immediates and scaled registers.
282 struct Formula {
283 /// AM - This is used to represent complex addressing, as well as other kinds
284 /// of interesting uses.
285 TargetLowering::AddrMode AM;
286
287 /// BaseRegs - The list of "base" registers for this use. When this is
288 /// non-empty, AM.HasBaseReg should be set to true.
289 SmallVector BaseRegs;
290
291 /// ScaledReg - The 'scaled' register for this use. This should be non-null
292 /// when AM.Scale is not zero.
293 const SCEV *ScaledReg;
294
295 Formula() : ScaledReg(0) {}
296
297 unsigned getNumRegs() const;
298 uint32_t getComplexity() const;
299 const Type *getType() const;
300
301 void InitialMatch(const SCEV *S, Loop *L,
302 ScalarEvolution &SE, DominatorTree &DT);
303
304 /// referencesReg - Test if this formula references the given register.
305 bool referencesReg(const SCEV *S) const {
306 return S == ScaledReg ||
307 std::find(BaseRegs.begin(), BaseRegs.end(), S) != BaseRegs.end();
308 }
309
310 bool operator==(const Formula &Other) const {
311 return BaseRegs == Other.BaseRegs &&
312 ScaledReg == Other.ScaledReg &&
313 AM.Scale == Other.AM.Scale &&
314 AM.BaseOffs == Other.AM.BaseOffs &&
315 AM.BaseGV == Other.AM.BaseGV;
316 }
317
318 // This sorts at least partially based on host pointer values which are
319 // not deterministic, so it is only usable for uniqification.
320 bool operator<(const Formula &Other) const {
321 if (BaseRegs != Other.BaseRegs)
322 return BaseRegs < Other.BaseRegs;
323 if (ScaledReg != Other.ScaledReg)
324 return ScaledReg < Other.ScaledReg;
325 if (AM.Scale != Other.AM.Scale)
326 return AM.Scale < Other.AM.Scale;
327 if (AM.BaseOffs != Other.AM.BaseOffs)
328 return AM.BaseOffs < Other.AM.BaseOffs;
329 if (AM.BaseGV != Other.AM.BaseGV)
330 return AM.BaseGV < Other.AM.BaseGV;
331 return false;
332 }
333
334 void print(raw_ostream &OS) const;
335 void dump() const;
336 };
337
338 }
339
340 /// getNumRegs - Return the total number of register operands used by this
341 /// formula. This does not include register uses implied by non-constant
342 /// addrec strides.
343 unsigned Formula::getNumRegs() const {
344 return !!ScaledReg + BaseRegs.size();
345 }
346
347 /// getComplexity - Return an oversimplified value indicating the complexity
348 /// of this formula. This is used as a tie-breaker in choosing register
349 /// preferences.
350 uint32_t Formula::getComplexity() const {
351 // Encode the information in a uint32_t so that comparing with operator<
352 // will be interesting.
353 return
354 // Most significant, the number of registers. This saturates because we
355 // need the bits, and because beyond a few hundred it doesn't really matter.
356 (std::min(getNumRegs(), (1u<<15)-1) << 17) |
357 // Having multiple base regs is worse than having a base reg and a scale.
358 ((BaseRegs.size() > 1) << 16) |
359 // Scale absolute value.
360 ((AM.Scale != 0 ? (Log2_64(abs64(AM.Scale)) + 1) : 0u) << 9) |
361 // Scale sign, which is less significant than the absolute value.
362 ((AM.Scale < 0) << 8) |
363 // Offset absolute value.
364 ((AM.BaseOffs != 0 ? (Log2_64(abs64(AM.BaseOffs)) + 1) : 0u) << 1) |
365 // If a GV is present, treat it like a maximal offset.
366 ((AM.BaseGV ? ((1u<<7)-1) : 0) << 1) |
367 // Offset sign, which is less significant than the absolute offset.
368 ((AM.BaseOffs < 0) << 0);
369 }
370
371 /// getType - Return the type of this formula, if it has one, or null
372 /// otherwise. This type is meaningless except for the bit size.
373 const Type *Formula::getType() const {
374 return !BaseRegs.empty() ? BaseRegs.front()->getType() :
375 ScaledReg ? ScaledReg->getType() :
376 AM.BaseGV ? AM.BaseGV->getType() :
377 0;
378 }
379
380 namespace {
381
382 /// ComplexitySorter - A predicate which orders Formulae by the number of
383 /// registers they contain.
384 struct ComplexitySorter {
385 bool operator()(const Formula &LHS, const Formula &RHS) const {
386 unsigned L = LHS.getNumRegs();
387 unsigned R = RHS.getNumRegs();
388 if (L != R) return L < R;
389
390 return LHS.getComplexity() < RHS.getComplexity();
391 }
392 };
393
394 }
395
396 /// DoInitialMatch - Recurrsion helper for InitialMatch.
397 static void DoInitialMatch(const SCEV *S, Loop *L,
398 SmallVectorImpl &Good,
399 SmallVectorImpl &Bad,
400 ScalarEvolution &SE, DominatorTree &DT) {
401 // Collect expressions which properly dominate the loop header.
402 if (S->properlyDominates(L->getHeader(), &DT)) {
403 Good.push_back(S);
404 return;
405 }
406
407 // Look at add operands.
408 if (const SCEVAddExpr *Add = dyn_cast(S)) {
409 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
410 I != E; ++I)
411 DoInitialMatch(*I, L, Good, Bad, SE, DT);
412 return;
413 }
414
415 // Look at addrec operands.
416 if (const SCEVAddRecExpr *AR = dyn_cast(S)) {
417 if (!AR->getStart()->isZero()) {
418 DoInitialMatch(AR->getStart(), L, Good, Bad, SE, DT);
419 DoInitialMatch(SE.getAddRecExpr(SE.getIntegerSCEV(0, AR->getType()),
420 AR->getStepRecurrence(SE),
421 AR->getLoop()),
422 L, Good, Bad, SE, DT);
423 return;
424 }
425 }
426
427 // Handle a multiplication by -1 (negation) if it didn't fold.
428 if (const SCEVMulExpr *Mul = dyn_cast(S))
429 if (Mul->getOperand(0)->isAllOnesValue()) {
430 SmallVector Ops(Mul->op_begin()+1, Mul->op_end());
431 const SCEV *NewMul = SE.getMulExpr(Ops);
432
433 SmallVector MyGood;
434 SmallVector MyBad;
435 DoInitialMatch(NewMul, L, MyGood, MyBad, SE, DT);
436 const SCEV *NegOne = SE.getSCEV(ConstantInt::getAllOnesValue(
437 SE.getEffectiveSCEVType(NewMul->getType())));
438 for (SmallVectorImpl::const_iterator I = MyGood.begin(),
439 E = MyGood.end(); I != E; ++I)
440 Good.push_back(SE.getMulExpr(NegOne, *I));
441 for (SmallVectorImpl::const_iterator I = MyBad.begin(),
442 E = MyBad.end(); I != E; ++I)
443 Bad.push_back(SE.getMulExpr(NegOne, *I));
444 return;
445 }
446
447 // Ok, we can't do anything interesting. Just stuff the whole thing into a
448 // register and hope for the best.
449 Bad.push_back(S);
450 }
451
452 /// InitialMatch - Incorporate loop-variant parts of S into this Formula,
453 /// attempting to keep all loop-invariant and loop-computable values in a
454 /// single base register.
455 void Formula::InitialMatch(const SCEV *S, Loop *L,
456 ScalarEvolution &SE, DominatorTree &DT) {
457 SmallVector Good;
458 SmallVector Bad;
459 DoInitialMatch(S, L, Good, Bad, SE, DT);
460 if (!Good.empty()) {
461 BaseRegs.push_back(SE.getAddExpr(Good));
462 AM.HasBaseReg = true;
463 }
464 if (!Bad.empty()) {
465 BaseRegs.push_back(SE.getAddExpr(Bad));
466 AM.HasBaseReg = true;
467 }
468 }
469
470 void Formula::print(raw_ostream &OS) const {
471 bool First = true;
472 if (AM.BaseGV) {
473 if (!First) OS << " + "; else First = false;
474 WriteAsOperand(OS, AM.BaseGV, /*PrintType=*/false);
475 }
476 if (AM.BaseOffs != 0) {
477 if (!First) OS << " + "; else First = false;
478 OS << AM.BaseOffs;
479 }
480 for (SmallVectorImpl::const_iterator I = BaseRegs.begin(),
481 E = BaseRegs.end(); I != E; ++I) {
482 if (!First) OS << " + "; else First = false;
483 OS << "reg(";
484 OS << **I;
485 OS << ")";
486 }
487 if (AM.Scale != 0) {
488 if (!First) OS << " + "; else First = false;
489 OS << AM.Scale << "*reg(";
490 if (ScaledReg)
491 OS << *ScaledReg;
492 else
493 OS << "";
494 OS << ")";
495 }
496 }
497
498 void Formula::dump() const {
499 print(errs()); errs() << '\n';
500 }
501
502 /// getSDiv - Return an expression for LHS /s RHS, if it can be determined,
503 /// or null otherwise. If IgnoreSignificantBits is true, expressions like
504 /// (X * Y) /s Y are simplified to Y, ignoring that the multiplication may
505 /// overflow, which is useful when the result will be used in a context where
506 /// the most significant bits are ignored.
507 static const SCEV *getSDiv(const SCEV *LHS, const SCEV *RHS,
508 ScalarEvolution &SE,
509 bool IgnoreSignificantBits = false) {
510 // Handle the trivial case, which works for any SCEV type.
511 if (LHS == RHS)
512 return SE.getIntegerSCEV(1, LHS->getType());
513
514 // Handle x /s -1 as x * -1, to give ScalarEvolution a chance to do some
515 // folding.
516 if (RHS->isAllOnesValue())
517 return SE.getMulExpr(LHS, RHS);
518
519 // Check for a division of a constant by a constant.
520 if (const SCEVConstant *C = dyn_cast(LHS)) {
521 const SCEVConstant *RC = dyn_cast(RHS);
522 if (!RC)
523 return 0;
524 if (C->getValue()->getValue().srem(RC->getValue()->getValue()) != 0)
525 return 0;
526 return SE.getConstant(C->getValue()->getValue()
527 .sdiv(RC->getValue()->getValue()));
528 }
529
530 // Distribute the sdiv over addrec operands.
531 if (const SCEVAddRecExpr *AR = dyn_cast(LHS)) {
532 const SCEV *Start = getSDiv(AR->getStart(), RHS, SE,
533 IgnoreSignificantBits);
534 if (!Start) return 0;
535 const SCEV *Step = getSDiv(AR->getStepRecurrence(SE), RHS, SE,
536 IgnoreSignificantBits);
537 if (!Step) return 0;
538 return SE.getAddRecExpr(Start, Step, AR->getLoop());
539 }
540
541 // Distribute the sdiv over add operands.
542 if (const SCEVAddExpr *Add = dyn_cast(LHS)) {
543 SmallVector Ops;
544 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
545 I != E; ++I) {
546 const SCEV *Op = getSDiv(*I, RHS, SE,
547 IgnoreSignificantBits);
548 if (!Op) return 0;
549 Ops.push_back(Op);
550 }
551 return SE.getAddExpr(Ops);
552 }
553
554 // Check for a multiply operand that we can pull RHS out of.
555 if (const SCEVMulExpr *Mul = dyn_cast(LHS))
556 if (IgnoreSignificantBits || Mul->hasNoSignedWrap()) {
557 SmallVector Ops;
558 bool Found = false;
559 for (SCEVMulExpr::op_iterator I = Mul->op_begin(), E = Mul->op_end();
560 I != E; ++I) {
561 if (!Found)
562 if (const SCEV *Q = getSDiv(*I, RHS, SE, IgnoreSignificantBits)) {
563 Ops.push_back(Q);
564 Found = true;
565 continue;
566 }
567 Ops.push_back(*I);
568 }
569 return Found ? SE.getMulExpr(Ops) : 0;
570 }
571
572 // Otherwise we don't know.
573 return 0;
574 }
575
576 namespace {
577
578 /// LSRUse - This class holds the state that LSR keeps for each use in
579 /// IVUsers, as well as uses invented by LSR itself. It includes information
580 /// about what kinds of things can be folded into the user, information
581 /// about the user itself, and information about how the use may be satisfied.
582 /// TODO: Represent multiple users of the same expression in common?
583 class LSRUse {
584 SmallSet FormulaeUniquifier;
585
586 public:
587 /// KindType - An enum for a kind of use, indicating what types of
588 /// scaled and immediate operands it might support.
589 enum KindType {
590 Basic, ///< A normal use, with no folding.
591 Special, ///< A special case of basic, allowing -1 scales.
592 Address, ///< An address use; folding according to TargetLowering
593 ICmpZero ///< An equality icmp with both operands folded into one.
594 // TODO: Add a generic icmp too?
57 struct BasedUser;
58
59 /// IVInfo - This structure keeps track of one IV expression inserted during
60 /// StrengthReduceStridedIVUsers. It contains the stride, the common base, as
61 /// well as the PHI node and increment value created for rewrite.
62 struct IVExpr {
63 const SCEV *Stride;
64 const SCEV *Base;
65 PHINode *PHI;
66
67 IVExpr(const SCEV *const stride, const SCEV *const base, PHINode *phi)
68 : Stride(stride), Base(base), PHI(phi) {}
59569 };
59670
597 KindType Kind;
598 const Type *AccessTy;
599 Instruction *UserInst;
600 Value *OperandValToReplace;
601
602 /// PostIncLoop - If this user is to use the post-incremented value of an
603 /// induction variable, this variable is non-null and holds the loop
604 /// associated with the induction variable.
605 const Loop *PostIncLoop;
606
607 /// Formulae - A list of ways to build a value that can satisfy this user.
608 /// After the list is populated, one of these is selected heuristically and
609 /// used to formulate a replacement for OperandValToReplace in UserInst.
610 SmallVector Formulae;
611
612 LSRUse() : Kind(Basic), AccessTy(0),
613 UserInst(0), OperandValToReplace(0), PostIncLoop(0) {}
614
615 void InsertInitialFormula(const SCEV *S, Loop *L,
616 ScalarEvolution &SE, DominatorTree &DT);
617 void InsertSupplementalFormula(const SCEV *S);
618
619 bool InsertFormula(const Formula &F);
620
621 void Rewrite(Loop *L, Instruction *IVIncInsertPos,
622 SCEVExpander &Rewriter,
623 SmallVectorImpl &DeadInsts,
624 ScalarEvolution &SE, DominatorTree &DT,
625 Pass *P) const;
626
627 void print(raw_ostream &OS) const;
628 void dump() const;
629
630 private:
631 Value *Expand(BasicBlock::iterator IP, Loop *L, Instruction *IVIncInsertPos,
632 SCEVExpander &Rewriter,
633 SmallVectorImpl &DeadInsts,
634 ScalarEvolution &SE, DominatorTree &DT) const;
635 };
636
637 }
638
639 /// ExtractImmediate - If S involves the addition of a constant integer value,
640 /// return that integer value, and mutate S to point to a new SCEV with that
641 /// value excluded.
642 static int64_t ExtractImmediate(const SCEV *&S, ScalarEvolution &SE) {
643 if (const SCEVConstant *C = dyn_cast(S)) {
644 if (C->getValue()->getValue().getMinSignedBits() <= 64) {
645 S = SE.getIntegerSCEV(0, C->getType());
646 return C->getValue()->getSExtValue();
647 }
648 } else if (const SCEVAddExpr *Add = dyn_cast(S)) {
649 SmallVector NewOps(Add->op_begin(), Add->op_end());
650 int64_t Result = ExtractImmediate(NewOps.front(), SE);
651 S = SE.getAddExpr(NewOps);
652 return Result;
653 } else if (const SCEVAddRecExpr *AR = dyn_cast(S)) {
654 SmallVector NewOps(AR->op_begin(), AR->op_end());
655 int64_t Result = ExtractImmediate(NewOps.front(), SE);
656 S = SE.getAddRecExpr(NewOps, AR->getLoop());
657 return Result;
658 }
659 return 0;
660 }
661
662 /// ExtractSymbol - If S involves the addition of a GlobalValue address,
663 /// return that symbol, and mutate S to point to a new SCEV with that
664 /// value excluded.
665 static GlobalValue *ExtractSymbol(const SCEV *&S, ScalarEvolution &SE) {
666 if (const SCEVUnknown *U = dyn_cast(S)) {
667 if (GlobalValue *GV = dyn_cast(U->getValue())) {
668 S = SE.getIntegerSCEV(0, GV->getType());
669 return GV;
670 }
671 } else if (const SCEVAddExpr *Add = dyn_cast(S)) {
672 SmallVector NewOps(Add->op_begin(), Add->op_end());
673 GlobalValue *Result = ExtractSymbol(NewOps.back(), SE);
674 S = SE.getAddExpr(NewOps);
675 return Result;
676 } else if (const SCEVAddRecExpr *AR = dyn_cast(S)) {
677 SmallVector NewOps(AR->op_begin(), AR->op_end());
678 GlobalValue *Result = ExtractSymbol(NewOps.front(), SE);
679 S = SE.getAddRecExpr(NewOps, AR->getLoop());
680 return Result;
681 }
682 return 0;
683 }
684
685 /// isLegalUse - Test whether the use described by AM is "legal", meaning
686 /// it can be completely folded into the user instruction at isel time.
687 /// This includes address-mode folding and special icmp tricks.
688 static bool isLegalUse(const TargetLowering::AddrMode &AM,
689 LSRUse::KindType Kind, const Type *AccessTy,
690 const TargetLowering *TLI) {
691 switch (Kind) {
692 case LSRUse::Address:
693 // If we have low-level target information, ask the target if it can
694 // completely fold this address.
695 if (TLI) return TLI->isLegalAddressingMode(AM, AccessTy);
696
697 // Otherwise, just guess that reg+reg addressing is legal.
698 return !AM.BaseGV && AM.BaseOffs == 0 && AM.Scale <= 1;
699
700 case LSRUse::ICmpZero:
701 // There's not even a target hook for querying whether it would be legal
702 // to fold a GV into an ICmp.
703 if (AM.BaseGV)
704 return false;
705
706 // ICmp only has two operands; don't allow more than two non-trivial parts.
707 if (AM.Scale != 0 && AM.HasBaseReg && AM.BaseOffs != 0)
708 return false;
709
710 // ICmp only supports no scale or a -1 scale, as we can "fold" a -1 scale
711 // by putting the scaled register in the other operand of the icmp.
712 if (AM.Scale != 0 && AM.Scale != -1)
713 return false;
714
715 // If we have low-level target information, ask the target if it can
716 // fold an integer immediate on an icmp.
717 if (AM.BaseOffs != 0) {
718 if (TLI) return TLI->isLegalICmpImmediate(-AM.BaseOffs);
719 return false;
720 }
721
722 return true;
723
724 case LSRUse::Basic:
725 // Only handle single-register values.
726 return !AM.BaseGV && AM.Scale == 0 && AM.BaseOffs == 0;
727
728 case LSRUse::Special:
729 // Only handle -1 scales, or no scale.
730 return AM.Scale == 0 || AM.Scale == -1;
731 }
732
733 return false;
734 }
735
736 static bool isAlwaysFoldable(const SCEV *S,
737 bool HasBaseReg,
738 LSRUse::KindType Kind, const Type *AccessTy,
739 const TargetLowering *TLI,
740 ScalarEvolution &SE) {
741 // Fast-path: zero is always foldable.
742 if (S->isZero()) return true;
743
744 // Conservatively, create an address with an immediate and a
745 // base and a scale.
746 TargetLowering::AddrMode AM;
747 AM.BaseOffs = ExtractImmediate(S, SE);
748 AM.BaseGV = ExtractSymbol(S, SE);
749 AM.HasBaseReg = HasBaseReg;
750 AM.Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
751
752 // If there's anything else involved, it's not foldable.
753 if (!S->isZero()) return false;
754
755 return isLegalUse(AM, Kind, AccessTy, TLI);
756 }
757
758 /// InsertFormula - If the given formula has not yet been inserted, add it
759 /// to the list, and return true. Return false otherwise.
760 bool LSRUse::InsertFormula(const Formula &F) {
761 Formula Copy = F;
762
763 // Sort the base regs, to avoid adding the same solution twice with
764 // the base regs in different orders. This uses host pointer values, but
765 // it doesn't matter since it's only used for uniquifying.
766 std::sort(Copy.BaseRegs.begin(), Copy.BaseRegs.end());
767
768 DEBUG(for (SmallVectorImpl::const_iterator I =
769 F.BaseRegs.begin(), E = F.BaseRegs.end(); I != E; ++I)
770 assert(!(*I)->isZero() && "Zero allocated in a base register!");
771 assert((!F.ScaledReg || !F.ScaledReg->isZero()) &&
772 "Zero allocated in a scaled register!"));
773
774 if (FormulaeUniquifier.insert(Copy)) {
775 Formulae.push_back(F);
776 return true;
777 }
778
779 return false;
780 }
781
782 void
783 LSRUse::InsertInitialFormula(const SCEV *S, Loop *L,
784 ScalarEvolution &SE, DominatorTree &DT) {
785 Formula F;
786 F.InitialMatch(S, L, SE, DT);
787 bool Inserted = InsertFormula(F);
788 assert(Inserted && "Initial formula already exists!"); (void)Inserted;
789 }
790
791 void
792 LSRUse::InsertSupplementalFormula(const SCEV *S) {
793 Formula F;
794 F.BaseRegs.push_back(S);
795 F.AM.HasBaseReg = true;
796 bool Inserted = InsertFormula(F);
797 assert(Inserted && "Supplemental formula already exists!"); (void)Inserted;
798 }
799
800 /// getImmediateDominator - A handy utility for the specific DominatorTree
801 /// query that we need here.
802 ///
803 static BasicBlock *getImmediateDominator(BasicBlock *BB, DominatorTree &DT) {
804 DomTreeNode *Node = DT.getNode(BB);
805 if (!Node) return 0;
806 Node = Node->getIDom();
807 if (!Node) return 0;
808 return Node->getBlock();
809 }
810
811 Value *LSRUse::Expand(BasicBlock::iterator IP,
812 Loop *L, Instruction *IVIncInsertPos,
813 SCEVExpander &Rewriter,
814 SmallVectorImpl &DeadInsts,
815 ScalarEvolution &SE, DominatorTree &DT) const {
816 // Then, collect some instructions which we will remain dominated by when
817 // expanding the replacement. These must be dominated by any operands that
818 // will be required in the expansion.
819 SmallVector Inputs;
820 if (Instruction *I = dyn_cast(OperandValToReplace))
821 Inputs.push_back(I);
822 if (Kind == ICmpZero)
823 if (Instruction *I =
824 dyn_cast(cast(UserInst)->getOperand(1)))
825 Inputs.push_back(I);
826 if (PostIncLoop && !L->contains(UserInst))
827 Inputs.push_back(L->getLoopLatch()->getTerminator());
828
829 // Then, climb up the immediate dominator tree as far as we can go while
830 // still being dominated by the input positions.
831 for (;;) {
832 bool AllDominate = true;
833 Instruction *BetterPos = 0;
834 BasicBlock *IDom = getImmediateDominator(IP->getParent(), DT);
835 if (!IDom) break;
836 Instruction *Tentative = IDom->getTerminator();
837 for (SmallVectorImpl::const_iterator I = Inputs.begin(),
838 E = Inputs.end(); I != E; ++I) {
839 Instruction *Inst = *I;
840 if (Inst == Tentative || !DT.dominates(Inst, Tentative)) {
841 AllDominate = false;
842 break;
843 }
844 if (IDom == Inst->getParent() &&
845 (!BetterPos || DT.dominates(BetterPos, Inst)))
846 BetterPos = next(BasicBlock::iterator(Inst));
847 }
848 if (!AllDominate)
849 break;
850 if (BetterPos)
851 IP = BetterPos;
852 else
853 IP = Tentative;
854 }
855 while (isa(IP)) ++IP;
856
857 // The first formula in the list is the winner.
858 const Formula &F = Formulae.front();
859
860 // Inform the Rewriter if we have a post-increment use, so that it can
861 // perform an advantageous expansion.
862 Rewriter.setPostInc(PostIncLoop);
863
864 // This is the type that the user actually needs.
865 const Type *OpTy = OperandValToReplace->getType();
866 // This will be the type that we'll initially expand to.
867 const Type *Ty = F.getType();
868 if (!Ty)
869 // No type known; just expand directly to the ultimate type.
870 Ty = OpTy;
871 else if (SE.getEffectiveSCEVType(Ty) == SE.getEffectiveSCEVType(OpTy))
872 // Expand directly to the ultimate type if it's the right size.
873 Ty = OpTy;
874 // This is the type to do integer arithmetic in.
875 const Type *IntTy = SE.getEffectiveSCEVType(Ty);
876
877 // Build up a list of operands to add together to form the full base.
878 SmallVector Ops;
879
880 // Expand the BaseRegs portion.
881 for (SmallVectorImpl::const_iterator I = F.BaseRegs.begin(),
882 E = F.BaseRegs.end(); I != E; ++I) {
883 const SCEV *Reg = *I;
884 assert(!Reg->isZero() && "Zero allocated in a base register!");
885
886 // If we're expanding for a post-inc user for the add-rec's loop, make the
887 // post-inc adjustment.
888 if (const SCEVAddRecExpr *AR = dyn_cast(Reg))
889 if (AR->getLoop() == PostIncLoop) {
890 Reg = SE.getAddExpr(Reg, AR->getStepRecurrence(SE));
891 // If the user is inside the loop, insert the code after the increment
892 // so that it is dominated by its operand.
893 if (L->contains(UserInst))
894 IP = IVIncInsertPos;
895 }
896
897 Ops.push_back(SE.getUnknown(Rewriter.expandCodeFor(Reg, 0, IP)));
898 }
899
900 // Expand the ScaledReg portion.
901 Value *ICmpScaledV = 0;
902 if (F.AM.Scale != 0) {
903 const SCEV *ScaledS = F.ScaledReg;
904
905 // If we're expanding for a post-inc user for the add-rec's loop, make the
906 // post-inc adjustment.
907 if (const SCEVAddRecExpr *AR = dyn_cast(ScaledS))
908 if (AR->getLoop() == PostIncLoop)
909 ScaledS = SE.getAddExpr(ScaledS, AR->getStepRecurrence(SE));
910
911 if (Kind == ICmpZero) {
912 // An interesting way of "folding" with an icmp is to use a negated
913 // scale, which we'll implement by inserting it into the other operand
914 // of the icmp.
915 assert(F.AM.Scale == -1 &&
916 "The only scale supported by ICmpZero uses is -1!");
917 ICmpScaledV = Rewriter.expandCodeFor(ScaledS, 0, IP);
918 } else {
919 // Otherwise just expand the scaled register and an explicit scale,
920 // which is expected to be matched as part of the address.
921 ScaledS = SE.getUnknown(Rewriter.expandCodeFor(ScaledS, 0, IP));
922 const Type *ScaledTy = SE.getEffectiveSCEVType(ScaledS->getType());
923 ScaledS = SE.getMulExpr(ScaledS,
924 SE.getSCEV(ConstantInt::get(ScaledTy,
925 F.AM.Scale)));
926 Ops.push_back(ScaledS);
927 }
928 }
929
930 // Expand the immediate portions.
931 if (F.AM.BaseGV)
932 Ops.push_back(SE.getSCEV(F.AM.BaseGV));
933 if (F.AM.BaseOffs != 0) {
934 if (Kind == ICmpZero) {
935 // The other interesting way of "folding" with an ICmpZero is to use a
936 // negated immediate.
937 if (!ICmpScaledV)
938 ICmpScaledV = ConstantInt::get(IntTy, -F.AM.BaseOffs);
939 else {
940 Ops.push_back(SE.getUnknown(ICmpScaledV));
941 ICmpScaledV = ConstantInt::get(IntTy, F.AM.BaseOffs);
942 }
943 } else {
944 // Just add the immediate values. These again are expected to be matched
945 // as part of the address.
946 Ops.push_back(SE.getSCEV(ConstantInt::get(IntTy, F.AM.BaseOffs)));
947 }
948 }
949
950 // Emit instructions summing all the operands.
951 const SCEV *FullS = Ops.empty() ?
952 SE.getIntegerSCEV(0, IntTy) :
953 SE.getAddExpr(Ops);
954 Value *FullV = Rewriter.expandCodeFor(FullS, Ty, IP);
955
956 // We're done expanding now, so reset the rewriter.
957 Rewriter.setPostInc(0);
958
959 // An ICmpZero Formula represents an ICmp which we're handling as a
960 // comparison against zero. Now that we've expanded an expression for that
961 // form, update the ICmp's other operand.
962 if (Kind == ICmpZero) {
963 ICmpInst *CI = cast(UserInst);
964 DeadInsts.push_back(CI->getOperand(1));
965 assert(!F.AM.BaseGV && "ICmp does not support folding a global value and "
966 "a scale at the same time!");
967 if (F.AM.Scale == -1) {
968 if (ICmpScaledV->getType() != OpTy) {
969 Instruction *Cast =
970 CastInst::Create(CastInst::getCastOpcode(ICmpScaledV, false,
971 OpTy, false),
972 ICmpScaledV, OpTy, "tmp", CI);
973 ICmpScaledV = Cast;
974 }
975 CI->setOperand(1, ICmpScaledV);
976 } else {
977 assert(F.AM.Scale == 0 &&
978 "ICmp does not support folding a global value and "
979 "a scale at the same time!");
980 Constant *C = ConstantInt::getSigned(SE.getEffectiveSCEVType(OpTy),
981 -(uint64_t)F.AM.BaseOffs);
982 if (C->getType() != OpTy)
983 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
984 OpTy, false),
985 C, OpTy);
986
987 CI->setOperand(1, C);
988 }
989 }
990
991 return FullV;
992 }
993
994 /// Rewrite - Emit instructions for the leading candidate expression for this
995 /// LSRUse (this is called "expanding"), and update the UserInst to reference
996 /// the newly expanded value.
997 void LSRUse::Rewrite(Loop *L, Instruction *IVIncInsertPos,
998 SCEVExpander &Rewriter,
999 SmallVectorImpl &DeadInsts,
1000 ScalarEvolution &SE, DominatorTree &DT,
1001 Pass *P) const {
1002 const Type *OpTy = OperandValToReplace->getType();
1003
1004 // First, find an insertion point that dominates UserInst. For PHI nodes,
1005 // find the nearest block which dominates all the relevant uses.
1006 if (PHINode *PN = dyn_cast(UserInst)) {
1007 DenseMap Inserted;
1008 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1009 if (PN->getIncomingValue(i) == OperandValToReplace) {
1010 BasicBlock *BB = PN->getIncomingBlock(i);
1011
1012 // If this is a critical edge, split the edge so that we do not insert
1013 // the code on all predecessor/successor paths. We do this unless this
1014 // is the canonical backedge for this loop, which complicates post-inc
1015 // users.
1016 if (e != 1 && BB->getTerminator()->getNumSuccessors() > 1 &&
1017 !isa(BB->getTerminator()) &&
1018 (PN->getParent() != L->getHeader() || !L->contains(BB))) {
1019 // Split the critical edge.
1020 BasicBlock *NewBB = SplitCriticalEdge(BB, PN->getParent(), P);
1021
1022 // If PN is outside of the loop and BB is in the loop, we want to
1023 // move the block to be immediately before the PHI block, not
1024 // immediately after BB.
1025 if (L->contains(BB) && !L->contains(PN))
1026 NewBB->moveBefore(PN->getParent());
1027
1028 // Splitting the edge can reduce the number of PHI entries we have.
1029 e = PN->getNumIncomingValues();
1030 BB = NewBB;
1031 i = PN->getBasicBlockIndex(BB);
1032 }
1033
1034 std::pair::iterator, bool> Pair =
1035 Inserted.insert(std::make_pair(BB, static_cast(0)));
1036 if (!Pair.second)
1037 PN->setIncomingValue(i, Pair.first->second);
1038 else {
1039 Value *FullV = Expand(BB->getTerminator(), L, IVIncInsertPos,
1040 Rewriter, DeadInsts, SE, DT);
1041
1042 // If this is reuse-by-noop-cast, insert the noop cast.
1043 if (FullV->getType() != OpTy)
1044 FullV =
1045 CastInst::Create(CastInst::getCastOpcode(FullV, false,
1046 OpTy, false),
1047 FullV, OperandValToReplace->getType(),
1048 "tmp", BB->getTerminator());
1049
1050 PN->setIncomingValue(i, FullV);
1051 Pair.first->second = FullV;
1052 }
1053 }
1054 } else {
1055 Value *FullV = Expand(UserInst, L, IVIncInsertPos,
1056 Rewriter, DeadInsts, SE, DT);
1057
1058 // If this is reuse-by-noop-cast, insert the noop cast.
1059 if (FullV->getType() != OpTy) {
1060 Instruction *Cast =
1061 CastInst::Create(CastInst::getCastOpcode(FullV, false, OpTy, false),
1062 FullV, OpTy, "tmp", UserInst);
1063 FullV = Cast;
1064 }
1065
1066 // Update the user.
1067 UserInst->replaceUsesOfWith(OperandValToReplace, FullV);
1068 }
1069
1070 DeadInsts.push_back(OperandValToReplace);
1071 }
1072
1073 void LSRUse::print(raw_ostream &OS) const {
1074 OS << "LSR Use: Kind=";
1075 switch (Kind) {
1076 case Basic: OS << "Basic"; break;
1077 case Special: OS << "Special"; break;
1078 case ICmpZero: OS << "ICmpZero"; break;
1079 case Address:
1080 OS << "Address of ";
1081 if (isa(AccessTy))
1082 OS << "pointer"; // the full pointer type could be really verbose
1083 else
1084 OS << *AccessTy;
1085 }
1086
1087 OS << ", UserInst=";
1088 // Store is common and interesting enough to be worth special-casing.
1089 if (StoreInst *Store = dyn_cast(UserInst)) {
1090 OS << "store ";
1091 WriteAsOperand(OS, Store->getOperand(0), /*PrintType=*/false);
1092 } else if (UserInst->getType()->isVoidTy())
1093 OS << UserInst->getOpcodeName();
1094 else
1095 WriteAsOperand(OS, UserInst, /*PrintType=*/false);
1096
1097 OS << ", OperandValToReplace=";
1098 WriteAsOperand(OS, OperandValToReplace, /*PrintType=*/false);
1099
1100 if (PostIncLoop) {
1101 OS << ", PostIncLoop=";
1102 WriteAsOperand(OS, PostIncLoop->getHeader(), /*PrintType=*/false);
1103 }
1104 }
1105
1106 void LSRUse::dump() const {
1107 print(errs()); errs() << '\n';
1108 }
1109
1110 namespace {
1111
1112 /// Score - This class is used to measure and compare candidate formulae.
1113 class Score {
1114 unsigned NumRegs;
1115 unsigned NumPhis;
1116 unsigned NumIVMuls;
1117 unsigned NumBaseAdds;
1118 unsigned NumImms;
1119
1120 public:
1121 Score()
1122 : NumRegs(0), NumPhis(0), NumIVMuls(0), NumBaseAdds(0), NumImms(0) {}
1123
1124 void RateInitial(SmallVector const &Uses, const Loop *L,
1125 ScalarEvolution &SE);
1126
1127 void Rate(const SCEV *Reg, const SmallBitVector &Bits,
1128 const SmallVector &Uses, const Loop *L,
1129 ScalarEvolution &SE);
1130
1131 unsigned getNumRegs() const { return NumRegs; }
1132
1133 bool operator<(const Score &Other) const;
1134
1135 void print_details(raw_ostream &OS, const SCEV *Reg,
1136 const SmallPtrSet &Regs) const;
1137
1138 void print(raw_ostream &OS) const;
1139 void dump() const;
1140
1141 private:
1142 void RateRegister(const SCEV *Reg, SmallPtrSet &Regs,
1143 const Loop *L);
1144 void RateFormula(const Formula &F, SmallPtrSet &Regs,
1145 const Loop *L);
1146
1147 void Loose();
1148 };
1149
1150 }
1151
1152 /// RateRegister - Tally up interesting quantities from the given register.
1153 void Score::RateRegister(const SCEV *Reg,
1154 SmallPtrSet &Regs,
1155 const Loop *L) {
1156 if (Regs.insert(Reg))
1157 if (const SCEVAddRecExpr *AR = dyn_cast(Reg)) {
1158 NumPhis += AR->getLoop() == L;
1159
1160 // Add the step value register, if it needs one.
1161 if (!AR->isAffine() || !isa(AR->getOperand(1)))
1162 RateRegister(AR->getOperand(1), Regs, L);
1163 }
1164 }
1165
1166 void Score::RateFormula(const Formula &F,
1167 SmallPtrSet &Regs,
1168 const Loop *L) {
1169 // Tally up the registers.
1170 if (F.ScaledReg)
1171 RateRegister(F.ScaledReg, Regs, L);
1172 for (SmallVectorImpl::const_iterator I = F.BaseRegs.begin(),
1173 E = F.BaseRegs.end(); I != E; ++I) {
1174 const SCEV *BaseReg = *I;
1175 RateRegister(BaseReg, Regs, L);
1176
1177 NumIVMuls += isa(BaseReg) &&
1178 BaseReg->hasComputableLoopEvolution(L);
1179 }
1180
1181 if (F.BaseRegs.size() > 1)
1182 NumBaseAdds += F.BaseRegs.size() - 1;
1183
1184 // Tally up the non-zero immediates.
1185 if (F.AM.BaseGV || F.AM.BaseOffs != 0)
1186 ++NumImms;
1187 }
1188
1189 /// Loose - Set this score to a loosing value.
1190 void Score::Loose() {
1191 NumRegs = ~0u;
1192 NumPhis = ~0u;
1193 NumIVMuls = ~0u;
1194 NumBaseAdds = ~0u;
1195 NumImms = ~0u;
1196 }
1197
1198 /// RateInitial - Compute a score for the initial "fully reduced" solution.
1199 void Score::RateInitial(SmallVector const &Uses, const Loop *L,
1200 ScalarEvolution &SE) {
1201 SmallPtrSet Regs;
1202 for (SmallVectorImpl::const_iterator I = Uses.begin(),
1203 E = Uses.end(); I != E; ++I)
1204 RateFormula(I->Formulae.front(), Regs, L);
1205 NumRegs += Regs.size();
1206
1207 DEBUG(print_details(dbgs(), 0, Regs));
1208 }
1209
1210 /// Rate - Compute a score for the solution where the reuse associated with
1211 /// putting Reg in a register is selected.
1212 void Score::Rate(const SCEV *Reg, const SmallBitVector &Bits,
1213 const SmallVector &Uses, const Loop *L,
1214 ScalarEvolution &SE) {
1215 SmallPtrSet Regs;
1216 for (size_t i = 0, e = Uses.size(); i != e; ++i) {
1217 const LSRUse &LU = Uses[i];
1218
1219 const Formula *BestFormula = 0;
1220 if (i >= Bits.size() || !Bits.test(i))
1221 // This use doesn't use the current register. Just go with the current
1222 // leading candidate formula.
1223 BestFormula = &LU.Formulae.front();
1224 else
1225 // Find the best formula for this use that uses the current register.
1226 for (SmallVectorImpl::const_iterator I = LU.Formulae.begin(),
1227 E = LU.Formulae.end(); I != E; ++I) {
1228 const Formula &F = *I;
1229 if (F.referencesReg(Reg) &&
1230 (!BestFormula || ComplexitySorter()(F, *BestFormula)))
1231 BestFormula = &F;
1232 }
1233
1234 // If we didn't find *any* forumlae, because earlier we eliminated some
1235 // in greedy fashion, skip the current register's reuse opportunity.
1236 if (!BestFormula) {
1237 DEBUG(dbgs() << "Reuse with reg " << *Reg
1238 << " wouldn't help any users.\n");
1239 Loose();
1240 return;
1241 }
1242
1243 // For an in-loop post-inc user, don't allow multiple base registers,
1244 // because that would require an awkward in-loop add after the increment.
1245 if (LU.PostIncLoop && LU.PostIncLoop->contains(LU.UserInst) &&
1246 BestFormula->BaseRegs.size() > 1) {
1247 DEBUG(dbgs() << "Reuse with reg " << *Reg
1248 << " would require an in-loop post-inc add: ";
1249 BestFormula->dump());
1250 Loose();
1251 return;
1252 }
1253
1254 RateFormula(*BestFormula, Regs, L);
1255 }
1256 NumRegs += Regs.size();
1257
1258 DEBUG(print_details(dbgs(), Reg, Regs));
1259 }
1260
1261 /// operator< - Choose the better score.
1262 bool Score::operator<(const Score &Other) const {
1263 if (NumRegs != Other.NumRegs)
1264 return NumRegs < Other.NumRegs;
1265 if (NumPhis != Other.NumPhis)
1266 return NumPhis < Other.NumPhis;
1267 if (NumIVMuls != Other.NumIVMuls)
1268 return NumIVMuls < Other.NumIVMuls;
1269 if (NumBaseAdds != Other.NumBaseAdds)
1270 return NumBaseAdds < Other.NumBaseAdds;
1271 return NumImms < Other.NumImms;
1272 }
1273
1274 void Score::print_details(raw_ostream &OS,
1275 const SCEV *Reg,
1276 const SmallPtrSet &Regs) const {
1277 if (Reg) OS << "Reuse with reg " << *Reg << " would require ";
1278 else OS << "The initial solution would require ";
1279 print(OS);
1280 OS << ". Regs:";
1281 for (SmallPtrSet::const_iterator I = Regs.begin(),
1282 E = Regs.end(); I != E; ++I)
1283 OS << ' ' << **I;
1284 OS << '\n';
1285 }
1286
1287 void Score::print(raw_ostream &OS) const {
1288 OS << NumRegs << " reg" << (NumRegs == 1 ? "" : "s");
1289 if (NumPhis != 0)
1290 OS << ", including " << NumPhis << " PHI" << (NumPhis == 1 ? "" : "s");
1291 if (NumIVMuls != 0)
1292 OS << ", plus " << NumIVMuls << " IV mul" << (NumIVMuls == 1 ? "" : "s");
1293 if (NumBaseAdds != 0)
1294 OS << ", plus " << NumBaseAdds << " base add"
1295 << (NumBaseAdds == 1 ? "" : "s");
1296 if (NumImms != 0)
1297 OS << ", plus " << NumImms << " imm" << (NumImms == 1 ? "" : "s");
1298 }
1299
1300 void Score::dump() const {
1301 print(errs()); errs() << '\n';
71 /// IVsOfOneStride - This structure keeps track of all IV expression inserted
72 /// during StrengthReduceStridedIVUsers for a particular stride of the IV.
73 struct IVsOfOneStride {
74 std::vector IVs;
75
76 void addIV(const SCEV *const Stride, const SCEV *const Base, PHINode *PHI) {
77 IVs.push_back(IVExpr(Stride, Base, PHI));
78 }
79 };
80
81 class LoopStrengthReduce : public LoopPass {
82 IVUsers *IU;
83 ScalarEvolution *SE;
84 bool Changed;
85
86 /// IVsByStride - Keep track of all IVs that have been inserted for a
87 /// particular stride.
88 std::map IVsByStride;
89
90 /// DeadInsts - Keep track of instructions we may have made dead, so that
91 /// we can remove them after we are done working.
92 SmallVector DeadInsts;
93
94 /// TLI - Keep a pointer of a TargetLowering to consult for determining
95 /// transformation profitability.
96 const TargetLowering *TLI;
97
98 public:
99 static char ID; // Pass ID, replacement for typeid
100 explicit LoopStrengthReduce(const TargetLowering *tli = NULL) :
101 LoopPass(&ID), TLI(tli) {}
102
103 bool runOnLoop(Loop *L, LPPassManager &LPM);
104
105 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
106 // We split critical edges, so we change the CFG. However, we do update
107 // many analyses if they are around.
108 AU.addPreservedID(LoopSimplifyID);
109 AU.addPreserved("loops");
110 AU.addPreserved("domfrontier");
111 AU.addPreserved("domtree");
112
113 AU.addRequiredID(LoopSimplifyID);
114 AU.addRequired();
115 AU.addPreserved();
116 AU.addRequired();
117 AU.addPreserved();
118 }
119
120 private:
121 void OptimizeIndvars(Loop *L);
122
123 /// OptimizeLoopTermCond - Change loop terminating condition to use the
124 /// postinc iv when possible.
125 void OptimizeLoopTermCond(Loop *L);
126
127 /// OptimizeShadowIV - If IV is used in a int-to-float cast
128 /// inside the loop then try to eliminate the cast opeation.
129 void OptimizeShadowIV(Loop *L);
130
131 /// OptimizeMax - Rewrite the loop's terminating condition
132 /// if it uses a max computation.
133 ICmpInst *OptimizeMax(Loop *L, ICmpInst *Cond,
134 IVStrideUse* &CondUse);
135
136 /// OptimizeLoopCountIV - If, after all sharing of IVs, the IV used for
137 /// deciding when to exit the loop is used only for that purpose, try to
138 /// rearrange things so it counts down to a test against zero.
139 bool OptimizeLoopCountIV(Loop *L);
140 bool OptimizeLoopCountIVOfStride(const SCEV* &Stride,
141 IVStrideUse* &CondUse, Loop *L);
142
143 /// StrengthReduceIVUsersOfStride - Strength reduce all of the users of a
144 /// single stride of IV. All of the users may have different starting
145 /// values, and this may not be the only stride.
146 void StrengthReduceIVUsersOfStride(const SCEV *Stride,
147 IVUsersOfOneStride &Uses,
148 Loop *L);
149 void StrengthReduceIVUsers(Loop *L);
150
151 ICmpInst *ChangeCompareStride(Loop *L, ICmpInst *Cond,
152 IVStrideUse* &CondUse,
153 const SCEV* &CondStride,
154 bool PostPass = false);
155
156 bool FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse,
157 const SCEV* &CondStride);
158 bool RequiresTypeConversion(const Type *Ty, const Type *NewTy);
159 const SCEV *CheckForIVReuse(bool, bool, bool, const SCEV *,
160 IVExpr&, const Type*,
161 const std::vector& UsersToProcess);
162 bool ValidScale(bool, int64_t,
163 const std::vector& UsersToProcess);
164 bool ValidOffset(bool, int64_t, int64_t,
165 const std::vector& UsersToProcess);
166 const SCEV *CollectIVUsers(const SCEV *Stride,
167 IVUsersOfOneStride &Uses,
168 Loop *L,
169 bool &AllUsesAreAddresses,
170 bool &AllUsesAreOutsideLoop,
171 std::vector &UsersToProcess);
172 bool StrideMightBeShared(const SCEV *Stride, Loop *L, bool CheckPreInc);
173 bool ShouldUseFullStrengthReductionMode(
174 const std::vector &UsersToProcess,
175 const Loop *L,
176 bool AllUsesAreAddresses,
177 const SCEV *Stride);
178 void PrepareToStrengthReduceFully(
179 std::vector &UsersToProcess,
180 const SCEV *Stride,
181 const SCEV *CommonExprs,
182 const Loop *L,
183 SCEVExpander &PreheaderRewriter);
184 void PrepareToStrengthReduceFromSmallerStride(
185 std::vector &UsersToProcess,
186 Value *CommonBaseV,
187 const IVExpr &ReuseIV,
188 Instruction *PreInsertPt);
189 void PrepareToStrengthReduceWithNewPhi(
190 std::vector &UsersToProcess,
191 const SCEV *Stride,
192 const SCEV *CommonExprs,
193 Value *CommonBaseV,
194 Instruction *IVIncInsertPt,
195 const Loop *L,
196 SCEVExpander &PreheaderRewriter);
197
198 void DeleteTriviallyDeadInstructions();
199 };
200 }
201
202 char LoopStrengthReduce::ID = 0;
203 static RegisterPass
204 X("loop-reduce", "Loop Strength Reduction");
205
206 Pass *llvm::createLoopStrengthReducePass(const TargetLowering *TLI) {
207 return new LoopStrengthReduce(TLI);
208 }
209
210 /// DeleteTriviallyDeadInstructions - If any of the instructions is the
211 /// specified set are trivially dead, delete them and see if this makes any of
212 /// their operands subsequently dead.
213 void LoopStrengthReduce::DeleteTriviallyDeadInstructions() {
214 while (!DeadInsts.empty()) {
215 Instruction *I = dyn_cast_or_null(DeadInsts.pop_back_val());
216
217 if (I == 0 || !isInstructionTriviallyDead(I))
218 continue;
219
220 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
221 if (Instruction *U = dyn_cast(*OI)) {
222 *OI = 0;
223 if (U->use_empty())
224 DeadInsts.push_back(U);
225 }
226
227 I->eraseFromParent();
228 Changed = true;
229 }
1302230 }
1303231
1304232 /// isAddressUse - Returns true if the specified instruction is using the
1350278 return AccessTy;
1351279 }
1352280
1353 /// DeleteTriviallyDeadInstructions - If any of the instructions is the
1354 /// specified set are trivially dead, delete them and see if this makes any of
1355 /// their operands subsequently dead.
1356 static bool
1357 DeleteTriviallyDeadInstructions(SmallVectorImpl &DeadInsts) {
1358 bool Changed = false;
1359
1360 while (!DeadInsts.empty()) {
1361 Instruction *I = dyn_cast_or_null(DeadInsts.pop_back_val());
1362
1363 if (I == 0 || !isInstructionTriviallyDead(I))
281 namespace {
282 /// BasedUser - For a particular base value, keep information about how we've
283 /// partitioned the expression so far.
284 struct BasedUser {
285 /// Base - The Base value for the PHI node that needs to be inserted for
286 /// this use. As the use is processed, information gets moved from this
287 /// field to the Imm field (below). BasedUser values are sorted by this
288 /// field.
289 const SCEV *Base;
290
291 /// Inst - The instruction using the induction variable.
292 Instruction *Inst;
293
294 /// OperandValToReplace - The operand value of Inst to replace with the
295 /// EmittedBase.
296 Value *OperandValToReplace;
297
298 /// Imm - The immediate value that should be added to the base immediately
299 /// before Inst, because it will be folded into the imm field of the
300 /// instruction. This is also sometimes used for loop-variant values that
301 /// must be added inside the loop.
302 const SCEV *Imm;
303
304 /// Phi - The induction variable that performs the striding that
305 /// should be used for this user.
306 PHINode *Phi;
307
308 // isUseOfPostIncrementedValue - True if this should use the
309 // post-incremented version of this IV, not the preincremented version.
310 // This can only be set in special cases, such as the terminating setcc
311 // instruction for a loop and uses outside the loop that are dominated by
312 // the loop.
313 bool isUseOfPostIncrementedValue;
314
315 BasedUser(IVStrideUse &IVSU, ScalarEvolution *se)
316 : Base(IVSU.getOffset()), Inst(IVSU.getUser()),
317 OperandValToReplace(IVSU.getOperandValToReplace()),
318 Imm(se->getIntegerSCEV(0, Base->getType())),
319 isUseOfPostIncrementedValue(IVSU.isUseOfPostIncrementedValue()) {}
320
321 // Once we rewrite the code to insert the new IVs we want, update the
322 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
323 // to it.
324 void RewriteInstructionToUseNewBase(const SCEV *NewBase,
325 Instruction *InsertPt,
326 SCEVExpander &Rewriter, Loop *L, Pass *P,
327 SmallVectorImpl &DeadInsts,
328 ScalarEvolution *SE);
329
330 Value *InsertCodeForBaseAtPosition(const SCEV *NewBase,
331 const Type *Ty,
332 SCEVExpander &Rewriter,
333 Instruction *IP,
334 ScalarEvolution *SE);
335 void dump() const;
336 };
337 }
338
339 void BasedUser::dump() const {
340 dbgs() << " Base=" << *Base;
341 dbgs() << " Imm=" << *Imm;
342 dbgs() << " Inst: " << *Inst;
343 }
344
345 Value *BasedUser::InsertCodeForBaseAtPosition(const SCEV *NewBase,
346 const Type *Ty,
347 SCEVExpander &Rewriter,
348 Instruction *IP,
349 ScalarEvolution *SE) {
350 Value *Base = Rewriter.expandCodeFor(NewBase, 0, IP);
351
352 // Wrap the base in a SCEVUnknown so that ScalarEvolution doesn't try to
353 // re-analyze it.
354 const SCEV *NewValSCEV = SE->getUnknown(Base);
355
356 // Always emit the immediate into the same block as the user.
357 NewValSCEV = SE->getAddExpr(NewValSCEV, Imm);
358
359 return Rewriter.expandCodeFor(NewValSCEV, Ty, IP);
360 }
361
362
363 // Once we rewrite the code to insert the new IVs we want, update the
364 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
365 // to it. NewBasePt is the last instruction which contributes to the
366 // value of NewBase in the case that it's a diffferent instruction from
367 // the PHI that NewBase is computed from, or null otherwise.
368 //
369 void BasedUser::RewriteInstructionToUseNewBase(const SCEV *NewBase,
370 Instruction *NewBasePt,
371 SCEVExpander &Rewriter, Loop *L, Pass *P,
372 SmallVectorImpl &DeadInsts,
373 ScalarEvolution *SE) {
374 if (!isa(Inst)) {
375 // By default, insert code at the user instruction.
376 BasicBlock::iterator InsertPt = Inst;
377
378 // However, if the Operand is itself an instruction, the (potentially
379 // complex) inserted code may be shared by many users. Because of this, we
380 // want to emit code for the computation of the operand right before its old
381 // computation. This is usually safe, because we obviously used to use the
382 // computation when it was computed in its current block. However, in some
383 // cases (e.g. use of a post-incremented induction variable) the NewBase
384 // value will be pinned to live somewhere after the original computation.
385 // In this case, we have to back off.
386 //
387 // If this is a use outside the loop (which means after, since it is based
388 // on a loop indvar) we use the post-incremented value, so that we don't
389 // artificially make the preinc value live out the bottom of the loop.
390 if (!isUseOfPostIncrementedValue && L->contains(Inst)) {
391 if (NewBasePt && isa(OperandValToReplace)) {
392 InsertPt = NewBasePt;
393 ++InsertPt;
394 } else if (Instruction *OpInst
395 = dyn_cast(OperandValToReplace)) {
396 InsertPt = OpInst;
397 while (isa(InsertPt)) ++InsertPt;
398 }
399 }
400 Value *NewVal = InsertCodeForBaseAtPosition(NewBase,
401 OperandValToReplace->getType(),
402 Rewriter, InsertPt, SE);
403 // Replace the use of the operand Value with the new Phi we just created.
404 Inst->replaceUsesOfWith(OperandValToReplace, NewVal);
405
406 DEBUG(dbgs() << " Replacing with ");
407 DEBUG(WriteAsOperand(dbgs(), NewVal, /*PrintType=*/false));
408 DEBUG(dbgs() << ", which has value " << *NewBase << " plus IMM "
409 << *Imm << "\n");
410 return;
411 }
412
413 // PHI nodes are more complex. We have to insert one copy of the NewBase+Imm
414 // expression into each operand block that uses it. Note that PHI nodes can
415 // have multiple entries for the same predecessor. We use a map to make sure
416 // that a PHI node only has a single Value* for each predecessor (which also
417 // prevents us from inserting duplicate code in some blocks).
418 DenseMap InsertedCode;
419 PHINode *PN = cast(Inst);
420 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
421 if (PN->getIncomingValue(i) == OperandValToReplace) {
422 // If the original expression is outside the loop, put the replacement
423 // code in the same place as the original expression,
424 // which need not be an immediate predecessor of this PHI. This way we
425 // need only one copy of it even if it is referenced multiple times in
426 // the PHI. We don't do this when the original expression is inside the
427 // loop because multiple copies sometimes do useful sinking of code in
428 // that case(?).
429 Instruction *OldLoc = dyn_cast(OperandValToReplace);
430 BasicBlock *PHIPred = PN->getIncomingBlock(i);
431 if (L->contains(OldLoc)) {
432 // If this is a critical edge, split the edge so that we do not insert
433 // the code on all predecessor/successor paths. We do this unless this
434 // is the canonical backedge for this loop, as this can make some
435 // inserted code be in an illegal position.
436 if (e != 1 && PHIPred->getTerminator()->getNumSuccessors() > 1 &&
437 !isa(PHIPred->getTerminator()) &&
438 (PN->getParent() != L->getHeader() || !L->contains(PHIPred))) {
439
440 // First step, split the critical edge.
441 BasicBlock *NewBB = SplitCriticalEdge(PHIPred, PN->getParent(),
442 P, false);
443
444 // Next step: move the basic block. In particular, if the PHI node
445 // is outside of the loop, and PredTI is in the loop, we want to
446 // move the block to be immediately before the PHI block, not
447 // immediately after PredTI.
448 if (L->contains(PHIPred) && !L->contains(PN))
449 NewBB->moveBefore(PN->getParent());
450
451 // Splitting the edge can reduce the number of PHI entries we have.
452 e = PN->getNumIncomingValues();
453 PHIPred = NewBB;
454 i = PN->getBasicBlockIndex(PHIPred);
455 }
456 }
457 Value *&Code = InsertedCode[PHIPred];
458 if (!Code) {
459 // Insert the code into the end of the predecessor block.
460 Instruction *InsertPt = (L->contains(OldLoc)) ?
461 PHIPred->getTerminator() :
462 OldLoc->getParent()->getTerminator();
463 Code = InsertCodeForBaseAtPosition(NewBase, PN->getType(),
464 Rewriter, InsertPt, SE);
465
466 DEBUG(dbgs() << " Changing PHI use to ");
467 DEBUG(WriteAsOperand(dbgs(), Code, /*PrintType=*/false));
468 DEBUG(dbgs() << ", which has value " << *NewBase << " plus IMM "
469 << *Imm << "\n");
470 }
471
472 // Replace the use of the operand Value with the new Phi we just created.
473 PN->setIncomingValue(i, Code);
474 Rewriter.clear();
475 }
476 }
477
478 // PHI node might have become a constant value after SplitCriticalEdge.
479 DeadInsts.push_back(Inst);
480 }
481
482
483 /// fitsInAddressMode - Return true if V can be subsumed within an addressing
484 /// mode, and does not need to be put in a register first.
485 static bool fitsInAddressMode(const SCEV *V, const Type *AccessTy,
486 const TargetLowering *TLI, bool HasBaseReg) {
487 if (const SCEVConstant *SC = dyn_cast(V)) {
488 int64_t VC = SC->getValue()->getSExtValue();
489 if (TLI) {
490 TargetLowering::AddrMode AM;
491 AM.BaseOffs = VC;
492 AM.HasBaseReg = HasBaseReg;
493 return TLI->isLegalAddressingMode(AM, AccessTy);
494 } else {
495 // Defaults to PPC. PPC allows a sign-extended 16-bit immediate field.
496 return (VC > -(1 << 16) && VC < (1 << 16)-1);
497 }
498 }
499
500 if (const SCEVUnknown *SU = dyn_cast(V))
501 if (GlobalValue *GV = dyn_cast(SU->getValue())) {
502 if (TLI) {
503 TargetLowering::AddrMode AM;
504 AM.BaseGV = GV;
505 AM.HasBaseReg = HasBaseReg;
506 return TLI->isLegalAddressingMode(AM, AccessTy);
507 } else {
508 // Default: assume global addresses are not legal.
509 }
510 }
511
512 return false;
513 }
514
515 /// MoveLoopVariantsToImmediateField - Move any subexpressions from Val that are
516 /// loop varying to the Imm operand.
517 static void MoveLoopVariantsToImmediateField(const SCEV *&Val, const SCEV *&Imm,
518 Loop *L, ScalarEvolution *SE) {
519 if (Val->isLoopInvariant(L)) return; // Nothing to do.
520
521 if (const SCEVAddExpr *SAE = dyn_cast(Val)) {
522 SmallVector NewOps;
523 NewOps.reserve(SAE->getNumOperands());
524
525 for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
526 if (!SAE->getOperand(i)->isLoopInvariant(L)) {
527 // If this is a loop-variant expression, it must stay in the immediate
528 // field of the expression.
529 Imm = SE->getAddExpr(Imm, SAE->getOperand(i));
530 } else {
531 NewOps.push_back(SAE->getOperand(i));
532 }
533
534 if (NewOps.empty())
535 Val = SE->getIntegerSCEV(0, Val->getType());
536 else
537 Val = SE->getAddExpr(NewOps);
538 } else if (const SCEVAddRecExpr *SARE = dyn_cast(Val)) {
539 // Try to pull immediates out of the start value of nested addrec's.
540 const SCEV *Start = SARE->getStart();
541 MoveLoopVariantsToImmediateField(Start, Imm, L, SE);
542
543 SmallVector Ops(SARE->op_begin(), SARE->op_end());
544 Ops[0] = Start;
545 Val = SE->getAddRecExpr(Ops, SARE->getLoop());
546 } else {
547 // Otherwise, all of Val is variant, move the whole thing over.
548 Imm = SE->getAddExpr(Imm, Val);
549 Val = SE->getIntegerSCEV(0, Val->getType());
550 }
551 }
552
553
554 /// MoveImmediateValues - Look at Val, and pull out any additions of constants
555 /// that can fit into the immediate field of instructions in the target.
556 /// Accumulate these immediate values into the Imm value.
557 static void MoveImmediateValues(const TargetLowering *TLI,
558 const Type *AccessTy,
559 const SCEV *&Val, const SCEV *&Imm,
560 bool isAddress, Loop *L,
561 ScalarEvolution *SE) {
562 if (const SCEVAddExpr *SAE = dyn_cast(Val)) {
563 SmallVector NewOps;
564 NewOps.reserve(SAE->getNumOperands());
565
566 for (unsigned i = 0; i != SAE->getNumOperands(); ++i) {
567 const SCEV *NewOp = SAE->getOperand(i);
568 MoveImmediateValues(TLI, AccessTy, NewOp, Imm, isAddress, L, SE);
569
570 if (!NewOp->isLoopInvariant(L)) {
571 // If this is a loop-variant expression, it must stay in the immediate
572 // field of the expression.
573 Imm = SE->getAddExpr(Imm, NewOp);
574 } else {
575 NewOps.push_back(NewOp);
576 }
577 }
578
579 if (NewOps.empty())
580 Val = SE->getIntegerSCEV(0, Val->getType());
581 else
582 Val = SE->getAddExpr(NewOps);
583 return;
584 } else if (const SCEVAddRecExpr *SARE = dyn_cast(Val)) {
585 // Try to pull immediates out of the start value of nested addrec's.
586 const SCEV *Start = SARE->getStart();
587 MoveImmediateValues(TLI, AccessTy, Start, Imm, isAddress, L, SE);
588
589 if (Start != SARE->getStart()) {
590 SmallVector Ops(SARE->op_begin(), SARE->op_end());
591 Ops[0] = Start;
592 Val = SE->getAddRecExpr(Ops, SARE->getLoop());
593 }
594 return;
595 } else if (const SCEVMulExpr *SME = dyn_cast(Val)) {
596 // Transform "8 * (4 + v)" -> "32 + 8*V" if "32" fits in the immed field.
597 if (isAddress &&
598 fitsInAddressMode(SME->getOperand(0), AccessTy, TLI, false) &&
599 SME->getNumOperands() == 2 && SME->isLoopInvariant(L)) {
600
601 const SCEV *SubImm = SE->getIntegerSCEV(0, Val->getType());
602 const SCEV *NewOp = SME->getOperand(1);
603 MoveImmediateValues(TLI, AccessTy, NewOp, SubImm, isAddress, L, SE);
604
605 // If we extracted something out of the subexpressions, see if we can
606 // simplify this!
607 if (NewOp != SME->getOperand(1)) {
608 // Scale SubImm up by "8". If the result is a target constant, we are
609 // good.
610 SubImm = SE->getMulExpr(SubImm, SME->getOperand(0));
611 if (fitsInAddressMode(SubImm, AccessTy, TLI, false)) {
612 // Accumulate the immediate.
613 Imm = SE->getAddExpr(Imm, SubImm);
614
615 // Update what is left of 'Val'.
616 Val = SE->getMulExpr(SME->getOperand(0), NewOp);
617 return;
618 }
619 }
620 }
621 }
622
623 // Loop-variant expressions must stay in the immediate field of the
624 // expression.
625 if ((isAddress && fitsInAddressMode(Val, AccessTy, TLI, false)) ||
626 !Val->isLoopInvariant(L)) {
627 Imm = SE->getAddExpr(Imm, Val);
628 Val = SE->getIntegerSCEV(0, Val->getType());
629 return;
630 }
631
632 // Otherwise, no immediates to move.
633 }
634
635 static void MoveImmediateValues(const TargetLowering *TLI,
636 Instruction *User,
637 const SCEV *&Val, const SCEV *&Imm,
638 bool isAddress, Loop *L,
639 ScalarEvolution *SE) {
640 const Type *AccessTy = getAccessType(User);
641 MoveImmediateValues(TLI, AccessTy, Val, Imm, isAddress, L, SE);
642 }
643
644 /// SeparateSubExprs - Decompose Expr into all of the subexpressions that are
645 /// added together. This is used to reassociate common addition subexprs
646 /// together for maximal sharing when rewriting bases.
647 static void SeparateSubExprs(SmallVector &SubExprs,
648 const SCEV *Expr,
649 ScalarEvolution *SE) {
650 if (const SCEVAddExpr *AE = dyn_cast(Expr)) {
651 for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
652 SeparateSubExprs(SubExprs, AE->getOperand(j), SE);
653 } else if (const SCEVAddRecExpr *SARE = dyn_cast(Expr)) {
654 const SCEV *Zero = SE->getIntegerSCEV(0, Expr->getType());
655 if (SARE->getOperand(0) == Zero) {
656 SubExprs.push_back(Expr);
657 } else {
658 // Compute the addrec with zero as its base.
659 SmallVector Ops(SARE->op_begin(), SARE->op_end());
660 Ops[0] = Zero; // Start with zero base.
661 SubExprs.push_back(SE->getAddRecExpr(Ops, SARE->getLoop()));
662
663
664 SeparateSubExprs(SubExprs, SARE->getOperand(0), SE);
665 }
666 } else if (!Expr->isZero()) {
667 // Do not add zero.
668 SubExprs.push_back(Expr);
669 }
670 }
671
672 // This is logically local to the following function, but C++ says we have
673 // to make it file scope.
674 struct SubExprUseData { unsigned Count; bool notAllUsesAreFree; };
675
676 /// RemoveCommonExpressionsFromUseBases - Look through all of the Bases of all
677 /// the Uses, removing any common subexpressions, except that if all such
678 /// subexpressions can be folded into an addressing mode for all uses inside
679 /// the loop (this case is referred to as "free" in comments herein) we do
680 /// not remove anything. This looks for things like (a+b+c) and
681 /// (a+c+d) and computes the common (a+c) subexpression. The common expression
682 /// is *removed* from the Bases and returned.
683 static const SCEV *
684 RemoveCommonExpressionsFromUseBases(std::vector &Uses,
685 ScalarEvolution *SE, Loop *L,
686 const TargetLowering *TLI) {
687 unsigned NumUses = Uses.size();
688
689 // Only one use? This is a very common case, so we handle it specially and
690 // cheaply.
691 const SCEV *Zero = SE->getIntegerSCEV(0, Uses[0].Base->getType());
692 const SCEV *Result = Zero;
693 const SCEV *FreeResult = Zero;
694 if (NumUses == 1) {
695 // If the use is inside the loop, use its base, regardless of what it is:
696 // it is clearly shared across all the IV's. If the use is outside the loop
697 // (which means after it) we don't want to factor anything *into* the loop,
698 // so just use 0 as the base.
699 if (L->contains(Uses[0].Inst))
700 std::swap(Result, Uses[0].Base);
701 return Result;
702 }
703
704 // To find common subexpressions, count how many of Uses use each expression.
705 // If any subexpressions are used Uses.size() times, they are common.
706 // Also track whether all uses of each expression can be moved into an
707 // an addressing mode "for free"; such expressions are left within the loop.
708 // struct SubExprUseData { unsigned Count; bool notAllUsesAreFree; };
709 std::map SubExpressionUseData;
710
711 // UniqueSubExprs - Keep track of all of the subexpressions we see in the
712 // order we see them.
713 SmallVector UniqueSubExprs;
714
715 SmallVector SubExprs;
716 unsigned NumUsesInsideLoop = 0;
717 for (unsigned i = 0; i != NumUses; ++i) {
718 // If the user is outside the loop, just ignore it for base computation.
719 // Since the user is outside the loop, it must be *after* the loop (if it
720 // were before, it could not be based on the loop IV). We don't want users
721 // after the loop to affect base computation of values *inside* the loop,
722 // because we can always add their offsets to the result IV after the loop
723 // is done, ensuring we get good code inside the loop.
724 if (!L->contains(Uses[i].Inst))
1364725 continue;
1365
1366 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
1367 if (Instruction *U = dyn_cast(*OI)) {
1368 *OI = 0;
1369 if (U->use_empty())
1370 DeadInsts.push_back(U);
1371 }
1372
1373 I->eraseFromParent();
1374 Changed = true;
1375 }
1376
1377 return Changed;
1378 }
1379
1380 namespace {
1381
1382 /// LSRInstance - This class holds state for the main loop strength
1383 /// reduction logic.
1384 class LSRInstance {
1385 IVUsers &IU;
1386 ScalarEvolution &SE;
1387 DominatorTree &DT;
1388 const TargetLowering *const TLI;
1389 Loop *const L;
1390 bool Changed;
1391
1392 /// IVIncInsertPos - This is the insert position that the current loop's
1393 /// induction variable increment should be placed. In simple loops, this is
1394 /// the latch block's terminator. But in more complicated cases, this is
1395 /// a position which will dominate all the in-loop post-increment users.
1396 Instruction *IVIncInsertPos;
1397
1398 /// CurrentArbitraryRegIndex - To ensure a deterministic ordering, assign an
1399 /// arbitrary index value to each register as a sort tie breaker.
1400 unsigned CurrentArbitraryRegIndex;
1401
1402 /// MaxNumRegs - To help prune the search for solutions, identify the number
1403 /// of registers needed by the initial solution. No formula should require
1404 /// more than this.
1405 unsigned MaxNumRegs;
1406
1407 /// Factors - Interesting factors between use strides.
1408 SmallSetVector Factors;
1409
1410 /// Types - Interesting use types, to facilitate truncation reuse.
1411 SmallSetVector Types;
1412
1413 /// Uses - The list of interesting uses.
1414 SmallVector Uses;
1415
1416 // TODO: Reorganize these data structures.
1417 typedef DenseMap RegUsesTy;
1418 RegUsesTy RegUses;
1419 SmallVector RegSequence;
1420
1421 void OptimizeShadowIV();
1422 bool FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse,
1423 const SCEV* &CondStride);
1424 ICmpInst *OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse);
1425 bool StrideMightBeShared(const SCEV* Stride);
1426 bool OptimizeLoopTermCond();
1427
1428 LSRUse &getNewUse() {
1429 Uses.push_back(LSRUse());
1430 return Uses.back();
1431 }
1432
1433 void CountRegister(const SCEV *Reg, uint32_t Complexity, size_t LUIdx);
1434 void CountRegisters(const Formula &F, size_t LUIdx);
1435
1436 bool InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F);
1437
1438 void GenerateSymbolicOffsetReuse(LSRUse &LU, unsigned LUIdx,
1439 Formula Base);
1440 void GenerateICmpZeroScaledReuse(LSRUse &LU, unsigned LUIdx,
1441 Formula Base);
1442 void GenerateFormulaeFromReplacedBaseReg(LSRUse &LU,
1443 unsigned LUIdx,
1444 const Formula &Base, unsigned i,
1445 const SmallVectorImpl
1446 &AddOps);
1447 void GenerateReassociationReuse(LSRUse &LU, unsigned LUIdx,
1448 Formula Base);
1449 void GenerateCombinationReuse(LSRUse &LU, unsigned LUIdx,
1450 Formula Base);
1451 void GenerateScaledReuse(LSRUse &LU, unsigned LUIdx,
1452 Formula Base);
1453 void GenerateTruncateReuse(LSRUse &LU, unsigned LUIdx,
1454 Formula Base);
1455
1456 void GenerateConstantOffsetReuse();
1457
1458 void GenerateAllReuseFormulae();
1459
1460 void GenerateLoopInvariantRegisterUses();
1461
1462 public:
1463 LSRInstance(const TargetLowering *tli, Loop *l, Pass *P);
1464
1465 bool getChanged() const { return Changed; }
1466
1467 void print(raw_ostream &OS) const;
1468 void dump() const;
1469 };
1470
1471 }
1472
1473 /// OptimizeShadowIV - If IV is used in a int-to-float cast
1474 /// inside the loop then try to eliminate the cast opeation.
1475 void LSRInstance::OptimizeShadowIV() {
1476 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
1477 if (isa(BackedgeTakenCount))
726 NumUsesInsideLoop++;
727
728 // If the base is zero (which is common), return zero now, there are no
729 // CSEs we can find.
730 if (Uses[i].Base == Zero) return Zero;
731
732 // If this use is as an address we may be able to put CSEs in the addressing
733 // mode rather than hoisting them.
734 bool isAddrUse = isAddressUse(Uses[i].Inst, Uses[i].OperandValToReplace);
735 // We may need the AccessTy below, but only when isAddrUse, so compute it
736 // only in that case.
737 const Type *AccessTy = 0;
738 if (isAddrUse)
739 AccessTy = getAccessType(Uses[i].Inst);
740
741 // Split the expression into subexprs.
742 SeparateSubExprs(SubExprs, Uses[i].Base, SE);
743 // Add one to SubExpressionUseData.Count for each subexpr present, and
744 // if the subexpr is not a valid immediate within an addressing mode use,
745 // set SubExpressionUseData.notAllUsesAreFree. We definitely want to
746 // hoist these out of the loop (if they are common to all uses).
747 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j) {
748 if (++SubExpressionUseData[SubExprs[j]].Count == 1)
749 UniqueSubExprs.push_back(SubExprs[j]);
750 if (!isAddrUse || !fitsInAddressMode(SubExprs[j], AccessTy, TLI, false))
751 SubExpressionUseData[SubExprs[j]].notAllUsesAreFree = true;
752 }
753 SubExprs.clear();
754 }
755
756 // Now that we know how many times each is used, build Result. Iterate over
757 // UniqueSubexprs so that we have a stable ordering.
758 for (unsigned i = 0, e = UniqueSubExprs.size(); i != e; ++i) {
759 std::map::iterator I =
760 SubExpressionUseData.find(UniqueSubExprs[i]);
761 assert(I != SubExpressionUseData.end() && "Entry not found?");
762 if (I->second.Count == NumUsesInsideLoop) { // Found CSE!
763 if (I->second.notAllUsesAreFree)
764 Result = SE->getAddExpr(Result, I->first);
765 else
766 FreeResult = SE->getAddExpr(FreeResult, I->first);
767 } else
768 // Remove non-cse's from SubExpressionUseData.
769 SubExpressionUseData.erase(I);
770 }
771
772 if (FreeResult != Zero) {
773 // We have some subexpressions that can be subsumed into addressing
774 // modes in every use inside the loop. However, it's possible that
775 // there are so many of them that the combined FreeResult cannot
776 // be subsumed, or that the target cannot handle both a FreeResult
777 // and a Result in the same instruction (for example because it would
778 // require too many registers). Check this.
779 for (unsigned i=0; i
780 if (!L->contains(Uses[i].Inst))
781 continue;
782 // We know this is an addressing mode use; if there are any uses that
783 // are not, FreeResult would be Zero.
784 const Type *AccessTy = getAccessType(Uses[i].Inst);
785 if (!fitsInAddressMode(FreeResult, AccessTy, TLI, Result!=Zero)) {
786 // FIXME: could split up FreeResult into pieces here, some hoisted
787 // and some not. There is no obvious advantage to this.
788 Result = SE->getAddExpr(Result, FreeResult);
789 FreeResult = Zero;
790 break;
791 }
792 }
793 }
794
795 // If we found no CSE's, return now.
796 if (Result == Zero) return Result;
797
798 // If we still have a FreeResult, remove its subexpressions from
799 // SubExpressionUseData. This means they will remain in the use Bases.
800 if (FreeResult != Zero) {
801 SeparateSubExprs(SubExprs, FreeResult, SE);
802 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j) {
803 std::map::iterator I =
804 SubExpressionUseData.find(SubExprs[j]);
805 SubExpressionUseData.erase(I);
806 }
807 SubExprs.clear();
808 }
809
810 // Otherwise, remove all of the CSE's we found from each of the base values.
811 for (unsigned i = 0; i != NumUses; ++i) {
812 // Uses outside the loop don't necessarily include the common base, but
813 // the final IV value coming into those uses does. Instead of trying to
814 // remove the pieces of the common base, which might not be there,
815 // subtract off the base to compensate for this.
816 if (!L->contains(Uses[i].Inst)) {
817 Uses[i].Base = SE->getMinusSCEV(Uses[i].Base, Result);
818 continue;
819 }
820
821 // Split the expression into subexprs.
822 SeparateSubExprs(SubExprs, Uses[i].Base, SE);
823
824 // Remove any common subexpressions.
825 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
826 if (SubExpressionUseData.count(SubExprs[j])) {
827 SubExprs.erase(SubExprs.begin()+j);
828 --j; --e;
829 }
830
831 // Finally, add the non-shared expressions together.
832 if (SubExprs.empty())
833 Uses[i].Base = Zero;
834 else
835 Uses[i].Base = SE->getAddExpr(SubExprs);
836 SubExprs.clear();
837 }
838
839 return Result;
840 }
841
842 /// ValidScale - Check whether the given Scale is valid for all loads and
843 /// stores in UsersToProcess.
844 ///
845 bool LoopStrengthReduce::ValidScale(bool HasBaseReg, int64_t Scale,
846 const std::vector& UsersToProcess) {
847 if (!TLI)
848 return true;
849
850 for (unsigned i = 0, e = UsersToProcess.size(); i!=e; ++i) {
851 // If this is a load or other access, pass the type of the access in.
852 const Type *AccessTy =
853 Type::getVoidTy(UsersToProcess[i].Inst->getContext());
854 if (isAddressUse(UsersToProcess[i].Inst,
855 UsersToProcess[i].OperandValToReplace))
856 AccessTy = getAccessType(UsersToProcess[i].Inst);
857 else if (isa(UsersToProcess[i].Inst))
858 continue;
859
860 TargetLowering::AddrMode AM;
861 if (const SCEVConstant *SC = dyn_cast(UsersToProcess[i].Imm))
862 AM.BaseOffs = SC->getValue()->getSExtValue();
863 AM.HasBaseReg = HasBaseReg || !UsersToProcess[i].Base->isZero();
864 AM.Scale = Scale;
865
866 // If load[imm+r*scale] is illegal, bail out.
867 if (!TLI->isLegalAddressingMode(AM, AccessTy))
868 return false;
869 }
870 return true;
871 }
872
873 /// ValidOffset - Check whether the given Offset is valid for all loads and
874 /// stores in UsersToProcess.
875 ///
876 bool LoopStrengthReduce::ValidOffset(bool HasBaseReg,
877 int64_t Offset,
878 int64_t Scale,
879 const std::vector& UsersToProcess) {
880 if (!TLI)
881 return true;
882
883 for (unsigned i=0, e = UsersToProcess.size(); i!=e; ++i) {
884 // If this is a load or other access, pass the type of the access in.
885 const Type *AccessTy =
886 Type::getVoidTy(UsersToProcess[i].Inst->getContext());
887 if (isAddressUse(UsersToProcess[i].Inst,
888 UsersToProcess[i].OperandValToReplace))
889 AccessTy = getAccessType(UsersToProcess[i].Inst);
890 else if (isa(UsersToProcess[i].Inst))
891 continue;
892
893 TargetLowering::AddrMode AM;
894 if (const SCEVConstant *SC = dyn_cast(UsersToProcess[i].Imm))
895 AM.BaseOffs = SC->getValue()->getSExtValue();
896 AM.BaseOffs = (uint64_t)AM.BaseOffs + (uint64_t)Offset;
897 AM.HasBaseReg = HasBaseReg || !UsersToProcess[i].Base->isZero();
898 AM.Scale = Scale;
899
900 // If load[imm+r*scale] is illegal, bail out.
901 if (!TLI->isLegalAddressingMode(AM, AccessTy))
902 return false;
903 }
904 return true;
905 }
906
907 /// RequiresTypeConversion - Returns true if converting Ty1 to Ty2 is not
908 /// a nop.
909 bool LoopStrengthReduce::RequiresTypeConversion(const Type *Ty1,
910 const Type *Ty2) {
911 if (Ty1 == Ty2)
912 return false;
913 Ty1 = SE->getEffectiveSCEVType(Ty1);
914 Ty2 = SE->getEffectiveSCEVType(Ty2);
915 if (Ty1 == Ty2)
916 return false;
917 if (Ty1->canLosslesslyBitCastTo(Ty2))
918 return false;
919 if (TLI && TLI->isTruncateFree(Ty1, Ty2))
920 return false;
921 return true;
922 }
923
924 /// CheckForIVReuse - Returns the multiple if the stride is the multiple
925 /// of a previous stride and it is a legal value for the target addressing
926 /// mode scale component and optional base reg. This allows the users of
927 /// this stride to be rewritten as prev iv * factor. It returns 0 if no
928 /// reuse is possible. Factors can be negative on same targets, e.g. ARM.
929 ///
930 /// If all uses are outside the loop, we don't require that all multiplies
931 /// be folded into the addressing mode, nor even that the factor be constant;
932 /// a multiply (executed once) outside the loop is better than another IV
933 /// within. Well, usually.
934 const SCEV *LoopStrengthReduce::CheckForIVReuse(bool HasBaseReg,
935 bool AllUsesAreAddresses,
936 bool AllUsesAreOutsideLoop,
937 const SCEV *Stride,
938 IVExpr &IV, const Type *Ty,
939 const std::vector& UsersToProcess) {
940 if (const SCEVConstant *SC = dyn_cast(Stride)) {
941 int64_t SInt = SC->getValue()->getSExtValue();
942 for (unsigned NewStride = 0, e = IU->StrideOrder.size();
943 NewStride != e; ++NewStride) {
944 std::map::iterator SI =
945 IVsByStride.find(IU->StrideOrder[NewStride]);
946 if (SI == IVsByStride.end() || !isa(SI->first))
947 continue;
948 // The other stride has no uses, don't reuse it.
949 std::map::iterator UI =
950 IU->IVUsesByStride.find(IU->StrideOrder[NewStride]);
951 if (UI->second->Users.empty())
952 continue;
953 int64_t SSInt = cast(SI->first)->getValue()->getSExtValue();
954 if (SI->first != Stride &&
955 (unsigned(abs64(SInt)) < SSInt || (SInt % SSInt) != 0))
956 continue;
957 int64_t Scale = SInt / SSInt;
958 // Check that this stride is valid for all the types used for loads and
959 // stores; if it can be used for some and not others, we might as well use
960 // the original stride everywhere, since we have to create the IV for it
961 // anyway. If the scale is 1, then we don't need to worry about folding
962 // multiplications.
963 if (Scale == 1 ||
964 (AllUsesAreAddresses &&
965 ValidScale(HasBaseReg, Scale, UsersToProcess))) {
966 // Prefer to reuse an IV with a base of zero.
967 for (std::vector::iterator II = SI->second.IVs.begin(),
968 IE = SI->second.IVs.end(); II != IE; ++II)
969 // Only reuse previous IV if it would not require a type conversion
970 // and if the base difference can be folded.
971 if (II->Base->isZero() &&
972 !RequiresTypeConversion(II->Base->getType(), Ty)) {
973 IV = *II;
974 return SE->getIntegerSCEV(Scale, Stride->getType());
975 }
976 // Otherwise, settle for an IV with a foldable base.
977 if (AllUsesAreAddresses)
978 for (std::vector::iterator II = SI->second.IVs.begin(),
979 IE = SI->second.IVs.end(); II != IE; ++II)
980 // Only reuse previous IV if it would not require a type conversion
981 // and if the base difference can be folded.
982 if (SE->getEffectiveSCEVType(II->Base->getType()) ==
983 SE->getEffectiveSCEVType(Ty) &&
984 isa(II->Base)) {
985 int64_t Base =
986 cast(II->Base)->getValue()->getSExtValue();
987 if (Base > INT32_MIN && Base <= INT32_MAX &&
988 ValidOffset(HasBaseReg, -Base * Scale,
989 Scale, UsersToProcess)) {
990 IV = *II;
991 return SE->getIntegerSCEV(Scale, Stride->getType());
992 }
993 }
994 }
995 }
996 } else if (AllUsesAreOutsideLoop) {
997 // Accept nonconstant strides here; it is really really right to substitute
998 // an existing IV if we can.
999 for (unsigned NewStride = 0, e = IU->StrideOrder.size();
1000 NewStride != e; ++NewStride) {
1001 std::map::iterator SI =
1002 IVsByStride.find(IU->StrideOrder[NewStride]);
1003 if (SI == IVsByStride.end() || !isa(SI->first))
1004 continue;
1005 int64_t SSInt = cast(SI->first)->getValue()->getSExtValue();
1006 if (SI->first != Stride && SSInt != 1)
1007 continue;
1008 for (std::vector::iterator II = SI->second.IVs.begin(),
1009 IE = SI->second.IVs.end(); II != IE; ++II)
1010 // Accept nonzero base here.
1011 // Only reuse previous IV if it would not require a type conversion.
1012 if (!RequiresTypeConversion(II->Base->getType(), Ty)) {
1013 IV = *II;
1014 return Stride;
1015 }
1016 }
1017 // Special case, old IV is -1*x and this one is x. Can treat this one as
1018 // -1*old.
1019 for (unsigned NewStride = 0, e = IU->StrideOrder.size();
1020 NewStride != e; ++NewStride) {
1021 std::map::iterator SI =
1022 IVsByStride.find(IU->StrideOrder[NewStride]);
1023 if (SI == IVsByStride.end())
1024 continue;
1025 if (const SCEVMulExpr *ME = dyn_cast(SI->first))
1026 if (const SCEVConstant *SC = dyn_cast(ME->getOperand(0)))
1027 if (Stride == ME->getOperand(1) &&
1028 SC->getValue()->getSExtValue() == -1LL)
1029 for (std::vector::iterator II = SI->second.IVs.begin(),
1030 IE = SI->second.IVs.end(); II != IE; ++II)
1031 // Accept nonzero base here.
1032 // Only reuse previous IV if it would not require type conversion.
1033 if (!RequiresTypeConversion(II->Base->getType(), Ty)) {
1034 IV = *II;
1035 return SE->getIntegerSCEV(-1LL, Stride->getType());
1036 }
1037 }
1038 }
1039 return SE->getIntegerSCEV(0, Stride->getType());
1040 }
1041
1042 /// PartitionByIsUseOfPostIncrementedValue - Simple boolean predicate that
1043 /// returns true if Val's isUseOfPostIncrementedValue is true.
1044 static bool PartitionByIsUseOfPostIncrementedValue(const BasedUser &Val) {
1045 return Val.isUseOfPostIncrementedValue;
1046 }
1047
1048 /// isNonConstantNegative - Return true if the specified scev is negated, but
1049 /// not a constant.
1050 static bool isNonConstantNegative(const SCEV *Expr) {
1051 const SCEVMulExpr *Mul = dyn_cast(Expr);
1052 if (!Mul) return false;
1053
1054 // If there is a constant factor, it will be first.
1055 const SCEVConstant *SC = dyn_cast(Mul->getOperand(0));
1056 if (!SC) return false;
1057
1058 // Return true if the value is negative, this matches things like (-42 * V).
1059 return SC->getValue()->getValue().isNegative();
1060 }
1061
1062 /// CollectIVUsers - Transform our list of users and offsets to a bit more
1063 /// complex table. In this new vector, each 'BasedUser' contains 'Base', the
1064 /// base of the strided accesses, as well as the old information from Uses. We
1065 /// progressively move information from the Base field to the Imm field, until
1066 /// we eventually have the full access expression to rewrite the use.
1067 const SCEV *LoopStrengthReduce::CollectIVUsers(const SCEV *Stride,
1068 IVUsersOfOneStride &Uses,
1069 Loop *L,
1070 bool &AllUsesAreAddresses,
1071 bool &AllUsesAreOutsideLoop,
1072 std::vector &UsersToProcess) {
1073 // FIXME: Generalize to non-affine IV's.
1074 if (!Stride->isLoopInvariant(L))
1075 return SE->getIntegerSCEV(0, Stride->getType());
1076
1077 UsersToProcess.reserve(Uses.Users.size());
1078 for (ilist::iterator I = Uses.Users.begin(),
1079 E = Uses.Users.end(); I != E; ++I) {
1080 UsersToProcess.push_back(BasedUser(*I, SE));
1081
1082 // Move any loop variant operands from the offset field to the immediate
1083 // field of the use, so that we don't try to use something before it is
1084 // computed.
1085 MoveLoopVariantsToImmediateField(UsersToProcess.back().Base,
1086 UsersToProcess.back().Imm, L, SE);
1087 assert(UsersToProcess.back().Base->isLoopInvariant(L) &&
1088 "Base value is not loop invariant!");
1089 }
1090
1091 // We now have a whole bunch of uses of like-strided induction variables, but
1092 // they might all have different bases. We want to emit one PHI node for this
1093 // stride which we fold as many common expressions (between the IVs) into as
1094 // possible. Start by identifying the common expressions in the base values
1095 // for the strides (e.g. if we have "A+C+B" and "A+B+D" as our bases, find
1096 // "A+B"), emit it to the preheader, then remove the expression from the
1097 // UsersToProcess base values.
1098 const SCEV *CommonExprs =
1099 RemoveCommonExpressionsFromUseBases(UsersToProcess, SE, L, TLI);
1100
1101 // Next, figure out what we can represent in the immediate fields of
1102 // instructions. If we can represent anything there, move it to the imm
1103 // fields of the BasedUsers. We do this so that it increases the commonality
1104 // of the remaining uses.
1105 unsigned NumPHI = 0;
1106 bool HasAddress = false;
1107 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1108 // If the user is not in the current loop, this means it is using the exit
1109 // value of the IV. Do not put anything in the base, make sure it's all in
1110 // the immediate field to allow as much factoring as possible.
1111 if (!L->contains(UsersToProcess[i].Inst)) {
1112 UsersToProcess[i].Imm = SE->getAddExpr(UsersToProcess[i].Imm,
1113 UsersToProcess[i].Base);
1114 UsersToProcess[i].Base =
1115 SE->getIntegerSCEV(0, UsersToProcess[i].Base->getType());
1116 } else {
1117 // Not all uses are outside the loop.
1118 AllUsesAreOutsideLoop = false;
1119
1120 // Addressing modes can be folded into loads and stores. Be careful that
1121 // the store is through the expression, not of the expression though.
1122 bool isPHI = false;
1123 bool isAddress = isAddressUse(UsersToProcess[i].Inst,
1124 UsersToProcess[i].OperandValToReplace);
1125 if (isa(UsersToProcess[i].Inst)) {
1126 isPHI = true;
1127 ++NumPHI;
1128 }
1129
1130 if (isAddress)
1131 HasAddress = true;
1132
1133 // If this use isn't an address, then not all uses are addresses.
1134 if (!isAddress && !isPHI)
1135 AllUsesAreAddresses = false;
1136
1137 MoveImmediateValues(TLI, UsersToProcess[i].Inst, UsersToProcess[i].Base,
1138 UsersToProcess[i].Imm, isAddress, L, SE);
1139 }
1140 }
1141
1142 // If one of the use is a PHI node and all other uses are addresses, still
1143 // allow iv reuse. Essentially we are trading one constant multiplication
1144 // for one fewer iv.
1145 if (NumPHI > 1)
1146 AllUsesAreAddresses = false;
1147
1148 // There are no in-loop address uses.
1149 if (AllUsesAreAddresses && (!HasAddress && !AllUsesAreOutsideLoop))
1150 AllUsesAreAddresses = false;
1151
1152 return CommonExprs;
1153 }
1154
1155 /// ShouldUseFullStrengthReductionMode - Test whether full strength-reduction
1156 /// is valid and profitable for the given set of users of a stride. In
1157 /// full strength-reduction mode, all addresses at the current stride are
1158 /// strength-reduced all the way down to pointer arithmetic.
1159 ///
1160 bool LoopStrengthReduce::ShouldUseFullStrengthReductionMode(
1161 const std::vector &UsersToProcess,
1162 const Loop *L,
1163 bool AllUsesAreAddresses,
1164 const SCEV *Stride) {
1165 if (!EnableFullLSRMode)
1166 return false;
1167
1168 // The heuristics below aim to avoid increasing register pressure, but
1169 // fully strength-reducing all the addresses increases the number of
1170 // add instructions, so don't do this when optimizing for size.
1171 // TODO: If the loop is large, the savings due to simpler addresses
1172 // may oughtweight the costs of the extra increment instructions.
1173 if (L->getHeader()->getParent()->hasFnAttr(Attribute::OptimizeForSize))
1174 return false;
1175
1176 // TODO: For now, don't do full strength reduction if there could
1177 // potentially be greater-stride multiples of the current stride
1178 // which could reuse the current stride IV.
1179 if (IU->StrideOrder.back() != Stride)
1180 return false;
1181
1182 // Iterate through the uses to find conditions that automatically rule out
1183 // full-lsr mode.
1184 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ) {
1185 const SCEV *Base = UsersToProcess[i].Base;
1186 const SCEV *Imm = UsersToProcess[i].Imm;
1187 // If any users have a loop-variant component, they can't be fully
1188 // strength-reduced.
1189 if (Imm && !Imm->isLoopInvariant(L))
1190 return false;
1191 // If there are to users with the same base and the difference between
1192 // the two Imm values can't be folded into the address, full
1193 // strength reduction would increase register pressure.
1194 do {
1195 const SCEV *CurImm = UsersToProcess[i].Imm;
1196 if ((CurImm || Imm) && CurImm != Imm) {
1197 if (!CurImm) CurImm = SE->getIntegerSCEV(0, Stride->getType());
1198 if (!Imm) Imm = SE->getIntegerSCEV(0, Stride->getType());
1199 const Instruction *Inst = UsersToProcess[i].Inst;
1200 const Type *AccessTy = getAccessType(Inst);
1201 const SCEV *Diff = SE->getMinusSCEV(UsersToProcess[i].Imm, Imm);
1202 if (!Diff->isZero() &&
1203 (!AllUsesAreAddresses ||
1204 !fitsInAddressMode(Diff, AccessTy, TLI, /*HasBaseReg=*/true)))
1205 return false;
1206 }
1207 } while (++i != e && Base == UsersToProcess[i].Base);
1208 }
1209
1210 // If there's exactly one user in this stride, fully strength-reducing it
1211 // won't increase register pressure. If it's starting from a non-zero base,
1212 // it'll be simpler this way.
1213 if (UsersToProcess.size() == 1 && !UsersToProcess[0].Base->isZero())
1214 return true;
1215
1216 // Otherwise, if there are any users in this stride that don't require
1217 // a register for their base, full strength-reduction will increase
1218 // register pressure.
1219 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
1220 if (UsersToProcess[i].Base->isZero())
1221 return false;
1222
1223 // Otherwise, go for it.
1224 return true;
1225 }
1226
1227 /// InsertAffinePhi Create and insert a PHI node for an induction variable
1228 /// with the specified start and step values in the specified loop.
1229 ///
1230 /// If NegateStride is true, the stride should be negated by using a
1231 /// subtract instead of an add.
1232 ///
1233 /// Return the created phi node.
1234 ///
1235 static PHINode *InsertAffinePhi(const SCEV *Start, const SCEV *Step,
1236 Instruction *IVIncInsertPt,
1237 const Loop *L,
1238 SCEVExpander &Rewriter) {
1239 assert(Start->isLoopInvariant(L) && "New PHI start is not loop invariant!");
1240 assert(Step->isLoopInvariant(L) && "New PHI stride is not loop invariant!");
1241
1242 BasicBlock *Header = L->getHeader();
1243 BasicBlock *Preheader = L->getLoopPreheader();
1244 BasicBlock *LatchBlock = L->getLoopLatch();
1245 const Type *Ty = Start->getType();
1246 Ty = Rewriter.SE.getEffectiveSCEVType(Ty);
1247
1248 PHINode *PN = PHINode::Create(Ty, "lsr.iv", Header->begin());
1249 PN->addIncoming(Rewriter.expandCodeFor(Start, Ty, Preheader->getTerminator()),
1250 Preheader);
1251
1252 // If the stride is negative, insert a sub instead of an add for the
1253 // increment.
1254 bool isNegative = isNonConstantNegative(Step);
1255 const SCEV *IncAmount = Step;
1256 if (isNegative)
1257 IncAmount = Rewriter.SE.getNegativeSCEV(Step);
1258
1259 // Insert an add instruction right before the terminator corresponding
1260 // to the back-edge or just before the only use. The location is determined
1261 // by the caller and passed in as IVIncInsertPt.
1262 Value *StepV = Rewriter.expandCodeFor(IncAmount, Ty,
1263 Preheader->getTerminator());
1264 Instruction *IncV;
1265 if (isNegative) {
1266 IncV = BinaryOperator::CreateSub(PN, StepV, "lsr.iv.next",
1267 IVIncInsertPt);
1268 } else {
1269 IncV = BinaryOperator::CreateAdd(PN, StepV, "lsr.iv.next",
1270 IVIncInsertPt);
1271 }
1272 if (!isa(StepV)) ++NumVariable;
1273
1274 PN->addIncoming(IncV, LatchBlock);
1275
1276 ++NumInserted;
1277 return PN;
1278 }
1279
1280 static void SortUsersToProcess(std::vector &UsersToProcess) {
1281 // We want to emit code for users inside the loop first. To do this, we
1282 // rearrange BasedUser so that the entries at the end have
1283 // isUseOfPostIncrementedValue = false, because we pop off the end of the
1284 // vector (so we handle them first).
1285 std::partition(UsersToProcess.begin(), UsersToProcess.end(),
1286 PartitionByIsUseOfPostIncrementedValue);
1287
1288 // Sort this by base, so that things with the same base are handled
1289 // together. By partitioning first and stable-sorting later, we are
1290 // guaranteed that within each base we will pop off users from within the
1291 // loop before users outside of the loop with a particular base.
1292 //
1293 // We would like to use stable_sort here, but we can't. The problem is that
1294 // const SCEV *'s don't have a deterministic ordering w.r.t to each other, so
1295 // we don't have anything to do a '<' comparison on. Because we think the
1296 // number of uses is small, do a horrible bubble sort which just relies on
1297 // ==.
1298 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1299 // Get a base value.
1300 const SCEV *Base = UsersToProcess[i].Base;
1301
1302 // Compact everything with this base to be consecutive with this one.
1303 for (unsigned j = i+1; j != e; ++j) {
1304 if (UsersToProcess[j].Base == Base) {
1305 std::swap(UsersToProcess[i+1], UsersToProcess[j]);
1306 ++i;
1307 }
1308 }
1309 }
1310 }
1311
1312 /// PrepareToStrengthReduceFully - Prepare to fully strength-reduce
1313 /// UsersToProcess, meaning lowering addresses all the way down to direct
1314 /// pointer arithmetic.
1315 ///
1316 void
1317 LoopStrengthReduce::PrepareToStrengthReduceFully(
1318 std::vector &UsersToProcess,
1319 const SCEV *Stride,
1320 const SCEV *CommonExprs,
1321 const Loop *L,
1322 SCEVExpander &PreheaderRewriter) {
1323 DEBUG(dbgs() << " Fully reducing all users\n");
1324
1325 // Rewrite the UsersToProcess records, creating a separate PHI for each
1326 // unique Base value.
1327 Instruction *IVIncInsertPt = L->getLoopLatch()->getTerminator();
1328 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ) {
1329 // TODO: The uses are grouped by base, but not sorted. We arbitrarily
1330 // pick the first Imm value here to start with, and adjust it for the
1331 // other uses.
1332 const SCEV *Imm = UsersToProcess[i].Imm;
1333 const SCEV *Base = UsersToProcess[i].Base;
1334 const SCEV *Start = SE->getAddExpr(CommonExprs, Base, Imm);
1335 PHINode *Phi = InsertAffinePhi(Start, Stride, IVIncInsertPt, L,
1336 PreheaderRewriter);
1337 // Loop over all the users with the same base.
1338 do {
1339 UsersToProcess[i].Base = SE->getIntegerSCEV(0, Stride->getType());
1340 UsersToProcess[i].Imm = SE->getMinusSCEV(UsersToProcess[i].Imm, Imm);
1341 UsersToProcess[i].Phi = Phi;
1342 assert(UsersToProcess[i].Imm->isLoopInvariant(L) &&
1343 "ShouldUseFullStrengthReductionMode should reject this!");
1344 } while (++i != e && Base == UsersToProcess[i].Base);
1345 }
1346 }
1347
1348 /// FindIVIncInsertPt - Return the location to insert the increment instruction.
1349 /// If the only use if a use of postinc value, (must be the loop termination
1350 /// condition), then insert it just before the use.
1351 static Instruction *FindIVIncInsertPt(std::vector &UsersToProcess,
1352 const Loop *L) {
1353 if (UsersToProcess.size() == 1 &&
1354 UsersToProcess[0].isUseOfPostIncrementedValue &&
1355 L->contains(UsersToProcess[0].Inst))
1356 return UsersToProcess[0].Inst;
1357 return L->getLoopLatch()->getTerminator();
1358 }
1359
1360 /// PrepareToStrengthReduceWithNewPhi - Insert a new induction variable for the
1361 /// given users to share.
1362 ///
1363 void
1364 LoopStrengthReduce::PrepareToStrengthReduceWithNewPhi(
1365 std::vector &UsersToProcess,
1366 const SCEV *Stride,
1367 const SCEV *CommonExprs,
1368 Value *CommonBaseV,
1369 Instruction *IVIncInsertPt,
1370 const Loop *L,
1371 SCEVExpander &PreheaderRewriter) {
1372 DEBUG(dbgs() << " Inserting new PHI:\n");
1373
1374 PHINode *Phi = InsertAffinePhi(SE->getUnknown(CommonBaseV),
1375 Stride, IVIncInsertPt, L,
1376 PreheaderRewriter);
1377
1378 // Remember this in case a later stride is multiple of this.
1379 IVsByStride[Stride].addIV(Stride, CommonExprs, Phi);
1380
1381 // All the users will share this new IV.
1382 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
1383 UsersToProcess[i].Phi = Phi;
1384
1385 DEBUG(dbgs() << " IV=");
1386 DEBUG(WriteAsOperand(dbgs(), Phi, /*PrintType=*/false));
1387 DEBUG(dbgs() << "\n");
1388 }
1389
1390 /// PrepareToStrengthReduceFromSmallerStride - Prepare for the given users to
1391 /// reuse an induction variable with a stride that is a factor of the current
1392 /// induction variable.
1393 ///
1394 void
1395 LoopStrengthReduce::PrepareToStrengthReduceFromSmallerStride(
1396 std::vector &UsersToProcess,
1397 Value *CommonBaseV,
1398 const IVExpr &ReuseIV,
1399 Instruction *PreInsertPt) {
1400 DEBUG(dbgs() << " Rewriting in terms of existing IV of STRIDE "
1401 << *ReuseIV.Stride << " and BASE " << *ReuseIV.Base << "\n");
1402
1403 // All the users will share the reused IV.
1404 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
1405 UsersToProcess[i].Phi = ReuseIV.PHI;
1406
1407 Constant *C = dyn_cast(CommonBaseV);
1408 if (C &&
1409 (!C->isNullValue() &&
1410 !fitsInAddressMode(SE->getUnknown(CommonBaseV), CommonBaseV->getType(),
1411 TLI, false)))
1412 // We want the common base emitted into the preheader! This is just
1413 // using cast as a copy so BitCast (no-op cast) is appropriate
1414 CommonBaseV = new BitCastInst(CommonBaseV, CommonBaseV->getType(),
1415 "commonbase", PreInsertPt);
1416 }
1417
1418 static bool IsImmFoldedIntoAddrMode(GlobalValue *GV, int64_t Offset,
1419 const Type *AccessTy,
1420 std::vector &UsersToProcess,
1421 const TargetLowering *TLI) {
1422 SmallVector AddrModeInsts;
1423 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1424 if (UsersToProcess[i].isUseOfPostIncrementedValue)
1425 continue;
1426 ExtAddrMode AddrMode =
1427 AddressingModeMatcher::Match(UsersToProcess[i].OperandValToReplace,
1428 AccessTy, UsersToProcess[i].Inst,
1429 AddrModeInsts, *TLI);
1430 if (GV && GV != AddrMode.BaseGV)
1431 return false;
1432 if (Offset && !AddrMode.BaseOffs)
1433 // FIXME: How to accurate check it's immediate offset is folded.
1434 return false;
1435 AddrModeInsts.clear();
1436 }
1437 return true;
1438 }
1439
1440 /// StrengthReduceIVUsersOfStride - Strength reduce all of the users of a single
1441 /// stride of IV. All of the users may have different starting values, and this
1442 /// may not be the only stride.
1443 void
1444 LoopStrengthReduce::StrengthReduceIVUsersOfStride(const SCEV *Stride,
1445 IVUsersOfOneStride &Uses,
1446 Loop *L) {
1447 // If all the users are moved to another stride, then there is nothing to do.
1448 if (Uses.Users.empty())
14781449 return;
14791450
1480 for (size_t StrideIdx = 0, e = IU.StrideOrder.size();
1481 StrideIdx != e; ++StrideIdx) {
1451 // Keep track if every use in UsersToProcess is an address. If they all are,
1452 // we may be able to rewrite the entire collection of them in terms of a
1453 // smaller-stride IV.
1454 bool AllUsesAreAddresses = true;
1455
1456 // Keep track if every use of a single stride is outside the loop. If so,
1457 // we want to be more aggressive about reusing a smaller-stride IV; a
1458 // multiply outside the loop is better than another IV inside. Well, usually.
1459 bool AllUsesAreOutsideLoop = true;
1460
1461 // Transform our list of users and offsets to a bit more complex table. In
1462 // this new vector, each 'BasedUser' contains 'Base' the base of the
1463 // strided accessas well as the old information from Uses. We progressively
1464 // move information from the Base field to the Imm field, until we eventually
1465 // have the full access expression to rewrite the use.
1466 std::vector UsersToProcess;
1467 const SCEV *CommonExprs = CollectIVUsers(Stride, Uses, L, AllUsesAreAddresses,
1468 AllUsesAreOutsideLoop,
1469 UsersToProcess);
1470
1471 // Sort the UsersToProcess array so that users with common bases are
1472 // next to each other.
1473 SortUsersToProcess(UsersToProcess);
1474
1475 // If we managed to find some expressions in common, we'll need to carry
1476 // their value in a register and add it in for each use. This will take up
1477 // a register operand, which potentially restricts what stride values are
1478 // valid.
1479 bool HaveCommonExprs = !CommonExprs->isZero();
1480 const Type *ReplacedTy = CommonExprs->getType();
1481
1482 // If all uses are addresses, consider sinking the immediate part of the
1483 // common expression back into uses if they can fit in the immediate fields.
1484 if (TLI && HaveCommonExprs && AllUsesAreAddresses) {
1485 const SCEV *NewCommon = CommonExprs;
1486 const SCEV *Imm = SE->getIntegerSCEV(0, ReplacedTy);
1487 MoveImmediateValues(TLI, Type::getVoidTy(
1488 L->getLoopPreheader()->getContext()),
1489 NewCommon, Imm, true, L, SE);
1490 if (!Imm->isZero()) {
1491 bool DoSink = true;
1492
1493 // If the immediate part of the common expression is a GV, check if it's
1494 // possible to fold it into the target addressing mode.
1495 GlobalValue *GV = 0;
1496 if (const SCEVUnknown *SU = dyn_cast(Imm))
1497 GV = dyn_cast(SU->getValue());
1498 int64_t Offset = 0;
1499 if (const SCEVConstant *SC = dyn_cast(Imm))
1500 Offset = SC->getValue()->getSExtValue();
1501 if (GV || Offset)
1502 // Pass VoidTy as the AccessTy to be conservative, because
1503 // there could be multiple access types among all the uses.
1504 DoSink = IsImmFoldedIntoAddrMode(GV, Offset,
1505 Type::getVoidTy(L->getLoopPreheader()->getContext()),
1506 UsersToProcess, TLI);
1507
1508 if (DoSink) {
1509 DEBUG(dbgs() << " Sinking " << *Imm << " back down into uses\n");
1510 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
1511 UsersToProcess[i].Imm = SE->getAddExpr(UsersToProcess[i].Imm, Imm);
1512 CommonExprs = NewCommon;
1513 HaveCommonExprs = !CommonExprs->isZero();
1514 ++NumImmSunk;
1515 }
1516 }
1517 }
1518
1519 // Now that we know what we need to do, insert the PHI node itself.
1520 //
1521 DEBUG(dbgs() << "LSR: Examining IVs of TYPE " << *ReplacedTy << " of STRIDE "
1522 << *Stride << ":\n"
1523 << " Common base: " << *CommonExprs << "\n");
1524
1525 SCEVExpander Rewriter(*SE);
1526 SCEVExpander PreheaderRewriter(*SE);
1527
1528 BasicBlock *Preheader = L->getLoopPreheader();
1529 Instruction *PreInsertPt = Preheader->getTerminator();
1530 BasicBlock *LatchBlock = L->getLoopLatch();
1531 Instruction *IVIncInsertPt = LatchBlock->getTerminator();
1532
1533 Value *CommonBaseV = Constant::getNullValue(ReplacedTy);
1534
1535 const SCEV *RewriteFactor = SE->getIntegerSCEV(0, ReplacedTy);
1536 IVExpr ReuseIV(SE->getIntegerSCEV(0,
1537 Type::getInt32Ty(Preheader->getContext())),
1538 SE->getIntegerSCEV(0,
1539 Type::getInt32Ty(Preheader->getContext())),
1540 0);
1541
1542 // Choose a strength-reduction strategy and prepare for it by creating
1543 // the necessary PHIs and adjusting the bookkeeping.
1544 if (ShouldUseFullStrengthReductionMode(UsersToProcess, L,
1545 AllUsesAreAddresses, Stride)) {
1546 PrepareToStrengthReduceFully(UsersToProcess, Stride, CommonExprs, L,
1547 PreheaderRewriter);
1548 } else {
1549 // Emit the initial base value into the loop preheader.
1550 CommonBaseV = PreheaderRewriter.expandCodeFor(CommonExprs, ReplacedTy,
1551 PreInsertPt);
1552
1553 // If all uses are addresses, check if it is possible to reuse an IV. The
1554 // new IV must have a stride that is a multiple of the old stride; the
1555 // multiple must be a number that can be encoded in the scale field of the
1556 // target addressing mode; and we must have a valid instruction after this
1557 // substitution, including the immediate field, if any.
1558 RewriteFactor = CheckForIVReuse(HaveCommonExprs, AllUsesAreAddresses,
1559 AllUsesAreOutsideLoop,
1560 Stride, ReuseIV, ReplacedTy,
1561 UsersToProcess);
1562 if (!RewriteFactor->isZero())
1563 PrepareToStrengthReduceFromSmallerStride(UsersToProcess, CommonBaseV,
1564 ReuseIV, PreInsertPt);
1565 else {
1566 IVIncInsertPt = FindIVIncInsertPt(UsersToProcess, L);
1567 PrepareToStrengthReduceWithNewPhi(UsersToProcess, Stride, CommonExprs,
1568 CommonBaseV, IVIncInsertPt,
1569 L, PreheaderRewriter);
1570 }
1571 }
1572
1573 // Process all the users now, replacing their strided uses with
1574 // strength-reduced forms. This outer loop handles all bases, the inner
1575 // loop handles all users of a particular base.
1576 while (!UsersToProcess.empty()) {
1577 const SCEV *Base = UsersToProcess.back().Base;
1578 Instruction *Inst = UsersToProcess.back().Inst;
1579
1580 // Emit the code for Base into the preheader.
1581 Value *BaseV = 0;
1582 if (!Base->isZero()) {
1583 BaseV = PreheaderRewriter.expandCodeFor(Base, 0, PreInsertPt);
1584
1585 DEBUG(dbgs() << " INSERTING code for BASE = " << *Base << ":");
1586 if (BaseV->hasName())
1587 DEBUG(dbgs() << " Result value name = %" << BaseV->getName());
1588 DEBUG(dbgs() << "\n");
1589
1590 // If BaseV is a non-zero constant, make sure that it gets inserted into
1591 // the preheader, instead of being forward substituted into the uses. We
1592 // do this by forcing a BitCast (noop cast) to be inserted into the
1593 // preheader in this case.
1594 if (!fitsInAddressMode(Base, getAccessType(Inst), TLI, false) &&
1595 isa(BaseV)) {
1596 // We want this constant emitted into the preheader! This is just
1597 // using cast as a copy so BitCast (no-op cast) is appropriate
1598 BaseV = new BitCastInst(BaseV, BaseV->getType(), "preheaderinsert",
1599 PreInsertPt);
1600 }
1601 }
1602
1603 // Emit the code to add the immediate offset to the Phi value, just before
1604 // the instructions that we identified as using this stride and base.
1605 do {
1606 // FIXME: Use emitted users to emit other users.
1607 BasedUser &User = UsersToProcess.back();
1608
1609 DEBUG(dbgs() << " Examining ");
1610 if (User.isUseOfPostIncrementedValue)
1611 DEBUG(dbgs() << "postinc");
1612 else
1613 DEBUG(dbgs() << "preinc");
1614 DEBUG(dbgs() << " use ");
1615 DEBUG(WriteAsOperand(dbgs(), UsersToProcess.back().OperandValToReplace,
1616 /*PrintType=*/false));
1617 DEBUG(dbgs() << " in Inst: " << *User.Inst);
1618
1619 // If this instruction wants to use the post-incremented value, move it
1620 // after the post-inc and use its value instead of the PHI.
1621 Value *RewriteOp = User.Phi;
1622 if (User.isUseOfPostIncrementedValue) {
1623 RewriteOp = User.Phi->getIncomingValueForBlock(LatchBlock);
1624 // If this user is in the loop, make sure it is the last thing in the
1625 // loop to ensure it is dominated by the increment. In case it's the
1626 // only use of the iv, the increment instruction is already before the
1627 // use.
1628 if (L->contains(User.Inst) && User.Inst != IVIncInsertPt)
1629 User.Inst->moveBefore(IVIncInsertPt);
1630 }
1631
1632 const SCEV *RewriteExpr = SE->getUnknown(RewriteOp);
1633
1634 if (SE->getEffectiveSCEVType(RewriteOp->getType()) !=
1635 SE->getEffectiveSCEVType(ReplacedTy)) {
1636 assert(SE->getTypeSizeInBits(RewriteOp->getType()) >
1637 SE->getTypeSizeInBits(ReplacedTy) &&
1638 "Unexpected widening cast!");
1639 RewriteExpr = SE->getTruncateExpr(RewriteExpr, ReplacedTy);
1640 }
1641
1642 // If we had to insert new instructions for RewriteOp, we have to
1643 // consider that they may not have been able to end up immediately
1644 // next to RewriteOp, because non-PHI instructions may never precede
1645 // PHI instructions in a block. In this case, remember where the last
1646 // instruction was inserted so that if we're replacing a different
1647 // PHI node, we can use the later point to expand the final
1648 // RewriteExpr.
1649 Instruction *NewBasePt = dyn_cast(RewriteOp);
1650 if (RewriteOp == User.Phi) NewBasePt = 0;
1651
1652 // Clear the SCEVExpander's expression map so that we are guaranteed
1653 // to have the code emitted where we expect it.
1654 Rewriter.clear();
1655
1656 // If we are reusing the iv, then it must be multiplied by a constant
1657 // factor to take advantage of the addressing mode scale component.
1658 if (!RewriteFactor->isZero()) {
1659 // If we're reusing an IV with a nonzero base (currently this happens
1660 // only when all reuses are outside the loop) subtract that base here.
1661 // The base has been used to initialize the PHI node but we don't want
1662 // it here.
1663 if (!ReuseIV.Base->isZero()) {
1664 const SCEV *typedBase = ReuseIV.Base;
1665 if (SE->getEffectiveSCEVType(RewriteExpr->getType()) !=
1666 SE->getEffectiveSCEVType(ReuseIV.Base->getType())) {
1667 // It's possible the original IV is a larger type than the new IV,
1668 // in which case we have to truncate the Base. We checked in
1669 // RequiresTypeConversion that this is valid.
1670 assert(SE->getTypeSizeInBits(RewriteExpr->getType()) <
1671 SE->getTypeSizeInBits(ReuseIV.Base->getType()) &&
1672 "Unexpected lengthening conversion!");
1673 typedBase = SE->getTruncateExpr(ReuseIV.Base,
1674 RewriteExpr->getType());
1675 }
1676 RewriteExpr = SE->getMinusSCEV(RewriteExpr, typedBase);
1677 }
1678
1679 // Multiply old variable, with base removed, by new scale factor.
1680 RewriteExpr = SE->getMulExpr(RewriteFactor,
1681 RewriteExpr);
1682
1683 // The common base is emitted in the loop preheader. But since we
1684 // are reusing an IV, it has not been used to initialize the PHI node.
1685 // Add it to the expression used to rewrite the uses.
1686 // When this use is outside the loop, we earlier subtracted the
1687 // common base, and are adding it back here. Use the same expression
1688 // as before, rather than CommonBaseV, so DAGCombiner will zap it.
1689 if (!CommonExprs->isZero()) {
1690 if (L->contains(User.Inst))
1691 RewriteExpr = SE->getAddExpr(RewriteExpr,
1692 SE->getUnknown(CommonBaseV));
1693 else
1694 RewriteExpr = SE->getAddExpr(RewriteExpr, CommonExprs);
1695 }
1696 }
1697
1698 // Now that we know what we need to do, insert code before User for the
1699 // immediate and any loop-variant expressions.
1700 if (BaseV)
1701 // Add BaseV to the PHI value if needed.
1702 RewriteExpr = SE->getAddExpr(RewriteExpr, SE->getUnknown(BaseV));
1703
1704 User.RewriteInstructionToUseNewBase(RewriteExpr, NewBasePt,
1705 Rewriter, L, this,
1706 DeadInsts, SE);
1707
1708 // Mark old value we replaced as possibly dead, so that it is eliminated
1709 // if we just replaced the last use of that value.
1710 DeadInsts.push_back(User.OperandValToReplace);
1711
1712 UsersToProcess.pop_back();
1713 ++NumReduced;
1714
1715 // If there are any more users to process with the same base, process them
1716 // now. We sorted by base above, so we just have to check the last elt.
1717 } while (!UsersToProcess.empty() && UsersToProcess.back().Base == Base);
1718 // TODO: Next, find out which base index is the most common, pull it out.
1719 }
1720
1721 // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
1722 // different starting values, into different PHIs.
1723 }
1724
1725 void LoopStrengthReduce::StrengthReduceIVUsers(Loop *L) {
1726 // Note: this processes each stride/type pair individually. All users
1727 // passed into StrengthReduceIVUsersOfStride have the same type AND stride.
1728 // Also, note that we iterate over IVUsesByStride indirectly by using
1729 // StrideOrder. This extra layer of indirection makes the ordering of
1730 // strides deterministic - not dependent on map order.
1731 for (unsigned Stride = 0, e = IU->StrideOrder.size(); Stride != e; ++Stride) {
14821732 std::map::iterator SI =
1483 IU.IVUsesByStride.find(IU.StrideOrder[StrideIdx]);
1484 assert(SI != IU.IVUsesByStride.end() && "Stride doesn't exist!");
1485 if (!isa(SI->first))
1733 IU->IVUsesByStride.find(IU->StrideOrder[Stride]);
1734 assert(SI != IU->IVUsesByStride.end() && "Stride doesn't exist!");
1735 // FIXME: Generalize to non-affine IV's.
1736 if (!SI->first->isLoopInvariant(L))
14861737 continue;
1487
1488 for (ilist::iterator UI = SI->second->Users.begin(),
1489 E = SI->second->Users.end(); UI != E; /* empty */) {
1490 ilist::iterator CandidateUI = UI;
1491 ++UI;
1492 Instruction *ShadowUse = CandidateUI->getUser();
1493 const Type *DestTy = NULL;
1494
1495 /* If shadow use is a int->float cast then insert a second IV
1496 to eliminate this cast.
1497
1498 for (unsigned i = 0; i < n; ++i)
1499 foo((double)i);
1500
1501 is transformed into
1502
1503 double d = 0.0;
1504 for (unsigned i = 0; i < n; ++i, ++d)
1505 foo(d);
1506 */
1507 if (UIToFPInst *UCast = dyn_cast(CandidateUI->getUser()))
1508 DestTy = UCast->getDestTy();
1509 else if (SIToFPInst *SCast = dyn_cast(CandidateUI->getUser()))
1510 DestTy = SCast->getDestTy();
1511 if (!DestTy) continue;
1512
1513 if (TLI) {
1514 // If target does not support DestTy natively then do not apply
1515 // this transformation.
1516 EVT DVT = TLI->getValueType(DestTy);
1517 if (!TLI->isTypeLegal(DVT)) continue;
1518 }
1519
1520 PHINode *PH = dyn_cast(ShadowUse->getOperand(0));
1521 if (!PH) continue;
1522 if (PH->getNumIncomingValues() != 2) continue;
1523
1524 const Type *SrcTy = PH->getType();
1525 int Mantissa = DestTy->getFPMantissaWidth();
1526 if (Mantissa == -1) continue;
1527 if ((int)SE.getTypeSizeInBits(SrcTy) > Mantissa)
1528 continue;
1529
1530 unsigned Entry, Latch;
1531 if (PH->getIncomingBlock(0) == L->getLoopPreheader()) {
1532 Entry = 0;
1533 Latch = 1;
1534 } else {
1535 Entry = 1;
1536 Latch = 0;
1537 }
1538
1539 ConstantInt *Init = dyn_cast(PH->getIncomingValue(Entry));
1540 if (!Init) continue;
1541 Constant *NewInit = ConstantFP::get(DestTy, Init->getZExtValue());
1542
1543 BinaryOperator *Incr =
1544 dyn_cast(PH->getIncomingValue(Latch));
1545 if (!Incr) continue;
1546 if (Incr->getOpcode() != Instruction::Add
1547 && Incr->getOpcode() != Instruction::Sub)
1548 continue;
1549
1550 /* Initialize new IV, double d = 0.0 in above example. */
1551 ConstantInt *C = NULL;
1552 if (Incr->getOperand(0) == PH)
1553 C = dyn_cast(Incr->getOperand(1));
1554 else if (Incr->getOperand(1) == PH)
1555 C = dyn_cast(Incr->getOperand(0));
1556 else
1557 continue;
1558
1559 if (!C) continue;
1560
1561 // Ignore negative constants, as the code below doesn't handle them
1562 // correctly. TODO: Remove this restriction.
1563 if (!C->getValue().isStrictlyPositive()) continue;
1564
1565 /* Add new PHINode. */
1566 PHINode *NewPH = PHINode::Create(DestTy, "IV.S.", PH);
1567
1568 /* create new increment. '++d' in above example. */
1569 Constant *CFP = ConstantFP::get(DestTy, C->getZExtValue());
1570 BinaryOperator *NewIncr =
1571 BinaryOperator::Create(Incr->getOpcode() == Instruction::Add ?
1572 Instruction::FAdd : Instruction::FSub,
1573 NewPH, CFP, "IV.S.next.", Incr);
1574
1575 NewPH->addIncoming(NewInit, PH->getIncomingBlock(Entry));
1576 NewPH->addIncoming(NewIncr, PH->getIncomingBlock(Latch));
1577
1578 /* Remove cast operation */
1579 ShadowUse->replaceAllUsesWith(NewPH);
1580 ShadowUse->eraseFromParent();
1581 break;
1582 }
1738 StrengthReduceIVUsersOfStride(SI->first, *SI->second, L);
15831739 }
15841740 }
15851741
15861742 /// FindIVUserForCond - If Cond has an operand that is an expression of an IV,
15871743 /// set the IV user and stride information and return true, otherwise return
15881744 /// false.
1589 bool LSRInstance::FindIVUserForCond(ICmpInst *Cond,
1590 IVStrideUse *&CondUse,
1591 const SCEV* &CondStride) {
1592 for (unsigned StrideIdx = 0, e = IU.StrideOrder.size();
1593 StrideIdx != e && !CondUse; ++StrideIdx) {
1745 bool LoopStrengthReduce::FindIVUserForCond(ICmpInst *Cond,
1746 IVStrideUse *&CondUse,
1747 const SCEV* &CondStride) {
1748 for (unsigned Stride = 0, e = IU->StrideOrder.size();
1749 Stride != e && !CondUse; ++Stride) {
15941750 std::map::iterator SI =
1595 IU.IVUsesByStride.find(IU.StrideOrder[StrideIdx]);
1596 assert(SI != IU.IVUsesByStride.end() && "Stride doesn't exist!");
1751 IU->IVUsesByStride.find(IU->StrideOrder[Stride]);
1752 assert(SI != IU->IVUsesByStride.end() && "Stride doesn't exist!");
15971753
15981754 for (ilist::iterator UI = SI->second->Users.begin(),
15991755 E = SI->second->Users.end(); UI != E; ++UI)
16071763 }
16081764 }
16091765 return false;
1766 }
1767
1768 namespace {
1769 // Constant strides come first which in turns are sorted by their absolute
1770 // values. If absolute values are the same, then positive strides comes first.
1771 // e.g.
1772 // 4, -1, X, 1, 2 ==> 1, -1, 2, 4, X
1773 struct StrideCompare {
1774 const ScalarEvolution *SE;
1775 explicit StrideCompare(const ScalarEvolution *se) : SE(se) {}
1776
1777 bool operator()(const SCEV *LHS, const SCEV *RHS) {
1778 const SCEVConstant *LHSC = dyn_cast(LHS);
1779 const SCEVConstant *RHSC = dyn_cast(RHS);
1780 if (LHSC && RHSC) {
1781 int64_t LV = LHSC->getValue()->getSExtValue();
1782 int64_t RV = RHSC->getValue()->getSExtValue();
1783 uint64_t ALV = (LV < 0) ? -LV : LV;
1784 uint64_t ARV = (RV < 0) ? -RV : RV;
1785 if (ALV == ARV) {
1786 if (LV != RV)
1787 return LV > RV;
1788 } else {
1789 return ALV < ARV;
1790 }
1791
1792 // If it's the same value but different type, sort by bit width so
1793 // that we emit larger induction variables before smaller
1794 // ones, letting the smaller be re-written in terms of larger ones.
1795 return SE->getTypeSizeInBits(RHS->getType()) <
1796 SE->getTypeSizeInBits(LHS->getType());
1797 }
1798 return LHSC && !RHSC;
1799 }
1800 };
1801 }
1802
1803 /// ChangeCompareStride - If a loop termination compare instruction is the
1804 /// only use of its stride, and the compaison is against a constant value,
1805 /// try eliminate the stride by moving the compare instruction to another
1806 /// stride and change its constant operand accordingly. e.g.
1807 ///
1808 /// loop:
1809 /// ...
1810 /// v1 = v1 + 3
1811 /// v2 = v2 + 1
1812 /// if (v2 < 10) goto loop
1813 /// =>
1814 /// loop:
1815 /// ...
1816 /// v1 = v1 + 3
1817 /// if (v1 < 30) goto loop
1818 ICmpInst *LoopStrengthReduce::ChangeCompareStride(Loop *L, ICmpInst *Cond,
1819 IVStrideUse* &CondUse,
1820 const SCEV* &CondStride,
1821 bool PostPass) {
1822 // If there's only one stride in the loop, there's nothing to do here.
1823 if (IU->StrideOrder.size() < 2)
1824 return Cond;
1825 // If there are other users of the condition's stride, don't bother
1826 // trying to change the condition because the stride will still
1827 // remain.
1828 std::map::iterator I =
1829 IU->IVUsesByStride.find(CondStride);
1830 if (I == IU->IVUsesByStride.end())
1831 return Cond;
1832 if (I->second->Users.size() > 1) {
1833 for (ilist::iterator II = I->second->Users.begin(),
1834 EE = I->second->Users.end(); II != EE; ++II) {
1835 if (II->getUser() == Cond)
1836 continue;
1837 if (!isInstructionTriviallyDead(II->getUser()))
1838 return Cond;
1839 }
1840 }
1841 // Only handle constant strides for now.
1842 const SCEVConstant *SC = dyn_cast(CondStride);
1843 if (!SC) return Cond;
1844
1845 ICmpInst::Predicate Predicate = Cond->getPredicate();
1846 int64_t CmpSSInt = SC->getValue()->getSExtValue();
1847 unsigned BitWidth = SE->getTypeSizeInBits(CondStride->getType());
1848 uint64_t SignBit = 1ULL << (BitWidth-1);
1849 const Type *CmpTy = Cond->getOperand(0)->getType();
1850 const Type *NewCmpTy = NULL;
1851 unsigned TyBits = SE->getTypeSizeInBits(CmpTy);
1852 unsigned NewTyBits = 0;
1853 const SCEV *NewStride = NULL;
1854 Value *NewCmpLHS = NULL;
1855 Value *NewCmpRHS = NULL;
1856 int64_t Scale = 1;
1857 const SCEV *NewOffset = SE->getIntegerSCEV(0, CmpTy);
1858
1859 if (ConstantInt *C = dyn_cast(Cond->getOperand(1))) {
1860 int64_t CmpVal = C->getValue().getSExtValue();
1861
1862 // Check the relevant induction variable for conformance to
1863 // the pattern.
1864 const SCEV *IV = SE->getSCEV(Cond->getOperand(0));
1865 const SCEVAddRecExpr *AR = dyn_cast(IV);
1866 if (!AR || !AR->isAffine())
1867 return Cond;
1868
1869 const SCEVConstant *StartC = dyn_cast(AR->getStart());
1870 // Check stride constant and the comparision constant signs to detect
1871 // overflow.
1872 if (StartC) {
1873 if ((StartC->getValue()->getSExtValue() < CmpVal && CmpSSInt < 0) ||
1874 (StartC->getValue()->getSExtValue() > CmpVal && CmpSSInt > 0))
1875 return Cond;
1876 } else {
1877 // More restrictive check for the other cases.
1878 if ((CmpVal & SignBit) != (CmpSSInt & SignBit))
1879 return Cond;
1880 }
1881
1882 // Look for a suitable stride / iv as replacement.
1883 for (unsigned i = 0, e = IU->StrideOrder.size(); i != e; ++i) {
1884 std::map::iterator SI =
1885 IU->IVUsesByStride.find(IU->StrideOrder[i]);
1886 if (!isa(SI->first) || SI->second->Users.empty())
1887 continue;
1888 int64_t SSInt = cast(SI->first)->getValue()->getSExtValue();
1889 if (SSInt == CmpSSInt ||
1890 abs64(SSInt) < abs64(CmpSSInt) ||
1891 (SSInt % CmpSSInt) != 0)
1892 continue;
1893
1894 Scale = SSInt / CmpSSInt;
1895 int64_t NewCmpVal = CmpVal * Scale;
1896
1897 // If old icmp value fits in icmp immediate field, but the new one doesn't
1898 // try something else.
1899 if (TLI &&
1900 TLI->isLegalICmpImmediate(CmpVal) &&
1901 !TLI->isLegalICmpImmediate(NewCmpVal))
1902 continue;
1903
1904 APInt Mul = APInt(BitWidth*2, CmpVal, true);
1905 Mul = Mul * APInt(BitWidth*2, Scale, true);
1906 // Check for overflow.
1907 if (!Mul.isSignedIntN(BitWidth))
1908 continue;
1909 // Check for overflow in the stride's type too.
1910 if (!Mul.isSignedIntN(SE->getTypeSizeInBits(SI->first->getType())))
1911 continue;
1912
1913 // Watch out for overflow.
1914 if (ICmpInst::isSigned(Predicate) &&
1915 (CmpVal & SignBit) != (NewCmpVal & SignBit))
1916 continue;
1917
1918 // Pick the best iv to use trying to avoid a cast.
1919 NewCmpLHS = NULL;
1920 for (ilist::iterator UI = SI->second->Users.begin(),
1921 E = SI->second->Users.end(); UI != E; ++UI) {
1922 Value *Op = UI->getOperandValToReplace();
1923
1924 // If the IVStrideUse implies a cast, check for an actual cast which
1925 // can be used to find the original IV expression.
1926 if (SE->getEffectiveSCEVType(Op->getType()) !=
1927 SE->getEffectiveSCEVType(SI->first->getType())) {
1928 CastInst *CI = dyn_cast(Op);
1929 // If it's not a simple cast, it's complicated.
1930 if (!CI)
1931 continue;
1932 // If it's a cast from a type other than the stride type,
1933 // it's complicated.
1934 if (CI->getOperand(0)->getType() != SI->first->getType())
1935 continue;
1936 // Ok, we found the IV expression in the stride's type.
1937 Op = CI->getOperand(0);
1938 }
1939
1940 NewCmpLHS = Op;
1941 if (NewCmpLHS->getType() == CmpTy)
1942 break;
1943 }
1944 if (!NewCmpLHS)
1945 continue;
1946
1947 NewCmpTy = NewCmpLHS->getType();
1948 NewTyBits = SE->getTypeSizeInBits(NewCmpTy);
1949 const Type *NewCmpIntTy = IntegerType::get(Cond->getContext(), NewTyBits);
1950 if (RequiresTypeConversion(NewCmpTy, CmpTy)) {
1951 // Check if it is possible to rewrite it using
1952 // an iv / stride of a smaller integer type.
1953 unsigned Bits = NewTyBits;
1954 if (ICmpInst::isSigned(Predicate))
1955 --Bits;
1956 uint64_t Mask = (1ULL << Bits) - 1;
1957 if (((uint64_t)NewCmpVal & Mask) != (uint64_t)NewCmpVal)
1958 continue;
1959 }
1960
1961 // Don't rewrite if use offset is non-constant and the new type is
1962 // of a different type.
1963 // FIXME: too conservative?
1964 if (NewTyBits != TyBits && !isa(CondUse->getOffset()))
1965 continue;
1966
1967 if (!PostPass) {
1968 bool AllUsesAreAddresses = true;
1969 bool AllUsesAreOutsideLoop = true;
1970 std::vector UsersToProcess;
1971 const SCEV *CommonExprs = CollectIVUsers(SI->first, *SI->second, L,
1972 AllUsesAreAddresses,
1973 AllUsesAreOutsideLoop,
1974 UsersToProcess);
1975 // Avoid rewriting the compare instruction with an iv of new stride
1976 // if it's likely the new stride uses will be rewritten using the
1977 // stride of the compare instruction.
1978 if (AllUsesAreAddresses &&
1979 ValidScale(!CommonExprs->isZero(), Scale, UsersToProcess))
1980 continue;
1981 }
1982
1983 // Avoid rewriting the compare instruction with an iv which has
1984 // implicit extension or truncation built into it.
1985 // TODO: This is over-conservative.
1986 if (SE->getTypeSizeInBits(CondUse->getOffset()->getType()) != TyBits)
1987 continue;
1988
1989 // If scale is negative, use swapped predicate unless it's testing
1990 // for equality.
1991 if (Scale < 0 && !Cond->isEquality())
1992 Predicate = ICmpInst::getSwappedPredicate(Predicate);
1993
1994 NewStride = IU->StrideOrder[i];
1995 if (!isa(NewCmpTy))
1996 NewCmpRHS = ConstantInt::get(NewCmpTy, NewCmpVal);
1997 else {
1998 Constant *CI = ConstantInt::get(NewCmpIntTy, NewCmpVal);
1999 NewCmpRHS = ConstantExpr::getIntToPtr(CI, NewCmpTy);
2000 }
2001 NewOffset = TyBits == NewTyBits
2002 ? SE->getMulExpr(CondUse->getOffset(),
2003 SE->getConstant(CmpTy, Scale))
2004 : SE->getConstant(NewCmpIntTy,
2005 cast(CondUse->getOffset())->getValue()
2006 ->getSExtValue()*Scale);
2007 break;
2008 }
2009 }
2010
2011 // Forgo this transformation if it the increment happens to be
2012 // unfortunately positioned after the condition, and the condition
2013 // has multiple uses which prevent it from being moved immediately
2014 // before the branch. See
2015 // test/Transforms/LoopStrengthReduce/change-compare-stride-trickiness-*.ll
2016 // for an example of this situation.
2017 if (!Cond->hasOneUse()) {
2018 for (BasicBlock::iterator I = Cond, E = Cond->getParent()->end();
2019 I != E; ++I)
2020 if (I == NewCmpLHS)
2021 return Cond;
2022 }
2023
2024 if (NewCmpRHS) {
2025 // Create a new compare instruction using new stride / iv.
2026 ICmpInst *OldCond = Cond;
2027 // Insert new compare instruction.
2028 Cond = new ICmpInst(OldCond, Predicate, NewCmpLHS, NewCmpRHS,
2029 L->getHeader()->getName() + ".termcond");
2030
2031 DEBUG(dbgs() << " Change compare stride in Inst " << *OldCond);
2032 DEBUG(dbgs() << " to " << *Cond << '\n');
2033
2034 // Remove the old compare instruction. The old indvar is probably dead too.
2035 DeadInsts.push_back(CondUse->getOperandValToReplace());
2036 OldCond->replaceAllUsesWith(Cond);
2037 OldCond->eraseFromParent();
2038
2039 IU->IVUsesByStride[NewStride]->addUser(NewOffset, Cond, NewCmpLHS);
2040 CondUse = &IU->IVUsesByStride[NewStride]->Users.back();
2041 CondStride = NewStride;
2042 ++NumEliminated;
2043 Changed = true;
2044 }
2045
2046 return Cond;
16102047 }
16112048
16122049 /// OptimizeMax - Rewrite the loop's terminating condition if it uses
16492086 /// are designed around them. The most obvious example of this is the
16502087 /// LoopInfo analysis, which doesn't remember trip count values. It
16512088 /// expects to be able to rediscover the trip count each time it is
1652 /// needed, and it does this using a simple analysis that only succeeds if
2089 /// needed, and it does this using a simple analyis that only succeeds if
16532090 /// the loop has a canonical induction variable.
16542091 ///
16552092 /// However, when it comes time to generate code, the maximum operation
16592096 /// rewriting their conditions from ICMP_NE back to ICMP_SLT, and deleting
16602097 /// the instructions for the maximum computation.
16612098 ///
1662 ICmpInst *LSRInstance::OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse) {
2099 ICmpInst *LoopStrengthReduce::OptimizeMax(Loop *L, ICmpInst *Cond,
2100 IVStrideUse* &CondUse) {
16632101 // Check that the loop matches the pattern we're looking for.
16642102 if (Cond->getPredicate() != CmpInst::ICMP_EQ &&
16652103 Cond->getPredicate() != CmpInst::ICMP_NE)
16682106 SelectInst *Sel = dyn_cast(Cond->getOperand(1));
16692107 if (!Sel || !Sel->hasOneUse()) return Cond;
16702108
1671 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
2109 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
16722110 if (isa(BackedgeTakenCount))
16732111 return Cond;
1674 const SCEV *One = SE.getIntegerSCEV(1, BackedgeTakenCount->getType());
2112 const SCEV *One = SE->getIntegerSCEV(1, BackedgeTakenCount->getType());
16752113
16762114 // Add one to the backedge-taken count to get the trip count.
1677<