LLVM 24.0.0git
IVDescriptors.cpp
Go to the documentation of this file.
1//===- llvm/Analysis/IVDescriptors.cpp - IndVar Descriptors -----*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file "describes" induction and recurrence variables.
10//
11//===----------------------------------------------------------------------===//
12
20#include "llvm/IR/Dominators.h"
23#include "llvm/IR/ValueHandle.h"
24#include "llvm/Support/Debug.h"
26
27using namespace llvm;
28using namespace llvm::PatternMatch;
29using namespace llvm::SCEVPatternMatch;
30
31#define DEBUG_TYPE "iv-descriptors"
32
35 for (const Use &Use : I->operands())
36 if (!Set.count(dyn_cast<Instruction>(Use)))
37 return false;
38 return true;
39}
40
42 switch (Kind) {
43 default:
44 break;
46 case RecurKind::Sub:
47 case RecurKind::Add:
48 case RecurKind::Mul:
49 case RecurKind::Or:
50 case RecurKind::And:
51 case RecurKind::Xor:
52 case RecurKind::SMax:
53 case RecurKind::SMin:
54 case RecurKind::UMax:
55 case RecurKind::UMin:
59 return true;
60 }
61 return false;
62}
63
67
68/// Determines if Phi may have been type-promoted. If Phi has a single user
69/// that ANDs the Phi with a type mask, return the user. RT is updated to
70/// account for the narrower bit width represented by the mask, and the AND
71/// instruction is added to CI.
75 if (!Phi->hasOneUse())
76 return Phi;
77
78 const APInt *M = nullptr;
79 Instruction *I, *J = cast<Instruction>(Phi->use_begin()->getUser());
80
81 // Matches either I & 2^x-1 or 2^x-1 & I. If we find a match, we update RT
82 // with a new integer type of the corresponding bit width.
83 if (match(J, m_And(m_Instruction(I), m_APInt(M)))) {
84 int32_t Bits = (*M + 1).exactLogBase2();
85 if (Bits > 0) {
86 RT = IntegerType::get(Phi->getContext(), Bits);
87 Visited.insert(Phi);
88 CI.insert(J);
89 return J;
90 }
91 }
92 return Phi;
93}
94
98
99/// Compute the minimal bit width needed to represent a reduction whose exit
100/// instruction is given by Exit.
101static std::pair<Type *, bool> computeRecurrenceType(Instruction *Exit,
102 DemandedBits *DB,
103 AssumptionCache *AC,
104 DominatorTree *DT) {
105 bool IsSigned = false;
106 const DataLayout &DL = Exit->getDataLayout();
107 uint64_t MaxBitWidth = DL.getTypeSizeInBits(Exit->getType());
108
109 if (DB) {
110 // Use the demanded bits analysis to determine the bits that are live out
111 // of the exit instruction, rounding up to the nearest power of two. If the
112 // use of demanded bits results in a smaller bit width, we know the value
113 // must be positive (i.e., IsSigned = false), because if this were not the
114 // case, the sign bit would have been demanded.
115 auto Mask = DB->getDemandedBits(Exit);
116 MaxBitWidth = Mask.getBitWidth() - Mask.countl_zero();
117 }
118
119 if (MaxBitWidth == DL.getTypeSizeInBits(Exit->getType()) && AC && DT) {
120 // If demanded bits wasn't able to limit the bit width, we can try to use
121 // value tracking instead. This can be the case, for example, if the value
122 // may be negative.
123 auto NumSignBits = ComputeNumSignBits(Exit, DL, AC, nullptr, DT);
124 auto NumTypeBits = DL.getTypeSizeInBits(Exit->getType());
125 MaxBitWidth = NumTypeBits - NumSignBits;
126 KnownBits Bits = computeKnownBits(Exit, DL);
127 if (!Bits.isNonNegative()) {
128 // If the value is not known to be non-negative, we set IsSigned to true,
129 // meaning that we will use sext instructions instead of zext
130 // instructions to restore the original type.
131 IsSigned = true;
132 // Make sure at least one sign bit is included in the result, so it
133 // will get properly sign-extended.
134 ++MaxBitWidth;
135 }
136 }
137 MaxBitWidth = llvm::bit_ceil(MaxBitWidth);
138
139 return std::make_pair(Type::getIntNTy(Exit->getContext(), MaxBitWidth),
140 IsSigned);
141}
142
143/// Collect cast instructions that can be ignored in the vectorizer's cost
144/// model, given a reduction exit value and the minimal type in which the
145// reduction can be represented. Also search casts to the recurrence type
146// to find the minimum width used by the recurrence.
147static void collectCastInstrs(Loop *TheLoop, Instruction *Exit,
148 Type *RecurrenceType,
150 Type *&MinWidthCastToRecurTy) {
151
154 Worklist.push_back(Exit);
155 MinWidthCastToRecurTy = nullptr;
156
157 while (!Worklist.empty()) {
158 Instruction *Val = Worklist.pop_back_val();
159 Visited.insert(Val);
160 if (auto *Cast = dyn_cast<CastInst>(Val)) {
161 if (Cast->getSrcTy() == RecurrenceType) {
162 // If the source type of a cast instruction is equal to the recurrence
163 // type, it will be eliminated, and should be ignored in the vectorizer
164 // cost model.
165 Casts.insert(Cast);
166 continue;
167 }
168 if (Cast->getDestTy() == RecurrenceType) {
169 // The minimum width used by the recurrence is found by checking for
170 // casts on its operands. The minimum width is used by the vectorizer
171 // when finding the widest type for in-loop reductions without any
172 // loads/stores.
173 Type *SrcTy = Cast->getSrcTy()->getScalarType();
174 if (!MinWidthCastToRecurTy ||
175 SrcTy->getScalarSizeInBits() <
176 MinWidthCastToRecurTy->getScalarSizeInBits())
177 MinWidthCastToRecurTy = SrcTy;
178 continue;
179 }
180 }
181 // Add all operands to the work list if they are loop-varying values that
182 // we haven't yet visited.
183 for (Value *O : cast<User>(Val)->operands())
184 if (auto *I = dyn_cast<Instruction>(O))
185 if (TheLoop->contains(I) && !Visited.count(I))
186 Worklist.push_back(I);
187 }
188}
189
190// Check if a given Phi node can be recognized as an ordered reduction for
191// vectorizing floating point operations without unsafe math.
192static bool checkOrderedReduction(RecurKind Kind, Instruction *ExactFPMathInst,
193 Instruction *Exit, PHINode *Phi) {
194 // Currently only FAdd and FMulAdd are supported.
195 if (Kind != RecurKind::FAdd && Kind != RecurKind::FMulAdd)
196 return false;
197
198 if (Kind == RecurKind::FAdd && Exit->getOpcode() != Instruction::FAdd)
199 return false;
200
201 if (Kind == RecurKind::FMulAdd &&
203 return false;
204
205 // Ensure the exit instruction has only one user other than the reduction PHI
206 if (Exit != ExactFPMathInst || Exit->hasNUsesOrMore(3))
207 return false;
208
209 // The only pattern accepted is the one in which the reduction PHI
210 // is used as one of the operands of the exit instruction
211 auto *Op0 = Exit->getOperand(0);
212 auto *Op1 = Exit->getOperand(1);
213 if (Kind == RecurKind::FAdd && Op0 != Phi && Op1 != Phi)
214 return false;
215 if (Kind == RecurKind::FMulAdd && Exit->getOperand(2) != Phi)
216 return false;
217
218 LLVM_DEBUG(dbgs() << "LV: Found an ordered reduction: Phi: " << *Phi
219 << ", ExitInst: " << *Exit << "\n");
220
221 return true;
222}
223
224// Collect FMF from a value and its associated fcmp in select patterns
226 FastMathFlags FMF = cast<FPMathOperator>(V)->getFastMathFlags();
227 if (auto *Sel = dyn_cast<SelectInst>(V)) {
228 // Accept FMF from either fcmp or select in a min/max idiom.
229 // TODO: Remove this when FMF propagation is fixed or we standardize on
230 // intrinsics.
231 if (auto *FCmp = dyn_cast<FCmpInst>(Sel->getCondition()))
232 FMF |= FCmp->getFastMathFlags();
233 }
234 return FMF;
235}
236
237static std::optional<FastMathFlags>
239 bool HasRequiredFMF = FPOp && FPOp->hasNoNaNs() && FPOp->hasNoSignedZeros();
240 if (HasRequiredFMF)
241 return collectMinMaxFMF(FPOp);
242
243 // Select-based min/max without nnan/nsz require equal non-NaN values to only
244 // differ in the sign of zero, i.e. an IEEE type without flushed denormals.
245 auto *Sel = dyn_cast<SelectInst>(FPOp);
246 Type *Ty = FPOp->getType();
247 if (Sel && (!Ty->isIEEELikeFPTy() ||
248 Sel->getFunction()->getDenormalMode(Ty->getFltSemantics()) !=
250 return std::nullopt;
251
252 switch (RK) {
257 break;
258
259 case RecurKind::FMax:
261 break;
262 case RecurKind::FMin:
264 break;
265 default:
266 return std::nullopt;
267 }
268 // Only use FPOp's flags, as e.g. nsz on the fcmp of a select-based min/max
269 // does not apply to its result.
270 return FPOp->getFastMathFlags();
271}
272
274 ScalarEvolution *SE) {
275 Type *Ty = Phi->getType()->getScalarType();
276 BasicBlock *Latch = TheLoop->getLoopLatch();
277 if (Phi->getNumIncomingValues() != 2 ||
278 Phi->getParent() != TheLoop->getHeader() ||
279 (!Ty->isIntegerTy() && !Ty->isFloatingPointTy()) || !Latch)
280 return {};
281
282 auto GetMinMaxRK = [](Value *V, Value *&A, Value *&B) -> RecurKind {
283 if (match(V, m_UMin(m_Value(A), m_Value(B))))
284 return RecurKind::UMin;
285 if (match(V, m_UMax(m_Value(A), m_Value(B))))
286 return RecurKind::UMax;
287 if (match(V, m_SMax(m_Value(A), m_Value(B))))
288 return RecurKind::SMax;
289 if (match(V, m_SMin(m_Value(A), m_Value(B))))
290 return RecurKind::SMin;
293 return RecurKind::FMin;
296 return RecurKind::FMax;
297 if (match(V, m_FMinimum(m_Value(A), m_Value(B))))
298 return RecurKind::FMinimum;
299 if (match(V, m_FMaximum(m_Value(A), m_Value(B))))
300 return RecurKind::FMaximum;
305 return RecurKind::None;
306 };
307
309 Value *BackedgeValue = Phi->getIncomingValueForBlock(Latch);
311 // Walk def-use chains upwards from BackedgeValue to identify min/max
312 // recurrences.
313 SmallVector<Value *> WorkList({BackedgeValue});
314 SmallPtrSet<Value *, 8> Chain({Phi});
315 while (!WorkList.empty()) {
316 Value *Cur = WorkList.pop_back_val();
317 if (!Chain.insert(Cur).second)
318 continue;
319 auto *I = dyn_cast<Instruction>(Cur);
320 if (!I || !TheLoop->contains(I))
321 return {};
322 if (auto *PN = dyn_cast<PHINode>(I)) {
323 append_range(WorkList, PN->operands());
324 continue;
325 }
326 Value *A, *B;
327 RecurKind CurRK = GetMinMaxRK(Cur, A, B);
328 if (CurRK == RecurKind::None || (RK != RecurKind::None && CurRK != RK))
329 return {};
330
331 RK = CurRK;
332 // Check required fast-math flags for FP recurrences.
334 auto CurFMF = hasRequiredFastMathFlags(cast<FPMathOperator>(Cur), RK);
335 if (!CurFMF)
336 return {};
337 FMF &= *CurFMF;
338 }
339
340 if (auto *SI = dyn_cast<SelectInst>(I))
341 Chain.insert(SI->getCondition());
342
343 if (A == Phi || B == Phi)
344 continue;
345
346 // Add operand to worklist if it matches the pattern (exactly one must
347 // match)
348 Value *X, *Y;
349 auto *IA = dyn_cast<Instruction>(A);
350 auto *IB = dyn_cast<Instruction>(B);
351 bool AMatches = IA && TheLoop->contains(IA) && GetMinMaxRK(A, X, Y) == RK;
352 bool BMatches = IB && TheLoop->contains(IB) && GetMinMaxRK(B, X, Y) == RK;
353 if (AMatches == BMatches) // Both or neither match
354 return {};
355 WorkList.push_back(AMatches ? A : B);
356 }
357
358 // Handle argmin/argmax pattern: PHI has uses outside the reduction chain
359 // that are not intermediate min/max operations (which are handled below).
360 // Requires integer min/max, and the PHI must be the only in-loop user of
361 // BackedgeValue (so vectorizer can handle both PHIs together).
362 bool PhiHasInvalidUses = any_of(Phi->users(), [&](Instruction *U) {
363 Value *A, *B;
364 return !Chain.contains(U) && TheLoop->contains(U) &&
365 GetMinMaxRK(U, A, B) == RecurKind::None;
366 });
367 if (PhiHasInvalidUses) {
369 any_of(BackedgeValue->users(), [&](User *U) {
370 auto *UI = cast<Instruction>(U);
371 return UI != Phi && TheLoop->contains(UI);
372 }))
373 return {};
375 Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader()),
376 /*Exit=*/nullptr, /*Store=*/nullptr, RK, FastMathFlags(),
377 /*ExactFP=*/nullptr, Phi->getType(), /*IsMultiUse=*/true);
378 }
379
380 // Validate chain entries and collect stores from chain entries and
381 // intermediate ops.
383 for (Value *V : Chain) {
384 for (User *U : V->users()) {
385 if (Chain.contains(U))
386 continue;
387 auto *I = dyn_cast<Instruction>(U);
388 if (!I || (!TheLoop->contains(I) && V != BackedgeValue))
389 return {};
390 if (!TheLoop->contains(I))
391 continue;
392 if (auto *SI = dyn_cast<StoreInst>(I)) {
393 Stores.push_back(SI);
394 continue;
395 }
396 // Must be intermediate min/max of the same kind.
397 Value *A, *B;
398 if (GetMinMaxRK(I, A, B) != RK)
399 return {};
400 for (User *IU : I->users()) {
401 if (auto *SI = dyn_cast<StoreInst>(IU))
402 Stores.push_back(SI);
403 else if (!Chain.contains(IU))
404 return {};
405 }
406 }
407 }
408
409 // Validate all stores go to same invariant address and are in the same block.
410 StoreInst *IntermediateStore = nullptr;
411 const SCEV *StorePtrSCEV = nullptr;
412 for (StoreInst *SI : Stores) {
413 if (!SE)
414 return {};
415 const SCEV *Ptr = SE->getSCEV(SI->getPointerOperand());
416 if (!SE->isLoopInvariant(Ptr, TheLoop) ||
417 (StorePtrSCEV && StorePtrSCEV != Ptr))
418 return {};
419 StorePtrSCEV = Ptr;
420 if (!IntermediateStore)
421 IntermediateStore = SI;
422 else if (IntermediateStore->getParent() != SI->getParent())
423 return {};
424 else if (IntermediateStore->comesBefore(SI))
425 IntermediateStore = SI;
426 }
427
428 // The vectorizer replaces the per-iteration store to the invariant address
429 // with a single store of the final reduced value in the middle block. That is
430 // only correct if the store stores the reduction value itself. If it stores a
431 // value derived from it (e.g. `%other = smax(%phi, 42); store %other`), that
432 // value observes the per-iteration running min/max, so replacing it with the
433 // final reduction value would miscompile. Mirrors the check in
434 // AddReductionVar.
435 if (IntermediateStore &&
436 IntermediateStore->getValueOperand() != BackedgeValue)
437 return {};
438
440 Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader()),
441 cast<Instruction>(BackedgeValue), IntermediateStore, RK, FMF, nullptr,
442 Phi->getType());
443}
444
445// This matches a phi that selects between the original value (HeaderPhi) and an
446// arbitrary non-reduction value.
447static bool isFindLastLikePhi(PHINode *Phi, PHINode *HeaderPhi,
448 SmallPtrSetImpl<Instruction *> &ReductionInstrs) {
449 unsigned NumNonReduxInputs = 0;
450 for (const Value *Op : Phi->operands()) {
451 if (!ReductionInstrs.contains(dyn_cast<Instruction>(Op))) {
452 if (++NumNonReduxInputs > 1)
453 return false;
454 } else if (Op != HeaderPhi) {
455 // TODO: Remove this restriction once chained phis are supported.
456 return false;
457 }
458 }
459 return NumNonReduxInputs == 1;
460}
461
463 PHINode *Phi, RecurKind Kind, Loop *TheLoop, RecurrenceDescriptor &RedDes,
465 ScalarEvolution *SE) {
466 if (Phi->getNumIncomingValues() != 2)
467 return false;
468
469 // Reduction variables are only found in the loop header block.
470 if (Phi->getParent() != TheLoop->getHeader())
471 return false;
472
473 // Obtain the reduction start value from the value that comes from the loop
474 // preheader.
475 if (!TheLoop->getLoopPreheader())
476 return false;
477
478 Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
479 // ExitInstruction is the single value which is used outside the loop.
480 // We only allow for a single reduction value to be used outside the loop.
481 // This includes users of the reduction, variables (which form a cycle
482 // which ends in the phi node).
483 Instruction *ExitInstruction = nullptr;
484
485 // Variable to keep last visited store instruction. By the end of the
486 // algorithm this variable will be either empty or having intermediate
487 // reduction value stored in invariant address.
488 StoreInst *IntermediateStore = nullptr;
489
490 // Indicates that we found a reduction operation in our scan.
491 bool FoundReduxOp = false;
492
493 // We start with the PHI node and scan for all of the users of this
494 // instruction. All users must be instructions that can be used as reduction
495 // variables (such as ADD). We must have a single out-of-block user. The cycle
496 // must include the original PHI.
497 bool FoundStartPHI = false;
498
499 // To recognize AnyOf patterns formed by a select, we store the select to
500 // make sure we only see one.
501 SelectInst *AnyOfSelect = nullptr;
502 InstDesc ReduxDesc(false, nullptr);
503
504 // To recognize find-lasts of conditional operations (such as loads or
505 // divides), that need masking, we track non-phi users and if we've found a
506 // "find-last-like" phi (see isFindLastLikePhi). We currently only support
507 // find-last reduction chains with a single "find-last-like" phi and do not
508 // allow any other operations.
509 [[maybe_unused]] unsigned NumNonPHIUsers = 0;
510 bool FoundFindLastLikePhi = false;
511
512 // Data used for determining if the recurrence has been type-promoted.
513 Type *RecurrenceType = Phi->getType();
515 Type *MinWidthCastToRecurrenceType = nullptr;
516 Instruction *Start = Phi;
517 bool IsSigned = false;
518
521
522 // Return early if the recurrence kind does not match the type of Phi. If the
523 // recurrence kind is arithmetic, we attempt to look through AND operations
524 // resulting from the type promotion performed by InstCombine. Vector
525 // operations are not limited to the legal integer widths, so we may be able
526 // to evaluate the reduction in the narrower width.
527 // Check the scalar type to handle both scalar and vector types.
528 Type *ScalarTy = RecurrenceType->getScalarType();
529 if (Kind == RecurKind::FindLast) {
530 // FindLast supports all primitive scalar types.
531 if (!ScalarTy->isFloatingPointTy() && !ScalarTy->isIntegerTy() &&
532 !ScalarTy->isPointerTy())
533 return false;
534 } else if (ScalarTy->isFloatingPointTy()) {
536 return false;
537 } else if (ScalarTy->isIntegerTy()) {
538 if (!isIntegerRecurrenceKind(Kind))
539 return false;
540 Start = lookThroughAnd(Phi, RecurrenceType, VisitedInsts, CastInsts);
541 } else {
542 // Pointer min/max may exist, but it is not supported as a reduction op.
543 return false;
544 }
545
546 Worklist.push_back(Start);
547 VisitedInsts.insert(Start);
548
549 // Start with all flags set because we will intersect this with the reduction
550 // flags from all the reduction operations.
552
553 // The first instruction in the use-def chain of the Phi node that requires
554 // exact floating point operations.
555 Instruction *ExactFPMathInst = nullptr;
556
557 // A value in the reduction can be used:
558 // - By the reduction:
559 // - Reduction operation:
560 // - One use of reduction value (safe).
561 // - Multiple use of reduction value (not safe).
562 // - PHI:
563 // - All uses of the PHI must be the reduction (safe).
564 // - Otherwise, not safe.
565 // - By instructions outside of the loop (safe).
566 // * One value may have several outside users, but all outside
567 // uses must be of the same value.
568 // - By store instructions with a loop invariant address (safe with
569 // the following restrictions):
570 // * If there are several stores, all must have the same address.
571 // * Final value should be stored in that loop invariant address.
572 // - By an instruction that is not part of the reduction (not safe).
573 // This is either:
574 // * An instruction type other than PHI or the reduction operation.
575 // * A PHI in the header other than the initial PHI.
576 while (!Worklist.empty()) {
577 Instruction *Cur = Worklist.pop_back_val();
578
579 // Store instructions are allowed iff it is the store of the reduction
580 // value to the same loop invariant memory location.
581 if (auto *SI = dyn_cast<StoreInst>(Cur)) {
582 if (!SE) {
583 LLVM_DEBUG(dbgs() << "Store instructions are not processed without "
584 << "Scalar Evolution Analysis\n");
585 return false;
586 }
587
588 const SCEV *PtrScev = SE->getSCEV(SI->getPointerOperand());
589 // Check it is the same address as previous stores
590 if (IntermediateStore) {
591 const SCEV *OtherScev =
592 SE->getSCEV(IntermediateStore->getPointerOperand());
593
594 if (OtherScev != PtrScev) {
595 LLVM_DEBUG(dbgs() << "Storing reduction value to different addresses "
596 << "inside the loop: " << *SI->getPointerOperand()
597 << " and "
598 << *IntermediateStore->getPointerOperand() << '\n');
599 return false;
600 }
601 }
602
603 // Check the pointer is loop invariant
604 if (!SE->isLoopInvariant(PtrScev, TheLoop)) {
605 LLVM_DEBUG(dbgs() << "Storing reduction value to non-uniform address "
606 << "inside the loop: " << *SI->getPointerOperand()
607 << '\n');
608 return false;
609 }
610
611 // IntermediateStore is always the last store in the loop.
613 continue;
614 }
615
616 // No Users.
617 // If the instruction has no users then this is a broken chain and can't be
618 // a reduction variable.
619 if (Cur->use_empty())
620 return false;
621
622 bool IsAPhi = isa<PHINode>(Cur);
623 if (!IsAPhi)
624 ++NumNonPHIUsers;
625
626 // A header PHI use other than the original PHI.
627 if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
628 return false;
629
630 // Reductions of instructions such as Div, and Sub is only possible if the
631 // LHS is the reduction variable.
632 if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
633 !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
634 !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
635 return false;
636
637 // Any reduction instruction must be of one of the allowed kinds. We ignore
638 // the starting value (the Phi or an AND instruction if the Phi has been
639 // type-promoted).
640 if (Cur != Start) {
641 ReduxDesc = isRecurrenceInstr(TheLoop, Phi, Cur, Kind, ReduxDesc, SE);
642 ExactFPMathInst = ExactFPMathInst == nullptr
643 ? ReduxDesc.getExactFPMathInst()
644 : ExactFPMathInst;
645 if (!ReduxDesc.isRecurrence())
646 return false;
647 // FIXME: FMF is allowed on phi, but propagation is not handled correctly.
648 if (isa<FPMathOperator>(ReduxDesc.getPatternInst()) && !IsAPhi)
649 FMF &= collectMinMaxFMF(ReduxDesc.getPatternInst());
650 // Update this reduction kind if we matched a new instruction.
651 // TODO: Can we eliminate the need for a 2nd InstDesc by keeping 'Kind'
652 // state accurate while processing the worklist?
653 if (ReduxDesc.getRecKind() != RecurKind::None)
654 Kind = ReduxDesc.getRecKind();
655 }
656
657 bool IsASelect = isa<SelectInst>(Cur);
658
659 // A conditional reduction operation must only have 2 or less uses in
660 // VisitedInsts.
661 if (IsASelect && (Kind == RecurKind::FAdd || Kind == RecurKind::FMul) &&
662 hasMultipleUsesOf(Cur, VisitedInsts, 2))
663 return false;
664
665 // A reduction operation must only have one use of the reduction value.
666 if (!IsAPhi && !IsASelect && !isAnyOfRecurrenceKind(Kind) &&
667 hasMultipleUsesOf(Cur, VisitedInsts, 1))
668 return false;
669
670 // All inputs to a PHI node must be a reduction value, unless the phi is a
671 // "FindLast-like" phi (described below).
672 if (IsAPhi && Cur != Phi) {
673 if (!areAllUsesIn(Cur, VisitedInsts)) {
674 // A "FindLast-like" phi acts like a conditional select between the
675 // previous reduction value, and an arbitrary value. Note: Multiple
676 // "FindLast-like" phis are not supported see:
677 // IVDescriptorsTest.UnsupportedFindLastPhi.
678 FoundFindLastLikePhi =
679 Kind == RecurKind::FindLast && !FoundFindLastLikePhi &&
680 isFindLastLikePhi(cast<PHINode>(Cur), Phi, VisitedInsts);
681 if (!FoundFindLastLikePhi)
682 return false;
683 }
684 }
685
686 if (isAnyOfRecurrenceKind(Kind) && IsASelect) {
687 if (AnyOfSelect)
688 return false;
689 AnyOfSelect = cast<SelectInst>(Cur);
690 }
691
692 // Check whether we found a reduction operator.
693 FoundReduxOp |= (!IsAPhi || FoundFindLastLikePhi) && Cur != Start;
694
695 // Process users of current instruction. Push non-PHI nodes after PHI nodes
696 // onto the stack. This way we are going to have seen all inputs to PHI
697 // nodes once we get to them.
700 for (Instruction *UI : Cur->users()) {
701 // If the user is a call to llvm.fmuladd then the instruction can only be
702 // the final operand.
703 if (isFMulAddIntrinsic(UI))
704 if (Cur == UI->getOperand(0) || Cur == UI->getOperand(1))
705 return false;
706
707 // Check if we found the exit user.
708 BasicBlock *Parent = UI->getParent();
709 if (!TheLoop->contains(Parent)) {
710 // If we already know this instruction is used externally, move on to
711 // the next user.
712 if (ExitInstruction == Cur)
713 continue;
714
715 // Exit if you find multiple values used outside or if the header phi
716 // node is being used. In this case the user uses the value of the
717 // previous iteration, in which case we would loose "VF-1" iterations of
718 // the reduction operation if we vectorize.
719 if (ExitInstruction != nullptr || Cur == Phi)
720 return false;
721
722 // The instruction used by an outside user must be the last instruction
723 // before we feed back to the reduction phi. Otherwise, we loose VF-1
724 // operations on the value.
725 if (!is_contained(Phi->operands(), Cur))
726 return false;
727
728 ExitInstruction = Cur;
729 continue;
730 }
731
732 // Process instructions only once (termination). Each reduction cycle
733 // value must only be used once, except by phi nodes and conditional
734 // reductions which are represented as a cmp followed by a select.
735 InstDesc IgnoredVal(false, nullptr);
736 if (VisitedInsts.insert(UI).second) {
737 if (isa<PHINode>(UI)) {
738 PHIs.push_back(UI);
739 } else {
741 if (SI && SI->getPointerOperand() == Cur) {
742 // Reduction variable chain can only be stored somewhere but it
743 // can't be used as an address.
744 return false;
745 }
746 NonPHIs.push_back(UI);
747 }
748 } else if (!isa<PHINode>(UI) &&
749 ((!isConditionalRdxPattern(UI).isRecurrence() &&
750 !isAnyOfPattern(TheLoop, Phi, UI, IgnoredVal)
751 .isRecurrence())))
752 return false;
753
754 // Remember that we completed the cycle.
755 if (UI == Phi)
756 FoundStartPHI = true;
757 }
758 Worklist.append(PHIs.begin(), PHIs.end());
759 Worklist.append(NonPHIs.begin(), NonPHIs.end());
760 }
761
762 // We only expect to match a single "find-last-like" phi per find-last
763 // reduction, with no non-phi operations in the reduction use chain.
764 assert((!FoundFindLastLikePhi ||
765 (Kind == RecurKind::FindLast && NumNonPHIUsers == 0)) &&
766 "Unexpectedly matched a 'find-last-like' phi");
767
768 if (isAnyOfRecurrenceKind(Kind)) {
769 if (!AnyOfSelect)
770 return false;
771 // Reject a select whose condition is part of the chain: the vectorizer
772 // replaces the chain, so the condition would become poison. Compares are
773 // allowed, since the vectorizer rewrites a compare of the reduction phi
774 // to use the start value.
775 auto *Cond = dyn_cast<Instruction>(AnyOfSelect->getCondition());
776 if (Cond && !isa<CmpInst>(Cond) && VisitedInsts.contains(Cond))
777 return false;
778 }
779
780 if (IntermediateStore) {
781 // Check that stored value goes to the phi node again. This way we make sure
782 // that the value stored in IntermediateStore is indeed the final reduction
783 // value.
784 if (!is_contained(Phi->operands(), IntermediateStore->getValueOperand())) {
785 LLVM_DEBUG(dbgs() << "Not a final reduction value stored: "
786 << *IntermediateStore << '\n');
787 return false;
788 }
789
790 // If there is an exit instruction it's value should be stored in
791 // IntermediateStore
792 if (ExitInstruction &&
793 IntermediateStore->getValueOperand() != ExitInstruction) {
794 LLVM_DEBUG(dbgs() << "Last store Instruction of reduction value does not "
795 "store last calculated value of the reduction: "
796 << *IntermediateStore << '\n');
797 return false;
798 }
799
800 // If all uses are inside the loop (intermediate stores), then the
801 // reduction value after the loop will be the one used in the last store.
802 if (!ExitInstruction)
803 ExitInstruction = cast<Instruction>(IntermediateStore->getValueOperand());
804 }
805
806 if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
807 return false;
808
809 const bool IsOrdered =
810 checkOrderedReduction(Kind, ExactFPMathInst, ExitInstruction, Phi);
811
812 if (Start != Phi) {
813 // If the starting value is not the same as the phi node, we speculatively
814 // looked through an 'and' instruction when evaluating a potential
815 // arithmetic reduction to determine if it may have been type-promoted.
816 //
817 // We now compute the minimal bit width that is required to represent the
818 // reduction. If this is the same width that was indicated by the 'and', we
819 // can represent the reduction in the smaller type. The 'and' instruction
820 // will be eliminated since it will essentially be a cast instruction that
821 // can be ignore in the cost model. If we compute a different type than we
822 // did when evaluating the 'and', the 'and' will not be eliminated, and we
823 // will end up with different kinds of operations in the recurrence
824 // expression (e.g., IntegerAND, IntegerADD). We give up if this is
825 // the case.
826 //
827 // The vectorizer relies on InstCombine to perform the actual
828 // type-shrinking. It does this by inserting instructions to truncate the
829 // exit value of the reduction to the width indicated by RecurrenceType and
830 // then extend this value back to the original width. If IsSigned is false,
831 // a 'zext' instruction will be generated; otherwise, a 'sext' will be
832 // used.
833 //
834 // TODO: We should not rely on InstCombine to rewrite the reduction in the
835 // smaller type. We should just generate a correctly typed expression
836 // to begin with.
837 Type *ComputedType;
838 std::tie(ComputedType, IsSigned) =
839 computeRecurrenceType(ExitInstruction, DB, AC, DT);
840 if (ComputedType != RecurrenceType)
841 return false;
842 }
843
844 // Collect cast instructions and the minimum width used by the recurrence.
845 // If the starting value is not the same as the phi node and the computed
846 // recurrence type is equal to the recurrence type, the recurrence expression
847 // will be represented in a narrower or wider type. If there are any cast
848 // instructions that will be unnecessary, collect them in CastsFromRecurTy.
849 // Note that the 'and' instruction was already included in this list.
850 //
851 // TODO: A better way to represent this may be to tag in some way all the
852 // instructions that are a part of the reduction. The vectorizer cost
853 // model could then apply the recurrence type to these instructions,
854 // without needing a white list of instructions to ignore.
855 // This may also be useful for the inloop reductions, if it can be
856 // kept simple enough.
857 collectCastInstrs(TheLoop, ExitInstruction, RecurrenceType, CastInsts,
858 MinWidthCastToRecurrenceType);
859
860 // We found a reduction var if we have reached the original phi node and we
861 // only have a single instruction with out-of-loop users.
862
863 // The ExitInstruction(Instruction which is allowed to have out-of-loop users)
864 // is saved as part of the RecurrenceDescriptor.
865
866 // Save the description of this reduction variable.
867 RedDes =
868 RecurrenceDescriptor(RdxStart, ExitInstruction, IntermediateStore, Kind,
869 FMF, ExactFPMathInst, RecurrenceType, IsSigned,
870 IsOrdered, CastInsts, MinWidthCastToRecurrenceType);
871 return true;
872}
873
874// We are looking for loops that do something like this:
875// int r = 0;
876// for (int i = 0; i < n; i++) {
877// if (src[i] > 3)
878// r = 3;
879// }
880// where the reduction value (r) only has two states, in this example 0 or 3.
881// The generated LLVM IR for this type of loop will be like this:
882// for.body:
883// %r = phi i32 [ %spec.select, %for.body ], [ 0, %entry ]
884// ...
885// %cmp = icmp sgt i32 %5, 3
886// %spec.select = select i1 %cmp, i32 3, i32 %r
887// ...
888// The condition can be any i1 value, including one defined outside the loop.
889// If it is part of the reduction chain, it has to be a compare (see
890// AddReductionVar).
891// In general we can support vectorization of loops where 'r' flips between
892// any two non-constants, provided they are loop invariant. The only thing
893// we actually care about at the end of the loop is whether or not any lane
894// in the selected vector is different from the start value. The final
895// across-vector reduction after the loop simply involves choosing the start
896// value if nothing changed (0 in the example above) or the other selected
897// value (3 in the example above).
900 Instruction *I, InstDesc &Prev) {
901 // We must handle the select(cmp(),x,y) as a single instruction. Advance to
902 // the select.
903 if (match(I, m_OneUse(m_Cmp()))) {
904 if (auto *Select = dyn_cast<SelectInst>(*I->user_begin()))
905 return InstDesc(Select, Prev.getRecKind());
906 }
907
909 if (!SI)
910 return InstDesc(false, I);
911
912 Value *NonPhi = nullptr;
913
914 if (OrigPhi == dyn_cast<PHINode>(SI->getTrueValue()))
915 NonPhi = SI->getFalseValue();
916 else if (OrigPhi == dyn_cast<PHINode>(SI->getFalseValue()))
917 NonPhi = SI->getTrueValue();
918 else
919 return InstDesc(false, I);
920
921 // We are looking for selects of the form:
922 // select(cond, phi, loop_invariant) or
923 // select(cond, loop_invariant, phi)
924 if (!Loop->isLoopInvariant(NonPhi))
925 return InstDesc(false, I);
926
927 return InstDesc(I, RecurKind::AnyOf);
928}
929
930// We are looking for loops that do something like this:
931// int r = 0;
932// for (int i = 0; i < n; i++) {
933// if (src[i] > 3)
934// r = i;
935// }
936// or like this:
937// int r = 0;
938// for (int i = 0; i < n; i++) {
939// if (src[i] > 3)
940// r = <loop-varying value>;
941// }
942// The reduction value (r) is derived from either the values of an induction
943// variable (i) sequence, an arbitrary loop-varying value, or from the start
944// value (0). The LLVM IR generated for such loops would be as follows:
945// for.body:
946// %r = phi i32 [ %spec.select, %for.body ], [ 0, %entry ]
947// %i = phi i32 [ %inc, %for.body ], [ 0, %entry ]
948// ...
949// %cmp = icmp sgt i32 %5, 3
950// %spec.select = select i1 %cmp, i32 %i, i32 %r
951// %inc = add nsw i32 %i, 1
952// ...
953//
954// When searching for an arbitrary loop-varying value, the reduction value will
955// either be the initial value (0) if the condition was never met, or the value
956// of the loop-varying value in the most recent loop iteration where the
957// condition was met.
961 // TODO: Support the vectorization of FindLastIV when the reduction phi is
962 // used by more than one select instruction. This vectorization is only
963 // performed when the SCEV of each increasing induction variable used by the
964 // select instructions is identical.
965 if (!OrigPhi->hasOneUse())
966 return InstDesc(false, I);
967
968 // We are looking for selects of the form:
969 // select(cmp(), phi, value) or
970 // select(cmp(), value, phi)
971 if (!match(I, m_CombineOr(m_Select(m_Cmp(), m_Value(), m_Specific(OrigPhi)),
972 m_Select(m_Cmp(), m_Specific(OrigPhi), m_Value()))))
973 return InstDesc(false, I);
974
976}
977
978/// Returns true if the select instruction has users in the compare-and-add
979/// reduction pattern below. The select instruction argument is the last one
980/// in the sequence.
981///
982/// %sum.1 = phi ...
983/// ...
984/// %cmp = fcmp pred %0, %CFP
985/// %add = fadd %0, %sum.1
986/// %sum.2 = select %cmp, %add, %sum.1
989 Value *TrueVal, *FalseVal;
990 // Only handle single use cases for now.
991 if (!match(I,
992 m_Select(m_OneUse(m_Cmp()), m_Value(TrueVal), m_Value(FalseVal))))
993 return InstDesc(false, I);
994
995 // Handle only when either of operands of select instruction is a PHI
996 // node for now.
997 if ((isa<PHINode>(TrueVal) && isa<PHINode>(FalseVal)) ||
998 (!isa<PHINode>(TrueVal) && !isa<PHINode>(FalseVal)))
999 return InstDesc(false, I);
1000
1001 Instruction *I1 = isa<PHINode>(TrueVal) ? dyn_cast<Instruction>(FalseVal)
1002 : dyn_cast<Instruction>(TrueVal);
1003 if (!I1 || !I1->isBinaryOp())
1004 return InstDesc(false, I);
1005
1006 Value *Op1, *Op2;
1007 if (!(((m_FAdd(m_Value(Op1), m_Value(Op2)).match(I1) ||
1008 m_FSub(m_Value(Op1), m_Value(Op2)).match(I1)) &&
1009 I1->isFast()) ||
1010 (m_FMul(m_Value(Op1), m_Value(Op2)).match(I1) && (I1->isFast())) ||
1011 ((m_Add(m_Value(Op1), m_Value(Op2)).match(I1) ||
1012 m_Sub(m_Value(Op1), m_Value(Op2)).match(I1))) ||
1013 (m_Mul(m_Value(Op1), m_Value(Op2)).match(I1))))
1014 return InstDesc(false, I);
1015
1017 : dyn_cast<Instruction>(Op2);
1018 if (!IPhi || IPhi != FalseVal)
1019 return InstDesc(false, I);
1020
1021 return InstDesc(true, I);
1022}
1023
1026 Instruction *I, RecurKind Kind,
1027 InstDesc &Prev, ScalarEvolution *SE) {
1028 assert(Prev.getRecKind() == RecurKind::None || Prev.getRecKind() == Kind);
1029 switch (I->getOpcode()) {
1030 default:
1031 return InstDesc(false, I);
1032 case Instruction::PHI:
1033 return InstDesc(I, Prev.getRecKind(), Prev.getExactFPMathInst());
1034 case Instruction::Sub:
1035 return InstDesc(
1036 Kind == RecurKind::Sub || Kind == RecurKind::AddChainWithSubs, I);
1037 case Instruction::Add:
1038 return InstDesc(
1039 Kind == RecurKind::Add || Kind == RecurKind::AddChainWithSubs, I);
1040 case Instruction::Mul:
1041 return InstDesc(Kind == RecurKind::Mul, I);
1042 case Instruction::And:
1043 return InstDesc(Kind == RecurKind::And, I);
1044 case Instruction::Or:
1045 return InstDesc(Kind == RecurKind::Or, I);
1046 case Instruction::Xor:
1047 return InstDesc(Kind == RecurKind::Xor, I);
1048 case Instruction::FDiv:
1049 case Instruction::FMul:
1050 return InstDesc(Kind == RecurKind::FMul, I,
1051 I->hasAllowReassoc() ? nullptr : I);
1052 case Instruction::FSub:
1053 return InstDesc(Kind == RecurKind::FSub ||
1055 I, I->hasAllowReassoc() ? nullptr : I);
1056 case Instruction::FAdd:
1057 return InstDesc(Kind == RecurKind::FAdd ||
1059 I, I->hasAllowReassoc() ? nullptr : I);
1060 case Instruction::Select:
1061 if (isSubRecurrenceKind(Kind) || Kind == RecurKind::FAdd ||
1062 Kind == RecurKind::FMul || Kind == RecurKind::Add ||
1063 Kind == RecurKind::Mul || Kind == RecurKind::AddChainWithSubs ||
1065 return isConditionalRdxPattern(I);
1066 if (isFindRecurrenceKind(Kind) && SE)
1067 return isFindPattern(L, OrigPhi, I, *SE);
1068 [[fallthrough]];
1069 case Instruction::FCmp:
1070 case Instruction::ICmp:
1071 case Instruction::Call:
1072 if (isAnyOfRecurrenceKind(Kind))
1073 return isAnyOfPattern(L, OrigPhi, I, Prev);
1074 if (isFMulAddIntrinsic(I))
1075 return InstDesc(Kind == RecurKind::FMulAdd, I,
1076 I->hasAllowReassoc() ? nullptr : I);
1077 return InstDesc(false, I);
1078 }
1079}
1080
1083 unsigned MaxNumUses) {
1084 unsigned NumUses = 0;
1085 for (const Use &U : I->operands()) {
1086 if (Insts.count(dyn_cast<Instruction>(U)))
1087 ++NumUses;
1088 if (NumUses > MaxNumUses)
1089 return true;
1090 }
1091
1092 return false;
1093}
1094
1096 RecurrenceDescriptor &RedDes,
1098 DominatorTree *DT,
1099 ScalarEvolution *SE) {
1100 if (AddReductionVar(Phi, RecurKind::Add, TheLoop, RedDes, DB, AC, DT, SE)) {
1101 LLVM_DEBUG(dbgs() << "Found an ADD reduction PHI." << *Phi << "\n");
1102 return true;
1103 }
1104 if (AddReductionVar(Phi, RecurKind::Sub, TheLoop, RedDes, DB, AC, DT, SE)) {
1105 LLVM_DEBUG(dbgs() << "Found a SUB reduction PHI." << *Phi << "\n");
1106 return true;
1107 }
1108 if (AddReductionVar(Phi, RecurKind::AddChainWithSubs, TheLoop, RedDes, DB, AC,
1109 DT, SE)) {
1110 LLVM_DEBUG(dbgs() << "Found a chained ADD-SUB reduction PHI." << *Phi
1111 << "\n");
1112 return true;
1113 }
1114 if (AddReductionVar(Phi, RecurKind::Mul, TheLoop, RedDes, DB, AC, DT, SE)) {
1115 LLVM_DEBUG(dbgs() << "Found a MUL reduction PHI." << *Phi << "\n");
1116 return true;
1117 }
1118 if (AddReductionVar(Phi, RecurKind::Or, TheLoop, RedDes, DB, AC, DT, SE)) {
1119 LLVM_DEBUG(dbgs() << "Found an OR reduction PHI." << *Phi << "\n");
1120 return true;
1121 }
1122 if (AddReductionVar(Phi, RecurKind::And, TheLoop, RedDes, DB, AC, DT, SE)) {
1123 LLVM_DEBUG(dbgs() << "Found an AND reduction PHI." << *Phi << "\n");
1124 return true;
1125 }
1126 if (AddReductionVar(Phi, RecurKind::Xor, TheLoop, RedDes, DB, AC, DT, SE)) {
1127 LLVM_DEBUG(dbgs() << "Found a XOR reduction PHI." << *Phi << "\n");
1128 return true;
1129 }
1130 auto RD = getMinMaxRecurrence(Phi, TheLoop, SE);
1131 if (RD.getRecurrenceKind() != RecurKind::None) {
1132 assert(
1133 RecurrenceDescriptor::isMinMaxRecurrenceKind(RD.getRecurrenceKind()) &&
1134 "Expected a min/max recurrence kind");
1135 LLVM_DEBUG(dbgs() << "Found a min/max reduction PHI." << *Phi << "\n");
1136 RedDes = std::move(RD);
1137 return true;
1138 }
1139 if (AddReductionVar(Phi, RecurKind::AnyOf, TheLoop, RedDes, DB, AC, DT, SE)) {
1140 LLVM_DEBUG(dbgs() << "Found a conditional select reduction PHI." << *Phi
1141 << "\n");
1142 return true;
1143 }
1144 if (AddReductionVar(Phi, RecurKind::FindLast, TheLoop, RedDes, DB, AC, DT,
1145 SE)) {
1146 LLVM_DEBUG(dbgs() << "Found a Find reduction PHI." << *Phi << "\n");
1147 return true;
1148 }
1149 if (AddReductionVar(Phi, RecurKind::FMul, TheLoop, RedDes, DB, AC, DT, SE)) {
1150 LLVM_DEBUG(dbgs() << "Found an FMult reduction PHI." << *Phi << "\n");
1151 return true;
1152 }
1153 if (AddReductionVar(Phi, RecurKind::FSub, TheLoop, RedDes, DB, AC, DT, SE)) {
1154 LLVM_DEBUG(dbgs() << "Found an FSub reduction PHI." << *Phi << "\n");
1155 return true;
1156 }
1157 if (AddReductionVar(Phi, RecurKind::FAdd, TheLoop, RedDes, DB, AC, DT, SE)) {
1158 LLVM_DEBUG(dbgs() << "Found an FAdd reduction PHI." << *Phi << "\n");
1159 return true;
1160 }
1161 if (AddReductionVar(Phi, RecurKind::FAddChainWithSubs, TheLoop, RedDes, DB,
1162 AC, DT, SE)) {
1163 LLVM_DEBUG(dbgs() << "Found a chained FADD-FSUB chained reduction PHI."
1164 << *Phi << "\n");
1165 return true;
1166 }
1167 if (AddReductionVar(Phi, RecurKind::FMulAdd, TheLoop, RedDes, DB, AC, DT,
1168 SE)) {
1169 LLVM_DEBUG(dbgs() << "Found an FMulAdd reduction PHI." << *Phi << "\n");
1170 return true;
1171 }
1172
1173 // Not a reduction of known type.
1174 return false;
1175}
1176
1178 DominatorTree *DT) {
1179
1180 // Ensure the phi node is in the loop header and has two incoming values.
1181 if (Phi->getParent() != TheLoop->getHeader() ||
1182 Phi->getNumIncomingValues() != 2)
1183 return false;
1184
1185 // Ensure the loop has a preheader and a single latch block. The loop
1186 // vectorizer will need the latch to set up the next iteration of the loop.
1187 auto *Preheader = TheLoop->getLoopPreheader();
1188 auto *Latch = TheLoop->getLoopLatch();
1189 if (!Preheader || !Latch)
1190 return false;
1191
1192 // Ensure the phi node's incoming blocks are the loop preheader and latch.
1193 if (Phi->getBasicBlockIndex(Preheader) < 0 ||
1194 Phi->getBasicBlockIndex(Latch) < 0)
1195 return false;
1196
1197 // Get the previous value. The previous value comes from the latch edge while
1198 // the initial value comes from the preheader edge.
1199 auto *Previous = dyn_cast<Instruction>(Phi->getIncomingValueForBlock(Latch));
1200
1201 // If Previous is a phi in the header, go through incoming values from the
1202 // latch until we find a non-phi value. Use this as the new Previous, all uses
1203 // in the header will be dominated by the original phi, but need to be moved
1204 // after the non-phi previous value.
1206 while (auto *PrevPhi = dyn_cast_or_null<PHINode>(Previous)) {
1207 if (PrevPhi->getParent() != Phi->getParent())
1208 return false;
1209 if (!SeenPhis.insert(PrevPhi).second)
1210 return false;
1211 Previous = dyn_cast<Instruction>(PrevPhi->getIncomingValueForBlock(Latch));
1212 }
1213
1214 if (!Previous || isa<PHINode>(Previous))
1215 return false;
1216
1217 // Handle recurrences with a loop-invariant latch value.
1218 if (!TheLoop->contains(Previous)) {
1219 assert(DT->dominates(Previous, Phi) &&
1220 "loop-invariant latch value must dominate the header phi");
1221 return true;
1222 }
1223
1224 // Ensure every user of the phi node (recursively) is dominated by the
1225 // previous value. The dominance requirement ensures the loop vectorizer will
1226 // not need to vectorize the initial value prior to the first iteration of the
1227 // loop.
1228 // TODO: Consider extending this sinking to handle memory instructions.
1229
1231 BasicBlock *PhiBB = Phi->getParent();
1233 auto TryToPushSinkCandidate = [&](Instruction *SinkCandidate) {
1234 // Cyclic dependence.
1235 if (Previous == SinkCandidate)
1236 return false;
1237
1238 if (!Seen.insert(SinkCandidate).second)
1239 return true;
1240 if (DT->dominates(Previous,
1241 SinkCandidate)) // We already are good w/o sinking.
1242 return true;
1243
1244 if (SinkCandidate->getParent() != PhiBB ||
1245 SinkCandidate->mayHaveSideEffects() ||
1246 SinkCandidate->mayReadFromMemory() || SinkCandidate->isTerminator())
1247 return false;
1248
1249 // If we reach a PHI node that is not dominated by Previous, we reached a
1250 // header PHI. No need for sinking.
1251 if (isa<PHINode>(SinkCandidate))
1252 return true;
1253
1254 // Sink User tentatively and check its users
1255 WorkList.push_back(SinkCandidate);
1256 return true;
1257 };
1258
1259 WorkList.push_back(Phi);
1260 // Try to recursively sink instructions and their users after Previous.
1261 while (!WorkList.empty()) {
1262 Instruction *Current = WorkList.pop_back_val();
1263 for (Instruction *User : Current->users()) {
1264 if (!TryToPushSinkCandidate(User))
1265 return false;
1266 }
1267 }
1268
1269 return true;
1270}
1271
1273 switch (Kind) {
1274 case RecurKind::Sub:
1275 return Instruction::Sub;
1277 case RecurKind::Add:
1278 return Instruction::Add;
1279 case RecurKind::Mul:
1280 return Instruction::Mul;
1281 case RecurKind::Or:
1282 return Instruction::Or;
1283 case RecurKind::And:
1284 return Instruction::And;
1285 case RecurKind::Xor:
1286 return Instruction::Xor;
1287 case RecurKind::FMul:
1288 return Instruction::FMul;
1289 case RecurKind::FMulAdd:
1291 case RecurKind::FAdd:
1292 return Instruction::FAdd;
1293 case RecurKind::FSub:
1294 return Instruction::FSub;
1295 case RecurKind::SMax:
1296 case RecurKind::SMin:
1297 case RecurKind::UMax:
1298 case RecurKind::UMin:
1299 return Instruction::ICmp;
1300 case RecurKind::FMax:
1301 case RecurKind::FMin:
1306 return Instruction::FCmp;
1308 case RecurKind::AnyOf:
1309 case RecurKind::FindIV:
1310 // TODO: Set AnyOf and FindIV to Instruction::Select once in-loop reductions
1311 // are supported.
1312 default:
1313 llvm_unreachable("Unknown recurrence operation");
1314 }
1315}
1316
1319 SmallVector<Instruction *, 4> ReductionOperations;
1320 const bool IsMinMax = isMinMaxRecurrenceKind(Kind);
1321
1322 // Search down from the Phi to the LoopExitInstr, looking for instructions
1323 // with a single user of the correct type for the reduction.
1324
1325 // Note that we check that the type of the operand is correct for each item in
1326 // the chain, including the last (the loop exit value). This can come up from
1327 // sub, which would otherwise be treated as an add reduction. MinMax also need
1328 // to check for a pair of icmp/select, for which we use getNextInstruction and
1329 // isCorrectOpcode functions to step the right number of instruction, and
1330 // check the icmp/select pair.
1331 // FIXME: We also do not attempt to look through Select's yet, which might
1332 // be part of the reduction chain, or attempt to looks through And's to find a
1333 // smaller bitwidth. Subs are also currently not allowed (which are usually
1334 // treated as part of a add reduction) as they are expected to generally be
1335 // more expensive than out-of-loop reductions, and need to be costed more
1336 // carefully.
1337 unsigned ExpectedUses = 1;
1338 if (IsMinMax)
1339 ExpectedUses = 2;
1340
1341 auto getNextInstruction = [&](Instruction *Cur) -> Instruction * {
1342 for (Instruction *UI : Cur->users()) {
1343 if (isa<PHINode>(UI))
1344 continue;
1345 if (IsMinMax) {
1346 // We are expecting a icmp/select pair, which we go to the next select
1347 // instruction if we can. We already know that Cur has 2 uses.
1348 if (isa<SelectInst>(UI))
1349 return UI;
1350 continue;
1351 }
1352 return UI;
1353 }
1354 return nullptr;
1355 };
1356 auto isCorrectOpcode = [&](Instruction *Cur) {
1357 if (IsMinMax) {
1358 Value *LHS, *RHS;
1360 matchSelectPattern(Cur, LHS, RHS).Flavor);
1361 }
1362 // Recognize a call to the llvm.fmuladd intrinsic.
1363 if (isFMulAddIntrinsic(Cur))
1364 return true;
1365
1366 if (Cur->getOpcode() == Instruction::Sub &&
1368 return true;
1369
1370 if (Cur->getOpcode() == Instruction::FSub &&
1372 return true;
1373
1374 return Cur->getOpcode() == getOpcode();
1375 };
1376
1377 // Attempt to look through Phis which are part of the reduction chain
1378 unsigned ExtraPhiUses = 0;
1379 Instruction *RdxInstr = LoopExitInstr;
1380 if (auto ExitPhi = dyn_cast<PHINode>(LoopExitInstr)) {
1381 if (ExitPhi->getNumIncomingValues() != 2)
1382 return {};
1383
1384 Instruction *Inc0 = dyn_cast<Instruction>(ExitPhi->getIncomingValue(0));
1385 Instruction *Inc1 = dyn_cast<Instruction>(ExitPhi->getIncomingValue(1));
1386
1387 Instruction *Chain = nullptr;
1388 if (Inc0 == Phi)
1389 Chain = Inc1;
1390 else if (Inc1 == Phi)
1391 Chain = Inc0;
1392 else
1393 return {};
1394
1395 RdxInstr = Chain;
1396 ExtraPhiUses = 1;
1397 }
1398
1399 // The loop exit instruction we check first (as a quick test) but add last. We
1400 // check the opcode is correct (and dont allow them to be Subs) and that they
1401 // have expected to have the expected number of uses. They will have one use
1402 // from the phi and one from a LCSSA value, no matter the type.
1403 if (!isCorrectOpcode(RdxInstr) || !LoopExitInstr->hasNUses(2))
1404 return {};
1405
1406 // Check that the Phi has one (or two for min/max) uses, plus an extra use
1407 // for conditional reductions.
1408 if (!Phi->hasNUses(ExpectedUses + ExtraPhiUses))
1409 return {};
1410
1411 Instruction *Cur = getNextInstruction(Phi);
1412
1413 // Each other instruction in the chain should have the expected number of uses
1414 // and be the correct opcode.
1415 while (Cur != RdxInstr) {
1416 if (!Cur || !isCorrectOpcode(Cur) || !Cur->hasNUses(ExpectedUses))
1417 return {};
1418
1419 ReductionOperations.push_back(Cur);
1420 Cur = getNextInstruction(Cur);
1421 }
1422
1423 ReductionOperations.push_back(Cur);
1424 return ReductionOperations;
1425}
1426
1428 Value *Start, InductionKind K, const SCEV *Step, BinaryOperator *BOp,
1431 : StartValue(Start), IK(K), Step(Step), InductionBinOp(BOp) {
1432 assert(IK != IK_NoInduction && "Not an induction");
1433
1434 // Start value type should match the induction kind and the value
1435 // itself should not be null.
1436 assert(StartValue && "StartValue is null");
1437 assert((IK != IK_PtrInduction || StartValue->getType()->isPointerTy()) &&
1438 "StartValue is not a pointer for pointer induction");
1439 assert((IK != IK_IntInduction || StartValue->getType()->isIntegerTy()) &&
1440 "StartValue is not an integer for integer induction");
1441
1442 // Check the Step Value. It should be non-zero integer value.
1443 assert((!getConstStepValue() || !getConstStepValue()->isZero()) &&
1444 "Step value is zero");
1445
1446 assert((IK == IK_FpInduction || Step->getType()->isIntegerTy()) &&
1447 "StepValue is not an integer");
1448
1449 assert((IK != IK_FpInduction || Step->getType()->isFloatingPointTy()) &&
1450 "StepValue is not FP for FpInduction");
1451 assert((IK != IK_FpInduction ||
1452 (InductionBinOp &&
1453 (InductionBinOp->getOpcode() == Instruction::FAdd ||
1454 InductionBinOp->getOpcode() == Instruction::FSub))) &&
1455 "Binary opcode should be specified for FP induction");
1456
1457 if (Casts)
1458 llvm::append_range(RedundantCasts, *Casts);
1459 llvm::append_range(NoWrapPredicates, NoWrapPreds);
1460}
1461
1467
1468std::optional<APInt> InductionDescriptor::getConstStepValue() const {
1469 if (auto *ConstStep = dyn_cast<SCEVConstant>(Step))
1470 return ConstStep->getValue()->getValue();
1471 return {};
1472}
1473
1475 ScalarEvolution *SE,
1477
1478 // Here we only handle FP induction variables.
1479 assert(Phi->getType()->isFloatingPointTy() && "Unexpected Phi type");
1480
1481 if (TheLoop->getHeader() != Phi->getParent())
1482 return false;
1483
1484 // The loop may have multiple entrances or multiple exits; we can analyze
1485 // this phi if it has a unique entry value and a unique backedge value.
1486 if (Phi->getNumIncomingValues() != 2)
1487 return false;
1488 Value *BEValue = nullptr, *StartValue = nullptr;
1489 if (TheLoop->contains(Phi->getIncomingBlock(0))) {
1490 BEValue = Phi->getIncomingValue(0);
1491 StartValue = Phi->getIncomingValue(1);
1492 } else {
1493 assert(TheLoop->contains(Phi->getIncomingBlock(1)) &&
1494 "Unexpected Phi node in the loop");
1495 BEValue = Phi->getIncomingValue(1);
1496 StartValue = Phi->getIncomingValue(0);
1497 }
1498
1500 if (!BOp)
1501 return false;
1502
1503 Value *Addend = nullptr;
1504 if (BOp->getOpcode() == Instruction::FAdd) {
1505 if (BOp->getOperand(0) == Phi)
1506 Addend = BOp->getOperand(1);
1507 else if (BOp->getOperand(1) == Phi)
1508 Addend = BOp->getOperand(0);
1509 } else if (BOp->getOpcode() == Instruction::FSub)
1510 if (BOp->getOperand(0) == Phi)
1511 Addend = BOp->getOperand(1);
1512
1513 if (!Addend)
1514 return false;
1515
1516 // The addend should be loop invariant
1517 if (auto *I = dyn_cast<Instruction>(Addend))
1518 if (TheLoop->contains(I))
1519 return false;
1520
1521 // FP Step has unknown SCEV
1522 const SCEV *Step = SE->getUnknown(Addend);
1523 D = InductionDescriptor(StartValue, IK_FpInduction, Step, BOp);
1524 return true;
1525}
1526
1527/// This function is called when we suspect that the update-chain of a phi node
1528/// (whose symbolic SCEV expression sin \p PhiScev) contains redundant casts,
1529/// that can be ignored. (This can happen when the PSCEV rewriter adds a runtime
1530/// predicate P under which the SCEV expression for the phi can be the
1531/// AddRecurrence \p AR; See createAddRecFromPHIWithCast). We want to find the
1532/// cast instructions that are involved in the update-chain of this induction.
1533/// A caller that adds the required runtime predicate can be free to drop these
1534/// cast instructions, and compute the phi using \p AR (instead of some scev
1535/// expression with casts).
1536///
1537/// For example, without a predicate the scev expression can take the following
1538/// form:
1539/// (Ext ix (Trunc iy ( Start + i*Step ) to ix) to iy)
1540///
1541/// It corresponds to the following IR sequence:
1542/// %for.body:
1543/// %x = phi i64 [ 0, %ph ], [ %add, %for.body ]
1544/// %casted_phi = "ExtTrunc i64 %x"
1545/// %add = add i64 %casted_phi, %step
1546///
1547/// where %x is given in \p PN,
1548/// PSE.getSCEV(%x) is equal to PSE.getSCEV(%casted_phi) under a predicate,
1549/// and the IR sequence that "ExtTrunc i64 %x" represents can take one of
1550/// several forms, for example, such as:
1551/// ExtTrunc1: %casted_phi = and %x, 2^n-1
1552/// or:
1553/// ExtTrunc2: %t = shl %x, m
1554/// %casted_phi = ashr %t, m
1555///
1556/// If we are able to find such sequence, we return the instructions
1557/// we found, namely %casted_phi and the instructions on its use-def chain up
1558/// to the phi (not including the phi).
1559static bool
1561 const SCEVUnknown *PhiScev, const SCEVAddRecExpr *AR,
1563 ArrayRef<const SCEVPredicate *> NoWrapPreds) {
1564
1565 assert(CastInsts.empty() && "CastInsts is expected to be empty.");
1566 auto *PN = cast<PHINode>(PhiScev->getValue());
1567
1568 // Build a predicate to rewrite SCEVs of values in the cast chain using the
1569 // predicates needed for this induction.
1570 ScalarEvolution &SE = *PSE.getSE();
1571 SCEVUnionPredicate NoWrapUnionPred(NoWrapPreds, SE);
1572 const Loop *L = AR->getLoop();
1573 assert(SE.rewriteUsingPredicate(SE.getSCEV(PN), L, NoWrapUnionPred) == AR &&
1574 "Unexpected phi node SCEV expression");
1575
1576 // Find any cast instructions that participate in the def-use chain of
1577 // PhiScev in the loop.
1578 // FORNOW/TODO: We currently expect the def-use chain to include only
1579 // two-operand instructions, where one of the operands is an invariant.
1580 // createAddRecFromPHIWithCasts() currently does not support anything more
1581 // involved than that, so we keep the search simple. This can be
1582 // extended/generalized as needed.
1583
1584 auto getDef = [&](const Value *Val) -> Value * {
1585 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Val);
1586 if (!BinOp)
1587 return nullptr;
1588 Value *Op0 = BinOp->getOperand(0);
1589 Value *Op1 = BinOp->getOperand(1);
1590 Value *Def = nullptr;
1591 if (L->isLoopInvariant(Op0))
1592 Def = Op1;
1593 else if (L->isLoopInvariant(Op1))
1594 Def = Op0;
1595 return Def;
1596 };
1597
1598 // Look for the instruction that defines the induction via the
1599 // loop backedge.
1600 BasicBlock *Latch = L->getLoopLatch();
1601 if (!Latch)
1602 return false;
1603 Value *Val = PN->getIncomingValueForBlock(Latch);
1604 if (!Val)
1605 return false;
1606
1607 // Follow the def-use chain until the induction phi is reached.
1608 // If on the way we encounter a Value that has the same SCEV Expr as the
1609 // phi node, we can consider the instructions we visit from that point
1610 // as part of the cast-sequence that can be ignored.
1611 bool InCastSequence = false;
1612 auto *Inst = dyn_cast<Instruction>(Val);
1613 while (Val != PN) {
1614 // If we encountered a phi node other than PN, or if we left the loop,
1615 // we bail out.
1616 if (!Inst || !L->contains(Inst)) {
1617 return false;
1618 }
1619 // Create AddRec with NoWrapPredicates applied.
1620 auto *AddRec = dyn_cast<SCEVAddRecExpr>(
1621 SE.rewriteUsingPredicate(SE.getSCEV(Val), L, NoWrapUnionPred));
1622 if (AddRec && PSE.areAddRecsEqualWithPreds(AddRec, AR, NoWrapPreds))
1623 InCastSequence = true;
1624 if (InCastSequence) {
1625 // Only the last instruction in the cast sequence is expected to have
1626 // uses outside the induction def-use chain.
1627 if (!CastInsts.empty())
1628 if (!Inst->hasOneUse())
1629 return false;
1630 CastInsts.push_back(Inst);
1631 }
1632 Val = getDef(Val);
1633 if (!Val)
1634 return false;
1635 Inst = dyn_cast<Instruction>(Val);
1636 }
1637
1638 return InCastSequence;
1639}
1640
1643 InductionDescriptor &D, bool Assume) {
1644 Type *PhiTy = Phi->getType();
1645
1646 // Handle integer and pointer inductions variables.
1647 // Now we handle also FP induction but not trying to make a
1648 // recurrent expression from the PHI node in-place.
1649
1650 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy() && !PhiTy->isFloatTy() &&
1651 !PhiTy->isDoubleTy() && !PhiTy->isHalfTy())
1652 return false;
1653
1654 if (PhiTy->isFloatingPointTy())
1655 return isFPInductionPHI(Phi, TheLoop, PSE.getSE(), D);
1656
1657 const SCEV *PhiScev = PSE.getSCEV(Phi);
1658 const auto *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
1659
1660 // Collect predicates needed to force the SCEV into an AddRecExpr.
1662
1663 // We need this expression to be an AddRecExpr.
1664 if (Assume && !AR)
1665 AR = PSE.getAsAddRec(Phi, &Preds);
1666
1667 if (!AR) {
1668 LLVM_DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
1669 return false;
1670 }
1671
1672 // Record any Cast instructions that participate in the induction update
1673 const auto *SymbolicPhi = dyn_cast<SCEVUnknown>(PhiScev);
1674 // If we started from an UnknownSCEV, and managed to build an addRecurrence
1675 // only after enabling Assume with PSCEV, this means we may have encountered
1676 // cast instructions that required adding a runtime check in order to
1677 // guarantee the correctness of the AddRecurrence respresentation of the
1678 // induction.
1679 if (PhiScev != AR && SymbolicPhi) {
1681 if (getCastsForInductionPHI(PSE, SymbolicPhi, AR, Casts, Preds))
1682 return isInductionPHI(Phi, TheLoop, PSE.getSE(), D, Preds, AR, &Casts);
1683 }
1684
1685 return isInductionPHI(Phi, TheLoop, PSE.getSE(), D, Preds, AR);
1686}
1687
1689 PHINode *Phi, const Loop *TheLoop, ScalarEvolution *SE,
1691 const SCEV *Expr, SmallVectorImpl<Instruction *> *CastsToIgnore) {
1692 Type *PhiTy = Phi->getType();
1693 // isSCEVable returns true for integer and pointer types.
1694 if (!SE->isSCEVable(PhiTy))
1695 return false;
1696
1697 // Check that the PHI is consecutive.
1698 const SCEV *PhiScev = Expr ? Expr : SE->getSCEV(Phi);
1699 const SCEV *Step;
1700
1701 // FIXME: We are currently matching the specific loop TheLoop; if it doesn't
1702 // match, we should treat it as a uniform. Unfortunately, we don't currently
1703 // know how to handled uniform PHIs.
1704 if (!match(PhiScev, m_scev_AffineAddRec(m_SCEV(), m_SCEV(Step),
1705 m_SpecificLoop(TheLoop)))) {
1706 LLVM_DEBUG(
1707 dbgs() << "LV: PHI is not a poly recurrence for requested loop.\n");
1708 return false;
1709 }
1710
1711 // This function assumes that InductionPhi is called only on Phi nodes
1712 // present inside loop headers. Check for the same, and throw an assert if
1713 // the current Phi is not present inside the loop header.
1714 assert(Phi->getParent() == TheLoop->getHeader() &&
1715 "Invalid Phi node, not present in loop header");
1716
1717 if (!TheLoop->getLoopPreheader())
1718 return false;
1719
1720 Value *StartValue =
1721 Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
1722
1723 BasicBlock *Latch = TheLoop->getLoopLatch();
1724 if (!Latch)
1725 return false;
1726
1727 if (PhiTy->isIntegerTy()) {
1728 BinaryOperator *BOp =
1729 dyn_cast<BinaryOperator>(Phi->getIncomingValueForBlock(Latch));
1730 D = InductionDescriptor(StartValue, IK_IntInduction, Step, BOp,
1731 CastsToIgnore, Preds);
1732 return true;
1733 }
1734
1735 assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
1736
1737 // This allows induction variables w/non-constant steps.
1738 D = InductionDescriptor(StartValue, IK_PtrInduction, Step,
1739 /*InductionBinOp=*/nullptr, /*Casts=*/nullptr, Preds);
1740 return true;
1741}
1742
1743// Recognize a conditional induction PHI by matching the following pattern:
1744// loop_header:
1745// %conditional_iv = phi [ %start, %preheader ], [ %latch_phi, %latch ]
1746// br i1 %do_step, label %step_bb, label %latch
1747//
1748// step_bb:
1749// %step = add/gep %conditional_iv, %step_val
1750// br label %latch
1751//
1752// latch:
1753// %latch_phi = phi [ %conditional_iv, %loop_header ], [ %step, %step_bb ]
1754// br label %loop_header
1757 ScalarEvolution &SE) {
1758 BasicBlock *Preheader = L->getLoopPreheader();
1759 if (!Preheader)
1760 return false;
1761
1762 BasicBlock *Latch = L->getLoopLatch();
1763 if (!Latch || !PN->getType()->isIntOrPtrTy() ||
1764 PN->getParent() != L->getHeader())
1765 return false;
1766
1767 auto *BackedgePHI = dyn_cast<PHINode>(PN->getIncomingValueForBlock(Latch));
1768 if (!BackedgePHI)
1769 return false;
1770
1771 // Ensure the only users of the backedge PHI are outside the loop or the
1772 // header PHI (PN).
1773 for (Instruction *UI : BackedgePHI->users()) {
1774 if (UI != PN && L->contains(UI))
1775 return false;
1776 }
1777
1778 // Find the step operation used to increment the conditional induction PHI.
1779 // TODO: Support chains of PHIs.
1780 Value *StepOp =
1781 find_singleton<Value>(BackedgePHI->incoming_values(),
1782 [&](Use &Incoming, bool /*AllowRepeats*/) {
1783 return Incoming != PN ? Incoming.get() : nullptr;
1784 });
1785 if (!StepOp || !StepOp->hasOneUse())
1786 return false;
1787
1788 auto *StepInst = dyn_cast<Instruction>(StepOp);
1789 if (!StepInst)
1790 return false;
1791
1792 const DataLayout &DL = SE.getDataLayout();
1793 Value *Step = nullptr;
1794 bool StepMatch =
1795 PN->getType()->isPointerTy()
1796 ? match(StepInst, m_PtrAdd(DL, m_Specific(PN), m_Value(Step)))
1797 : match(StepInst, m_c_Add(m_Specific(PN), m_Value(Step)));
1798 if (!StepMatch || !L->isLoopInvariant(Step))
1799 return false;
1800
1801 const SCEV *StepSCEV = SE.getSCEV(Step);
1802 if (StepSCEV->isZero())
1803 return false;
1804
1805 Value *Start = PN->getIncomingValueForBlock(Preheader);
1806 const SCEV *StartSCEV = SE.getSCEV(Start);
1807
1808 SCEVFlags NoWrapFlags = SCEV::FlagNone;
1809 if (auto *GEP = dyn_cast<GEPOperator>(StepInst)) {
1810 // With NUSW, we can add NUW if the step is non-negative. We can't add NSW
1811 // as the base address is unsigned.
1812 if (GEP->hasNoUnsignedWrap() ||
1813 (GEP->hasNoUnsignedSignedWrap() && SE.isKnownNonNegative(StepSCEV)))
1814 NoWrapFlags = ScalarEvolution::setFlags(NoWrapFlags, SCEV::FlagNUW);
1815 } else if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(StepInst)) {
1816 if (OBO->hasNoUnsignedWrap())
1817 NoWrapFlags = ScalarEvolution::setFlags(NoWrapFlags, SCEV::FlagNUW);
1818 if (OBO->hasNoSignedWrap())
1819 NoWrapFlags = ScalarEvolution::setFlags(NoWrapFlags, SCEV::FlagNSW);
1820 }
1821
1822 LLVM_DEBUG(dbgs() << "LV: Found a conditional induction phi: HeaderPHI: "
1823 << *PN << ", StepInst: " << *StepInst << "\n");
1824
1825 Desc = ConditionalInductionDescriptor(PN, BackedgePHI, StepInst, StartSCEV,
1826 StepSCEV, NoWrapFlags);
1827 return true;
1828}
1829
1830SCEVUse
1832 const Loop &L) const {
1833 assert(L.contains(HeaderPHI) &&
1834 "The provided loop does not contain this conditional induction");
1835 return SE.getAddRecExpr(
1836 getStartSCEV(), getStepSCEV(), &L,
1838}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
AMDGPU Register Bank Select
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Hexagon Common GEP
static bool getCastsForInductionPHI(PredicatedScalarEvolution &PSE, const SCEVUnknown *PhiScev, const SCEVAddRecExpr *AR, SmallVectorImpl< Instruction * > &CastInsts, ArrayRef< const SCEVPredicate * > NoWrapPreds)
This function is called when we suspect that the update-chain of a phi node (whose symbolic SCEV expr...
static std::optional< FastMathFlags > hasRequiredFastMathFlags(FPMathOperator *FPOp, RecurKind &RK)
static bool checkOrderedReduction(RecurKind Kind, Instruction *ExactFPMathInst, Instruction *Exit, PHINode *Phi)
static bool isFindLastLikePhi(PHINode *Phi, PHINode *HeaderPhi, SmallPtrSetImpl< Instruction * > &ReductionInstrs)
static Instruction * lookThroughAnd(PHINode *Phi, Type *&RT, SmallPtrSetImpl< Instruction * > &Visited, SmallPtrSetImpl< Instruction * > &CI)
Determines if Phi may have been type-promoted.
static FastMathFlags collectMinMaxFMF(Value *V)
static RecurrenceDescriptor getMinMaxRecurrence(PHINode *Phi, Loop *TheLoop, ScalarEvolution *SE)
static void collectCastInstrs(Loop *TheLoop, Instruction *Exit, Type *RecurrenceType, SmallPtrSetImpl< Instruction * > &Casts, Type *&MinWidthCastToRecurTy)
Collect cast instructions that can be ignored in the vectorizer's cost model, given a reduction exit ...
static std::pair< Type *, bool > computeRecurrenceType(Instruction *Exit, DemandedBits *DB, AssumptionCache *AC, DominatorTree *DT)
Compute the minimal bit width needed to represent a reduction whose exit instruction is given by Exit...
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition Lint.cpp:550
SmallVector< MachineOperand, 4 > Cond
#define I(x, y, z)
Definition MD5.cpp:57
#define LLVM_DEBUG(...)
Definition Debug.h:119
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
Class for arbitrary precision integers.
Definition APInt.h:78
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition BasicBlock.h:61
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:212
BinaryOps getOpcode() const
Definition InstrTypes.h:409
SCEVFlags getSCEVNoWrapFlags() const
Returns the SCEV no-wrap flags that apply to StepInst.
LLVM_ABI SCEVUse getUnconditionalAddRec(ScalarEvolution &SE, const Loop &L) const
Returns an over-approximation of the conditional induction as a SCEVAddRec assuming the condition is ...
static LLVM_ABI bool isConditionalInductionPHI(PHINode *PN, const Loop *L, ConditionalInductionDescriptor &Desc, ScalarEvolution &SE)
Returns true if PN is a conditional induction variable in the loop L.
const SCEV * getStartSCEV() const
Returns a SCEV expression for the initial value of the conditional induction PHI.
const SCEV * getStepSCEV() const
Returns a SCEV expression for the step of the conditional induction PHI.
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
Utility class for floating point operations which can have information about relaxed accuracy require...
Definition Operator.h:202
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
static FastMathFlags getFast()
Definition FMF.h:50
A struct for saving information about induction variables.
static LLVM_ABI InductionDescriptor getCanonicalIntInduction(Type *Ty, ScalarEvolution &SE)
Returns the canonical integer induction for type Ty with start = 0 and step = 1.
LLVM_ABI std::optional< APInt > getConstStepValue() const
static LLVM_ABI bool isInductionPHI(PHINode *Phi, const Loop *L, ScalarEvolution *SE, InductionDescriptor &D, ArrayRef< const SCEVPredicate * > NoWrapPreds={}, const SCEV *Expr=nullptr, SmallVectorImpl< Instruction * > *CastsToIgnore=nullptr)
Returns true if Phi is an induction in the loop L.
@ IK_FpInduction
Floating point induction variable.
@ IK_PtrInduction
Pointer induction var. Step = C.
@ IK_IntInduction
Integer induction variable. Step = C.
static LLVM_ABI bool isFPInductionPHI(PHINode *Phi, const Loop *L, ScalarEvolution *SE, InductionDescriptor &D)
Returns true if Phi is a floating point induction in the loop L.
InductionDescriptor()=default
Default constructor - creates an invalid induction.
LLVM_ABI bool isCommutative() const LLVM_READONLY
Return true if the instruction is commutative:
LLVM_ABI bool comesBefore(const Instruction *Other) const
Given an instruction Other in the same basic block as this instruction, return true if this instructi...
iterator_range< user_iterator > users()
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:333
bool contains(const LoopT *L) const
Return true if the specified loop is contained within this loop.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
BlockT * getHeader() const
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
LLVM_ABI bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
Definition LoopInfo.cpp:64
Value * getIncomingValueForBlock(const BasicBlock *BB) const
An interface layer with SCEV used to manage how we see SCEV expressions for values in the context of ...
ScalarEvolution * getSE() const
Returns the ScalarEvolution analysis used.
LLVM_ABI bool areAddRecsEqualWithPreds(const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2, ArrayRef< const SCEVPredicate * > ExtraPreds={}) const
Check if AR1 and AR2 are equal, while taking into account Equal predicates in Preds and ExtraPreds.
LLVM_ABI const SCEVAddRecExpr * getAsAddRec(Value *V, SmallVectorImpl< const SCEVPredicate * > *WrapPredsAdded=nullptr)
Attempts to produce an AddRecExpr for V by adding additional SCEV predicates.
LLVM_ABI const SCEV * getSCEV(Value *V)
Returns the SCEV expression of V, in the context of the current SCEV predicate.
This POD struct holds information about a potential recurrence operation.
Instruction * getExactFPMathInst() const
The RecurrenceDescriptor is used to identify recurrences variables in a loop.
static bool isFPMinMaxRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is a floating-point min/max kind.
static bool isFMulAddIntrinsic(Instruction *I)
Returns true if the instruction is a call to the llvm.fmuladd intrinsic.
static LLVM_ABI bool isFixedOrderRecurrence(PHINode *Phi, Loop *TheLoop, DominatorTree *DT)
Returns true if Phi is a fixed-order recurrence.
static LLVM_ABI InstDesc isConditionalRdxPattern(Instruction *I)
Returns a struct describing if the instruction is a Select(FCmp(X, Y), (Z = X op PHINode),...
static LLVM_ABI bool hasMultipleUsesOf(Instruction *I, SmallPtrSetImpl< Instruction * > &Insts, unsigned MaxNumUses)
Returns true if instruction I has multiple uses in Insts.
static LLVM_ABI bool isReductionPHI(PHINode *Phi, Loop *TheLoop, RecurrenceDescriptor &RedDes, DemandedBits *DB=nullptr, AssumptionCache *AC=nullptr, DominatorTree *DT=nullptr, ScalarEvolution *SE=nullptr)
Returns true if Phi is a reduction in TheLoop.
static LLVM_ABI bool areAllUsesIn(Instruction *I, SmallPtrSetImpl< Instruction * > &Set)
Returns true if all uses of the instruction I is within the Set.
LLVM_ABI SmallVector< Instruction *, 4 > getReductionOpChain(PHINode *Phi, Loop *L) const
Attempts to find a chain of operations from Phi to LoopExitInst that can be treated as a set of reduc...
static bool isAnyOfRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cond,x,y) where one of (x,...
static LLVM_ABI InstDesc isAnyOfPattern(Loop *Loop, PHINode *OrigPhi, Instruction *I, InstDesc &Prev)
Returns a struct describing whether the instruction is a Select(Cond, X, Y) where one of (X,...
static LLVM_ABI bool isSubRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is for a sub operation.
StoreInst * IntermediateStore
Reductions may store temporary or final result to an invariant address.
static bool isFindRecurrenceKind(RecurKind Kind)
static LLVM_ABI bool isFloatingPointRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is a floating point kind.
static LLVM_ABI InstDesc isRecurrenceInstr(Loop *L, PHINode *Phi, Instruction *I, RecurKind Kind, InstDesc &Prev, ScalarEvolution *SE)
Returns a struct describing if the instruction 'I' can be a recurrence variable of type 'Kind' for a ...
static LLVM_ABI bool AddReductionVar(PHINode *Phi, RecurKind Kind, Loop *TheLoop, RecurrenceDescriptor &RedDes, DemandedBits *DB=nullptr, AssumptionCache *AC=nullptr, DominatorTree *DT=nullptr, ScalarEvolution *SE=nullptr)
Returns true if Phi is a reduction of type Kind and adds it to the RecurrenceDescriptor.
static LLVM_ABI InstDesc isFindPattern(Loop *TheLoop, PHINode *OrigPhi, Instruction *I, ScalarEvolution &SE)
Returns a struct describing whether the instruction is either a Select(ICmp(A, B),...
static LLVM_ABI bool isIntegerRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is an integer kind.
static bool isMinMaxRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is any min/max kind.
This node represents a polynomial recurrence on the trip count of the specified loop.
This class represents a composition of other SCEV predicates, and is the class that most clients will...
This means that we are dealing with an entirely unknown SCEV value, and only represent it as its LLVM...
This class represents an analyzed expression in the program.
static constexpr auto FlagNUW
static constexpr auto FlagNSW
Type * getType() const
Return the LLVM type of this SCEV expression.
static constexpr auto FlagNone
The main scalar evolution driver.
const DataLayout & getDataLayout() const
Return the DataLayout associated with the module this SCEV instance is operating on.
LLVM_ABI bool isKnownNonNegative(const SCEV *S)
Test if the given expression is known to be non-negative.
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
static SCEVFlags setFlags(SCEVFlags Flags, SCEVFlags OnFlags)
const SCEV * getOne(Type *Ty)
Return a SCEV for the constant 1 of a specific type.
LLVM_ABI SCEVUse getAddRecExpr(SCEVUse Start, SCEVUse Step, const Loop *L, SCEVFlagsPair Flags)
Get an add recurrence expression for the specified loop.
LLVM_ABI bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
LLVM_ABI bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
LLVM_ABI const SCEV * getUnknown(Value *V)
LLVM_ABI const SCEV * rewriteUsingPredicate(const SCEV *S, const Loop *L, const SCEVPredicate &A)
Re-writes the SCEV according to the Predicates in A.
This class represents the LLVM 'select' instruction.
const Value * getCondition() const
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
Value * getValueOperand()
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition Type.h:155
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.h:354
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:370
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
Definition Type.h:144
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
Definition Type.h:158
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
Definition Type.h:265
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:298
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
iterator_range< user_iterator > users()
Definition Value.h:428
LLVM_ABI bool hasNUses(unsigned N) const
Return true if this Value has exactly N uses.
Definition Value.cpp:142
bool use_empty() const
Definition Value.h:348
const ParentTy * getParent() const
Definition ilist_node.h:34
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
auto m_Cmp()
Matches any compare instruction and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::FSub > m_FSub(const LHS &L, const RHS &R)
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
BinaryOp_match< LHS, RHS, Instruction::FMul > m_FMul(const LHS &L, const RHS &R)
bool match(Val *V, const Pattern &P)
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
auto m_UMin(const Opnd0 &Op0, const Opnd1 &Op1)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
auto m_SMax(const Opnd0 &Op0, const Opnd1 &Op1)
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_UMax(const Opnd0 &Op0, const Opnd1 &Op1)
auto m_FMinimum(const Opnd0 &Op0, const Opnd1 &Op1)
auto m_Value()
Match an arbitrary value and ignore it.
BinaryOp_match< LHS, RHS, Instruction::FAdd > m_FAdd(const LHS &L, const RHS &R)
auto m_FMaximum(const Opnd0 &Op0, const Opnd1 &Op1)
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
match_combine_or< FMaxMin_match< LHS, RHS, ofmin_pred_ty >, FMaxMin_match< LHS, RHS, ufmin_pred_ty > > m_OrdOrUnordFMin(const LHS &L, const RHS &R)
Match an 'ordered' or 'unordered' floating point minimum function.
PtrAdd_match< PointerOpTy, OffsetOpTy > m_PtrAdd(const DataLayout &DL, const PointerOpTy &PointerOp, const OffsetOpTy &OffsetOp)
Matches GEP with i8 source element type and canonical index type.
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
auto m_SMin(const Opnd0 &Op0, const Opnd1 &Op1)
match_combine_or< FMaxMin_match< LHS, RHS, ofmax_pred_ty >, FMaxMin_match< LHS, RHS, ufmax_pred_ty > > m_OrdOrUnordFMax(const LHS &L, const RHS &R)
Match an 'ordered' or 'unordered' floating point maximum function.
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
specificloop_ty m_SpecificLoop(const Loop *L)
SCEVAffineAddRec_match< Op0_t, Op1_t, match_isa< const Loop > > m_scev_AffineAddRec(const Op0_t &Op0, const Op1_t &Op1)
This is an optimization pass for GlobalISel generic memory operations.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
MachineInstr * getDef(const MachineOperand &MO, const MachineRegisterInfo *MRI)
SCEVUseT< const SCEV * > SCEVUse
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
T bit_ceil(T Value)
Returns the smallest integral power of two no smaller than Value if Value is nonzero.
Definition bit.h:362
Op::Description Desc
LLVM_ABI unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Return the number of times the sign bit of the register is replicated into the other bits.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
FPOp
The floating-point operations supported by the folding helpers.
Definition FPFold.h:25
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
T * find_singleton(R &&Range, Predicate P, bool AllowRepeats=false)
Return the single value in Range that satisfies P(<member of Range> *, AllowRepeats)->T * returning n...
Definition STLExtras.h:1853
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
RecurKind
These are the kinds of recurrences that we support.
@ UMin
Unsigned integer min implemented in terms of select(cmp()).
@ FMinimumNum
FP min with llvm.minimumnum semantics.
@ FindIV
FindIV reduction with select(icmp(),x,y) where one of (x,y) is a loop induction variable (increasing ...
@ Or
Bitwise or logical OR of integers.
@ FMaxSelectNoFMF
FMax as select(cmp()) lacking nnan or nsz, on IEEE types with IEEE denormals.
@ FMinimum
FP min with llvm.minimum semantics.
@ FMaxNum
FP max with llvm.maxnum semantics including NaNs.
@ Mul
Product of integers.
@ FSub
Subtraction of floats.
@ FAddChainWithSubs
A chain of fadds and fsubs.
@ None
Not a recurrence.
@ AnyOf
AnyOf reduction with select(cond,x,y) where one of (x,y) is loop invariant, and both x and y are inte...
@ Xor
Bitwise or logical XOR of integers.
@ FindLast
FindLast reduction with select(cmp(),x,y) where x and y.
@ FMax
FP max as select(cmp()) with nnan/nsz, or llvm.maxnum.
@ FMinSelectNoFMF
FMin as select(cmp()) lacking nnan or nsz, on IEEE types with IEEE denormals.
@ FMaximum
FP max with llvm.maximum semantics.
@ FMulAdd
Sum of float products with llvm.fmuladd(a * b + sum).
@ FMul
Product of floats.
@ SMax
Signed integer max implemented in terms of select(cmp()).
@ And
Bitwise or logical AND of integers.
@ SMin
Signed integer min implemented in terms of select(cmp()).
@ FMin
FP min as select(cmp()) with nnan/nsz, or llvm.minnum.
@ FMinNum
FP min with llvm.minnum semantics including NaNs.
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
@ AddChainWithSubs
A chain of adds and subs.
@ FAdd
Sum of floats.
@ FMaximumNum
FP max with llvm.maximumnum semantics.
@ UMax
Unsigned integer max implemented in terms of select(cmp()).
DWARFExpression::Operation Op
SCEVFlags
SCEVFlags are bitfield indices into SCEV's SubclassData.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
LLVM_ABI SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS, Instruction::CastOps *CastOp=nullptr)
Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind and providing the out param...
static constexpr DenormalMode getIEEE()
The no-wrap flags to apply when creating a SCEV expression, to the expression and use respectively.
static bool isMinOrMax(SelectPatternFlavor SPF)
When implementing this min/max pattern as fcmp; select, does the fcmp have to be ordered?