LLVM 23.0.0git
VPlanRecipes.cpp
Go to the documentation of this file.
1//===- VPlanRecipes.cpp - Implementations for VPlan recipes ---------------===//
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/// \file
10/// This file contains implementations for different VPlan recipes.
11///
12//===----------------------------------------------------------------------===//
13
15#include "VPlan.h"
16#include "VPlanAnalysis.h"
17#include "VPlanHelpers.h"
18#include "VPlanPatternMatch.h"
19#include "VPlanUtils.h"
20#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/Twine.h"
27#include "llvm/IR/BasicBlock.h"
28#include "llvm/IR/IRBuilder.h"
29#include "llvm/IR/Instruction.h"
31#include "llvm/IR/Intrinsics.h"
32#include "llvm/IR/Type.h"
33#include "llvm/IR/Value.h"
36#include "llvm/Support/Debug.h"
40#include <cassert>
41
42using namespace llvm;
43using namespace llvm::VPlanPatternMatch;
44
46
47#define LV_NAME "loop-vectorize"
48#define DEBUG_TYPE LV_NAME
49
51 switch (getVPRecipeID()) {
52 case VPExpressionSC:
53 return cast<VPExpressionRecipe>(this)->mayReadOrWriteMemory();
54 case VPInstructionSC: {
55 auto *VPI = cast<VPInstruction>(this);
56 // Loads read from memory but don't write to memory.
57 if (VPI->getOpcode() == Instruction::Load)
58 return false;
59 return VPI->opcodeMayReadOrWriteFromMemory();
60 }
61 case VPInterleaveEVLSC:
62 case VPInterleaveSC:
63 return cast<VPInterleaveBase>(this)->getNumStoreOperands() > 0;
64 case VPWidenStoreEVLSC:
65 case VPWidenStoreSC:
66 return true;
67 case VPReplicateSC:
68 return cast<Instruction>(getVPSingleValue()->getUnderlyingValue())
69 ->mayWriteToMemory();
70 case VPWidenCallSC:
71 return !cast<VPWidenCallRecipe>(this)
72 ->getCalledScalarFunction()
73 ->onlyReadsMemory();
74 case VPWidenIntrinsicSC:
75 return cast<VPWidenIntrinsicRecipe>(this)->mayWriteToMemory();
76 case VPActiveLaneMaskPHISC:
77 case VPCanonicalIVPHISC:
78 case VPBranchOnMaskSC:
79 case VPDerivedIVSC:
80 case VPFirstOrderRecurrencePHISC:
81 case VPReductionPHISC:
82 case VPScalarIVStepsSC:
83 case VPPredInstPHISC:
84 return false;
85 case VPBlendSC:
86 case VPReductionEVLSC:
87 case VPReductionSC:
88 case VPVectorPointerSC:
89 case VPWidenCanonicalIVSC:
90 case VPWidenCastSC:
91 case VPWidenGEPSC:
92 case VPWidenIntOrFpInductionSC:
93 case VPWidenLoadEVLSC:
94 case VPWidenLoadSC:
95 case VPWidenPHISC:
96 case VPWidenPointerInductionSC:
97 case VPWidenSC: {
98 const Instruction *I =
99 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
100 (void)I;
101 assert((!I || !I->mayWriteToMemory()) &&
102 "underlying instruction may write to memory");
103 return false;
104 }
105 default:
106 return true;
107 }
108}
109
111 switch (getVPRecipeID()) {
112 case VPExpressionSC:
113 return cast<VPExpressionRecipe>(this)->mayReadOrWriteMemory();
114 case VPInstructionSC:
115 return cast<VPInstruction>(this)->opcodeMayReadOrWriteFromMemory();
116 case VPWidenLoadEVLSC:
117 case VPWidenLoadSC:
118 return true;
119 case VPReplicateSC:
120 return cast<Instruction>(getVPSingleValue()->getUnderlyingValue())
121 ->mayReadFromMemory();
122 case VPWidenCallSC:
123 return !cast<VPWidenCallRecipe>(this)
124 ->getCalledScalarFunction()
125 ->onlyWritesMemory();
126 case VPWidenIntrinsicSC:
127 return cast<VPWidenIntrinsicRecipe>(this)->mayReadFromMemory();
128 case VPBranchOnMaskSC:
129 case VPDerivedIVSC:
130 case VPFirstOrderRecurrencePHISC:
131 case VPReductionPHISC:
132 case VPPredInstPHISC:
133 case VPScalarIVStepsSC:
134 case VPWidenStoreEVLSC:
135 case VPWidenStoreSC:
136 return false;
137 case VPBlendSC:
138 case VPReductionEVLSC:
139 case VPReductionSC:
140 case VPVectorPointerSC:
141 case VPWidenCanonicalIVSC:
142 case VPWidenCastSC:
143 case VPWidenGEPSC:
144 case VPWidenIntOrFpInductionSC:
145 case VPWidenPHISC:
146 case VPWidenPointerInductionSC:
147 case VPWidenSC: {
148 const Instruction *I =
149 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
150 (void)I;
151 assert((!I || !I->mayReadFromMemory()) &&
152 "underlying instruction may read from memory");
153 return false;
154 }
155 default:
156 // FIXME: Return false if the recipe represents an interleaved store.
157 return true;
158 }
159}
160
162 switch (getVPRecipeID()) {
163 case VPExpressionSC:
164 return cast<VPExpressionRecipe>(this)->mayHaveSideEffects();
165 case VPActiveLaneMaskPHISC:
166 case VPDerivedIVSC:
167 case VPFirstOrderRecurrencePHISC:
168 case VPReductionPHISC:
169 case VPPredInstPHISC:
170 case VPVectorEndPointerSC:
171 return false;
172 case VPInstructionSC: {
173 auto *VPI = cast<VPInstruction>(this);
174 return mayWriteToMemory() ||
175 VPI->getOpcode() == VPInstruction::BranchOnCount ||
176 VPI->getOpcode() == VPInstruction::BranchOnCond ||
177 VPI->getOpcode() == VPInstruction::BranchOnTwoConds;
178 }
179 case VPWidenCallSC: {
180 Function *Fn = cast<VPWidenCallRecipe>(this)->getCalledScalarFunction();
181 return mayWriteToMemory() || !Fn->doesNotThrow() || !Fn->willReturn();
182 }
183 case VPWidenIntrinsicSC:
184 return cast<VPWidenIntrinsicRecipe>(this)->mayHaveSideEffects();
185 case VPBlendSC:
186 case VPReductionEVLSC:
187 case VPReductionSC:
188 case VPScalarIVStepsSC:
189 case VPVectorPointerSC:
190 case VPWidenCanonicalIVSC:
191 case VPWidenCastSC:
192 case VPWidenGEPSC:
193 case VPWidenIntOrFpInductionSC:
194 case VPWidenPHISC:
195 case VPWidenPointerInductionSC:
196 case VPWidenSC: {
197 const Instruction *I =
198 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
199 (void)I;
200 assert((!I || !I->mayHaveSideEffects()) &&
201 "underlying instruction has side-effects");
202 return false;
203 }
204 case VPInterleaveEVLSC:
205 case VPInterleaveSC:
206 return mayWriteToMemory();
207 case VPWidenLoadEVLSC:
208 case VPWidenLoadSC:
209 case VPWidenStoreEVLSC:
210 case VPWidenStoreSC:
211 assert(
212 cast<VPWidenMemoryRecipe>(this)->getIngredient().mayHaveSideEffects() ==
214 "mayHaveSideffects result for ingredient differs from this "
215 "implementation");
216 return mayWriteToMemory();
217 case VPReplicateSC: {
218 auto *R = cast<VPReplicateRecipe>(this);
219 return R->getUnderlyingInstr()->mayHaveSideEffects();
220 }
221 default:
222 return true;
223 }
224}
225
227 assert(!Parent && "Recipe already in some VPBasicBlock");
228 assert(InsertPos->getParent() &&
229 "Insertion position not in any VPBasicBlock");
230 InsertPos->getParent()->insert(this, InsertPos->getIterator());
231}
232
233void VPRecipeBase::insertBefore(VPBasicBlock &BB,
235 assert(!Parent && "Recipe already in some VPBasicBlock");
236 assert(I == BB.end() || I->getParent() == &BB);
237 BB.insert(this, I);
238}
239
241 assert(!Parent && "Recipe already in some VPBasicBlock");
242 assert(InsertPos->getParent() &&
243 "Insertion position not in any VPBasicBlock");
244 InsertPos->getParent()->insert(this, std::next(InsertPos->getIterator()));
245}
246
248 assert(getParent() && "Recipe not in any VPBasicBlock");
250 Parent = nullptr;
251}
252
254 assert(getParent() && "Recipe not in any VPBasicBlock");
256}
257
260 insertAfter(InsertPos);
261}
262
268
270 // Get the underlying instruction for the recipe, if there is one. It is used
271 // to
272 // * decide if cost computation should be skipped for this recipe,
273 // * apply forced target instruction cost.
274 Instruction *UI = nullptr;
275 if (auto *S = dyn_cast<VPSingleDefRecipe>(this))
276 UI = dyn_cast_or_null<Instruction>(S->getUnderlyingValue());
277 else if (auto *IG = dyn_cast<VPInterleaveBase>(this))
278 UI = IG->getInsertPos();
279 else if (auto *WidenMem = dyn_cast<VPWidenMemoryRecipe>(this))
280 UI = &WidenMem->getIngredient();
281
282 InstructionCost RecipeCost;
283 if (UI && Ctx.skipCostComputation(UI, VF.isVector())) {
284 RecipeCost = 0;
285 } else {
286 RecipeCost = computeCost(VF, Ctx);
287 if (ForceTargetInstructionCost.getNumOccurrences() > 0 &&
288 RecipeCost.isValid()) {
289 if (UI)
291 else
292 RecipeCost = InstructionCost(0);
293 }
294 }
295
296 LLVM_DEBUG({
297 dbgs() << "Cost of " << RecipeCost << " for VF " << VF << ": ";
298 dump();
299 });
300 return RecipeCost;
301}
302
304 VPCostContext &Ctx) const {
305 llvm_unreachable("subclasses should implement computeCost");
306}
307
309 return (getVPRecipeID() >= VPFirstPHISC && getVPRecipeID() <= VPLastPHISC) ||
311}
312
314 auto *VPI = dyn_cast<VPInstruction>(this);
315 return VPI && Instruction::isCast(VPI->getOpcode());
316}
317
319 assert(OpType == Other.OpType && "OpType must match");
320 switch (OpType) {
321 case OperationType::OverflowingBinOp:
322 WrapFlags.HasNUW &= Other.WrapFlags.HasNUW;
323 WrapFlags.HasNSW &= Other.WrapFlags.HasNSW;
324 break;
325 case OperationType::Trunc:
326 TruncFlags.HasNUW &= Other.TruncFlags.HasNUW;
327 TruncFlags.HasNSW &= Other.TruncFlags.HasNSW;
328 break;
329 case OperationType::DisjointOp:
330 DisjointFlags.IsDisjoint &= Other.DisjointFlags.IsDisjoint;
331 break;
332 case OperationType::PossiblyExactOp:
333 ExactFlags.IsExact &= Other.ExactFlags.IsExact;
334 break;
335 case OperationType::GEPOp:
336 GEPFlags &= Other.GEPFlags;
337 break;
338 case OperationType::FPMathOp:
339 case OperationType::FCmp:
340 assert((OpType != OperationType::FCmp ||
341 FCmpFlags.Pred == Other.FCmpFlags.Pred) &&
342 "Cannot drop CmpPredicate");
343 getFMFsRef().NoNaNs &= Other.getFMFsRef().NoNaNs;
344 getFMFsRef().NoInfs &= Other.getFMFsRef().NoInfs;
345 break;
346 case OperationType::NonNegOp:
347 NonNegFlags.NonNeg &= Other.NonNegFlags.NonNeg;
348 break;
349 case OperationType::Cmp:
350 assert(CmpPredicate == Other.CmpPredicate && "Cannot drop CmpPredicate");
351 break;
352 case OperationType::ReductionOp:
353 assert(ReductionFlags.Kind == Other.ReductionFlags.Kind &&
354 "Cannot change RecurKind");
355 assert(ReductionFlags.IsOrdered == Other.ReductionFlags.IsOrdered &&
356 "Cannot change IsOrdered");
357 assert(ReductionFlags.IsInLoop == Other.ReductionFlags.IsInLoop &&
358 "Cannot change IsInLoop");
359 getFMFsRef().NoNaNs &= Other.getFMFsRef().NoNaNs;
360 getFMFsRef().NoInfs &= Other.getFMFsRef().NoInfs;
361 break;
362 case OperationType::Other:
363 assert(AllFlags == Other.AllFlags && "Cannot drop other flags");
364 break;
365 }
366}
367
369 assert((OpType == OperationType::FPMathOp || OpType == OperationType::FCmp ||
370 OpType == OperationType::ReductionOp) &&
371 "recipe doesn't have fast math flags");
372 const FastMathFlagsTy &F = getFMFsRef();
373 FastMathFlags Res;
374 Res.setAllowReassoc(F.AllowReassoc);
375 Res.setNoNaNs(F.NoNaNs);
376 Res.setNoInfs(F.NoInfs);
377 Res.setNoSignedZeros(F.NoSignedZeros);
378 Res.setAllowReciprocal(F.AllowReciprocal);
379 Res.setAllowContract(F.AllowContract);
380 Res.setApproxFunc(F.ApproxFunc);
381 return Res;
382}
383
384#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
386
387void VPRecipeBase::print(raw_ostream &O, const Twine &Indent,
388 VPSlotTracker &SlotTracker) const {
389 printRecipe(O, Indent, SlotTracker);
390 if (auto DL = getDebugLoc()) {
391 O << ", !dbg ";
392 DL.print(O);
393 }
394
395 if (auto *Metadata = dyn_cast<VPIRMetadata>(this))
397}
398#endif
399
400template <unsigned PartOpIdx>
401VPValue *
403 if (U.getNumOperands() == PartOpIdx + 1)
404 return U.getOperand(PartOpIdx);
405 return nullptr;
406}
407
408template <unsigned PartOpIdx>
410 if (auto *UnrollPartOp = getUnrollPartOperand(U))
411 return cast<VPConstantInt>(UnrollPartOp)->getZExtValue();
412 return 0;
413}
414
415namespace llvm {
416template class VPUnrollPartAccessor<1>;
417template class VPUnrollPartAccessor<2>;
418template class VPUnrollPartAccessor<3>;
419}
420
422 const VPIRFlags &Flags, const VPIRMetadata &MD,
423 DebugLoc DL, const Twine &Name)
424 : VPRecipeWithIRFlags(VPRecipeBase::VPInstructionSC, Operands, Flags, DL),
425 VPIRMetadata(MD), Opcode(Opcode), Name(Name.str()) {
427 "Set flags not supported for the provided opcode");
428 assert((getNumOperandsForOpcode(Opcode) == -1u ||
430 "number of operands does not match opcode");
431}
432
433#ifndef NDEBUG
434unsigned VPInstruction::getNumOperandsForOpcode(unsigned Opcode) {
435 if (Instruction::isUnaryOp(Opcode) || Instruction::isCast(Opcode))
436 return 1;
437
438 if (Instruction::isBinaryOp(Opcode))
439 return 2;
440
441 switch (Opcode) {
444 return 0;
445 case Instruction::Alloca:
446 case Instruction::ExtractValue:
447 case Instruction::Freeze:
448 case Instruction::Load:
464 return 1;
465 case Instruction::ICmp:
466 case Instruction::FCmp:
467 case Instruction::ExtractElement:
468 case Instruction::Store:
476 return 2;
477 case Instruction::Select:
482 return 3;
483 case Instruction::Call:
484 case Instruction::GetElementPtr:
485 case Instruction::PHI:
486 case Instruction::Switch:
493 // Cannot determine the number of operands from the opcode.
494 return -1u;
495 }
496 llvm_unreachable("all cases should be handled above");
497}
498#endif
499
503
504bool VPInstruction::canGenerateScalarForFirstLane() const {
506 return true;
508 return true;
509 switch (Opcode) {
510 case Instruction::Freeze:
511 case Instruction::ICmp:
512 case Instruction::PHI:
513 case Instruction::Select:
523 return true;
524 default:
525 return false;
526 }
527}
528
529Value *VPInstruction::generate(VPTransformState &State) {
530 IRBuilderBase &Builder = State.Builder;
531
533 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
534 Value *A = State.get(getOperand(0), OnlyFirstLaneUsed);
535 Value *B = State.get(getOperand(1), OnlyFirstLaneUsed);
536 auto *Res =
537 Builder.CreateBinOp((Instruction::BinaryOps)getOpcode(), A, B, Name);
538 if (auto *I = dyn_cast<Instruction>(Res))
539 applyFlags(*I);
540 return Res;
541 }
542
543 switch (getOpcode()) {
544 case VPInstruction::Not: {
545 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
546 Value *A = State.get(getOperand(0), OnlyFirstLaneUsed);
547 return Builder.CreateNot(A, Name);
548 }
549 case Instruction::ExtractElement: {
550 assert(State.VF.isVector() && "Only extract elements from vectors");
551 if (auto *Idx = dyn_cast<VPConstantInt>(getOperand(1)))
552 return State.get(getOperand(0), VPLane(Idx->getZExtValue()));
553 Value *Vec = State.get(getOperand(0));
554 Value *Idx = State.get(getOperand(1), /*IsScalar=*/true);
555 return Builder.CreateExtractElement(Vec, Idx, Name);
556 }
557 case Instruction::Freeze: {
559 return Builder.CreateFreeze(Op, Name);
560 }
561 case Instruction::FCmp:
562 case Instruction::ICmp: {
563 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
564 Value *A = State.get(getOperand(0), OnlyFirstLaneUsed);
565 Value *B = State.get(getOperand(1), OnlyFirstLaneUsed);
566 return Builder.CreateCmp(getPredicate(), A, B, Name);
567 }
568 case Instruction::PHI: {
569 llvm_unreachable("should be handled by VPPhi::execute");
570 }
571 case Instruction::Select: {
572 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
573 Value *Cond =
574 State.get(getOperand(0),
575 OnlyFirstLaneUsed || vputils::isSingleScalar(getOperand(0)));
576 Value *Op1 = State.get(getOperand(1), OnlyFirstLaneUsed);
577 Value *Op2 = State.get(getOperand(2), OnlyFirstLaneUsed);
578 return Builder.CreateSelect(Cond, Op1, Op2, Name);
579 }
581 // Get first lane of vector induction variable.
582 Value *VIVElem0 = State.get(getOperand(0), VPLane(0));
583 // Get the original loop tripcount.
584 Value *ScalarTC = State.get(getOperand(1), VPLane(0));
585
586 // If this part of the active lane mask is scalar, generate the CMP directly
587 // to avoid unnecessary extracts.
588 if (State.VF.isScalar())
589 return Builder.CreateCmp(CmpInst::Predicate::ICMP_ULT, VIVElem0, ScalarTC,
590 Name);
591
592 ElementCount EC = State.VF.multiplyCoefficientBy(
593 cast<VPConstantInt>(getOperand(2))->getZExtValue());
594 auto *PredTy = VectorType::get(Builder.getInt1Ty(), EC);
595 return Builder.CreateIntrinsic(Intrinsic::get_active_lane_mask,
596 {PredTy, ScalarTC->getType()},
597 {VIVElem0, ScalarTC}, nullptr, Name);
598 }
600 // Generate code to combine the previous and current values in vector v3.
601 //
602 // vector.ph:
603 // v_init = vector(..., ..., ..., a[-1])
604 // br vector.body
605 //
606 // vector.body
607 // i = phi [0, vector.ph], [i+4, vector.body]
608 // v1 = phi [v_init, vector.ph], [v2, vector.body]
609 // v2 = a[i, i+1, i+2, i+3];
610 // v3 = vector(v1(3), v2(0, 1, 2))
611
612 auto *V1 = State.get(getOperand(0));
613 if (!V1->getType()->isVectorTy())
614 return V1;
615 Value *V2 = State.get(getOperand(1));
616 return Builder.CreateVectorSpliceRight(V1, V2, 1, Name);
617 }
619 unsigned UF = getParent()->getPlan()->getUF();
620 Value *ScalarTC = State.get(getOperand(0), VPLane(0));
621 Value *Step = createStepForVF(Builder, ScalarTC->getType(), State.VF, UF);
622 Value *Sub = Builder.CreateSub(ScalarTC, Step);
623 Value *Cmp = Builder.CreateICmp(CmpInst::Predicate::ICMP_UGT, ScalarTC, Step);
625 return Builder.CreateSelect(Cmp, Sub, Zero);
626 }
628 // TODO: Restructure this code with an explicit remainder loop, vsetvli can
629 // be outside of the main loop.
630 Value *AVL = State.get(getOperand(0), /*IsScalar*/ true);
631 // Compute EVL
632 assert(AVL->getType()->isIntegerTy() &&
633 "Requested vector length should be an integer.");
634
635 assert(State.VF.isScalable() && "Expected scalable vector factor.");
636 Value *VFArg = Builder.getInt32(State.VF.getKnownMinValue());
637
638 Value *EVL = Builder.CreateIntrinsic(
639 Builder.getInt32Ty(), Intrinsic::experimental_get_vector_length,
640 {AVL, VFArg, Builder.getTrue()});
641 return EVL;
642 }
644 unsigned Part = getUnrollPart(*this);
645 auto *IV = State.get(getOperand(0), VPLane(0));
646 assert(Part != 0 && "Must have a positive part");
647 // The canonical IV is incremented by the vectorization factor (num of
648 // SIMD elements) times the unroll part.
649 Value *Step = createStepForVF(Builder, IV->getType(), State.VF, Part);
650 return Builder.CreateAdd(IV, Step, Name, hasNoUnsignedWrap(),
652 }
654 Value *Cond = State.get(getOperand(0), VPLane(0));
655 // Replace the temporary unreachable terminator with a new conditional
656 // branch, hooking it up to backward destination for latch blocks now, and
657 // to forward destination(s) later when they are created.
658 // Second successor may be backwards - iff it is already in VPBB2IRBB.
659 VPBasicBlock *SecondVPSucc =
660 cast<VPBasicBlock>(getParent()->getSuccessors()[1]);
661 BasicBlock *SecondIRSucc = State.CFG.VPBB2IRBB.lookup(SecondVPSucc);
662 BasicBlock *IRBB = State.CFG.VPBB2IRBB[getParent()];
663 auto *Br = Builder.CreateCondBr(Cond, IRBB, SecondIRSucc);
664 // First successor is always forward, reset it to nullptr.
665 Br->setSuccessor(0, nullptr);
667 applyMetadata(*Br);
668 return Br;
669 }
671 return Builder.CreateVectorSplat(
672 State.VF, State.get(getOperand(0), /*IsScalar*/ true), "broadcast");
673 }
675 // For struct types, we need to build a new 'wide' struct type, where each
676 // element is widened, i.e., we create a struct of vectors.
677 auto *StructTy =
679 Value *Res = PoisonValue::get(toVectorizedTy(StructTy, State.VF));
680 for (const auto &[LaneIndex, Op] : enumerate(operands())) {
681 for (unsigned FieldIndex = 0; FieldIndex != StructTy->getNumElements();
682 FieldIndex++) {
683 Value *ScalarValue =
684 Builder.CreateExtractValue(State.get(Op, true), FieldIndex);
685 Value *VectorValue = Builder.CreateExtractValue(Res, FieldIndex);
686 VectorValue =
687 Builder.CreateInsertElement(VectorValue, ScalarValue, LaneIndex);
688 Res = Builder.CreateInsertValue(Res, VectorValue, FieldIndex);
689 }
690 }
691 return Res;
692 }
694 auto *ScalarTy = State.TypeAnalysis.inferScalarType(getOperand(0));
695 auto NumOfElements = ElementCount::getFixed(getNumOperands());
696 Value *Res = PoisonValue::get(toVectorizedTy(ScalarTy, NumOfElements));
697 for (const auto &[Idx, Op] : enumerate(operands()))
698 Res = Builder.CreateInsertElement(Res, State.get(Op, true),
699 Builder.getInt32(Idx));
700 return Res;
701 }
703 if (State.VF.isScalar())
704 return State.get(getOperand(0), true);
705 IRBuilderBase::FastMathFlagGuard FMFG(Builder);
707 // If this start vector is scaled then it should produce a vector with fewer
708 // elements than the VF.
709 ElementCount VF = State.VF.divideCoefficientBy(
710 cast<VPConstantInt>(getOperand(2))->getZExtValue());
711 auto *Iden = Builder.CreateVectorSplat(VF, State.get(getOperand(1), true));
712 return Builder.CreateInsertElement(Iden, State.get(getOperand(0), true),
713 Builder.getInt32(0));
714 }
716 Value *Start = State.get(getOperand(0), VPLane(0));
717 Value *NewVal = State.get(getOperand(1), VPLane(0));
718 Value *ReducedResult = State.get(getOperand(2));
719 for (unsigned Idx = 3; Idx < getNumOperands(); ++Idx)
720 ReducedResult =
721 Builder.CreateBinOp(Instruction::Or, State.get(getOperand(Idx)),
722 ReducedResult, "bin.rdx");
723 // If any predicate is true it means that we want to select the new value.
724 if (ReducedResult->getType()->isVectorTy())
725 ReducedResult = Builder.CreateOrReduce(ReducedResult);
726 // The compares in the loop may yield poison, which propagates through the
727 // bitwise ORs. Freeze it here before the condition is used.
728 ReducedResult = Builder.CreateFreeze(ReducedResult);
729 return Builder.CreateSelect(ReducedResult, NewVal, Start, "rdx.select");
730 }
732 RecurKind RK = getRecurKind();
733 bool IsOrdered = isReductionOrdered();
734 bool IsInLoop = isReductionInLoop();
736 "FindIV should use min/max reduction kinds");
737
738 // The recipe may have multiple operands to be reduced together.
739 unsigned NumOperandsToReduce = getNumOperands();
740 VectorParts RdxParts(NumOperandsToReduce);
741 for (unsigned Part = 0; Part < NumOperandsToReduce; ++Part)
742 RdxParts[Part] = State.get(getOperand(Part), IsInLoop);
743
744 IRBuilderBase::FastMathFlagGuard FMFG(Builder);
745 if (hasFastMathFlags())
747
748 // Reduce multiple operands into one.
749 Value *ReducedPartRdx = RdxParts[0];
750 if (IsOrdered) {
751 ReducedPartRdx = RdxParts[NumOperandsToReduce - 1];
752 } else {
753 // Floating-point operations should have some FMF to enable the reduction.
754 for (unsigned Part = 1; Part < NumOperandsToReduce; ++Part) {
755 Value *RdxPart = RdxParts[Part];
757 ReducedPartRdx = createMinMaxOp(Builder, RK, ReducedPartRdx, RdxPart);
758 else {
759 // For sub-recurrences, each part's reduction variable is already
760 // negative, we need to do: reduce.add(-acc_uf0 + -acc_uf1)
762 RK == RecurKind::Sub
763 ? Instruction::Add
765 ReducedPartRdx =
766 Builder.CreateBinOp(Opcode, RdxPart, ReducedPartRdx, "bin.rdx");
767 }
768 }
769 }
770
771 // Create the reduction after the loop. Note that inloop reductions create
772 // the target reduction in the loop using a Reduction recipe.
773 if (State.VF.isVector() && !IsInLoop) {
774 // TODO: Support in-order reductions based on the recurrence descriptor.
775 // All ops in the reduction inherit fast-math-flags from the recurrence
776 // descriptor.
777 ReducedPartRdx = createSimpleReduction(Builder, ReducedPartRdx, RK);
778 }
779
780 return ReducedPartRdx;
781 }
784 unsigned Offset =
786 Value *Res;
787 if (State.VF.isVector()) {
788 assert(Offset <= State.VF.getKnownMinValue() &&
789 "invalid offset to extract from");
790 // Extract lane VF - Offset from the operand.
791 Res = State.get(getOperand(0), VPLane::getLaneFromEnd(State.VF, Offset));
792 } else {
793 // TODO: Remove ExtractLastLane for scalar VFs.
794 assert(Offset <= 1 && "invalid offset to extract from");
795 Res = State.get(getOperand(0));
796 }
798 Res->setName(Name);
799 return Res;
800 }
802 Value *A = State.get(getOperand(0));
803 Value *B = State.get(getOperand(1));
804 return Builder.CreateLogicalAnd(A, B, Name);
805 }
808 "can only generate first lane for PtrAdd");
809 Value *Ptr = State.get(getOperand(0), VPLane(0));
810 Value *Addend = State.get(getOperand(1), VPLane(0));
811 return Builder.CreatePtrAdd(Ptr, Addend, Name, getGEPNoWrapFlags());
812 }
814 Value *Ptr =
816 Value *Addend = State.get(getOperand(1));
817 return Builder.CreatePtrAdd(Ptr, Addend, Name, getGEPNoWrapFlags());
818 }
820 Value *Res = Builder.CreateFreeze(State.get(getOperand(0)));
821 for (VPValue *Op : drop_begin(operands()))
822 Res = Builder.CreateOr(Res, Builder.CreateFreeze(State.get(Op)));
823 return State.VF.isScalar() ? Res : Builder.CreateOrReduce(Res);
824 }
826 assert(getNumOperands() != 2 && "ExtractLane from single source should be "
827 "simplified to ExtractElement.");
828 Value *LaneToExtract = State.get(getOperand(0), true);
829 Type *IdxTy = State.TypeAnalysis.inferScalarType(getOperand(0));
830 Value *Res = nullptr;
831 Value *RuntimeVF = getRuntimeVF(Builder, IdxTy, State.VF);
832
833 for (unsigned Idx = 1; Idx != getNumOperands(); ++Idx) {
834 Value *VectorStart =
835 Builder.CreateMul(RuntimeVF, ConstantInt::get(IdxTy, Idx - 1));
836 Value *VectorIdx = Idx == 1
837 ? LaneToExtract
838 : Builder.CreateSub(LaneToExtract, VectorStart);
839 Value *Ext = State.VF.isScalar()
840 ? State.get(getOperand(Idx))
841 : Builder.CreateExtractElement(
842 State.get(getOperand(Idx)), VectorIdx);
843 if (Res) {
844 Value *Cmp = Builder.CreateICmpUGE(LaneToExtract, VectorStart);
845 Res = Builder.CreateSelect(Cmp, Ext, Res);
846 } else {
847 Res = Ext;
848 }
849 }
850 return Res;
851 }
853 if (getNumOperands() == 1) {
854 Value *Mask = State.get(getOperand(0));
855 return Builder.CreateCountTrailingZeroElems(Builder.getInt64Ty(), Mask,
856 /*ZeroIsPoison=*/false, Name);
857 }
858 // If there are multiple operands, create a chain of selects to pick the
859 // first operand with an active lane and add the number of lanes of the
860 // preceding operands.
861 Value *RuntimeVF = getRuntimeVF(Builder, Builder.getInt64Ty(), State.VF);
862 unsigned LastOpIdx = getNumOperands() - 1;
863 Value *Res = nullptr;
864 for (int Idx = LastOpIdx; Idx >= 0; --Idx) {
865 Value *TrailingZeros =
866 State.VF.isScalar()
867 ? Builder.CreateZExt(
868 Builder.CreateICmpEQ(State.get(getOperand(Idx)),
869 Builder.getFalse()),
870 Builder.getInt64Ty())
872 Builder.getInt64Ty(), State.get(getOperand(Idx)),
873 /*ZeroIsPoison=*/false, Name);
874 Value *Current = Builder.CreateAdd(
875 Builder.CreateMul(RuntimeVF, Builder.getInt64(Idx)), TrailingZeros);
876 if (Res) {
877 Value *Cmp = Builder.CreateICmpNE(TrailingZeros, RuntimeVF);
878 Res = Builder.CreateSelect(Cmp, Current, Res);
879 } else {
880 Res = Current;
881 }
882 }
883
884 return Res;
885 }
887 return State.get(getOperand(0), true);
889 return Builder.CreateVectorReverse(State.get(getOperand(0)), "reverse");
891 Value *Data = State.get(getOperand(0));
892 Value *Mask = State.get(getOperand(1));
893 Value *Default = State.get(getOperand(2), /*IsScalar=*/true);
894 Type *VTy = Data->getType();
895 return Builder.CreateIntrinsic(
896 Intrinsic::experimental_vector_extract_last_active, {VTy},
897 {Data, Mask, Default});
898 }
899 default:
900 llvm_unreachable("Unsupported opcode for instruction");
901 }
902}
903
905 unsigned Opcode, ElementCount VF, VPCostContext &Ctx) const {
906 Type *ScalarTy = Ctx.Types.inferScalarType(this);
907 Type *ResultTy = VF.isVector() ? toVectorTy(ScalarTy, VF) : ScalarTy;
908 switch (Opcode) {
909 case Instruction::FNeg:
910 return Ctx.TTI.getArithmeticInstrCost(Opcode, ResultTy, Ctx.CostKind);
911 case Instruction::UDiv:
912 case Instruction::SDiv:
913 case Instruction::SRem:
914 case Instruction::URem:
915 case Instruction::Add:
916 case Instruction::FAdd:
917 case Instruction::Sub:
918 case Instruction::FSub:
919 case Instruction::Mul:
920 case Instruction::FMul:
921 case Instruction::FDiv:
922 case Instruction::FRem:
923 case Instruction::Shl:
924 case Instruction::LShr:
925 case Instruction::AShr:
926 case Instruction::And:
927 case Instruction::Or:
928 case Instruction::Xor: {
931
932 if (VF.isVector()) {
933 // Certain instructions can be cheaper to vectorize if they have a
934 // constant second vector operand. One example of this are shifts on x86.
935 VPValue *RHS = getOperand(1);
936 RHSInfo = Ctx.getOperandInfo(RHS);
937
938 if (RHSInfo.Kind == TargetTransformInfo::OK_AnyValue &&
941 }
942
945 if (CtxI)
946 Operands.append(CtxI->value_op_begin(), CtxI->value_op_end());
947 return Ctx.TTI.getArithmeticInstrCost(
948 Opcode, ResultTy, Ctx.CostKind,
949 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
950 RHSInfo, Operands, CtxI, &Ctx.TLI);
951 }
952 case Instruction::Freeze:
953 // This opcode is unknown. Assume that it is the same as 'mul'.
954 return Ctx.TTI.getArithmeticInstrCost(Instruction::Mul, ResultTy,
955 Ctx.CostKind);
956 case Instruction::ExtractValue:
957 return Ctx.TTI.getInsertExtractValueCost(Instruction::ExtractValue,
958 Ctx.CostKind);
959 case Instruction::ICmp:
960 case Instruction::FCmp: {
961 Type *ScalarOpTy = Ctx.Types.inferScalarType(getOperand(0));
962 Type *OpTy = VF.isVector() ? toVectorTy(ScalarOpTy, VF) : ScalarOpTy;
964 return Ctx.TTI.getCmpSelInstrCost(
965 Opcode, OpTy, CmpInst::makeCmpResultType(OpTy), getPredicate(),
966 Ctx.CostKind, {TTI::OK_AnyValue, TTI::OP_None},
967 {TTI::OK_AnyValue, TTI::OP_None}, CtxI);
968 }
969 case Instruction::BitCast: {
970 Type *ScalarTy = Ctx.Types.inferScalarType(this);
971 if (ScalarTy->isPointerTy())
972 return 0;
973 [[fallthrough]];
974 }
975 case Instruction::SExt:
976 case Instruction::ZExt:
977 case Instruction::FPToUI:
978 case Instruction::FPToSI:
979 case Instruction::FPExt:
980 case Instruction::PtrToInt:
981 case Instruction::PtrToAddr:
982 case Instruction::IntToPtr:
983 case Instruction::SIToFP:
984 case Instruction::UIToFP:
985 case Instruction::Trunc:
986 case Instruction::FPTrunc:
987 case Instruction::AddrSpaceCast: {
988 // Computes the CastContextHint from a recipe that may access memory.
989 auto ComputeCCH = [&](const VPRecipeBase *R) -> TTI::CastContextHint {
992 if (const auto *ReplicateRecipe = dyn_cast<VPReplicateRecipe>(R)) {
993 // Only compute CCH for memory operations, matching the legacy model
994 // which only considers loads/stores for cast context hints.
995 auto *UI = cast<Instruction>(ReplicateRecipe->getUnderlyingValue());
998 return ReplicateRecipe->isPredicated() ? TTI::CastContextHint::Masked
1000 }
1001 const auto *WidenMemoryRecipe = dyn_cast<VPWidenMemoryRecipe>(R);
1002 if (WidenMemoryRecipe == nullptr)
1004 if (VF.isScalar())
1006 if (!WidenMemoryRecipe->isConsecutive())
1008 if (WidenMemoryRecipe->isReverse())
1010 if (WidenMemoryRecipe->isMasked())
1013 };
1014
1015 VPValue *Operand = getOperand(0);
1017 // For Trunc/FPTrunc, get the context from the only user.
1018 if (Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) {
1019 auto GetOnlyUser = [](const VPSingleDefRecipe *R) -> VPRecipeBase * {
1020 if (R->getNumUsers() == 0 || R->hasMoreThanOneUniqueUser())
1021 return nullptr;
1022 return dyn_cast<VPRecipeBase>(*R->user_begin());
1023 };
1024 if (VPRecipeBase *Recipe = GetOnlyUser(this)) {
1025 if (match(Recipe, m_Reverse(m_VPValue())))
1026 Recipe = GetOnlyUser(cast<VPInstruction>(Recipe));
1027 if (Recipe)
1028 CCH = ComputeCCH(Recipe);
1029 }
1030 }
1031 // For Z/Sext, get the context from the operand.
1032 else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt ||
1033 Opcode == Instruction::FPExt) {
1034 if (auto *Recipe = Operand->getDefiningRecipe()) {
1035 VPValue *ReverseOp;
1036 if (match(Recipe, m_Reverse(m_VPValue(ReverseOp))))
1037 Recipe = ReverseOp->getDefiningRecipe();
1038 if (Recipe)
1039 CCH = ComputeCCH(Recipe);
1040 }
1041 }
1042
1043 auto *ScalarSrcTy = Ctx.Types.inferScalarType(Operand);
1044 Type *SrcTy = VF.isVector() ? toVectorTy(ScalarSrcTy, VF) : ScalarSrcTy;
1045 // Arm TTI will use the underlying instruction to determine the cost.
1046 return Ctx.TTI.getCastInstrCost(
1047 Opcode, ResultTy, SrcTy, CCH, Ctx.CostKind,
1049 }
1050 case Instruction::Select: {
1052 bool IsScalarCond = getOperand(0)->isDefinedOutsideLoopRegions();
1053 Type *ScalarTy = Ctx.Types.inferScalarType(this);
1054
1055 VPValue *Op0, *Op1;
1056 bool IsLogicalAnd =
1057 match(this, m_LogicalAnd(m_VPValue(Op0), m_VPValue(Op1)));
1058 bool IsLogicalOr = match(this, m_LogicalOr(m_VPValue(Op0), m_VPValue(Op1)));
1059 // Also match the inverted forms:
1060 // select x, false, y --> !x & y (still AND)
1061 // select x, y, true --> !x | y (still OR)
1062 IsLogicalAnd |=
1063 match(this, m_Select(m_VPValue(Op0), m_False(), m_VPValue(Op1)));
1064 IsLogicalOr |=
1065 match(this, m_Select(m_VPValue(Op0), m_VPValue(Op1), m_True()));
1066
1067 if (!IsScalarCond && ScalarTy->getScalarSizeInBits() == 1 &&
1068 (IsLogicalAnd || IsLogicalOr)) {
1069 // select x, y, false --> x & y
1070 // select x, true, y --> x | y
1071 const auto [Op1VK, Op1VP] = Ctx.getOperandInfo(Op0);
1072 const auto [Op2VK, Op2VP] = Ctx.getOperandInfo(Op1);
1073
1075 if (SI && all_of(operands(),
1076 [](VPValue *Op) { return Op->getUnderlyingValue(); }))
1077 append_range(Operands, SI->operands());
1078 return Ctx.TTI.getArithmeticInstrCost(
1079 IsLogicalOr ? Instruction::Or : Instruction::And, ResultTy,
1080 Ctx.CostKind, {Op1VK, Op1VP}, {Op2VK, Op2VP}, Operands, SI);
1081 }
1083 Type *CondTy = Ctx.Types.inferScalarType(getOperand(0));
1084 if (!IsScalarCond)
1085 CondTy = VectorType::get(CondTy, VF);
1086
1087 llvm::CmpPredicate Pred;
1088 if (!match(getOperand(0), m_Cmp(Pred, m_VPValue(), m_VPValue())))
1089 if (auto *CondIRV = dyn_cast<VPIRValue>(getOperand(0)))
1090 if (auto *Cmp = dyn_cast<CmpInst>(CondIRV->getValue()))
1091 Pred = Cmp->getPredicate();
1092 Type *VectorTy = toVectorTy(Ctx.Types.inferScalarType(this), VF);
1093 return Ctx.TTI.getCmpSelInstrCost(
1094 Instruction::Select, VectorTy, CondTy, Pred, Ctx.CostKind,
1095 {TTI::OK_AnyValue, TTI::OP_None}, {TTI::OK_AnyValue, TTI::OP_None}, SI);
1096 }
1097 }
1098 llvm_unreachable("called for unsupported opcode");
1099}
1100
1102 VPCostContext &Ctx) const {
1104 if (!getUnderlyingValue() && getOpcode() != Instruction::FMul) {
1105 // TODO: Compute cost for VPInstructions without underlying values once
1106 // the legacy cost model has been retired.
1107 return 0;
1108 }
1109
1111 "Should only generate a vector value or single scalar, not scalars "
1112 "for all lanes.");
1114 getOpcode(),
1116 }
1117
1118 switch (getOpcode()) {
1119 case Instruction::Select: {
1121 match(getOperand(0), m_Cmp(Pred, m_VPValue(), m_VPValue()));
1122 auto *CondTy = Ctx.Types.inferScalarType(getOperand(0));
1123 auto *VecTy = Ctx.Types.inferScalarType(getOperand(1));
1124 if (!vputils::onlyFirstLaneUsed(this)) {
1125 CondTy = toVectorTy(CondTy, VF);
1126 VecTy = toVectorTy(VecTy, VF);
1127 }
1128 return Ctx.TTI.getCmpSelInstrCost(Instruction::Select, VecTy, CondTy, Pred,
1129 Ctx.CostKind);
1130 }
1131 case Instruction::ExtractElement:
1133 if (VF.isScalar()) {
1134 // ExtractLane with VF=1 takes care of handling extracting across multiple
1135 // parts.
1136 return 0;
1137 }
1138
1139 // Add on the cost of extracting the element.
1140 auto *VecTy = toVectorTy(Ctx.Types.inferScalarType(getOperand(0)), VF);
1141 return Ctx.TTI.getVectorInstrCost(Instruction::ExtractElement, VecTy,
1142 Ctx.CostKind);
1143 }
1144 case VPInstruction::AnyOf: {
1145 auto *VecTy = toVectorTy(Ctx.Types.inferScalarType(this), VF);
1146 return Ctx.TTI.getArithmeticReductionCost(
1147 Instruction::Or, cast<VectorType>(VecTy), std::nullopt, Ctx.CostKind);
1148 }
1150 Type *ScalarTy = Ctx.Types.inferScalarType(getOperand(0));
1151 if (VF.isScalar())
1152 return Ctx.TTI.getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
1154 CmpInst::ICMP_EQ, Ctx.CostKind);
1155 // Calculate the cost of determining the lane index.
1156 auto *PredTy = toVectorTy(ScalarTy, VF);
1157 IntrinsicCostAttributes Attrs(Intrinsic::experimental_cttz_elts,
1158 Type::getInt64Ty(Ctx.LLVMCtx),
1159 {PredTy, Type::getInt1Ty(Ctx.LLVMCtx)});
1160 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1161 }
1163 Type *ScalarTy = Ctx.Types.inferScalarType(getOperand(0));
1164 if (VF.isScalar())
1165 return Ctx.TTI.getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
1167 CmpInst::ICMP_EQ, Ctx.CostKind);
1168 // Calculate the cost of determining the lane index: NOT + cttz_elts + SUB.
1169 auto *PredTy = toVectorTy(ScalarTy, VF);
1170 IntrinsicCostAttributes Attrs(Intrinsic::experimental_cttz_elts,
1171 Type::getInt64Ty(Ctx.LLVMCtx),
1172 {PredTy, Type::getInt1Ty(Ctx.LLVMCtx)});
1173 InstructionCost Cost = Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1174 // Add cost of NOT operation on the predicate.
1175 Cost += Ctx.TTI.getArithmeticInstrCost(
1176 Instruction::Xor, PredTy, Ctx.CostKind,
1177 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
1178 {TargetTransformInfo::OK_UniformConstantValue,
1179 TargetTransformInfo::OP_None});
1180 // Add cost of SUB operation on the index.
1181 Cost += Ctx.TTI.getArithmeticInstrCost(
1182 Instruction::Sub, Type::getInt64Ty(Ctx.LLVMCtx), Ctx.CostKind);
1183 return Cost;
1184 }
1186 Type *ScalarTy = Ctx.Types.inferScalarType(this);
1187 Type *VecTy = toVectorTy(ScalarTy, VF);
1188 Type *MaskTy = toVectorTy(Type::getInt1Ty(Ctx.LLVMCtx), VF);
1190 Intrinsic::experimental_vector_extract_last_active, ScalarTy,
1191 {VecTy, MaskTy, ScalarTy});
1192 return Ctx.TTI.getIntrinsicInstrCost(ICA, Ctx.CostKind);
1193 }
1195 assert(VF.isVector() && "Scalar FirstOrderRecurrenceSplice?");
1197 std::iota(Mask.begin(), Mask.end(), VF.getKnownMinValue() - 1);
1198 Type *VectorTy = toVectorTy(Ctx.Types.inferScalarType(this), VF);
1199
1200 return Ctx.TTI.getShuffleCost(TargetTransformInfo::SK_Splice,
1201 cast<VectorType>(VectorTy),
1202 cast<VectorType>(VectorTy), Mask,
1203 Ctx.CostKind, VF.getKnownMinValue() - 1);
1204 }
1206 Type *ArgTy = Ctx.Types.inferScalarType(getOperand(0));
1207 unsigned Multiplier = cast<VPConstantInt>(getOperand(2))->getZExtValue();
1208 Type *RetTy = toVectorTy(Type::getInt1Ty(Ctx.LLVMCtx), VF * Multiplier);
1209 IntrinsicCostAttributes Attrs(Intrinsic::get_active_lane_mask, RetTy,
1210 {ArgTy, ArgTy});
1211 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1212 }
1214 Type *Arg0Ty = Ctx.Types.inferScalarType(getOperand(0));
1215 Type *I32Ty = Type::getInt32Ty(Ctx.LLVMCtx);
1216 Type *I1Ty = Type::getInt1Ty(Ctx.LLVMCtx);
1217 IntrinsicCostAttributes Attrs(Intrinsic::experimental_get_vector_length,
1218 I32Ty, {Arg0Ty, I32Ty, I1Ty});
1219 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1220 }
1222 assert(VF.isVector() && "Reverse operation must be vector type");
1223 auto *VectorTy = cast<VectorType>(
1224 toVectorTy(Ctx.Types.inferScalarType(getOperand(0)), VF));
1225 return Ctx.TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy,
1226 VectorTy, /*Mask=*/{}, Ctx.CostKind,
1227 /*Index=*/0);
1228 }
1230 // Add on the cost of extracting the element.
1231 auto *VecTy = toVectorTy(Ctx.Types.inferScalarType(getOperand(0)), VF);
1232 return Ctx.TTI.getIndexedVectorInstrCostFromEnd(Instruction::ExtractElement,
1233 VecTy, Ctx.CostKind, 0);
1234 }
1236 if (VF == ElementCount::getScalable(1))
1238 [[fallthrough]];
1239 default:
1240 // TODO: Compute cost other VPInstructions once the legacy cost model has
1241 // been retired.
1243 "unexpected VPInstruction witht underlying value");
1244 return 0;
1245 }
1246}
1247
1260
1262 switch (getOpcode()) {
1263 case Instruction::PHI:
1267 return true;
1268 default:
1269 return isScalarCast();
1270 }
1271}
1272
1274 assert(!State.Lane && "VPInstruction executing an Lane");
1275 IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder);
1277 "Set flags not supported for the provided opcode");
1278 if (hasFastMathFlags())
1279 State.Builder.setFastMathFlags(getFastMathFlags());
1280 Value *GeneratedValue = generate(State);
1281 if (!hasResult())
1282 return;
1283 assert(GeneratedValue && "generate must produce a value");
1284 bool GeneratesPerFirstLaneOnly = canGenerateScalarForFirstLane() &&
1287 assert((((GeneratedValue->getType()->isVectorTy() ||
1288 GeneratedValue->getType()->isStructTy()) ==
1289 !GeneratesPerFirstLaneOnly) ||
1290 State.VF.isScalar()) &&
1291 "scalar value but not only first lane defined");
1292 State.set(this, GeneratedValue,
1293 /*IsScalar*/ GeneratesPerFirstLaneOnly);
1294}
1295
1298 return false;
1299 switch (getOpcode()) {
1300 case Instruction::GetElementPtr:
1301 case Instruction::ExtractElement:
1302 case Instruction::Freeze:
1303 case Instruction::FCmp:
1304 case Instruction::ICmp:
1305 case Instruction::Select:
1306 case Instruction::PHI:
1327 case VPInstruction::Not:
1336 return false;
1337 default:
1338 return true;
1339 }
1340}
1341
1343 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
1345 return vputils::onlyFirstLaneUsed(this);
1346
1347 switch (getOpcode()) {
1348 default:
1349 return false;
1350 case Instruction::ExtractElement:
1351 return Op == getOperand(1);
1352 case Instruction::PHI:
1353 return true;
1354 case Instruction::FCmp:
1355 case Instruction::ICmp:
1356 case Instruction::Select:
1357 case Instruction::Or:
1358 case Instruction::Freeze:
1359 case VPInstruction::Not:
1360 // TODO: Cover additional opcodes.
1361 return vputils::onlyFirstLaneUsed(this);
1370 return true;
1373 // Before replicating by VF, Build(Struct)Vector uses all lanes of the
1374 // operand, after replicating its operands only the first lane is used.
1375 // Before replicating, it will have only a single operand.
1376 return getNumOperands() > 1;
1378 return Op == getOperand(0) || vputils::onlyFirstLaneUsed(this);
1380 // WidePtrAdd supports scalar and vector base addresses.
1381 return false;
1383 return Op == getOperand(0) || Op == getOperand(1);
1385 return Op == getOperand(0);
1386 };
1387 llvm_unreachable("switch should return");
1388}
1389
1391 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
1393 return vputils::onlyFirstPartUsed(this);
1394
1395 switch (getOpcode()) {
1396 default:
1397 return false;
1398 case Instruction::FCmp:
1399 case Instruction::ICmp:
1400 case Instruction::Select:
1401 return vputils::onlyFirstPartUsed(this);
1406 return true;
1407 };
1408 llvm_unreachable("switch should return");
1409}
1410
1411#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1413 VPSlotTracker SlotTracker(getParent()->getPlan());
1415}
1416
1418 VPSlotTracker &SlotTracker) const {
1419 O << Indent << "EMIT" << (isSingleScalar() ? "-SCALAR" : "") << " ";
1420
1421 if (hasResult()) {
1423 O << " = ";
1424 }
1425
1426 switch (getOpcode()) {
1427 case VPInstruction::Not:
1428 O << "not";
1429 break;
1431 O << "combined load";
1432 break;
1434 O << "combined store";
1435 break;
1437 O << "active lane mask";
1438 break;
1440 O << "EXPLICIT-VECTOR-LENGTH";
1441 break;
1443 O << "first-order splice";
1444 break;
1446 O << "branch-on-cond";
1447 break;
1449 O << "branch-on-two-conds";
1450 break;
1452 O << "TC > VF ? TC - VF : 0";
1453 break;
1455 O << "VF * Part +";
1456 break;
1458 O << "branch-on-count";
1459 break;
1461 O << "broadcast";
1462 break;
1464 O << "buildstructvector";
1465 break;
1467 O << "buildvector";
1468 break;
1470 O << "extract-lane";
1471 break;
1473 O << "extract-last-lane";
1474 break;
1476 O << "extract-last-part";
1477 break;
1479 O << "extract-penultimate-element";
1480 break;
1482 O << "compute-anyof-result";
1483 break;
1485 O << "compute-reduction-result";
1486 break;
1488 O << "logical-and";
1489 break;
1491 O << "ptradd";
1492 break;
1494 O << "wide-ptradd";
1495 break;
1497 O << "any-of";
1498 break;
1500 O << "first-active-lane";
1501 break;
1503 O << "last-active-lane";
1504 break;
1506 O << "reduction-start-vector";
1507 break;
1509 O << "resume-for-epilogue";
1510 break;
1512 O << "reverse";
1513 break;
1515 O << "unpack";
1516 break;
1518 O << "extract-last-active";
1519 break;
1520 default:
1522 }
1523
1524 printFlags(O);
1526}
1527#endif
1528
1530 State.setDebugLocFrom(getDebugLoc());
1531 if (isScalarCast()) {
1532 Value *Op = State.get(getOperand(0), VPLane(0));
1533 Value *Cast = State.Builder.CreateCast(Instruction::CastOps(getOpcode()),
1534 Op, ResultTy);
1535 State.set(this, Cast, VPLane(0));
1536 return;
1537 }
1538 switch (getOpcode()) {
1540 Value *StepVector =
1541 State.Builder.CreateStepVector(VectorType::get(ResultTy, State.VF));
1542 State.set(this, StepVector);
1543 break;
1544 }
1545 case VPInstruction::VScale: {
1546 Value *VScale = State.Builder.CreateVScale(ResultTy);
1547 State.set(this, VScale, true);
1548 break;
1549 }
1550
1551 default:
1552 llvm_unreachable("opcode not implemented yet");
1553 }
1554}
1555
1556#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1558 VPSlotTracker &SlotTracker) const {
1559 O << Indent << "EMIT" << (isSingleScalar() ? "-SCALAR" : "") << " ";
1561 O << " = ";
1562
1563 switch (getOpcode()) {
1565 O << "wide-iv-step ";
1567 break;
1569 O << "step-vector " << *ResultTy;
1570 break;
1572 O << "vscale " << *ResultTy;
1573 break;
1574 default:
1575 assert(Instruction::isCast(getOpcode()) && "unhandled opcode");
1578 O << " to " << *ResultTy;
1579 }
1580}
1581#endif
1582
1584 State.setDebugLocFrom(getDebugLoc());
1585 PHINode *NewPhi = State.Builder.CreatePHI(
1586 State.TypeAnalysis.inferScalarType(this), 2, getName());
1587 unsigned NumIncoming = getNumIncoming();
1588 if (getParent() != getParent()->getPlan()->getScalarPreheader()) {
1589 // TODO: Fixup all incoming values of header phis once recipes defining them
1590 // are introduced.
1591 NumIncoming = 1;
1592 }
1593 for (unsigned Idx = 0; Idx != NumIncoming; ++Idx) {
1594 Value *IncV = State.get(getIncomingValue(Idx), VPLane(0));
1595 BasicBlock *PredBB = State.CFG.VPBB2IRBB.at(getIncomingBlock(Idx));
1596 NewPhi->addIncoming(IncV, PredBB);
1597 }
1598 State.set(this, NewPhi, VPLane(0));
1599}
1600
1601#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1602void VPPhi::printRecipe(raw_ostream &O, const Twine &Indent,
1603 VPSlotTracker &SlotTracker) const {
1604 O << Indent << "EMIT" << (isSingleScalar() ? "-SCALAR" : "") << " ";
1606 O << " = phi ";
1608}
1609#endif
1610
1611VPIRInstruction *VPIRInstruction ::create(Instruction &I) {
1612 if (auto *Phi = dyn_cast<PHINode>(&I))
1613 return new VPIRPhi(*Phi);
1614 return new VPIRInstruction(I);
1615}
1616
1618 assert(!isa<VPIRPhi>(this) && getNumOperands() == 0 &&
1619 "PHINodes must be handled by VPIRPhi");
1620 // Advance the insert point after the wrapped IR instruction. This allows
1621 // interleaving VPIRInstructions and other recipes.
1622 State.Builder.SetInsertPoint(I.getParent(), std::next(I.getIterator()));
1623}
1624
1626 VPCostContext &Ctx) const {
1627 // The recipe wraps an existing IR instruction on the border of VPlan's scope,
1628 // hence it does not contribute to the cost-modeling for the VPlan.
1629 return 0;
1630}
1631
1633 VPBuilder &Builder) {
1635 "can only update exiting operands to phi nodes");
1636 assert(getNumOperands() > 0 && "must have at least one operand");
1637 VPValue *Exiting = getOperand(0);
1638 if (isa<VPIRValue>(Exiting))
1639 return;
1640
1641 Exiting = Builder.createNaryOp(VPInstruction::ExtractLastPart, Exiting);
1642 Exiting = Builder.createNaryOp(VPInstruction::ExtractLastLane, Exiting);
1643 setOperand(0, Exiting);
1644}
1645
1646#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1648 VPSlotTracker &SlotTracker) const {
1649 O << Indent << "IR " << I;
1650}
1651#endif
1652
1654 PHINode *Phi = &getIRPhi();
1655 for (const auto &[Idx, Op] : enumerate(operands())) {
1656 VPValue *ExitValue = Op;
1657 auto Lane = vputils::isSingleScalar(ExitValue)
1659 : VPLane::getLastLaneForVF(State.VF);
1660 VPBlockBase *Pred = getParent()->getPredecessors()[Idx];
1661 auto *PredVPBB = Pred->getExitingBasicBlock();
1662 BasicBlock *PredBB = State.CFG.VPBB2IRBB[PredVPBB];
1663 // Set insertion point in PredBB in case an extract needs to be generated.
1664 // TODO: Model extracts explicitly.
1665 State.Builder.SetInsertPoint(PredBB, PredBB->getFirstNonPHIIt());
1666 Value *V = State.get(ExitValue, VPLane(Lane));
1667 // If there is no existing block for PredBB in the phi, add a new incoming
1668 // value. Otherwise update the existing incoming value for PredBB.
1669 if (Phi->getBasicBlockIndex(PredBB) == -1)
1670 Phi->addIncoming(V, PredBB);
1671 else
1672 Phi->setIncomingValueForBlock(PredBB, V);
1673 }
1674
1675 // Advance the insert point after the wrapped IR instruction. This allows
1676 // interleaving VPIRInstructions and other recipes.
1677 State.Builder.SetInsertPoint(Phi->getParent(), std::next(Phi->getIterator()));
1678}
1679
1681 VPRecipeBase *R = const_cast<VPRecipeBase *>(getAsRecipe());
1682 assert(R->getNumOperands() == R->getParent()->getNumPredecessors() &&
1683 "Number of phi operands must match number of predecessors");
1684 unsigned Position = R->getParent()->getIndexForPredecessor(IncomingBlock);
1685 R->removeOperand(Position);
1686}
1687
1688#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1690 VPSlotTracker &SlotTracker) const {
1691 interleaveComma(enumerate(getAsRecipe()->operands()), O,
1692 [this, &O, &SlotTracker](auto Op) {
1693 O << "[ ";
1694 Op.value()->printAsOperand(O, SlotTracker);
1695 O << ", ";
1696 getIncomingBlock(Op.index())->printAsOperand(O);
1697 O << " ]";
1698 });
1699}
1700#endif
1701
1702#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1704 VPSlotTracker &SlotTracker) const {
1706
1707 if (getNumOperands() != 0) {
1708 O << " (extra operand" << (getNumOperands() > 1 ? "s" : "") << ": ";
1710 [&O, &SlotTracker](auto Op) {
1711 std::get<0>(Op)->printAsOperand(O, SlotTracker);
1712 O << " from ";
1713 std::get<1>(Op)->printAsOperand(O);
1714 });
1715 O << ")";
1716 }
1717}
1718#endif
1719
1721 for (const auto &[Kind, Node] : Metadata)
1722 I.setMetadata(Kind, Node);
1723}
1724
1726 SmallVector<std::pair<unsigned, MDNode *>> MetadataIntersection;
1727 for (const auto &[KindA, MDA] : Metadata) {
1728 for (const auto &[KindB, MDB] : Other.Metadata) {
1729 if (KindA == KindB && MDA == MDB) {
1730 MetadataIntersection.emplace_back(KindA, MDA);
1731 break;
1732 }
1733 }
1734 }
1735 Metadata = std::move(MetadataIntersection);
1736}
1737
1738#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1740 const Module *M = SlotTracker.getModule();
1741 if (Metadata.empty() || !M)
1742 return;
1743
1744 ArrayRef<StringRef> MDNames = SlotTracker.getMDNames();
1745 O << " (";
1746 interleaveComma(Metadata, O, [&](const auto &KindNodePair) {
1747 auto [Kind, Node] = KindNodePair;
1748 assert(Kind < MDNames.size() && !MDNames[Kind].empty() &&
1749 "Unexpected unnamed metadata kind");
1750 O << "!" << MDNames[Kind] << " ";
1751 Node->printAsOperand(O, M);
1752 });
1753 O << ")";
1754}
1755#endif
1756
1758 assert(State.VF.isVector() && "not widening");
1759 assert(Variant != nullptr && "Can't create vector function.");
1760
1761 FunctionType *VFTy = Variant->getFunctionType();
1762 // Add return type if intrinsic is overloaded on it.
1764 for (const auto &I : enumerate(args())) {
1765 Value *Arg;
1766 // Some vectorized function variants may also take a scalar argument,
1767 // e.g. linear parameters for pointers. This needs to be the scalar value
1768 // from the start of the respective part when interleaving.
1769 if (!VFTy->getParamType(I.index())->isVectorTy())
1770 Arg = State.get(I.value(), VPLane(0));
1771 else
1772 Arg = State.get(I.value(), usesFirstLaneOnly(I.value()));
1773 Args.push_back(Arg);
1774 }
1775
1778 if (CI)
1779 CI->getOperandBundlesAsDefs(OpBundles);
1780
1781 CallInst *V = State.Builder.CreateCall(Variant, Args, OpBundles);
1782 applyFlags(*V);
1783 applyMetadata(*V);
1784 V->setCallingConv(Variant->getCallingConv());
1785
1786 if (!V->getType()->isVoidTy())
1787 State.set(this, V);
1788}
1789
1791 VPCostContext &Ctx) const {
1792 return Ctx.TTI.getCallInstrCost(nullptr, Variant->getReturnType(),
1793 Variant->getFunctionType()->params(),
1794 Ctx.CostKind);
1795}
1796
1797#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1799 VPSlotTracker &SlotTracker) const {
1800 O << Indent << "WIDEN-CALL ";
1801
1802 Function *CalledFn = getCalledScalarFunction();
1803 if (CalledFn->getReturnType()->isVoidTy())
1804 O << "void ";
1805 else {
1807 O << " = ";
1808 }
1809
1810 O << "call";
1811 printFlags(O);
1812 O << " @" << CalledFn->getName() << "(";
1813 interleaveComma(args(), O, [&O, &SlotTracker](VPValue *Op) {
1814 Op->printAsOperand(O, SlotTracker);
1815 });
1816 O << ")";
1817
1818 O << " (using library function";
1819 if (Variant->hasName())
1820 O << ": " << Variant->getName();
1821 O << ")";
1822}
1823#endif
1824
1826 assert(State.VF.isVector() && "not widening");
1827
1828 SmallVector<Type *, 2> TysForDecl;
1829 // Add return type if intrinsic is overloaded on it.
1830 if (isVectorIntrinsicWithOverloadTypeAtArg(VectorIntrinsicID, -1,
1831 State.TTI)) {
1832 Type *RetTy = toVectorizedTy(getResultType(), State.VF);
1833 ArrayRef<Type *> ContainedTys = getContainedTypes(RetTy);
1834 for (auto [Idx, Ty] : enumerate(ContainedTys)) {
1836 Idx, State.TTI))
1837 TysForDecl.push_back(Ty);
1838 }
1839 }
1841 for (const auto &I : enumerate(operands())) {
1842 // Some intrinsics have a scalar argument - don't replace it with a
1843 // vector.
1844 Value *Arg;
1845 if (isVectorIntrinsicWithScalarOpAtArg(VectorIntrinsicID, I.index(),
1846 State.TTI))
1847 Arg = State.get(I.value(), VPLane(0));
1848 else
1849 Arg = State.get(I.value(), usesFirstLaneOnly(I.value()));
1850 if (isVectorIntrinsicWithOverloadTypeAtArg(VectorIntrinsicID, I.index(),
1851 State.TTI))
1852 TysForDecl.push_back(Arg->getType());
1853 Args.push_back(Arg);
1854 }
1855
1856 // Use vector version of the intrinsic.
1857 Module *M = State.Builder.GetInsertBlock()->getModule();
1858 Function *VectorF =
1859 Intrinsic::getOrInsertDeclaration(M, VectorIntrinsicID, TysForDecl);
1860 assert(VectorF &&
1861 "Can't retrieve vector intrinsic or vector-predication intrinsics.");
1862
1865 if (CI)
1866 CI->getOperandBundlesAsDefs(OpBundles);
1867
1868 CallInst *V = State.Builder.CreateCall(VectorF, Args, OpBundles);
1869
1870 applyFlags(*V);
1871 applyMetadata(*V);
1872
1873 if (!V->getType()->isVoidTy())
1874 State.set(this, V);
1875}
1876
1877/// Compute the cost for the intrinsic \p ID with \p Operands, produced by \p R.
1880 const VPRecipeWithIRFlags &R,
1881 ElementCount VF,
1882 VPCostContext &Ctx) {
1883 // Some backends analyze intrinsic arguments to determine cost. Use the
1884 // underlying value for the operand if it has one. Otherwise try to use the
1885 // operand of the underlying call instruction, if there is one. Otherwise
1886 // clear Arguments.
1887 // TODO: Rework TTI interface to be independent of concrete IR values.
1889 for (const auto &[Idx, Op] : enumerate(Operands)) {
1890 auto *V = Op->getUnderlyingValue();
1891 if (!V) {
1892 if (auto *UI = dyn_cast_or_null<CallBase>(R.getUnderlyingValue())) {
1893 Arguments.push_back(UI->getArgOperand(Idx));
1894 continue;
1895 }
1896 Arguments.clear();
1897 break;
1898 }
1899 Arguments.push_back(V);
1900 }
1901
1902 Type *ScalarRetTy = Ctx.Types.inferScalarType(&R);
1903 Type *RetTy = VF.isVector() ? toVectorizedTy(ScalarRetTy, VF) : ScalarRetTy;
1904 SmallVector<Type *> ParamTys;
1905 for (const VPValue *Op : Operands) {
1906 ParamTys.push_back(VF.isVector()
1907 ? toVectorTy(Ctx.Types.inferScalarType(Op), VF)
1908 : Ctx.Types.inferScalarType(Op));
1909 }
1910
1911 // TODO: Rework TTI interface to avoid reliance on underlying IntrinsicInst.
1912 FastMathFlags FMF =
1913 R.hasFastMathFlags() ? R.getFastMathFlags() : FastMathFlags();
1914 IntrinsicCostAttributes CostAttrs(
1915 ID, RetTy, Arguments, ParamTys, FMF,
1916 dyn_cast_or_null<IntrinsicInst>(R.getUnderlyingValue()),
1917 InstructionCost::getInvalid(), &Ctx.TLI);
1918 return Ctx.TTI.getIntrinsicInstrCost(CostAttrs, Ctx.CostKind);
1919}
1920
1922 VPCostContext &Ctx) const {
1924 return getCostForIntrinsics(VectorIntrinsicID, ArgOps, *this, VF, Ctx);
1925}
1926
1928 return Intrinsic::getBaseName(VectorIntrinsicID);
1929}
1930
1932 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
1933 return all_of(enumerate(operands()), [this, &Op](const auto &X) {
1934 auto [Idx, V] = X;
1936 Idx, nullptr);
1937 });
1938}
1939
1940#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1942 VPSlotTracker &SlotTracker) const {
1943 O << Indent << "WIDEN-INTRINSIC ";
1944 if (ResultTy->isVoidTy()) {
1945 O << "void ";
1946 } else {
1948 O << " = ";
1949 }
1950
1951 O << "call";
1952 printFlags(O);
1953 O << getIntrinsicName() << "(";
1954
1956 Op->printAsOperand(O, SlotTracker);
1957 });
1958 O << ")";
1959}
1960#endif
1961
1963 IRBuilderBase &Builder = State.Builder;
1964
1965 Value *Address = State.get(getOperand(0));
1966 Value *IncAmt = State.get(getOperand(1), /*IsScalar=*/true);
1967 VectorType *VTy = cast<VectorType>(Address->getType());
1968
1969 // The histogram intrinsic requires a mask even if the recipe doesn't;
1970 // if the mask operand was omitted then all lanes should be executed and
1971 // we just need to synthesize an all-true mask.
1972 Value *Mask = nullptr;
1973 if (VPValue *VPMask = getMask())
1974 Mask = State.get(VPMask);
1975 else
1976 Mask =
1977 Builder.CreateVectorSplat(VTy->getElementCount(), Builder.getInt1(1));
1978
1979 // If this is a subtract, we want to invert the increment amount. We may
1980 // add a separate intrinsic in future, but for now we'll try this.
1981 if (Opcode == Instruction::Sub)
1982 IncAmt = Builder.CreateNeg(IncAmt);
1983 else
1984 assert(Opcode == Instruction::Add && "only add or sub supported for now");
1985
1986 State.Builder.CreateIntrinsic(Intrinsic::experimental_vector_histogram_add,
1987 {VTy, IncAmt->getType()},
1988 {Address, IncAmt, Mask});
1989}
1990
1992 VPCostContext &Ctx) const {
1993 // FIXME: Take the gather and scatter into account as well. For now we're
1994 // generating the same cost as the fallback path, but we'll likely
1995 // need to create a new TTI method for determining the cost, including
1996 // whether we can use base + vec-of-smaller-indices or just
1997 // vec-of-pointers.
1998 assert(VF.isVector() && "Invalid VF for histogram cost");
1999 Type *AddressTy = Ctx.Types.inferScalarType(getOperand(0));
2000 VPValue *IncAmt = getOperand(1);
2001 Type *IncTy = Ctx.Types.inferScalarType(IncAmt);
2002 VectorType *VTy = VectorType::get(IncTy, VF);
2003
2004 // Assume that a non-constant update value (or a constant != 1) requires
2005 // a multiply, and add that into the cost.
2006 InstructionCost MulCost =
2007 Ctx.TTI.getArithmeticInstrCost(Instruction::Mul, VTy, Ctx.CostKind);
2008 if (auto *CI = dyn_cast<VPConstantInt>(IncAmt))
2009 if (CI->isOne())
2010 MulCost = TTI::TCC_Free;
2011
2012 // Find the cost of the histogram operation itself.
2013 Type *PtrTy = VectorType::get(AddressTy, VF);
2014 Type *MaskTy = VectorType::get(Type::getInt1Ty(Ctx.LLVMCtx), VF);
2015 IntrinsicCostAttributes ICA(Intrinsic::experimental_vector_histogram_add,
2016 Type::getVoidTy(Ctx.LLVMCtx),
2017 {PtrTy, IncTy, MaskTy});
2018
2019 // Add the costs together with the add/sub operation.
2020 return Ctx.TTI.getIntrinsicInstrCost(ICA, Ctx.CostKind) + MulCost +
2021 Ctx.TTI.getArithmeticInstrCost(Opcode, VTy, Ctx.CostKind);
2022}
2023
2024#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2026 VPSlotTracker &SlotTracker) const {
2027 O << Indent << "WIDEN-HISTOGRAM buckets: ";
2029
2030 if (Opcode == Instruction::Sub)
2031 O << ", dec: ";
2032 else {
2033 assert(Opcode == Instruction::Add);
2034 O << ", inc: ";
2035 }
2037
2038 if (VPValue *Mask = getMask()) {
2039 O << ", mask: ";
2040 Mask->printAsOperand(O, SlotTracker);
2041 }
2042}
2043#endif
2044
2045VPIRFlags::FastMathFlagsTy::FastMathFlagsTy(const FastMathFlags &FMF) {
2046 AllowReassoc = FMF.allowReassoc();
2047 NoNaNs = FMF.noNaNs();
2048 NoInfs = FMF.noInfs();
2049 NoSignedZeros = FMF.noSignedZeros();
2050 AllowReciprocal = FMF.allowReciprocal();
2051 AllowContract = FMF.allowContract();
2052 ApproxFunc = FMF.approxFunc();
2053}
2054
2055#if !defined(NDEBUG)
2056bool VPIRFlags::flagsValidForOpcode(unsigned Opcode) const {
2057 switch (OpType) {
2058 case OperationType::OverflowingBinOp:
2059 return Opcode == Instruction::Add || Opcode == Instruction::Sub ||
2060 Opcode == Instruction::Mul || Opcode == Instruction::Shl ||
2061 Opcode == VPInstruction::VPInstruction::CanonicalIVIncrementForPart;
2062 case OperationType::Trunc:
2063 return Opcode == Instruction::Trunc;
2064 case OperationType::DisjointOp:
2065 return Opcode == Instruction::Or;
2066 case OperationType::PossiblyExactOp:
2067 return Opcode == Instruction::AShr || Opcode == Instruction::LShr ||
2068 Opcode == Instruction::UDiv || Opcode == Instruction::SDiv;
2069 case OperationType::GEPOp:
2070 return Opcode == Instruction::GetElementPtr ||
2071 Opcode == VPInstruction::PtrAdd ||
2072 Opcode == VPInstruction::WidePtrAdd;
2073 case OperationType::FPMathOp:
2074 return Opcode == Instruction::Call || Opcode == Instruction::FAdd ||
2075 Opcode == Instruction::FMul || Opcode == Instruction::FSub ||
2076 Opcode == Instruction::FNeg || Opcode == Instruction::FDiv ||
2077 Opcode == Instruction::FRem || Opcode == Instruction::FPExt ||
2078 Opcode == Instruction::FPTrunc || Opcode == Instruction::Select ||
2079 Opcode == VPInstruction::WideIVStep ||
2081 case OperationType::FCmp:
2082 return Opcode == Instruction::FCmp;
2083 case OperationType::NonNegOp:
2084 return Opcode == Instruction::ZExt || Opcode == Instruction::UIToFP;
2085 case OperationType::Cmp:
2086 return Opcode == Instruction::FCmp || Opcode == Instruction::ICmp;
2087 case OperationType::ReductionOp:
2089 case OperationType::Other:
2090 return true;
2091 }
2092 llvm_unreachable("Unknown OperationType enum");
2093}
2094#endif
2095
2096#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2098 switch (OpType) {
2099 case OperationType::Cmp:
2101 break;
2102 case OperationType::FCmp:
2105 break;
2106 case OperationType::DisjointOp:
2107 if (DisjointFlags.IsDisjoint)
2108 O << " disjoint";
2109 break;
2110 case OperationType::PossiblyExactOp:
2111 if (ExactFlags.IsExact)
2112 O << " exact";
2113 break;
2114 case OperationType::OverflowingBinOp:
2115 if (WrapFlags.HasNUW)
2116 O << " nuw";
2117 if (WrapFlags.HasNSW)
2118 O << " nsw";
2119 break;
2120 case OperationType::Trunc:
2121 if (TruncFlags.HasNUW)
2122 O << " nuw";
2123 if (TruncFlags.HasNSW)
2124 O << " nsw";
2125 break;
2126 case OperationType::FPMathOp:
2128 break;
2129 case OperationType::GEPOp:
2130 if (GEPFlags.isInBounds())
2131 O << " inbounds";
2132 else if (GEPFlags.hasNoUnsignedSignedWrap())
2133 O << " nusw";
2134 if (GEPFlags.hasNoUnsignedWrap())
2135 O << " nuw";
2136 break;
2137 case OperationType::NonNegOp:
2138 if (NonNegFlags.NonNeg)
2139 O << " nneg";
2140 break;
2141 case OperationType::ReductionOp: {
2142 RecurKind RK = getRecurKind();
2143 O << " (";
2144 switch (RK) {
2145 case RecurKind::AnyOf:
2146 O << "any-of";
2147 break;
2148 case RecurKind::SMax:
2149 O << "smax";
2150 break;
2151 case RecurKind::SMin:
2152 O << "smin";
2153 break;
2154 case RecurKind::UMax:
2155 O << "umax";
2156 break;
2157 case RecurKind::UMin:
2158 O << "umin";
2159 break;
2160 case RecurKind::FMinNum:
2161 O << "fminnum";
2162 break;
2163 case RecurKind::FMaxNum:
2164 O << "fmaxnum";
2165 break;
2167 O << "fminimum";
2168 break;
2170 O << "fmaximum";
2171 break;
2173 O << "fminimumnum";
2174 break;
2176 O << "fmaximumnum";
2177 break;
2178 default:
2180 break;
2181 }
2182 if (isReductionInLoop())
2183 O << ", in-loop";
2184 if (isReductionOrdered())
2185 O << ", ordered";
2186 O << ")";
2188 break;
2189 }
2190 case OperationType::Other:
2191 break;
2192 }
2193 O << " ";
2194}
2195#endif
2196
2198 auto &Builder = State.Builder;
2199 switch (Opcode) {
2200 case Instruction::Call:
2201 case Instruction::Br:
2202 case Instruction::PHI:
2203 case Instruction::GetElementPtr:
2204 llvm_unreachable("This instruction is handled by a different recipe.");
2205 case Instruction::UDiv:
2206 case Instruction::SDiv:
2207 case Instruction::SRem:
2208 case Instruction::URem:
2209 case Instruction::Add:
2210 case Instruction::FAdd:
2211 case Instruction::Sub:
2212 case Instruction::FSub:
2213 case Instruction::FNeg:
2214 case Instruction::Mul:
2215 case Instruction::FMul:
2216 case Instruction::FDiv:
2217 case Instruction::FRem:
2218 case Instruction::Shl:
2219 case Instruction::LShr:
2220 case Instruction::AShr:
2221 case Instruction::And:
2222 case Instruction::Or:
2223 case Instruction::Xor: {
2224 // Just widen unops and binops.
2226 for (VPValue *VPOp : operands())
2227 Ops.push_back(State.get(VPOp));
2228
2229 Value *V = Builder.CreateNAryOp(Opcode, Ops);
2230
2231 if (auto *VecOp = dyn_cast<Instruction>(V)) {
2232 applyFlags(*VecOp);
2233 applyMetadata(*VecOp);
2234 }
2235
2236 // Use this vector value for all users of the original instruction.
2237 State.set(this, V);
2238 break;
2239 }
2240 case Instruction::ExtractValue: {
2241 assert(getNumOperands() == 2 && "expected single level extractvalue");
2242 Value *Op = State.get(getOperand(0));
2243 Value *Extract = Builder.CreateExtractValue(
2244 Op, cast<VPConstantInt>(getOperand(1))->getZExtValue());
2245 State.set(this, Extract);
2246 break;
2247 }
2248 case Instruction::Freeze: {
2249 Value *Op = State.get(getOperand(0));
2250 Value *Freeze = Builder.CreateFreeze(Op);
2251 State.set(this, Freeze);
2252 break;
2253 }
2254 case Instruction::ICmp:
2255 case Instruction::FCmp: {
2256 // Widen compares. Generate vector compares.
2257 bool FCmp = Opcode == Instruction::FCmp;
2258 Value *A = State.get(getOperand(0));
2259 Value *B = State.get(getOperand(1));
2260 Value *C = nullptr;
2261 if (FCmp) {
2262 C = Builder.CreateFCmp(getPredicate(), A, B);
2263 } else {
2264 C = Builder.CreateICmp(getPredicate(), A, B);
2265 }
2266 if (auto *I = dyn_cast<Instruction>(C)) {
2267 applyFlags(*I);
2268 applyMetadata(*I);
2269 }
2270 State.set(this, C);
2271 break;
2272 }
2273 case Instruction::Select: {
2274 VPValue *CondOp = getOperand(0);
2275 Value *Cond = State.get(CondOp, vputils::isSingleScalar(CondOp));
2276 Value *Op0 = State.get(getOperand(1));
2277 Value *Op1 = State.get(getOperand(2));
2278 Value *Sel = State.Builder.CreateSelect(Cond, Op0, Op1);
2279 State.set(this, Sel);
2280 if (auto *I = dyn_cast<Instruction>(Sel)) {
2282 applyFlags(*I);
2283 applyMetadata(*I);
2284 }
2285 break;
2286 }
2287 default:
2288 // This instruction is not vectorized by simple widening.
2289 LLVM_DEBUG(dbgs() << "LV: Found an unhandled opcode : "
2290 << Instruction::getOpcodeName(Opcode));
2291 llvm_unreachable("Unhandled instruction!");
2292 } // end of switch.
2293
2294#if !defined(NDEBUG)
2295 // Verify that VPlan type inference results agree with the type of the
2296 // generated values.
2297 assert(VectorType::get(State.TypeAnalysis.inferScalarType(this), State.VF) ==
2298 State.get(this)->getType() &&
2299 "inferred type and type from generated instructions do not match");
2300#endif
2301}
2302
2304 VPCostContext &Ctx) const {
2305 switch (Opcode) {
2306 case Instruction::UDiv:
2307 case Instruction::SDiv:
2308 case Instruction::SRem:
2309 case Instruction::URem:
2310 // If the div/rem operation isn't safe to speculate and requires
2311 // predication, then the only way we can even create a vplan is to insert
2312 // a select on the second input operand to ensure we use the value of 1
2313 // for the inactive lanes. The select will be costed separately.
2314 case Instruction::FNeg:
2315 case Instruction::Add:
2316 case Instruction::FAdd:
2317 case Instruction::Sub:
2318 case Instruction::FSub:
2319 case Instruction::Mul:
2320 case Instruction::FMul:
2321 case Instruction::FDiv:
2322 case Instruction::FRem:
2323 case Instruction::Shl:
2324 case Instruction::LShr:
2325 case Instruction::AShr:
2326 case Instruction::And:
2327 case Instruction::Or:
2328 case Instruction::Xor:
2329 case Instruction::Freeze:
2330 case Instruction::ExtractValue:
2331 case Instruction::ICmp:
2332 case Instruction::FCmp:
2333 case Instruction::Select:
2334 return getCostForRecipeWithOpcode(getOpcode(), VF, Ctx);
2335 default:
2336 llvm_unreachable("Unsupported opcode for instruction");
2337 }
2338}
2339
2340#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2342 VPSlotTracker &SlotTracker) const {
2343 O << Indent << "WIDEN ";
2345 O << " = " << Instruction::getOpcodeName(Opcode);
2346 printFlags(O);
2348}
2349#endif
2350
2352 auto &Builder = State.Builder;
2353 /// Vectorize casts.
2354 assert(State.VF.isVector() && "Not vectorizing?");
2355 Type *DestTy = VectorType::get(getResultType(), State.VF);
2356 VPValue *Op = getOperand(0);
2357 Value *A = State.get(Op);
2358 Value *Cast = Builder.CreateCast(Instruction::CastOps(Opcode), A, DestTy);
2359 State.set(this, Cast);
2360 if (auto *CastOp = dyn_cast<Instruction>(Cast)) {
2361 applyFlags(*CastOp);
2362 applyMetadata(*CastOp);
2363 }
2364}
2365
2367 VPCostContext &Ctx) const {
2368 // TODO: In some cases, VPWidenCastRecipes are created but not considered in
2369 // the legacy cost model, including truncates/extends when evaluating a
2370 // reduction in a smaller type.
2371 if (!getUnderlyingValue())
2372 return 0;
2373 return getCostForRecipeWithOpcode(getOpcode(), VF, Ctx);
2374}
2375
2376#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2378 VPSlotTracker &SlotTracker) const {
2379 O << Indent << "WIDEN-CAST ";
2381 O << " = " << Instruction::getOpcodeName(Opcode);
2382 printFlags(O);
2384 O << " to " << *getResultType();
2385}
2386#endif
2387
2389 VPCostContext &Ctx) const {
2390 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
2391}
2392
2393#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2395 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
2396 O << Indent;
2398 O << " = WIDEN-INDUCTION";
2399 printFlags(O);
2401
2402 if (auto *TI = getTruncInst())
2403 O << " (truncated to " << *TI->getType() << ")";
2404}
2405#endif
2406
2408 // The step may be defined by a recipe in the preheader (e.g. if it requires
2409 // SCEV expansion), but for the canonical induction the step is required to be
2410 // 1, which is represented as live-in.
2411 auto *StepC = dyn_cast<VPConstantInt>(getStepValue());
2412 auto *StartC = dyn_cast<VPConstantInt>(getStartValue());
2413 return StartC && StartC->isZero() && StepC && StepC->isOne() &&
2414 getScalarType() == getRegion()->getCanonicalIVType();
2415}
2416
2418 assert(!State.Lane && "VPDerivedIVRecipe being replicated.");
2419
2420 // Fast-math-flags propagate from the original induction instruction.
2421 IRBuilder<>::FastMathFlagGuard FMFG(State.Builder);
2422 if (FPBinOp)
2423 State.Builder.setFastMathFlags(FPBinOp->getFastMathFlags());
2424
2425 Value *Step = State.get(getStepValue(), VPLane(0));
2426 Value *Index = State.get(getOperand(1), VPLane(0));
2427 Value *DerivedIV = emitTransformedIndex(
2428 State.Builder, Index, getStartValue()->getLiveInIRValue(), Step, Kind,
2430 DerivedIV->setName(Name);
2431 State.set(this, DerivedIV, VPLane(0));
2432}
2433
2434#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2436 VPSlotTracker &SlotTracker) const {
2437 O << Indent;
2439 O << " = DERIVED-IV ";
2440 getStartValue()->printAsOperand(O, SlotTracker);
2441 O << " + ";
2442 getOperand(1)->printAsOperand(O, SlotTracker);
2443 O << " * ";
2444 getStepValue()->printAsOperand(O, SlotTracker);
2445}
2446#endif
2447
2449 // Fast-math-flags propagate from the original induction instruction.
2450 IRBuilder<>::FastMathFlagGuard FMFG(State.Builder);
2451 if (hasFastMathFlags())
2452 State.Builder.setFastMathFlags(getFastMathFlags());
2453
2454 /// Compute scalar induction steps. \p ScalarIV is the scalar induction
2455 /// variable on which to base the steps, \p Step is the size of the step.
2456
2457 Value *BaseIV = State.get(getOperand(0), VPLane(0));
2458 Value *Step = State.get(getStepValue(), VPLane(0));
2459 IRBuilderBase &Builder = State.Builder;
2460
2461 // Ensure step has the same type as that of scalar IV.
2462 Type *BaseIVTy = BaseIV->getType()->getScalarType();
2463 assert(BaseIVTy == Step->getType() && "Types of BaseIV and Step must match!");
2464
2465 // We build scalar steps for both integer and floating-point induction
2466 // variables. Here, we determine the kind of arithmetic we will perform.
2469 if (BaseIVTy->isIntegerTy()) {
2470 AddOp = Instruction::Add;
2471 MulOp = Instruction::Mul;
2472 } else {
2473 AddOp = InductionOpcode;
2474 MulOp = Instruction::FMul;
2475 }
2476
2477 // Determine the number of scalars we need to generate.
2478 bool FirstLaneOnly = vputils::onlyFirstLaneUsed(this);
2479 // Compute the scalar steps and save the results in State.
2480
2481 unsigned StartLane = 0;
2482 unsigned EndLane = FirstLaneOnly ? 1 : State.VF.getKnownMinValue();
2483 if (State.Lane) {
2484 StartLane = State.Lane->getKnownLane();
2485 EndLane = StartLane + 1;
2486 }
2487 Value *StartIdx0 = getStartIndex() ? State.get(getStartIndex(), true)
2488 : Constant::getNullValue(BaseIVTy);
2489
2490 for (unsigned Lane = StartLane; Lane < EndLane; ++Lane) {
2491 // It is okay if the induction variable type cannot hold the lane number,
2492 // we expect truncation in this case.
2493 Constant *LaneValue =
2494 BaseIVTy->isIntegerTy()
2495 ? ConstantInt::get(BaseIVTy, Lane, /*IsSigned=*/false,
2496 /*ImplicitTrunc=*/true)
2497 : ConstantFP::get(BaseIVTy, Lane);
2498 Value *StartIdx = Builder.CreateBinOp(AddOp, StartIdx0, LaneValue);
2499 // The step returned by `createStepForVF` is a runtime-evaluated value
2500 // when VF is scalable. Otherwise, it should be folded into a Constant.
2501 assert((State.VF.isScalable() || isa<Constant>(StartIdx)) &&
2502 "Expected StartIdx to be folded to a constant when VF is not "
2503 "scalable");
2504 auto *Mul = Builder.CreateBinOp(MulOp, StartIdx, Step);
2505 auto *Add = Builder.CreateBinOp(AddOp, BaseIV, Mul);
2506 State.set(this, Add, VPLane(Lane));
2507 }
2508}
2509
2510#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2512 VPSlotTracker &SlotTracker) const {
2513 O << Indent;
2515 O << " = SCALAR-STEPS ";
2517}
2518#endif
2519
2521 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
2523}
2524
2526 assert(State.VF.isVector() && "not widening");
2527 // Construct a vector GEP by widening the operands of the scalar GEP as
2528 // necessary. We mark the vector GEP 'inbounds' if appropriate. A GEP
2529 // results in a vector of pointers when at least one operand of the GEP
2530 // is vector-typed. Thus, to keep the representation compact, we only use
2531 // vector-typed operands for loop-varying values.
2532
2533 bool AllOperandsAreInvariant = all_of(operands(), [](VPValue *Op) {
2534 return Op->isDefinedOutsideLoopRegions();
2535 });
2536 if (AllOperandsAreInvariant) {
2537 // If we are vectorizing, but the GEP has only loop-invariant operands,
2538 // the GEP we build (by only using vector-typed operands for
2539 // loop-varying values) would be a scalar pointer. Thus, to ensure we
2540 // produce a vector of pointers, we need to either arbitrarily pick an
2541 // operand to broadcast, or broadcast a clone of the original GEP.
2542 // Here, we broadcast a clone of the original.
2543
2545 for (unsigned I = 0, E = getNumOperands(); I != E; I++)
2546 Ops.push_back(State.get(getOperand(I), VPLane(0)));
2547
2548 auto *NewGEP =
2549 State.Builder.CreateGEP(getSourceElementType(), Ops[0], drop_begin(Ops),
2550 "", getGEPNoWrapFlags());
2551 Value *Splat = State.Builder.CreateVectorSplat(State.VF, NewGEP);
2552 State.set(this, Splat);
2553 return;
2554 }
2555
2556 // If the GEP has at least one loop-varying operand, we are sure to
2557 // produce a vector of pointers unless VF is scalar.
2558 // The pointer operand of the new GEP. If it's loop-invariant, we
2559 // won't broadcast it.
2560 auto *Ptr = State.get(getOperand(0), isPointerLoopInvariant());
2561
2562 // Collect all the indices for the new GEP. If any index is
2563 // loop-invariant, we won't broadcast it.
2565 for (unsigned I = 1, E = getNumOperands(); I < E; I++) {
2566 VPValue *Operand = getOperand(I);
2567 Indices.push_back(State.get(Operand, isIndexLoopInvariant(I - 1)));
2568 }
2569
2570 // Create the new GEP. Note that this GEP may be a scalar if VF == 1,
2571 // but it should be a vector, otherwise.
2572 auto *NewGEP = State.Builder.CreateGEP(getSourceElementType(), Ptr, Indices,
2573 "", getGEPNoWrapFlags());
2574 assert((State.VF.isScalar() || NewGEP->getType()->isVectorTy()) &&
2575 "NewGEP is not a pointer vector");
2576 State.set(this, NewGEP);
2577}
2578
2579#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2581 VPSlotTracker &SlotTracker) const {
2582 O << Indent << "WIDEN-GEP ";
2583 O << (isPointerLoopInvariant() ? "Inv" : "Var");
2584 for (size_t I = 0; I < getNumOperands() - 1; ++I)
2585 O << "[" << (isIndexLoopInvariant(I) ? "Inv" : "Var") << "]";
2586
2587 O << " ";
2589 O << " = getelementptr";
2590 printFlags(O);
2592}
2593#endif
2594
2596 auto &Builder = State.Builder;
2597 unsigned CurrentPart = getUnrollPart(*this);
2598 const DataLayout &DL = Builder.GetInsertBlock()->getDataLayout();
2599 Type *IndexTy = DL.getIndexType(State.TypeAnalysis.inferScalarType(this));
2600
2601 // The wide store needs to start at the last vector element.
2602 Value *RunTimeVF = State.get(getVFValue(), VPLane(0));
2603 if (IndexTy != RunTimeVF->getType())
2604 RunTimeVF = Builder.CreateZExtOrTrunc(RunTimeVF, IndexTy);
2605 // NumElt = Stride * CurrentPart * RunTimeVF
2606 Value *NumElt = Builder.CreateMul(
2607 ConstantInt::getSigned(IndexTy, Stride * (int64_t)CurrentPart),
2608 RunTimeVF);
2609 // LastLane = Stride * (RunTimeVF - 1)
2610 Value *LastLane = Builder.CreateSub(RunTimeVF, ConstantInt::get(IndexTy, 1));
2611 if (Stride != 1)
2612 LastLane =
2613 Builder.CreateMul(ConstantInt::getSigned(IndexTy, Stride), LastLane);
2614 Value *Ptr = State.get(getOperand(0), VPLane(0));
2615 Value *ResultPtr =
2616 Builder.CreateGEP(IndexedTy, Ptr, NumElt, "", getGEPNoWrapFlags());
2617 ResultPtr = Builder.CreateGEP(IndexedTy, ResultPtr, LastLane, "",
2619
2620 State.set(this, ResultPtr, /*IsScalar*/ true);
2621}
2622
2623#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2625 VPSlotTracker &SlotTracker) const {
2626 O << Indent;
2628 O << " = vector-end-pointer";
2629 printFlags(O);
2631}
2632#endif
2633
2635 auto &Builder = State.Builder;
2636 assert(getOffset() &&
2637 "Expected prior simplification of recipe without offset");
2638 Value *Ptr = State.get(getOperand(0), VPLane(0));
2639 Value *Offset = State.get(getOffset(), true);
2640 Value *ResultPtr = Builder.CreateGEP(getSourceElementType(), Ptr, Offset, "",
2642 State.set(this, ResultPtr, /*IsScalar*/ true);
2643}
2644
2645#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2647 VPSlotTracker &SlotTracker) const {
2648 O << Indent;
2650 O << " = vector-pointer";
2651 printFlags(O);
2653}
2654#endif
2655
2657 VPCostContext &Ctx) const {
2658 // A blend will be expanded to a select VPInstruction, which will generate a
2659 // scalar select if only the first lane is used.
2661 VF = ElementCount::getFixed(1);
2662
2663 Type *ResultTy = toVectorTy(Ctx.Types.inferScalarType(this), VF);
2664 Type *CmpTy = toVectorTy(Type::getInt1Ty(Ctx.Types.getContext()), VF);
2665 return (getNumIncomingValues() - 1) *
2666 Ctx.TTI.getCmpSelInstrCost(Instruction::Select, ResultTy, CmpTy,
2667 CmpInst::BAD_ICMP_PREDICATE, Ctx.CostKind);
2668}
2669
2670#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2672 VPSlotTracker &SlotTracker) const {
2673 O << Indent << "BLEND ";
2675 O << " =";
2676 if (getNumIncomingValues() == 1) {
2677 // Not a User of any mask: not really blending, this is a
2678 // single-predecessor phi.
2679 O << " ";
2680 getIncomingValue(0)->printAsOperand(O, SlotTracker);
2681 } else {
2682 for (unsigned I = 0, E = getNumIncomingValues(); I < E; ++I) {
2683 O << " ";
2684 getIncomingValue(I)->printAsOperand(O, SlotTracker);
2685 if (I == 0)
2686 continue;
2687 O << "/";
2688 getMask(I)->printAsOperand(O, SlotTracker);
2689 }
2690 }
2691}
2692#endif
2693
2695 assert(!State.Lane && "Reduction being replicated.");
2698 "In-loop AnyOf reductions aren't currently supported");
2699 // Propagate the fast-math flags carried by the underlying instruction.
2700 IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder);
2701 State.Builder.setFastMathFlags(getFastMathFlags());
2702 Value *NewVecOp = State.get(getVecOp());
2703 if (VPValue *Cond = getCondOp()) {
2704 Value *NewCond = State.get(Cond, State.VF.isScalar());
2705 VectorType *VecTy = dyn_cast<VectorType>(NewVecOp->getType());
2706 Type *ElementTy = VecTy ? VecTy->getElementType() : NewVecOp->getType();
2707
2708 Value *Start = getRecurrenceIdentity(Kind, ElementTy, getFastMathFlags());
2709 if (State.VF.isVector())
2710 Start = State.Builder.CreateVectorSplat(VecTy->getElementCount(), Start);
2711
2712 Value *Select = State.Builder.CreateSelect(NewCond, NewVecOp, Start);
2713 NewVecOp = Select;
2714 }
2715 Value *NewRed;
2716 Value *NextInChain;
2717 if (isOrdered()) {
2718 Value *PrevInChain = State.get(getChainOp(), /*IsScalar*/ true);
2719 if (State.VF.isVector())
2720 NewRed =
2721 createOrderedReduction(State.Builder, Kind, NewVecOp, PrevInChain);
2722 else
2723 NewRed = State.Builder.CreateBinOp(
2725 PrevInChain, NewVecOp);
2726 PrevInChain = NewRed;
2727 NextInChain = NewRed;
2728 } else if (isPartialReduction()) {
2729 assert((Kind == RecurKind::Add || Kind == RecurKind::FAdd) &&
2730 "Unexpected partial reduction kind");
2731 Value *PrevInChain = State.get(getChainOp(), /*IsScalar*/ false);
2732 NewRed = State.Builder.CreateIntrinsic(
2733 PrevInChain->getType(),
2734 Kind == RecurKind::Add ? Intrinsic::vector_partial_reduce_add
2735 : Intrinsic::vector_partial_reduce_fadd,
2736 {PrevInChain, NewVecOp}, State.Builder.getFastMathFlags(),
2737 "partial.reduce");
2738 PrevInChain = NewRed;
2739 NextInChain = NewRed;
2740 } else {
2741 assert(isInLoop() &&
2742 "The reduction must either be ordered, partial or in-loop");
2743 Value *PrevInChain = State.get(getChainOp(), /*IsScalar*/ true);
2744 NewRed = createSimpleReduction(State.Builder, NewVecOp, Kind);
2746 NextInChain = createMinMaxOp(State.Builder, Kind, NewRed, PrevInChain);
2747 else
2748 NextInChain = State.Builder.CreateBinOp(
2750 PrevInChain, NewRed);
2751 }
2752 State.set(this, NextInChain, /*IsScalar*/ !isPartialReduction());
2753}
2754
2756 assert(!State.Lane && "Reduction being replicated.");
2757
2758 auto &Builder = State.Builder;
2759 // Propagate the fast-math flags carried by the underlying instruction.
2760 IRBuilderBase::FastMathFlagGuard FMFGuard(Builder);
2761 Builder.setFastMathFlags(getFastMathFlags());
2762
2764 Value *Prev = State.get(getChainOp(), /*IsScalar*/ true);
2765 Value *VecOp = State.get(getVecOp());
2766 Value *EVL = State.get(getEVL(), VPLane(0));
2767
2768 Value *Mask;
2769 if (VPValue *CondOp = getCondOp())
2770 Mask = State.get(CondOp);
2771 else
2772 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
2773
2774 Value *NewRed;
2775 if (isOrdered()) {
2776 NewRed = createOrderedReduction(Builder, Kind, VecOp, Prev, Mask, EVL);
2777 } else {
2778 NewRed = createSimpleReduction(Builder, VecOp, Kind, Mask, EVL);
2780 NewRed = createMinMaxOp(Builder, Kind, NewRed, Prev);
2781 else
2782 NewRed = Builder.CreateBinOp(
2784 Prev);
2785 }
2786 State.set(this, NewRed, /*IsScalar*/ true);
2787}
2788
2790 VPCostContext &Ctx) const {
2791 RecurKind RdxKind = getRecurrenceKind();
2792 Type *ElementTy = Ctx.Types.inferScalarType(this);
2793 auto *VectorTy = cast<VectorType>(toVectorTy(ElementTy, VF));
2794 unsigned Opcode = RecurrenceDescriptor::getOpcode(RdxKind);
2796 std::optional<FastMathFlags> OptionalFMF =
2797 ElementTy->isFloatingPointTy() ? std::make_optional(FMFs) : std::nullopt;
2798
2799 if (isPartialReduction()) {
2800 InstructionCost CondCost = 0;
2801 if (isConditional()) {
2803 auto *CondTy = cast<VectorType>(
2804 toVectorTy(Ctx.Types.inferScalarType(getCondOp()), VF));
2805 CondCost = Ctx.TTI.getCmpSelInstrCost(Instruction::Select, VectorTy,
2806 CondTy, Pred, Ctx.CostKind);
2807 }
2808 return CondCost + Ctx.TTI.getPartialReductionCost(
2809 Opcode, ElementTy, ElementTy, ElementTy, VF,
2810 TTI::PR_None, TTI::PR_None, {}, Ctx.CostKind,
2811 OptionalFMF);
2812 }
2813
2814 // TODO: Support any-of reductions.
2815 assert(
2817 ForceTargetInstructionCost.getNumOccurrences() > 0) &&
2818 "Any-of reduction not implemented in VPlan-based cost model currently.");
2819
2820 // Note that TTI should model the cost of moving result to the scalar register
2821 // and the BinOp cost in the getMinMaxReductionCost().
2824 return Ctx.TTI.getMinMaxReductionCost(Id, VectorTy, FMFs, Ctx.CostKind);
2825 }
2826
2827 // Note that TTI should model the cost of moving result to the scalar register
2828 // and the BinOp cost in the getArithmeticReductionCost().
2829 return Ctx.TTI.getArithmeticReductionCost(Opcode, VectorTy, OptionalFMF,
2830 Ctx.CostKind);
2831}
2832
2833VPExpressionRecipe::VPExpressionRecipe(
2834 ExpressionTypes ExpressionType,
2835 ArrayRef<VPSingleDefRecipe *> ExpressionRecipes)
2836 : VPSingleDefRecipe(VPRecipeBase::VPExpressionSC, {}, {}),
2837 ExpressionRecipes(ExpressionRecipes), ExpressionType(ExpressionType) {
2838 assert(!ExpressionRecipes.empty() && "Nothing to combine?");
2839 assert(
2840 none_of(ExpressionRecipes,
2841 [](VPSingleDefRecipe *R) { return R->mayHaveSideEffects(); }) &&
2842 "expression cannot contain recipes with side-effects");
2843
2844 // Maintain a copy of the expression recipes as a set of users.
2845 SmallPtrSet<VPUser *, 4> ExpressionRecipesAsSetOfUsers;
2846 for (auto *R : ExpressionRecipes)
2847 ExpressionRecipesAsSetOfUsers.insert(R);
2848
2849 // Recipes in the expression, except the last one, must only be used by
2850 // (other) recipes inside the expression. If there are other users, external
2851 // to the expression, use a clone of the recipe for external users.
2852 for (VPSingleDefRecipe *R : reverse(ExpressionRecipes)) {
2853 if (R != ExpressionRecipes.back() &&
2854 any_of(R->users(), [&ExpressionRecipesAsSetOfUsers](VPUser *U) {
2855 return !ExpressionRecipesAsSetOfUsers.contains(U);
2856 })) {
2857 // There are users outside of the expression. Clone the recipe and use the
2858 // clone those external users.
2859 VPSingleDefRecipe *CopyForExtUsers = R->clone();
2860 R->replaceUsesWithIf(CopyForExtUsers, [&ExpressionRecipesAsSetOfUsers](
2861 VPUser &U, unsigned) {
2862 return !ExpressionRecipesAsSetOfUsers.contains(&U);
2863 });
2864 CopyForExtUsers->insertBefore(R);
2865 }
2866 if (R->getParent())
2867 R->removeFromParent();
2868 }
2869
2870 // Internalize all external operands to the expression recipes. To do so,
2871 // create new temporary VPValues for all operands defined by a recipe outside
2872 // the expression. The original operands are added as operands of the
2873 // VPExpressionRecipe itself.
2874 for (auto *R : ExpressionRecipes) {
2875 for (const auto &[Idx, Op] : enumerate(R->operands())) {
2876 auto *Def = Op->getDefiningRecipe();
2877 if (Def && ExpressionRecipesAsSetOfUsers.contains(Def))
2878 continue;
2879 addOperand(Op);
2880 LiveInPlaceholders.push_back(new VPSymbolicValue());
2881 }
2882 }
2883
2884 // Replace each external operand with the first one created for it in
2885 // LiveInPlaceholders.
2886 for (auto *R : ExpressionRecipes)
2887 for (auto const &[LiveIn, Tmp] : zip(operands(), LiveInPlaceholders))
2888 R->replaceUsesOfWith(LiveIn, Tmp);
2889}
2890
2892 for (auto *R : ExpressionRecipes)
2893 // Since the list could contain duplicates, make sure the recipe hasn't
2894 // already been inserted.
2895 if (!R->getParent())
2896 R->insertBefore(this);
2897
2898 for (const auto &[Idx, Op] : enumerate(operands()))
2899 LiveInPlaceholders[Idx]->replaceAllUsesWith(Op);
2900
2901 replaceAllUsesWith(ExpressionRecipes.back());
2902 ExpressionRecipes.clear();
2903}
2904
2906 VPCostContext &Ctx) const {
2907 Type *RedTy = Ctx.Types.inferScalarType(this);
2908 auto *SrcVecTy = cast<VectorType>(
2909 toVectorTy(Ctx.Types.inferScalarType(getOperand(0)), VF));
2910 unsigned Opcode = RecurrenceDescriptor::getOpcode(
2911 cast<VPReductionRecipe>(ExpressionRecipes.back())->getRecurrenceKind());
2912 switch (ExpressionType) {
2913 case ExpressionTypes::ExtendedReduction: {
2914 unsigned Opcode = RecurrenceDescriptor::getOpcode(
2915 cast<VPReductionRecipe>(ExpressionRecipes[1])->getRecurrenceKind());
2916 auto *ExtR = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
2917 auto *RedR = cast<VPReductionRecipe>(ExpressionRecipes.back());
2918
2919 if (RedR->isPartialReduction())
2920 return Ctx.TTI.getPartialReductionCost(
2921 Opcode, Ctx.Types.inferScalarType(getOperand(0)), nullptr, RedTy, VF,
2923 TargetTransformInfo::PR_None, std::nullopt, Ctx.CostKind,
2924 RedTy->isFloatingPointTy() ? std::optional{RedR->getFastMathFlags()}
2925 : std::nullopt);
2926 else if (!RedTy->isFloatingPointTy())
2927 // TTI::getExtendedReductionCost only supports integer types.
2928 return Ctx.TTI.getExtendedReductionCost(
2929 Opcode, ExtR->getOpcode() == Instruction::ZExt, RedTy, SrcVecTy,
2930 std::nullopt, Ctx.CostKind);
2931 else
2933 }
2934 case ExpressionTypes::MulAccReduction:
2935 return Ctx.TTI.getMulAccReductionCost(false, Opcode, RedTy, SrcVecTy,
2936 Ctx.CostKind);
2937
2938 case ExpressionTypes::ExtNegatedMulAccReduction:
2939 assert(Opcode == Instruction::Add && "Unexpected opcode");
2940 Opcode = Instruction::Sub;
2941 [[fallthrough]];
2942 case ExpressionTypes::ExtMulAccReduction: {
2943 auto *RedR = cast<VPReductionRecipe>(ExpressionRecipes.back());
2944 if (RedR->isPartialReduction()) {
2945 auto *Ext0R = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
2946 auto *Ext1R = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
2947 auto *Mul = cast<VPWidenRecipe>(ExpressionRecipes[2]);
2948 return Ctx.TTI.getPartialReductionCost(
2949 Opcode, Ctx.Types.inferScalarType(getOperand(0)),
2950 Ctx.Types.inferScalarType(getOperand(1)), RedTy, VF,
2952 Ext0R->getOpcode()),
2954 Ext1R->getOpcode()),
2955 Mul->getOpcode(), Ctx.CostKind,
2956 RedTy->isFloatingPointTy() ? std::optional{RedR->getFastMathFlags()}
2957 : std::nullopt);
2958 }
2959 return Ctx.TTI.getMulAccReductionCost(
2960 cast<VPWidenCastRecipe>(ExpressionRecipes.front())->getOpcode() ==
2961 Instruction::ZExt,
2962 Opcode, RedTy, SrcVecTy, Ctx.CostKind);
2963 }
2964 }
2965 llvm_unreachable("Unknown VPExpressionRecipe::ExpressionTypes enum");
2966}
2967
2969 return any_of(ExpressionRecipes, [](VPSingleDefRecipe *R) {
2970 return R->mayReadFromMemory() || R->mayWriteToMemory();
2971 });
2972}
2973
2975 assert(
2976 none_of(ExpressionRecipes,
2977 [](VPSingleDefRecipe *R) { return R->mayHaveSideEffects(); }) &&
2978 "expression cannot contain recipes with side-effects");
2979 return false;
2980}
2981
2983 // Cannot use vputils::isSingleScalar(), because all external operands
2984 // of the expression will be live-ins while bundled.
2985 auto *RR = dyn_cast<VPReductionRecipe>(ExpressionRecipes.back());
2986 return RR && !RR->isPartialReduction();
2987}
2988
2989#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2990
2992 VPSlotTracker &SlotTracker) const {
2993 O << Indent << "EXPRESSION ";
2995 O << " = ";
2996 auto *Red = cast<VPReductionRecipe>(ExpressionRecipes.back());
2997 unsigned Opcode = RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind());
2998
2999 switch (ExpressionType) {
3000 case ExpressionTypes::ExtendedReduction: {
3002 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
3003 O << Instruction::getOpcodeName(Opcode) << " (";
3005 Red->printFlags(O);
3006
3007 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3008 O << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
3009 << *Ext0->getResultType();
3010 if (Red->isConditional()) {
3011 O << ", ";
3012 Red->getCondOp()->printAsOperand(O, SlotTracker);
3013 }
3014 O << ")";
3015 break;
3016 }
3017 case ExpressionTypes::ExtNegatedMulAccReduction: {
3019 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
3021 RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind()))
3022 << " (sub (0, mul";
3023 auto *Mul = cast<VPWidenRecipe>(ExpressionRecipes[2]);
3024 Mul->printFlags(O);
3025 O << "(";
3027 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3028 O << " " << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
3029 << *Ext0->getResultType() << "), (";
3031 auto *Ext1 = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
3032 O << " " << Instruction::getOpcodeName(Ext1->getOpcode()) << " to "
3033 << *Ext1->getResultType() << ")";
3034 if (Red->isConditional()) {
3035 O << ", ";
3036 Red->getCondOp()->printAsOperand(O, SlotTracker);
3037 }
3038 O << "))";
3039 break;
3040 }
3041 case ExpressionTypes::MulAccReduction:
3042 case ExpressionTypes::ExtMulAccReduction: {
3044 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
3046 RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind()))
3047 << " (";
3048 O << "mul";
3049 bool IsExtended = ExpressionType == ExpressionTypes::ExtMulAccReduction;
3050 auto *Mul = cast<VPWidenRecipe>(IsExtended ? ExpressionRecipes[2]
3051 : ExpressionRecipes[0]);
3052 Mul->printFlags(O);
3053 if (IsExtended)
3054 O << "(";
3056 if (IsExtended) {
3057 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3058 O << " " << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
3059 << *Ext0->getResultType() << "), (";
3060 } else {
3061 O << ", ";
3062 }
3064 if (IsExtended) {
3065 auto *Ext1 = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
3066 O << " " << Instruction::getOpcodeName(Ext1->getOpcode()) << " to "
3067 << *Ext1->getResultType() << ")";
3068 }
3069 if (Red->isConditional()) {
3070 O << ", ";
3071 Red->getCondOp()->printAsOperand(O, SlotTracker);
3072 }
3073 O << ")";
3074 break;
3075 }
3076 }
3077}
3078
3080 VPSlotTracker &SlotTracker) const {
3081 if (isPartialReduction())
3082 O << Indent << "PARTIAL-REDUCE ";
3083 else
3084 O << Indent << "REDUCE ";
3086 O << " = ";
3088 O << " +";
3089 printFlags(O);
3090 O << " reduce."
3093 << " (";
3095 if (isConditional()) {
3096 O << ", ";
3098 }
3099 O << ")";
3100}
3101
3103 VPSlotTracker &SlotTracker) const {
3104 O << Indent << "REDUCE ";
3106 O << " = ";
3108 O << " +";
3109 printFlags(O);
3110 O << " vp.reduce."
3113 << " (";
3115 O << ", ";
3117 if (isConditional()) {
3118 O << ", ";
3120 }
3121 O << ")";
3122}
3123
3124#endif
3125
3126/// A helper function to scalarize a single Instruction in the innermost loop.
3127/// Generates a sequence of scalar instances for lane \p Lane. Uses the VPValue
3128/// operands from \p RepRecipe instead of \p Instr's operands.
3129static void scalarizeInstruction(const Instruction *Instr,
3130 VPReplicateRecipe *RepRecipe,
3131 const VPLane &Lane, VPTransformState &State) {
3132 assert((!Instr->getType()->isAggregateType() ||
3133 canVectorizeTy(Instr->getType())) &&
3134 "Expected vectorizable or non-aggregate type.");
3135
3136 // Does this instruction return a value ?
3137 bool IsVoidRetTy = Instr->getType()->isVoidTy();
3138
3139 Instruction *Cloned = Instr->clone();
3140 if (!IsVoidRetTy) {
3141 Cloned->setName(Instr->getName() + ".cloned");
3142 Type *ResultTy = State.TypeAnalysis.inferScalarType(RepRecipe);
3143 // The operands of the replicate recipe may have been narrowed, resulting in
3144 // a narrower result type. Update the type of the cloned instruction to the
3145 // correct type.
3146 if (ResultTy != Cloned->getType())
3147 Cloned->mutateType(ResultTy);
3148 }
3149
3150 RepRecipe->applyFlags(*Cloned);
3151 RepRecipe->applyMetadata(*Cloned);
3152
3153 if (RepRecipe->hasPredicate())
3154 cast<CmpInst>(Cloned)->setPredicate(RepRecipe->getPredicate());
3155
3156 if (auto DL = RepRecipe->getDebugLoc())
3157 State.setDebugLocFrom(DL);
3158
3159 // Replace the operands of the cloned instructions with their scalar
3160 // equivalents in the new loop.
3161 for (const auto &I : enumerate(RepRecipe->operands())) {
3162 auto InputLane = Lane;
3163 VPValue *Operand = I.value();
3164 if (vputils::isSingleScalar(Operand))
3165 InputLane = VPLane::getFirstLane();
3166 Cloned->setOperand(I.index(), State.get(Operand, InputLane));
3167 }
3168
3169 // Place the cloned scalar in the new loop.
3170 State.Builder.Insert(Cloned);
3171
3172 State.set(RepRecipe, Cloned, Lane);
3173
3174 // If we just cloned a new assumption, add it the assumption cache.
3175 if (auto *II = dyn_cast<AssumeInst>(Cloned))
3176 State.AC->registerAssumption(II);
3177
3178 assert(
3179 (RepRecipe->getRegion() ||
3180 !RepRecipe->getParent()->getPlan()->getVectorLoopRegion() ||
3181 all_of(RepRecipe->operands(),
3182 [](VPValue *Op) { return Op->isDefinedOutsideLoopRegions(); })) &&
3183 "Expected a recipe is either within a region or all of its operands "
3184 "are defined outside the vectorized region.");
3185}
3186
3189
3190 if (!State.Lane) {
3191 assert(IsSingleScalar && "VPReplicateRecipes outside replicate regions "
3192 "must have already been unrolled");
3193 scalarizeInstruction(UI, this, VPLane(0), State);
3194 return;
3195 }
3196
3197 assert((State.VF.isScalar() || !isSingleScalar()) &&
3198 "uniform recipe shouldn't be predicated");
3199 assert(!State.VF.isScalable() && "Can't scalarize a scalable vector");
3200 scalarizeInstruction(UI, this, *State.Lane, State);
3201 // Insert scalar instance packing it into a vector.
3202 if (State.VF.isVector() && shouldPack()) {
3203 Value *WideValue =
3204 State.Lane->isFirstLane()
3205 ? PoisonValue::get(toVectorizedTy(UI->getType(), State.VF))
3206 : State.get(this);
3207 State.set(this, State.packScalarIntoVectorizedValue(this, WideValue,
3208 *State.Lane));
3209 }
3210}
3211
3213 // Find if the recipe is used by a widened recipe via an intervening
3214 // VPPredInstPHIRecipe. In this case, also pack the scalar values in a vector.
3215 return any_of(users(), [](const VPUser *U) {
3216 if (auto *PredR = dyn_cast<VPPredInstPHIRecipe>(U))
3217 return !vputils::onlyScalarValuesUsed(PredR);
3218 return false;
3219 });
3220}
3221
3222/// Returns a SCEV expression for \p Ptr if it is a pointer computation for
3223/// which the legacy cost model computes a SCEV expression when computing the
3224/// address cost. Computing SCEVs for VPValues is incomplete and returns
3225/// SCEVCouldNotCompute in cases the legacy cost model can compute SCEVs. In
3226/// those cases we fall back to the legacy cost model. Otherwise return nullptr.
3227static const SCEV *getAddressAccessSCEV(const VPValue *Ptr,
3229 const Loop *L) {
3230 const SCEV *Addr = vputils::getSCEVExprForVPValue(Ptr, PSE, L);
3231 if (isa<SCEVCouldNotCompute>(Addr))
3232 return Addr;
3233
3234 return vputils::isAddressSCEVForCost(Addr, *PSE.getSE(), L) ? Addr : nullptr;
3235}
3236
3237/// Returns true if \p V is used as part of the address of another load or
3238/// store.
3239static bool isUsedByLoadStoreAddress(const VPUser *V) {
3241 SmallVector<const VPUser *> WorkList = {V};
3242
3243 while (!WorkList.empty()) {
3244 auto *Cur = dyn_cast<VPSingleDefRecipe>(WorkList.pop_back_val());
3245 if (!Cur || !Seen.insert(Cur).second)
3246 continue;
3247
3248 auto *Blend = dyn_cast<VPBlendRecipe>(Cur);
3249 // Skip blends that use V only through a compare by checking if any incoming
3250 // value was already visited.
3251 if (Blend && none_of(seq<unsigned>(0, Blend->getNumIncomingValues()),
3252 [&](unsigned I) {
3253 return Seen.contains(
3254 Blend->getIncomingValue(I)->getDefiningRecipe());
3255 }))
3256 continue;
3257
3258 for (VPUser *U : Cur->users()) {
3259 if (auto *InterleaveR = dyn_cast<VPInterleaveBase>(U))
3260 if (InterleaveR->getAddr() == Cur)
3261 return true;
3262 if (auto *RepR = dyn_cast<VPReplicateRecipe>(U)) {
3263 if (RepR->getOpcode() == Instruction::Load &&
3264 RepR->getOperand(0) == Cur)
3265 return true;
3266 if (RepR->getOpcode() == Instruction::Store &&
3267 RepR->getOperand(1) == Cur)
3268 return true;
3269 }
3270 if (auto *MemR = dyn_cast<VPWidenMemoryRecipe>(U)) {
3271 if (MemR->getAddr() == Cur && MemR->isConsecutive())
3272 return true;
3273 }
3274 }
3275
3276 // The legacy cost model only supports scalarization loads/stores with phi
3277 // addresses, if the phi is directly used as load/store address. Don't
3278 // traverse further for Blends.
3279 if (Blend)
3280 continue;
3281
3282 append_range(WorkList, Cur->users());
3283 }
3284 return false;
3285}
3286
3288 VPCostContext &Ctx) const {
3290 // VPReplicateRecipe may be cloned as part of an existing VPlan-to-VPlan
3291 // transform, avoid computing their cost multiple times for now.
3292 Ctx.SkipCostComputation.insert(UI);
3293
3294 if (VF.isScalable() && !isSingleScalar())
3296
3297 switch (UI->getOpcode()) {
3298 case Instruction::Alloca:
3299 if (VF.isScalable())
3301 return Ctx.TTI.getArithmeticInstrCost(
3302 Instruction::Mul, Ctx.Types.inferScalarType(this), Ctx.CostKind);
3303 case Instruction::GetElementPtr:
3304 // We mark this instruction as zero-cost because the cost of GEPs in
3305 // vectorized code depends on whether the corresponding memory instruction
3306 // is scalarized or not. Therefore, we handle GEPs with the memory
3307 // instruction cost.
3308 return 0;
3309 case Instruction::Call: {
3310 auto *CalledFn =
3312
3315 for (const VPValue *ArgOp : ArgOps)
3316 Tys.push_back(Ctx.Types.inferScalarType(ArgOp));
3317
3318 if (CalledFn->isIntrinsic())
3319 // Various pseudo-intrinsics with costs of 0 are scalarized instead of
3320 // vectorized via VPWidenIntrinsicRecipe. Return 0 for them early.
3321 switch (CalledFn->getIntrinsicID()) {
3322 case Intrinsic::assume:
3323 case Intrinsic::lifetime_end:
3324 case Intrinsic::lifetime_start:
3325 case Intrinsic::sideeffect:
3326 case Intrinsic::pseudoprobe:
3327 case Intrinsic::experimental_noalias_scope_decl: {
3328 assert(getCostForIntrinsics(CalledFn->getIntrinsicID(), ArgOps, *this,
3329 ElementCount::getFixed(1), Ctx) == 0 &&
3330 "scalarizing intrinsic should be free");
3331 return InstructionCost(0);
3332 }
3333 default:
3334 break;
3335 }
3336
3337 Type *ResultTy = Ctx.Types.inferScalarType(this);
3338 InstructionCost ScalarCallCost =
3339 Ctx.TTI.getCallInstrCost(CalledFn, ResultTy, Tys, Ctx.CostKind);
3340 if (isSingleScalar()) {
3341 if (CalledFn->isIntrinsic())
3342 ScalarCallCost = std::min(
3343 ScalarCallCost,
3344 getCostForIntrinsics(CalledFn->getIntrinsicID(), ArgOps, *this,
3345 ElementCount::getFixed(1), Ctx));
3346 return ScalarCallCost;
3347 }
3348
3349 return ScalarCallCost * VF.getFixedValue() +
3350 Ctx.getScalarizationOverhead(ResultTy, ArgOps, VF);
3351 }
3352 case Instruction::Add:
3353 case Instruction::Sub:
3354 case Instruction::FAdd:
3355 case Instruction::FSub:
3356 case Instruction::Mul:
3357 case Instruction::FMul:
3358 case Instruction::FDiv:
3359 case Instruction::FRem:
3360 case Instruction::Shl:
3361 case Instruction::LShr:
3362 case Instruction::AShr:
3363 case Instruction::And:
3364 case Instruction::Or:
3365 case Instruction::Xor:
3366 case Instruction::ICmp:
3367 case Instruction::FCmp:
3369 Ctx) *
3370 (isSingleScalar() ? 1 : VF.getFixedValue());
3371 case Instruction::SDiv:
3372 case Instruction::UDiv:
3373 case Instruction::SRem:
3374 case Instruction::URem: {
3375 InstructionCost ScalarCost =
3377 if (isSingleScalar())
3378 return ScalarCost;
3379
3380 // If any of the operands is from a different replicate region and has its
3381 // cost skipped, it may have been forced to scalar. Fall back to legacy cost
3382 // model to avoid cost mis-match.
3383 if (any_of(operands(), [&Ctx, VF](VPValue *Op) {
3384 auto *PredR = dyn_cast<VPPredInstPHIRecipe>(Op);
3385 if (!PredR)
3386 return false;
3387 return Ctx.skipCostComputation(
3389 PredR->getOperand(0)->getUnderlyingValue()),
3390 VF.isVector());
3391 }))
3392 break;
3393
3394 ScalarCost = ScalarCost * VF.getFixedValue() +
3395 Ctx.getScalarizationOverhead(Ctx.Types.inferScalarType(this),
3396 to_vector(operands()), VF);
3397 // If the recipe is not predicated (i.e. not in a replicate region), return
3398 // the scalar cost. Otherwise handle predicated cost.
3399 if (!getRegion()->isReplicator())
3400 return ScalarCost;
3401
3402 // Account for the phi nodes that we will create.
3403 ScalarCost += VF.getFixedValue() *
3404 Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
3405 // Scale the cost by the probability of executing the predicated blocks.
3406 // This assumes the predicated block for each vector lane is equally
3407 // likely.
3408 ScalarCost /= Ctx.getPredBlockCostDivisor(UI->getParent());
3409 return ScalarCost;
3410 }
3411 case Instruction::Load:
3412 case Instruction::Store: {
3413 // TODO: See getMemInstScalarizationCost for how to handle replicating and
3414 // predicated cases.
3415 const VPRegionBlock *ParentRegion = getRegion();
3416 if (ParentRegion && ParentRegion->isReplicator())
3417 break;
3418
3419 bool IsLoad = UI->getOpcode() == Instruction::Load;
3420 const VPValue *PtrOp = getOperand(!IsLoad);
3421 const SCEV *PtrSCEV = getAddressAccessSCEV(PtrOp, Ctx.PSE, Ctx.L);
3423 break;
3424
3425 Type *ValTy = Ctx.Types.inferScalarType(IsLoad ? this : getOperand(0));
3426 Type *ScalarPtrTy = Ctx.Types.inferScalarType(PtrOp);
3427 const Align Alignment = getLoadStoreAlignment(UI);
3428 unsigned AS = cast<PointerType>(ScalarPtrTy)->getAddressSpace();
3430 InstructionCost ScalarMemOpCost = Ctx.TTI.getMemoryOpCost(
3431 UI->getOpcode(), ValTy, Alignment, AS, Ctx.CostKind, OpInfo);
3432
3433 Type *PtrTy = isSingleScalar() ? ScalarPtrTy : toVectorTy(ScalarPtrTy, VF);
3434 bool PreferVectorizedAddressing = Ctx.TTI.prefersVectorizedAddressing();
3435 bool UsedByLoadStoreAddress =
3436 !PreferVectorizedAddressing && isUsedByLoadStoreAddress(this);
3437 InstructionCost ScalarCost =
3438 ScalarMemOpCost +
3439 Ctx.TTI.getAddressComputationCost(
3440 PtrTy, UsedByLoadStoreAddress ? nullptr : Ctx.PSE.getSE(), PtrSCEV,
3441 Ctx.CostKind);
3442 if (isSingleScalar())
3443 return ScalarCost;
3444
3445 SmallVector<const VPValue *> OpsToScalarize;
3446 Type *ResultTy = Type::getVoidTy(PtrTy->getContext());
3447 // Set ResultTy and OpsToScalarize, if scalarization is needed. Currently we
3448 // don't assign scalarization overhead in general, if the target prefers
3449 // vectorized addressing or the loaded value is used as part of an address
3450 // of another load or store.
3451 if (!UsedByLoadStoreAddress) {
3452 bool EfficientVectorLoadStore =
3453 Ctx.TTI.supportsEfficientVectorElementLoadStore();
3454 if (!(IsLoad && !PreferVectorizedAddressing) &&
3455 !(!IsLoad && EfficientVectorLoadStore))
3456 append_range(OpsToScalarize, operands());
3457
3458 if (!EfficientVectorLoadStore)
3459 ResultTy = Ctx.Types.inferScalarType(this);
3460 }
3461
3464 return (ScalarCost * VF.getFixedValue()) +
3465 Ctx.getScalarizationOverhead(ResultTy, OpsToScalarize, VF, VIC,
3466 true);
3467 }
3468 case Instruction::SExt:
3469 case Instruction::ZExt:
3470 case Instruction::FPToUI:
3471 case Instruction::FPToSI:
3472 case Instruction::FPExt:
3473 case Instruction::PtrToInt:
3474 case Instruction::PtrToAddr:
3475 case Instruction::IntToPtr:
3476 case Instruction::SIToFP:
3477 case Instruction::UIToFP:
3478 case Instruction::Trunc:
3479 case Instruction::FPTrunc:
3480 case Instruction::AddrSpaceCast: {
3482 Ctx) *
3483 (isSingleScalar() ? 1 : VF.getFixedValue());
3484 }
3485 case Instruction::ExtractValue:
3486 case Instruction::InsertValue:
3487 return Ctx.TTI.getInsertExtractValueCost(getOpcode(), Ctx.CostKind);
3488 }
3489
3490 return Ctx.getLegacyCost(UI, VF);
3491}
3492
3493#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3495 VPSlotTracker &SlotTracker) const {
3496 O << Indent << (IsSingleScalar ? "CLONE " : "REPLICATE ");
3497
3498 if (!getUnderlyingInstr()->getType()->isVoidTy()) {
3500 O << " = ";
3501 }
3502 if (auto *CB = dyn_cast<CallBase>(getUnderlyingInstr())) {
3503 O << "call";
3504 printFlags(O);
3505 O << "@" << CB->getCalledFunction()->getName() << "(";
3507 O, [&O, &SlotTracker](VPValue *Op) {
3508 Op->printAsOperand(O, SlotTracker);
3509 });
3510 O << ")";
3511 } else {
3513 printFlags(O);
3515 }
3516
3517 if (shouldPack())
3518 O << " (S->V)";
3519}
3520#endif
3521
3523 assert(State.Lane && "Branch on Mask works only on single instance.");
3524
3525 VPValue *BlockInMask = getOperand(0);
3526 Value *ConditionBit = State.get(BlockInMask, *State.Lane);
3527
3528 // Replace the temporary unreachable terminator with a new conditional branch,
3529 // whose two destinations will be set later when they are created.
3530 auto *CurrentTerminator = State.CFG.PrevBB->getTerminator();
3531 assert(isa<UnreachableInst>(CurrentTerminator) &&
3532 "Expected to replace unreachable terminator with conditional branch.");
3533 auto CondBr =
3534 State.Builder.CreateCondBr(ConditionBit, State.CFG.PrevBB, nullptr);
3535 CondBr->setSuccessor(0, nullptr);
3536 CurrentTerminator->eraseFromParent();
3537}
3538
3540 VPCostContext &Ctx) const {
3541 // The legacy cost model doesn't assign costs to branches for individual
3542 // replicate regions. Match the current behavior in the VPlan cost model for
3543 // now.
3544 return 0;
3545}
3546
3548 assert(State.Lane && "Predicated instruction PHI works per instance.");
3549 Instruction *ScalarPredInst =
3550 cast<Instruction>(State.get(getOperand(0), *State.Lane));
3551 BasicBlock *PredicatedBB = ScalarPredInst->getParent();
3552 BasicBlock *PredicatingBB = PredicatedBB->getSinglePredecessor();
3553 assert(PredicatingBB && "Predicated block has no single predecessor.");
3555 "operand must be VPReplicateRecipe");
3556
3557 // By current pack/unpack logic we need to generate only a single phi node: if
3558 // a vector value for the predicated instruction exists at this point it means
3559 // the instruction has vector users only, and a phi for the vector value is
3560 // needed. In this case the recipe of the predicated instruction is marked to
3561 // also do that packing, thereby "hoisting" the insert-element sequence.
3562 // Otherwise, a phi node for the scalar value is needed.
3563 if (State.hasVectorValue(getOperand(0))) {
3564 auto *VecI = cast<Instruction>(State.get(getOperand(0)));
3566 "Packed operands must generate an insertelement or insertvalue");
3567
3568 // If VectorI is a struct, it will be a sequence like:
3569 // %1 = insertvalue %unmodified, %x, 0
3570 // %2 = insertvalue %1, %y, 1
3571 // %VectorI = insertvalue %2, %z, 2
3572 // To get the unmodified vector we need to look through the chain.
3573 if (auto *StructTy = dyn_cast<StructType>(VecI->getType()))
3574 for (unsigned I = 0; I < StructTy->getNumContainedTypes() - 1; I++)
3575 VecI = cast<InsertValueInst>(VecI->getOperand(0));
3576
3577 PHINode *VPhi = State.Builder.CreatePHI(VecI->getType(), 2);
3578 VPhi->addIncoming(VecI->getOperand(0), PredicatingBB); // Unmodified vector.
3579 VPhi->addIncoming(VecI, PredicatedBB); // New vector with inserted element.
3580 if (State.hasVectorValue(this))
3581 State.reset(this, VPhi);
3582 else
3583 State.set(this, VPhi);
3584 // NOTE: Currently we need to update the value of the operand, so the next
3585 // predicated iteration inserts its generated value in the correct vector.
3586 State.reset(getOperand(0), VPhi);
3587 } else {
3588 if (vputils::onlyFirstLaneUsed(this) && !State.Lane->isFirstLane())
3589 return;
3590
3591 Type *PredInstType = State.TypeAnalysis.inferScalarType(getOperand(0));
3592 PHINode *Phi = State.Builder.CreatePHI(PredInstType, 2);
3593 Phi->addIncoming(PoisonValue::get(ScalarPredInst->getType()),
3594 PredicatingBB);
3595 Phi->addIncoming(ScalarPredInst, PredicatedBB);
3596 if (State.hasScalarValue(this, *State.Lane))
3597 State.reset(this, Phi, *State.Lane);
3598 else
3599 State.set(this, Phi, *State.Lane);
3600 // NOTE: Currently we need to update the value of the operand, so the next
3601 // predicated iteration inserts its generated value in the correct vector.
3602 State.reset(getOperand(0), Phi, *State.Lane);
3603 }
3604}
3605
3606#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3608 VPSlotTracker &SlotTracker) const {
3609 O << Indent << "PHI-PREDICATED-INSTRUCTION ";
3611 O << " = ";
3613}
3614#endif
3615
3617 VPCostContext &Ctx) const {
3619 unsigned AS = cast<PointerType>(Ctx.Types.inferScalarType(getAddr()))
3620 ->getAddressSpace();
3621 unsigned Opcode = isa<VPWidenLoadRecipe, VPWidenLoadEVLRecipe>(this)
3622 ? Instruction::Load
3623 : Instruction::Store;
3624
3625 if (!Consecutive) {
3626 // TODO: Using the original IR may not be accurate.
3627 // Currently, ARM will use the underlying IR to calculate gather/scatter
3628 // instruction cost.
3629 assert(!Reverse &&
3630 "Inconsecutive memory access should not have the order.");
3631
3633 Type *PtrTy = Ptr->getType();
3634
3635 // If the address value is uniform across all lanes, then the address can be
3636 // calculated with scalar type and broadcast.
3638 PtrTy = toVectorTy(PtrTy, VF);
3639
3640 unsigned IID = isa<VPWidenLoadRecipe>(this) ? Intrinsic::masked_gather
3641 : isa<VPWidenStoreRecipe>(this) ? Intrinsic::masked_scatter
3642 : isa<VPWidenLoadEVLRecipe>(this) ? Intrinsic::vp_gather
3643 : Intrinsic::vp_scatter;
3644 return Ctx.TTI.getAddressComputationCost(PtrTy, nullptr, nullptr,
3645 Ctx.CostKind) +
3646 Ctx.TTI.getMemIntrinsicInstrCost(
3648 &Ingredient),
3649 Ctx.CostKind);
3650 }
3651
3653 if (IsMasked) {
3654 unsigned IID = isa<VPWidenLoadRecipe>(this) ? Intrinsic::masked_load
3655 : Intrinsic::masked_store;
3656 Cost += Ctx.TTI.getMemIntrinsicInstrCost(
3657 MemIntrinsicCostAttributes(IID, Ty, Alignment, AS), Ctx.CostKind);
3658 } else {
3659 TTI::OperandValueInfo OpInfo = Ctx.getOperandInfo(
3661 : getOperand(1));
3662 Cost += Ctx.TTI.getMemoryOpCost(Opcode, Ty, Alignment, AS, Ctx.CostKind,
3663 OpInfo, &Ingredient);
3664 }
3665 return Cost;
3666}
3667
3669 Type *ScalarDataTy = getLoadStoreType(&Ingredient);
3670 auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
3671 bool CreateGather = !isConsecutive();
3672
3673 auto &Builder = State.Builder;
3674 Value *Mask = nullptr;
3675 if (auto *VPMask = getMask()) {
3676 // Mask reversal is only needed for non-all-one (null) masks, as reverse
3677 // of a null all-one mask is a null mask.
3678 Mask = State.get(VPMask);
3679 if (isReverse())
3680 Mask = Builder.CreateVectorReverse(Mask, "reverse");
3681 }
3682
3683 Value *Addr = State.get(getAddr(), /*IsScalar*/ !CreateGather);
3684 Value *NewLI;
3685 if (CreateGather) {
3686 NewLI = Builder.CreateMaskedGather(DataTy, Addr, Alignment, Mask, nullptr,
3687 "wide.masked.gather");
3688 } else if (Mask) {
3689 NewLI =
3690 Builder.CreateMaskedLoad(DataTy, Addr, Alignment, Mask,
3691 PoisonValue::get(DataTy), "wide.masked.load");
3692 } else {
3693 NewLI = Builder.CreateAlignedLoad(DataTy, Addr, Alignment, "wide.load");
3694 }
3696 State.set(this, NewLI);
3697}
3698
3699#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3701 VPSlotTracker &SlotTracker) const {
3702 O << Indent << "WIDEN ";
3704 O << " = load ";
3706}
3707#endif
3708
3709/// Use all-true mask for reverse rather than actual mask, as it avoids a
3710/// dependence w/o affecting the result.
3712 Value *EVL, const Twine &Name) {
3713 VectorType *ValTy = cast<VectorType>(Operand->getType());
3714 Value *AllTrueMask =
3715 Builder.CreateVectorSplat(ValTy->getElementCount(), Builder.getTrue());
3716 return Builder.CreateIntrinsic(ValTy, Intrinsic::experimental_vp_reverse,
3717 {Operand, AllTrueMask, EVL}, nullptr, Name);
3718}
3719
3721 Type *ScalarDataTy = getLoadStoreType(&Ingredient);
3722 auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
3723 bool CreateGather = !isConsecutive();
3724
3725 auto &Builder = State.Builder;
3726 CallInst *NewLI;
3727 Value *EVL = State.get(getEVL(), VPLane(0));
3728 Value *Addr = State.get(getAddr(), !CreateGather);
3729 Value *Mask = nullptr;
3730 if (VPValue *VPMask = getMask()) {
3731 Mask = State.get(VPMask);
3732 if (isReverse())
3733 Mask = createReverseEVL(Builder, Mask, EVL, "vp.reverse.mask");
3734 } else {
3735 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
3736 }
3737
3738 if (CreateGather) {
3739 NewLI =
3740 Builder.CreateIntrinsic(DataTy, Intrinsic::vp_gather, {Addr, Mask, EVL},
3741 nullptr, "wide.masked.gather");
3742 } else {
3743 NewLI = Builder.CreateIntrinsic(DataTy, Intrinsic::vp_load,
3744 {Addr, Mask, EVL}, nullptr, "vp.op.load");
3745 }
3746 NewLI->addParamAttr(
3748 applyMetadata(*NewLI);
3749 Instruction *Res = NewLI;
3750 State.set(this, Res);
3751}
3752
3754 VPCostContext &Ctx) const {
3755 if (!Consecutive || IsMasked)
3756 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
3757
3758 // We need to use the getMemIntrinsicInstrCost() instead of getMemoryOpCost()
3759 // here because the EVL recipes using EVL to replace the tail mask. But in the
3760 // legacy model, it will always calculate the cost of mask.
3761 // TODO: Using getMemoryOpCost() instead of getMemIntrinsicInstrCost when we
3762 // don't need to compare to the legacy cost model.
3764 unsigned AS = cast<PointerType>(Ctx.Types.inferScalarType(getAddr()))
3765 ->getAddressSpace();
3766 return Ctx.TTI.getMemIntrinsicInstrCost(
3767 MemIntrinsicCostAttributes(Intrinsic::vp_load, Ty, Alignment, AS),
3768 Ctx.CostKind);
3769}
3770
3771#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3773 VPSlotTracker &SlotTracker) const {
3774 O << Indent << "WIDEN ";
3776 O << " = vp.load ";
3778}
3779#endif
3780
3782 VPValue *StoredVPValue = getStoredValue();
3783 bool CreateScatter = !isConsecutive();
3784
3785 auto &Builder = State.Builder;
3786
3787 Value *Mask = nullptr;
3788 if (auto *VPMask = getMask()) {
3789 // Mask reversal is only needed for non-all-one (null) masks, as reverse
3790 // of a null all-one mask is a null mask.
3791 Mask = State.get(VPMask);
3792 if (isReverse())
3793 Mask = Builder.CreateVectorReverse(Mask, "reverse");
3794 }
3795
3796 Value *StoredVal = State.get(StoredVPValue);
3797 Value *Addr = State.get(getAddr(), /*IsScalar*/ !CreateScatter);
3798 Instruction *NewSI = nullptr;
3799 if (CreateScatter)
3800 NewSI = Builder.CreateMaskedScatter(StoredVal, Addr, Alignment, Mask);
3801 else if (Mask)
3802 NewSI = Builder.CreateMaskedStore(StoredVal, Addr, Alignment, Mask);
3803 else
3804 NewSI = Builder.CreateAlignedStore(StoredVal, Addr, Alignment);
3805 applyMetadata(*NewSI);
3806}
3807
3808#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3810 VPSlotTracker &SlotTracker) const {
3811 O << Indent << "WIDEN store ";
3813}
3814#endif
3815
3817 VPValue *StoredValue = getStoredValue();
3818 bool CreateScatter = !isConsecutive();
3819
3820 auto &Builder = State.Builder;
3821
3822 CallInst *NewSI = nullptr;
3823 Value *StoredVal = State.get(StoredValue);
3824 Value *EVL = State.get(getEVL(), VPLane(0));
3825 Value *Mask = nullptr;
3826 if (VPValue *VPMask = getMask()) {
3827 Mask = State.get(VPMask);
3828 if (isReverse())
3829 Mask = createReverseEVL(Builder, Mask, EVL, "vp.reverse.mask");
3830 } else {
3831 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
3832 }
3833 Value *Addr = State.get(getAddr(), !CreateScatter);
3834 if (CreateScatter) {
3835 NewSI = Builder.CreateIntrinsic(Type::getVoidTy(EVL->getContext()),
3836 Intrinsic::vp_scatter,
3837 {StoredVal, Addr, Mask, EVL});
3838 } else {
3839 NewSI = Builder.CreateIntrinsic(Type::getVoidTy(EVL->getContext()),
3840 Intrinsic::vp_store,
3841 {StoredVal, Addr, Mask, EVL});
3842 }
3843 NewSI->addParamAttr(
3845 applyMetadata(*NewSI);
3846}
3847
3849 VPCostContext &Ctx) const {
3850 if (!Consecutive || IsMasked)
3851 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
3852
3853 // We need to use the getMemIntrinsicInstrCost() instead of getMemoryOpCost()
3854 // here because the EVL recipes using EVL to replace the tail mask. But in the
3855 // legacy model, it will always calculate the cost of mask.
3856 // TODO: Using getMemoryOpCost() instead of getMemIntrinsicInstrCost when we
3857 // don't need to compare to the legacy cost model.
3859 unsigned AS = cast<PointerType>(Ctx.Types.inferScalarType(getAddr()))
3860 ->getAddressSpace();
3861 return Ctx.TTI.getMemIntrinsicInstrCost(
3862 MemIntrinsicCostAttributes(Intrinsic::vp_store, Ty, Alignment, AS),
3863 Ctx.CostKind);
3864}
3865
3866#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3868 VPSlotTracker &SlotTracker) const {
3869 O << Indent << "WIDEN vp.store ";
3871}
3872#endif
3873
3875 VectorType *DstVTy, const DataLayout &DL) {
3876 // Verify that V is a vector type with same number of elements as DstVTy.
3877 auto VF = DstVTy->getElementCount();
3878 auto *SrcVecTy = cast<VectorType>(V->getType());
3879 assert(VF == SrcVecTy->getElementCount() && "Vector dimensions do not match");
3880 Type *SrcElemTy = SrcVecTy->getElementType();
3881 Type *DstElemTy = DstVTy->getElementType();
3882 assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&
3883 "Vector elements must have same size");
3884
3885 // Do a direct cast if element types are castable.
3886 if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
3887 return Builder.CreateBitOrPointerCast(V, DstVTy);
3888 }
3889 // V cannot be directly casted to desired vector type.
3890 // May happen when V is a floating point vector but DstVTy is a vector of
3891 // pointers or vice-versa. Handle this using a two-step bitcast using an
3892 // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
3893 assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&
3894 "Only one type should be a pointer type");
3895 assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&
3896 "Only one type should be a floating point type");
3897 Type *IntTy =
3898 IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy));
3899 auto *VecIntTy = VectorType::get(IntTy, VF);
3900 Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
3901 return Builder.CreateBitOrPointerCast(CastVal, DstVTy);
3902}
3903
3904/// Return a vector containing interleaved elements from multiple
3905/// smaller input vectors.
3907 const Twine &Name) {
3908 unsigned Factor = Vals.size();
3909 assert(Factor > 1 && "Tried to interleave invalid number of vectors");
3910
3911 VectorType *VecTy = cast<VectorType>(Vals[0]->getType());
3912#ifndef NDEBUG
3913 for (Value *Val : Vals)
3914 assert(Val->getType() == VecTy && "Tried to interleave mismatched types");
3915#endif
3916
3917 // Scalable vectors cannot use arbitrary shufflevectors (only splats), so
3918 // must use intrinsics to interleave.
3919 if (VecTy->isScalableTy()) {
3920 assert(Factor <= 8 && "Unsupported interleave factor for scalable vectors");
3921 return Builder.CreateVectorInterleave(Vals, Name);
3922 }
3923
3924 // Fixed length. Start by concatenating all vectors into a wide vector.
3925 Value *WideVec = concatenateVectors(Builder, Vals);
3926
3927 // Interleave the elements into the wide vector.
3928 const unsigned NumElts = VecTy->getElementCount().getFixedValue();
3929 return Builder.CreateShuffleVector(
3930 WideVec, createInterleaveMask(NumElts, Factor), Name);
3931}
3932
3933// Try to vectorize the interleave group that \p Instr belongs to.
3934//
3935// E.g. Translate following interleaved load group (factor = 3):
3936// for (i = 0; i < N; i+=3) {
3937// R = Pic[i]; // Member of index 0
3938// G = Pic[i+1]; // Member of index 1
3939// B = Pic[i+2]; // Member of index 2
3940// ... // do something to R, G, B
3941// }
3942// To:
3943// %wide.vec = load <12 x i32> ; Read 4 tuples of R,G,B
3944// %R.vec = shuffle %wide.vec, poison, <0, 3, 6, 9> ; R elements
3945// %G.vec = shuffle %wide.vec, poison, <1, 4, 7, 10> ; G elements
3946// %B.vec = shuffle %wide.vec, poison, <2, 5, 8, 11> ; B elements
3947//
3948// Or translate following interleaved store group (factor = 3):
3949// for (i = 0; i < N; i+=3) {
3950// ... do something to R, G, B
3951// Pic[i] = R; // Member of index 0
3952// Pic[i+1] = G; // Member of index 1
3953// Pic[i+2] = B; // Member of index 2
3954// }
3955// To:
3956// %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
3957// %B_U.vec = shuffle %B.vec, poison, <0, 1, 2, 3, u, u, u, u>
3958// %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
3959// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> ; Interleave R,G,B elements
3960// store <12 x i32> %interleaved.vec ; Write 4 tuples of R,G,B
3962 assert(!State.Lane && "Interleave group being replicated.");
3963 assert((!needsMaskForGaps() || !State.VF.isScalable()) &&
3964 "Masking gaps for scalable vectors is not yet supported.");
3966 Instruction *Instr = Group->getInsertPos();
3967
3968 // Prepare for the vector type of the interleaved load/store.
3969 Type *ScalarTy = getLoadStoreType(Instr);
3970 unsigned InterleaveFactor = Group->getFactor();
3971 auto *VecTy = VectorType::get(ScalarTy, State.VF * InterleaveFactor);
3972
3973 VPValue *BlockInMask = getMask();
3974 VPValue *Addr = getAddr();
3975 Value *ResAddr = State.get(Addr, VPLane(0));
3976
3977 auto CreateGroupMask = [&BlockInMask, &State,
3978 &InterleaveFactor](Value *MaskForGaps) -> Value * {
3979 if (State.VF.isScalable()) {
3980 assert(!MaskForGaps && "Interleaved groups with gaps are not supported.");
3981 assert(InterleaveFactor <= 8 &&
3982 "Unsupported deinterleave factor for scalable vectors");
3983 auto *ResBlockInMask = State.get(BlockInMask);
3984 SmallVector<Value *> Ops(InterleaveFactor, ResBlockInMask);
3985 return interleaveVectors(State.Builder, Ops, "interleaved.mask");
3986 }
3987
3988 if (!BlockInMask)
3989 return MaskForGaps;
3990
3991 Value *ResBlockInMask = State.get(BlockInMask);
3992 Value *ShuffledMask = State.Builder.CreateShuffleVector(
3993 ResBlockInMask,
3994 createReplicatedMask(InterleaveFactor, State.VF.getFixedValue()),
3995 "interleaved.mask");
3996 return MaskForGaps ? State.Builder.CreateBinOp(Instruction::And,
3997 ShuffledMask, MaskForGaps)
3998 : ShuffledMask;
3999 };
4000
4001 const DataLayout &DL = Instr->getDataLayout();
4002 // Vectorize the interleaved load group.
4003 if (isa<LoadInst>(Instr)) {
4004 Value *MaskForGaps = nullptr;
4005 if (needsMaskForGaps()) {
4006 MaskForGaps =
4007 createBitMaskForGaps(State.Builder, State.VF.getFixedValue(), *Group);
4008 assert(MaskForGaps && "Mask for Gaps is required but it is null");
4009 }
4010
4011 Instruction *NewLoad;
4012 if (BlockInMask || MaskForGaps) {
4013 Value *GroupMask = CreateGroupMask(MaskForGaps);
4014 Value *PoisonVec = PoisonValue::get(VecTy);
4015 NewLoad = State.Builder.CreateMaskedLoad(VecTy, ResAddr,
4016 Group->getAlign(), GroupMask,
4017 PoisonVec, "wide.masked.vec");
4018 } else
4019 NewLoad = State.Builder.CreateAlignedLoad(VecTy, ResAddr,
4020 Group->getAlign(), "wide.vec");
4021 applyMetadata(*NewLoad);
4022 // TODO: Also manage existing metadata using VPIRMetadata.
4023 Group->addMetadata(NewLoad);
4024
4026 if (VecTy->isScalableTy()) {
4027 // Scalable vectors cannot use arbitrary shufflevectors (only splats),
4028 // so must use intrinsics to deinterleave.
4029 assert(InterleaveFactor <= 8 &&
4030 "Unsupported deinterleave factor for scalable vectors");
4031 NewLoad = State.Builder.CreateIntrinsic(
4032 Intrinsic::getDeinterleaveIntrinsicID(InterleaveFactor),
4033 NewLoad->getType(), NewLoad,
4034 /*FMFSource=*/nullptr, "strided.vec");
4035 }
4036
4037 auto CreateStridedVector = [&InterleaveFactor, &State,
4038 &NewLoad](unsigned Index) -> Value * {
4039 assert(Index < InterleaveFactor && "Illegal group index");
4040 if (State.VF.isScalable())
4041 return State.Builder.CreateExtractValue(NewLoad, Index);
4042
4043 // For fixed length VF, use shuffle to extract the sub-vectors from the
4044 // wide load.
4045 auto StrideMask =
4046 createStrideMask(Index, InterleaveFactor, State.VF.getFixedValue());
4047 return State.Builder.CreateShuffleVector(NewLoad, StrideMask,
4048 "strided.vec");
4049 };
4050
4051 for (unsigned I = 0, J = 0; I < InterleaveFactor; ++I) {
4052 Instruction *Member = Group->getMember(I);
4053
4054 // Skip the gaps in the group.
4055 if (!Member)
4056 continue;
4057
4058 Value *StridedVec = CreateStridedVector(I);
4059
4060 // If this member has different type, cast the result type.
4061 if (Member->getType() != ScalarTy) {
4062 VectorType *OtherVTy = VectorType::get(Member->getType(), State.VF);
4063 StridedVec =
4064 createBitOrPointerCast(State.Builder, StridedVec, OtherVTy, DL);
4065 }
4066
4067 if (Group->isReverse())
4068 StridedVec = State.Builder.CreateVectorReverse(StridedVec, "reverse");
4069
4070 State.set(VPDefs[J], StridedVec);
4071 ++J;
4072 }
4073 return;
4074 }
4075
4076 // The sub vector type for current instruction.
4077 auto *SubVT = VectorType::get(ScalarTy, State.VF);
4078
4079 // Vectorize the interleaved store group.
4080 Value *MaskForGaps =
4081 createBitMaskForGaps(State.Builder, State.VF.getKnownMinValue(), *Group);
4082 assert(((MaskForGaps != nullptr) == needsMaskForGaps()) &&
4083 "Mismatch between NeedsMaskForGaps and MaskForGaps");
4084 ArrayRef<VPValue *> StoredValues = getStoredValues();
4085 // Collect the stored vector from each member.
4086 SmallVector<Value *, 4> StoredVecs;
4087 unsigned StoredIdx = 0;
4088 for (unsigned i = 0; i < InterleaveFactor; i++) {
4089 assert((Group->getMember(i) || MaskForGaps) &&
4090 "Fail to get a member from an interleaved store group");
4091 Instruction *Member = Group->getMember(i);
4092
4093 // Skip the gaps in the group.
4094 if (!Member) {
4095 Value *Undef = PoisonValue::get(SubVT);
4096 StoredVecs.push_back(Undef);
4097 continue;
4098 }
4099
4100 Value *StoredVec = State.get(StoredValues[StoredIdx]);
4101 ++StoredIdx;
4102
4103 if (Group->isReverse())
4104 StoredVec = State.Builder.CreateVectorReverse(StoredVec, "reverse");
4105
4106 // If this member has different type, cast it to a unified type.
4107
4108 if (StoredVec->getType() != SubVT)
4109 StoredVec = createBitOrPointerCast(State.Builder, StoredVec, SubVT, DL);
4110
4111 StoredVecs.push_back(StoredVec);
4112 }
4113
4114 // Interleave all the smaller vectors into one wider vector.
4115 Value *IVec = interleaveVectors(State.Builder, StoredVecs, "interleaved.vec");
4116 Instruction *NewStoreInstr;
4117 if (BlockInMask || MaskForGaps) {
4118 Value *GroupMask = CreateGroupMask(MaskForGaps);
4119 NewStoreInstr = State.Builder.CreateMaskedStore(
4120 IVec, ResAddr, Group->getAlign(), GroupMask);
4121 } else
4122 NewStoreInstr =
4123 State.Builder.CreateAlignedStore(IVec, ResAddr, Group->getAlign());
4124
4125 applyMetadata(*NewStoreInstr);
4126 // TODO: Also manage existing metadata using VPIRMetadata.
4127 Group->addMetadata(NewStoreInstr);
4128}
4129
4130#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4132 VPSlotTracker &SlotTracker) const {
4134 O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << " at ";
4135 IG->getInsertPos()->printAsOperand(O, false);
4136 O << ", ";
4138 VPValue *Mask = getMask();
4139 if (Mask) {
4140 O << ", ";
4141 Mask->printAsOperand(O, SlotTracker);
4142 }
4143
4144 unsigned OpIdx = 0;
4145 for (unsigned i = 0; i < IG->getFactor(); ++i) {
4146 if (!IG->getMember(i))
4147 continue;
4148 if (getNumStoreOperands() > 0) {
4149 O << "\n" << Indent << " store ";
4151 O << " to index " << i;
4152 } else {
4153 O << "\n" << Indent << " ";
4155 O << " = load from index " << i;
4156 }
4157 ++OpIdx;
4158 }
4159}
4160#endif
4161
4163 assert(!State.Lane && "Interleave group being replicated.");
4164 assert(State.VF.isScalable() &&
4165 "Only support scalable VF for EVL tail-folding.");
4167 "Masking gaps for scalable vectors is not yet supported.");
4169 Instruction *Instr = Group->getInsertPos();
4170
4171 // Prepare for the vector type of the interleaved load/store.
4172 Type *ScalarTy = getLoadStoreType(Instr);
4173 unsigned InterleaveFactor = Group->getFactor();
4174 assert(InterleaveFactor <= 8 &&
4175 "Unsupported deinterleave/interleave factor for scalable vectors");
4176 ElementCount WideVF = State.VF * InterleaveFactor;
4177 auto *VecTy = VectorType::get(ScalarTy, WideVF);
4178
4179 VPValue *Addr = getAddr();
4180 Value *ResAddr = State.get(Addr, VPLane(0));
4181 Value *EVL = State.get(getEVL(), VPLane(0));
4182 Value *InterleaveEVL = State.Builder.CreateMul(
4183 EVL, ConstantInt::get(EVL->getType(), InterleaveFactor), "interleave.evl",
4184 /* NUW= */ true, /* NSW= */ true);
4185 LLVMContext &Ctx = State.Builder.getContext();
4186
4187 Value *GroupMask = nullptr;
4188 if (VPValue *BlockInMask = getMask()) {
4189 SmallVector<Value *> Ops(InterleaveFactor, State.get(BlockInMask));
4190 GroupMask = interleaveVectors(State.Builder, Ops, "interleaved.mask");
4191 } else {
4192 GroupMask =
4193 State.Builder.CreateVectorSplat(WideVF, State.Builder.getTrue());
4194 }
4195
4196 // Vectorize the interleaved load group.
4197 if (isa<LoadInst>(Instr)) {
4198 CallInst *NewLoad = State.Builder.CreateIntrinsic(
4199 VecTy, Intrinsic::vp_load, {ResAddr, GroupMask, InterleaveEVL}, nullptr,
4200 "wide.vp.load");
4201 NewLoad->addParamAttr(0,
4202 Attribute::getWithAlignment(Ctx, Group->getAlign()));
4203
4204 applyMetadata(*NewLoad);
4205 // TODO: Also manage existing metadata using VPIRMetadata.
4206 Group->addMetadata(NewLoad);
4207
4208 // Scalable vectors cannot use arbitrary shufflevectors (only splats),
4209 // so must use intrinsics to deinterleave.
4210 NewLoad = State.Builder.CreateIntrinsic(
4211 Intrinsic::getDeinterleaveIntrinsicID(InterleaveFactor),
4212 NewLoad->getType(), NewLoad,
4213 /*FMFSource=*/nullptr, "strided.vec");
4214
4215 const DataLayout &DL = Instr->getDataLayout();
4216 for (unsigned I = 0, J = 0; I < InterleaveFactor; ++I) {
4217 Instruction *Member = Group->getMember(I);
4218 // Skip the gaps in the group.
4219 if (!Member)
4220 continue;
4221
4222 Value *StridedVec = State.Builder.CreateExtractValue(NewLoad, I);
4223 // If this member has different type, cast the result type.
4224 if (Member->getType() != ScalarTy) {
4225 VectorType *OtherVTy = VectorType::get(Member->getType(), State.VF);
4226 StridedVec =
4227 createBitOrPointerCast(State.Builder, StridedVec, OtherVTy, DL);
4228 }
4229
4230 State.set(getVPValue(J), StridedVec);
4231 ++J;
4232 }
4233 return;
4234 } // End for interleaved load.
4235
4236 // The sub vector type for current instruction.
4237 auto *SubVT = VectorType::get(ScalarTy, State.VF);
4238 // Vectorize the interleaved store group.
4239 ArrayRef<VPValue *> StoredValues = getStoredValues();
4240 // Collect the stored vector from each member.
4241 SmallVector<Value *, 4> StoredVecs;
4242 const DataLayout &DL = Instr->getDataLayout();
4243 for (unsigned I = 0, StoredIdx = 0; I < InterleaveFactor; I++) {
4244 Instruction *Member = Group->getMember(I);
4245 // Skip the gaps in the group.
4246 if (!Member) {
4247 StoredVecs.push_back(PoisonValue::get(SubVT));
4248 continue;
4249 }
4250
4251 Value *StoredVec = State.get(StoredValues[StoredIdx]);
4252 // If this member has different type, cast it to a unified type.
4253 if (StoredVec->getType() != SubVT)
4254 StoredVec = createBitOrPointerCast(State.Builder, StoredVec, SubVT, DL);
4255
4256 StoredVecs.push_back(StoredVec);
4257 ++StoredIdx;
4258 }
4259
4260 // Interleave all the smaller vectors into one wider vector.
4261 Value *IVec = interleaveVectors(State.Builder, StoredVecs, "interleaved.vec");
4262 CallInst *NewStore =
4263 State.Builder.CreateIntrinsic(Type::getVoidTy(Ctx), Intrinsic::vp_store,
4264 {IVec, ResAddr, GroupMask, InterleaveEVL});
4265 NewStore->addParamAttr(1,
4266 Attribute::getWithAlignment(Ctx, Group->getAlign()));
4267
4268 applyMetadata(*NewStore);
4269 // TODO: Also manage existing metadata using VPIRMetadata.
4270 Group->addMetadata(NewStore);
4271}
4272
4273#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4275 VPSlotTracker &SlotTracker) const {
4277 O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << " at ";
4278 IG->getInsertPos()->printAsOperand(O, false);
4279 O << ", ";
4281 O << ", ";
4283 if (VPValue *Mask = getMask()) {
4284 O << ", ";
4285 Mask->printAsOperand(O, SlotTracker);
4286 }
4287
4288 unsigned OpIdx = 0;
4289 for (unsigned i = 0; i < IG->getFactor(); ++i) {
4290 if (!IG->getMember(i))
4291 continue;
4292 if (getNumStoreOperands() > 0) {
4293 O << "\n" << Indent << " vp.store ";
4295 O << " to index " << i;
4296 } else {
4297 O << "\n" << Indent << " ";
4299 O << " = vp.load from index " << i;
4300 }
4301 ++OpIdx;
4302 }
4303}
4304#endif
4305
4307 VPCostContext &Ctx) const {
4308 Instruction *InsertPos = getInsertPos();
4309 // Find the VPValue index of the interleave group. We need to skip gaps.
4310 unsigned InsertPosIdx = 0;
4311 for (unsigned Idx = 0; IG->getFactor(); ++Idx)
4312 if (auto *Member = IG->getMember(Idx)) {
4313 if (Member == InsertPos)
4314 break;
4315 InsertPosIdx++;
4316 }
4317 Type *ValTy = Ctx.Types.inferScalarType(
4318 getNumDefinedValues() > 0 ? getVPValue(InsertPosIdx)
4319 : getStoredValues()[InsertPosIdx]);
4320 auto *VectorTy = cast<VectorType>(toVectorTy(ValTy, VF));
4321 unsigned AS = cast<PointerType>(Ctx.Types.inferScalarType(getAddr()))
4322 ->getAddressSpace();
4323
4324 unsigned InterleaveFactor = IG->getFactor();
4325 auto *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
4326
4327 // Holds the indices of existing members in the interleaved group.
4329 for (unsigned IF = 0; IF < InterleaveFactor; IF++)
4330 if (IG->getMember(IF))
4331 Indices.push_back(IF);
4332
4333 // Calculate the cost of the whole interleaved group.
4334 InstructionCost Cost = Ctx.TTI.getInterleavedMemoryOpCost(
4335 InsertPos->getOpcode(), WideVecTy, IG->getFactor(), Indices,
4336 IG->getAlign(), AS, Ctx.CostKind, getMask(), NeedsMaskForGaps);
4337
4338 if (!IG->isReverse())
4339 return Cost;
4340
4341 return Cost + IG->getNumMembers() *
4342 Ctx.TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
4343 VectorTy, VectorTy, {}, Ctx.CostKind,
4344 0);
4345}
4346
4347#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4349 VPSlotTracker &SlotTracker) const {
4350 O << Indent << "EMIT ";
4352 O << " = CANONICAL-INDUCTION ";
4354}
4355#endif
4356
4358 return vputils::onlyScalarValuesUsed(this) &&
4359 (!IsScalable || vputils::onlyFirstLaneUsed(this));
4360}
4361
4362#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4364 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
4365 assert((getNumOperands() == 3 || getNumOperands() == 5) &&
4366 "unexpected number of operands");
4367 O << Indent << "EMIT ";
4369 O << " = WIDEN-POINTER-INDUCTION ";
4371 O << ", ";
4373 O << ", ";
4375 if (getNumOperands() == 5) {
4376 O << ", ";
4378 O << ", ";
4380 }
4381}
4382
4384 VPSlotTracker &SlotTracker) const {
4385 O << Indent << "EMIT ";
4387 O << " = EXPAND SCEV " << *Expr;
4388}
4389#endif
4390
4392 Value *CanonicalIV = State.get(getOperand(0), /*IsScalar*/ true);
4393 Type *STy = CanonicalIV->getType();
4394 IRBuilder<> Builder(State.CFG.PrevBB->getTerminator());
4395 ElementCount VF = State.VF;
4396 Value *VStart = VF.isScalar()
4397 ? CanonicalIV
4398 : Builder.CreateVectorSplat(VF, CanonicalIV, "broadcast");
4399 Value *VStep = createStepForVF(Builder, STy, VF, getUnrollPart(*this));
4400 if (VF.isVector()) {
4401 VStep = Builder.CreateVectorSplat(VF, VStep);
4402 VStep =
4403 Builder.CreateAdd(VStep, Builder.CreateStepVector(VStep->getType()));
4404 }
4405 Value *CanonicalVectorIV = Builder.CreateAdd(VStart, VStep, "vec.iv");
4406 State.set(this, CanonicalVectorIV);
4407}
4408
4409#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4411 VPSlotTracker &SlotTracker) const {
4412 O << Indent << "EMIT ";
4414 O << " = WIDEN-CANONICAL-INDUCTION ";
4416}
4417#endif
4418
4420 auto &Builder = State.Builder;
4421 // Create a vector from the initial value.
4422 auto *VectorInit = getStartValue()->getLiveInIRValue();
4423
4424 Type *VecTy = State.VF.isScalar()
4425 ? VectorInit->getType()
4426 : VectorType::get(VectorInit->getType(), State.VF);
4427
4428 BasicBlock *VectorPH =
4429 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
4430 if (State.VF.isVector()) {
4431 auto *IdxTy = Builder.getInt32Ty();
4432 auto *One = ConstantInt::get(IdxTy, 1);
4433 IRBuilder<>::InsertPointGuard Guard(Builder);
4434 Builder.SetInsertPoint(VectorPH->getTerminator());
4435 auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, State.VF);
4436 auto *LastIdx = Builder.CreateSub(RuntimeVF, One);
4437 VectorInit = Builder.CreateInsertElement(
4438 PoisonValue::get(VecTy), VectorInit, LastIdx, "vector.recur.init");
4439 }
4440
4441 // Create a phi node for the new recurrence.
4442 PHINode *Phi = PHINode::Create(VecTy, 2, "vector.recur");
4443 Phi->insertBefore(State.CFG.PrevBB->getFirstInsertionPt());
4444 Phi->addIncoming(VectorInit, VectorPH);
4445 State.set(this, Phi);
4446}
4447
4450 VPCostContext &Ctx) const {
4451 if (VF.isScalar())
4452 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
4453
4454 return 0;
4455}
4456
4457#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4459 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
4460 O << Indent << "FIRST-ORDER-RECURRENCE-PHI ";
4462 O << " = phi ";
4464}
4465#endif
4466
4468 // Reductions do not have to start at zero. They can start with
4469 // any loop invariant values.
4470 VPValue *StartVPV = getStartValue();
4471
4472 // In order to support recurrences we need to be able to vectorize Phi nodes.
4473 // Phi nodes have cycles, so we need to vectorize them in two stages. This is
4474 // stage #1: We create a new vector PHI node with no incoming edges. We'll use
4475 // this value when we vectorize all of the instructions that use the PHI.
4476 BasicBlock *VectorPH =
4477 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
4478 bool ScalarPHI = State.VF.isScalar() || isInLoop();
4479 Value *StartV = State.get(StartVPV, ScalarPHI);
4480 Type *VecTy = StartV->getType();
4481
4482 BasicBlock *HeaderBB = State.CFG.PrevBB;
4483 assert(State.CurrentParentLoop->getHeader() == HeaderBB &&
4484 "recipe must be in the vector loop header");
4485 auto *Phi = PHINode::Create(VecTy, 2, "vec.phi");
4486 Phi->insertBefore(HeaderBB->getFirstInsertionPt());
4487 State.set(this, Phi, isInLoop());
4488
4489 Phi->addIncoming(StartV, VectorPH);
4490}
4491
4492#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4494 VPSlotTracker &SlotTracker) const {
4495 O << Indent << "WIDEN-REDUCTION-PHI ";
4496
4498 O << " = phi ";
4500 if (getVFScaleFactor() > 1)
4501 O << " (VF scaled by 1/" << getVFScaleFactor() << ")";
4502}
4503#endif
4504
4506 Value *Op0 = State.get(getOperand(0));
4507 Type *VecTy = Op0->getType();
4508 Instruction *VecPhi = State.Builder.CreatePHI(VecTy, 2, Name);
4509 State.set(this, VecPhi);
4510}
4511
4513 VPCostContext &Ctx) const {
4514 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
4515}
4516
4517#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4519 VPSlotTracker &SlotTracker) const {
4520 O << Indent << "WIDEN-PHI ";
4521
4523 O << " = phi ";
4525}
4526#endif
4527
4529 BasicBlock *VectorPH =
4530 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
4531 Value *StartMask = State.get(getOperand(0));
4532 PHINode *Phi =
4533 State.Builder.CreatePHI(StartMask->getType(), 2, "active.lane.mask");
4534 Phi->addIncoming(StartMask, VectorPH);
4535 State.set(this, Phi);
4536}
4537
4538#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4540 VPSlotTracker &SlotTracker) const {
4541 O << Indent << "ACTIVE-LANE-MASK-PHI ";
4542
4544 O << " = phi ";
4546}
4547#endif
4548
4549#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4551 VPSlotTracker &SlotTracker) const {
4552 O << Indent << "EXPLICIT-VECTOR-LENGTH-BASED-IV-PHI ";
4553
4555 O << " = phi ";
4557}
4558#endif
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static MCDisassembler::DecodeStatus addOperand(MCInst &Inst, const MCOperand &Opnd)
AMDGPU Lower Kernel Arguments
AMDGPU Register Bank Select
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
iv users
Definition IVUsers.cpp:48
static std::pair< Value *, APInt > getMask(Value *WideMask, unsigned Factor, ElementCount LeafValueEC)
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
This file provides a LoopVectorizationPlanner class.
static const SCEV * getAddressAccessSCEV(Value *Ptr, PredicatedScalarEvolution &PSE, const Loop *TheLoop)
Gets the address access SCEV for Ptr, if it should be used for cost modeling according to isAddressSC...
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static bool isOrdered(const Instruction *I)
MachineInstr unsigned OpIdx
uint64_t IntrinsicInst * II
const SmallVectorImpl< MachineOperand > & Cond
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:114
static TableGen::Emitter::OptClass< SkeletonEmitter > X("gen-skeleton-class", "Generate example skeleton class")
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
This file contains the declarations of different VPlan-related auxiliary helpers.
static Instruction * createReverseEVL(IRBuilderBase &Builder, Value *Operand, Value *EVL, const Twine &Name)
Use all-true mask for reverse rather than actual mask, as it avoids a dependence w/o affecting the re...
static Value * interleaveVectors(IRBuilderBase &Builder, ArrayRef< Value * > Vals, const Twine &Name)
Return a vector containing interleaved elements from multiple smaller input vectors.
static InstructionCost getCostForIntrinsics(Intrinsic::ID ID, ArrayRef< const VPValue * > Operands, const VPRecipeWithIRFlags &R, ElementCount VF, VPCostContext &Ctx)
Compute the cost for the intrinsic ID with Operands, produced by R.
static Value * createBitOrPointerCast(IRBuilderBase &Builder, Value *V, VectorType *DstVTy, const DataLayout &DL)
SmallVector< Value *, 2 > VectorParts
static bool isUsedByLoadStoreAddress(const VPUser *V)
Returns true if V is used as part of the address of another load or store.
static void scalarizeInstruction(const Instruction *Instr, VPReplicateRecipe *RepRecipe, const VPLane &Lane, VPTransformState &State)
A helper function to scalarize a single Instruction in the innermost loop.
static std::optional< unsigned > getOpcode(ArrayRef< VPValue * > Values)
Returns the opcode of Values or ~0 if they do not all agree.
Definition VPlanSLP.cpp:247
This file contains the declarations of the Vectorization Plan base classes:
static const uint32_t IV[8]
Definition blake3_impl.h:83
void printAsOperand(OutputBuffer &OB, Prec P=Prec::Default, bool StrictlyWorse=false) const
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
size - Get the array size.
Definition ArrayRef.h:142
bool empty() const
empty - Check if the array is empty.
Definition ArrayRef.h:137
static LLVM_ABI Attribute getWithAlignment(LLVMContext &Context, Align Alignment)
Return a uniquified Attribute object that has the specific alignment set.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition BasicBlock.h:233
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
Adds the attribute to the indicated argument.
This class represents a function call, abstracting a target machine's calling convention.
static LLVM_ABI bool isBitOrNoopPointerCastable(Type *SrcTy, Type *DestTy, const DataLayout &DL)
Check whether a bitcast, inttoptr, or ptrtoint cast between these types is valid and a no-op.
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
Definition InstrTypes.h:982
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:676
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:699
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:701
static LLVM_ABI StringRef getPredicateName(Predicate P)
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
This is an important base class in LLVM.
Definition Constant.h:43
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:64
A debug info location.
Definition DebugLoc.h:123
constexpr bool isVector() const
One or more elements.
Definition TypeSize.h:324
static constexpr ElementCount getScalable(ScalarTy MinVal)
Definition TypeSize.h:312
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:309
constexpr bool isScalar() const
Exactly one element.
Definition TypeSize.h:320
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:22
LLVM_ABI void print(raw_ostream &O) const
Print fast-math flags to O.
Definition Operator.cpp:283
void setAllowContract(bool B=true)
Definition FMF.h:90
bool noSignedZeros() const
Definition FMF.h:67
bool noInfs() const
Definition FMF.h:66
void setAllowReciprocal(bool B=true)
Definition FMF.h:87
bool allowReciprocal() const
Definition FMF.h:68
void setNoSignedZeros(bool B=true)
Definition FMF.h:84
bool allowReassoc() const
Flag queries.
Definition FMF.h:64
bool approxFunc() const
Definition FMF.h:70
void setNoNaNs(bool B=true)
Definition FMF.h:78
void setAllowReassoc(bool B=true)
Flag setters.
Definition FMF.h:75
bool noNaNs() const
Definition FMF.h:65
void setApproxFunc(bool B=true)
Definition FMF.h:93
void setNoInfs(bool B=true)
Definition FMF.h:81
bool allowContract() const
Definition FMF.h:69
Class to represent function types.
Type * getParamType(unsigned i) const
Parameter type accessors.
bool willReturn() const
Determine if the function will return.
Definition Function.h:667
bool doesNotThrow() const
Determine if the function cannot unwind.
Definition Function.h:600
Type * getReturnType() const
Returns the type of the ret val.
Definition Function.h:214
Common base class shared among various IRBuilders.
Definition IRBuilder.h:114
Value * CreateInsertElement(Type *VecTy, Value *NewElt, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2555
IntegerType * getInt1Ty()
Fetch the type representing a single bit.
Definition IRBuilder.h:547
Value * CreateInsertValue(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &Name="")
Definition IRBuilder.h:2609
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2543
LLVM_ABI Value * CreateVectorSpliceRight(Value *V1, Value *V2, Value *Offset, const Twine &Name="")
Create a vector.splice.right intrinsic call, or a shufflevector that produces the same result if the ...
LLVM_ABI Value * CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name="")
Return a vector value that contains.
Value * CreateExtractValue(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &Name="")
Definition IRBuilder.h:2602
LLVM_ABI Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
Value * CreateFreeze(Value *V, const Twine &Name="")
Definition IRBuilder.h:2621
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
Definition IRBuilder.h:562
Value * CreatePtrAdd(Value *Ptr, Value *Offset, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Definition IRBuilder.h:2026
void setFastMathFlags(FastMathFlags NewFMF)
Set the fast-math flags to be used with generated fp-math operators.
Definition IRBuilder.h:345
IntegerType * getInt64Ty()
Fetch the type representing a 64-bit integer.
Definition IRBuilder.h:567
LLVM_ABI Value * CreateVectorReverse(Value *V, const Twine &Name="")
Return a vector value that contains the vector V reversed.
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2306
ConstantInt * getInt64(uint64_t C)
Get a constant 64-bit value.
Definition IRBuilder.h:527
LLVM_ABI CallInst * CreateOrReduce(Value *Src)
Create a vector int OR reduction intrinsic of the source vector.
Value * CreateLogicalAnd(Value *Cond1, Value *Cond2, const Twine &Name="", Instruction *MDFrom=nullptr)
Definition IRBuilder.h:1729
LLVM_ABI CallInst * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > Types, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="")
Create a call to intrinsic ID with Args, mangled using Types.
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition IRBuilder.h:522
Value * CreateCmp(CmpInst::Predicate Pred, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2436
Value * CreateNot(Value *V, const Twine &Name="")
Definition IRBuilder.h:1813
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2302
Value * CreateCountTrailingZeroElems(Type *ResTy, Value *Mask, bool ZeroIsPoison=true, const Twine &Name="")
Create a call to llvm.experimental_cttz_elts.
Definition IRBuilder.h:1138
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1424
BranchInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a conditional 'br Cond, TrueDest, FalseDest' instruction.
Definition IRBuilder.h:1201
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNeg=false)
Definition IRBuilder.h:2055
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1407
ConstantInt * getFalse()
Get the constant value for i1 false.
Definition IRBuilder.h:507
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:1712
Value * CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2314
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2412
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
Definition IRBuilder.h:1577
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1441
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2776
static InstructionCost getInvalid(CostType Val=0)
bool isCast() const
bool isBinaryOp() const
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
const char * getOpcodeName() const
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
bool isUnaryOp() const
The group of interleaved loads/stores sharing the same stride and close to each other.
uint32_t getFactor() const
InstTy * getMember(uint32_t Index) const
Get the member with the given index Index.
bool isReverse() const
InstTy * getInsertPos() const
void addMetadata(InstTy *NewInst) const
Add metadata (e.g.
Align getAlign() const
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Information for memory intrinsic cost model.
Root of the metadata hierarchy.
Definition Metadata.h:64
LLVM_ABI void print(raw_ostream &OS, const Module *M=nullptr, bool IsForDebug=false) const
Print.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
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.
static LLVM_ABI unsigned getOpcode(RecurKind Kind)
Returns the opcode corresponding to the RecurrenceKind.
static bool isAnyOfRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
static bool isFindIVRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
static bool isMinMaxRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is any min/max kind.
This class represents an analyzed expression in the program.
This class represents the LLVM 'select' instruction.
This class provides computation of slot numbers for LLVM Assembly writing.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
reference emplace_back(ArgTypes &&... Args)
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.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
VectorInstrContext
Represents a hint about the context in which an insert/extract is used.
@ None
The insert/extract is not used with a load/store.
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
static LLVM_ABI PartialReductionExtendKind getPartialReductionExtendKind(Instruction *I)
Get the kind of extension that an instruction represents.
static LLVM_ABI OperandValueInfo getOperandInfo(const Value *V)
Collect properties of V used in cost analysis, e.g. OP_PowerOf2.
@ TCC_Free
Expected to fold away in lowering.
@ SK_Splice
Concatenates elements from the first input vector with elements of the second input vector.
@ SK_Reverse
Reverse the order of the vector.
CastContextHint
Represents a hint about the context in which a cast is used.
@ Reversed
The cast is used with a reversed load/store.
@ Masked
The cast is used with a masked load/store.
@ Normal
The cast is used with a normal load/store.
@ Interleave
The cast is used with an interleaved load/store.
@ GatherScatter
The cast is used with a gather/scatter.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:45
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:297
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:273
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:296
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:267
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:280
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:352
bool isStructTy() const
True if this is an instance of StructType.
Definition Type.h:261
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:128
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:230
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:293
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:184
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:240
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:300
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:139
value_op_iterator value_op_end()
Definition User.h:288
void setOperand(unsigned i, Value *Val)
Definition User.h:212
Value * getOperand(unsigned i) const
Definition User.h:207
value_op_iterator value_op_begin()
Definition User.h:285
void execute(VPTransformState &State) override
Generate the active lane mask phi of the vector loop.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
RecipeListTy & getRecipeList()
Returns a reference to the list of recipes.
Definition VPlan.h:4134
iterator end()
Definition VPlan.h:4118
void insert(VPRecipeBase *Recipe, iterator InsertPt)
Definition VPlan.h:4147
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenMemoryRecipe.
VPValue * getIncomingValue(unsigned Idx) const
Return incoming value number Idx.
Definition VPlan.h:2646
unsigned getNumIncomingValues() const
Return the number of incoming values, taking into account when normalized the first incoming value wi...
Definition VPlan.h:2641
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
Definition VPlan.h:81
const VPBlocksTy & getPredecessors() const
Definition VPlan.h:204
VPlan * getPlan()
Definition VPlan.cpp:175
void printAsOperand(raw_ostream &OS, bool PrintType=false) const
Definition VPlan.h:349
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPBranchOnMaskRecipe.
void execute(VPTransformState &State) override
Generate the extraction of the appropriate bit from the block mask and the conditional branch.
VPlan-based builder utility analogous to IRBuilder.
LLVM_ABI_FOR_TEST void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
unsigned getNumDefinedValues() const
Returns the number of values defined by the VPDef.
Definition VPlanValue.h:427
VPValue * getVPSingleValue()
Returns the only VPValue defined by the VPDef.
Definition VPlanValue.h:400
VPValue * getVPValue(unsigned I)
Returns the VPValue with index I defined by the VPDef.
Definition VPlanValue.h:412
ArrayRef< VPRecipeValue * > definedValues()
Returns an ArrayRef of the values defined by the VPDef.
Definition VPlanValue.h:422
void execute(VPTransformState &State) override
Generate the transformed value of the induction at offset StartValue (1.
VPIRValue * getStartValue() const
Definition VPlan.h:3872
VPValue * getStepValue() const
Definition VPlan.h:3873
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
LLVM_ABI_FOR_TEST void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void decompose()
Insert the recipes of the expression back into the VPlan, directly before the current recipe.
bool isSingleScalar() const
Returns true if the result of this VPExpressionRecipe is a single-scalar.
bool mayHaveSideEffects() const
Returns true if this expression contains recipes that may have side effects.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Compute the cost of this recipe either using a recipe's specialized implementation or using the legac...
bool mayReadOrWriteMemory() const
Returns true if this expression contains recipes that may read from or write to memory.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this header phi recipe.
VPValue * getStartValue()
Returns the start value of the phi, if one is set.
Definition VPlan.h:2164
void execute(VPTransformState &State) override
Produce a vectorized histogram operation.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPHistogramRecipe.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPValue * getMask() const
Return the mask operand if one was provided, or a null pointer if all lanes should be executed uncond...
Definition VPlan.h:1915
Class to record and manage LLVM IR flags.
Definition VPlan.h:665
FastMathFlagsTy FMFs
Definition VPlan.h:752
ReductionFlagsTy ReductionFlags
Definition VPlan.h:754
LLVM_ABI_FOR_TEST bool flagsValidForOpcode(unsigned Opcode) const
Returns true if the set flags are valid for Opcode.
WrapFlagsTy WrapFlags
Definition VPlan.h:746
CmpInst::Predicate CmpPredicate
Definition VPlan.h:745
void printFlags(raw_ostream &O) const
GEPNoWrapFlags GEPFlags
Definition VPlan.h:750
bool hasFastMathFlags() const
Returns true if the recipe has fast-math flags.
Definition VPlan.h:938
LLVM_ABI_FOR_TEST FastMathFlags getFastMathFlags() const
bool isReductionOrdered() const
Definition VPlan.h:988
TruncFlagsTy TruncFlags
Definition VPlan.h:747
CmpInst::Predicate getPredicate() const
Definition VPlan.h:915
ExactFlagsTy ExactFlags
Definition VPlan.h:749
bool hasNoSignedWrap() const
Definition VPlan.h:965
void intersectFlags(const VPIRFlags &Other)
Only keep flags also present in Other.
GEPNoWrapFlags getGEPNoWrapFlags() const
Definition VPlan.h:930
bool hasPredicate() const
Returns true if the recipe has a comparison predicate.
Definition VPlan.h:933
DisjointFlagsTy DisjointFlags
Definition VPlan.h:748
unsigned AllFlags
Definition VPlan.h:755
bool hasNoUnsignedWrap() const
Definition VPlan.h:954
FCmpFlagsTy FCmpFlags
Definition VPlan.h:753
NonNegFlagsTy NonNegFlags
Definition VPlan.h:751
bool isReductionInLoop() const
Definition VPlan.h:994
void applyFlags(Instruction &I) const
Apply the IR flags to I.
Definition VPlan.h:873
RecurKind getRecurKind() const
Definition VPlan.h:982
Instruction & getInstruction() const
Definition VPlan.h:1567
void extractLastLaneOfLastPartOfFirstOperand(VPBuilder &Builder)
Update the recipe's first operand to the last lane of the last part of the operand using Builder.
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
LLVM_ABI_FOR_TEST InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPIRInstruction.
VPIRInstruction(Instruction &I)
VPIRInstruction::create() should be used to create VPIRInstructions, as subclasses may need to be cre...
Definition VPlan.h:1541
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void intersect(const VPIRMetadata &MD)
Intersect this VPIRMetadata object with MD, keeping only metadata nodes that are common to both.
VPIRMetadata()=default
void print(raw_ostream &O, VPSlotTracker &SlotTracker) const
Print metadata with node IDs.
void applyMetadata(Instruction &I) const
Add all metadata to I.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate the instruction.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPInstruction.
static unsigned getNumOperandsForOpcode(unsigned Opcode)
Return the number of operands determined by the opcode of the VPInstruction.
bool doesGeneratePerAllLanes() const
Returns true if this VPInstruction generates scalar values for all lanes.
@ ExtractLastActive
Extracts the lane from the first operand corresponding to the last active (non-zero) lane in the mask...
Definition VPlan.h:1249
@ ExtractLane
Extracts a single lane (first operand) from a set of vector operands.
Definition VPlan.h:1242
@ ComputeAnyOfResult
Compute the final result of a AnyOf reduction with select(cmp(),x,y), where one of (x,...
Definition VPlan.h:1188
@ WideIVStep
Scale the first operand (vector step) by the second operand (scalar-step).
Definition VPlan.h:1232
@ ResumeForEpilogue
Explicit user for the resume phi of the canonical induction in the main VPlan, used by the epilogue v...
Definition VPlan.h:1245
@ Unpack
Extracts all lanes from its (non-scalable) vector operand.
Definition VPlan.h:1185
@ ReductionStartVector
Start vector for reductions with 3 operands: the original start value, the identity value for the red...
Definition VPlan.h:1236
@ BuildVector
Creates a fixed-width vector containing all operands.
Definition VPlan.h:1180
@ BuildStructVector
Given operands of (the same) struct type, creates a struct of fixed- width vectors each containing a ...
Definition VPlan.h:1177
@ VScale
Returns the value for vscale.
Definition VPlan.h:1252
@ CanonicalIVIncrementForPart
Definition VPlan.h:1161
bool hasResult() const
Definition VPlan.h:1316
bool opcodeMayReadOrWriteFromMemory() const
Returns true if the underlying opcode may read from or write to memory.
LLVM_DUMP_METHOD void dump() const
Print the VPInstruction to dbgs() (for debugging).
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the VPInstruction to O.
StringRef getName() const
Returns the symbolic name assigned to the VPInstruction.
Definition VPlan.h:1357
unsigned getOpcode() const
Definition VPlan.h:1300
VPInstruction(unsigned Opcode, ArrayRef< VPValue * > Operands, const VPIRFlags &Flags={}, const VPIRMetadata &MD={}, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
bool isVectorToScalar() const
Returns true if this VPInstruction produces a scalar value from a vector, e.g.
bool isSingleScalar() const
Returns true if this VPInstruction's operands are single scalars and the result is also a single scal...
void execute(VPTransformState &State) override
Generate the instruction.
bool usesFirstPartOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first part of operand Op.
bool needsMaskForGaps() const
Return true if the access needs a mask because of the gaps.
Definition VPlan.h:2758
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this recipe.
Instruction * getInsertPos() const
Definition VPlan.h:2762
const InterleaveGroup< Instruction > * getInterleaveGroup() const
Definition VPlan.h:2760
VPValue * getMask() const
Return the mask used by this recipe.
Definition VPlan.h:2752
ArrayRef< VPValue * > getStoredValues() const
Return the VPValues stored by this interleave group.
Definition VPlan.h:2781
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition VPlan.h:2746
VPValue * getEVL() const
The VPValue of the explicit vector length.
Definition VPlan.h:2856
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
unsigned getNumStoreOperands() const override
Returns the number of stored operands of this interleave group.
Definition VPlan.h:2869
void execute(VPTransformState &State) override
Generate the wide load or store, and shuffles.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
unsigned getNumStoreOperands() const override
Returns the number of stored operands of this interleave group.
Definition VPlan.h:2819
void execute(VPTransformState &State) override
Generate the wide load or store, and shuffles.
In what follows, the term "input IR" refers to code that is fed into the vectorizer whereas the term ...
static VPLane getLastLaneForVF(const ElementCount &VF)
static VPLane getLaneFromEnd(const ElementCount &VF, unsigned Offset)
static VPLane getFirstLane()
virtual const VPRecipeBase * getAsRecipe() const =0
Return a VPRecipeBase* to the current object.
virtual unsigned getNumIncoming() const
Returns the number of incoming values, also number of incoming blocks.
Definition VPlan.h:1456
void removeIncomingValueFor(VPBlockBase *IncomingBlock) const
Removes the incoming value for IncomingBlock, which must be a predecessor.
const VPBasicBlock * getIncomingBlock(unsigned Idx) const
Returns the incoming block with index Idx.
Definition VPlan.h:4225
detail::zippy< llvm::detail::zip_first, VPUser::const_operand_range, const_incoming_blocks_range > incoming_values_and_blocks() const
Returns an iterator range over pairs of incoming values and corresponding incoming blocks.
Definition VPlan.h:1481
VPValue * getIncomingValue(unsigned Idx) const
Returns the incoming VPValue with index Idx.
Definition VPlan.h:1448
void printPhiOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const
Print the recipe.
void execute(VPTransformState &State) override
Generates phi nodes for live-outs (from a replicate region) as needed to retain SSA form.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPRecipeBase is a base class modeling a sequence of one or more output IR instructions.
Definition VPlan.h:387
bool mayReadFromMemory() const
Returns true if the recipe may read from memory.
bool mayHaveSideEffects() const
Returns true if the recipe may have side-effects.
virtual void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const =0
Each concrete VPRecipe prints itself, without printing common information, like debug info or metadat...
VPRegionBlock * getRegion()
Definition VPlan.h:4386
LLVM_ABI_FOR_TEST void dump() const
Dump the recipe to stderr (for debugging).
Definition VPlan.cpp:114
bool isPhi() const
Returns true for PHI-like recipes.
bool mayWriteToMemory() const
Returns true if the recipe may write to memory.
virtual InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const
Compute the cost of this recipe either using a recipe's specialized implementation or using the legac...
VPBasicBlock * getParent()
Definition VPlan.h:462
DebugLoc getDebugLoc() const
Returns the debug location of the recipe.
Definition VPlan.h:536
void moveBefore(VPBasicBlock &BB, iplist< VPRecipeBase >::iterator I)
Unlink this recipe and insert into BB before I.
void insertBefore(VPRecipeBase *InsertPos)
Insert an unlinked recipe into a basic block immediately before the specified recipe.
void insertAfter(VPRecipeBase *InsertPos)
Insert an unlinked Recipe into a basic block immediately after the specified Recipe.
iplist< VPRecipeBase >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
InstructionCost cost(ElementCount VF, VPCostContext &Ctx)
Return the cost of this recipe, taking into account if the cost computation should be skipped and the...
bool isScalarCast() const
Return true if the recipe is a scalar cast.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const
Print the recipe, delegating to printRecipe().
void removeFromParent()
This method unlinks 'this' from the containing basic block, but does not delete it.
unsigned getVPRecipeID() const
Definition VPlan.h:508
void moveAfter(VPRecipeBase *MovePos)
Unlink this recipe from its current VPBasicBlock and insert it into the VPBasicBlock that MovePos liv...
VPRecipeBase(const unsigned char SC, ArrayRef< VPValue * > Operands, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:452
friend class VPValue
Definition VPlanValue.h:233
void execute(VPTransformState &State) override
Generate the reduction in the loop.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPValue * getEVL() const
The VPValue of the explicit vector length.
Definition VPlan.h:3019
unsigned getVFScaleFactor() const
Get the factor that the VF of this recipe's output should be scaled by, or 1 if it isn't scaled.
Definition VPlan.h:2563
bool isInLoop() const
Returns true if the phi is part of an in-loop reduction.
Definition VPlan.h:2587
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate the phi/select nodes.
bool isConditional() const
Return true if the in-loop reduction is conditional.
Definition VPlan.h:2961
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of VPReductionRecipe.
VPValue * getVecOp() const
The VPValue of the vector value to be reduced.
Definition VPlan.h:2972
VPValue * getCondOp() const
The VPValue of the condition for the block.
Definition VPlan.h:2974
RecurKind getRecurrenceKind() const
Return the recurrence kind for the in-loop reduction.
Definition VPlan.h:2957
bool isPartialReduction() const
Returns true if the reduction outputs a vector with a scaled down VF.
Definition VPlan.h:2963
VPValue * getChainOp() const
The VPValue of the scalar Chain being accumulated.
Definition VPlan.h:2970
bool isInLoop() const
Returns true if the reduction is in-loop.
Definition VPlan.h:2965
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate the reduction in the loop.
VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks which form a Single-Entry-S...
Definition VPlan.h:4269
bool isReplicator() const
An indicator whether this region is to generate multiple replicated instances of output IR correspond...
Definition VPlan.h:4337
VPReplicateRecipe replicates a given instruction producing multiple scalar copies of the original sca...
Definition VPlan.h:3041
void execute(VPTransformState &State) override
Generate replicas of the desired Ingredient.
bool isSingleScalar() const
Definition VPlan.h:3082
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPReplicateRecipe.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
unsigned getOpcode() const
Definition VPlan.h:3111
bool shouldPack() const
Returns true if the recipe is used by a widened recipe via an intervening VPPredInstPHIRecipe.
VPValue * getStepValue() const
Definition VPlan.h:3939
VPValue * getStartIndex() const
Return the StartIndex, or null if known to be zero, valid only after unrolling.
Definition VPlan.h:3947
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate the scalarized versions of the phi node as needed by their users.
VPSingleDef is a base class for recipes for modeling a sequence of one or more output IR that define ...
Definition VPlan.h:588
Instruction * getUnderlyingInstr()
Returns the underlying instruction.
Definition VPlan.h:651
LLVM_ABI_FOR_TEST LLVM_DUMP_METHOD void dump() const
Print this VPSingleDefRecipe to dbgs() (for debugging).
VPSingleDefRecipe(const unsigned char SC, ArrayRef< VPValue * > Operands, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:590
This class can be used to assign names to VPValues.
Type * inferScalarType(const VPValue *V)
Infer the type of V. Returns the scalar type of V.
Helper to access the operand that contains the unroll part for this recipe after unrolling.
Definition VPlan.h:1075
VPValue * getUnrollPartOperand(const VPUser &U) const
Return the VPValue operand containing the unroll part or null if there is no such operand.
unsigned getUnrollPart(const VPUser &U) const
Return the unroll part.
This class augments VPValue with operands which provide the inverse def-use edges from VPValue's user...
Definition VPlanValue.h:258
void printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const
Print the operands to O.
Definition VPlan.cpp:1437
operand_range operands()
Definition VPlanValue.h:326
void setOperand(unsigned I, VPValue *New)
Definition VPlanValue.h:302
unsigned getNumOperands() const
Definition VPlanValue.h:296
operand_iterator op_begin()
Definition VPlanValue.h:322
VPValue * getOperand(unsigned N) const
Definition VPlanValue.h:297
virtual bool usesFirstLaneOnly(const VPValue *Op) const
Returns true if the VPUser only uses the first lane of operand Op.
Definition VPlanValue.h:341
This is the base class of the VPlan Def/Use graph, used for modeling the data flow into,...
Definition VPlanValue.h:46
Value * getLiveInIRValue() const
Return the underlying IR value for a VPIRValue.
Definition VPlan.cpp:135
bool isDefinedOutsideLoopRegions() const
Returns true if the VPValue is defined outside any loop.
Definition VPlan.cpp:1391
VPRecipeBase * getDefiningRecipe()
Returns the recipe defining this VPValue or nullptr if it is not defined by a recipe,...
Definition VPlan.cpp:125
void printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const
Definition VPlan.cpp:1433
Value * getUnderlyingValue() const
Return the underlying Value attached to this VPValue.
Definition VPlanValue.h:71
void replaceAllUsesWith(VPValue *New)
Definition VPlan.cpp:1394
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
Type * getSourceElementType() const
Definition VPlan.h:2069
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
operand_range args()
Definition VPlan.h:1870
Function * getCalledScalarFunction() const
Definition VPlan.h:1866
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenCallRecipe.
void execute(VPTransformState &State) override
Produce a widened version of the call instruction.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate a canonical vector induction variable of the vector loop, with start = {<Part*VF,...
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
LLVM_ABI_FOR_TEST void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
Type * getResultType() const
Returns the result type of the cast.
Definition VPlan.h:1719
LLVM_ABI_FOR_TEST void execute(VPTransformState &State) override
Produce widened copies of the cast.
LLVM_ABI_FOR_TEST InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenCastRecipe.
void execute(VPTransformState &State) override
Generate the gep nodes.
Type * getSourceElementType() const
Definition VPlan.h:1967
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
VPIRValue * getStartValue() const
Returns the start value of the induction.
Definition VPlan.h:2227
VPValue * getStepValue()
Returns the step value of the induction.
Definition VPlan.h:2230
VPIRValue * getStartValue() const
Returns the start value of the induction.
Definition VPlan.h:2325
TruncInst * getTruncInst()
Returns the first defined value as TruncInst, if it is one or nullptr otherwise.
Definition VPlan.h:2340
Type * getScalarType() const
Returns the scalar type of the induction.
Definition VPlan.h:2349
bool isCanonical() const
Returns true if the induction is canonical, i.e.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
Intrinsic::ID getVectorIntrinsicID() const
Return the ID of the intrinsic.
Definition VPlan.h:1801
LLVM_ABI_FOR_TEST void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
StringRef getIntrinsicName() const
Return to name of the intrinsic as string.
LLVM_ABI_FOR_TEST bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the VPUser only uses the first lane of operand Op.
Type * getResultType() const
Return the scalar return type of the intrinsic.
Definition VPlan.h:1804
LLVM_ABI_FOR_TEST void execute(VPTransformState &State) override
Produce a widened version of the vector intrinsic.
LLVM_ABI_FOR_TEST InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this vector intrinsic.
bool IsMasked
Whether the memory access is masked.
Definition VPlan.h:3366
bool Reverse
Whether the consecutive accessed addresses are in reverse order.
Definition VPlan.h:3363
bool isConsecutive() const
Return whether the loaded-from / stored-to addresses are consecutive.
Definition VPlan.h:3406
Instruction & Ingredient
Definition VPlan.h:3354
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenMemoryRecipe.
bool Consecutive
Whether the accessed addresses are consecutive.
Definition VPlan.h:3360
VPValue * getMask() const
Return the mask used by this recipe.
Definition VPlan.h:3420
Align Alignment
Alignment information for this memory access.
Definition VPlan.h:3357
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition VPlan.h:3413
bool isReverse() const
Return whether the consecutive loaded/stored addresses are in reverse order.
Definition VPlan.h:3410
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenPHIRecipe.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate the phi/select nodes.
bool onlyScalarsGenerated(bool IsScalable)
Returns true if only scalar values will be generated.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenRecipe.
void execute(VPTransformState &State) override
Produce a widened instruction using the opcode and operands of the recipe, processing State....
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
unsigned getUF() const
Definition VPlan.h:4616
LLVM_ABI_FOR_TEST VPRegionBlock * getVectorLoopRegion()
Returns the VPRegionBlock of the vector loop.
Definition VPlan.cpp:1031
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:256
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:397
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:259
void mutateType(Type *Ty)
Mutate the type of this Value to be of the specified type.
Definition Value.h:838
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:322
Base class of all SIMD vector types.
ElementCount getElementCount() const
Return an ElementCount instance to represent the (possibly scalable) number of elements in the vector...
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
Type * getElementType() const
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
constexpr LeafTy multiplyCoefficientBy(ScalarTy RHS) const
Definition TypeSize.h:256
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:165
constexpr LeafTy divideCoefficientBy(ScalarTy RHS) const
We do not provide the '/' operator here because division for polynomial types does not work in the sa...
Definition TypeSize.h:252
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
iterator erase(iterator where)
Definition ilist.h:204
pointer remove(iterator &IT)
Definition ilist.h:188
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > Tys={})
Look up the Function declaration of the intrinsic id in the Module M.
LLVM_ABI Intrinsic::ID getDeinterleaveIntrinsicID(unsigned Factor)
Returns the corresponding llvm.vector.deinterleaveN intrinsic for factor N.
LLVM_ABI StringRef getBaseName(ID id)
Return the LLVM name for an intrinsic, without encoded types for overloading, such as "llvm....
bool match(Val *V, const Pattern &P)
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
class_match< CmpInst > m_Cmp()
Matches any compare instruction and ignore it.
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
specific_intval< 1 > m_False()
specific_intval< 1 > m_True()
class_match< VPValue > m_VPValue()
Match an arbitrary VPValue and ignore it.
VPInstruction_match< VPInstruction::Reverse, Op0_t > m_Reverse(const Op0_t &Op0)
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
bool isSingleScalar(const VPValue *VPV)
Returns true if VPV is a single scalar, either because it produces the same value for all lanes or on...
bool isAddressSCEVForCost(const SCEV *Addr, ScalarEvolution &SE, const Loop *L)
Returns true if Addr is an address SCEV that can be passed to TTI::getAddressComputationCost,...
bool onlyFirstPartUsed(const VPValue *Def)
Returns true if only the first part of Def is used.
bool onlyFirstLaneUsed(const VPValue *Def)
Returns true if only the first lane of Def is used.
bool onlyScalarValuesUsed(const VPValue *Def)
Returns true if only scalar values of Def are used by all users.
const SCEV * getSCEVExprForVPValue(const VPValue *V, PredicatedScalarEvolution &PSE, const Loop *L=nullptr)
Return the SCEV expression for V.
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
LLVM_ABI Value * createSimpleReduction(IRBuilderBase &B, Value *Src, RecurKind RdxKind)
Create a reduction of the given vector.
@ Offset
Definition DWP.cpp:532
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
Definition STLExtras.h:829
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
auto cast_if_present(const Y &Val)
cast_if_present<X> - Functionally identical to cast, except that a null value is accepted.
Definition Casting.h:683
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1737
LLVM_ABI Intrinsic::ID getMinMaxReductionIntrinsicOp(Intrinsic::ID RdxID)
Returns the min/max intrinsic used when expanding a min/max reduction.
InstructionCost Cost
@ Undef
Value of the register doesn't matter.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2544
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
Value * getRuntimeVF(IRBuilderBase &B, Type *Ty, ElementCount VF)
Return the runtime value for VF.
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2198
void interleaveComma(const Container &c, StreamT &os, UnaryFunctor each_fn)
Definition STLExtras.h:2303
auto cast_or_null(const Y &Val)
Definition Casting.h:714
LLVM_ABI Value * concatenateVectors(IRBuilderBase &Builder, ArrayRef< Value * > Vecs)
Concatenate a list of vectors.
Align getLoadStoreAlignment(const Value *I)
A helper function that returns the alignment of load or store instruction.
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
LLVM_ABI Value * createMinMaxOp(IRBuilderBase &Builder, RecurKind RK, Value *Left, Value *Right)
Returns a Min/Max operation corresponding to MinMaxRecurrenceKind.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
static Error getOffset(const SymbolRef &Sym, SectionRef Sec, uint64_t &Result)
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:1744
LLVM_ABI Constant * createBitMaskForGaps(IRBuilderBase &Builder, unsigned VF, const InterleaveGroup< Instruction > &Group)
Create a mask that filters the members of an interleave group where there are gaps.
LLVM_ABI llvm::SmallVector< int, 16 > createStrideMask(unsigned Start, unsigned Stride, unsigned VF)
Create a stride shuffle mask.
auto reverse(ContainerTy &&C)
Definition STLExtras.h:406
LLVM_ABI llvm::SmallVector< int, 16 > createReplicatedMask(unsigned ReplicationFactor, unsigned VF)
Create a mask with replicated elements.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1751
SmallVector< ValueTypeFromRangeType< R >, Size > to_vector(R &&Range)
Given a range of type R, iterate the entire range and return a SmallVector with elements of the vecto...
Type * toVectorizedTy(Type *Ty, ElementCount EC)
A helper for converting to vectorized types.
cl::opt< unsigned > ForceTargetInstructionCost
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
auto drop_end(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the last N elements excluded.
Definition STLExtras.h:323
LLVM_ABI bool isVectorIntrinsicWithStructReturnOverloadAtField(Intrinsic::ID ID, int RetIdx, const TargetTransformInfo *TTI)
Identifies if the vector form of the intrinsic that returns a struct is overloaded at the struct elem...
@ Other
Any other memory.
Definition ModRef.h:68
bool canVectorizeTy(Type *Ty)
Returns true if Ty is a valid vector element type, void, or an unpacked literal struct where all elem...
FunctionAddr VTableAddr uintptr_t uintptr_t Data
Definition InstrProf.h:189
LLVM_ABI llvm::SmallVector< int, 16 > createInterleaveMask(unsigned VF, unsigned NumVecs)
Create an interleave shuffle mask.
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.
@ FMinimum
FP min with llvm.minimum semantics.
@ FMaxNum
FP max with llvm.maxnum semantics including NaNs.
@ Mul
Product of integers.
@ AnyOf
AnyOf reduction with select(cmp(),x,y) where one of (x,y) is loop invariant, and both x and y are int...
@ FMaximum
FP max with llvm.maximum semantics.
@ SMax
Signed integer max implemented in terms of select(cmp()).
@ SMin
Signed integer min implemented in terms of select(cmp()).
@ FMinNum
FP min with llvm.minnum semantics including NaNs.
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
@ FAdd
Sum of floats.
@ FMaximumNum
FP max with llvm.maximumnum semantics.
@ UMax
Unsigned integer max implemented in terms of select(cmp()).
LLVM_ABI bool isVectorIntrinsicWithScalarOpAtArg(Intrinsic::ID ID, unsigned ScalarOpdIdx, const TargetTransformInfo *TTI)
Identifies if the vector form of the intrinsic has a scalar operand.
LLVM_ABI Value * getRecurrenceIdentity(RecurKind K, Type *Tp, FastMathFlags FMF)
Given information about an recurrence kind, return the identity for the @llvm.vector....
DWARFExpression::Operation Op
Value * createStepForVF(IRBuilderBase &B, Type *Ty, ElementCount VF, int64_t Step)
Return a value for Step multiplied by VF.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
Value * emitTransformedIndex(IRBuilderBase &B, Value *Index, Value *StartValue, Value *Step, InductionDescriptor::InductionKind InductionKind, const BinaryOperator *InductionBinOp)
Compute the transformed value of Index at offset StartValue using step StepValue.
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1945
Type * getLoadStoreType(const Value *I)
A helper function that returns the type of a load or store instruction.
LLVM_ABI Value * createOrderedReduction(IRBuilderBase &B, RecurKind RdxKind, Value *Src, Value *Start)
Create an ordered reduction intrinsic using the given recurrence kind RdxKind.
ArrayRef< Type * > getContainedTypes(Type *const &Ty)
Returns the types contained in Ty.
auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:305
Type * toVectorTy(Type *Scalar, ElementCount EC)
A helper function for converting Scalar types to vector types.
@ Default
The result values are uniform if and only if all operands are uniform.
Definition Uniformity.h:20
LLVM_ABI bool isVectorIntrinsicWithOverloadTypeAtArg(Intrinsic::ID ID, int OpdIdx, const TargetTransformInfo *TTI)
Identifies if the vector form of the intrinsic is overloaded on the type of the operand at index OpdI...
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Struct to hold various analysis needed for cost computations.
void execute(VPTransformState &State) override
Generate the phi nodes.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this first-order recurrence phi recipe.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
An overlay for VPIRInstructions wrapping PHI nodes enabling convenient use cast/dyn_cast/isa and exec...
Definition VPlan.h:1605
PHINode & getIRPhi()
Definition VPlan.h:1613
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
void execute(VPTransformState &State) override
Generate the instruction.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
A pure-virtual common base class for recipes defining a single VPValue and using IR flags.
Definition VPlan.h:1030
InstructionCost getCostForRecipeWithOpcode(unsigned Opcode, ElementCount VF, VPCostContext &Ctx) const
Compute the cost for this recipe for VF, using Opcode and Ctx.
VPRecipeWithIRFlags(const unsigned char SC, ArrayRef< VPValue * > Operands, const VPIRFlags &Flags, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:1031
A symbolic live-in VPValue, used for values like vector trip count, VF, and VFxUF.
Definition VPlanValue.h:223
SmallDenseMap< const VPBasicBlock *, BasicBlock * > VPBB2IRBB
A mapping of each VPBasicBlock to the corresponding BasicBlock.
VPTransformState holds information passed down when "executing" a VPlan, needed for generating the ou...
VPTypeAnalysis TypeAnalysis
VPlan-based type analysis.
struct llvm::VPTransformState::CFGState CFG
Value * get(const VPValue *Def, bool IsScalar=false)
Get the generated vector Value for a given VPValue Def if IsScalar is false, otherwise return the gen...
Definition VPlan.cpp:277
IRBuilderBase & Builder
Hold a reference to the IRBuilder used to generate output IR code.
ElementCount VF
The chosen Vectorization Factor of the loop being vectorized.
LLVM_ABI_FOR_TEST void execute(VPTransformState &State) override
Generate the wide load or gather.
LLVM_ABI_FOR_TEST void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
LLVM_ABI_FOR_TEST InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenLoadEVLRecipe.
VPValue * getEVL() const
Return the EVL operand.
Definition VPlan.h:3498
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate a wide load or gather.
VPValue * getStoredValue() const
Return the address accessed by this recipe.
Definition VPlan.h:3582
LLVM_ABI_FOR_TEST void execute(VPTransformState &State) override
Generate the wide store or scatter.
LLVM_ABI_FOR_TEST void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
LLVM_ABI_FOR_TEST InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenStoreEVLRecipe.
VPValue * getEVL() const
Return the EVL operand.
Definition VPlan.h:3585
void execute(VPTransformState &State) override
Generate a wide store or scatter.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPValue * getStoredValue() const
Return the value stored by this recipe.
Definition VPlan.h:3545