LLVM 23.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
95/// Compute the minimal bit width needed to represent a reduction whose exit
96/// instruction is given by Exit.
97static std::pair<Type *, bool> computeRecurrenceType(Instruction *Exit,
98 DemandedBits *DB,
100 DominatorTree *DT) {
101 bool IsSigned = false;
102 const DataLayout &DL = Exit->getDataLayout();
103 uint64_t MaxBitWidth = DL.getTypeSizeInBits(Exit->getType());
104
105 if (DB) {
106 // Use the demanded bits analysis to determine the bits that are live out
107 // of the exit instruction, rounding up to the nearest power of two. If the
108 // use of demanded bits results in a smaller bit width, we know the value
109 // must be positive (i.e., IsSigned = false), because if this were not the
110 // case, the sign bit would have been demanded.
111 auto Mask = DB->getDemandedBits(Exit);
112 MaxBitWidth = Mask.getBitWidth() - Mask.countl_zero();
113 }
114
115 if (MaxBitWidth == DL.getTypeSizeInBits(Exit->getType()) && AC && DT) {
116 // If demanded bits wasn't able to limit the bit width, we can try to use
117 // value tracking instead. This can be the case, for example, if the value
118 // may be negative.
119 auto NumSignBits = ComputeNumSignBits(Exit, DL, AC, nullptr, DT);
120 auto NumTypeBits = DL.getTypeSizeInBits(Exit->getType());
121 MaxBitWidth = NumTypeBits - NumSignBits;
122 KnownBits Bits = computeKnownBits(Exit, DL);
123 if (!Bits.isNonNegative()) {
124 // If the value is not known to be non-negative, we set IsSigned to true,
125 // meaning that we will use sext instructions instead of zext
126 // instructions to restore the original type.
127 IsSigned = true;
128 // Make sure at least one sign bit is included in the result, so it
129 // will get properly sign-extended.
130 ++MaxBitWidth;
131 }
132 }
133 MaxBitWidth = llvm::bit_ceil(MaxBitWidth);
134
135 return std::make_pair(Type::getIntNTy(Exit->getContext(), MaxBitWidth),
136 IsSigned);
137}
138
139/// Collect cast instructions that can be ignored in the vectorizer's cost
140/// model, given a reduction exit value and the minimal type in which the
141// reduction can be represented. Also search casts to the recurrence type
142// to find the minimum width used by the recurrence.
143static void collectCastInstrs(Loop *TheLoop, Instruction *Exit,
144 Type *RecurrenceType,
146 unsigned &MinWidthCastToRecurTy) {
147
150 Worklist.push_back(Exit);
151 MinWidthCastToRecurTy = -1U;
152
153 while (!Worklist.empty()) {
154 Instruction *Val = Worklist.pop_back_val();
155 Visited.insert(Val);
156 if (auto *Cast = dyn_cast<CastInst>(Val)) {
157 if (Cast->getSrcTy() == RecurrenceType) {
158 // If the source type of a cast instruction is equal to the recurrence
159 // type, it will be eliminated, and should be ignored in the vectorizer
160 // cost model.
161 Casts.insert(Cast);
162 continue;
163 }
164 if (Cast->getDestTy() == RecurrenceType) {
165 // The minimum width used by the recurrence is found by checking for
166 // casts on its operands. The minimum width is used by the vectorizer
167 // when finding the widest type for in-loop reductions without any
168 // loads/stores.
169 MinWidthCastToRecurTy = std::min<unsigned>(
170 MinWidthCastToRecurTy, Cast->getSrcTy()->getScalarSizeInBits());
171 continue;
172 }
173 }
174 // Add all operands to the work list if they are loop-varying values that
175 // we haven't yet visited.
176 for (Value *O : cast<User>(Val)->operands())
177 if (auto *I = dyn_cast<Instruction>(O))
178 if (TheLoop->contains(I) && !Visited.count(I))
179 Worklist.push_back(I);
180 }
181}
182
183// Check if a given Phi node can be recognized as an ordered reduction for
184// vectorizing floating point operations without unsafe math.
185static bool checkOrderedReduction(RecurKind Kind, Instruction *ExactFPMathInst,
186 Instruction *Exit, PHINode *Phi) {
187 // Currently only FAdd and FMulAdd are supported.
188 if (Kind != RecurKind::FAdd && Kind != RecurKind::FMulAdd)
189 return false;
190
191 if (Kind == RecurKind::FAdd && Exit->getOpcode() != Instruction::FAdd)
192 return false;
193
194 if (Kind == RecurKind::FMulAdd &&
196 return false;
197
198 // Ensure the exit instruction has only one user other than the reduction PHI
199 if (Exit != ExactFPMathInst || Exit->hasNUsesOrMore(3))
200 return false;
201
202 // The only pattern accepted is the one in which the reduction PHI
203 // is used as one of the operands of the exit instruction
204 auto *Op0 = Exit->getOperand(0);
205 auto *Op1 = Exit->getOperand(1);
206 if (Kind == RecurKind::FAdd && Op0 != Phi && Op1 != Phi)
207 return false;
208 if (Kind == RecurKind::FMulAdd && Exit->getOperand(2) != Phi)
209 return false;
210
211 LLVM_DEBUG(dbgs() << "LV: Found an ordered reduction: Phi: " << *Phi
212 << ", ExitInst: " << *Exit << "\n");
213
214 return true;
215}
216
217// Collect FMF from a value and its associated fcmp in select patterns
219 FastMathFlags FMF = cast<FPMathOperator>(V)->getFastMathFlags();
220 if (auto *Sel = dyn_cast<SelectInst>(V)) {
221 // Accept FMF from either fcmp or select in a min/max idiom.
222 // TODO: Remove this when FMF propagation is fixed or we standardize on
223 // intrinsics.
224 if (auto *FCmp = dyn_cast<FCmpInst>(Sel->getCondition()))
225 FMF |= FCmp->getFastMathFlags();
226 }
227 return FMF;
228}
229
230static std::optional<FastMathFlags>
232 bool HasRequiredFMF = FPOp && FPOp->hasNoNaNs() && FPOp->hasNoSignedZeros();
233 if (HasRequiredFMF)
234 return collectMinMaxFMF(FPOp);
235
236 switch (RK) {
241 break;
242
243 case RecurKind::FMax:
245 return std::nullopt;
247 break;
248 case RecurKind::FMin:
250 return std::nullopt;
252 break;
253 default:
254 return std::nullopt;
255 }
256 return collectMinMaxFMF(FPOp);
257}
258
260 ScalarEvolution *SE) {
261 Type *Ty = Phi->getType();
262 BasicBlock *Latch = TheLoop->getLoopLatch();
263 if (Phi->getNumIncomingValues() != 2 ||
264 Phi->getParent() != TheLoop->getHeader() ||
265 (!Ty->isIntegerTy() && !Ty->isFloatingPointTy()) || !Latch)
266 return {};
267
268 auto GetMinMaxRK = [](Value *V, Value *&A, Value *&B) -> RecurKind {
269 if (match(V, m_UMin(m_Value(A), m_Value(B))))
270 return RecurKind::UMin;
271 if (match(V, m_UMax(m_Value(A), m_Value(B))))
272 return RecurKind::UMax;
273 if (match(V, m_SMax(m_Value(A), m_Value(B))))
274 return RecurKind::SMax;
275 if (match(V, m_SMin(m_Value(A), m_Value(B))))
276 return RecurKind::SMin;
277 if (match(V, m_OrdOrUnordFMin(m_Value(A), m_Value(B))) ||
279 return RecurKind::FMin;
280 if (match(V, m_OrdOrUnordFMax(m_Value(A), m_Value(B))) ||
282 return RecurKind::FMax;
283 if (match(V, m_FMinimum(m_Value(A), m_Value(B))))
284 return RecurKind::FMinimum;
285 if (match(V, m_FMaximum(m_Value(A), m_Value(B))))
286 return RecurKind::FMaximum;
291 return RecurKind::None;
292 };
293
295 Value *BackedgeValue = Phi->getIncomingValueForBlock(Latch);
297 // Walk def-use chains upwards from BackedgeValue to identify min/max
298 // recurrences.
299 SmallVector<Value *> WorkList({BackedgeValue});
300 SmallPtrSet<Value *, 8> Chain({Phi});
301 while (!WorkList.empty()) {
302 Value *Cur = WorkList.pop_back_val();
303 if (!Chain.insert(Cur).second)
304 continue;
305 auto *I = dyn_cast<Instruction>(Cur);
306 if (!I || !TheLoop->contains(I))
307 return {};
308 if (auto *PN = dyn_cast<PHINode>(I)) {
309 append_range(WorkList, PN->operands());
310 continue;
311 }
312 Value *A, *B;
313 RecurKind CurRK = GetMinMaxRK(Cur, A, B);
314 if (CurRK == RecurKind::None || (RK != RecurKind::None && CurRK != RK))
315 return {};
316
317 RK = CurRK;
318 // Check required fast-math flags for FP recurrences.
320 auto CurFMF = hasRequiredFastMathFlags(cast<FPMathOperator>(Cur), RK);
321 if (!CurFMF)
322 return {};
323 FMF &= *CurFMF;
324 }
325
326 if (auto *SI = dyn_cast<SelectInst>(I))
327 Chain.insert(SI->getCondition());
328
329 if (A == Phi || B == Phi)
330 continue;
331
332 // Add operand to worklist if it matches the pattern (exactly one must
333 // match)
334 Value *X, *Y;
335 auto *IA = dyn_cast<Instruction>(A);
336 auto *IB = dyn_cast<Instruction>(B);
337 bool AMatches = IA && TheLoop->contains(IA) && GetMinMaxRK(A, X, Y) == RK;
338 bool BMatches = IB && TheLoop->contains(IB) && GetMinMaxRK(B, X, Y) == RK;
339 if (AMatches == BMatches) // Both or neither match
340 return {};
341 WorkList.push_back(AMatches ? A : B);
342 }
343
344 // Handle argmin/argmax pattern: PHI has uses outside the reduction chain
345 // that are not intermediate min/max operations (which are handled below).
346 // Requires integer min/max, and single-use BackedgeValue (so vectorizer can
347 // handle both PHIs together).
348 bool PhiHasInvalidUses = any_of(Phi->users(), [&](User *U) {
349 Value *A, *B;
350 return !Chain.contains(U) && TheLoop->contains(cast<Instruction>(U)) &&
351 GetMinMaxRK(U, A, B) == RecurKind::None;
352 });
353 if (PhiHasInvalidUses) {
355 !BackedgeValue->hasOneUse())
356 return {};
358 Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader()),
359 /*Exit=*/nullptr, /*Store=*/nullptr, RK, FastMathFlags(),
360 /*ExactFP=*/nullptr, Phi->getType(), /*IsMultiUse=*/true);
361 }
362
363 // Validate chain entries and collect stores from chain entries and
364 // intermediate ops.
366 for (Value *V : Chain) {
367 for (User *U : V->users()) {
368 if (Chain.contains(U))
369 continue;
370 auto *I = dyn_cast<Instruction>(U);
371 if (!I || (!TheLoop->contains(I) && V != BackedgeValue))
372 return {};
373 if (!TheLoop->contains(I))
374 continue;
375 if (auto *SI = dyn_cast<StoreInst>(I)) {
376 Stores.push_back(SI);
377 continue;
378 }
379 // Must be intermediate min/max of the same kind.
380 Value *A, *B;
381 if (GetMinMaxRK(I, A, B) != RK)
382 return {};
383 for (User *IU : I->users()) {
384 if (auto *SI = dyn_cast<StoreInst>(IU))
385 Stores.push_back(SI);
386 else if (!Chain.contains(IU))
387 return {};
388 }
389 }
390 }
391
392 // Validate all stores go to same invariant address and are in the same block.
393 StoreInst *IntermediateStore = nullptr;
394 const SCEV *StorePtrSCEV = nullptr;
395 for (StoreInst *SI : Stores) {
396 const SCEV *Ptr = SE->getSCEV(SI->getPointerOperand());
397 if (!SE->isLoopInvariant(Ptr, TheLoop) ||
398 (StorePtrSCEV && StorePtrSCEV != Ptr))
399 return {};
400 StorePtrSCEV = Ptr;
401 if (!IntermediateStore)
402 IntermediateStore = SI;
403 else if (IntermediateStore->getParent() != SI->getParent())
404 return {};
405 else if (IntermediateStore->comesBefore(SI))
406 IntermediateStore = SI;
407 }
408
410 Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader()),
411 cast<Instruction>(BackedgeValue), IntermediateStore, RK, FMF, nullptr,
412 Phi->getType());
413}
414
415// This matches a phi that selects between the original value (HeaderPhi) and an
416// arbitrary non-reduction value.
417static bool isFindLastLikePhi(PHINode *Phi, PHINode *HeaderPhi,
418 SmallPtrSetImpl<Instruction *> &ReductionInstrs) {
419 unsigned NumNonReduxInputs = 0;
420 for (const Value *Op : Phi->operands()) {
421 if (!ReductionInstrs.contains(dyn_cast<Instruction>(Op))) {
422 if (++NumNonReduxInputs > 1)
423 return false;
424 } else if (Op != HeaderPhi) {
425 // TODO: Remove this restriction once chained phis are supported.
426 return false;
427 }
428 }
429 return NumNonReduxInputs == 1;
430}
431
433 PHINode *Phi, RecurKind Kind, Loop *TheLoop, RecurrenceDescriptor &RedDes,
435 ScalarEvolution *SE) {
436 if (Phi->getNumIncomingValues() != 2)
437 return false;
438
439 // Reduction variables are only found in the loop header block.
440 if (Phi->getParent() != TheLoop->getHeader())
441 return false;
442
443 // Obtain the reduction start value from the value that comes from the loop
444 // preheader.
445 if (!TheLoop->getLoopPreheader())
446 return false;
447
448 Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
449 // ExitInstruction is the single value which is used outside the loop.
450 // We only allow for a single reduction value to be used outside the loop.
451 // This includes users of the reduction, variables (which form a cycle
452 // which ends in the phi node).
453 Instruction *ExitInstruction = nullptr;
454
455 // Variable to keep last visited store instruction. By the end of the
456 // algorithm this variable will be either empty or having intermediate
457 // reduction value stored in invariant address.
458 StoreInst *IntermediateStore = nullptr;
459
460 // Indicates that we found a reduction operation in our scan.
461 bool FoundReduxOp = false;
462
463 // We start with the PHI node and scan for all of the users of this
464 // instruction. All users must be instructions that can be used as reduction
465 // variables (such as ADD). We must have a single out-of-block user. The cycle
466 // must include the original PHI.
467 bool FoundStartPHI = false;
468
469 // To recognize AnyOf patterns formed by a icmp select sequence, we store
470 // the number of instruction we saw to make sure we only see one.
471 unsigned NumCmpSelectPatternInst = 0;
472 InstDesc ReduxDesc(false, nullptr);
473
474 // To recognize find-lasts of conditional operations (such as loads or
475 // divides), that need masking, we track non-phi users and if we've found a
476 // "find-last-like" phi (see isFindLastLikePhi). We currently only support
477 // find-last reduction chains with a single "find-last-like" phi and do not
478 // allow any other operations.
479 [[maybe_unused]] unsigned NumNonPHIUsers = 0;
480 bool FoundFindLastLikePhi = false;
481
482 // Data used for determining if the recurrence has been type-promoted.
483 Type *RecurrenceType = Phi->getType();
485 unsigned MinWidthCastToRecurrenceType;
486 Instruction *Start = Phi;
487 bool IsSigned = false;
488
491
492 // Return early if the recurrence kind does not match the type of Phi. If the
493 // recurrence kind is arithmetic, we attempt to look through AND operations
494 // resulting from the type promotion performed by InstCombine. Vector
495 // operations are not limited to the legal integer widths, so we may be able
496 // to evaluate the reduction in the narrower width.
497 // Check the scalar type to handle both scalar and vector types.
498 Type *ScalarTy = RecurrenceType->getScalarType();
499 if (Kind == RecurKind::FindLast) {
500 // FindLast supports all primitive scalar types.
501 if (!ScalarTy->isFloatingPointTy() && !ScalarTy->isIntegerTy() &&
502 !ScalarTy->isPointerTy())
503 return false;
504 } else if (ScalarTy->isFloatingPointTy()) {
506 return false;
507 } else if (ScalarTy->isIntegerTy()) {
508 if (!isIntegerRecurrenceKind(Kind))
509 return false;
510 Start = lookThroughAnd(Phi, RecurrenceType, VisitedInsts, CastInsts);
511 } else {
512 // Pointer min/max may exist, but it is not supported as a reduction op.
513 return false;
514 }
515
516 Worklist.push_back(Start);
517 VisitedInsts.insert(Start);
518
519 // Start with all flags set because we will intersect this with the reduction
520 // flags from all the reduction operations.
522
523 // The first instruction in the use-def chain of the Phi node that requires
524 // exact floating point operations.
525 Instruction *ExactFPMathInst = nullptr;
526
527 // A value in the reduction can be used:
528 // - By the reduction:
529 // - Reduction operation:
530 // - One use of reduction value (safe).
531 // - Multiple use of reduction value (not safe).
532 // - PHI:
533 // - All uses of the PHI must be the reduction (safe).
534 // - Otherwise, not safe.
535 // - By instructions outside of the loop (safe).
536 // * One value may have several outside users, but all outside
537 // uses must be of the same value.
538 // - By store instructions with a loop invariant address (safe with
539 // the following restrictions):
540 // * If there are several stores, all must have the same address.
541 // * Final value should be stored in that loop invariant address.
542 // - By an instruction that is not part of the reduction (not safe).
543 // This is either:
544 // * An instruction type other than PHI or the reduction operation.
545 // * A PHI in the header other than the initial PHI.
546 while (!Worklist.empty()) {
547 Instruction *Cur = Worklist.pop_back_val();
548
549 // Store instructions are allowed iff it is the store of the reduction
550 // value to the same loop invariant memory location.
551 if (auto *SI = dyn_cast<StoreInst>(Cur)) {
552 if (!SE) {
553 LLVM_DEBUG(dbgs() << "Store instructions are not processed without "
554 << "Scalar Evolution Analysis\n");
555 return false;
556 }
557
558 const SCEV *PtrScev = SE->getSCEV(SI->getPointerOperand());
559 // Check it is the same address as previous stores
560 if (IntermediateStore) {
561 const SCEV *OtherScev =
562 SE->getSCEV(IntermediateStore->getPointerOperand());
563
564 if (OtherScev != PtrScev) {
565 LLVM_DEBUG(dbgs() << "Storing reduction value to different addresses "
566 << "inside the loop: " << *SI->getPointerOperand()
567 << " and "
568 << *IntermediateStore->getPointerOperand() << '\n');
569 return false;
570 }
571 }
572
573 // Check the pointer is loop invariant
574 if (!SE->isLoopInvariant(PtrScev, TheLoop)) {
575 LLVM_DEBUG(dbgs() << "Storing reduction value to non-uniform address "
576 << "inside the loop: " << *SI->getPointerOperand()
577 << '\n');
578 return false;
579 }
580
581 // IntermediateStore is always the last store in the loop.
583 continue;
584 }
585
586 // No Users.
587 // If the instruction has no users then this is a broken chain and can't be
588 // a reduction variable.
589 if (Cur->use_empty())
590 return false;
591
592 bool IsAPhi = isa<PHINode>(Cur);
593 if (!IsAPhi)
594 ++NumNonPHIUsers;
595
596 // A header PHI use other than the original PHI.
597 if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
598 return false;
599
600 // Reductions of instructions such as Div, and Sub is only possible if the
601 // LHS is the reduction variable.
602 if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
603 !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
604 !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
605 return false;
606
607 // Any reduction instruction must be of one of the allowed kinds. We ignore
608 // the starting value (the Phi or an AND instruction if the Phi has been
609 // type-promoted).
610 if (Cur != Start) {
611 ReduxDesc = isRecurrenceInstr(TheLoop, Phi, Cur, Kind, ReduxDesc, SE);
612 ExactFPMathInst = ExactFPMathInst == nullptr
613 ? ReduxDesc.getExactFPMathInst()
614 : ExactFPMathInst;
615 if (!ReduxDesc.isRecurrence())
616 return false;
617 // FIXME: FMF is allowed on phi, but propagation is not handled correctly.
618 if (isa<FPMathOperator>(ReduxDesc.getPatternInst()) && !IsAPhi)
619 FMF &= collectMinMaxFMF(ReduxDesc.getPatternInst());
620 // Update this reduction kind if we matched a new instruction.
621 // TODO: Can we eliminate the need for a 2nd InstDesc by keeping 'Kind'
622 // state accurate while processing the worklist?
623 if (ReduxDesc.getRecKind() != RecurKind::None)
624 Kind = ReduxDesc.getRecKind();
625 }
626
627 bool IsASelect = isa<SelectInst>(Cur);
628
629 // A conditional reduction operation must only have 2 or less uses in
630 // VisitedInsts.
631 if (IsASelect && (Kind == RecurKind::FAdd || Kind == RecurKind::FMul) &&
632 hasMultipleUsesOf(Cur, VisitedInsts, 2))
633 return false;
634
635 // A reduction operation must only have one use of the reduction value.
636 if (!IsAPhi && !IsASelect && !isAnyOfRecurrenceKind(Kind) &&
637 hasMultipleUsesOf(Cur, VisitedInsts, 1))
638 return false;
639
640 // All inputs to a PHI node must be a reduction value, unless the phi is a
641 // "FindLast-like" phi (described below).
642 if (IsAPhi && Cur != Phi) {
643 if (!areAllUsesIn(Cur, VisitedInsts)) {
644 // A "FindLast-like" phi acts like a conditional select between the
645 // previous reduction value, and an arbitrary value. Note: Multiple
646 // "FindLast-like" phis are not supported see:
647 // IVDescriptorsTest.UnsupportedFindLastPhi.
648 FoundFindLastLikePhi =
649 Kind == RecurKind::FindLast && !FoundFindLastLikePhi &&
650 isFindLastLikePhi(cast<PHINode>(Cur), Phi, VisitedInsts);
651 if (!FoundFindLastLikePhi)
652 return false;
653 }
654 }
655
656 if (isAnyOfRecurrenceKind(Kind) && IsASelect)
657 ++NumCmpSelectPatternInst;
658
659 // Check whether we found a reduction operator.
660 FoundReduxOp |= (!IsAPhi || FoundFindLastLikePhi) && Cur != Start;
661
662 // Process users of current instruction. Push non-PHI nodes after PHI nodes
663 // onto the stack. This way we are going to have seen all inputs to PHI
664 // nodes once we get to them.
667 for (User *U : Cur->users()) {
669
670 // If the user is a call to llvm.fmuladd then the instruction can only be
671 // the final operand.
672 if (isFMulAddIntrinsic(UI))
673 if (Cur == UI->getOperand(0) || Cur == UI->getOperand(1))
674 return false;
675
676 // Check if we found the exit user.
677 BasicBlock *Parent = UI->getParent();
678 if (!TheLoop->contains(Parent)) {
679 // If we already know this instruction is used externally, move on to
680 // the next user.
681 if (ExitInstruction == Cur)
682 continue;
683
684 // Exit if you find multiple values used outside or if the header phi
685 // node is being used. In this case the user uses the value of the
686 // previous iteration, in which case we would loose "VF-1" iterations of
687 // the reduction operation if we vectorize.
688 if (ExitInstruction != nullptr || Cur == Phi)
689 return false;
690
691 // The instruction used by an outside user must be the last instruction
692 // before we feed back to the reduction phi. Otherwise, we loose VF-1
693 // operations on the value.
694 if (!is_contained(Phi->operands(), Cur))
695 return false;
696
697 ExitInstruction = Cur;
698 continue;
699 }
700
701 // Process instructions only once (termination). Each reduction cycle
702 // value must only be used once, except by phi nodes and conditional
703 // reductions which are represented as a cmp followed by a select.
704 InstDesc IgnoredVal(false, nullptr);
705 if (VisitedInsts.insert(UI).second) {
706 if (isa<PHINode>(UI)) {
707 PHIs.push_back(UI);
708 } else {
710 if (SI && SI->getPointerOperand() == Cur) {
711 // Reduction variable chain can only be stored somewhere but it
712 // can't be used as an address.
713 return false;
714 }
715 NonPHIs.push_back(UI);
716 }
717 } else if (!isa<PHINode>(UI) &&
718 ((!isConditionalRdxPattern(UI).isRecurrence() &&
719 !isAnyOfPattern(TheLoop, Phi, UI, IgnoredVal)
720 .isRecurrence())))
721 return false;
722
723 // Remember that we completed the cycle.
724 if (UI == Phi)
725 FoundStartPHI = true;
726 }
727 Worklist.append(PHIs.begin(), PHIs.end());
728 Worklist.append(NonPHIs.begin(), NonPHIs.end());
729 }
730
731 // We only expect to match a single "find-last-like" phi per find-last
732 // reduction, with no non-phi operations in the reduction use chain.
733 assert((!FoundFindLastLikePhi ||
734 (Kind == RecurKind::FindLast && NumNonPHIUsers == 0)) &&
735 "Unexpectedly matched a 'find-last-like' phi");
736
737 if (isAnyOfRecurrenceKind(Kind) && NumCmpSelectPatternInst != 1)
738 return false;
739
740 if (IntermediateStore) {
741 // Check that stored value goes to the phi node again. This way we make sure
742 // that the value stored in IntermediateStore is indeed the final reduction
743 // value.
744 if (!is_contained(Phi->operands(), IntermediateStore->getValueOperand())) {
745 LLVM_DEBUG(dbgs() << "Not a final reduction value stored: "
746 << *IntermediateStore << '\n');
747 return false;
748 }
749
750 // If there is an exit instruction it's value should be stored in
751 // IntermediateStore
752 if (ExitInstruction &&
753 IntermediateStore->getValueOperand() != ExitInstruction) {
754 LLVM_DEBUG(dbgs() << "Last store Instruction of reduction value does not "
755 "store last calculated value of the reduction: "
756 << *IntermediateStore << '\n');
757 return false;
758 }
759
760 // If all uses are inside the loop (intermediate stores), then the
761 // reduction value after the loop will be the one used in the last store.
762 if (!ExitInstruction)
763 ExitInstruction = cast<Instruction>(IntermediateStore->getValueOperand());
764 }
765
766 if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
767 return false;
768
769 const bool IsOrdered =
770 checkOrderedReduction(Kind, ExactFPMathInst, ExitInstruction, Phi);
771
772 if (Start != Phi) {
773 // If the starting value is not the same as the phi node, we speculatively
774 // looked through an 'and' instruction when evaluating a potential
775 // arithmetic reduction to determine if it may have been type-promoted.
776 //
777 // We now compute the minimal bit width that is required to represent the
778 // reduction. If this is the same width that was indicated by the 'and', we
779 // can represent the reduction in the smaller type. The 'and' instruction
780 // will be eliminated since it will essentially be a cast instruction that
781 // can be ignore in the cost model. If we compute a different type than we
782 // did when evaluating the 'and', the 'and' will not be eliminated, and we
783 // will end up with different kinds of operations in the recurrence
784 // expression (e.g., IntegerAND, IntegerADD). We give up if this is
785 // the case.
786 //
787 // The vectorizer relies on InstCombine to perform the actual
788 // type-shrinking. It does this by inserting instructions to truncate the
789 // exit value of the reduction to the width indicated by RecurrenceType and
790 // then extend this value back to the original width. If IsSigned is false,
791 // a 'zext' instruction will be generated; otherwise, a 'sext' will be
792 // used.
793 //
794 // TODO: We should not rely on InstCombine to rewrite the reduction in the
795 // smaller type. We should just generate a correctly typed expression
796 // to begin with.
797 Type *ComputedType;
798 std::tie(ComputedType, IsSigned) =
799 computeRecurrenceType(ExitInstruction, DB, AC, DT);
800 if (ComputedType != RecurrenceType)
801 return false;
802 }
803
804 // Collect cast instructions and the minimum width used by the recurrence.
805 // If the starting value is not the same as the phi node and the computed
806 // recurrence type is equal to the recurrence type, the recurrence expression
807 // will be represented in a narrower or wider type. If there are any cast
808 // instructions that will be unnecessary, collect them in CastsFromRecurTy.
809 // Note that the 'and' instruction was already included in this list.
810 //
811 // TODO: A better way to represent this may be to tag in some way all the
812 // instructions that are a part of the reduction. The vectorizer cost
813 // model could then apply the recurrence type to these instructions,
814 // without needing a white list of instructions to ignore.
815 // This may also be useful for the inloop reductions, if it can be
816 // kept simple enough.
817 collectCastInstrs(TheLoop, ExitInstruction, RecurrenceType, CastInsts,
818 MinWidthCastToRecurrenceType);
819
820 // We found a reduction var if we have reached the original phi node and we
821 // only have a single instruction with out-of-loop users.
822
823 // The ExitInstruction(Instruction which is allowed to have out-of-loop users)
824 // is saved as part of the RecurrenceDescriptor.
825
826 // Save the description of this reduction variable.
827 RedDes =
828 RecurrenceDescriptor(RdxStart, ExitInstruction, IntermediateStore, Kind,
829 FMF, ExactFPMathInst, RecurrenceType, IsSigned,
830 IsOrdered, CastInsts, MinWidthCastToRecurrenceType);
831 return true;
832}
833
834// We are looking for loops that do something like this:
835// int r = 0;
836// for (int i = 0; i < n; i++) {
837// if (src[i] > 3)
838// r = 3;
839// }
840// where the reduction value (r) only has two states, in this example 0 or 3.
841// The generated LLVM IR for this type of loop will be like this:
842// for.body:
843// %r = phi i32 [ %spec.select, %for.body ], [ 0, %entry ]
844// ...
845// %cmp = icmp sgt i32 %5, 3
846// %spec.select = select i1 %cmp, i32 3, i32 %r
847// ...
848// In general we can support vectorization of loops where 'r' flips between
849// any two non-constants, provided they are loop invariant. The only thing
850// we actually care about at the end of the loop is whether or not any lane
851// in the selected vector is different from the start value. The final
852// across-vector reduction after the loop simply involves choosing the start
853// value if nothing changed (0 in the example above) or the other selected
854// value (3 in the example above).
857 Instruction *I, InstDesc &Prev) {
858 // We must handle the select(cmp(),x,y) as a single instruction. Advance to
859 // the select.
860 if (match(I, m_OneUse(m_Cmp()))) {
861 if (auto *Select = dyn_cast<SelectInst>(*I->user_begin()))
862 return InstDesc(Select, Prev.getRecKind());
863 }
864
865 if (!match(I, m_Select(m_Cmp(), m_Value(), m_Value())))
866 return InstDesc(false, I);
867
869 Value *NonPhi = nullptr;
870
871 if (OrigPhi == dyn_cast<PHINode>(SI->getTrueValue()))
872 NonPhi = SI->getFalseValue();
873 else if (OrigPhi == dyn_cast<PHINode>(SI->getFalseValue()))
874 NonPhi = SI->getTrueValue();
875 else
876 return InstDesc(false, I);
877
878 // We are looking for selects of the form:
879 // select(cmp(), phi, loop_invariant) or
880 // select(cmp(), loop_invariant, phi)
881 if (!Loop->isLoopInvariant(NonPhi))
882 return InstDesc(false, I);
883
884 return InstDesc(I, RecurKind::AnyOf);
885}
886
887// We are looking for loops that do something like this:
888// int r = 0;
889// for (int i = 0; i < n; i++) {
890// if (src[i] > 3)
891// r = i;
892// }
893// or like this:
894// int r = 0;
895// for (int i = 0; i < n; i++) {
896// if (src[i] > 3)
897// r = <loop-varying value>;
898// }
899// The reduction value (r) is derived from either the values of an induction
900// variable (i) sequence, an arbitrary loop-varying value, or from the start
901// value (0). The LLVM IR generated for such loops would be as follows:
902// for.body:
903// %r = phi i32 [ %spec.select, %for.body ], [ 0, %entry ]
904// %i = phi i32 [ %inc, %for.body ], [ 0, %entry ]
905// ...
906// %cmp = icmp sgt i32 %5, 3
907// %spec.select = select i1 %cmp, i32 %i, i32 %r
908// %inc = add nsw i32 %i, 1
909// ...
910//
911// When searching for an arbitrary loop-varying value, the reduction value will
912// either be the initial value (0) if the condition was never met, or the value
913// of the loop-varying value in the most recent loop iteration where the
914// condition was met.
918 // TODO: Support the vectorization of FindLastIV when the reduction phi is
919 // used by more than one select instruction. This vectorization is only
920 // performed when the SCEV of each increasing induction variable used by the
921 // select instructions is identical.
922 if (!OrigPhi->hasOneUse())
923 return InstDesc(false, I);
924
925 // We are looking for selects of the form:
926 // select(cmp(), phi, value) or
927 // select(cmp(), value, phi)
928 if (!match(I, m_CombineOr(m_Select(m_Cmp(), m_Value(), m_Specific(OrigPhi)),
929 m_Select(m_Cmp(), m_Specific(OrigPhi), m_Value()))))
930 return InstDesc(false, I);
931
933}
934
935/// Returns true if the select instruction has users in the compare-and-add
936/// reduction pattern below. The select instruction argument is the last one
937/// in the sequence.
938///
939/// %sum.1 = phi ...
940/// ...
941/// %cmp = fcmp pred %0, %CFP
942/// %add = fadd %0, %sum.1
943/// %sum.2 = select %cmp, %add, %sum.1
946 Value *TrueVal, *FalseVal;
947 // Only handle single use cases for now.
948 if (!match(I,
949 m_Select(m_OneUse(m_Cmp()), m_Value(TrueVal), m_Value(FalseVal))))
950 return InstDesc(false, I);
951
952 // Handle only when either of operands of select instruction is a PHI
953 // node for now.
954 if ((isa<PHINode>(TrueVal) && isa<PHINode>(FalseVal)) ||
955 (!isa<PHINode>(TrueVal) && !isa<PHINode>(FalseVal)))
956 return InstDesc(false, I);
957
958 Instruction *I1 = isa<PHINode>(TrueVal) ? dyn_cast<Instruction>(FalseVal)
959 : dyn_cast<Instruction>(TrueVal);
960 if (!I1 || !I1->isBinaryOp())
961 return InstDesc(false, I);
962
963 Value *Op1, *Op2;
964 if (!(((m_FAdd(m_Value(Op1), m_Value(Op2)).match(I1) ||
965 m_FSub(m_Value(Op1), m_Value(Op2)).match(I1)) &&
966 I1->isFast()) ||
967 (m_FMul(m_Value(Op1), m_Value(Op2)).match(I1) && (I1->isFast())) ||
968 ((m_Add(m_Value(Op1), m_Value(Op2)).match(I1) ||
969 m_Sub(m_Value(Op1), m_Value(Op2)).match(I1))) ||
970 (m_Mul(m_Value(Op1), m_Value(Op2)).match(I1))))
971 return InstDesc(false, I);
972
975 if (!IPhi || IPhi != FalseVal)
976 return InstDesc(false, I);
977
978 return InstDesc(true, I);
979}
980
983 Instruction *I, RecurKind Kind,
984 InstDesc &Prev, ScalarEvolution *SE) {
985 assert(Prev.getRecKind() == RecurKind::None || Prev.getRecKind() == Kind);
986 switch (I->getOpcode()) {
987 default:
988 return InstDesc(false, I);
989 case Instruction::PHI:
990 return InstDesc(I, Prev.getRecKind(), Prev.getExactFPMathInst());
991 case Instruction::Sub:
992 return InstDesc(
993 Kind == RecurKind::Sub || Kind == RecurKind::AddChainWithSubs, I);
994 case Instruction::Add:
995 return InstDesc(
996 Kind == RecurKind::Add || Kind == RecurKind::AddChainWithSubs, I);
997 case Instruction::Mul:
998 return InstDesc(Kind == RecurKind::Mul, I);
999 case Instruction::And:
1000 return InstDesc(Kind == RecurKind::And, I);
1001 case Instruction::Or:
1002 return InstDesc(Kind == RecurKind::Or, I);
1003 case Instruction::Xor:
1004 return InstDesc(Kind == RecurKind::Xor, I);
1005 case Instruction::FDiv:
1006 case Instruction::FMul:
1007 return InstDesc(Kind == RecurKind::FMul, I,
1008 I->hasAllowReassoc() ? nullptr : I);
1009 case Instruction::FSub:
1010 case Instruction::FAdd:
1011 return InstDesc(Kind == RecurKind::FAdd, I,
1012 I->hasAllowReassoc() ? nullptr : I);
1013 case Instruction::Select:
1014 if (Kind == RecurKind::FAdd || Kind == RecurKind::FMul ||
1015 Kind == RecurKind::Add || Kind == RecurKind::Mul ||
1017 return isConditionalRdxPattern(I);
1018 if (isFindRecurrenceKind(Kind) && SE)
1019 return isFindPattern(L, OrigPhi, I, *SE);
1020 [[fallthrough]];
1021 case Instruction::FCmp:
1022 case Instruction::ICmp:
1023 case Instruction::Call:
1024 if (isAnyOfRecurrenceKind(Kind))
1025 return isAnyOfPattern(L, OrigPhi, I, Prev);
1026 if (isFMulAddIntrinsic(I))
1027 return InstDesc(Kind == RecurKind::FMulAdd, I,
1028 I->hasAllowReassoc() ? nullptr : I);
1029 return InstDesc(false, I);
1030 }
1031}
1032
1035 unsigned MaxNumUses) {
1036 unsigned NumUses = 0;
1037 for (const Use &U : I->operands()) {
1038 if (Insts.count(dyn_cast<Instruction>(U)))
1039 ++NumUses;
1040 if (NumUses > MaxNumUses)
1041 return true;
1042 }
1043
1044 return false;
1045}
1046
1048 RecurrenceDescriptor &RedDes,
1050 DominatorTree *DT,
1051 ScalarEvolution *SE) {
1052 if (AddReductionVar(Phi, RecurKind::Add, TheLoop, RedDes, DB, AC, DT, SE)) {
1053 LLVM_DEBUG(dbgs() << "Found an ADD reduction PHI." << *Phi << "\n");
1054 return true;
1055 }
1056 if (AddReductionVar(Phi, RecurKind::Sub, TheLoop, RedDes, DB, AC, DT, SE)) {
1057 LLVM_DEBUG(dbgs() << "Found a SUB reduction PHI." << *Phi << "\n");
1058 return true;
1059 }
1060 if (AddReductionVar(Phi, RecurKind::AddChainWithSubs, TheLoop, RedDes, DB, AC,
1061 DT, SE)) {
1062 LLVM_DEBUG(dbgs() << "Found a chained ADD-SUB reduction PHI." << *Phi
1063 << "\n");
1064 return true;
1065 }
1066 if (AddReductionVar(Phi, RecurKind::Mul, TheLoop, RedDes, DB, AC, DT, SE)) {
1067 LLVM_DEBUG(dbgs() << "Found a MUL reduction PHI." << *Phi << "\n");
1068 return true;
1069 }
1070 if (AddReductionVar(Phi, RecurKind::Or, TheLoop, RedDes, DB, AC, DT, SE)) {
1071 LLVM_DEBUG(dbgs() << "Found an OR reduction PHI." << *Phi << "\n");
1072 return true;
1073 }
1074 if (AddReductionVar(Phi, RecurKind::And, TheLoop, RedDes, DB, AC, DT, SE)) {
1075 LLVM_DEBUG(dbgs() << "Found an AND reduction PHI." << *Phi << "\n");
1076 return true;
1077 }
1078 if (AddReductionVar(Phi, RecurKind::Xor, TheLoop, RedDes, DB, AC, DT, SE)) {
1079 LLVM_DEBUG(dbgs() << "Found a XOR reduction PHI." << *Phi << "\n");
1080 return true;
1081 }
1082 auto RD = getMinMaxRecurrence(Phi, TheLoop, SE);
1083 if (RD.getRecurrenceKind() != RecurKind::None) {
1084 assert(
1085 RecurrenceDescriptor::isMinMaxRecurrenceKind(RD.getRecurrenceKind()) &&
1086 "Expected a min/max recurrence kind");
1087 LLVM_DEBUG(dbgs() << "Found a min/max reduction PHI." << *Phi << "\n");
1088 RedDes = std::move(RD);
1089 return true;
1090 }
1091 if (AddReductionVar(Phi, RecurKind::AnyOf, TheLoop, RedDes, DB, AC, DT, SE)) {
1092 LLVM_DEBUG(dbgs() << "Found a conditional select reduction PHI." << *Phi
1093 << "\n");
1094 return true;
1095 }
1096 if (AddReductionVar(Phi, RecurKind::FindLast, TheLoop, RedDes, DB, AC, DT,
1097 SE)) {
1098 LLVM_DEBUG(dbgs() << "Found a Find reduction PHI." << *Phi << "\n");
1099 return true;
1100 }
1101 if (AddReductionVar(Phi, RecurKind::FMul, TheLoop, RedDes, DB, AC, DT, SE)) {
1102 LLVM_DEBUG(dbgs() << "Found an FMult reduction PHI." << *Phi << "\n");
1103 return true;
1104 }
1105 if (AddReductionVar(Phi, RecurKind::FAdd, TheLoop, RedDes, DB, AC, DT, SE)) {
1106 LLVM_DEBUG(dbgs() << "Found an FAdd reduction PHI." << *Phi << "\n");
1107 return true;
1108 }
1109 if (AddReductionVar(Phi, RecurKind::FMulAdd, TheLoop, RedDes, DB, AC, DT,
1110 SE)) {
1111 LLVM_DEBUG(dbgs() << "Found an FMulAdd reduction PHI." << *Phi << "\n");
1112 return true;
1113 }
1114
1115 // Not a reduction of known type.
1116 return false;
1117}
1118
1120 DominatorTree *DT) {
1121
1122 // Ensure the phi node is in the loop header and has two incoming values.
1123 if (Phi->getParent() != TheLoop->getHeader() ||
1124 Phi->getNumIncomingValues() != 2)
1125 return false;
1126
1127 // Ensure the loop has a preheader and a single latch block. The loop
1128 // vectorizer will need the latch to set up the next iteration of the loop.
1129 auto *Preheader = TheLoop->getLoopPreheader();
1130 auto *Latch = TheLoop->getLoopLatch();
1131 if (!Preheader || !Latch)
1132 return false;
1133
1134 // Ensure the phi node's incoming blocks are the loop preheader and latch.
1135 if (Phi->getBasicBlockIndex(Preheader) < 0 ||
1136 Phi->getBasicBlockIndex(Latch) < 0)
1137 return false;
1138
1139 // Get the previous value. The previous value comes from the latch edge while
1140 // the initial value comes from the preheader edge.
1141 auto *Previous = dyn_cast<Instruction>(Phi->getIncomingValueForBlock(Latch));
1142
1143 // If Previous is a phi in the header, go through incoming values from the
1144 // latch until we find a non-phi value. Use this as the new Previous, all uses
1145 // in the header will be dominated by the original phi, but need to be moved
1146 // after the non-phi previous value.
1148 while (auto *PrevPhi = dyn_cast_or_null<PHINode>(Previous)) {
1149 if (PrevPhi->getParent() != Phi->getParent())
1150 return false;
1151 if (!SeenPhis.insert(PrevPhi).second)
1152 return false;
1153 Previous = dyn_cast<Instruction>(PrevPhi->getIncomingValueForBlock(Latch));
1154 }
1155
1156 if (!Previous || !TheLoop->contains(Previous) || isa<PHINode>(Previous))
1157 return false;
1158
1159 // Ensure every user of the phi node (recursively) is dominated by the
1160 // previous value. The dominance requirement ensures the loop vectorizer will
1161 // not need to vectorize the initial value prior to the first iteration of the
1162 // loop.
1163 // TODO: Consider extending this sinking to handle memory instructions.
1164
1166 BasicBlock *PhiBB = Phi->getParent();
1168 auto TryToPushSinkCandidate = [&](Instruction *SinkCandidate) {
1169 // Cyclic dependence.
1170 if (Previous == SinkCandidate)
1171 return false;
1172
1173 if (!Seen.insert(SinkCandidate).second)
1174 return true;
1175 if (DT->dominates(Previous,
1176 SinkCandidate)) // We already are good w/o sinking.
1177 return true;
1178
1179 if (SinkCandidate->getParent() != PhiBB ||
1180 SinkCandidate->mayHaveSideEffects() ||
1181 SinkCandidate->mayReadFromMemory() || SinkCandidate->isTerminator())
1182 return false;
1183
1184 // If we reach a PHI node that is not dominated by Previous, we reached a
1185 // header PHI. No need for sinking.
1186 if (isa<PHINode>(SinkCandidate))
1187 return true;
1188
1189 // Sink User tentatively and check its users
1190 WorkList.push_back(SinkCandidate);
1191 return true;
1192 };
1193
1194 WorkList.push_back(Phi);
1195 // Try to recursively sink instructions and their users after Previous.
1196 while (!WorkList.empty()) {
1197 Instruction *Current = WorkList.pop_back_val();
1198 for (User *User : Current->users()) {
1199 if (!TryToPushSinkCandidate(cast<Instruction>(User)))
1200 return false;
1201 }
1202 }
1203
1204 return true;
1205}
1206
1208 switch (Kind) {
1209 case RecurKind::Sub:
1210 return Instruction::Sub;
1212 case RecurKind::Add:
1213 return Instruction::Add;
1214 case RecurKind::Mul:
1215 return Instruction::Mul;
1216 case RecurKind::Or:
1217 return Instruction::Or;
1218 case RecurKind::And:
1219 return Instruction::And;
1220 case RecurKind::Xor:
1221 return Instruction::Xor;
1222 case RecurKind::FMul:
1223 return Instruction::FMul;
1224 case RecurKind::FMulAdd:
1225 case RecurKind::FAdd:
1226 return Instruction::FAdd;
1227 case RecurKind::SMax:
1228 case RecurKind::SMin:
1229 case RecurKind::UMax:
1230 case RecurKind::UMin:
1231 return Instruction::ICmp;
1232 case RecurKind::FMax:
1233 case RecurKind::FMin:
1238 return Instruction::FCmp;
1240 case RecurKind::AnyOf:
1241 case RecurKind::FindIV:
1242 // TODO: Set AnyOf and FindIV to Instruction::Select once in-loop reductions
1243 // are supported.
1244 default:
1245 llvm_unreachable("Unknown recurrence operation");
1246 }
1247}
1248
1251 SmallVector<Instruction *, 4> ReductionOperations;
1252 const bool IsMinMax = isMinMaxRecurrenceKind(Kind);
1253
1254 // Search down from the Phi to the LoopExitInstr, looking for instructions
1255 // with a single user of the correct type for the reduction.
1256
1257 // Note that we check that the type of the operand is correct for each item in
1258 // the chain, including the last (the loop exit value). This can come up from
1259 // sub, which would otherwise be treated as an add reduction. MinMax also need
1260 // to check for a pair of icmp/select, for which we use getNextInstruction and
1261 // isCorrectOpcode functions to step the right number of instruction, and
1262 // check the icmp/select pair.
1263 // FIXME: We also do not attempt to look through Select's yet, which might
1264 // be part of the reduction chain, or attempt to looks through And's to find a
1265 // smaller bitwidth. Subs are also currently not allowed (which are usually
1266 // treated as part of a add reduction) as they are expected to generally be
1267 // more expensive than out-of-loop reductions, and need to be costed more
1268 // carefully.
1269 unsigned ExpectedUses = 1;
1270 if (IsMinMax)
1271 ExpectedUses = 2;
1272
1273 auto getNextInstruction = [&](Instruction *Cur) -> Instruction * {
1274 for (auto *User : Cur->users()) {
1276 if (isa<PHINode>(UI))
1277 continue;
1278 if (IsMinMax) {
1279 // We are expecting a icmp/select pair, which we go to the next select
1280 // instruction if we can. We already know that Cur has 2 uses.
1281 if (isa<SelectInst>(UI))
1282 return UI;
1283 continue;
1284 }
1285 return UI;
1286 }
1287 return nullptr;
1288 };
1289 auto isCorrectOpcode = [&](Instruction *Cur) {
1290 if (IsMinMax) {
1291 Value *LHS, *RHS;
1293 matchSelectPattern(Cur, LHS, RHS).Flavor);
1294 }
1295 // Recognize a call to the llvm.fmuladd intrinsic.
1296 if (isFMulAddIntrinsic(Cur))
1297 return true;
1298
1299 if (Cur->getOpcode() == Instruction::Sub &&
1301 return true;
1302
1303 return Cur->getOpcode() == getOpcode();
1304 };
1305
1306 // Attempt to look through Phis which are part of the reduction chain
1307 unsigned ExtraPhiUses = 0;
1308 Instruction *RdxInstr = LoopExitInstr;
1309 if (auto ExitPhi = dyn_cast<PHINode>(LoopExitInstr)) {
1310 if (ExitPhi->getNumIncomingValues() != 2)
1311 return {};
1312
1313 Instruction *Inc0 = dyn_cast<Instruction>(ExitPhi->getIncomingValue(0));
1314 Instruction *Inc1 = dyn_cast<Instruction>(ExitPhi->getIncomingValue(1));
1315
1316 Instruction *Chain = nullptr;
1317 if (Inc0 == Phi)
1318 Chain = Inc1;
1319 else if (Inc1 == Phi)
1320 Chain = Inc0;
1321 else
1322 return {};
1323
1324 RdxInstr = Chain;
1325 ExtraPhiUses = 1;
1326 }
1327
1328 // The loop exit instruction we check first (as a quick test) but add last. We
1329 // check the opcode is correct (and dont allow them to be Subs) and that they
1330 // have expected to have the expected number of uses. They will have one use
1331 // from the phi and one from a LCSSA value, no matter the type.
1332 if (!isCorrectOpcode(RdxInstr) || !LoopExitInstr->hasNUses(2))
1333 return {};
1334
1335 // Check that the Phi has one (or two for min/max) uses, plus an extra use
1336 // for conditional reductions.
1337 if (!Phi->hasNUses(ExpectedUses + ExtraPhiUses))
1338 return {};
1339
1340 Instruction *Cur = getNextInstruction(Phi);
1341
1342 // Each other instruction in the chain should have the expected number of uses
1343 // and be the correct opcode.
1344 while (Cur != RdxInstr) {
1345 if (!Cur || !isCorrectOpcode(Cur) || !Cur->hasNUses(ExpectedUses))
1346 return {};
1347
1348 ReductionOperations.push_back(Cur);
1349 Cur = getNextInstruction(Cur);
1350 }
1351
1352 ReductionOperations.push_back(Cur);
1353 return ReductionOperations;
1354}
1355
1356InductionDescriptor::InductionDescriptor(Value *Start, InductionKind K,
1357 const SCEV *Step, BinaryOperator *BOp,
1359 : StartValue(Start), IK(K), Step(Step), InductionBinOp(BOp) {
1360 assert(IK != IK_NoInduction && "Not an induction");
1361
1362 // Start value type should match the induction kind and the value
1363 // itself should not be null.
1364 assert(StartValue && "StartValue is null");
1365 assert((IK != IK_PtrInduction || StartValue->getType()->isPointerTy()) &&
1366 "StartValue is not a pointer for pointer induction");
1367 assert((IK != IK_IntInduction || StartValue->getType()->isIntegerTy()) &&
1368 "StartValue is not an integer for integer induction");
1369
1370 // Check the Step Value. It should be non-zero integer value.
1371 assert((!getConstIntStepValue() || !getConstIntStepValue()->isZero()) &&
1372 "Step value is zero");
1373
1374 assert((IK == IK_FpInduction || Step->getType()->isIntegerTy()) &&
1375 "StepValue is not an integer");
1376
1377 assert((IK != IK_FpInduction || Step->getType()->isFloatingPointTy()) &&
1378 "StepValue is not FP for FpInduction");
1379 assert((IK != IK_FpInduction ||
1380 (InductionBinOp &&
1381 (InductionBinOp->getOpcode() == Instruction::FAdd ||
1382 InductionBinOp->getOpcode() == Instruction::FSub))) &&
1383 "Binary opcode should be specified for FP induction");
1384
1385 if (Casts)
1386 llvm::append_range(RedundantCasts, *Casts);
1387}
1388
1390 if (auto *ConstStep = dyn_cast<SCEVConstant>(Step))
1391 return ConstStep->getValue();
1392 return nullptr;
1393}
1394
1396 ScalarEvolution *SE,
1398
1399 // Here we only handle FP induction variables.
1400 assert(Phi->getType()->isFloatingPointTy() && "Unexpected Phi type");
1401
1402 if (TheLoop->getHeader() != Phi->getParent())
1403 return false;
1404
1405 // The loop may have multiple entrances or multiple exits; we can analyze
1406 // this phi if it has a unique entry value and a unique backedge value.
1407 if (Phi->getNumIncomingValues() != 2)
1408 return false;
1409 Value *BEValue = nullptr, *StartValue = nullptr;
1410 if (TheLoop->contains(Phi->getIncomingBlock(0))) {
1411 BEValue = Phi->getIncomingValue(0);
1412 StartValue = Phi->getIncomingValue(1);
1413 } else {
1414 assert(TheLoop->contains(Phi->getIncomingBlock(1)) &&
1415 "Unexpected Phi node in the loop");
1416 BEValue = Phi->getIncomingValue(1);
1417 StartValue = Phi->getIncomingValue(0);
1418 }
1419
1421 if (!BOp)
1422 return false;
1423
1424 Value *Addend = nullptr;
1425 if (BOp->getOpcode() == Instruction::FAdd) {
1426 if (BOp->getOperand(0) == Phi)
1427 Addend = BOp->getOperand(1);
1428 else if (BOp->getOperand(1) == Phi)
1429 Addend = BOp->getOperand(0);
1430 } else if (BOp->getOpcode() == Instruction::FSub)
1431 if (BOp->getOperand(0) == Phi)
1432 Addend = BOp->getOperand(1);
1433
1434 if (!Addend)
1435 return false;
1436
1437 // The addend should be loop invariant
1438 if (auto *I = dyn_cast<Instruction>(Addend))
1439 if (TheLoop->contains(I))
1440 return false;
1441
1442 // FP Step has unknown SCEV
1443 const SCEV *Step = SE->getUnknown(Addend);
1444 D = InductionDescriptor(StartValue, IK_FpInduction, Step, BOp);
1445 return true;
1446}
1447
1448/// This function is called when we suspect that the update-chain of a phi node
1449/// (whose symbolic SCEV expression sin \p PhiScev) contains redundant casts,
1450/// that can be ignored. (This can happen when the PSCEV rewriter adds a runtime
1451/// predicate P under which the SCEV expression for the phi can be the
1452/// AddRecurrence \p AR; See createAddRecFromPHIWithCast). We want to find the
1453/// cast instructions that are involved in the update-chain of this induction.
1454/// A caller that adds the required runtime predicate can be free to drop these
1455/// cast instructions, and compute the phi using \p AR (instead of some scev
1456/// expression with casts).
1457///
1458/// For example, without a predicate the scev expression can take the following
1459/// form:
1460/// (Ext ix (Trunc iy ( Start + i*Step ) to ix) to iy)
1461///
1462/// It corresponds to the following IR sequence:
1463/// %for.body:
1464/// %x = phi i64 [ 0, %ph ], [ %add, %for.body ]
1465/// %casted_phi = "ExtTrunc i64 %x"
1466/// %add = add i64 %casted_phi, %step
1467///
1468/// where %x is given in \p PN,
1469/// PSE.getSCEV(%x) is equal to PSE.getSCEV(%casted_phi) under a predicate,
1470/// and the IR sequence that "ExtTrunc i64 %x" represents can take one of
1471/// several forms, for example, such as:
1472/// ExtTrunc1: %casted_phi = and %x, 2^n-1
1473/// or:
1474/// ExtTrunc2: %t = shl %x, m
1475/// %casted_phi = ashr %t, m
1476///
1477/// If we are able to find such sequence, we return the instructions
1478/// we found, namely %casted_phi and the instructions on its use-def chain up
1479/// to the phi (not including the phi).
1481 const SCEVUnknown *PhiScev,
1482 const SCEVAddRecExpr *AR,
1483 SmallVectorImpl<Instruction *> &CastInsts) {
1484
1485 assert(CastInsts.empty() && "CastInsts is expected to be empty.");
1486 auto *PN = cast<PHINode>(PhiScev->getValue());
1487 assert(PSE.getSCEV(PN) == AR && "Unexpected phi node SCEV expression");
1488 const Loop *L = AR->getLoop();
1489
1490 // Find any cast instructions that participate in the def-use chain of
1491 // PhiScev in the loop.
1492 // FORNOW/TODO: We currently expect the def-use chain to include only
1493 // two-operand instructions, where one of the operands is an invariant.
1494 // createAddRecFromPHIWithCasts() currently does not support anything more
1495 // involved than that, so we keep the search simple. This can be
1496 // extended/generalized as needed.
1497
1498 auto getDef = [&](const Value *Val) -> Value * {
1499 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Val);
1500 if (!BinOp)
1501 return nullptr;
1502 Value *Op0 = BinOp->getOperand(0);
1503 Value *Op1 = BinOp->getOperand(1);
1504 Value *Def = nullptr;
1505 if (L->isLoopInvariant(Op0))
1506 Def = Op1;
1507 else if (L->isLoopInvariant(Op1))
1508 Def = Op0;
1509 return Def;
1510 };
1511
1512 // Look for the instruction that defines the induction via the
1513 // loop backedge.
1514 BasicBlock *Latch = L->getLoopLatch();
1515 if (!Latch)
1516 return false;
1517 Value *Val = PN->getIncomingValueForBlock(Latch);
1518 if (!Val)
1519 return false;
1520
1521 // Follow the def-use chain until the induction phi is reached.
1522 // If on the way we encounter a Value that has the same SCEV Expr as the
1523 // phi node, we can consider the instructions we visit from that point
1524 // as part of the cast-sequence that can be ignored.
1525 bool InCastSequence = false;
1526 auto *Inst = dyn_cast<Instruction>(Val);
1527 while (Val != PN) {
1528 // If we encountered a phi node other than PN, or if we left the loop,
1529 // we bail out.
1530 if (!Inst || !L->contains(Inst)) {
1531 return false;
1532 }
1533 auto *AddRec = dyn_cast<SCEVAddRecExpr>(PSE.getSCEV(Val));
1534 if (AddRec && PSE.areAddRecsEqualWithPreds(AddRec, AR))
1535 InCastSequence = true;
1536 if (InCastSequence) {
1537 // Only the last instruction in the cast sequence is expected to have
1538 // uses outside the induction def-use chain.
1539 if (!CastInsts.empty())
1540 if (!Inst->hasOneUse())
1541 return false;
1542 CastInsts.push_back(Inst);
1543 }
1544 Val = getDef(Val);
1545 if (!Val)
1546 return false;
1547 Inst = dyn_cast<Instruction>(Val);
1548 }
1549
1550 return InCastSequence;
1551}
1552
1555 InductionDescriptor &D, bool Assume) {
1556 Type *PhiTy = Phi->getType();
1557
1558 // Handle integer and pointer inductions variables.
1559 // Now we handle also FP induction but not trying to make a
1560 // recurrent expression from the PHI node in-place.
1561
1562 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy() && !PhiTy->isFloatTy() &&
1563 !PhiTy->isDoubleTy() && !PhiTy->isHalfTy())
1564 return false;
1565
1566 if (PhiTy->isFloatingPointTy())
1567 return isFPInductionPHI(Phi, TheLoop, PSE.getSE(), D);
1568
1569 const SCEV *PhiScev = PSE.getSCEV(Phi);
1570 const auto *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
1571
1572 // We need this expression to be an AddRecExpr.
1573 if (Assume && !AR)
1574 AR = PSE.getAsAddRec(Phi);
1575
1576 if (!AR) {
1577 LLVM_DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
1578 return false;
1579 }
1580
1581 // Record any Cast instructions that participate in the induction update
1582 const auto *SymbolicPhi = dyn_cast<SCEVUnknown>(PhiScev);
1583 // If we started from an UnknownSCEV, and managed to build an addRecurrence
1584 // only after enabling Assume with PSCEV, this means we may have encountered
1585 // cast instructions that required adding a runtime check in order to
1586 // guarantee the correctness of the AddRecurrence respresentation of the
1587 // induction.
1588 if (PhiScev != AR && SymbolicPhi) {
1590 if (getCastsForInductionPHI(PSE, SymbolicPhi, AR, Casts))
1591 return isInductionPHI(Phi, TheLoop, PSE.getSE(), D, AR, &Casts);
1592 }
1593
1594 return isInductionPHI(Phi, TheLoop, PSE.getSE(), D, AR);
1595}
1596
1598 PHINode *Phi, const Loop *TheLoop, ScalarEvolution *SE,
1599 InductionDescriptor &D, const SCEV *Expr,
1600 SmallVectorImpl<Instruction *> *CastsToIgnore) {
1601 Type *PhiTy = Phi->getType();
1602 // isSCEVable returns true for integer and pointer types.
1603 if (!SE->isSCEVable(PhiTy))
1604 return false;
1605
1606 // Check that the PHI is consecutive.
1607 const SCEV *PhiScev = Expr ? Expr : SE->getSCEV(Phi);
1608 const SCEV *Step;
1609
1610 // FIXME: We are currently matching the specific loop TheLoop; if it doesn't
1611 // match, we should treat it as a uniform. Unfortunately, we don't currently
1612 // know how to handled uniform PHIs.
1613 if (!match(PhiScev, m_scev_AffineAddRec(m_SCEV(), m_SCEV(Step),
1614 m_SpecificLoop(TheLoop)))) {
1615 LLVM_DEBUG(
1616 dbgs() << "LV: PHI is not a poly recurrence for requested loop.\n");
1617 return false;
1618 }
1619
1620 // This function assumes that InductionPhi is called only on Phi nodes
1621 // present inside loop headers. Check for the same, and throw an assert if
1622 // the current Phi is not present inside the loop header.
1623 assert(Phi->getParent() == TheLoop->getHeader() &&
1624 "Invalid Phi node, not present in loop header");
1625
1626 if (!TheLoop->getLoopPreheader())
1627 return false;
1628
1629 Value *StartValue =
1630 Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
1631
1632 BasicBlock *Latch = TheLoop->getLoopLatch();
1633 if (!Latch)
1634 return false;
1635
1636 if (PhiTy->isIntegerTy()) {
1637 BinaryOperator *BOp =
1638 dyn_cast<BinaryOperator>(Phi->getIncomingValueForBlock(Latch));
1639 D = InductionDescriptor(StartValue, IK_IntInduction, Step, BOp,
1640 CastsToIgnore);
1641 return true;
1642 }
1643
1644 assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
1645
1646 // This allows induction variables w/non-constant steps.
1647 D = InductionDescriptor(StartValue, IK_PtrInduction, Step);
1648 return true;
1649}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
AMDGPU Register Bank Select
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define X(NUM, ENUM, NAME)
Definition ELF.h:851
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")
static bool getCastsForInductionPHI(PredicatedScalarEvolution &PSE, const SCEVUnknown *PhiScev, const SCEVAddRecExpr *AR, SmallVectorImpl< Instruction * > &CastInsts)
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 void collectCastInstrs(Loop *TheLoop, Instruction *Exit, Type *RecurrenceType, SmallPtrSetImpl< Instruction * > &Casts, unsigned &MinWidthCastToRecurTy)
Collect cast instructions that can be ignored in the vectorizer's cost model, given a reduction exit ...
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 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:539
#define I(x, y, z)
Definition MD5.cpp:57
#define LLVM_DEBUG(...)
Definition Debug.h:114
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
Class for arbitrary precision integers.
Definition APInt.h:78
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
BinaryOps getOpcode() const
Definition InstrTypes.h:374
This is the shared class of boolean and integer constants.
Definition Constants.h:87
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:159
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:200
bool hasNoNaNs() const
Test if this operation's arguments and results are assumed not-NaN.
Definition Operator.h:302
bool hasNoSignedZeros() const
Test if this operation can ignore the sign of zero.
Definition Operator.h:312
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
static FastMathFlags getFast()
Definition FMF.h:53
@ IK_FpInduction
Floating point induction variable.
@ IK_PtrInduction
Pointer induction var. Step = C.
@ IK_IntInduction
Integer induction variable. Step = C.
static LLVM_ABI bool isInductionPHI(PHINode *Phi, const Loop *L, ScalarEvolution *SE, InductionDescriptor &D, const SCEV *Expr=nullptr, SmallVectorImpl< Instruction * > *CastsToIgnore=nullptr)
Returns true if Phi is an induction in the loop L.
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 ConstantInt * getConstIntStepValue() const
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...
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:354
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in 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
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
Definition LoopInfo.cpp:67
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) const
Check if AR1 and AR2 are equal, while taking into account Equal predicates in Preds.
LLVM_ABI const SCEVAddRecExpr * getAsAddRec(Value *V)
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(cmp(),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 either a Select(ICmp(A, B),...
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 isIntMinMaxRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is an integer min/max 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 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.
LLVM_ABI Type * getType() const
Return the LLVM type of this SCEV expression.
The main scalar evolution driver.
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
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)
This class represents the LLVM 'select' instruction.
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)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
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:284
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition Type.h:155
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 isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:317
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
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:439
iterator_range< user_iterator > users()
Definition Value.h:426
LLVM_ABI bool hasNUses(unsigned N) const
Return true if this Value has exactly N uses.
Definition Value.cpp:146
bool use_empty() const
Definition Value.h:346
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.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
IntrinsicID_match m_Intrinsic()
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
m_Intrinsic_Ty< Opnd0, Opnd1 >::Ty m_FMinimum(const Opnd0 &Op0, const Opnd1 &Op1)
match_combine_or< MaxMin_match< FCmpInst, LHS, RHS, ofmin_pred_ty >, MaxMin_match< FCmpInst, LHS, RHS, ufmin_pred_ty > > m_OrdOrUnordFMin(const LHS &L, const RHS &R)
Match an 'ordered' or 'unordered' floating point minimum function.
MaxMin_match< ICmpInst, LHS, RHS, smin_pred_ty > m_SMin(const LHS &L, const RHS &R)
m_Intrinsic_Ty< Opnd0, Opnd1 >::Ty m_FMaximum(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)
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
MaxMin_match< ICmpInst, LHS, RHS, umax_pred_ty > m_UMax(const LHS &L, const RHS &R)
match_combine_or< MaxMin_match< FCmpInst, LHS, RHS, ofmax_pred_ty >, MaxMin_match< FCmpInst, LHS, RHS, ufmax_pred_ty > > m_OrdOrUnordFMax(const LHS &L, const RHS &R)
Match an 'ordered' or 'unordered' floating point maximum function.
MaxMin_match< ICmpInst, LHS, RHS, smax_pred_ty > m_SMax(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
MaxMin_match< ICmpInst, LHS, RHS, umin_pred_ty > m_UMin(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)
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2208
T bit_ceil(T Value)
Returns the smallest integral power of two no smaller than Value if Value is nonzero.
Definition bit.h:362
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:1746
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=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...
LLVM_ABI SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS, Instruction::CastOps *CastOp=nullptr, unsigned Depth=0)
Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind and providing the out param...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
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.
@ FMinimum
FP min with llvm.minimum semantics.
@ FMaxNum
FP max with llvm.maxnum semantics including NaNs.
@ Mul
Product of integers.
@ None
Not a recurrence.
@ AnyOf
AnyOf reduction with select(cmp(),x,y) where one of (x,y) is loop invariant, and both x and y are int...
@ Xor
Bitwise or logical XOR of integers.
@ FindLast
FindLast reduction with select(cmp(),x,y) where x and y.
@ FMax
FP max implemented in terms of select(cmp()).
@ 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 implemented in terms of select(cmp()).
@ 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
LLVM_ABI unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=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.
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:1947
static bool isMinOrMax(SelectPatternFlavor SPF)
When implementing this min/max pattern as fcmp; select, does the fcmp have to be ordered?