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