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