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 VPCurrentIterationPHISC:
79 case VPBranchOnMaskSC:
80 case VPDerivedIVSC:
81 case VPFirstOrderRecurrencePHISC:
82 case VPReductionPHISC:
83 case VPScalarIVStepsSC:
84 case VPPredInstPHISC:
85 return false;
86 case VPBlendSC:
87 case VPReductionEVLSC:
88 case VPReductionSC:
89 case VPVectorPointerSC:
90 case VPWidenCanonicalIVSC:
91 case VPWidenCastSC:
92 case VPWidenGEPSC:
93 case VPWidenIntOrFpInductionSC:
94 case VPWidenLoadEVLSC:
95 case VPWidenLoadSC:
96 case VPWidenPHISC:
97 case VPWidenPointerInductionSC:
98 case VPWidenSC: {
99 const Instruction *I =
100 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
101 (void)I;
102 assert((!I || !I->mayWriteToMemory()) &&
103 "underlying instruction may write to memory");
104 return false;
105 }
106 default:
107 return true;
108 }
109}
110
112 switch (getVPRecipeID()) {
113 case VPExpressionSC:
114 return cast<VPExpressionRecipe>(this)->mayReadOrWriteMemory();
115 case VPInstructionSC:
116 return cast<VPInstruction>(this)->opcodeMayReadOrWriteFromMemory();
117 case VPWidenLoadEVLSC:
118 case VPWidenLoadSC:
119 return true;
120 case VPReplicateSC:
121 return cast<Instruction>(getVPSingleValue()->getUnderlyingValue())
122 ->mayReadFromMemory();
123 case VPWidenCallSC:
124 return !cast<VPWidenCallRecipe>(this)
125 ->getCalledScalarFunction()
126 ->onlyWritesMemory();
127 case VPWidenIntrinsicSC:
128 return cast<VPWidenIntrinsicRecipe>(this)->mayReadFromMemory();
129 case VPBranchOnMaskSC:
130 case VPDerivedIVSC:
131 case VPFirstOrderRecurrencePHISC:
132 case VPReductionPHISC:
133 case VPPredInstPHISC:
134 case VPScalarIVStepsSC:
135 case VPWidenStoreEVLSC:
136 case VPWidenStoreSC:
137 return false;
138 case VPBlendSC:
139 case VPReductionEVLSC:
140 case VPReductionSC:
141 case VPVectorPointerSC:
142 case VPWidenCanonicalIVSC:
143 case VPWidenCastSC:
144 case VPWidenGEPSC:
145 case VPWidenIntOrFpInductionSC:
146 case VPWidenPHISC:
147 case VPWidenPointerInductionSC:
148 case VPWidenSC: {
149 const Instruction *I =
150 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
151 (void)I;
152 assert((!I || !I->mayReadFromMemory()) &&
153 "underlying instruction may read from memory");
154 return false;
155 }
156 default:
157 // FIXME: Return false if the recipe represents an interleaved store.
158 return true;
159 }
160}
161
163 switch (getVPRecipeID()) {
164 case VPExpressionSC:
165 return cast<VPExpressionRecipe>(this)->mayHaveSideEffects();
166 case VPActiveLaneMaskPHISC:
167 case VPDerivedIVSC:
168 case VPFirstOrderRecurrencePHISC:
169 case VPReductionPHISC:
170 case VPPredInstPHISC:
171 case VPVectorEndPointerSC:
172 return false;
173 case VPInstructionSC: {
174 auto *VPI = cast<VPInstruction>(this);
175 return mayWriteToMemory() ||
176 VPI->getOpcode() == VPInstruction::BranchOnCount ||
177 VPI->getOpcode() == VPInstruction::BranchOnCond ||
178 VPI->getOpcode() == VPInstruction::BranchOnTwoConds;
179 }
180 case VPWidenCallSC: {
181 Function *Fn = cast<VPWidenCallRecipe>(this)->getCalledScalarFunction();
182 return mayWriteToMemory() || !Fn->doesNotThrow() || !Fn->willReturn();
183 }
184 case VPWidenIntrinsicSC:
185 return cast<VPWidenIntrinsicRecipe>(this)->mayHaveSideEffects();
186 case VPBlendSC:
187 case VPReductionEVLSC:
188 case VPReductionSC:
189 case VPScalarIVStepsSC:
190 case VPVectorPointerSC:
191 case VPWidenCanonicalIVSC:
192 case VPWidenCastSC:
193 case VPWidenGEPSC:
194 case VPWidenIntOrFpInductionSC:
195 case VPWidenPHISC:
196 case VPWidenPointerInductionSC:
197 case VPWidenSC: {
198 const Instruction *I =
199 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
200 (void)I;
201 assert((!I || !I->mayHaveSideEffects()) &&
202 "underlying instruction has side-effects");
203 return false;
204 }
205 case VPInterleaveEVLSC:
206 case VPInterleaveSC:
207 return mayWriteToMemory();
208 case VPWidenLoadEVLSC:
209 case VPWidenLoadSC:
210 case VPWidenStoreEVLSC:
211 case VPWidenStoreSC:
212 assert(
213 cast<VPWidenMemoryRecipe>(this)->getIngredient().mayHaveSideEffects() ==
215 "mayHaveSideffects result for ingredient differs from this "
216 "implementation");
217 return mayWriteToMemory();
218 case VPReplicateSC: {
219 auto *R = cast<VPReplicateRecipe>(this);
220 return R->getUnderlyingInstr()->mayHaveSideEffects();
221 }
222 default:
223 return true;
224 }
225}
226
228 assert(!Parent && "Recipe already in some VPBasicBlock");
229 assert(InsertPos->getParent() &&
230 "Insertion position not in any VPBasicBlock");
231 InsertPos->getParent()->insert(this, InsertPos->getIterator());
232}
233
234void VPRecipeBase::insertBefore(VPBasicBlock &BB,
236 assert(!Parent && "Recipe already in some VPBasicBlock");
237 assert(I == BB.end() || I->getParent() == &BB);
238 BB.insert(this, I);
239}
240
242 assert(!Parent && "Recipe already in some VPBasicBlock");
243 assert(InsertPos->getParent() &&
244 "Insertion position not in any VPBasicBlock");
245 InsertPos->getParent()->insert(this, std::next(InsertPos->getIterator()));
246}
247
249 assert(getParent() && "Recipe not in any VPBasicBlock");
251 Parent = nullptr;
252}
253
255 assert(getParent() && "Recipe not in any VPBasicBlock");
257}
258
261 insertAfter(InsertPos);
262}
263
269
271 // Get the underlying instruction for the recipe, if there is one. It is used
272 // to
273 // * decide if cost computation should be skipped for this recipe,
274 // * apply forced target instruction cost.
275 Instruction *UI = nullptr;
276 if (auto *S = dyn_cast<VPSingleDefRecipe>(this))
277 UI = dyn_cast_or_null<Instruction>(S->getUnderlyingValue());
278 else if (auto *IG = dyn_cast<VPInterleaveBase>(this))
279 UI = IG->getInsertPos();
280 else if (auto *WidenMem = dyn_cast<VPWidenMemoryRecipe>(this))
281 UI = &WidenMem->getIngredient();
282
283 InstructionCost RecipeCost;
284 if (UI && Ctx.skipCostComputation(UI, VF.isVector())) {
285 RecipeCost = 0;
286 } else {
287 RecipeCost = computeCost(VF, Ctx);
288 if (ForceTargetInstructionCost.getNumOccurrences() > 0 &&
289 RecipeCost.isValid()) {
290 if (UI)
292 else
293 RecipeCost = InstructionCost(0);
294 }
295 }
296
297 LLVM_DEBUG({
298 dbgs() << "Cost of " << RecipeCost << " for VF " << VF << ": ";
299 dump();
300 });
301 return RecipeCost;
302}
303
305 VPCostContext &Ctx) const {
306 llvm_unreachable("subclasses should implement computeCost");
307}
308
310 return (getVPRecipeID() >= VPFirstPHISC && getVPRecipeID() <= VPLastPHISC) ||
312}
313
315 auto *VPI = dyn_cast<VPInstruction>(this);
316 return VPI && Instruction::isCast(VPI->getOpcode());
317}
318
320 assert(OpType == Other.OpType && "OpType must match");
321 switch (OpType) {
322 case OperationType::OverflowingBinOp:
323 WrapFlags.HasNUW &= Other.WrapFlags.HasNUW;
324 WrapFlags.HasNSW &= Other.WrapFlags.HasNSW;
325 break;
326 case OperationType::Trunc:
327 TruncFlags.HasNUW &= Other.TruncFlags.HasNUW;
328 TruncFlags.HasNSW &= Other.TruncFlags.HasNSW;
329 break;
330 case OperationType::DisjointOp:
331 DisjointFlags.IsDisjoint &= Other.DisjointFlags.IsDisjoint;
332 break;
333 case OperationType::PossiblyExactOp:
334 ExactFlags.IsExact &= Other.ExactFlags.IsExact;
335 break;
336 case OperationType::GEPOp:
337 GEPFlags &= Other.GEPFlags;
338 break;
339 case OperationType::FPMathOp:
340 case OperationType::FCmp:
341 assert((OpType != OperationType::FCmp ||
342 FCmpFlags.Pred == Other.FCmpFlags.Pred) &&
343 "Cannot drop CmpPredicate");
344 getFMFsRef().NoNaNs &= Other.getFMFsRef().NoNaNs;
345 getFMFsRef().NoInfs &= Other.getFMFsRef().NoInfs;
346 break;
347 case OperationType::NonNegOp:
348 NonNegFlags.NonNeg &= Other.NonNegFlags.NonNeg;
349 break;
350 case OperationType::Cmp:
351 assert(CmpPredicate == Other.CmpPredicate && "Cannot drop CmpPredicate");
352 break;
353 case OperationType::ReductionOp:
354 assert(ReductionFlags.Kind == Other.ReductionFlags.Kind &&
355 "Cannot change RecurKind");
356 assert(ReductionFlags.IsOrdered == Other.ReductionFlags.IsOrdered &&
357 "Cannot change IsOrdered");
358 assert(ReductionFlags.IsInLoop == Other.ReductionFlags.IsInLoop &&
359 "Cannot change IsInLoop");
360 getFMFsRef().NoNaNs &= Other.getFMFsRef().NoNaNs;
361 getFMFsRef().NoInfs &= Other.getFMFsRef().NoInfs;
362 break;
363 case OperationType::Other:
364 assert(AllFlags == Other.AllFlags && "Cannot drop other flags");
365 break;
366 }
367}
368
370 assert((OpType == OperationType::FPMathOp || OpType == OperationType::FCmp ||
371 OpType == OperationType::ReductionOp ||
372 OpType == OperationType::Other) &&
373 "recipe doesn't have fast math flags");
374 if (OpType == OperationType::Other)
375 return FastMathFlags();
376 const FastMathFlagsTy &F = getFMFsRef();
377 FastMathFlags Res;
378 Res.setAllowReassoc(F.AllowReassoc);
379 Res.setNoNaNs(F.NoNaNs);
380 Res.setNoInfs(F.NoInfs);
381 Res.setNoSignedZeros(F.NoSignedZeros);
382 Res.setAllowReciprocal(F.AllowReciprocal);
383 Res.setAllowContract(F.AllowContract);
384 Res.setApproxFunc(F.ApproxFunc);
385 return Res;
386}
387
388#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
390
391void VPRecipeBase::print(raw_ostream &O, const Twine &Indent,
392 VPSlotTracker &SlotTracker) const {
393 printRecipe(O, Indent, SlotTracker);
394 if (auto DL = getDebugLoc()) {
395 O << ", !dbg ";
396 DL.print(O);
397 }
398
399 if (auto *Metadata = dyn_cast<VPIRMetadata>(this))
401}
402#endif
403
404template <unsigned PartOpIdx>
405VPValue *
407 if (U.getNumOperands() == PartOpIdx + 1)
408 return U.getOperand(PartOpIdx);
409 return nullptr;
410}
411
412template <unsigned PartOpIdx>
414 if (auto *UnrollPartOp = getUnrollPartOperand(U))
415 return cast<VPConstantInt>(UnrollPartOp)->getZExtValue();
416 return 0;
417}
418
419namespace llvm {
420template class VPUnrollPartAccessor<1>;
421template class VPUnrollPartAccessor<2>;
422template class VPUnrollPartAccessor<3>;
423}
424
426 const VPIRFlags &Flags, const VPIRMetadata &MD,
427 DebugLoc DL, const Twine &Name)
428 : VPRecipeWithIRFlags(VPRecipeBase::VPInstructionSC, Operands, Flags, DL),
429 VPIRMetadata(MD), Opcode(Opcode), Name(Name.str()) {
431 "Set flags not supported for the provided opcode");
433 "Opcode requires specific flags to be set");
437 "number of operands does not match opcode");
438}
439
441 if (Instruction::isUnaryOp(Opcode) || Instruction::isCast(Opcode))
442 return 1;
443
444 if (Instruction::isBinaryOp(Opcode))
445 return 2;
446
447 switch (Opcode) {
450 return 0;
451 case Instruction::Alloca:
452 case Instruction::ExtractValue:
453 case Instruction::Freeze:
454 case Instruction::Load:
467 return 1;
468 case Instruction::ICmp:
469 case Instruction::FCmp:
470 case Instruction::ExtractElement:
471 case Instruction::Store:
481 return 2;
482 case Instruction::Select:
486 return 3;
487 case Instruction::Call: {
488 // For unmasked calls, the last argument will the called function. Use that
489 // to compute the number of operands without the mask.
490 VPValue *LastOp = getOperand(getNumOperands() - 1);
491 if (isa<VPIRValue>(LastOp) && isa<Function>(LastOp->getLiveInIRValue()))
492 return getNumOperands();
493 return getNumOperands() - 1;
494 }
495 case Instruction::GetElementPtr:
496 case Instruction::PHI:
497 case Instruction::Switch:
509 // Cannot determine the number of operands from the opcode.
510 return -1u;
511 }
512 llvm_unreachable("all cases should be handled above");
513}
514
518
519bool VPInstruction::canGenerateScalarForFirstLane() const {
521 return true;
523 return true;
524 switch (Opcode) {
525 case Instruction::Freeze:
526 case Instruction::ICmp:
527 case Instruction::PHI:
528 case Instruction::Select:
538 return true;
539 default:
540 return false;
541 }
542}
543
544Value *VPInstruction::generate(VPTransformState &State) {
545 IRBuilderBase &Builder = State.Builder;
546
548 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
549 Value *A = State.get(getOperand(0), OnlyFirstLaneUsed);
550 Value *B = State.get(getOperand(1), OnlyFirstLaneUsed);
551 auto *Res =
552 Builder.CreateBinOp((Instruction::BinaryOps)getOpcode(), A, B, Name);
553 if (auto *I = dyn_cast<Instruction>(Res))
554 applyFlags(*I);
555 return Res;
556 }
557
558 switch (getOpcode()) {
559 case VPInstruction::Not: {
560 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
561 Value *A = State.get(getOperand(0), OnlyFirstLaneUsed);
562 return Builder.CreateNot(A, Name);
563 }
564 case Instruction::ExtractElement: {
565 assert(State.VF.isVector() && "Only extract elements from vectors");
566 if (auto *Idx = dyn_cast<VPConstantInt>(getOperand(1)))
567 return State.get(getOperand(0), VPLane(Idx->getZExtValue()));
568 Value *Vec = State.get(getOperand(0));
569 Value *Idx = State.get(getOperand(1), /*IsScalar=*/true);
570 return Builder.CreateExtractElement(Vec, Idx, Name);
571 }
572 case Instruction::Freeze: {
574 return Builder.CreateFreeze(Op, Name);
575 }
576 case Instruction::FCmp:
577 case Instruction::ICmp: {
578 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
579 Value *A = State.get(getOperand(0), OnlyFirstLaneUsed);
580 Value *B = State.get(getOperand(1), OnlyFirstLaneUsed);
581 return Builder.CreateCmp(getPredicate(), A, B, Name);
582 }
583 case Instruction::PHI: {
584 llvm_unreachable("should be handled by VPPhi::execute");
585 }
586 case Instruction::Select: {
587 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
588 Value *Cond =
589 State.get(getOperand(0),
590 OnlyFirstLaneUsed || vputils::isSingleScalar(getOperand(0)));
591 Value *Op1 = State.get(getOperand(1), OnlyFirstLaneUsed);
592 Value *Op2 = State.get(getOperand(2), OnlyFirstLaneUsed);
593 return Builder.CreateSelectFMF(Cond, Op1, Op2, getFastMathFlags(), Name);
594 }
596 // Get first lane of vector induction variable.
597 Value *VIVElem0 = State.get(getOperand(0), VPLane(0));
598 // Get the original loop tripcount.
599 Value *ScalarTC = State.get(getOperand(1), VPLane(0));
600
601 // If this part of the active lane mask is scalar, generate the CMP directly
602 // to avoid unnecessary extracts.
603 if (State.VF.isScalar())
604 return Builder.CreateCmp(CmpInst::Predicate::ICMP_ULT, VIVElem0, ScalarTC,
605 Name);
606
607 ElementCount EC = State.VF.multiplyCoefficientBy(
608 cast<VPConstantInt>(getOperand(2))->getZExtValue());
609 auto *PredTy = VectorType::get(Builder.getInt1Ty(), EC);
610 return Builder.CreateIntrinsic(Intrinsic::get_active_lane_mask,
611 {PredTy, ScalarTC->getType()},
612 {VIVElem0, ScalarTC}, nullptr, Name);
613 }
615 // Generate code to combine the previous and current values in vector v3.
616 //
617 // vector.ph:
618 // v_init = vector(..., ..., ..., a[-1])
619 // br vector.body
620 //
621 // vector.body
622 // i = phi [0, vector.ph], [i+4, vector.body]
623 // v1 = phi [v_init, vector.ph], [v2, vector.body]
624 // v2 = a[i, i+1, i+2, i+3];
625 // v3 = vector(v1(3), v2(0, 1, 2))
626
627 auto *V1 = State.get(getOperand(0));
628 if (!V1->getType()->isVectorTy())
629 return V1;
630 Value *V2 = State.get(getOperand(1));
631 return Builder.CreateVectorSpliceRight(V1, V2, 1, Name);
632 }
634 Value *ScalarTC = State.get(getOperand(0), VPLane(0));
635 Value *VFxUF = State.get(getOperand(1), VPLane(0));
636 Value *Sub = Builder.CreateSub(ScalarTC, VFxUF);
637 Value *Cmp =
638 Builder.CreateICmp(CmpInst::Predicate::ICMP_UGT, ScalarTC, VFxUF);
640 return Builder.CreateSelect(Cmp, Sub, Zero);
641 }
643 // TODO: Restructure this code with an explicit remainder loop, vsetvli can
644 // be outside of the main loop.
645 Value *AVL = State.get(getOperand(0), /*IsScalar*/ true);
646 // Compute EVL
647 assert(AVL->getType()->isIntegerTy() &&
648 "Requested vector length should be an integer.");
649
650 assert(State.VF.isScalable() && "Expected scalable vector factor.");
651 Value *VFArg = Builder.getInt32(State.VF.getKnownMinValue());
652
653 Value *EVL = Builder.CreateIntrinsic(
654 Builder.getInt32Ty(), Intrinsic::experimental_get_vector_length,
655 {AVL, VFArg, Builder.getTrue()});
656 return EVL;
657 }
659 auto *IV = State.get(getOperand(0), VPLane(0));
660 auto *VFxPart = State.get(getOperand(1), VPLane(0));
661 // The canonical IV is incremented by the vectorization factor (num of
662 // SIMD elements) times the unroll part.
663 return Builder.CreateAdd(IV, VFxPart, Name, hasNoUnsignedWrap(),
665 }
667 Value *Cond = State.get(getOperand(0), VPLane(0));
668 // Replace the temporary unreachable terminator with a new conditional
669 // branch, hooking it up to backward destination for latch blocks now, and
670 // to forward destination(s) later when they are created.
671 // Second successor may be backwards - iff it is already in VPBB2IRBB.
672 VPBasicBlock *SecondVPSucc =
673 cast<VPBasicBlock>(getParent()->getSuccessors()[1]);
674 BasicBlock *SecondIRSucc = State.CFG.VPBB2IRBB.lookup(SecondVPSucc);
675 BasicBlock *IRBB = State.CFG.VPBB2IRBB[getParent()];
676 auto *Br = Builder.CreateCondBr(Cond, IRBB, SecondIRSucc);
677 // First successor is always forward, reset it to nullptr.
678 Br->setSuccessor(0, nullptr);
680 applyMetadata(*Br);
681 return Br;
682 }
684 return Builder.CreateVectorSplat(
685 State.VF, State.get(getOperand(0), /*IsScalar*/ true), "broadcast");
686 }
688 // For struct types, we need to build a new 'wide' struct type, where each
689 // element is widened, i.e., we create a struct of vectors.
690 auto *StructTy =
692 Value *Res = PoisonValue::get(toVectorizedTy(StructTy, State.VF));
693 for (const auto &[LaneIndex, Op] : enumerate(operands())) {
694 for (unsigned FieldIndex = 0; FieldIndex != StructTy->getNumElements();
695 FieldIndex++) {
696 Value *ScalarValue =
697 Builder.CreateExtractValue(State.get(Op, true), FieldIndex);
698 Value *VectorValue = Builder.CreateExtractValue(Res, FieldIndex);
699 VectorValue =
700 Builder.CreateInsertElement(VectorValue, ScalarValue, LaneIndex);
701 Res = Builder.CreateInsertValue(Res, VectorValue, FieldIndex);
702 }
703 }
704 return Res;
705 }
707 auto *ScalarTy = State.TypeAnalysis.inferScalarType(getOperand(0));
708 auto NumOfElements = ElementCount::getFixed(getNumOperands());
709 Value *Res = PoisonValue::get(toVectorizedTy(ScalarTy, NumOfElements));
710 for (const auto &[Idx, Op] : enumerate(operands()))
711 Res = Builder.CreateInsertElement(Res, State.get(Op, true),
712 Builder.getInt32(Idx));
713 return Res;
714 }
716 if (State.VF.isScalar())
717 return State.get(getOperand(0), true);
718 IRBuilderBase::FastMathFlagGuard FMFG(Builder);
720 // If this start vector is scaled then it should produce a vector with fewer
721 // elements than the VF.
722 ElementCount VF = State.VF.divideCoefficientBy(
723 cast<VPConstantInt>(getOperand(2))->getZExtValue());
724 auto *Iden = Builder.CreateVectorSplat(VF, State.get(getOperand(1), true));
725 return Builder.CreateInsertElement(Iden, State.get(getOperand(0), true),
726 Builder.getInt32(0));
727 }
729 Value *Start = State.get(getOperand(0), VPLane(0));
730 Value *NewVal = State.get(getOperand(1), VPLane(0));
731 Value *ReducedResult = State.get(getOperand(2));
732 for (unsigned Idx = 3; Idx < getNumOperands(); ++Idx)
733 ReducedResult =
734 Builder.CreateBinOp(Instruction::Or, State.get(getOperand(Idx)),
735 ReducedResult, "bin.rdx");
736 // If any predicate is true it means that we want to select the new value.
737 if (ReducedResult->getType()->isVectorTy())
738 ReducedResult = Builder.CreateOrReduce(ReducedResult);
739 // The compares in the loop may yield poison, which propagates through the
740 // bitwise ORs. Freeze it here before the condition is used.
741 ReducedResult = Builder.CreateFreeze(ReducedResult);
742 return Builder.CreateSelect(ReducedResult, NewVal, Start, "rdx.select");
743 }
745 RecurKind RK = getRecurKind();
746 bool IsOrdered = isReductionOrdered();
747 bool IsInLoop = isReductionInLoop();
749 "FindIV should use min/max reduction kinds");
750
751 // The recipe may have multiple operands to be reduced together.
752 unsigned NumOperandsToReduce = getNumOperands();
753 VectorParts RdxParts(NumOperandsToReduce);
754 for (unsigned Part = 0; Part < NumOperandsToReduce; ++Part)
755 RdxParts[Part] = State.get(getOperand(Part), IsInLoop);
756
757 IRBuilderBase::FastMathFlagGuard FMFG(Builder);
759
760 // Reduce multiple operands into one.
761 Value *ReducedPartRdx = RdxParts[0];
762 if (IsOrdered) {
763 ReducedPartRdx = RdxParts[NumOperandsToReduce - 1];
764 } else {
765 // Floating-point operations should have some FMF to enable the reduction.
766 for (unsigned Part = 1; Part < NumOperandsToReduce; ++Part) {
767 Value *RdxPart = RdxParts[Part];
769 ReducedPartRdx = createMinMaxOp(Builder, RK, ReducedPartRdx, RdxPart);
770 else {
771 // For sub-recurrences, each part's reduction variable is already
772 // negative, we need to do: reduce.add(-acc_uf0 + -acc_uf1)
774 RK == RecurKind::Sub
775 ? Instruction::Add
777 ReducedPartRdx =
778 Builder.CreateBinOp(Opcode, RdxPart, ReducedPartRdx, "bin.rdx");
779 }
780 }
781 }
782
783 // Create the reduction after the loop. Note that inloop reductions create
784 // the target reduction in the loop using a Reduction recipe.
785 if (State.VF.isVector() && !IsInLoop) {
786 // TODO: Support in-order reductions based on the recurrence descriptor.
787 // All ops in the reduction inherit fast-math-flags from the recurrence
788 // descriptor.
789 ReducedPartRdx = createSimpleReduction(Builder, ReducedPartRdx, RK);
790 }
791
792 return ReducedPartRdx;
793 }
796 unsigned Offset =
798 Value *Res;
799 if (State.VF.isVector()) {
800 assert(Offset <= State.VF.getKnownMinValue() &&
801 "invalid offset to extract from");
802 // Extract lane VF - Offset from the operand.
803 Res = State.get(getOperand(0), VPLane::getLaneFromEnd(State.VF, Offset));
804 } else {
805 // TODO: Remove ExtractLastLane for scalar VFs.
806 assert(Offset <= 1 && "invalid offset to extract from");
807 Res = State.get(getOperand(0));
808 }
810 Res->setName(Name);
811 return Res;
812 }
814 Value *A = State.get(getOperand(0));
815 Value *B = State.get(getOperand(1));
816 return Builder.CreateLogicalAnd(A, B, Name);
817 }
819 Value *A = State.get(getOperand(0));
820 Value *B = State.get(getOperand(1));
821 return Builder.CreateLogicalOr(A, B, Name);
822 }
824 assert((State.VF.isScalar() || vputils::onlyFirstLaneUsed(this)) &&
825 "can only generate first lane for PtrAdd");
826 Value *Ptr = State.get(getOperand(0), VPLane(0));
827 Value *Addend = State.get(getOperand(1), VPLane(0));
828 return Builder.CreatePtrAdd(Ptr, Addend, Name, getGEPNoWrapFlags());
829 }
831 Value *Ptr =
833 Value *Addend = State.get(getOperand(1));
834 return Builder.CreatePtrAdd(Ptr, Addend, Name, getGEPNoWrapFlags());
835 }
837 Value *Res = Builder.CreateFreeze(State.get(getOperand(0)));
838 for (VPValue *Op : drop_begin(operands()))
839 Res = Builder.CreateOr(Res, Builder.CreateFreeze(State.get(Op)));
840 return State.VF.isScalar() ? Res : Builder.CreateOrReduce(Res);
841 }
843 assert(getNumOperands() != 2 && "ExtractLane from single source should be "
844 "simplified to ExtractElement.");
845 Value *LaneToExtract = State.get(getOperand(0), true);
846 Type *IdxTy = State.TypeAnalysis.inferScalarType(getOperand(0));
847 Value *Res = nullptr;
848 Value *RuntimeVF = getRuntimeVF(Builder, IdxTy, State.VF);
849
850 for (unsigned Idx = 1; Idx != getNumOperands(); ++Idx) {
851 Value *VectorStart =
852 Builder.CreateMul(RuntimeVF, ConstantInt::get(IdxTy, Idx - 1));
853 Value *VectorIdx = Idx == 1
854 ? LaneToExtract
855 : Builder.CreateSub(LaneToExtract, VectorStart);
856 Value *Ext = State.VF.isScalar()
857 ? State.get(getOperand(Idx))
858 : Builder.CreateExtractElement(
859 State.get(getOperand(Idx)), VectorIdx);
860 if (Res) {
861 Value *Cmp = Builder.CreateICmpUGE(LaneToExtract, VectorStart);
862 Res = Builder.CreateSelect(Cmp, Ext, Res);
863 } else {
864 Res = Ext;
865 }
866 }
867 return Res;
868 }
870 if (getNumOperands() == 1) {
871 Value *Mask = State.get(getOperand(0));
872 return Builder.CreateCountTrailingZeroElems(Builder.getInt64Ty(), Mask,
873 /*ZeroIsPoison=*/false, Name);
874 }
875 // If there are multiple operands, create a chain of selects to pick the
876 // first operand with an active lane and add the number of lanes of the
877 // preceding operands.
878 Value *RuntimeVF = getRuntimeVF(Builder, Builder.getInt64Ty(), State.VF);
879 unsigned LastOpIdx = getNumOperands() - 1;
880 Value *Res = nullptr;
881 for (int Idx = LastOpIdx; Idx >= 0; --Idx) {
882 Value *TrailingZeros =
883 State.VF.isScalar()
884 ? Builder.CreateZExt(
885 Builder.CreateICmpEQ(State.get(getOperand(Idx)),
886 Builder.getFalse()),
887 Builder.getInt64Ty())
889 Builder.getInt64Ty(), State.get(getOperand(Idx)),
890 /*ZeroIsPoison=*/false, Name);
891 Value *Current = Builder.CreateAdd(
892 Builder.CreateMul(RuntimeVF, Builder.getInt64(Idx)), TrailingZeros);
893 if (Res) {
894 Value *Cmp = Builder.CreateICmpNE(TrailingZeros, RuntimeVF);
895 Res = Builder.CreateSelect(Cmp, Current, Res);
896 } else {
897 Res = Current;
898 }
899 }
900
901 return Res;
902 }
904 return State.get(getOperand(0), true);
906 return Builder.CreateVectorReverse(State.get(getOperand(0)), "reverse");
908 Value *Data = State.get(getOperand(0));
909 Value *Mask = State.get(getOperand(1));
910 Value *Default = State.get(getOperand(2), /*IsScalar=*/true);
911 Type *VTy = Data->getType();
912 return Builder.CreateIntrinsic(
913 Intrinsic::experimental_vector_extract_last_active, {VTy},
914 {Data, Mask, Default});
915 }
916 default:
917 llvm_unreachable("Unsupported opcode for instruction");
918 }
919}
920
922 unsigned Opcode, ElementCount VF, VPCostContext &Ctx) const {
923 Type *ScalarTy = Ctx.Types.inferScalarType(this);
924 Type *ResultTy = VF.isVector() ? toVectorTy(ScalarTy, VF) : ScalarTy;
925 switch (Opcode) {
926 case Instruction::FNeg:
927 return Ctx.TTI.getArithmeticInstrCost(Opcode, ResultTy, Ctx.CostKind);
928 case Instruction::UDiv:
929 case Instruction::SDiv:
930 case Instruction::SRem:
931 case Instruction::URem:
932 case Instruction::Add:
933 case Instruction::FAdd:
934 case Instruction::Sub:
935 case Instruction::FSub:
936 case Instruction::Mul:
937 case Instruction::FMul:
938 case Instruction::FDiv:
939 case Instruction::FRem:
940 case Instruction::Shl:
941 case Instruction::LShr:
942 case Instruction::AShr:
943 case Instruction::And:
944 case Instruction::Or:
945 case Instruction::Xor: {
948
949 if (VF.isVector()) {
950 // Certain instructions can be cheaper to vectorize if they have a
951 // constant second vector operand. One example of this are shifts on x86.
952 VPValue *RHS = getOperand(1);
953 RHSInfo = Ctx.getOperandInfo(RHS);
954
955 if (RHSInfo.Kind == TargetTransformInfo::OK_AnyValue &&
958 }
959
962 if (CtxI)
963 Operands.append(CtxI->value_op_begin(), CtxI->value_op_end());
964 return Ctx.TTI.getArithmeticInstrCost(
965 Opcode, ResultTy, Ctx.CostKind,
966 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
967 RHSInfo, Operands, CtxI, &Ctx.TLI);
968 }
969 case Instruction::Freeze:
970 // This opcode is unknown. Assume that it is the same as 'mul'.
971 return Ctx.TTI.getArithmeticInstrCost(Instruction::Mul, ResultTy,
972 Ctx.CostKind);
973 case Instruction::ExtractValue:
974 return Ctx.TTI.getInsertExtractValueCost(Instruction::ExtractValue,
975 Ctx.CostKind);
976 case Instruction::ICmp:
977 case Instruction::FCmp: {
978 Type *ScalarOpTy = Ctx.Types.inferScalarType(getOperand(0));
979 Type *OpTy = VF.isVector() ? toVectorTy(ScalarOpTy, VF) : ScalarOpTy;
981 return Ctx.TTI.getCmpSelInstrCost(
982 Opcode, OpTy, CmpInst::makeCmpResultType(OpTy), getPredicate(),
983 Ctx.CostKind, {TTI::OK_AnyValue, TTI::OP_None},
984 {TTI::OK_AnyValue, TTI::OP_None}, CtxI);
985 }
986 case Instruction::BitCast: {
987 Type *ScalarTy = Ctx.Types.inferScalarType(this);
988 if (ScalarTy->isPointerTy())
989 return 0;
990 [[fallthrough]];
991 }
992 case Instruction::SExt:
993 case Instruction::ZExt:
994 case Instruction::FPToUI:
995 case Instruction::FPToSI:
996 case Instruction::FPExt:
997 case Instruction::PtrToInt:
998 case Instruction::PtrToAddr:
999 case Instruction::IntToPtr:
1000 case Instruction::SIToFP:
1001 case Instruction::UIToFP:
1002 case Instruction::Trunc:
1003 case Instruction::FPTrunc:
1004 case Instruction::AddrSpaceCast: {
1005 // Computes the CastContextHint from a recipe that may access memory.
1006 auto ComputeCCH = [&](const VPRecipeBase *R) -> TTI::CastContextHint {
1007 if (isa<VPInterleaveBase>(R))
1009 if (const auto *ReplicateRecipe = dyn_cast<VPReplicateRecipe>(R)) {
1010 // Only compute CCH for memory operations, matching the legacy model
1011 // which only considers loads/stores for cast context hints.
1012 auto *UI = cast<Instruction>(ReplicateRecipe->getUnderlyingValue());
1013 if (!isa<LoadInst, StoreInst>(UI))
1015 return ReplicateRecipe->isPredicated() ? TTI::CastContextHint::Masked
1017 }
1018 const auto *WidenMemoryRecipe = dyn_cast<VPWidenMemoryRecipe>(R);
1019 if (WidenMemoryRecipe == nullptr)
1021 if (VF.isScalar())
1023 if (!WidenMemoryRecipe->isConsecutive())
1025 if (WidenMemoryRecipe->isReverse())
1027 if (WidenMemoryRecipe->isMasked())
1030 };
1031
1032 VPValue *Operand = getOperand(0);
1034 // For Trunc/FPTrunc, get the context from the only user.
1035 if (Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) {
1036 auto GetOnlyUser = [](const VPSingleDefRecipe *R) -> VPRecipeBase * {
1037 if (R->getNumUsers() == 0 || R->hasMoreThanOneUniqueUser())
1038 return nullptr;
1039 return dyn_cast<VPRecipeBase>(*R->user_begin());
1040 };
1041 if (VPRecipeBase *Recipe = GetOnlyUser(this)) {
1042 if (match(Recipe, m_Reverse(m_VPValue())))
1043 Recipe = GetOnlyUser(cast<VPInstruction>(Recipe));
1044 if (Recipe)
1045 CCH = ComputeCCH(Recipe);
1046 }
1047 }
1048 // For Z/Sext, get the context from the operand.
1049 else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt ||
1050 Opcode == Instruction::FPExt) {
1051 if (auto *Recipe = Operand->getDefiningRecipe()) {
1052 VPValue *ReverseOp;
1053 if (match(Recipe, m_Reverse(m_VPValue(ReverseOp))))
1054 Recipe = ReverseOp->getDefiningRecipe();
1055 if (Recipe)
1056 CCH = ComputeCCH(Recipe);
1057 }
1058 }
1059
1060 auto *ScalarSrcTy = Ctx.Types.inferScalarType(Operand);
1061 Type *SrcTy = VF.isVector() ? toVectorTy(ScalarSrcTy, VF) : ScalarSrcTy;
1062 // Arm TTI will use the underlying instruction to determine the cost.
1063 return Ctx.TTI.getCastInstrCost(
1064 Opcode, ResultTy, SrcTy, CCH, Ctx.CostKind,
1066 }
1067 case Instruction::Select: {
1069 bool IsScalarCond = getOperand(0)->isDefinedOutsideLoopRegions();
1070 Type *ScalarTy = Ctx.Types.inferScalarType(this);
1071
1072 VPValue *Op0, *Op1;
1073 bool IsLogicalAnd =
1074 match(this, m_c_LogicalAnd(m_VPValue(Op0), m_VPValue(Op1)));
1075 bool IsLogicalOr =
1076 match(this, m_c_LogicalOr(m_VPValue(Op0), m_VPValue(Op1)));
1077 // Also match the inverted forms:
1078 // select x, false, y --> !x & y (still AND)
1079 // select x, y, true --> !x | y (still OR)
1080 IsLogicalAnd |=
1081 match(this, m_Select(m_VPValue(Op0), m_False(), m_VPValue(Op1)));
1082 IsLogicalOr |=
1083 match(this, m_Select(m_VPValue(Op0), m_VPValue(Op1), m_True()));
1084
1085 if (!IsScalarCond && ScalarTy->getScalarSizeInBits() == 1 &&
1086 (IsLogicalAnd || IsLogicalOr)) {
1087 // select x, y, false --> x & y
1088 // select x, true, y --> x | y
1089 const auto [Op1VK, Op1VP] = Ctx.getOperandInfo(Op0);
1090 const auto [Op2VK, Op2VP] = Ctx.getOperandInfo(Op1);
1091
1093 if (SI && all_of(operands(),
1094 [](VPValue *Op) { return Op->getUnderlyingValue(); }))
1095 append_range(Operands, SI->operands());
1096 return Ctx.TTI.getArithmeticInstrCost(
1097 IsLogicalOr ? Instruction::Or : Instruction::And, ResultTy,
1098 Ctx.CostKind, {Op1VK, Op1VP}, {Op2VK, Op2VP}, Operands, SI);
1099 }
1101 Type *CondTy = Ctx.Types.inferScalarType(getOperand(0));
1102 if (!IsScalarCond)
1103 CondTy = VectorType::get(CondTy, VF);
1104
1105 llvm::CmpPredicate Pred;
1106 if (!match(getOperand(0), m_Cmp(Pred, m_VPValue(), m_VPValue())))
1107 if (auto *CondIRV = dyn_cast<VPIRValue>(getOperand(0)))
1108 if (auto *Cmp = dyn_cast<CmpInst>(CondIRV->getValue()))
1109 Pred = Cmp->getPredicate();
1110 Type *VectorTy = toVectorTy(Ctx.Types.inferScalarType(this), VF);
1111 return Ctx.TTI.getCmpSelInstrCost(
1112 Instruction::Select, VectorTy, CondTy, Pred, Ctx.CostKind,
1113 {TTI::OK_AnyValue, TTI::OP_None}, {TTI::OK_AnyValue, TTI::OP_None}, SI);
1114 }
1115 }
1116 llvm_unreachable("called for unsupported opcode");
1117}
1118
1120 VPCostContext &Ctx) const {
1122 if (!getUnderlyingValue() && getOpcode() != Instruction::FMul) {
1123 // TODO: Compute cost for VPInstructions without underlying values once
1124 // the legacy cost model has been retired.
1125 return 0;
1126 }
1127
1129 "Should only generate a vector value or single scalar, not scalars "
1130 "for all lanes.");
1132 getOpcode(),
1134 }
1135
1136 switch (getOpcode()) {
1137 case Instruction::Select: {
1139 match(getOperand(0), m_Cmp(Pred, m_VPValue(), m_VPValue()));
1140 auto *CondTy = Ctx.Types.inferScalarType(getOperand(0));
1141 auto *VecTy = Ctx.Types.inferScalarType(getOperand(1));
1142 if (!vputils::onlyFirstLaneUsed(this)) {
1143 CondTy = toVectorTy(CondTy, VF);
1144 VecTy = toVectorTy(VecTy, VF);
1145 }
1146 return Ctx.TTI.getCmpSelInstrCost(Instruction::Select, VecTy, CondTy, Pred,
1147 Ctx.CostKind);
1148 }
1149 case Instruction::ExtractElement:
1151 if (VF.isScalar()) {
1152 // ExtractLane with VF=1 takes care of handling extracting across multiple
1153 // parts.
1154 return 0;
1155 }
1156
1157 // Add on the cost of extracting the element.
1158 auto *VecTy = toVectorTy(Ctx.Types.inferScalarType(getOperand(0)), VF);
1159 return Ctx.TTI.getVectorInstrCost(Instruction::ExtractElement, VecTy,
1160 Ctx.CostKind);
1161 }
1162 case VPInstruction::AnyOf: {
1163 auto *VecTy = toVectorTy(Ctx.Types.inferScalarType(this), VF);
1164 return Ctx.TTI.getArithmeticReductionCost(
1165 Instruction::Or, cast<VectorType>(VecTy), std::nullopt, Ctx.CostKind);
1166 }
1168 Type *ScalarTy = Ctx.Types.inferScalarType(getOperand(0));
1169 if (VF.isScalar())
1170 return Ctx.TTI.getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
1172 CmpInst::ICMP_EQ, Ctx.CostKind);
1173 // Calculate the cost of determining the lane index.
1174 auto *PredTy = toVectorTy(ScalarTy, VF);
1175 IntrinsicCostAttributes Attrs(Intrinsic::experimental_cttz_elts,
1176 Type::getInt64Ty(Ctx.LLVMCtx),
1177 {PredTy, Type::getInt1Ty(Ctx.LLVMCtx)});
1178 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1179 }
1181 Type *ScalarTy = Ctx.Types.inferScalarType(getOperand(0));
1182 if (VF.isScalar())
1183 return Ctx.TTI.getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
1185 CmpInst::ICMP_EQ, Ctx.CostKind);
1186 // Calculate the cost of determining the lane index: NOT + cttz_elts + SUB.
1187 auto *PredTy = toVectorTy(ScalarTy, VF);
1188 IntrinsicCostAttributes Attrs(Intrinsic::experimental_cttz_elts,
1189 Type::getInt64Ty(Ctx.LLVMCtx),
1190 {PredTy, Type::getInt1Ty(Ctx.LLVMCtx)});
1191 InstructionCost Cost = Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1192 // Add cost of NOT operation on the predicate.
1193 Cost += Ctx.TTI.getArithmeticInstrCost(
1194 Instruction::Xor, PredTy, Ctx.CostKind,
1195 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
1196 {TargetTransformInfo::OK_UniformConstantValue,
1197 TargetTransformInfo::OP_None});
1198 // Add cost of SUB operation on the index.
1199 Cost += Ctx.TTI.getArithmeticInstrCost(
1200 Instruction::Sub, Type::getInt64Ty(Ctx.LLVMCtx), Ctx.CostKind);
1201 return Cost;
1202 }
1204 Type *ScalarTy = Ctx.Types.inferScalarType(this);
1205 Type *VecTy = toVectorTy(ScalarTy, VF);
1206 Type *MaskTy = toVectorTy(Type::getInt1Ty(Ctx.LLVMCtx), VF);
1208 Intrinsic::experimental_vector_extract_last_active, ScalarTy,
1209 {VecTy, MaskTy, ScalarTy});
1210 return Ctx.TTI.getIntrinsicInstrCost(ICA, Ctx.CostKind);
1211 }
1213 assert(VF.isVector() && "Scalar FirstOrderRecurrenceSplice?");
1215 std::iota(Mask.begin(), Mask.end(), VF.getKnownMinValue() - 1);
1216 Type *VectorTy = toVectorTy(Ctx.Types.inferScalarType(this), VF);
1217
1218 return Ctx.TTI.getShuffleCost(TargetTransformInfo::SK_Splice,
1219 cast<VectorType>(VectorTy),
1220 cast<VectorType>(VectorTy), Mask,
1221 Ctx.CostKind, VF.getKnownMinValue() - 1);
1222 }
1224 Type *ArgTy = Ctx.Types.inferScalarType(getOperand(0));
1225 unsigned Multiplier = cast<VPConstantInt>(getOperand(2))->getZExtValue();
1226 Type *RetTy = toVectorTy(Type::getInt1Ty(Ctx.LLVMCtx), VF * Multiplier);
1227 IntrinsicCostAttributes Attrs(Intrinsic::get_active_lane_mask, RetTy,
1228 {ArgTy, ArgTy});
1229 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1230 }
1232 Type *Arg0Ty = Ctx.Types.inferScalarType(getOperand(0));
1233 Type *I32Ty = Type::getInt32Ty(Ctx.LLVMCtx);
1234 Type *I1Ty = Type::getInt1Ty(Ctx.LLVMCtx);
1235 IntrinsicCostAttributes Attrs(Intrinsic::experimental_get_vector_length,
1236 I32Ty, {Arg0Ty, I32Ty, I1Ty});
1237 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1238 }
1240 assert(VF.isVector() && "Reverse operation must be vector type");
1241 auto *VectorTy = cast<VectorType>(
1242 toVectorTy(Ctx.Types.inferScalarType(getOperand(0)), VF));
1243 return Ctx.TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy,
1244 VectorTy, /*Mask=*/{}, Ctx.CostKind,
1245 /*Index=*/0);
1246 }
1248 // Add on the cost of extracting the element.
1249 auto *VecTy = toVectorTy(Ctx.Types.inferScalarType(getOperand(0)), VF);
1250 return Ctx.TTI.getIndexedVectorInstrCostFromEnd(Instruction::ExtractElement,
1251 VecTy, Ctx.CostKind, 0);
1252 }
1254 if (VF == ElementCount::getScalable(1))
1256 [[fallthrough]];
1257 default:
1258 // TODO: Compute cost other VPInstructions once the legacy cost model has
1259 // been retired.
1261 "unexpected VPInstruction witht underlying value");
1262 return 0;
1263 }
1264}
1265
1278
1280 switch (getOpcode()) {
1281 case Instruction::Load:
1282 case Instruction::PHI:
1286 return true;
1287 default:
1288 return isScalarCast();
1289 }
1290}
1291
1293 assert(!isMasked() && "cannot execute masked VPInstruction");
1294 assert(!State.Lane && "VPInstruction executing an Lane");
1295 IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder);
1297 "Set flags not supported for the provided opcode");
1299 "Opcode requires specific flags to be set");
1300 if (hasFastMathFlags())
1301 State.Builder.setFastMathFlags(getFastMathFlags());
1302 Value *GeneratedValue = generate(State);
1303 if (!hasResult())
1304 return;
1305 assert(GeneratedValue && "generate must produce a value");
1306 bool GeneratesPerFirstLaneOnly = canGenerateScalarForFirstLane() &&
1309 assert((((GeneratedValue->getType()->isVectorTy() ||
1310 GeneratedValue->getType()->isStructTy()) ==
1311 !GeneratesPerFirstLaneOnly) ||
1312 State.VF.isScalar()) &&
1313 "scalar value but not only first lane defined");
1314 State.set(this, GeneratedValue,
1315 /*IsScalar*/ GeneratesPerFirstLaneOnly);
1316}
1317
1320 return false;
1321 switch (getOpcode()) {
1322 case Instruction::GetElementPtr:
1323 case Instruction::ExtractElement:
1324 case Instruction::Freeze:
1325 case Instruction::FCmp:
1326 case Instruction::ICmp:
1327 case Instruction::Select:
1328 case Instruction::PHI:
1352 case VPInstruction::Not:
1361 return false;
1362 default:
1363 return true;
1364 }
1365}
1366
1368 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
1370 return vputils::onlyFirstLaneUsed(this);
1371
1372 switch (getOpcode()) {
1373 default:
1374 return false;
1375 case Instruction::ExtractElement:
1376 return Op == getOperand(1);
1377 case Instruction::PHI:
1378 return true;
1379 case Instruction::FCmp:
1380 case Instruction::ICmp:
1381 case Instruction::Select:
1382 case Instruction::Or:
1383 case Instruction::Freeze:
1384 case VPInstruction::Not:
1385 // TODO: Cover additional opcodes.
1386 return vputils::onlyFirstLaneUsed(this);
1387 case Instruction::Load:
1396 return true;
1399 // Before replicating by VF, Build(Struct)Vector uses all lanes of the
1400 // operand, after replicating its operands only the first lane is used.
1401 // Before replicating, it will have only a single operand.
1402 return getNumOperands() > 1;
1404 return Op == getOperand(0) || vputils::onlyFirstLaneUsed(this);
1406 // WidePtrAdd supports scalar and vector base addresses.
1407 return false;
1409 return Op == getOperand(0) || Op == getOperand(1);
1412 return Op == getOperand(0);
1413 };
1414 llvm_unreachable("switch should return");
1415}
1416
1418 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
1420 return vputils::onlyFirstPartUsed(this);
1421
1422 switch (getOpcode()) {
1423 default:
1424 return false;
1425 case Instruction::FCmp:
1426 case Instruction::ICmp:
1427 case Instruction::Select:
1428 return vputils::onlyFirstPartUsed(this);
1433 return true;
1434 };
1435 llvm_unreachable("switch should return");
1436}
1437
1438#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1440 VPSlotTracker SlotTracker(getParent()->getPlan());
1442}
1443
1445 VPSlotTracker &SlotTracker) const {
1446 O << Indent << "EMIT" << (isSingleScalar() ? "-SCALAR" : "") << " ";
1447
1448 if (hasResult()) {
1450 O << " = ";
1451 }
1452
1453 switch (getOpcode()) {
1454 case VPInstruction::Not:
1455 O << "not";
1456 break;
1458 O << "combined load";
1459 break;
1461 O << "combined store";
1462 break;
1464 O << "active lane mask";
1465 break;
1467 O << "EXPLICIT-VECTOR-LENGTH";
1468 break;
1470 O << "first-order splice";
1471 break;
1473 O << "branch-on-cond";
1474 break;
1476 O << "branch-on-two-conds";
1477 break;
1479 O << "TC > VF ? TC - VF : 0";
1480 break;
1482 O << "VF * Part +";
1483 break;
1485 O << "branch-on-count";
1486 break;
1488 O << "broadcast";
1489 break;
1491 O << "buildstructvector";
1492 break;
1494 O << "buildvector";
1495 break;
1497 O << "exiting-iv-value";
1498 break;
1500 O << "masked-cond";
1501 break;
1503 O << "extract-lane";
1504 break;
1506 O << "extract-last-lane";
1507 break;
1509 O << "extract-last-part";
1510 break;
1512 O << "extract-penultimate-element";
1513 break;
1515 O << "compute-anyof-result";
1516 break;
1518 O << "compute-reduction-result";
1519 break;
1521 O << "logical-and";
1522 break;
1524 O << "logical-or";
1525 break;
1527 O << "ptradd";
1528 break;
1530 O << "wide-ptradd";
1531 break;
1533 O << "any-of";
1534 break;
1536 O << "first-active-lane";
1537 break;
1539 O << "last-active-lane";
1540 break;
1542 O << "reduction-start-vector";
1543 break;
1545 O << "resume-for-epilogue";
1546 break;
1548 O << "reverse";
1549 break;
1551 O << "unpack";
1552 break;
1554 O << "extract-last-active";
1555 break;
1556 default:
1558 }
1559
1560 printFlags(O);
1562}
1563#endif
1564
1566 State.setDebugLocFrom(getDebugLoc());
1567 if (isScalarCast()) {
1568 Value *Op = State.get(getOperand(0), VPLane(0));
1569 Value *Cast = State.Builder.CreateCast(Instruction::CastOps(getOpcode()),
1570 Op, ResultTy);
1571 State.set(this, Cast, VPLane(0));
1572 return;
1573 }
1574 switch (getOpcode()) {
1576 Value *StepVector =
1577 State.Builder.CreateStepVector(VectorType::get(ResultTy, State.VF));
1578 State.set(this, StepVector);
1579 break;
1580 }
1581 case VPInstruction::VScale: {
1582 Value *VScale = State.Builder.CreateVScale(ResultTy);
1583 State.set(this, VScale, true);
1584 break;
1585 }
1586
1587 default:
1588 llvm_unreachable("opcode not implemented yet");
1589 }
1590}
1591
1592#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1594 VPSlotTracker &SlotTracker) const {
1595 O << Indent << "EMIT" << (isSingleScalar() ? "-SCALAR" : "") << " ";
1597 O << " = ";
1598
1599 switch (getOpcode()) {
1601 O << "wide-iv-step ";
1603 break;
1605 O << "step-vector " << *ResultTy;
1606 break;
1608 O << "vscale " << *ResultTy;
1609 break;
1610 case Instruction::Load:
1611 O << "load ";
1613 break;
1614 default:
1615 assert(Instruction::isCast(getOpcode()) && "unhandled opcode");
1618 O << " to " << *ResultTy;
1619 }
1620}
1621#endif
1622
1624 State.setDebugLocFrom(getDebugLoc());
1625 PHINode *NewPhi = State.Builder.CreatePHI(
1626 State.TypeAnalysis.inferScalarType(this), 2, getName());
1627 unsigned NumIncoming = getNumIncoming();
1628 if (getParent() != getParent()->getPlan()->getScalarPreheader()) {
1629 // TODO: Fixup all incoming values of header phis once recipes defining them
1630 // are introduced.
1631 NumIncoming = 1;
1632 }
1633 for (unsigned Idx = 0; Idx != NumIncoming; ++Idx) {
1634 Value *IncV = State.get(getIncomingValue(Idx), VPLane(0));
1635 BasicBlock *PredBB = State.CFG.VPBB2IRBB.at(getIncomingBlock(Idx));
1636 NewPhi->addIncoming(IncV, PredBB);
1637 }
1638 State.set(this, NewPhi, VPLane(0));
1639}
1640
1641#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1642void VPPhi::printRecipe(raw_ostream &O, const Twine &Indent,
1643 VPSlotTracker &SlotTracker) const {
1644 O << Indent << "EMIT" << (isSingleScalar() ? "-SCALAR" : "") << " ";
1646 O << " = phi";
1647 printFlags(O);
1649}
1650#endif
1651
1652VPIRInstruction *VPIRInstruction ::create(Instruction &I) {
1653 if (auto *Phi = dyn_cast<PHINode>(&I))
1654 return new VPIRPhi(*Phi);
1655 return new VPIRInstruction(I);
1656}
1657
1659 assert(!isa<VPIRPhi>(this) && getNumOperands() == 0 &&
1660 "PHINodes must be handled by VPIRPhi");
1661 // Advance the insert point after the wrapped IR instruction. This allows
1662 // interleaving VPIRInstructions and other recipes.
1663 State.Builder.SetInsertPoint(I.getParent(), std::next(I.getIterator()));
1664}
1665
1667 VPCostContext &Ctx) const {
1668 // The recipe wraps an existing IR instruction on the border of VPlan's scope,
1669 // hence it does not contribute to the cost-modeling for the VPlan.
1670 return 0;
1671}
1672
1673#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1675 VPSlotTracker &SlotTracker) const {
1676 O << Indent << "IR " << I;
1677}
1678#endif
1679
1681 PHINode *Phi = &getIRPhi();
1682 for (const auto &[Idx, Op] : enumerate(operands())) {
1683 VPValue *ExitValue = Op;
1684 auto Lane = vputils::isSingleScalar(ExitValue)
1686 : VPLane::getLastLaneForVF(State.VF);
1687 VPBlockBase *Pred = getParent()->getPredecessors()[Idx];
1688 auto *PredVPBB = Pred->getExitingBasicBlock();
1689 BasicBlock *PredBB = State.CFG.VPBB2IRBB[PredVPBB];
1690 // Set insertion point in PredBB in case an extract needs to be generated.
1691 // TODO: Model extracts explicitly.
1692 State.Builder.SetInsertPoint(PredBB->getTerminator());
1693 Value *V = State.get(ExitValue, VPLane(Lane));
1694 // If there is no existing block for PredBB in the phi, add a new incoming
1695 // value. Otherwise update the existing incoming value for PredBB.
1696 if (Phi->getBasicBlockIndex(PredBB) == -1)
1697 Phi->addIncoming(V, PredBB);
1698 else
1699 Phi->setIncomingValueForBlock(PredBB, V);
1700 }
1701
1702 // Advance the insert point after the wrapped IR instruction. This allows
1703 // interleaving VPIRInstructions and other recipes.
1704 State.Builder.SetInsertPoint(Phi->getParent(), std::next(Phi->getIterator()));
1705}
1706
1708 VPRecipeBase *R = const_cast<VPRecipeBase *>(getAsRecipe());
1709 assert(R->getNumOperands() == R->getParent()->getNumPredecessors() &&
1710 "Number of phi operands must match number of predecessors");
1711 unsigned Position = R->getParent()->getIndexForPredecessor(IncomingBlock);
1712 R->removeOperand(Position);
1713}
1714
1715VPValue *
1717 VPRecipeBase *R = const_cast<VPRecipeBase *>(getAsRecipe());
1718 return getIncomingValue(R->getParent()->getIndexForPredecessor(VPBB));
1719}
1720
1722 VPValue *V) const {
1723 VPRecipeBase *R = const_cast<VPRecipeBase *>(getAsRecipe());
1724 R->setOperand(R->getParent()->getIndexForPredecessor(VPBB), V);
1725}
1726
1727#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1729 VPSlotTracker &SlotTracker) const {
1730 interleaveComma(enumerate(getAsRecipe()->operands()), O,
1731 [this, &O, &SlotTracker](auto Op) {
1732 O << "[ ";
1733 Op.value()->printAsOperand(O, SlotTracker);
1734 O << ", ";
1735 getIncomingBlock(Op.index())->printAsOperand(O);
1736 O << " ]";
1737 });
1738}
1739#endif
1740
1741#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1743 VPSlotTracker &SlotTracker) const {
1745
1746 if (getNumOperands() != 0) {
1747 O << " (extra operand" << (getNumOperands() > 1 ? "s" : "") << ": ";
1749 [&O, &SlotTracker](auto Op) {
1750 std::get<0>(Op)->printAsOperand(O, SlotTracker);
1751 O << " from ";
1752 std::get<1>(Op)->printAsOperand(O);
1753 });
1754 O << ")";
1755 }
1756}
1757#endif
1758
1760 for (const auto &[Kind, Node] : Metadata)
1761 I.setMetadata(Kind, Node);
1762}
1763
1765 SmallVector<std::pair<unsigned, MDNode *>> MetadataIntersection;
1766 for (const auto &[KindA, MDA] : Metadata) {
1767 for (const auto &[KindB, MDB] : Other.Metadata) {
1768 if (KindA == KindB && MDA == MDB) {
1769 MetadataIntersection.emplace_back(KindA, MDA);
1770 break;
1771 }
1772 }
1773 }
1774 Metadata = std::move(MetadataIntersection);
1775}
1776
1777#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1779 const Module *M = SlotTracker.getModule();
1780 if (Metadata.empty() || !M)
1781 return;
1782
1783 ArrayRef<StringRef> MDNames = SlotTracker.getMDNames();
1784 O << " (";
1785 interleaveComma(Metadata, O, [&](const auto &KindNodePair) {
1786 auto [Kind, Node] = KindNodePair;
1787 assert(Kind < MDNames.size() && !MDNames[Kind].empty() &&
1788 "Unexpected unnamed metadata kind");
1789 O << "!" << MDNames[Kind] << " ";
1790 Node->printAsOperand(O, M);
1791 });
1792 O << ")";
1793}
1794#endif
1795
1797 assert(State.VF.isVector() && "not widening");
1798 assert(Variant != nullptr && "Can't create vector function.");
1799
1800 FunctionType *VFTy = Variant->getFunctionType();
1801 // Add return type if intrinsic is overloaded on it.
1803 for (const auto &I : enumerate(args())) {
1804 Value *Arg;
1805 // Some vectorized function variants may also take a scalar argument,
1806 // e.g. linear parameters for pointers. This needs to be the scalar value
1807 // from the start of the respective part when interleaving.
1808 if (!VFTy->getParamType(I.index())->isVectorTy())
1809 Arg = State.get(I.value(), VPLane(0));
1810 else
1811 Arg = State.get(I.value(), usesFirstLaneOnly(I.value()));
1812 Args.push_back(Arg);
1813 }
1814
1817 if (CI)
1818 CI->getOperandBundlesAsDefs(OpBundles);
1819
1820 CallInst *V = State.Builder.CreateCall(Variant, Args, OpBundles);
1821 applyFlags(*V);
1822 applyMetadata(*V);
1823 V->setCallingConv(Variant->getCallingConv());
1824
1825 if (!V->getType()->isVoidTy())
1826 State.set(this, V);
1827}
1828
1830 VPCostContext &Ctx) const {
1831 return Ctx.TTI.getCallInstrCost(nullptr, Variant->getReturnType(),
1832 Variant->getFunctionType()->params(),
1833 Ctx.CostKind);
1834}
1835
1836#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1838 VPSlotTracker &SlotTracker) const {
1839 O << Indent << "WIDEN-CALL ";
1840
1841 Function *CalledFn = getCalledScalarFunction();
1842 if (CalledFn->getReturnType()->isVoidTy())
1843 O << "void ";
1844 else {
1846 O << " = ";
1847 }
1848
1849 O << "call";
1850 printFlags(O);
1851 O << " @" << CalledFn->getName() << "(";
1852 interleaveComma(args(), O, [&O, &SlotTracker](VPValue *Op) {
1853 Op->printAsOperand(O, SlotTracker);
1854 });
1855 O << ")";
1856
1857 O << " (using library function";
1858 if (Variant->hasName())
1859 O << ": " << Variant->getName();
1860 O << ")";
1861}
1862#endif
1863
1865 assert(State.VF.isVector() && "not widening");
1866
1867 SmallVector<Type *, 2> TysForDecl;
1868 // Add return type if intrinsic is overloaded on it.
1869 if (isVectorIntrinsicWithOverloadTypeAtArg(VectorIntrinsicID, -1,
1870 State.TTI)) {
1871 Type *RetTy = toVectorizedTy(getResultType(), State.VF);
1872 ArrayRef<Type *> ContainedTys = getContainedTypes(RetTy);
1873 for (auto [Idx, Ty] : enumerate(ContainedTys)) {
1875 Idx, State.TTI))
1876 TysForDecl.push_back(Ty);
1877 }
1878 }
1880 for (const auto &I : enumerate(operands())) {
1881 // Some intrinsics have a scalar argument - don't replace it with a
1882 // vector.
1883 Value *Arg;
1884 if (isVectorIntrinsicWithScalarOpAtArg(VectorIntrinsicID, I.index(),
1885 State.TTI))
1886 Arg = State.get(I.value(), VPLane(0));
1887 else
1888 Arg = State.get(I.value(), usesFirstLaneOnly(I.value()));
1889 if (isVectorIntrinsicWithOverloadTypeAtArg(VectorIntrinsicID, I.index(),
1890 State.TTI))
1891 TysForDecl.push_back(Arg->getType());
1892 Args.push_back(Arg);
1893 }
1894
1895 // Use vector version of the intrinsic.
1896 Module *M = State.Builder.GetInsertBlock()->getModule();
1897 Function *VectorF =
1898 Intrinsic::getOrInsertDeclaration(M, VectorIntrinsicID, TysForDecl);
1899 assert(VectorF &&
1900 "Can't retrieve vector intrinsic or vector-predication intrinsics.");
1901
1904 if (CI)
1905 CI->getOperandBundlesAsDefs(OpBundles);
1906
1907 CallInst *V = State.Builder.CreateCall(VectorF, Args, OpBundles);
1908
1909 applyFlags(*V);
1910 applyMetadata(*V);
1911
1912 if (!V->getType()->isVoidTy())
1913 State.set(this, V);
1914}
1915
1916/// Compute the cost for the intrinsic \p ID with \p Operands, produced by \p R.
1919 const VPRecipeWithIRFlags &R,
1920 ElementCount VF,
1921 VPCostContext &Ctx) {
1922 // Some backends analyze intrinsic arguments to determine cost. Use the
1923 // underlying value for the operand if it has one. Otherwise try to use the
1924 // operand of the underlying call instruction, if there is one. Otherwise
1925 // clear Arguments.
1926 // TODO: Rework TTI interface to be independent of concrete IR values.
1928 for (const auto &[Idx, Op] : enumerate(Operands)) {
1929 auto *V = Op->getUnderlyingValue();
1930 if (!V) {
1931 if (auto *UI = dyn_cast_or_null<CallBase>(R.getUnderlyingValue())) {
1932 Arguments.push_back(UI->getArgOperand(Idx));
1933 continue;
1934 }
1935 Arguments.clear();
1936 break;
1937 }
1938 Arguments.push_back(V);
1939 }
1940
1941 Type *ScalarRetTy = Ctx.Types.inferScalarType(&R);
1942 Type *RetTy = VF.isVector() ? toVectorizedTy(ScalarRetTy, VF) : ScalarRetTy;
1943 SmallVector<Type *> ParamTys;
1944 for (const VPValue *Op : Operands) {
1945 ParamTys.push_back(VF.isVector()
1946 ? toVectorTy(Ctx.Types.inferScalarType(Op), VF)
1947 : Ctx.Types.inferScalarType(Op));
1948 }
1949
1950 // TODO: Rework TTI interface to avoid reliance on underlying IntrinsicInst.
1951 IntrinsicCostAttributes CostAttrs(
1952 ID, RetTy, Arguments, ParamTys, R.getFastMathFlags(),
1953 dyn_cast_or_null<IntrinsicInst>(R.getUnderlyingValue()),
1955 return Ctx.TTI.getIntrinsicInstrCost(CostAttrs, Ctx.CostKind);
1956}
1957
1959 VPCostContext &Ctx) const {
1961 return getCostForIntrinsics(VectorIntrinsicID, ArgOps, *this, VF, Ctx);
1962}
1963
1965 return Intrinsic::getBaseName(VectorIntrinsicID);
1966}
1967
1969 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
1970 return all_of(enumerate(operands()), [this, &Op](const auto &X) {
1971 auto [Idx, V] = X;
1973 Idx, nullptr);
1974 });
1975}
1976
1977#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1979 VPSlotTracker &SlotTracker) const {
1980 O << Indent << "WIDEN-INTRINSIC ";
1981 if (ResultTy->isVoidTy()) {
1982 O << "void ";
1983 } else {
1985 O << " = ";
1986 }
1987
1988 O << "call";
1989 printFlags(O);
1990 O << getIntrinsicName() << "(";
1991
1993 Op->printAsOperand(O, SlotTracker);
1994 });
1995 O << ")";
1996}
1997#endif
1998
2000 IRBuilderBase &Builder = State.Builder;
2001
2002 Value *Address = State.get(getOperand(0));
2003 Value *IncAmt = State.get(getOperand(1), /*IsScalar=*/true);
2004 VectorType *VTy = cast<VectorType>(Address->getType());
2005
2006 // The histogram intrinsic requires a mask even if the recipe doesn't;
2007 // if the mask operand was omitted then all lanes should be executed and
2008 // we just need to synthesize an all-true mask.
2009 Value *Mask = nullptr;
2010 if (VPValue *VPMask = getMask())
2011 Mask = State.get(VPMask);
2012 else
2013 Mask =
2014 Builder.CreateVectorSplat(VTy->getElementCount(), Builder.getInt1(1));
2015
2016 // If this is a subtract, we want to invert the increment amount. We may
2017 // add a separate intrinsic in future, but for now we'll try this.
2018 if (Opcode == Instruction::Sub)
2019 IncAmt = Builder.CreateNeg(IncAmt);
2020 else
2021 assert(Opcode == Instruction::Add && "only add or sub supported for now");
2022
2023 State.Builder.CreateIntrinsic(Intrinsic::experimental_vector_histogram_add,
2024 {VTy, IncAmt->getType()},
2025 {Address, IncAmt, Mask});
2026}
2027
2029 VPCostContext &Ctx) const {
2030 // FIXME: Take the gather and scatter into account as well. For now we're
2031 // generating the same cost as the fallback path, but we'll likely
2032 // need to create a new TTI method for determining the cost, including
2033 // whether we can use base + vec-of-smaller-indices or just
2034 // vec-of-pointers.
2035 assert(VF.isVector() && "Invalid VF for histogram cost");
2036 Type *AddressTy = Ctx.Types.inferScalarType(getOperand(0));
2037 VPValue *IncAmt = getOperand(1);
2038 Type *IncTy = Ctx.Types.inferScalarType(IncAmt);
2039 VectorType *VTy = VectorType::get(IncTy, VF);
2040
2041 // Assume that a non-constant update value (or a constant != 1) requires
2042 // a multiply, and add that into the cost.
2043 InstructionCost MulCost =
2044 Ctx.TTI.getArithmeticInstrCost(Instruction::Mul, VTy, Ctx.CostKind);
2045 if (auto *CI = dyn_cast<VPConstantInt>(IncAmt))
2046 if (CI->isOne())
2047 MulCost = TTI::TCC_Free;
2048
2049 // Find the cost of the histogram operation itself.
2050 Type *PtrTy = VectorType::get(AddressTy, VF);
2051 Type *MaskTy = VectorType::get(Type::getInt1Ty(Ctx.LLVMCtx), VF);
2052 IntrinsicCostAttributes ICA(Intrinsic::experimental_vector_histogram_add,
2053 Type::getVoidTy(Ctx.LLVMCtx),
2054 {PtrTy, IncTy, MaskTy});
2055
2056 // Add the costs together with the add/sub operation.
2057 return Ctx.TTI.getIntrinsicInstrCost(ICA, Ctx.CostKind) + MulCost +
2058 Ctx.TTI.getArithmeticInstrCost(Opcode, VTy, Ctx.CostKind);
2059}
2060
2061#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2063 VPSlotTracker &SlotTracker) const {
2064 O << Indent << "WIDEN-HISTOGRAM buckets: ";
2066
2067 if (Opcode == Instruction::Sub)
2068 O << ", dec: ";
2069 else {
2070 assert(Opcode == Instruction::Add);
2071 O << ", inc: ";
2072 }
2074
2075 if (VPValue *Mask = getMask()) {
2076 O << ", mask: ";
2077 Mask->printAsOperand(O, SlotTracker);
2078 }
2079}
2080#endif
2081
2082VPIRFlags::FastMathFlagsTy::FastMathFlagsTy(const FastMathFlags &FMF) {
2083 AllowReassoc = FMF.allowReassoc();
2084 NoNaNs = FMF.noNaNs();
2085 NoInfs = FMF.noInfs();
2086 NoSignedZeros = FMF.noSignedZeros();
2087 AllowReciprocal = FMF.allowReciprocal();
2088 AllowContract = FMF.allowContract();
2089 ApproxFunc = FMF.approxFunc();
2090}
2091
2093 switch (Opcode) {
2094 case Instruction::Add:
2095 case Instruction::Sub:
2096 case Instruction::Mul:
2097 case Instruction::Shl:
2099 return WrapFlagsTy(false, false);
2100 case Instruction::Trunc:
2101 return TruncFlagsTy(false, false);
2102 case Instruction::Or:
2103 return DisjointFlagsTy(false);
2104 case Instruction::AShr:
2105 case Instruction::LShr:
2106 case Instruction::UDiv:
2107 case Instruction::SDiv:
2108 return ExactFlagsTy(false);
2109 case Instruction::GetElementPtr:
2112 return GEPNoWrapFlags::none();
2113 case Instruction::ZExt:
2114 case Instruction::UIToFP:
2115 return NonNegFlagsTy(false);
2116 case Instruction::FAdd:
2117 case Instruction::FSub:
2118 case Instruction::FMul:
2119 case Instruction::FDiv:
2120 case Instruction::FRem:
2121 case Instruction::FNeg:
2122 case Instruction::FPExt:
2123 case Instruction::FPTrunc:
2124 return FastMathFlags();
2125 case Instruction::ICmp:
2126 case Instruction::FCmp:
2128 llvm_unreachable("opcode requires explicit flags");
2129 default:
2130 return VPIRFlags();
2131 }
2132}
2133
2134#if !defined(NDEBUG)
2135bool VPIRFlags::flagsValidForOpcode(unsigned Opcode) const {
2136 switch (OpType) {
2137 case OperationType::OverflowingBinOp:
2138 return Opcode == Instruction::Add || Opcode == Instruction::Sub ||
2139 Opcode == Instruction::Mul || Opcode == Instruction::Shl ||
2140 Opcode == VPInstruction::VPInstruction::CanonicalIVIncrementForPart;
2141 case OperationType::Trunc:
2142 return Opcode == Instruction::Trunc;
2143 case OperationType::DisjointOp:
2144 return Opcode == Instruction::Or;
2145 case OperationType::PossiblyExactOp:
2146 return Opcode == Instruction::AShr || Opcode == Instruction::LShr ||
2147 Opcode == Instruction::UDiv || Opcode == Instruction::SDiv;
2148 case OperationType::GEPOp:
2149 return Opcode == Instruction::GetElementPtr ||
2150 Opcode == VPInstruction::PtrAdd ||
2151 Opcode == VPInstruction::WidePtrAdd;
2152 case OperationType::FPMathOp:
2153 return Opcode == Instruction::Call || Opcode == Instruction::FAdd ||
2154 Opcode == Instruction::FMul || Opcode == Instruction::FSub ||
2155 Opcode == Instruction::FNeg || Opcode == Instruction::FDiv ||
2156 Opcode == Instruction::FRem || Opcode == Instruction::FPExt ||
2157 Opcode == Instruction::FPTrunc || Opcode == Instruction::PHI ||
2158 Opcode == Instruction::Select ||
2159 Opcode == VPInstruction::WideIVStep ||
2161 case OperationType::FCmp:
2162 return Opcode == Instruction::FCmp;
2163 case OperationType::NonNegOp:
2164 return Opcode == Instruction::ZExt || Opcode == Instruction::UIToFP;
2165 case OperationType::Cmp:
2166 return Opcode == Instruction::FCmp || Opcode == Instruction::ICmp;
2167 case OperationType::ReductionOp:
2169 case OperationType::Other:
2170 return true;
2171 }
2172 llvm_unreachable("Unknown OperationType enum");
2173}
2174
2175bool VPIRFlags::hasRequiredFlagsForOpcode(unsigned Opcode) const {
2176 // Handle opcodes without default flags.
2177 if (Opcode == Instruction::ICmp)
2178 return OpType == OperationType::Cmp;
2179 if (Opcode == Instruction::FCmp)
2180 return OpType == OperationType::FCmp;
2182 return OpType == OperationType::ReductionOp;
2183
2184 OperationType Required = getDefaultFlags(Opcode).OpType;
2185 return Required == OperationType::Other || Required == OpType;
2186}
2187#endif
2188
2189#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2191 switch (OpType) {
2192 case OperationType::Cmp:
2194 break;
2195 case OperationType::FCmp:
2198 break;
2199 case OperationType::DisjointOp:
2200 if (DisjointFlags.IsDisjoint)
2201 O << " disjoint";
2202 break;
2203 case OperationType::PossiblyExactOp:
2204 if (ExactFlags.IsExact)
2205 O << " exact";
2206 break;
2207 case OperationType::OverflowingBinOp:
2208 if (WrapFlags.HasNUW)
2209 O << " nuw";
2210 if (WrapFlags.HasNSW)
2211 O << " nsw";
2212 break;
2213 case OperationType::Trunc:
2214 if (TruncFlags.HasNUW)
2215 O << " nuw";
2216 if (TruncFlags.HasNSW)
2217 O << " nsw";
2218 break;
2219 case OperationType::FPMathOp:
2221 break;
2222 case OperationType::GEPOp:
2223 if (GEPFlags.isInBounds())
2224 O << " inbounds";
2225 else if (GEPFlags.hasNoUnsignedSignedWrap())
2226 O << " nusw";
2227 if (GEPFlags.hasNoUnsignedWrap())
2228 O << " nuw";
2229 break;
2230 case OperationType::NonNegOp:
2231 if (NonNegFlags.NonNeg)
2232 O << " nneg";
2233 break;
2234 case OperationType::ReductionOp: {
2235 RecurKind RK = getRecurKind();
2236 O << " (";
2237 switch (RK) {
2238 case RecurKind::AnyOf:
2239 O << "any-of";
2240 break;
2241 case RecurKind::SMax:
2242 O << "smax";
2243 break;
2244 case RecurKind::SMin:
2245 O << "smin";
2246 break;
2247 case RecurKind::UMax:
2248 O << "umax";
2249 break;
2250 case RecurKind::UMin:
2251 O << "umin";
2252 break;
2253 case RecurKind::FMinNum:
2254 O << "fminnum";
2255 break;
2256 case RecurKind::FMaxNum:
2257 O << "fmaxnum";
2258 break;
2260 O << "fminimum";
2261 break;
2263 O << "fmaximum";
2264 break;
2266 O << "fminimumnum";
2267 break;
2269 O << "fmaximumnum";
2270 break;
2271 default:
2273 break;
2274 }
2275 if (isReductionInLoop())
2276 O << ", in-loop";
2277 if (isReductionOrdered())
2278 O << ", ordered";
2279 O << ")";
2281 break;
2282 }
2283 case OperationType::Other:
2284 break;
2285 }
2286 O << " ";
2287}
2288#endif
2289
2291 auto &Builder = State.Builder;
2292 switch (Opcode) {
2293 case Instruction::Call:
2294 case Instruction::Br:
2295 case Instruction::PHI:
2296 case Instruction::GetElementPtr:
2297 llvm_unreachable("This instruction is handled by a different recipe.");
2298 case Instruction::UDiv:
2299 case Instruction::SDiv:
2300 case Instruction::SRem:
2301 case Instruction::URem:
2302 case Instruction::Add:
2303 case Instruction::FAdd:
2304 case Instruction::Sub:
2305 case Instruction::FSub:
2306 case Instruction::FNeg:
2307 case Instruction::Mul:
2308 case Instruction::FMul:
2309 case Instruction::FDiv:
2310 case Instruction::FRem:
2311 case Instruction::Shl:
2312 case Instruction::LShr:
2313 case Instruction::AShr:
2314 case Instruction::And:
2315 case Instruction::Or:
2316 case Instruction::Xor: {
2317 // Just widen unops and binops.
2319 for (VPValue *VPOp : operands())
2320 Ops.push_back(State.get(VPOp));
2321
2322 Value *V = Builder.CreateNAryOp(Opcode, Ops);
2323
2324 if (auto *VecOp = dyn_cast<Instruction>(V)) {
2325 applyFlags(*VecOp);
2326 applyMetadata(*VecOp);
2327 }
2328
2329 // Use this vector value for all users of the original instruction.
2330 State.set(this, V);
2331 break;
2332 }
2333 case Instruction::ExtractValue: {
2334 assert(getNumOperands() == 2 && "expected single level extractvalue");
2335 Value *Op = State.get(getOperand(0));
2336 Value *Extract = Builder.CreateExtractValue(
2337 Op, cast<VPConstantInt>(getOperand(1))->getZExtValue());
2338 State.set(this, Extract);
2339 break;
2340 }
2341 case Instruction::Freeze: {
2342 Value *Op = State.get(getOperand(0));
2343 Value *Freeze = Builder.CreateFreeze(Op);
2344 State.set(this, Freeze);
2345 break;
2346 }
2347 case Instruction::ICmp:
2348 case Instruction::FCmp: {
2349 // Widen compares. Generate vector compares.
2350 bool FCmp = Opcode == Instruction::FCmp;
2351 Value *A = State.get(getOperand(0));
2352 Value *B = State.get(getOperand(1));
2353 Value *C = nullptr;
2354 if (FCmp) {
2355 C = Builder.CreateFCmp(getPredicate(), A, B);
2356 } else {
2357 C = Builder.CreateICmp(getPredicate(), A, B);
2358 }
2359 if (auto *I = dyn_cast<Instruction>(C)) {
2360 applyFlags(*I);
2361 applyMetadata(*I);
2362 }
2363 State.set(this, C);
2364 break;
2365 }
2366 case Instruction::Select: {
2367 VPValue *CondOp = getOperand(0);
2368 Value *Cond = State.get(CondOp, vputils::isSingleScalar(CondOp));
2369 Value *Op0 = State.get(getOperand(1));
2370 Value *Op1 = State.get(getOperand(2));
2371 Value *Sel = State.Builder.CreateSelect(Cond, Op0, Op1);
2372 State.set(this, Sel);
2373 if (auto *I = dyn_cast<Instruction>(Sel)) {
2375 applyFlags(*I);
2376 applyMetadata(*I);
2377 }
2378 break;
2379 }
2380 default:
2381 // This instruction is not vectorized by simple widening.
2382 LLVM_DEBUG(dbgs() << "LV: Found an unhandled opcode : "
2383 << Instruction::getOpcodeName(Opcode));
2384 llvm_unreachable("Unhandled instruction!");
2385 } // end of switch.
2386
2387#if !defined(NDEBUG)
2388 // Verify that VPlan type inference results agree with the type of the
2389 // generated values.
2390 assert(VectorType::get(State.TypeAnalysis.inferScalarType(this), State.VF) ==
2391 State.get(this)->getType() &&
2392 "inferred type and type from generated instructions do not match");
2393#endif
2394}
2395
2397 VPCostContext &Ctx) const {
2398 switch (Opcode) {
2399 case Instruction::UDiv:
2400 case Instruction::SDiv:
2401 case Instruction::SRem:
2402 case Instruction::URem:
2403 // If the div/rem operation isn't safe to speculate and requires
2404 // predication, then the only way we can even create a vplan is to insert
2405 // a select on the second input operand to ensure we use the value of 1
2406 // for the inactive lanes. The select will be costed separately.
2407 case Instruction::FNeg:
2408 case Instruction::Add:
2409 case Instruction::FAdd:
2410 case Instruction::Sub:
2411 case Instruction::FSub:
2412 case Instruction::Mul:
2413 case Instruction::FMul:
2414 case Instruction::FDiv:
2415 case Instruction::FRem:
2416 case Instruction::Shl:
2417 case Instruction::LShr:
2418 case Instruction::AShr:
2419 case Instruction::And:
2420 case Instruction::Or:
2421 case Instruction::Xor:
2422 case Instruction::Freeze:
2423 case Instruction::ExtractValue:
2424 case Instruction::ICmp:
2425 case Instruction::FCmp:
2426 case Instruction::Select:
2427 return getCostForRecipeWithOpcode(getOpcode(), VF, Ctx);
2428 default:
2429 llvm_unreachable("Unsupported opcode for instruction");
2430 }
2431}
2432
2433#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2435 VPSlotTracker &SlotTracker) const {
2436 O << Indent << "WIDEN ";
2438 O << " = " << Instruction::getOpcodeName(Opcode);
2439 printFlags(O);
2441}
2442#endif
2443
2445 auto &Builder = State.Builder;
2446 /// Vectorize casts.
2447 assert(State.VF.isVector() && "Not vectorizing?");
2448 Type *DestTy = VectorType::get(getResultType(), State.VF);
2449 VPValue *Op = getOperand(0);
2450 Value *A = State.get(Op);
2451 Value *Cast = Builder.CreateCast(Instruction::CastOps(Opcode), A, DestTy);
2452 State.set(this, Cast);
2453 if (auto *CastOp = dyn_cast<Instruction>(Cast)) {
2454 applyFlags(*CastOp);
2455 applyMetadata(*CastOp);
2456 }
2457}
2458
2460 VPCostContext &Ctx) const {
2461 // TODO: In some cases, VPWidenCastRecipes are created but not considered in
2462 // the legacy cost model, including truncates/extends when evaluating a
2463 // reduction in a smaller type.
2464 if (!getUnderlyingValue())
2465 return 0;
2466 return getCostForRecipeWithOpcode(getOpcode(), VF, Ctx);
2467}
2468
2469#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2471 VPSlotTracker &SlotTracker) const {
2472 O << Indent << "WIDEN-CAST ";
2474 O << " = " << Instruction::getOpcodeName(Opcode);
2475 printFlags(O);
2477 O << " to " << *getResultType();
2478}
2479#endif
2480
2482 VPCostContext &Ctx) const {
2483 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
2484}
2485
2486#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2488 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
2489 O << Indent;
2491 O << " = WIDEN-INDUCTION";
2492 printFlags(O);
2494
2495 if (auto *TI = getTruncInst())
2496 O << " (truncated to " << *TI->getType() << ")";
2497}
2498#endif
2499
2501 // The step may be defined by a recipe in the preheader (e.g. if it requires
2502 // SCEV expansion), but for the canonical induction the step is required to be
2503 // 1, which is represented as live-in.
2504 auto *StepC = dyn_cast<VPConstantInt>(getStepValue());
2505 auto *StartC = dyn_cast<VPConstantInt>(getStartValue());
2506 return StartC && StartC->isZero() && StepC && StepC->isOne() &&
2507 getScalarType() == getRegion()->getCanonicalIVType();
2508}
2509
2511 assert(!State.Lane && "VPDerivedIVRecipe being replicated.");
2512
2513 // Fast-math-flags propagate from the original induction instruction.
2514 IRBuilder<>::FastMathFlagGuard FMFG(State.Builder);
2515 if (FPBinOp)
2516 State.Builder.setFastMathFlags(FPBinOp->getFastMathFlags());
2517
2518 Value *Step = State.get(getStepValue(), VPLane(0));
2519 Value *Index = State.get(getOperand(1), VPLane(0));
2520 Value *DerivedIV = emitTransformedIndex(
2521 State.Builder, Index, getStartValue()->getLiveInIRValue(), Step, Kind,
2523 DerivedIV->setName(Name);
2524 State.set(this, DerivedIV, VPLane(0));
2525}
2526
2527#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2529 VPSlotTracker &SlotTracker) const {
2530 O << Indent;
2532 O << " = DERIVED-IV ";
2533 getStartValue()->printAsOperand(O, SlotTracker);
2534 O << " + ";
2535 getOperand(1)->printAsOperand(O, SlotTracker);
2536 O << " * ";
2537 getStepValue()->printAsOperand(O, SlotTracker);
2538}
2539#endif
2540
2542 // Fast-math-flags propagate from the original induction instruction.
2543 IRBuilder<>::FastMathFlagGuard FMFG(State.Builder);
2544 State.Builder.setFastMathFlags(getFastMathFlags());
2545
2546 /// Compute scalar induction steps. \p ScalarIV is the scalar induction
2547 /// variable on which to base the steps, \p Step is the size of the step.
2548
2549 Value *BaseIV = State.get(getOperand(0), VPLane(0));
2550 Value *Step = State.get(getStepValue(), VPLane(0));
2551 IRBuilderBase &Builder = State.Builder;
2552
2553 // Ensure step has the same type as that of scalar IV.
2554 Type *BaseIVTy = BaseIV->getType()->getScalarType();
2555 assert(BaseIVTy == Step->getType() && "Types of BaseIV and Step must match!");
2556
2557 // We build scalar steps for both integer and floating-point induction
2558 // variables. Here, we determine the kind of arithmetic we will perform.
2561 if (BaseIVTy->isIntegerTy()) {
2562 AddOp = Instruction::Add;
2563 MulOp = Instruction::Mul;
2564 } else {
2565 AddOp = InductionOpcode;
2566 MulOp = Instruction::FMul;
2567 }
2568
2569 // Determine the number of scalars we need to generate.
2570 bool FirstLaneOnly = vputils::onlyFirstLaneUsed(this);
2571 // Compute the scalar steps and save the results in State.
2572
2573 unsigned StartLane = 0;
2574 unsigned EndLane = FirstLaneOnly ? 1 : State.VF.getKnownMinValue();
2575 if (State.Lane) {
2576 StartLane = State.Lane->getKnownLane();
2577 EndLane = StartLane + 1;
2578 }
2579 Value *StartIdx0 = getStartIndex() ? State.get(getStartIndex(), true)
2580 : Constant::getNullValue(BaseIVTy);
2581
2582 for (unsigned Lane = StartLane; Lane < EndLane; ++Lane) {
2583 // It is okay if the induction variable type cannot hold the lane number,
2584 // we expect truncation in this case.
2585 Constant *LaneValue =
2586 BaseIVTy->isIntegerTy()
2587 ? ConstantInt::get(BaseIVTy, Lane, /*IsSigned=*/false,
2588 /*ImplicitTrunc=*/true)
2589 : ConstantFP::get(BaseIVTy, Lane);
2590 Value *StartIdx = Builder.CreateBinOp(AddOp, StartIdx0, LaneValue);
2591 // The step returned by `createStepForVF` is a runtime-evaluated value
2592 // when VF is scalable. Otherwise, it should be folded into a Constant.
2593 assert((State.VF.isScalable() || isa<Constant>(StartIdx)) &&
2594 "Expected StartIdx to be folded to a constant when VF is not "
2595 "scalable");
2596 auto *Mul = Builder.CreateBinOp(MulOp, StartIdx, Step);
2597 auto *Add = Builder.CreateBinOp(AddOp, BaseIV, Mul);
2598 State.set(this, Add, VPLane(Lane));
2599 }
2600}
2601
2602#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2604 VPSlotTracker &SlotTracker) const {
2605 O << Indent;
2607 O << " = SCALAR-STEPS ";
2609}
2610#endif
2611
2613 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
2615}
2616
2618 assert(State.VF.isVector() && "not widening");
2619 // Construct a vector GEP by widening the operands of the scalar GEP as
2620 // necessary. We mark the vector GEP 'inbounds' if appropriate. A GEP
2621 // results in a vector of pointers when at least one operand of the GEP
2622 // is vector-typed. Thus, to keep the representation compact, we only use
2623 // vector-typed operands for loop-varying values.
2624
2625 bool AllOperandsAreInvariant = all_of(operands(), [](VPValue *Op) {
2626 return Op->isDefinedOutsideLoopRegions();
2627 });
2628 if (AllOperandsAreInvariant) {
2629 // If we are vectorizing, but the GEP has only loop-invariant operands,
2630 // the GEP we build (by only using vector-typed operands for
2631 // loop-varying values) would be a scalar pointer. Thus, to ensure we
2632 // produce a vector of pointers, we need to either arbitrarily pick an
2633 // operand to broadcast, or broadcast a clone of the original GEP.
2634 // Here, we broadcast a clone of the original.
2635
2637 for (unsigned I = 0, E = getNumOperands(); I != E; I++)
2638 Ops.push_back(State.get(getOperand(I), VPLane(0)));
2639
2640 auto *NewGEP =
2641 State.Builder.CreateGEP(getSourceElementType(), Ops[0], drop_begin(Ops),
2642 "", getGEPNoWrapFlags());
2643 Value *Splat = State.Builder.CreateVectorSplat(State.VF, NewGEP);
2644 State.set(this, Splat);
2645 return;
2646 }
2647
2648 // If the GEP has at least one loop-varying operand, we are sure to
2649 // produce a vector of pointers unless VF is scalar.
2650 // The pointer operand of the new GEP. If it's loop-invariant, we
2651 // won't broadcast it.
2652 auto *Ptr = State.get(getOperand(0), isPointerLoopInvariant());
2653
2654 // Collect all the indices for the new GEP. If any index is
2655 // loop-invariant, we won't broadcast it.
2657 for (unsigned I = 1, E = getNumOperands(); I < E; I++) {
2658 VPValue *Operand = getOperand(I);
2659 Indices.push_back(State.get(Operand, isIndexLoopInvariant(I - 1)));
2660 }
2661
2662 // Create the new GEP. Note that this GEP may be a scalar if VF == 1,
2663 // but it should be a vector, otherwise.
2664 auto *NewGEP = State.Builder.CreateGEP(getSourceElementType(), Ptr, Indices,
2665 "", getGEPNoWrapFlags());
2666 assert((State.VF.isScalar() || NewGEP->getType()->isVectorTy()) &&
2667 "NewGEP is not a pointer vector");
2668 State.set(this, NewGEP);
2669}
2670
2671#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2673 VPSlotTracker &SlotTracker) const {
2674 O << Indent << "WIDEN-GEP ";
2675 O << (isPointerLoopInvariant() ? "Inv" : "Var");
2676 for (size_t I = 0; I < getNumOperands() - 1; ++I)
2677 O << "[" << (isIndexLoopInvariant(I) ? "Inv" : "Var") << "]";
2678
2679 O << " ";
2681 O << " = getelementptr";
2682 printFlags(O);
2684}
2685#endif
2686
2688 assert(!getOffset() && "Unexpected offset operand");
2689 VPBuilder Builder(this);
2690 VPlan &Plan = *getParent()->getPlan();
2691 VPValue *VFVal = getVFValue();
2692 VPTypeAnalysis TypeInfo(Plan);
2693 const DataLayout &DL =
2695 Type *IndexTy = DL.getIndexType(TypeInfo.inferScalarType(getPointer()));
2696 VPValue *Stride =
2697 Plan.getConstantInt(IndexTy, getStride(), /*IsSigned=*/true);
2698 Type *VFTy = TypeInfo.inferScalarType(VFVal);
2699 VPValue *VF = Builder.createScalarZExtOrTrunc(VFVal, IndexTy, VFTy,
2701
2702 // Offset for Part0 = Offset0 = Stride * (VF - 1).
2703 VPInstruction *VFMinusOne =
2704 Builder.createSub(VF, Plan.getConstantInt(IndexTy, 1u),
2705 DebugLoc::getUnknown(), "", {true, true});
2706 VPInstruction *Offset0 =
2707 Builder.createOverflowingOp(Instruction::Mul, {VFMinusOne, Stride});
2708
2709 // Offset for PartN = Offset0 + Part * Stride * VF.
2710 VPValue *PartxStride =
2711 Plan.getConstantInt(IndexTy, Part * getStride(), /*IsSigned=*/true);
2712 VPValue *Offset = Builder.createAdd(
2713 Offset0,
2714 Builder.createOverflowingOp(Instruction::Mul, {PartxStride, VF}));
2716}
2717
2719 auto &Builder = State.Builder;
2720 assert(getOffset() && "Expected prior materialization of offset");
2721 Value *Ptr = State.get(getPointer(), true);
2722 Value *Offset = State.get(getOffset(), true);
2723 Value *ResultPtr = Builder.CreateGEP(getSourceElementType(), Ptr, Offset, "",
2725 State.set(this, ResultPtr, /*IsScalar*/ true);
2726}
2727
2728#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2730 VPSlotTracker &SlotTracker) const {
2731 O << Indent;
2733 O << " = vector-end-pointer";
2734 printFlags(O);
2736}
2737#endif
2738
2740 auto &Builder = State.Builder;
2741 assert(getOffset() &&
2742 "Expected prior simplification of recipe without offset");
2743 Value *Ptr = State.get(getOperand(0), VPLane(0));
2744 Value *Offset = State.get(getOffset(), true);
2745 Value *ResultPtr = Builder.CreateGEP(getSourceElementType(), Ptr, Offset, "",
2747 State.set(this, ResultPtr, /*IsScalar*/ true);
2748}
2749
2750#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2752 VPSlotTracker &SlotTracker) const {
2753 O << Indent;
2755 O << " = vector-pointer";
2756 printFlags(O);
2758}
2759#endif
2760
2762 VPCostContext &Ctx) const {
2763 // A blend will be expanded to a select VPInstruction, which will generate a
2764 // scalar select if only the first lane is used.
2766 VF = ElementCount::getFixed(1);
2767
2768 Type *ResultTy = toVectorTy(Ctx.Types.inferScalarType(this), VF);
2769 Type *CmpTy = toVectorTy(Type::getInt1Ty(Ctx.Types.getContext()), VF);
2770 return (getNumIncomingValues() - 1) *
2771 Ctx.TTI.getCmpSelInstrCost(Instruction::Select, ResultTy, CmpTy,
2772 CmpInst::BAD_ICMP_PREDICATE, Ctx.CostKind);
2773}
2774
2775#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2777 VPSlotTracker &SlotTracker) const {
2778 O << Indent << "BLEND ";
2780 O << " =";
2781 printFlags(O);
2782 if (getNumIncomingValues() == 1) {
2783 // Not a User of any mask: not really blending, this is a
2784 // single-predecessor phi.
2785 getIncomingValue(0)->printAsOperand(O, SlotTracker);
2786 } else {
2787 for (unsigned I = 0, E = getNumIncomingValues(); I < E; ++I) {
2788 if (I != 0)
2789 O << " ";
2790 getIncomingValue(I)->printAsOperand(O, SlotTracker);
2791 if (I == 0 && isNormalized())
2792 continue;
2793 O << "/";
2794 getMask(I)->printAsOperand(O, SlotTracker);
2795 }
2796 }
2797}
2798#endif
2799
2801 assert(!State.Lane && "Reduction being replicated.");
2804 "In-loop AnyOf reductions aren't currently supported");
2805 // Propagate the fast-math flags carried by the underlying instruction.
2806 IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder);
2807 State.Builder.setFastMathFlags(getFastMathFlags());
2808 Value *NewVecOp = State.get(getVecOp());
2809 if (VPValue *Cond = getCondOp()) {
2810 Value *NewCond = State.get(Cond, State.VF.isScalar());
2811 VectorType *VecTy = dyn_cast<VectorType>(NewVecOp->getType());
2812 Type *ElementTy = VecTy ? VecTy->getElementType() : NewVecOp->getType();
2813
2814 Value *Start = getRecurrenceIdentity(Kind, ElementTy, getFastMathFlags());
2815 if (State.VF.isVector())
2816 Start = State.Builder.CreateVectorSplat(VecTy->getElementCount(), Start);
2817
2818 Value *Select = State.Builder.CreateSelect(NewCond, NewVecOp, Start);
2819 NewVecOp = Select;
2820 }
2821 Value *NewRed;
2822 Value *NextInChain;
2823 if (isOrdered()) {
2824 Value *PrevInChain = State.get(getChainOp(), /*IsScalar*/ true);
2825 if (State.VF.isVector())
2826 NewRed =
2827 createOrderedReduction(State.Builder, Kind, NewVecOp, PrevInChain);
2828 else
2829 NewRed = State.Builder.CreateBinOp(
2831 PrevInChain, NewVecOp);
2832 PrevInChain = NewRed;
2833 NextInChain = NewRed;
2834 } else if (isPartialReduction()) {
2835 assert((Kind == RecurKind::Add || Kind == RecurKind::FAdd) &&
2836 "Unexpected partial reduction kind");
2837 Value *PrevInChain = State.get(getChainOp(), /*IsScalar*/ false);
2838 NewRed = State.Builder.CreateIntrinsic(
2839 PrevInChain->getType(),
2840 Kind == RecurKind::Add ? Intrinsic::vector_partial_reduce_add
2841 : Intrinsic::vector_partial_reduce_fadd,
2842 {PrevInChain, NewVecOp}, State.Builder.getFastMathFlags(),
2843 "partial.reduce");
2844 PrevInChain = NewRed;
2845 NextInChain = NewRed;
2846 } else {
2847 assert(isInLoop() &&
2848 "The reduction must either be ordered, partial or in-loop");
2849 Value *PrevInChain = State.get(getChainOp(), /*IsScalar*/ true);
2850 NewRed = createSimpleReduction(State.Builder, NewVecOp, Kind);
2852 NextInChain = createMinMaxOp(State.Builder, Kind, NewRed, PrevInChain);
2853 else
2854 NextInChain = State.Builder.CreateBinOp(
2856 PrevInChain, NewRed);
2857 }
2858 State.set(this, NextInChain, /*IsScalar*/ !isPartialReduction());
2859}
2860
2862 assert(!State.Lane && "Reduction being replicated.");
2863
2864 auto &Builder = State.Builder;
2865 // Propagate the fast-math flags carried by the underlying instruction.
2866 IRBuilderBase::FastMathFlagGuard FMFGuard(Builder);
2867 Builder.setFastMathFlags(getFastMathFlags());
2868
2870 Value *Prev = State.get(getChainOp(), /*IsScalar*/ true);
2871 Value *VecOp = State.get(getVecOp());
2872 Value *EVL = State.get(getEVL(), VPLane(0));
2873
2874 Value *Mask;
2875 if (VPValue *CondOp = getCondOp())
2876 Mask = State.get(CondOp);
2877 else
2878 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
2879
2880 Value *NewRed;
2881 if (isOrdered()) {
2882 NewRed = createOrderedReduction(Builder, Kind, VecOp, Prev, Mask, EVL);
2883 } else {
2884 NewRed = createSimpleReduction(Builder, VecOp, Kind, Mask, EVL);
2886 NewRed = createMinMaxOp(Builder, Kind, NewRed, Prev);
2887 else
2888 NewRed = Builder.CreateBinOp(
2890 Prev);
2891 }
2892 State.set(this, NewRed, /*IsScalar*/ true);
2893}
2894
2896 VPCostContext &Ctx) const {
2897 RecurKind RdxKind = getRecurrenceKind();
2898 Type *ElementTy = Ctx.Types.inferScalarType(this);
2899 auto *VectorTy = cast<VectorType>(toVectorTy(ElementTy, VF));
2900 unsigned Opcode = RecurrenceDescriptor::getOpcode(RdxKind);
2902 std::optional<FastMathFlags> OptionalFMF =
2903 ElementTy->isFloatingPointTy() ? std::make_optional(FMFs) : std::nullopt;
2904
2905 if (isPartialReduction()) {
2906 InstructionCost CondCost = 0;
2907 if (isConditional()) {
2909 auto *CondTy = cast<VectorType>(
2910 toVectorTy(Ctx.Types.inferScalarType(getCondOp()), VF));
2911 CondCost = Ctx.TTI.getCmpSelInstrCost(Instruction::Select, VectorTy,
2912 CondTy, Pred, Ctx.CostKind);
2913 }
2914 return CondCost + Ctx.TTI.getPartialReductionCost(
2915 Opcode, ElementTy, ElementTy, ElementTy, VF,
2916 TTI::PR_None, TTI::PR_None, {}, Ctx.CostKind,
2917 OptionalFMF);
2918 }
2919
2920 // TODO: Support any-of reductions.
2921 assert(
2923 ForceTargetInstructionCost.getNumOccurrences() > 0) &&
2924 "Any-of reduction not implemented in VPlan-based cost model currently.");
2925
2926 // Note that TTI should model the cost of moving result to the scalar register
2927 // and the BinOp cost in the getMinMaxReductionCost().
2930 return Ctx.TTI.getMinMaxReductionCost(Id, VectorTy, FMFs, Ctx.CostKind);
2931 }
2932
2933 // Note that TTI should model the cost of moving result to the scalar register
2934 // and the BinOp cost in the getArithmeticReductionCost().
2935 return Ctx.TTI.getArithmeticReductionCost(Opcode, VectorTy, OptionalFMF,
2936 Ctx.CostKind);
2937}
2938
2939VPExpressionRecipe::VPExpressionRecipe(
2940 ExpressionTypes ExpressionType,
2941 ArrayRef<VPSingleDefRecipe *> ExpressionRecipes)
2942 : VPSingleDefRecipe(VPRecipeBase::VPExpressionSC, {}, {}),
2943 ExpressionRecipes(ExpressionRecipes), ExpressionType(ExpressionType) {
2944 assert(!ExpressionRecipes.empty() && "Nothing to combine?");
2945 assert(
2946 none_of(ExpressionRecipes,
2947 [](VPSingleDefRecipe *R) { return R->mayHaveSideEffects(); }) &&
2948 "expression cannot contain recipes with side-effects");
2949
2950 // Maintain a copy of the expression recipes as a set of users.
2951 SmallPtrSet<VPUser *, 4> ExpressionRecipesAsSetOfUsers;
2952 for (auto *R : ExpressionRecipes)
2953 ExpressionRecipesAsSetOfUsers.insert(R);
2954
2955 // Recipes in the expression, except the last one, must only be used by
2956 // (other) recipes inside the expression. If there are other users, external
2957 // to the expression, use a clone of the recipe for external users.
2958 for (VPSingleDefRecipe *R : reverse(ExpressionRecipes)) {
2959 if (R != ExpressionRecipes.back() &&
2960 any_of(R->users(), [&ExpressionRecipesAsSetOfUsers](VPUser *U) {
2961 return !ExpressionRecipesAsSetOfUsers.contains(U);
2962 })) {
2963 // There are users outside of the expression. Clone the recipe and use the
2964 // clone those external users.
2965 VPSingleDefRecipe *CopyForExtUsers = R->clone();
2966 R->replaceUsesWithIf(CopyForExtUsers, [&ExpressionRecipesAsSetOfUsers](
2967 VPUser &U, unsigned) {
2968 return !ExpressionRecipesAsSetOfUsers.contains(&U);
2969 });
2970 CopyForExtUsers->insertBefore(R);
2971 }
2972 if (R->getParent())
2973 R->removeFromParent();
2974 }
2975
2976 // Internalize all external operands to the expression recipes. To do so,
2977 // create new temporary VPValues for all operands defined by a recipe outside
2978 // the expression. The original operands are added as operands of the
2979 // VPExpressionRecipe itself.
2980 for (auto *R : ExpressionRecipes) {
2981 for (const auto &[Idx, Op] : enumerate(R->operands())) {
2982 auto *Def = Op->getDefiningRecipe();
2983 if (Def && ExpressionRecipesAsSetOfUsers.contains(Def))
2984 continue;
2985 addOperand(Op);
2986 LiveInPlaceholders.push_back(new VPSymbolicValue());
2987 }
2988 }
2989
2990 // Replace each external operand with the first one created for it in
2991 // LiveInPlaceholders.
2992 for (auto *R : ExpressionRecipes)
2993 for (auto const &[LiveIn, Tmp] : zip(operands(), LiveInPlaceholders))
2994 R->replaceUsesOfWith(LiveIn, Tmp);
2995}
2996
2998 for (auto *R : ExpressionRecipes)
2999 // Since the list could contain duplicates, make sure the recipe hasn't
3000 // already been inserted.
3001 if (!R->getParent())
3002 R->insertBefore(this);
3003
3004 for (const auto &[Idx, Op] : enumerate(operands()))
3005 LiveInPlaceholders[Idx]->replaceAllUsesWith(Op);
3006
3007 replaceAllUsesWith(ExpressionRecipes.back());
3008 ExpressionRecipes.clear();
3009}
3010
3012 VPCostContext &Ctx) const {
3013 Type *RedTy = Ctx.Types.inferScalarType(this);
3014 auto *SrcVecTy = cast<VectorType>(
3015 toVectorTy(Ctx.Types.inferScalarType(getOperand(0)), VF));
3016 unsigned Opcode = RecurrenceDescriptor::getOpcode(
3017 cast<VPReductionRecipe>(ExpressionRecipes.back())->getRecurrenceKind());
3018 switch (ExpressionType) {
3019 case ExpressionTypes::ExtendedReduction: {
3020 unsigned Opcode = RecurrenceDescriptor::getOpcode(
3021 cast<VPReductionRecipe>(ExpressionRecipes[1])->getRecurrenceKind());
3022 auto *ExtR = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3023 auto *RedR = cast<VPReductionRecipe>(ExpressionRecipes.back());
3024
3025 if (RedR->isPartialReduction())
3026 return Ctx.TTI.getPartialReductionCost(
3027 Opcode, Ctx.Types.inferScalarType(getOperand(0)), nullptr, RedTy, VF,
3029 TargetTransformInfo::PR_None, std::nullopt, Ctx.CostKind,
3030 RedTy->isFloatingPointTy() ? std::optional{RedR->getFastMathFlags()}
3031 : std::nullopt);
3032 else if (!RedTy->isFloatingPointTy())
3033 // TTI::getExtendedReductionCost only supports integer types.
3034 return Ctx.TTI.getExtendedReductionCost(
3035 Opcode, ExtR->getOpcode() == Instruction::ZExt, RedTy, SrcVecTy,
3036 std::nullopt, Ctx.CostKind);
3037 else
3039 }
3040 case ExpressionTypes::MulAccReduction:
3041 return Ctx.TTI.getMulAccReductionCost(false, Opcode, RedTy, SrcVecTy,
3042 Ctx.CostKind);
3043
3044 case ExpressionTypes::ExtNegatedMulAccReduction:
3045 assert(Opcode == Instruction::Add && "Unexpected opcode");
3046 Opcode = Instruction::Sub;
3047 [[fallthrough]];
3048 case ExpressionTypes::ExtMulAccReduction: {
3049 auto *RedR = cast<VPReductionRecipe>(ExpressionRecipes.back());
3050 if (RedR->isPartialReduction()) {
3051 auto *Ext0R = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3052 auto *Ext1R = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
3053 auto *Mul = cast<VPWidenRecipe>(ExpressionRecipes[2]);
3054 return Ctx.TTI.getPartialReductionCost(
3055 Opcode, Ctx.Types.inferScalarType(getOperand(0)),
3056 Ctx.Types.inferScalarType(getOperand(1)), RedTy, VF,
3058 Ext0R->getOpcode()),
3060 Ext1R->getOpcode()),
3061 Mul->getOpcode(), Ctx.CostKind,
3062 RedTy->isFloatingPointTy() ? std::optional{RedR->getFastMathFlags()}
3063 : std::nullopt);
3064 }
3065 return Ctx.TTI.getMulAccReductionCost(
3066 cast<VPWidenCastRecipe>(ExpressionRecipes.front())->getOpcode() ==
3067 Instruction::ZExt,
3068 Opcode, RedTy, SrcVecTy, Ctx.CostKind);
3069 }
3070 }
3071 llvm_unreachable("Unknown VPExpressionRecipe::ExpressionTypes enum");
3072}
3073
3075 return any_of(ExpressionRecipes, [](VPSingleDefRecipe *R) {
3076 return R->mayReadFromMemory() || R->mayWriteToMemory();
3077 });
3078}
3079
3081 assert(
3082 none_of(ExpressionRecipes,
3083 [](VPSingleDefRecipe *R) { return R->mayHaveSideEffects(); }) &&
3084 "expression cannot contain recipes with side-effects");
3085 return false;
3086}
3087
3089 // Cannot use vputils::isSingleScalar(), because all external operands
3090 // of the expression will be live-ins while bundled.
3091 auto *RR = dyn_cast<VPReductionRecipe>(ExpressionRecipes.back());
3092 return RR && !RR->isPartialReduction();
3093}
3094
3095#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3096
3098 VPSlotTracker &SlotTracker) const {
3099 O << Indent << "EXPRESSION ";
3101 O << " = ";
3102 auto *Red = cast<VPReductionRecipe>(ExpressionRecipes.back());
3103 unsigned Opcode = RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind());
3104
3105 switch (ExpressionType) {
3106 case ExpressionTypes::ExtendedReduction: {
3108 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
3109 O << Instruction::getOpcodeName(Opcode) << " (";
3111 Red->printFlags(O);
3112
3113 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3114 O << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
3115 << *Ext0->getResultType();
3116 if (Red->isConditional()) {
3117 O << ", ";
3118 Red->getCondOp()->printAsOperand(O, SlotTracker);
3119 }
3120 O << ")";
3121 break;
3122 }
3123 case ExpressionTypes::ExtNegatedMulAccReduction: {
3125 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
3127 RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind()))
3128 << " (sub (0, mul";
3129 auto *Mul = cast<VPWidenRecipe>(ExpressionRecipes[2]);
3130 Mul->printFlags(O);
3131 O << "(";
3133 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3134 O << " " << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
3135 << *Ext0->getResultType() << "), (";
3137 auto *Ext1 = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
3138 O << " " << Instruction::getOpcodeName(Ext1->getOpcode()) << " to "
3139 << *Ext1->getResultType() << ")";
3140 if (Red->isConditional()) {
3141 O << ", ";
3142 Red->getCondOp()->printAsOperand(O, SlotTracker);
3143 }
3144 O << "))";
3145 break;
3146 }
3147 case ExpressionTypes::MulAccReduction:
3148 case ExpressionTypes::ExtMulAccReduction: {
3150 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
3152 RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind()))
3153 << " (";
3154 O << "mul";
3155 bool IsExtended = ExpressionType == ExpressionTypes::ExtMulAccReduction;
3156 auto *Mul = cast<VPWidenRecipe>(IsExtended ? ExpressionRecipes[2]
3157 : ExpressionRecipes[0]);
3158 Mul->printFlags(O);
3159 if (IsExtended)
3160 O << "(";
3162 if (IsExtended) {
3163 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3164 O << " " << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
3165 << *Ext0->getResultType() << "), (";
3166 } else {
3167 O << ", ";
3168 }
3170 if (IsExtended) {
3171 auto *Ext1 = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
3172 O << " " << Instruction::getOpcodeName(Ext1->getOpcode()) << " to "
3173 << *Ext1->getResultType() << ")";
3174 }
3175 if (Red->isConditional()) {
3176 O << ", ";
3177 Red->getCondOp()->printAsOperand(O, SlotTracker);
3178 }
3179 O << ")";
3180 break;
3181 }
3182 }
3183}
3184
3186 VPSlotTracker &SlotTracker) const {
3187 if (isPartialReduction())
3188 O << Indent << "PARTIAL-REDUCE ";
3189 else
3190 O << Indent << "REDUCE ";
3192 O << " = ";
3194 O << " +";
3195 printFlags(O);
3196 O << " reduce."
3199 << " (";
3201 if (isConditional()) {
3202 O << ", ";
3204 }
3205 O << ")";
3206}
3207
3209 VPSlotTracker &SlotTracker) const {
3210 O << Indent << "REDUCE ";
3212 O << " = ";
3214 O << " +";
3215 printFlags(O);
3216 O << " vp.reduce."
3219 << " (";
3221 O << ", ";
3223 if (isConditional()) {
3224 O << ", ";
3226 }
3227 O << ")";
3228}
3229
3230#endif
3231
3232/// A helper function to scalarize a single Instruction in the innermost loop.
3233/// Generates a sequence of scalar instances for lane \p Lane. Uses the VPValue
3234/// operands from \p RepRecipe instead of \p Instr's operands.
3235static void scalarizeInstruction(const Instruction *Instr,
3236 VPReplicateRecipe *RepRecipe,
3237 const VPLane &Lane, VPTransformState &State) {
3238 assert((!Instr->getType()->isAggregateType() ||
3239 canVectorizeTy(Instr->getType())) &&
3240 "Expected vectorizable or non-aggregate type.");
3241
3242 // Does this instruction return a value ?
3243 bool IsVoidRetTy = Instr->getType()->isVoidTy();
3244
3245 Instruction *Cloned = Instr->clone();
3246 if (!IsVoidRetTy) {
3247 Cloned->setName(Instr->getName() + ".cloned");
3248 Type *ResultTy = State.TypeAnalysis.inferScalarType(RepRecipe);
3249 // The operands of the replicate recipe may have been narrowed, resulting in
3250 // a narrower result type. Update the type of the cloned instruction to the
3251 // correct type.
3252 if (ResultTy != Cloned->getType())
3253 Cloned->mutateType(ResultTy);
3254 }
3255
3256 RepRecipe->applyFlags(*Cloned);
3257 RepRecipe->applyMetadata(*Cloned);
3258
3259 if (RepRecipe->hasPredicate())
3260 cast<CmpInst>(Cloned)->setPredicate(RepRecipe->getPredicate());
3261
3262 if (auto DL = RepRecipe->getDebugLoc())
3263 State.setDebugLocFrom(DL);
3264
3265 // Replace the operands of the cloned instructions with their scalar
3266 // equivalents in the new loop.
3267 for (const auto &I : enumerate(RepRecipe->operands())) {
3268 auto InputLane = Lane;
3269 VPValue *Operand = I.value();
3270 if (vputils::isSingleScalar(Operand))
3271 InputLane = VPLane::getFirstLane();
3272 Cloned->setOperand(I.index(), State.get(Operand, InputLane));
3273 }
3274
3275 // Place the cloned scalar in the new loop.
3276 State.Builder.Insert(Cloned);
3277
3278 State.set(RepRecipe, Cloned, Lane);
3279
3280 // If we just cloned a new assumption, add it the assumption cache.
3281 if (auto *II = dyn_cast<AssumeInst>(Cloned))
3282 State.AC->registerAssumption(II);
3283
3284 assert(
3285 (RepRecipe->getRegion() ||
3286 !RepRecipe->getParent()->getPlan()->getVectorLoopRegion() ||
3287 all_of(RepRecipe->operands(),
3288 [](VPValue *Op) { return Op->isDefinedOutsideLoopRegions(); })) &&
3289 "Expected a recipe is either within a region or all of its operands "
3290 "are defined outside the vectorized region.");
3291}
3292
3295
3296 if (!State.Lane) {
3297 assert(IsSingleScalar && "VPReplicateRecipes outside replicate regions "
3298 "must have already been unrolled");
3299 scalarizeInstruction(UI, this, VPLane(0), State);
3300 return;
3301 }
3302
3303 assert((State.VF.isScalar() || !isSingleScalar()) &&
3304 "uniform recipe shouldn't be predicated");
3305 assert(!State.VF.isScalable() && "Can't scalarize a scalable vector");
3306 scalarizeInstruction(UI, this, *State.Lane, State);
3307 // Insert scalar instance packing it into a vector.
3308 if (State.VF.isVector() && shouldPack()) {
3309 Value *WideValue =
3310 State.Lane->isFirstLane()
3311 ? PoisonValue::get(toVectorizedTy(UI->getType(), State.VF))
3312 : State.get(this);
3313 State.set(this, State.packScalarIntoVectorizedValue(this, WideValue,
3314 *State.Lane));
3315 }
3316}
3317
3319 // Find if the recipe is used by a widened recipe via an intervening
3320 // VPPredInstPHIRecipe. In this case, also pack the scalar values in a vector.
3321 return any_of(users(), [](const VPUser *U) {
3322 if (auto *PredR = dyn_cast<VPPredInstPHIRecipe>(U))
3323 return !vputils::onlyScalarValuesUsed(PredR);
3324 return false;
3325 });
3326}
3327
3328/// Returns a SCEV expression for \p Ptr if it is a pointer computation for
3329/// which the legacy cost model computes a SCEV expression when computing the
3330/// address cost. Computing SCEVs for VPValues is incomplete and returns
3331/// SCEVCouldNotCompute in cases the legacy cost model can compute SCEVs. In
3332/// those cases we fall back to the legacy cost model. Otherwise return nullptr.
3333static const SCEV *getAddressAccessSCEV(const VPValue *Ptr,
3335 const Loop *L) {
3336 const SCEV *Addr = vputils::getSCEVExprForVPValue(Ptr, PSE, L);
3337 if (isa<SCEVCouldNotCompute>(Addr))
3338 return Addr;
3339
3340 return vputils::isAddressSCEVForCost(Addr, *PSE.getSE(), L) ? Addr : nullptr;
3341}
3342
3343/// Returns true if \p V is used as part of the address of another load or
3344/// store.
3345static bool isUsedByLoadStoreAddress(const VPUser *V) {
3347 SmallVector<const VPUser *> WorkList = {V};
3348
3349 while (!WorkList.empty()) {
3350 auto *Cur = dyn_cast<VPSingleDefRecipe>(WorkList.pop_back_val());
3351 if (!Cur || !Seen.insert(Cur).second)
3352 continue;
3353
3354 auto *Blend = dyn_cast<VPBlendRecipe>(Cur);
3355 // Skip blends that use V only through a compare by checking if any incoming
3356 // value was already visited.
3357 if (Blend && none_of(seq<unsigned>(0, Blend->getNumIncomingValues()),
3358 [&](unsigned I) {
3359 return Seen.contains(
3360 Blend->getIncomingValue(I)->getDefiningRecipe());
3361 }))
3362 continue;
3363
3364 for (VPUser *U : Cur->users()) {
3365 if (auto *InterleaveR = dyn_cast<VPInterleaveBase>(U))
3366 if (InterleaveR->getAddr() == Cur)
3367 return true;
3368 if (auto *RepR = dyn_cast<VPReplicateRecipe>(U)) {
3369 if (RepR->getOpcode() == Instruction::Load &&
3370 RepR->getOperand(0) == Cur)
3371 return true;
3372 if (RepR->getOpcode() == Instruction::Store &&
3373 RepR->getOperand(1) == Cur)
3374 return true;
3375 }
3376 if (auto *MemR = dyn_cast<VPWidenMemoryRecipe>(U)) {
3377 if (MemR->getAddr() == Cur && MemR->isConsecutive())
3378 return true;
3379 }
3380 }
3381
3382 // The legacy cost model only supports scalarization loads/stores with phi
3383 // addresses, if the phi is directly used as load/store address. Don't
3384 // traverse further for Blends.
3385 if (Blend)
3386 continue;
3387
3388 append_range(WorkList, Cur->users());
3389 }
3390 return false;
3391}
3392
3394 VPCostContext &Ctx) const {
3396 // VPReplicateRecipe may be cloned as part of an existing VPlan-to-VPlan
3397 // transform, avoid computing their cost multiple times for now.
3398 Ctx.SkipCostComputation.insert(UI);
3399
3400 if (VF.isScalable() && !isSingleScalar())
3402
3403 switch (UI->getOpcode()) {
3404 case Instruction::Alloca:
3405 if (VF.isScalable())
3407 return Ctx.TTI.getArithmeticInstrCost(
3408 Instruction::Mul, Ctx.Types.inferScalarType(this), Ctx.CostKind);
3409 case Instruction::GetElementPtr:
3410 // We mark this instruction as zero-cost because the cost of GEPs in
3411 // vectorized code depends on whether the corresponding memory instruction
3412 // is scalarized or not. Therefore, we handle GEPs with the memory
3413 // instruction cost.
3414 return 0;
3415 case Instruction::Call: {
3416 auto *CalledFn =
3418
3421 for (const VPValue *ArgOp : ArgOps)
3422 Tys.push_back(Ctx.Types.inferScalarType(ArgOp));
3423
3424 if (CalledFn->isIntrinsic())
3425 // Various pseudo-intrinsics with costs of 0 are scalarized instead of
3426 // vectorized via VPWidenIntrinsicRecipe. Return 0 for them early.
3427 switch (CalledFn->getIntrinsicID()) {
3428 case Intrinsic::assume:
3429 case Intrinsic::lifetime_end:
3430 case Intrinsic::lifetime_start:
3431 case Intrinsic::sideeffect:
3432 case Intrinsic::pseudoprobe:
3433 case Intrinsic::experimental_noalias_scope_decl: {
3434 assert(getCostForIntrinsics(CalledFn->getIntrinsicID(), ArgOps, *this,
3435 ElementCount::getFixed(1), Ctx) == 0 &&
3436 "scalarizing intrinsic should be free");
3437 return InstructionCost(0);
3438 }
3439 default:
3440 break;
3441 }
3442
3443 Type *ResultTy = Ctx.Types.inferScalarType(this);
3444 InstructionCost ScalarCallCost =
3445 Ctx.TTI.getCallInstrCost(CalledFn, ResultTy, Tys, Ctx.CostKind);
3446 if (isSingleScalar()) {
3447 if (CalledFn->isIntrinsic())
3448 ScalarCallCost = std::min(
3449 ScalarCallCost,
3450 getCostForIntrinsics(CalledFn->getIntrinsicID(), ArgOps, *this,
3451 ElementCount::getFixed(1), Ctx));
3452 return ScalarCallCost;
3453 }
3454
3455 return ScalarCallCost * VF.getFixedValue() +
3456 Ctx.getScalarizationOverhead(ResultTy, ArgOps, VF);
3457 }
3458 case Instruction::Add:
3459 case Instruction::Sub:
3460 case Instruction::FAdd:
3461 case Instruction::FSub:
3462 case Instruction::Mul:
3463 case Instruction::FMul:
3464 case Instruction::FDiv:
3465 case Instruction::FRem:
3466 case Instruction::Shl:
3467 case Instruction::LShr:
3468 case Instruction::AShr:
3469 case Instruction::And:
3470 case Instruction::Or:
3471 case Instruction::Xor:
3472 case Instruction::ICmp:
3473 case Instruction::FCmp:
3475 Ctx) *
3476 (isSingleScalar() ? 1 : VF.getFixedValue());
3477 case Instruction::SDiv:
3478 case Instruction::UDiv:
3479 case Instruction::SRem:
3480 case Instruction::URem: {
3481 InstructionCost ScalarCost =
3483 if (isSingleScalar())
3484 return ScalarCost;
3485
3486 // If any of the operands is from a different replicate region and has its
3487 // cost skipped, it may have been forced to scalar. Fall back to legacy cost
3488 // model to avoid cost mis-match.
3489 if (any_of(operands(), [&Ctx, VF](VPValue *Op) {
3490 auto *PredR = dyn_cast<VPPredInstPHIRecipe>(Op);
3491 if (!PredR)
3492 return false;
3493 return Ctx.skipCostComputation(
3495 PredR->getOperand(0)->getUnderlyingValue()),
3496 VF.isVector());
3497 }))
3498 break;
3499
3500 ScalarCost = ScalarCost * VF.getFixedValue() +
3501 Ctx.getScalarizationOverhead(Ctx.Types.inferScalarType(this),
3502 to_vector(operands()), VF);
3503 // If the recipe is not predicated (i.e. not in a replicate region), return
3504 // the scalar cost. Otherwise handle predicated cost.
3505 if (!getRegion()->isReplicator())
3506 return ScalarCost;
3507
3508 // Account for the phi nodes that we will create.
3509 ScalarCost += VF.getFixedValue() *
3510 Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
3511 // Scale the cost by the probability of executing the predicated blocks.
3512 // This assumes the predicated block for each vector lane is equally
3513 // likely.
3514 ScalarCost /= Ctx.getPredBlockCostDivisor(UI->getParent());
3515 return ScalarCost;
3516 }
3517 case Instruction::Load:
3518 case Instruction::Store: {
3519 bool IsLoad = UI->getOpcode() == Instruction::Load;
3520 const VPValue *PtrOp = getOperand(!IsLoad);
3521 const SCEV *PtrSCEV = getAddressAccessSCEV(PtrOp, Ctx.PSE, Ctx.L);
3523 break;
3524
3525 Type *ValTy = Ctx.Types.inferScalarType(IsLoad ? this : getOperand(0));
3526 Type *ScalarPtrTy = Ctx.Types.inferScalarType(PtrOp);
3527 const Align Alignment = getLoadStoreAlignment(UI);
3528 unsigned AS = cast<PointerType>(ScalarPtrTy)->getAddressSpace();
3530 bool PreferVectorizedAddressing = Ctx.TTI.prefersVectorizedAddressing();
3531 bool UsedByLoadStoreAddress =
3532 !PreferVectorizedAddressing && isUsedByLoadStoreAddress(this);
3533 InstructionCost ScalarMemOpCost = Ctx.TTI.getMemoryOpCost(
3534 UI->getOpcode(), ValTy, Alignment, AS, Ctx.CostKind, OpInfo,
3535 UsedByLoadStoreAddress ? UI : nullptr);
3536
3537 Type *PtrTy = isSingleScalar() ? ScalarPtrTy : toVectorTy(ScalarPtrTy, VF);
3538 InstructionCost ScalarCost =
3539 ScalarMemOpCost +
3540 Ctx.TTI.getAddressComputationCost(
3541 PtrTy, UsedByLoadStoreAddress ? nullptr : Ctx.PSE.getSE(), PtrSCEV,
3542 Ctx.CostKind);
3543 if (isSingleScalar())
3544 return ScalarCost;
3545
3546 SmallVector<const VPValue *> OpsToScalarize;
3547 Type *ResultTy = Type::getVoidTy(PtrTy->getContext());
3548 // Set ResultTy and OpsToScalarize, if scalarization is needed. Currently we
3549 // don't assign scalarization overhead in general, if the target prefers
3550 // vectorized addressing or the loaded value is used as part of an address
3551 // of another load or store.
3552 if (!UsedByLoadStoreAddress) {
3553 bool EfficientVectorLoadStore =
3554 Ctx.TTI.supportsEfficientVectorElementLoadStore();
3555 if (!(IsLoad && !PreferVectorizedAddressing) &&
3556 !(!IsLoad && EfficientVectorLoadStore))
3557 append_range(OpsToScalarize, operands());
3558
3559 if (!EfficientVectorLoadStore)
3560 ResultTy = Ctx.Types.inferScalarType(this);
3561 }
3562
3566 (ScalarCost * VF.getFixedValue()) +
3567 Ctx.getScalarizationOverhead(ResultTy, OpsToScalarize, VF, VIC, true);
3568
3569 const VPRegionBlock *ParentRegion = getRegion();
3570 if (ParentRegion && ParentRegion->isReplicator()) {
3571 // TODO: Handle loop-invariant pointers in predicated blocks. For now,
3572 // fall back to the legacy cost model.
3573 if (!PtrSCEV || Ctx.PSE.getSE()->isLoopInvariant(PtrSCEV, Ctx.L))
3574 break;
3575 Cost /= Ctx.getPredBlockCostDivisor(UI->getParent());
3576 Cost += Ctx.TTI.getCFInstrCost(Instruction::Br, Ctx.CostKind);
3577
3578 auto *VecI1Ty = VectorType::get(
3579 IntegerType::getInt1Ty(Ctx.L->getHeader()->getContext()), VF);
3580 Cost += Ctx.TTI.getScalarizationOverhead(
3581 VecI1Ty, APInt::getAllOnes(VF.getFixedValue()),
3582 /*Insert=*/false, /*Extract=*/true, Ctx.CostKind);
3583
3584 if (Ctx.useEmulatedMaskMemRefHack(this, VF)) {
3585 // Artificially setting to a high enough value to practically disable
3586 // vectorization with such operations.
3587 return 3000000;
3588 }
3589 }
3590 return Cost;
3591 }
3592 case Instruction::SExt:
3593 case Instruction::ZExt:
3594 case Instruction::FPToUI:
3595 case Instruction::FPToSI:
3596 case Instruction::FPExt:
3597 case Instruction::PtrToInt:
3598 case Instruction::PtrToAddr:
3599 case Instruction::IntToPtr:
3600 case Instruction::SIToFP:
3601 case Instruction::UIToFP:
3602 case Instruction::Trunc:
3603 case Instruction::FPTrunc:
3604 case Instruction::AddrSpaceCast: {
3606 Ctx) *
3607 (isSingleScalar() ? 1 : VF.getFixedValue());
3608 }
3609 case Instruction::ExtractValue:
3610 case Instruction::InsertValue:
3611 return Ctx.TTI.getInsertExtractValueCost(getOpcode(), Ctx.CostKind);
3612 }
3613
3614 return Ctx.getLegacyCost(UI, VF);
3615}
3616
3617#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3619 VPSlotTracker &SlotTracker) const {
3620 O << Indent << (IsSingleScalar ? "CLONE " : "REPLICATE ");
3621
3622 if (!getUnderlyingInstr()->getType()->isVoidTy()) {
3624 O << " = ";
3625 }
3626 if (auto *CB = dyn_cast<CallBase>(getUnderlyingInstr())) {
3627 O << "call";
3628 printFlags(O);
3629 O << "@" << CB->getCalledFunction()->getName() << "(";
3631 O, [&O, &SlotTracker](VPValue *Op) {
3632 Op->printAsOperand(O, SlotTracker);
3633 });
3634 O << ")";
3635 } else {
3637 printFlags(O);
3639 }
3640
3641 if (shouldPack())
3642 O << " (S->V)";
3643}
3644#endif
3645
3647 assert(State.Lane && "Branch on Mask works only on single instance.");
3648
3649 VPValue *BlockInMask = getOperand(0);
3650 Value *ConditionBit = State.get(BlockInMask, *State.Lane);
3651
3652 // Replace the temporary unreachable terminator with a new conditional branch,
3653 // whose two destinations will be set later when they are created.
3654 auto *CurrentTerminator = State.CFG.PrevBB->getTerminator();
3655 assert(isa<UnreachableInst>(CurrentTerminator) &&
3656 "Expected to replace unreachable terminator with conditional branch.");
3657 auto CondBr =
3658 State.Builder.CreateCondBr(ConditionBit, State.CFG.PrevBB, nullptr);
3659 CondBr->setSuccessor(0, nullptr);
3660 CurrentTerminator->eraseFromParent();
3661}
3662
3664 VPCostContext &Ctx) const {
3665 // The legacy cost model doesn't assign costs to branches for individual
3666 // replicate regions. Match the current behavior in the VPlan cost model for
3667 // now.
3668 return 0;
3669}
3670
3672 assert(State.Lane && "Predicated instruction PHI works per instance.");
3673 Instruction *ScalarPredInst =
3674 cast<Instruction>(State.get(getOperand(0), *State.Lane));
3675 BasicBlock *PredicatedBB = ScalarPredInst->getParent();
3676 BasicBlock *PredicatingBB = PredicatedBB->getSinglePredecessor();
3677 assert(PredicatingBB && "Predicated block has no single predecessor.");
3679 "operand must be VPReplicateRecipe");
3680
3681 // By current pack/unpack logic we need to generate only a single phi node: if
3682 // a vector value for the predicated instruction exists at this point it means
3683 // the instruction has vector users only, and a phi for the vector value is
3684 // needed. In this case the recipe of the predicated instruction is marked to
3685 // also do that packing, thereby "hoisting" the insert-element sequence.
3686 // Otherwise, a phi node for the scalar value is needed.
3687 if (State.hasVectorValue(getOperand(0))) {
3688 auto *VecI = cast<Instruction>(State.get(getOperand(0)));
3690 "Packed operands must generate an insertelement or insertvalue");
3691
3692 // If VectorI is a struct, it will be a sequence like:
3693 // %1 = insertvalue %unmodified, %x, 0
3694 // %2 = insertvalue %1, %y, 1
3695 // %VectorI = insertvalue %2, %z, 2
3696 // To get the unmodified vector we need to look through the chain.
3697 if (auto *StructTy = dyn_cast<StructType>(VecI->getType()))
3698 for (unsigned I = 0; I < StructTy->getNumContainedTypes() - 1; I++)
3699 VecI = cast<InsertValueInst>(VecI->getOperand(0));
3700
3701 PHINode *VPhi = State.Builder.CreatePHI(VecI->getType(), 2);
3702 VPhi->addIncoming(VecI->getOperand(0), PredicatingBB); // Unmodified vector.
3703 VPhi->addIncoming(VecI, PredicatedBB); // New vector with inserted element.
3704 if (State.hasVectorValue(this))
3705 State.reset(this, VPhi);
3706 else
3707 State.set(this, VPhi);
3708 // NOTE: Currently we need to update the value of the operand, so the next
3709 // predicated iteration inserts its generated value in the correct vector.
3710 State.reset(getOperand(0), VPhi);
3711 } else {
3712 if (vputils::onlyFirstLaneUsed(this) && !State.Lane->isFirstLane())
3713 return;
3714
3715 Type *PredInstType = State.TypeAnalysis.inferScalarType(getOperand(0));
3716 PHINode *Phi = State.Builder.CreatePHI(PredInstType, 2);
3717 Phi->addIncoming(PoisonValue::get(ScalarPredInst->getType()),
3718 PredicatingBB);
3719 Phi->addIncoming(ScalarPredInst, PredicatedBB);
3720 if (State.hasScalarValue(this, *State.Lane))
3721 State.reset(this, Phi, *State.Lane);
3722 else
3723 State.set(this, Phi, *State.Lane);
3724 // NOTE: Currently we need to update the value of the operand, so the next
3725 // predicated iteration inserts its generated value in the correct vector.
3726 State.reset(getOperand(0), Phi, *State.Lane);
3727 }
3728}
3729
3730#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3732 VPSlotTracker &SlotTracker) const {
3733 O << Indent << "PHI-PREDICATED-INSTRUCTION ";
3735 O << " = ";
3737}
3738#endif
3739
3741 VPCostContext &Ctx) const {
3743 unsigned AS = cast<PointerType>(Ctx.Types.inferScalarType(getAddr()))
3744 ->getAddressSpace();
3745 unsigned Opcode = isa<VPWidenLoadRecipe, VPWidenLoadEVLRecipe>(this)
3746 ? Instruction::Load
3747 : Instruction::Store;
3748
3749 if (!Consecutive) {
3750 // TODO: Using the original IR may not be accurate.
3751 // Currently, ARM will use the underlying IR to calculate gather/scatter
3752 // instruction cost.
3753 assert(!Reverse &&
3754 "Inconsecutive memory access should not have the order.");
3755
3757 Type *PtrTy = Ptr->getType();
3758
3759 // If the address value is uniform across all lanes, then the address can be
3760 // calculated with scalar type and broadcast.
3762 PtrTy = toVectorTy(PtrTy, VF);
3763
3764 unsigned IID = isa<VPWidenLoadRecipe>(this) ? Intrinsic::masked_gather
3765 : isa<VPWidenStoreRecipe>(this) ? Intrinsic::masked_scatter
3766 : isa<VPWidenLoadEVLRecipe>(this) ? Intrinsic::vp_gather
3767 : Intrinsic::vp_scatter;
3768 return Ctx.TTI.getAddressComputationCost(PtrTy, nullptr, nullptr,
3769 Ctx.CostKind) +
3770 Ctx.TTI.getMemIntrinsicInstrCost(
3772 &Ingredient),
3773 Ctx.CostKind);
3774 }
3775
3777 if (IsMasked) {
3778 unsigned IID = isa<VPWidenLoadRecipe>(this) ? Intrinsic::masked_load
3779 : Intrinsic::masked_store;
3780 Cost += Ctx.TTI.getMemIntrinsicInstrCost(
3781 MemIntrinsicCostAttributes(IID, Ty, Alignment, AS), Ctx.CostKind);
3782 } else {
3783 TTI::OperandValueInfo OpInfo = Ctx.getOperandInfo(
3785 : getOperand(1));
3786 Cost += Ctx.TTI.getMemoryOpCost(Opcode, Ty, Alignment, AS, Ctx.CostKind,
3787 OpInfo, &Ingredient);
3788 }
3789 return Cost;
3790}
3791
3793 Type *ScalarDataTy = getLoadStoreType(&Ingredient);
3794 auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
3795 bool CreateGather = !isConsecutive();
3796
3797 auto &Builder = State.Builder;
3798 Value *Mask = nullptr;
3799 if (auto *VPMask = getMask()) {
3800 // Mask reversal is only needed for non-all-one (null) masks, as reverse
3801 // of a null all-one mask is a null mask.
3802 Mask = State.get(VPMask);
3803 if (isReverse())
3804 Mask = Builder.CreateVectorReverse(Mask, "reverse");
3805 }
3806
3807 Value *Addr = State.get(getAddr(), /*IsScalar*/ !CreateGather);
3808 Value *NewLI;
3809 if (CreateGather) {
3810 NewLI = Builder.CreateMaskedGather(DataTy, Addr, Alignment, Mask, nullptr,
3811 "wide.masked.gather");
3812 } else if (Mask) {
3813 NewLI =
3814 Builder.CreateMaskedLoad(DataTy, Addr, Alignment, Mask,
3815 PoisonValue::get(DataTy), "wide.masked.load");
3816 } else {
3817 NewLI = Builder.CreateAlignedLoad(DataTy, Addr, Alignment, "wide.load");
3818 }
3820 State.set(this, NewLI);
3821}
3822
3823#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3825 VPSlotTracker &SlotTracker) const {
3826 O << Indent << "WIDEN ";
3828 O << " = load ";
3830}
3831#endif
3832
3833/// Use all-true mask for reverse rather than actual mask, as it avoids a
3834/// dependence w/o affecting the result.
3836 Value *EVL, const Twine &Name) {
3837 VectorType *ValTy = cast<VectorType>(Operand->getType());
3838 Value *AllTrueMask =
3839 Builder.CreateVectorSplat(ValTy->getElementCount(), Builder.getTrue());
3840 return Builder.CreateIntrinsic(ValTy, Intrinsic::experimental_vp_reverse,
3841 {Operand, AllTrueMask, EVL}, nullptr, Name);
3842}
3843
3845 Type *ScalarDataTy = getLoadStoreType(&Ingredient);
3846 auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
3847 bool CreateGather = !isConsecutive();
3848
3849 auto &Builder = State.Builder;
3850 CallInst *NewLI;
3851 Value *EVL = State.get(getEVL(), VPLane(0));
3852 Value *Addr = State.get(getAddr(), !CreateGather);
3853 Value *Mask = nullptr;
3854 if (VPValue *VPMask = getMask()) {
3855 Mask = State.get(VPMask);
3856 if (isReverse())
3857 Mask = createReverseEVL(Builder, Mask, EVL, "vp.reverse.mask");
3858 } else {
3859 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
3860 }
3861
3862 if (CreateGather) {
3863 NewLI =
3864 Builder.CreateIntrinsic(DataTy, Intrinsic::vp_gather, {Addr, Mask, EVL},
3865 nullptr, "wide.masked.gather");
3866 } else {
3867 NewLI = Builder.CreateIntrinsic(DataTy, Intrinsic::vp_load,
3868 {Addr, Mask, EVL}, nullptr, "vp.op.load");
3869 }
3870 NewLI->addParamAttr(
3872 applyMetadata(*NewLI);
3873 Instruction *Res = NewLI;
3874 State.set(this, Res);
3875}
3876
3878 VPCostContext &Ctx) const {
3879 if (!Consecutive || IsMasked)
3880 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
3881
3882 // We need to use the getMemIntrinsicInstrCost() instead of getMemoryOpCost()
3883 // here because the EVL recipes using EVL to replace the tail mask. But in the
3884 // legacy model, it will always calculate the cost of mask.
3885 // TODO: Using getMemoryOpCost() instead of getMemIntrinsicInstrCost when we
3886 // don't need to compare to the legacy cost model.
3888 unsigned AS = cast<PointerType>(Ctx.Types.inferScalarType(getAddr()))
3889 ->getAddressSpace();
3890 return Ctx.TTI.getMemIntrinsicInstrCost(
3891 MemIntrinsicCostAttributes(Intrinsic::vp_load, Ty, Alignment, AS),
3892 Ctx.CostKind);
3893}
3894
3895#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3897 VPSlotTracker &SlotTracker) const {
3898 O << Indent << "WIDEN ";
3900 O << " = vp.load ";
3902}
3903#endif
3904
3906 VPValue *StoredVPValue = getStoredValue();
3907 bool CreateScatter = !isConsecutive();
3908
3909 auto &Builder = State.Builder;
3910
3911 Value *Mask = nullptr;
3912 if (auto *VPMask = getMask()) {
3913 // Mask reversal is only needed for non-all-one (null) masks, as reverse
3914 // of a null all-one mask is a null mask.
3915 Mask = State.get(VPMask);
3916 if (isReverse())
3917 Mask = Builder.CreateVectorReverse(Mask, "reverse");
3918 }
3919
3920 Value *StoredVal = State.get(StoredVPValue);
3921 Value *Addr = State.get(getAddr(), /*IsScalar*/ !CreateScatter);
3922 Instruction *NewSI = nullptr;
3923 if (CreateScatter)
3924 NewSI = Builder.CreateMaskedScatter(StoredVal, Addr, Alignment, Mask);
3925 else if (Mask)
3926 NewSI = Builder.CreateMaskedStore(StoredVal, Addr, Alignment, Mask);
3927 else
3928 NewSI = Builder.CreateAlignedStore(StoredVal, Addr, Alignment);
3929 applyMetadata(*NewSI);
3930}
3931
3932#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3934 VPSlotTracker &SlotTracker) const {
3935 O << Indent << "WIDEN store ";
3937}
3938#endif
3939
3941 VPValue *StoredValue = getStoredValue();
3942 bool CreateScatter = !isConsecutive();
3943
3944 auto &Builder = State.Builder;
3945
3946 CallInst *NewSI = nullptr;
3947 Value *StoredVal = State.get(StoredValue);
3948 Value *EVL = State.get(getEVL(), VPLane(0));
3949 Value *Mask = nullptr;
3950 if (VPValue *VPMask = getMask()) {
3951 Mask = State.get(VPMask);
3952 if (isReverse())
3953 Mask = createReverseEVL(Builder, Mask, EVL, "vp.reverse.mask");
3954 } else {
3955 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
3956 }
3957 Value *Addr = State.get(getAddr(), !CreateScatter);
3958 if (CreateScatter) {
3959 NewSI = Builder.CreateIntrinsic(Type::getVoidTy(EVL->getContext()),
3960 Intrinsic::vp_scatter,
3961 {StoredVal, Addr, Mask, EVL});
3962 } else {
3963 NewSI = Builder.CreateIntrinsic(Type::getVoidTy(EVL->getContext()),
3964 Intrinsic::vp_store,
3965 {StoredVal, Addr, Mask, EVL});
3966 }
3967 NewSI->addParamAttr(
3969 applyMetadata(*NewSI);
3970}
3971
3973 VPCostContext &Ctx) const {
3974 if (!Consecutive || IsMasked)
3975 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
3976
3977 // We need to use the getMemIntrinsicInstrCost() instead of getMemoryOpCost()
3978 // here because the EVL recipes using EVL to replace the tail mask. But in the
3979 // legacy model, it will always calculate the cost of mask.
3980 // TODO: Using getMemoryOpCost() instead of getMemIntrinsicInstrCost when we
3981 // don't need to compare to the legacy cost model.
3983 unsigned AS = cast<PointerType>(Ctx.Types.inferScalarType(getAddr()))
3984 ->getAddressSpace();
3985 return Ctx.TTI.getMemIntrinsicInstrCost(
3986 MemIntrinsicCostAttributes(Intrinsic::vp_store, Ty, Alignment, AS),
3987 Ctx.CostKind);
3988}
3989
3990#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3992 VPSlotTracker &SlotTracker) const {
3993 O << Indent << "WIDEN vp.store ";
3995}
3996#endif
3997
3999 VectorType *DstVTy, const DataLayout &DL) {
4000 // Verify that V is a vector type with same number of elements as DstVTy.
4001 auto VF = DstVTy->getElementCount();
4002 auto *SrcVecTy = cast<VectorType>(V->getType());
4003 assert(VF == SrcVecTy->getElementCount() && "Vector dimensions do not match");
4004 Type *SrcElemTy = SrcVecTy->getElementType();
4005 Type *DstElemTy = DstVTy->getElementType();
4006 assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&
4007 "Vector elements must have same size");
4008
4009 // Do a direct cast if element types are castable.
4010 if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
4011 return Builder.CreateBitOrPointerCast(V, DstVTy);
4012 }
4013 // V cannot be directly casted to desired vector type.
4014 // May happen when V is a floating point vector but DstVTy is a vector of
4015 // pointers or vice-versa. Handle this using a two-step bitcast using an
4016 // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
4017 assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&
4018 "Only one type should be a pointer type");
4019 assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&
4020 "Only one type should be a floating point type");
4021 Type *IntTy =
4022 IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy));
4023 auto *VecIntTy = VectorType::get(IntTy, VF);
4024 Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
4025 return Builder.CreateBitOrPointerCast(CastVal, DstVTy);
4026}
4027
4028/// Return a vector containing interleaved elements from multiple
4029/// smaller input vectors.
4031 const Twine &Name) {
4032 unsigned Factor = Vals.size();
4033 assert(Factor > 1 && "Tried to interleave invalid number of vectors");
4034
4035 VectorType *VecTy = cast<VectorType>(Vals[0]->getType());
4036#ifndef NDEBUG
4037 for (Value *Val : Vals)
4038 assert(Val->getType() == VecTy && "Tried to interleave mismatched types");
4039#endif
4040
4041 // Scalable vectors cannot use arbitrary shufflevectors (only splats), so
4042 // must use intrinsics to interleave.
4043 if (VecTy->isScalableTy()) {
4044 assert(Factor <= 8 && "Unsupported interleave factor for scalable vectors");
4045 return Builder.CreateVectorInterleave(Vals, Name);
4046 }
4047
4048 // Fixed length. Start by concatenating all vectors into a wide vector.
4049 Value *WideVec = concatenateVectors(Builder, Vals);
4050
4051 // Interleave the elements into the wide vector.
4052 const unsigned NumElts = VecTy->getElementCount().getFixedValue();
4053 return Builder.CreateShuffleVector(
4054 WideVec, createInterleaveMask(NumElts, Factor), Name);
4055}
4056
4057// Try to vectorize the interleave group that \p Instr belongs to.
4058//
4059// E.g. Translate following interleaved load group (factor = 3):
4060// for (i = 0; i < N; i+=3) {
4061// R = Pic[i]; // Member of index 0
4062// G = Pic[i+1]; // Member of index 1
4063// B = Pic[i+2]; // Member of index 2
4064// ... // do something to R, G, B
4065// }
4066// To:
4067// %wide.vec = load <12 x i32> ; Read 4 tuples of R,G,B
4068// %R.vec = shuffle %wide.vec, poison, <0, 3, 6, 9> ; R elements
4069// %G.vec = shuffle %wide.vec, poison, <1, 4, 7, 10> ; G elements
4070// %B.vec = shuffle %wide.vec, poison, <2, 5, 8, 11> ; B elements
4071//
4072// Or translate following interleaved store group (factor = 3):
4073// for (i = 0; i < N; i+=3) {
4074// ... do something to R, G, B
4075// Pic[i] = R; // Member of index 0
4076// Pic[i+1] = G; // Member of index 1
4077// Pic[i+2] = B; // Member of index 2
4078// }
4079// To:
4080// %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
4081// %B_U.vec = shuffle %B.vec, poison, <0, 1, 2, 3, u, u, u, u>
4082// %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
4083// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> ; Interleave R,G,B elements
4084// store <12 x i32> %interleaved.vec ; Write 4 tuples of R,G,B
4086 assert(!State.Lane && "Interleave group being replicated.");
4087 assert((!needsMaskForGaps() || !State.VF.isScalable()) &&
4088 "Masking gaps for scalable vectors is not yet supported.");
4090 Instruction *Instr = Group->getInsertPos();
4091
4092 // Prepare for the vector type of the interleaved load/store.
4093 Type *ScalarTy = getLoadStoreType(Instr);
4094 unsigned InterleaveFactor = Group->getFactor();
4095 auto *VecTy = VectorType::get(ScalarTy, State.VF * InterleaveFactor);
4096
4097 VPValue *BlockInMask = getMask();
4098 VPValue *Addr = getAddr();
4099 Value *ResAddr = State.get(Addr, VPLane(0));
4100
4101 auto CreateGroupMask = [&BlockInMask, &State,
4102 &InterleaveFactor](Value *MaskForGaps) -> Value * {
4103 if (State.VF.isScalable()) {
4104 assert(!MaskForGaps && "Interleaved groups with gaps are not supported.");
4105 assert(InterleaveFactor <= 8 &&
4106 "Unsupported deinterleave factor for scalable vectors");
4107 auto *ResBlockInMask = State.get(BlockInMask);
4108 SmallVector<Value *> Ops(InterleaveFactor, ResBlockInMask);
4109 return interleaveVectors(State.Builder, Ops, "interleaved.mask");
4110 }
4111
4112 if (!BlockInMask)
4113 return MaskForGaps;
4114
4115 Value *ResBlockInMask = State.get(BlockInMask);
4116 Value *ShuffledMask = State.Builder.CreateShuffleVector(
4117 ResBlockInMask,
4118 createReplicatedMask(InterleaveFactor, State.VF.getFixedValue()),
4119 "interleaved.mask");
4120 return MaskForGaps ? State.Builder.CreateBinOp(Instruction::And,
4121 ShuffledMask, MaskForGaps)
4122 : ShuffledMask;
4123 };
4124
4125 const DataLayout &DL = Instr->getDataLayout();
4126 // Vectorize the interleaved load group.
4127 if (isa<LoadInst>(Instr)) {
4128 Value *MaskForGaps = nullptr;
4129 if (needsMaskForGaps()) {
4130 MaskForGaps =
4131 createBitMaskForGaps(State.Builder, State.VF.getFixedValue(), *Group);
4132 assert(MaskForGaps && "Mask for Gaps is required but it is null");
4133 }
4134
4135 Instruction *NewLoad;
4136 if (BlockInMask || MaskForGaps) {
4137 Value *GroupMask = CreateGroupMask(MaskForGaps);
4138 Value *PoisonVec = PoisonValue::get(VecTy);
4139 NewLoad = State.Builder.CreateMaskedLoad(VecTy, ResAddr,
4140 Group->getAlign(), GroupMask,
4141 PoisonVec, "wide.masked.vec");
4142 } else
4143 NewLoad = State.Builder.CreateAlignedLoad(VecTy, ResAddr,
4144 Group->getAlign(), "wide.vec");
4145 applyMetadata(*NewLoad);
4146 // TODO: Also manage existing metadata using VPIRMetadata.
4147 Group->addMetadata(NewLoad);
4148
4150 if (VecTy->isScalableTy()) {
4151 // Scalable vectors cannot use arbitrary shufflevectors (only splats),
4152 // so must use intrinsics to deinterleave.
4153 assert(InterleaveFactor <= 8 &&
4154 "Unsupported deinterleave factor for scalable vectors");
4155 NewLoad = State.Builder.CreateIntrinsic(
4156 Intrinsic::getDeinterleaveIntrinsicID(InterleaveFactor),
4157 NewLoad->getType(), NewLoad,
4158 /*FMFSource=*/nullptr, "strided.vec");
4159 }
4160
4161 auto CreateStridedVector = [&InterleaveFactor, &State,
4162 &NewLoad](unsigned Index) -> Value * {
4163 assert(Index < InterleaveFactor && "Illegal group index");
4164 if (State.VF.isScalable())
4165 return State.Builder.CreateExtractValue(NewLoad, Index);
4166
4167 // For fixed length VF, use shuffle to extract the sub-vectors from the
4168 // wide load.
4169 auto StrideMask =
4170 createStrideMask(Index, InterleaveFactor, State.VF.getFixedValue());
4171 return State.Builder.CreateShuffleVector(NewLoad, StrideMask,
4172 "strided.vec");
4173 };
4174
4175 for (unsigned I = 0, J = 0; I < InterleaveFactor; ++I) {
4176 Instruction *Member = Group->getMember(I);
4177
4178 // Skip the gaps in the group.
4179 if (!Member)
4180 continue;
4181
4182 Value *StridedVec = CreateStridedVector(I);
4183
4184 // If this member has different type, cast the result type.
4185 if (Member->getType() != ScalarTy) {
4186 VectorType *OtherVTy = VectorType::get(Member->getType(), State.VF);
4187 StridedVec =
4188 createBitOrPointerCast(State.Builder, StridedVec, OtherVTy, DL);
4189 }
4190
4191 if (Group->isReverse())
4192 StridedVec = State.Builder.CreateVectorReverse(StridedVec, "reverse");
4193
4194 State.set(VPDefs[J], StridedVec);
4195 ++J;
4196 }
4197 return;
4198 }
4199
4200 // The sub vector type for current instruction.
4201 auto *SubVT = VectorType::get(ScalarTy, State.VF);
4202
4203 // Vectorize the interleaved store group.
4204 Value *MaskForGaps =
4205 createBitMaskForGaps(State.Builder, State.VF.getKnownMinValue(), *Group);
4206 assert(((MaskForGaps != nullptr) == needsMaskForGaps()) &&
4207 "Mismatch between NeedsMaskForGaps and MaskForGaps");
4208 ArrayRef<VPValue *> StoredValues = getStoredValues();
4209 // Collect the stored vector from each member.
4210 SmallVector<Value *, 4> StoredVecs;
4211 unsigned StoredIdx = 0;
4212 for (unsigned i = 0; i < InterleaveFactor; i++) {
4213 assert((Group->getMember(i) || MaskForGaps) &&
4214 "Fail to get a member from an interleaved store group");
4215 Instruction *Member = Group->getMember(i);
4216
4217 // Skip the gaps in the group.
4218 if (!Member) {
4219 Value *Undef = PoisonValue::get(SubVT);
4220 StoredVecs.push_back(Undef);
4221 continue;
4222 }
4223
4224 Value *StoredVec = State.get(StoredValues[StoredIdx]);
4225 ++StoredIdx;
4226
4227 if (Group->isReverse())
4228 StoredVec = State.Builder.CreateVectorReverse(StoredVec, "reverse");
4229
4230 // If this member has different type, cast it to a unified type.
4231
4232 if (StoredVec->getType() != SubVT)
4233 StoredVec = createBitOrPointerCast(State.Builder, StoredVec, SubVT, DL);
4234
4235 StoredVecs.push_back(StoredVec);
4236 }
4237
4238 // Interleave all the smaller vectors into one wider vector.
4239 Value *IVec = interleaveVectors(State.Builder, StoredVecs, "interleaved.vec");
4240 Instruction *NewStoreInstr;
4241 if (BlockInMask || MaskForGaps) {
4242 Value *GroupMask = CreateGroupMask(MaskForGaps);
4243 NewStoreInstr = State.Builder.CreateMaskedStore(
4244 IVec, ResAddr, Group->getAlign(), GroupMask);
4245 } else
4246 NewStoreInstr =
4247 State.Builder.CreateAlignedStore(IVec, ResAddr, Group->getAlign());
4248
4249 applyMetadata(*NewStoreInstr);
4250 // TODO: Also manage existing metadata using VPIRMetadata.
4251 Group->addMetadata(NewStoreInstr);
4252}
4253
4254#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4256 VPSlotTracker &SlotTracker) const {
4258 O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << " at ";
4259 IG->getInsertPos()->printAsOperand(O, false);
4260 O << ", ";
4262 VPValue *Mask = getMask();
4263 if (Mask) {
4264 O << ", ";
4265 Mask->printAsOperand(O, SlotTracker);
4266 }
4267
4268 unsigned OpIdx = 0;
4269 for (unsigned i = 0; i < IG->getFactor(); ++i) {
4270 if (!IG->getMember(i))
4271 continue;
4272 if (getNumStoreOperands() > 0) {
4273 O << "\n" << Indent << " store ";
4275 O << " to index " << i;
4276 } else {
4277 O << "\n" << Indent << " ";
4279 O << " = load from index " << i;
4280 }
4281 ++OpIdx;
4282 }
4283}
4284#endif
4285
4287 assert(!State.Lane && "Interleave group being replicated.");
4288 assert(State.VF.isScalable() &&
4289 "Only support scalable VF for EVL tail-folding.");
4291 "Masking gaps for scalable vectors is not yet supported.");
4293 Instruction *Instr = Group->getInsertPos();
4294
4295 // Prepare for the vector type of the interleaved load/store.
4296 Type *ScalarTy = getLoadStoreType(Instr);
4297 unsigned InterleaveFactor = Group->getFactor();
4298 assert(InterleaveFactor <= 8 &&
4299 "Unsupported deinterleave/interleave factor for scalable vectors");
4300 ElementCount WideVF = State.VF * InterleaveFactor;
4301 auto *VecTy = VectorType::get(ScalarTy, WideVF);
4302
4303 VPValue *Addr = getAddr();
4304 Value *ResAddr = State.get(Addr, VPLane(0));
4305 Value *EVL = State.get(getEVL(), VPLane(0));
4306 Value *InterleaveEVL = State.Builder.CreateMul(
4307 EVL, ConstantInt::get(EVL->getType(), InterleaveFactor), "interleave.evl",
4308 /* NUW= */ true, /* NSW= */ true);
4309 LLVMContext &Ctx = State.Builder.getContext();
4310
4311 Value *GroupMask = nullptr;
4312 if (VPValue *BlockInMask = getMask()) {
4313 SmallVector<Value *> Ops(InterleaveFactor, State.get(BlockInMask));
4314 GroupMask = interleaveVectors(State.Builder, Ops, "interleaved.mask");
4315 } else {
4316 GroupMask =
4317 State.Builder.CreateVectorSplat(WideVF, State.Builder.getTrue());
4318 }
4319
4320 // Vectorize the interleaved load group.
4321 if (isa<LoadInst>(Instr)) {
4322 CallInst *NewLoad = State.Builder.CreateIntrinsic(
4323 VecTy, Intrinsic::vp_load, {ResAddr, GroupMask, InterleaveEVL}, nullptr,
4324 "wide.vp.load");
4325 NewLoad->addParamAttr(0,
4326 Attribute::getWithAlignment(Ctx, Group->getAlign()));
4327
4328 applyMetadata(*NewLoad);
4329 // TODO: Also manage existing metadata using VPIRMetadata.
4330 Group->addMetadata(NewLoad);
4331
4332 // Scalable vectors cannot use arbitrary shufflevectors (only splats),
4333 // so must use intrinsics to deinterleave.
4334 NewLoad = State.Builder.CreateIntrinsic(
4335 Intrinsic::getDeinterleaveIntrinsicID(InterleaveFactor),
4336 NewLoad->getType(), NewLoad,
4337 /*FMFSource=*/nullptr, "strided.vec");
4338
4339 const DataLayout &DL = Instr->getDataLayout();
4340 for (unsigned I = 0, J = 0; I < InterleaveFactor; ++I) {
4341 Instruction *Member = Group->getMember(I);
4342 // Skip the gaps in the group.
4343 if (!Member)
4344 continue;
4345
4346 Value *StridedVec = State.Builder.CreateExtractValue(NewLoad, I);
4347 // If this member has different type, cast the result type.
4348 if (Member->getType() != ScalarTy) {
4349 VectorType *OtherVTy = VectorType::get(Member->getType(), State.VF);
4350 StridedVec =
4351 createBitOrPointerCast(State.Builder, StridedVec, OtherVTy, DL);
4352 }
4353
4354 State.set(getVPValue(J), StridedVec);
4355 ++J;
4356 }
4357 return;
4358 } // End for interleaved load.
4359
4360 // The sub vector type for current instruction.
4361 auto *SubVT = VectorType::get(ScalarTy, State.VF);
4362 // Vectorize the interleaved store group.
4363 ArrayRef<VPValue *> StoredValues = getStoredValues();
4364 // Collect the stored vector from each member.
4365 SmallVector<Value *, 4> StoredVecs;
4366 const DataLayout &DL = Instr->getDataLayout();
4367 for (unsigned I = 0, StoredIdx = 0; I < InterleaveFactor; I++) {
4368 Instruction *Member = Group->getMember(I);
4369 // Skip the gaps in the group.
4370 if (!Member) {
4371 StoredVecs.push_back(PoisonValue::get(SubVT));
4372 continue;
4373 }
4374
4375 Value *StoredVec = State.get(StoredValues[StoredIdx]);
4376 // If this member has different type, cast it to a unified type.
4377 if (StoredVec->getType() != SubVT)
4378 StoredVec = createBitOrPointerCast(State.Builder, StoredVec, SubVT, DL);
4379
4380 StoredVecs.push_back(StoredVec);
4381 ++StoredIdx;
4382 }
4383
4384 // Interleave all the smaller vectors into one wider vector.
4385 Value *IVec = interleaveVectors(State.Builder, StoredVecs, "interleaved.vec");
4386 CallInst *NewStore =
4387 State.Builder.CreateIntrinsic(Type::getVoidTy(Ctx), Intrinsic::vp_store,
4388 {IVec, ResAddr, GroupMask, InterleaveEVL});
4389 NewStore->addParamAttr(1,
4390 Attribute::getWithAlignment(Ctx, Group->getAlign()));
4391
4392 applyMetadata(*NewStore);
4393 // TODO: Also manage existing metadata using VPIRMetadata.
4394 Group->addMetadata(NewStore);
4395}
4396
4397#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4399 VPSlotTracker &SlotTracker) const {
4401 O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << " at ";
4402 IG->getInsertPos()->printAsOperand(O, false);
4403 O << ", ";
4405 O << ", ";
4407 if (VPValue *Mask = getMask()) {
4408 O << ", ";
4409 Mask->printAsOperand(O, SlotTracker);
4410 }
4411
4412 unsigned OpIdx = 0;
4413 for (unsigned i = 0; i < IG->getFactor(); ++i) {
4414 if (!IG->getMember(i))
4415 continue;
4416 if (getNumStoreOperands() > 0) {
4417 O << "\n" << Indent << " vp.store ";
4419 O << " to index " << i;
4420 } else {
4421 O << "\n" << Indent << " ";
4423 O << " = vp.load from index " << i;
4424 }
4425 ++OpIdx;
4426 }
4427}
4428#endif
4429
4431 VPCostContext &Ctx) const {
4432 Instruction *InsertPos = getInsertPos();
4433 // Find the VPValue index of the interleave group. We need to skip gaps.
4434 unsigned InsertPosIdx = 0;
4435 for (unsigned Idx = 0; IG->getFactor(); ++Idx)
4436 if (auto *Member = IG->getMember(Idx)) {
4437 if (Member == InsertPos)
4438 break;
4439 InsertPosIdx++;
4440 }
4441 Type *ValTy = Ctx.Types.inferScalarType(
4442 getNumDefinedValues() > 0 ? getVPValue(InsertPosIdx)
4443 : getStoredValues()[InsertPosIdx]);
4444 auto *VectorTy = cast<VectorType>(toVectorTy(ValTy, VF));
4445 unsigned AS = cast<PointerType>(Ctx.Types.inferScalarType(getAddr()))
4446 ->getAddressSpace();
4447
4448 unsigned InterleaveFactor = IG->getFactor();
4449 auto *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
4450
4451 // Holds the indices of existing members in the interleaved group.
4453 for (unsigned IF = 0; IF < InterleaveFactor; IF++)
4454 if (IG->getMember(IF))
4455 Indices.push_back(IF);
4456
4457 // Calculate the cost of the whole interleaved group.
4458 InstructionCost Cost = Ctx.TTI.getInterleavedMemoryOpCost(
4459 InsertPos->getOpcode(), WideVecTy, IG->getFactor(), Indices,
4460 IG->getAlign(), AS, Ctx.CostKind, getMask(), NeedsMaskForGaps);
4461
4462 if (!IG->isReverse())
4463 return Cost;
4464
4465 return Cost + IG->getNumMembers() *
4466 Ctx.TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
4467 VectorTy, VectorTy, {}, Ctx.CostKind,
4468 0);
4469}
4470
4471#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4473 VPSlotTracker &SlotTracker) const {
4474 O << Indent << "EMIT ";
4476 O << " = CANONICAL-INDUCTION ";
4478}
4479#endif
4480
4482 return vputils::onlyScalarValuesUsed(this) &&
4483 (!IsScalable || vputils::onlyFirstLaneUsed(this));
4484}
4485
4486#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4488 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
4489 assert((getNumOperands() == 3 || getNumOperands() == 5) &&
4490 "unexpected number of operands");
4491 O << Indent << "EMIT ";
4493 O << " = WIDEN-POINTER-INDUCTION ";
4495 O << ", ";
4497 O << ", ";
4499 if (getNumOperands() == 5) {
4500 O << ", ";
4502 O << ", ";
4504 }
4505}
4506
4508 VPSlotTracker &SlotTracker) const {
4509 O << Indent << "EMIT ";
4511 O << " = EXPAND SCEV " << *Expr;
4512}
4513#endif
4514
4516 Value *CanonicalIV = State.get(getOperand(0), /*IsScalar*/ true);
4517 Type *STy = CanonicalIV->getType();
4518 IRBuilder<> Builder(State.CFG.PrevBB->getTerminator());
4519 ElementCount VF = State.VF;
4520 Value *VStart = VF.isScalar()
4521 ? CanonicalIV
4522 : Builder.CreateVectorSplat(VF, CanonicalIV, "broadcast");
4523 Value *VStep = createStepForVF(Builder, STy, VF, getUnrollPart(*this));
4524 if (VF.isVector()) {
4525 VStep = Builder.CreateVectorSplat(VF, VStep);
4526 VStep =
4527 Builder.CreateAdd(VStep, Builder.CreateStepVector(VStep->getType()));
4528 }
4529 Value *CanonicalVectorIV = Builder.CreateAdd(VStart, VStep, "vec.iv");
4530 State.set(this, CanonicalVectorIV);
4531}
4532
4533#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4535 VPSlotTracker &SlotTracker) const {
4536 O << Indent << "EMIT ";
4538 O << " = WIDEN-CANONICAL-INDUCTION ";
4540}
4541#endif
4542
4544 auto &Builder = State.Builder;
4545 // Create a vector from the initial value.
4546 auto *VectorInit = getStartValue()->getLiveInIRValue();
4547
4548 Type *VecTy = State.VF.isScalar()
4549 ? VectorInit->getType()
4550 : VectorType::get(VectorInit->getType(), State.VF);
4551
4552 BasicBlock *VectorPH =
4553 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
4554 if (State.VF.isVector()) {
4555 auto *IdxTy = Builder.getInt32Ty();
4556 auto *One = ConstantInt::get(IdxTy, 1);
4557 IRBuilder<>::InsertPointGuard Guard(Builder);
4558 Builder.SetInsertPoint(VectorPH->getTerminator());
4559 auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, State.VF);
4560 auto *LastIdx = Builder.CreateSub(RuntimeVF, One);
4561 VectorInit = Builder.CreateInsertElement(
4562 PoisonValue::get(VecTy), VectorInit, LastIdx, "vector.recur.init");
4563 }
4564
4565 // Create a phi node for the new recurrence.
4566 PHINode *Phi = PHINode::Create(VecTy, 2, "vector.recur");
4567 Phi->insertBefore(State.CFG.PrevBB->getFirstInsertionPt());
4568 Phi->addIncoming(VectorInit, VectorPH);
4569 State.set(this, Phi);
4570}
4571
4574 VPCostContext &Ctx) const {
4575 if (VF.isScalar())
4576 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
4577
4578 return 0;
4579}
4580
4581#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4583 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
4584 O << Indent << "FIRST-ORDER-RECURRENCE-PHI ";
4586 O << " = phi ";
4588}
4589#endif
4590
4592 // Reductions do not have to start at zero. They can start with
4593 // any loop invariant values.
4594 VPValue *StartVPV = getStartValue();
4595
4596 // In order to support recurrences we need to be able to vectorize Phi nodes.
4597 // Phi nodes have cycles, so we need to vectorize them in two stages. This is
4598 // stage #1: We create a new vector PHI node with no incoming edges. We'll use
4599 // this value when we vectorize all of the instructions that use the PHI.
4600 BasicBlock *VectorPH =
4601 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
4602 bool ScalarPHI = State.VF.isScalar() || isInLoop();
4603 Value *StartV = State.get(StartVPV, ScalarPHI);
4604 Type *VecTy = StartV->getType();
4605
4606 BasicBlock *HeaderBB = State.CFG.PrevBB;
4607 assert(State.CurrentParentLoop->getHeader() == HeaderBB &&
4608 "recipe must be in the vector loop header");
4609 auto *Phi = PHINode::Create(VecTy, 2, "vec.phi");
4610 Phi->insertBefore(HeaderBB->getFirstInsertionPt());
4611 State.set(this, Phi, isInLoop());
4612
4613 Phi->addIncoming(StartV, VectorPH);
4614}
4615
4616#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4618 VPSlotTracker &SlotTracker) const {
4619 O << Indent << "WIDEN-REDUCTION-PHI ";
4620
4622 O << " = phi";
4623 printFlags(O);
4625 if (getVFScaleFactor() > 1)
4626 O << " (VF scaled by 1/" << getVFScaleFactor() << ")";
4627}
4628#endif
4629
4631 Value *Op0 = State.get(getOperand(0));
4632 Type *VecTy = Op0->getType();
4633 Instruction *VecPhi = State.Builder.CreatePHI(VecTy, 2, Name);
4634 State.set(this, VecPhi);
4635}
4636
4638 VPCostContext &Ctx) const {
4639 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
4640}
4641
4642#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4644 VPSlotTracker &SlotTracker) const {
4645 O << Indent << "WIDEN-PHI ";
4646
4648 O << " = phi ";
4650}
4651#endif
4652
4654 BasicBlock *VectorPH =
4655 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
4656 Value *StartMask = State.get(getOperand(0));
4657 PHINode *Phi =
4658 State.Builder.CreatePHI(StartMask->getType(), 2, "active.lane.mask");
4659 Phi->addIncoming(StartMask, VectorPH);
4660 State.set(this, Phi);
4661}
4662
4663#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4665 VPSlotTracker &SlotTracker) const {
4666 O << Indent << "ACTIVE-LANE-MASK-PHI ";
4667
4669 O << " = phi ";
4671}
4672#endif
4673
4674#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4676 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
4677 O << Indent << "CURRENT-ITERATION-PHI ";
4678
4680 O << " = phi ";
4682}
4683#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 const Function * getParent(const Value *V)
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Value * getPointer(Value *Ptr)
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
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:235
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 const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
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...
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
static DebugLoc getUnknown()
Definition DebugLoc.h:161
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:23
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:93
bool noSignedZeros() const
Definition FMF.h:70
bool noInfs() const
Definition FMF.h:69
void setAllowReciprocal(bool B=true)
Definition FMF.h:90
bool allowReciprocal() const
Definition FMF.h:71
void setNoSignedZeros(bool B=true)
Definition FMF.h:87
bool allowReassoc() const
Flag queries.
Definition FMF.h:67
bool approxFunc() const
Definition FMF.h:73
void setNoNaNs(bool B=true)
Definition FMF.h:81
void setAllowReassoc(bool B=true)
Flag setters.
Definition FMF.h:78
bool noNaNs() const
Definition FMF.h:68
void setApproxFunc(bool B=true)
Definition FMF.h:96
void setNoInfs(bool B=true)
Definition FMF.h:84
bool allowContract() const
Definition FMF.h:72
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:669
bool doesNotThrow() const
Determine if the function cannot unwind.
Definition Function.h:602
Type * getReturnType() const
Returns the type of the ret val.
Definition Function.h:216
static GEPNoWrapFlags none()
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:2561
IntegerType * getInt1Ty()
Fetch the type representing a single bit.
Definition IRBuilder.h:546
Value * CreateInsertValue(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &Name="")
Definition IRBuilder.h:2615
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2549
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 * CreateSelectFMF(Value *C, Value *True, Value *False, FMFSource FMFSource, const Twine &Name="", Instruction *MDFrom=nullptr)
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:2608
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:2627
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
Definition IRBuilder.h:561
Value * CreatePtrAdd(Value *Ptr, Value *Offset, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Definition IRBuilder.h:2025
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:566
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:2312
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:1728
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:2442
Value * CreateNot(Value *V, const Twine &Name="")
Definition IRBuilder.h:1812
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2308
Value * CreateCountTrailingZeroElems(Type *ResTy, Value *Mask, bool ZeroIsPoison=true, const Twine &Name="")
Create a call to llvm.experimental_cttz_elts.
Definition IRBuilder.h:1137
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1423
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:1200
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNeg=false)
Definition IRBuilder.h:2054
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1406
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:1711
Value * CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2320
Value * CreateLogicalOr(Value *Cond1, Value *Cond2, const Twine &Name="", Instruction *MDFrom=nullptr)
Definition IRBuilder.h:1736
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2418
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
Definition IRBuilder.h:1576
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1440
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2787
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.
VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph.
Definition VPlan.h:4182
RecipeListTy & getRecipeList()
Returns a reference to the list of recipes.
Definition VPlan.h:4235
iterator end()
Definition VPlan.h:4219
void insert(VPRecipeBase *Recipe, iterator InsertPt)
Definition VPlan.h:4248
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:2751
unsigned getNumIncomingValues() const
Return the number of incoming values, taking into account when normalized the first incoming value wi...
Definition VPlan.h:2746
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
bool isNormalized() const
A normalized blend is one that has an odd number of operands, whereby the first operand does not have...
Definition VPlan.h:2742
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:177
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.
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:3974
VPValue * getStepValue() const
Definition VPlan.h:3975
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:2264
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:2004
BasicBlock * getIRBasicBlock() const
Definition VPlan.h:4359
Class to record and manage LLVM IR flags.
Definition VPlan.h:670
FastMathFlagsTy FMFs
Definition VPlan.h:758
ReductionFlagsTy ReductionFlags
Definition VPlan.h:760
LLVM_ABI_FOR_TEST bool hasRequiredFlagsForOpcode(unsigned Opcode) const
Returns true if Opcode has its required flags set.
LLVM_ABI_FOR_TEST bool flagsValidForOpcode(unsigned Opcode) const
Returns true if the set flags are valid for Opcode.
static VPIRFlags getDefaultFlags(unsigned Opcode)
Returns default flags for Opcode for opcodes that support it, asserts otherwise.
WrapFlagsTy WrapFlags
Definition VPlan.h:752
CmpInst::Predicate CmpPredicate
Definition VPlan.h:751
void printFlags(raw_ostream &O) const
GEPNoWrapFlags GEPFlags
Definition VPlan.h:756
bool hasFastMathFlags() const
Returns true if the recipe has fast-math flags.
Definition VPlan.h:947
LLVM_ABI_FOR_TEST FastMathFlags getFastMathFlags() const
bool isReductionOrdered() const
Definition VPlan.h:997
TruncFlagsTy TruncFlags
Definition VPlan.h:753
CmpInst::Predicate getPredicate() const
Definition VPlan.h:924
ExactFlagsTy ExactFlags
Definition VPlan.h:755
bool hasNoSignedWrap() const
Definition VPlan.h:974
void intersectFlags(const VPIRFlags &Other)
Only keep flags also present in Other.
GEPNoWrapFlags getGEPNoWrapFlags() const
Definition VPlan.h:939
bool hasPredicate() const
Returns true if the recipe has a comparison predicate.
Definition VPlan.h:942
DisjointFlagsTy DisjointFlags
Definition VPlan.h:754
unsigned AllFlags
Definition VPlan.h:761
bool hasNoUnsignedWrap() const
Definition VPlan.h:963
FCmpFlagsTy FCmpFlags
Definition VPlan.h:759
NonNegFlagsTy NonNegFlags
Definition VPlan.h:757
bool isReductionInLoop() const
Definition VPlan.h:1003
void applyFlags(Instruction &I) const
Apply the IR flags to I.
Definition VPlan.h:882
RecurKind getRecurKind() const
Definition VPlan.h:991
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:1626
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.
This is a concrete Recipe that models a single VPlan-level instruction.
Definition VPlan.h:1160
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this 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:1269
@ ExtractLane
Extracts a single lane (first operand) from a set of vector operands.
Definition VPlan.h:1262
@ ExitingIVValue
Compute the exiting value of a wide induction after vectorization, that is the value of the last lane...
Definition VPlan.h:1276
@ ComputeAnyOfResult
Compute the final result of a AnyOf reduction with select(cmp(),x,y), where one of (x,...
Definition VPlan.h:1207
@ WideIVStep
Scale the first operand (vector step) by the second operand (scalar-step).
Definition VPlan.h:1252
@ ResumeForEpilogue
Explicit user for the resume phi of the canonical induction in the main VPlan, used by the epilogue v...
Definition VPlan.h:1265
@ Unpack
Extracts all lanes from its (non-scalable) vector operand.
Definition VPlan.h:1204
@ ReductionStartVector
Start vector for reductions with 3 operands: the original start value, the identity value for the red...
Definition VPlan.h:1256
@ BuildVector
Creates a fixed-width vector containing all operands.
Definition VPlan.h:1199
@ BuildStructVector
Given operands of (the same) struct type, creates a struct of fixed- width vectors each containing a ...
Definition VPlan.h:1196
@ VScale
Returns the value for vscale.
Definition VPlan.h:1272
@ CanonicalIVIncrementForPart
Definition VPlan.h:1180
bool hasResult() const
Definition VPlan.h:1354
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:1433
unsigned getOpcode() const
Definition VPlan.h:1338
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...
unsigned getNumOperandsForOpcode() const
Return the number of operands determined by the opcode of the VPInstruction, excluding mask.
bool isMasked() const
Returns true if the VPInstruction has a mask operand.
Definition VPlan.h:1378
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:2863
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this recipe.
Instruction * getInsertPos() const
Definition VPlan.h:2867
const InterleaveGroup< Instruction > * getInterleaveGroup() const
Definition VPlan.h:2865
VPValue * getMask() const
Return the mask used by this recipe.
Definition VPlan.h:2857
ArrayRef< VPValue * > getStoredValues() const
Return the VPValues stored by this interleave group.
Definition VPlan.h:2886
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition VPlan.h:2851
VPValue * getEVL() const
The VPValue of the explicit vector length.
Definition VPlan.h:2960
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:2973
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:2923
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.
VPValue * getIncomingValueForBlock(const VPBasicBlock *VPBB) const
Returns the incoming value for VPBB. VPBB must be an incoming block.
virtual unsigned getNumIncoming() const
Returns the number of incoming values, also number of incoming blocks.
Definition VPlan.h:1540
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:4326
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:1565
VPValue * getIncomingValue(unsigned Idx) const
Returns the incoming VPValue with index Idx.
Definition VPlan.h:1525
void printPhiOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const
Print the recipe.
void setIncomingValueForBlock(const VPBasicBlock *VPBB, VPValue *V) const
Sets the incoming value for VPBB to V.
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:4487
LLVM_ABI_FOR_TEST void dump() const
Dump the recipe to stderr (for debugging).
Definition VPlan.cpp:116
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:3121
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:2666
bool isInLoop() const
Returns true if the phi is part of an in-loop reduction.
Definition VPlan.h:2690
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:3063
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:3074
VPValue * getCondOp() const
The VPValue of the condition for the block.
Definition VPlan.h:3076
RecurKind getRecurrenceKind() const
Return the recurrence kind for the in-loop reduction.
Definition VPlan.h:3059
bool isPartialReduction() const
Returns true if the reduction outputs a vector with a scaled down VF.
Definition VPlan.h:3065
VPValue * getChainOp() const
The VPValue of the scalar Chain being accumulated.
Definition VPlan.h:3072
bool isInLoop() const
Returns true if the reduction is in-loop.
Definition VPlan.h:3067
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:4370
bool isReplicator() const
An indicator whether this region is to generate multiple replicated instances of output IR correspond...
Definition VPlan.h:4438
VPReplicateRecipe replicates a given instruction producing multiple scalar copies of the original sca...
Definition VPlan.h:3143
void execute(VPTransformState &State) override
Generate replicas of the desired Ingredient.
bool isSingleScalar() const
Definition VPlan.h:3184
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:3213
bool shouldPack() const
Returns true if the recipe is used by a widened recipe via an intervening VPPredInstPHIRecipe.
VPValue * getStepValue() const
Definition VPlan.h:4040
VPValue * getStartIndex() const
Return the StartIndex, or null if known to be zero, valid only after unrolling.
Definition VPlan.h:4048
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:656
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.
An analysis for type-inference for 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:1093
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:1446
operand_range operands()
Definition VPlanValue.h:326
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:137
bool isDefinedOutsideLoopRegions() const
Returns true if the VPValue is defined outside any loop.
Definition VPlan.cpp:1400
VPRecipeBase * getDefiningRecipe()
Returns the recipe defining this VPValue or nullptr if it is not defined by a recipe,...
Definition VPlan.cpp:127
void printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const
Definition VPlan.cpp:1442
Value * getUnderlyingValue() const
Return the underlying Value attached to this VPValue.
Definition VPlanValue.h:71
void replaceAllUsesWith(VPValue *New)
Definition VPlan.cpp:1403
VPValue * getVFValue() const
Definition VPlan.h:2102
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:2099
int64_t getStride() const
Definition VPlan.h:2100
VPValue * getPointer() const
Definition VPlan.h:2101
void materializeOffset(unsigned Part=0)
Adds the offset operand to the recipe.
Type * getSourceElementType() const
Definition VPlan.h:2171
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:1959
Function * getCalledScalarFunction() const
Definition VPlan.h:1955
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:1808
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:2056
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:2327
VPValue * getStepValue()
Returns the step value of the induction.
Definition VPlan.h:2330
VPIRValue * getStartValue() const
Returns the start value of the induction.
Definition VPlan.h:2428
TruncInst * getTruncInst()
Returns the first defined value as TruncInst, if it is one or nullptr otherwise.
Definition VPlan.h:2443
Type * getScalarType() const
Returns the scalar type of the induction.
Definition VPlan.h:2452
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:1890
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:1893
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:3468
bool Reverse
Whether the consecutive accessed addresses are in reverse order.
Definition VPlan.h:3465
bool isConsecutive() const
Return whether the loaded-from / stored-to addresses are consecutive.
Definition VPlan.h:3508
Instruction & Ingredient
Definition VPlan.h:3456
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:3462
VPValue * getMask() const
Return the mask used by this recipe.
Definition VPlan.h:3522
Align Alignment
Alignment information for this memory access.
Definition VPlan.h:3459
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition VPlan.h:3515
bool isReverse() const
Return whether the consecutive loaded/stored addresses are in reverse order.
Definition VPlan.h:3512
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.
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition VPlan.h:4500
LLVM_ABI_FOR_TEST VPRegionBlock * getVectorLoopRegion()
Returns the VPRegionBlock of the vector loop.
Definition VPlan.cpp:1033
VPIRBasicBlock * getScalarHeader() const
Return the VPIRBasicBlock wrapping the header of the scalar loop.
Definition VPlan.h:4636
VPIRValue * getConstantInt(Type *Ty, uint64_t Val, bool IsSigned=false)
Return a VPIRValue wrapping a ConstantInt with the given type and value.
Definition VPlan.h:4778
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:839
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.
class_match< CmpInst > m_Cmp()
Matches any compare instruction and ignore it.
LogicalOp_match< LHS, RHS, Instruction::And, true > m_c_LogicalAnd(const LHS &L, const RHS &R)
Matches L && R with LHS and RHS in either order.
LogicalOp_match< LHS, RHS, Instruction::Or, true > m_c_LogicalOr(const LHS &L, const RHS &R)
Matches L || R with LHS and RHS in either order.
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:831
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:1739
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:2554
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:2208
void interleaveComma(const Container &c, StreamT &os, UnaryFunctor each_fn)
Definition STLExtras.h:2313
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:1746
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:408
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:1753
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:1947
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:1684
PHINode & getIRPhi()
Definition VPlan.h:1692
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:1047
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:1048
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:279
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:3600
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:3684
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:3687
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:3647