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)
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 }
1135
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);
1324}
1325
1328 return false;
1329 switch (getOpcode()) {
1330 case Instruction::GetElementPtr:
1331 case Instruction::ExtractElement:
1332 case Instruction::Freeze:
1333 case Instruction::FCmp:
1334 case Instruction::ICmp:
1335 case Instruction::Select:
1336 case Instruction::PHI:
1360 case VPInstruction::Not:
1369 return false;
1370 default:
1371 return true;
1372 }
1373}
1374
1376 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
1378 return vputils::onlyFirstLaneUsed(this);
1379
1380 switch (getOpcode()) {
1381 default:
1382 return false;
1383 case Instruction::ExtractElement:
1384 return Op == getOperand(1);
1385 case Instruction::PHI:
1386 return true;
1387 case Instruction::FCmp:
1388 case Instruction::ICmp:
1389 case Instruction::Select:
1390 case Instruction::Or:
1391 case Instruction::Freeze:
1392 case VPInstruction::Not:
1393 // TODO: Cover additional opcodes.
1394 return vputils::onlyFirstLaneUsed(this);
1395 case Instruction::Load:
1404 return true;
1407 // Before replicating by VF, Build(Struct)Vector uses all lanes of the
1408 // operand, after replicating its operands only the first lane is used.
1409 // Before replicating, it will have only a single operand.
1410 return getNumOperands() > 1;
1412 return Op == getOperand(0) || vputils::onlyFirstLaneUsed(this);
1414 // WidePtrAdd supports scalar and vector base addresses.
1415 return false;
1417 return Op == getOperand(0) || Op == getOperand(1);
1420 return Op == getOperand(0);
1421 };
1422 llvm_unreachable("switch should return");
1423}
1424
1426 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
1428 return vputils::onlyFirstPartUsed(this);
1429
1430 switch (getOpcode()) {
1431 default:
1432 return false;
1433 case Instruction::FCmp:
1434 case Instruction::ICmp:
1435 case Instruction::Select:
1436 return vputils::onlyFirstPartUsed(this);
1441 return true;
1442 };
1443 llvm_unreachable("switch should return");
1444}
1445
1446#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1448 VPSlotTracker SlotTracker(getParent()->getPlan());
1450}
1451
1453 VPSlotTracker &SlotTracker) const {
1454 O << Indent << "EMIT" << (isSingleScalar() ? "-SCALAR" : "") << " ";
1455
1456 if (hasResult()) {
1458 O << " = ";
1459 }
1460
1461 switch (getOpcode()) {
1462 case VPInstruction::Not:
1463 O << "not";
1464 break;
1466 O << "combined load";
1467 break;
1469 O << "combined store";
1470 break;
1472 O << "active lane mask";
1473 break;
1475 O << "EXPLICIT-VECTOR-LENGTH";
1476 break;
1478 O << "first-order splice";
1479 break;
1481 O << "branch-on-cond";
1482 break;
1484 O << "branch-on-two-conds";
1485 break;
1487 O << "TC > VF ? TC - VF : 0";
1488 break;
1490 O << "VF * Part +";
1491 break;
1493 O << "branch-on-count";
1494 break;
1496 O << "broadcast";
1497 break;
1499 O << "buildstructvector";
1500 break;
1502 O << "buildvector";
1503 break;
1505 O << "exiting-iv-value";
1506 break;
1508 O << "masked-cond";
1509 break;
1511 O << "extract-lane";
1512 break;
1514 O << "extract-last-lane";
1515 break;
1517 O << "extract-last-part";
1518 break;
1520 O << "extract-penultimate-element";
1521 break;
1523 O << "compute-anyof-result";
1524 break;
1526 O << "compute-reduction-result";
1527 break;
1529 O << "logical-and";
1530 break;
1532 O << "logical-or";
1533 break;
1535 O << "ptradd";
1536 break;
1538 O << "wide-ptradd";
1539 break;
1541 O << "any-of";
1542 break;
1544 O << "first-active-lane";
1545 break;
1547 O << "last-active-lane";
1548 break;
1550 O << "reduction-start-vector";
1551 break;
1553 O << "resume-for-epilogue";
1554 break;
1556 O << "reverse";
1557 break;
1559 O << "unpack";
1560 break;
1562 O << "extract-last-active";
1563 break;
1564 default:
1566 }
1567
1568 printFlags(O);
1570}
1571#endif
1572
1574 State.setDebugLocFrom(getDebugLoc());
1575 if (isScalarCast()) {
1576 Value *Op = State.get(getOperand(0), VPLane(0));
1577 Value *Cast = State.Builder.CreateCast(Instruction::CastOps(getOpcode()),
1578 Op, ResultTy);
1579 State.set(this, Cast, VPLane(0));
1580 return;
1581 }
1582 switch (getOpcode()) {
1584 Value *StepVector =
1585 State.Builder.CreateStepVector(VectorType::get(ResultTy, State.VF));
1586 State.set(this, StepVector);
1587 break;
1588 }
1589 case VPInstruction::VScale: {
1590 Value *VScale = State.Builder.CreateVScale(ResultTy);
1591 State.set(this, VScale, true);
1592 break;
1593 }
1594
1595 default:
1596 llvm_unreachable("opcode not implemented yet");
1597 }
1598}
1599
1600#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1602 VPSlotTracker &SlotTracker) const {
1603 O << Indent << "EMIT" << (isSingleScalar() ? "-SCALAR" : "") << " ";
1605 O << " = ";
1606
1607 switch (getOpcode()) {
1609 O << "wide-iv-step ";
1611 break;
1613 O << "step-vector " << *ResultTy;
1614 break;
1616 O << "vscale " << *ResultTy;
1617 break;
1618 case Instruction::Load:
1619 O << "load ";
1621 break;
1622 default:
1623 assert(Instruction::isCast(getOpcode()) && "unhandled opcode");
1626 O << " to " << *ResultTy;
1627 }
1628}
1629#endif
1630
1632 State.setDebugLocFrom(getDebugLoc());
1633 PHINode *NewPhi = State.Builder.CreatePHI(
1634 State.TypeAnalysis.inferScalarType(this), 2, getName());
1635 unsigned NumIncoming = getNumIncoming();
1636 if (getParent() != getParent()->getPlan()->getScalarPreheader()) {
1637 // TODO: Fixup all incoming values of header phis once recipes defining them
1638 // are introduced.
1639 NumIncoming = 1;
1640 }
1641 for (unsigned Idx = 0; Idx != NumIncoming; ++Idx) {
1642 Value *IncV = State.get(getIncomingValue(Idx), VPLane(0));
1643 BasicBlock *PredBB = State.CFG.VPBB2IRBB.at(getIncomingBlock(Idx));
1644 NewPhi->addIncoming(IncV, PredBB);
1645 }
1646 State.set(this, NewPhi, VPLane(0));
1647}
1648
1649#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1650void VPPhi::printRecipe(raw_ostream &O, const Twine &Indent,
1651 VPSlotTracker &SlotTracker) const {
1652 O << Indent << "EMIT" << (isSingleScalar() ? "-SCALAR" : "") << " ";
1654 O << " = phi";
1655 printFlags(O);
1657}
1658#endif
1659
1660VPIRInstruction *VPIRInstruction ::create(Instruction &I) {
1661 if (auto *Phi = dyn_cast<PHINode>(&I))
1662 return new VPIRPhi(*Phi);
1663 return new VPIRInstruction(I);
1664}
1665
1667 assert(!isa<VPIRPhi>(this) && getNumOperands() == 0 &&
1668 "PHINodes must be handled by VPIRPhi");
1669 // Advance the insert point after the wrapped IR instruction. This allows
1670 // interleaving VPIRInstructions and other recipes.
1671 State.Builder.SetInsertPoint(I.getParent(), std::next(I.getIterator()));
1672}
1673
1675 VPCostContext &Ctx) const {
1676 // The recipe wraps an existing IR instruction on the border of VPlan's scope,
1677 // hence it does not contribute to the cost-modeling for the VPlan.
1678 return 0;
1679}
1680
1681#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1683 VPSlotTracker &SlotTracker) const {
1684 O << Indent << "IR " << I;
1685}
1686#endif
1687
1689 PHINode *Phi = &getIRPhi();
1690 for (const auto &[Idx, Op] : enumerate(operands())) {
1691 VPValue *ExitValue = Op;
1692 auto Lane = vputils::isSingleScalar(ExitValue)
1694 : VPLane::getLastLaneForVF(State.VF);
1695 VPBlockBase *Pred = getParent()->getPredecessors()[Idx];
1696 auto *PredVPBB = Pred->getExitingBasicBlock();
1697 BasicBlock *PredBB = State.CFG.VPBB2IRBB[PredVPBB];
1698 // Set insertion point in PredBB in case an extract needs to be generated.
1699 // TODO: Model extracts explicitly.
1700 State.Builder.SetInsertPoint(PredBB->getTerminator());
1701 Value *V = State.get(ExitValue, VPLane(Lane));
1702 // If there is no existing block for PredBB in the phi, add a new incoming
1703 // value. Otherwise update the existing incoming value for PredBB.
1704 if (Phi->getBasicBlockIndex(PredBB) == -1)
1705 Phi->addIncoming(V, PredBB);
1706 else
1707 Phi->setIncomingValueForBlock(PredBB, V);
1708 }
1709
1710 // Advance the insert point after the wrapped IR instruction. This allows
1711 // interleaving VPIRInstructions and other recipes.
1712 State.Builder.SetInsertPoint(Phi->getParent(), std::next(Phi->getIterator()));
1713}
1714
1716 VPRecipeBase *R = const_cast<VPRecipeBase *>(getAsRecipe());
1717 assert(R->getNumOperands() == R->getParent()->getNumPredecessors() &&
1718 "Number of phi operands must match number of predecessors");
1719 unsigned Position = R->getParent()->getIndexForPredecessor(IncomingBlock);
1720 R->removeOperand(Position);
1721}
1722
1723VPValue *
1725 VPRecipeBase *R = const_cast<VPRecipeBase *>(getAsRecipe());
1726 return getIncomingValue(R->getParent()->getIndexForPredecessor(VPBB));
1727}
1728
1730 VPValue *V) const {
1731 VPRecipeBase *R = const_cast<VPRecipeBase *>(getAsRecipe());
1732 R->setOperand(R->getParent()->getIndexForPredecessor(VPBB), V);
1733}
1734
1735#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1737 VPSlotTracker &SlotTracker) const {
1738 interleaveComma(enumerate(getAsRecipe()->operands()), O,
1739 [this, &O, &SlotTracker](auto Op) {
1740 O << "[ ";
1741 Op.value()->printAsOperand(O, SlotTracker);
1742 O << ", ";
1743 getIncomingBlock(Op.index())->printAsOperand(O);
1744 O << " ]";
1745 });
1746}
1747#endif
1748
1749#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1751 VPSlotTracker &SlotTracker) const {
1753
1754 if (getNumOperands() != 0) {
1755 O << " (extra operand" << (getNumOperands() > 1 ? "s" : "") << ": ";
1757 [&O, &SlotTracker](auto Op) {
1758 std::get<0>(Op)->printAsOperand(O, SlotTracker);
1759 O << " from ";
1760 std::get<1>(Op)->printAsOperand(O);
1761 });
1762 O << ")";
1763 }
1764}
1765#endif
1766
1768 for (const auto &[Kind, Node] : Metadata)
1769 I.setMetadata(Kind, Node);
1770}
1771
1773 SmallVector<std::pair<unsigned, MDNode *>> MetadataIntersection;
1774 for (const auto &[KindA, MDA] : Metadata) {
1775 for (const auto &[KindB, MDB] : Other.Metadata) {
1776 if (KindA == KindB && MDA == MDB) {
1777 MetadataIntersection.emplace_back(KindA, MDA);
1778 break;
1779 }
1780 }
1781 }
1782 Metadata = std::move(MetadataIntersection);
1783}
1784
1785#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1787 const Module *M = SlotTracker.getModule();
1788 if (Metadata.empty() || !M)
1789 return;
1790
1791 ArrayRef<StringRef> MDNames = SlotTracker.getMDNames();
1792 O << " (";
1793 interleaveComma(Metadata, O, [&](const auto &KindNodePair) {
1794 auto [Kind, Node] = KindNodePair;
1795 assert(Kind < MDNames.size() && !MDNames[Kind].empty() &&
1796 "Unexpected unnamed metadata kind");
1797 O << "!" << MDNames[Kind] << " ";
1798 Node->printAsOperand(O, M);
1799 });
1800 O << ")";
1801}
1802#endif
1803
1805 assert(State.VF.isVector() && "not widening");
1806 assert(Variant != nullptr && "Can't create vector function.");
1807
1808 FunctionType *VFTy = Variant->getFunctionType();
1809 // Add return type if intrinsic is overloaded on it.
1811 for (const auto &I : enumerate(args())) {
1812 Value *Arg;
1813 // Some vectorized function variants may also take a scalar argument,
1814 // e.g. linear parameters for pointers. This needs to be the scalar value
1815 // from the start of the respective part when interleaving.
1816 if (!VFTy->getParamType(I.index())->isVectorTy())
1817 Arg = State.get(I.value(), VPLane(0));
1818 else
1819 Arg = State.get(I.value(), usesFirstLaneOnly(I.value()));
1820 Args.push_back(Arg);
1821 }
1822
1825 if (CI)
1826 CI->getOperandBundlesAsDefs(OpBundles);
1827
1828 CallInst *V = State.Builder.CreateCall(Variant, Args, OpBundles);
1829 applyFlags(*V);
1830 applyMetadata(*V);
1831 V->setCallingConv(Variant->getCallingConv());
1832
1833 if (!V->getType()->isVoidTy())
1834 State.set(this, V);
1835}
1836
1838 VPCostContext &Ctx) const {
1839 return Ctx.TTI.getCallInstrCost(nullptr, Variant->getReturnType(),
1840 Variant->getFunctionType()->params(),
1841 Ctx.CostKind);
1842}
1843
1844#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1846 VPSlotTracker &SlotTracker) const {
1847 O << Indent << "WIDEN-CALL ";
1848
1849 Function *CalledFn = getCalledScalarFunction();
1850 if (CalledFn->getReturnType()->isVoidTy())
1851 O << "void ";
1852 else {
1854 O << " = ";
1855 }
1856
1857 O << "call";
1858 printFlags(O);
1859 O << " @" << CalledFn->getName() << "(";
1860 interleaveComma(args(), O, [&O, &SlotTracker](VPValue *Op) {
1861 Op->printAsOperand(O, SlotTracker);
1862 });
1863 O << ")";
1864
1865 O << " (using library function";
1866 if (Variant->hasName())
1867 O << ": " << Variant->getName();
1868 O << ")";
1869}
1870#endif
1871
1873 assert(State.VF.isVector() && "not widening");
1874
1875 SmallVector<Type *, 2> TysForDecl;
1876 // Add return type if intrinsic is overloaded on it.
1877 if (isVectorIntrinsicWithOverloadTypeAtArg(VectorIntrinsicID, -1,
1878 State.TTI)) {
1879 Type *RetTy = toVectorizedTy(getResultType(), State.VF);
1880 ArrayRef<Type *> ContainedTys = getContainedTypes(RetTy);
1881 for (auto [Idx, Ty] : enumerate(ContainedTys)) {
1883 Idx, State.TTI))
1884 TysForDecl.push_back(Ty);
1885 }
1886 }
1888 for (const auto &I : enumerate(operands())) {
1889 // Some intrinsics have a scalar argument - don't replace it with a
1890 // vector.
1891 Value *Arg;
1892 if (isVectorIntrinsicWithScalarOpAtArg(VectorIntrinsicID, I.index(),
1893 State.TTI))
1894 Arg = State.get(I.value(), VPLane(0));
1895 else
1896 Arg = State.get(I.value(), usesFirstLaneOnly(I.value()));
1897 if (isVectorIntrinsicWithOverloadTypeAtArg(VectorIntrinsicID, I.index(),
1898 State.TTI))
1899 TysForDecl.push_back(Arg->getType());
1900 Args.push_back(Arg);
1901 }
1902
1903 // Use vector version of the intrinsic.
1904 Module *M = State.Builder.GetInsertBlock()->getModule();
1905 Function *VectorF =
1906 Intrinsic::getOrInsertDeclaration(M, VectorIntrinsicID, TysForDecl);
1907 assert(VectorF &&
1908 "Can't retrieve vector intrinsic or vector-predication intrinsics.");
1909
1912 if (CI)
1913 CI->getOperandBundlesAsDefs(OpBundles);
1914
1915 CallInst *V = State.Builder.CreateCall(VectorF, Args, OpBundles);
1916
1917 applyFlags(*V);
1918 applyMetadata(*V);
1919
1920 if (!V->getType()->isVoidTy())
1921 State.set(this, V);
1922}
1923
1924/// Compute the cost for the intrinsic \p ID with \p Operands, produced by \p R.
1927 const VPRecipeWithIRFlags &R,
1928 ElementCount VF,
1929 VPCostContext &Ctx) {
1930 // Some backends analyze intrinsic arguments to determine cost. Use the
1931 // underlying value for the operand if it has one. Otherwise try to use the
1932 // operand of the underlying call instruction, if there is one. Otherwise
1933 // clear Arguments.
1934 // TODO: Rework TTI interface to be independent of concrete IR values.
1936 for (const auto &[Idx, Op] : enumerate(Operands)) {
1937 auto *V = Op->getUnderlyingValue();
1938 if (!V) {
1939 if (auto *UI = dyn_cast_or_null<CallBase>(R.getUnderlyingValue())) {
1940 Arguments.push_back(UI->getArgOperand(Idx));
1941 continue;
1942 }
1943 Arguments.clear();
1944 break;
1945 }
1946 Arguments.push_back(V);
1947 }
1948
1949 Type *ScalarRetTy = Ctx.Types.inferScalarType(&R);
1950 Type *RetTy = VF.isVector() ? toVectorizedTy(ScalarRetTy, VF) : ScalarRetTy;
1951 SmallVector<Type *> ParamTys;
1952 for (const VPValue *Op : Operands) {
1953 ParamTys.push_back(VF.isVector()
1954 ? toVectorTy(Ctx.Types.inferScalarType(Op), VF)
1955 : Ctx.Types.inferScalarType(Op));
1956 }
1957
1958 // TODO: Rework TTI interface to avoid reliance on underlying IntrinsicInst.
1959 IntrinsicCostAttributes CostAttrs(
1960 ID, RetTy, Arguments, ParamTys, R.getFastMathFlags(),
1961 dyn_cast_or_null<IntrinsicInst>(R.getUnderlyingValue()),
1963 return Ctx.TTI.getIntrinsicInstrCost(CostAttrs, Ctx.CostKind);
1964}
1965
1967 VPCostContext &Ctx) const {
1969 return getCostForIntrinsics(VectorIntrinsicID, ArgOps, *this, VF, Ctx);
1970}
1971
1973 return Intrinsic::getBaseName(VectorIntrinsicID);
1974}
1975
1977 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
1978 return all_of(enumerate(operands()), [this, &Op](const auto &X) {
1979 auto [Idx, V] = X;
1981 Idx, nullptr);
1982 });
1983}
1984
1985#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1987 VPSlotTracker &SlotTracker) const {
1988 O << Indent << "WIDEN-INTRINSIC ";
1989 if (ResultTy->isVoidTy()) {
1990 O << "void ";
1991 } else {
1993 O << " = ";
1994 }
1995
1996 O << "call";
1997 printFlags(O);
1998 O << getIntrinsicName() << "(";
1999
2001 Op->printAsOperand(O, SlotTracker);
2002 });
2003 O << ")";
2004}
2005#endif
2006
2008 IRBuilderBase &Builder = State.Builder;
2009
2010 Value *Address = State.get(getOperand(0));
2011 Value *IncAmt = State.get(getOperand(1), /*IsScalar=*/true);
2012 VectorType *VTy = cast<VectorType>(Address->getType());
2013
2014 // The histogram intrinsic requires a mask even if the recipe doesn't;
2015 // if the mask operand was omitted then all lanes should be executed and
2016 // we just need to synthesize an all-true mask.
2017 Value *Mask = nullptr;
2018 if (VPValue *VPMask = getMask())
2019 Mask = State.get(VPMask);
2020 else
2021 Mask =
2022 Builder.CreateVectorSplat(VTy->getElementCount(), Builder.getInt1(1));
2023
2024 // If this is a subtract, we want to invert the increment amount. We may
2025 // add a separate intrinsic in future, but for now we'll try this.
2026 if (Opcode == Instruction::Sub)
2027 IncAmt = Builder.CreateNeg(IncAmt);
2028 else
2029 assert(Opcode == Instruction::Add && "only add or sub supported for now");
2030
2031 State.Builder.CreateIntrinsic(Intrinsic::experimental_vector_histogram_add,
2032 {VTy, IncAmt->getType()},
2033 {Address, IncAmt, Mask});
2034}
2035
2037 VPCostContext &Ctx) const {
2038 // FIXME: Take the gather and scatter into account as well. For now we're
2039 // generating the same cost as the fallback path, but we'll likely
2040 // need to create a new TTI method for determining the cost, including
2041 // whether we can use base + vec-of-smaller-indices or just
2042 // vec-of-pointers.
2043 assert(VF.isVector() && "Invalid VF for histogram cost");
2044 Type *AddressTy = Ctx.Types.inferScalarType(getOperand(0));
2045 VPValue *IncAmt = getOperand(1);
2046 Type *IncTy = Ctx.Types.inferScalarType(IncAmt);
2047 VectorType *VTy = VectorType::get(IncTy, VF);
2048
2049 // Assume that a non-constant update value (or a constant != 1) requires
2050 // a multiply, and add that into the cost.
2051 InstructionCost MulCost =
2052 Ctx.TTI.getArithmeticInstrCost(Instruction::Mul, VTy, Ctx.CostKind);
2053 if (auto *CI = dyn_cast<VPConstantInt>(IncAmt))
2054 if (CI->isOne())
2055 MulCost = TTI::TCC_Free;
2056
2057 // Find the cost of the histogram operation itself.
2058 Type *PtrTy = VectorType::get(AddressTy, VF);
2059 Type *MaskTy = VectorType::get(Type::getInt1Ty(Ctx.LLVMCtx), VF);
2060 IntrinsicCostAttributes ICA(Intrinsic::experimental_vector_histogram_add,
2061 Type::getVoidTy(Ctx.LLVMCtx),
2062 {PtrTy, IncTy, MaskTy});
2063
2064 // Add the costs together with the add/sub operation.
2065 return Ctx.TTI.getIntrinsicInstrCost(ICA, Ctx.CostKind) + MulCost +
2066 Ctx.TTI.getArithmeticInstrCost(Opcode, VTy, Ctx.CostKind);
2067}
2068
2069#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2071 VPSlotTracker &SlotTracker) const {
2072 O << Indent << "WIDEN-HISTOGRAM buckets: ";
2074
2075 if (Opcode == Instruction::Sub)
2076 O << ", dec: ";
2077 else {
2078 assert(Opcode == Instruction::Add);
2079 O << ", inc: ";
2080 }
2082
2083 if (VPValue *Mask = getMask()) {
2084 O << ", mask: ";
2085 Mask->printAsOperand(O, SlotTracker);
2086 }
2087}
2088#endif
2089
2090VPIRFlags::FastMathFlagsTy::FastMathFlagsTy(const FastMathFlags &FMF) {
2091 AllowReassoc = FMF.allowReassoc();
2092 NoNaNs = FMF.noNaNs();
2093 NoInfs = FMF.noInfs();
2094 NoSignedZeros = FMF.noSignedZeros();
2095 AllowReciprocal = FMF.allowReciprocal();
2096 AllowContract = FMF.allowContract();
2097 ApproxFunc = FMF.approxFunc();
2098}
2099
2101 switch (Opcode) {
2102 case Instruction::Add:
2103 case Instruction::Sub:
2104 case Instruction::Mul:
2105 case Instruction::Shl:
2107 return WrapFlagsTy(false, false);
2108 case Instruction::Trunc:
2109 return TruncFlagsTy(false, false);
2110 case Instruction::Or:
2111 return DisjointFlagsTy(false);
2112 case Instruction::AShr:
2113 case Instruction::LShr:
2114 case Instruction::UDiv:
2115 case Instruction::SDiv:
2116 return ExactFlagsTy(false);
2117 case Instruction::GetElementPtr:
2120 return GEPNoWrapFlags::none();
2121 case Instruction::ZExt:
2122 case Instruction::UIToFP:
2123 return NonNegFlagsTy(false);
2124 case Instruction::FAdd:
2125 case Instruction::FSub:
2126 case Instruction::FMul:
2127 case Instruction::FDiv:
2128 case Instruction::FRem:
2129 case Instruction::FNeg:
2130 case Instruction::FPExt:
2131 case Instruction::FPTrunc:
2132 return FastMathFlags();
2133 case Instruction::ICmp:
2134 case Instruction::FCmp:
2136 llvm_unreachable("opcode requires explicit flags");
2137 default:
2138 return VPIRFlags();
2139 }
2140}
2141
2142#if !defined(NDEBUG)
2143bool VPIRFlags::flagsValidForOpcode(unsigned Opcode) const {
2144 switch (OpType) {
2145 case OperationType::OverflowingBinOp:
2146 return Opcode == Instruction::Add || Opcode == Instruction::Sub ||
2147 Opcode == Instruction::Mul || Opcode == Instruction::Shl ||
2148 Opcode == VPInstruction::VPInstruction::CanonicalIVIncrementForPart;
2149 case OperationType::Trunc:
2150 return Opcode == Instruction::Trunc;
2151 case OperationType::DisjointOp:
2152 return Opcode == Instruction::Or;
2153 case OperationType::PossiblyExactOp:
2154 return Opcode == Instruction::AShr || Opcode == Instruction::LShr ||
2155 Opcode == Instruction::UDiv || Opcode == Instruction::SDiv;
2156 case OperationType::GEPOp:
2157 return Opcode == Instruction::GetElementPtr ||
2158 Opcode == VPInstruction::PtrAdd ||
2159 Opcode == VPInstruction::WidePtrAdd;
2160 case OperationType::FPMathOp:
2161 return Opcode == Instruction::Call || Opcode == Instruction::FAdd ||
2162 Opcode == Instruction::FMul || Opcode == Instruction::FSub ||
2163 Opcode == Instruction::FNeg || Opcode == Instruction::FDiv ||
2164 Opcode == Instruction::FRem || Opcode == Instruction::FPExt ||
2165 Opcode == Instruction::FPTrunc || Opcode == Instruction::PHI ||
2166 Opcode == Instruction::Select ||
2167 Opcode == VPInstruction::WideIVStep ||
2169 case OperationType::FCmp:
2170 return Opcode == Instruction::FCmp;
2171 case OperationType::NonNegOp:
2172 return Opcode == Instruction::ZExt || Opcode == Instruction::UIToFP;
2173 case OperationType::Cmp:
2174 return Opcode == Instruction::FCmp || Opcode == Instruction::ICmp;
2175 case OperationType::ReductionOp:
2177 case OperationType::Other:
2178 return true;
2179 }
2180 llvm_unreachable("Unknown OperationType enum");
2181}
2182
2183bool VPIRFlags::hasRequiredFlagsForOpcode(unsigned Opcode) const {
2184 // Handle opcodes without default flags.
2185 if (Opcode == Instruction::ICmp)
2186 return OpType == OperationType::Cmp;
2187 if (Opcode == Instruction::FCmp)
2188 return OpType == OperationType::FCmp;
2190 return OpType == OperationType::ReductionOp;
2191
2192 OperationType Required = getDefaultFlags(Opcode).OpType;
2193 return Required == OperationType::Other || Required == OpType;
2194}
2195#endif
2196
2197#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2199 switch (OpType) {
2200 case OperationType::Cmp:
2202 break;
2203 case OperationType::FCmp:
2206 break;
2207 case OperationType::DisjointOp:
2208 if (DisjointFlags.IsDisjoint)
2209 O << " disjoint";
2210 break;
2211 case OperationType::PossiblyExactOp:
2212 if (ExactFlags.IsExact)
2213 O << " exact";
2214 break;
2215 case OperationType::OverflowingBinOp:
2216 if (WrapFlags.HasNUW)
2217 O << " nuw";
2218 if (WrapFlags.HasNSW)
2219 O << " nsw";
2220 break;
2221 case OperationType::Trunc:
2222 if (TruncFlags.HasNUW)
2223 O << " nuw";
2224 if (TruncFlags.HasNSW)
2225 O << " nsw";
2226 break;
2227 case OperationType::FPMathOp:
2229 break;
2230 case OperationType::GEPOp: {
2232 if (Flags.isInBounds())
2233 O << " inbounds";
2234 else if (Flags.hasNoUnsignedSignedWrap())
2235 O << " nusw";
2236 if (Flags.hasNoUnsignedWrap())
2237 O << " nuw";
2238 break;
2239 }
2240 case OperationType::NonNegOp:
2241 if (NonNegFlags.NonNeg)
2242 O << " nneg";
2243 break;
2244 case OperationType::ReductionOp: {
2245 RecurKind RK = getRecurKind();
2246 O << " (";
2247 switch (RK) {
2248 case RecurKind::AnyOf:
2249 O << "any-of";
2250 break;
2252 O << "find-last";
2253 break;
2254 case RecurKind::SMax:
2255 O << "smax";
2256 break;
2257 case RecurKind::SMin:
2258 O << "smin";
2259 break;
2260 case RecurKind::UMax:
2261 O << "umax";
2262 break;
2263 case RecurKind::UMin:
2264 O << "umin";
2265 break;
2266 case RecurKind::FMinNum:
2267 O << "fminnum";
2268 break;
2269 case RecurKind::FMaxNum:
2270 O << "fmaxnum";
2271 break;
2273 O << "fminimum";
2274 break;
2276 O << "fmaximum";
2277 break;
2279 O << "fminimumnum";
2280 break;
2282 O << "fmaximumnum";
2283 break;
2284 default:
2286 break;
2287 }
2288 if (isReductionInLoop())
2289 O << ", in-loop";
2290 if (isReductionOrdered())
2291 O << ", ordered";
2292 O << ")";
2294 break;
2295 }
2296 case OperationType::Other:
2297 break;
2298 }
2299 O << " ";
2300}
2301#endif
2302
2304 auto &Builder = State.Builder;
2305 switch (Opcode) {
2306 case Instruction::Call:
2307 case Instruction::UncondBr:
2308 case Instruction::CondBr:
2309 case Instruction::PHI:
2310 case Instruction::GetElementPtr:
2311 llvm_unreachable("This instruction is handled by a different recipe.");
2312 case Instruction::UDiv:
2313 case Instruction::SDiv:
2314 case Instruction::SRem:
2315 case Instruction::URem:
2316 case Instruction::Add:
2317 case Instruction::FAdd:
2318 case Instruction::Sub:
2319 case Instruction::FSub:
2320 case Instruction::FNeg:
2321 case Instruction::Mul:
2322 case Instruction::FMul:
2323 case Instruction::FDiv:
2324 case Instruction::FRem:
2325 case Instruction::Shl:
2326 case Instruction::LShr:
2327 case Instruction::AShr:
2328 case Instruction::And:
2329 case Instruction::Or:
2330 case Instruction::Xor: {
2331 // Just widen unops and binops.
2333 for (VPValue *VPOp : operands())
2334 Ops.push_back(State.get(VPOp));
2335
2336 Value *V = Builder.CreateNAryOp(Opcode, Ops);
2337
2338 if (auto *VecOp = dyn_cast<Instruction>(V)) {
2339 applyFlags(*VecOp);
2340 applyMetadata(*VecOp);
2341 }
2342
2343 // Use this vector value for all users of the original instruction.
2344 State.set(this, V);
2345 break;
2346 }
2347 case Instruction::ExtractValue: {
2348 assert(getNumOperands() == 2 && "expected single level extractvalue");
2349 Value *Op = State.get(getOperand(0));
2350 Value *Extract = Builder.CreateExtractValue(
2351 Op, cast<VPConstantInt>(getOperand(1))->getZExtValue());
2352 State.set(this, Extract);
2353 break;
2354 }
2355 case Instruction::Freeze: {
2356 Value *Op = State.get(getOperand(0));
2357 Value *Freeze = Builder.CreateFreeze(Op);
2358 State.set(this, Freeze);
2359 break;
2360 }
2361 case Instruction::ICmp:
2362 case Instruction::FCmp: {
2363 // Widen compares. Generate vector compares.
2364 bool FCmp = Opcode == Instruction::FCmp;
2365 Value *A = State.get(getOperand(0));
2366 Value *B = State.get(getOperand(1));
2367 Value *C = nullptr;
2368 if (FCmp) {
2369 C = Builder.CreateFCmp(getPredicate(), A, B);
2370 } else {
2371 C = Builder.CreateICmp(getPredicate(), A, B);
2372 }
2373 if (auto *I = dyn_cast<Instruction>(C)) {
2374 applyFlags(*I);
2375 applyMetadata(*I);
2376 }
2377 State.set(this, C);
2378 break;
2379 }
2380 case Instruction::Select: {
2381 VPValue *CondOp = getOperand(0);
2382 Value *Cond = State.get(CondOp, vputils::isSingleScalar(CondOp));
2383 Value *Op0 = State.get(getOperand(1));
2384 Value *Op1 = State.get(getOperand(2));
2385 Value *Sel = State.Builder.CreateSelect(Cond, Op0, Op1);
2386 State.set(this, Sel);
2387 if (auto *I = dyn_cast<Instruction>(Sel)) {
2389 applyFlags(*I);
2390 applyMetadata(*I);
2391 }
2392 break;
2393 }
2394 default:
2395 // This instruction is not vectorized by simple widening.
2396 LLVM_DEBUG(dbgs() << "LV: Found an unhandled opcode : "
2397 << Instruction::getOpcodeName(Opcode));
2398 llvm_unreachable("Unhandled instruction!");
2399 } // end of switch.
2400
2401#if !defined(NDEBUG)
2402 // Verify that VPlan type inference results agree with the type of the
2403 // generated values.
2404 assert(VectorType::get(State.TypeAnalysis.inferScalarType(this), State.VF) ==
2405 State.get(this)->getType() &&
2406 "inferred type and type from generated instructions do not match");
2407#endif
2408}
2409
2411 VPCostContext &Ctx) const {
2412 switch (Opcode) {
2413 case Instruction::UDiv:
2414 case Instruction::SDiv:
2415 case Instruction::SRem:
2416 case Instruction::URem:
2417 // If the div/rem operation isn't safe to speculate and requires
2418 // predication, then the only way we can even create a vplan is to insert
2419 // a select on the second input operand to ensure we use the value of 1
2420 // for the inactive lanes. The select will be costed separately.
2421 case Instruction::FNeg:
2422 case Instruction::Add:
2423 case Instruction::FAdd:
2424 case Instruction::Sub:
2425 case Instruction::FSub:
2426 case Instruction::Mul:
2427 case Instruction::FMul:
2428 case Instruction::FDiv:
2429 case Instruction::FRem:
2430 case Instruction::Shl:
2431 case Instruction::LShr:
2432 case Instruction::AShr:
2433 case Instruction::And:
2434 case Instruction::Or:
2435 case Instruction::Xor:
2436 case Instruction::Freeze:
2437 case Instruction::ExtractValue:
2438 case Instruction::ICmp:
2439 case Instruction::FCmp:
2440 case Instruction::Select:
2441 return getCostForRecipeWithOpcode(getOpcode(), VF, Ctx);
2442 default:
2443 llvm_unreachable("Unsupported opcode for instruction");
2444 }
2445}
2446
2447#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2449 VPSlotTracker &SlotTracker) const {
2450 O << Indent << "WIDEN ";
2452 O << " = " << Instruction::getOpcodeName(Opcode);
2453 printFlags(O);
2455}
2456#endif
2457
2459 auto &Builder = State.Builder;
2460 /// Vectorize casts.
2461 assert(State.VF.isVector() && "Not vectorizing?");
2462 Type *DestTy = VectorType::get(getResultType(), State.VF);
2463 VPValue *Op = getOperand(0);
2464 Value *A = State.get(Op);
2465 Value *Cast = Builder.CreateCast(Instruction::CastOps(Opcode), A, DestTy);
2466 State.set(this, Cast);
2467 if (auto *CastOp = dyn_cast<Instruction>(Cast)) {
2468 applyFlags(*CastOp);
2469 applyMetadata(*CastOp);
2470 }
2471}
2472
2474 VPCostContext &Ctx) const {
2475 // TODO: In some cases, VPWidenCastRecipes are created but not considered in
2476 // the legacy cost model, including truncates/extends when evaluating a
2477 // reduction in a smaller type.
2478 if (!getUnderlyingValue())
2479 return 0;
2480 return getCostForRecipeWithOpcode(getOpcode(), VF, Ctx);
2481}
2482
2483#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2485 VPSlotTracker &SlotTracker) const {
2486 O << Indent << "WIDEN-CAST ";
2488 O << " = " << Instruction::getOpcodeName(Opcode);
2489 printFlags(O);
2491 O << " to " << *getResultType();
2492}
2493#endif
2494
2496 VPCostContext &Ctx) const {
2497 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
2498}
2499
2500#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2502 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
2503 O << Indent;
2505 O << " = WIDEN-INDUCTION";
2506 printFlags(O);
2508
2509 if (auto *TI = getTruncInst())
2510 O << " (truncated to " << *TI->getType() << ")";
2511}
2512#endif
2513
2515 // The step may be defined by a recipe in the preheader (e.g. if it requires
2516 // SCEV expansion), but for the canonical induction the step is required to be
2517 // 1, which is represented as live-in.
2518 auto *StepC = dyn_cast<VPConstantInt>(getStepValue());
2519 auto *StartC = dyn_cast<VPConstantInt>(getStartValue());
2520 return StartC && StartC->isZero() && StepC && StepC->isOne() &&
2521 getScalarType() == getRegion()->getCanonicalIVType();
2522}
2523
2525 assert(!State.Lane && "VPDerivedIVRecipe being replicated.");
2526
2527 // Fast-math-flags propagate from the original induction instruction.
2528 IRBuilder<>::FastMathFlagGuard FMFG(State.Builder);
2529 if (FPBinOp)
2530 State.Builder.setFastMathFlags(FPBinOp->getFastMathFlags());
2531
2532 Value *Step = State.get(getStepValue(), VPLane(0));
2533 Value *Index = State.get(getOperand(1), VPLane(0));
2534 Value *DerivedIV = emitTransformedIndex(
2535 State.Builder, Index, getStartValue()->getLiveInIRValue(), Step, Kind,
2537 DerivedIV->setName(Name);
2538 State.set(this, DerivedIV, VPLane(0));
2539}
2540
2541#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2543 VPSlotTracker &SlotTracker) const {
2544 O << Indent;
2546 O << " = DERIVED-IV ";
2547 getStartValue()->printAsOperand(O, SlotTracker);
2548 O << " + ";
2549 getOperand(1)->printAsOperand(O, SlotTracker);
2550 O << " * ";
2551 getStepValue()->printAsOperand(O, SlotTracker);
2552}
2553#endif
2554
2556 // Fast-math-flags propagate from the original induction instruction.
2557 IRBuilder<>::FastMathFlagGuard FMFG(State.Builder);
2558 State.Builder.setFastMathFlags(getFastMathFlags());
2559
2560 /// Compute scalar induction steps. \p ScalarIV is the scalar induction
2561 /// variable on which to base the steps, \p Step is the size of the step.
2562
2563 Value *BaseIV = State.get(getOperand(0), VPLane(0));
2564 Value *Step = State.get(getStepValue(), VPLane(0));
2565 IRBuilderBase &Builder = State.Builder;
2566
2567 // Ensure step has the same type as that of scalar IV.
2568 Type *BaseIVTy = BaseIV->getType()->getScalarType();
2569 assert(BaseIVTy == Step->getType() && "Types of BaseIV and Step must match!");
2570
2571 // We build scalar steps for both integer and floating-point induction
2572 // variables. Here, we determine the kind of arithmetic we will perform.
2575 if (BaseIVTy->isIntegerTy()) {
2576 AddOp = Instruction::Add;
2577 MulOp = Instruction::Mul;
2578 } else {
2579 AddOp = InductionOpcode;
2580 MulOp = Instruction::FMul;
2581 }
2582
2583 // Determine the number of scalars we need to generate.
2584 bool FirstLaneOnly = vputils::onlyFirstLaneUsed(this);
2585 // Compute the scalar steps and save the results in State.
2586
2587 unsigned StartLane = 0;
2588 unsigned EndLane = FirstLaneOnly ? 1 : State.VF.getKnownMinValue();
2589 if (State.Lane) {
2590 StartLane = State.Lane->getKnownLane();
2591 EndLane = StartLane + 1;
2592 }
2593 Value *StartIdx0 = getStartIndex() ? State.get(getStartIndex(), true)
2594 : Constant::getNullValue(BaseIVTy);
2595
2596 for (unsigned Lane = StartLane; Lane < EndLane; ++Lane) {
2597 // It is okay if the induction variable type cannot hold the lane number,
2598 // we expect truncation in this case.
2599 Constant *LaneValue =
2600 BaseIVTy->isIntegerTy()
2601 ? ConstantInt::get(BaseIVTy, Lane, /*IsSigned=*/false,
2602 /*ImplicitTrunc=*/true)
2603 : ConstantFP::get(BaseIVTy, Lane);
2604 Value *StartIdx = Builder.CreateBinOp(AddOp, StartIdx0, LaneValue);
2605 // The step returned by `createStepForVF` is a runtime-evaluated value
2606 // when VF is scalable. Otherwise, it should be folded into a Constant.
2607 assert((State.VF.isScalable() || isa<Constant>(StartIdx)) &&
2608 "Expected StartIdx to be folded to a constant when VF is not "
2609 "scalable");
2610 auto *Mul = Builder.CreateBinOp(MulOp, StartIdx, Step);
2611 auto *Add = Builder.CreateBinOp(AddOp, BaseIV, Mul);
2612 State.set(this, Add, VPLane(Lane));
2613 }
2614}
2615
2616#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2618 VPSlotTracker &SlotTracker) const {
2619 O << Indent;
2621 O << " = SCALAR-STEPS ";
2623}
2624#endif
2625
2627 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
2629}
2630
2632 assert(State.VF.isVector() && "not widening");
2633 // Construct a vector GEP by widening the operands of the scalar GEP as
2634 // necessary. We mark the vector GEP 'inbounds' if appropriate. A GEP
2635 // results in a vector of pointers when at least one operand of the GEP
2636 // is vector-typed. Thus, to keep the representation compact, we only use
2637 // vector-typed operands for loop-varying values.
2638
2639 bool AllOperandsAreInvariant = all_of(operands(), [](VPValue *Op) {
2640 return Op->isDefinedOutsideLoopRegions();
2641 });
2642 if (AllOperandsAreInvariant) {
2643 // If we are vectorizing, but the GEP has only loop-invariant operands,
2644 // the GEP we build (by only using vector-typed operands for
2645 // loop-varying values) would be a scalar pointer. Thus, to ensure we
2646 // produce a vector of pointers, we need to either arbitrarily pick an
2647 // operand to broadcast, or broadcast a clone of the original GEP.
2648 // Here, we broadcast a clone of the original.
2649
2651 for (unsigned I = 0, E = getNumOperands(); I != E; I++)
2652 Ops.push_back(State.get(getOperand(I), VPLane(0)));
2653
2654 auto *NewGEP =
2655 State.Builder.CreateGEP(getSourceElementType(), Ops[0], drop_begin(Ops),
2656 "", getGEPNoWrapFlags());
2657 Value *Splat = State.Builder.CreateVectorSplat(State.VF, NewGEP);
2658 State.set(this, Splat);
2659 return;
2660 }
2661
2662 // If the GEP has at least one loop-varying operand, we are sure to
2663 // produce a vector of pointers unless VF is scalar.
2664 // The pointer operand of the new GEP. If it's loop-invariant, we
2665 // won't broadcast it.
2666 auto *Ptr = State.get(getOperand(0), isPointerLoopInvariant());
2667
2668 // Collect all the indices for the new GEP. If any index is
2669 // loop-invariant, we won't broadcast it.
2671 for (unsigned I = 1, E = getNumOperands(); I < E; I++) {
2672 VPValue *Operand = getOperand(I);
2673 Indices.push_back(State.get(Operand, isIndexLoopInvariant(I - 1)));
2674 }
2675
2676 // Create the new GEP. Note that this GEP may be a scalar if VF == 1,
2677 // but it should be a vector, otherwise.
2678 auto *NewGEP = State.Builder.CreateGEP(getSourceElementType(), Ptr, Indices,
2679 "", getGEPNoWrapFlags());
2680 assert((State.VF.isScalar() || NewGEP->getType()->isVectorTy()) &&
2681 "NewGEP is not a pointer vector");
2682 State.set(this, NewGEP);
2683}
2684
2685#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2687 VPSlotTracker &SlotTracker) const {
2688 O << Indent << "WIDEN-GEP ";
2689 O << (isPointerLoopInvariant() ? "Inv" : "Var");
2690 for (size_t I = 0; I < getNumOperands() - 1; ++I)
2691 O << "[" << (isIndexLoopInvariant(I) ? "Inv" : "Var") << "]";
2692
2693 O << " ";
2695 O << " = getelementptr";
2696 printFlags(O);
2698}
2699#endif
2700
2702 assert(!getOffset() && "Unexpected offset operand");
2703 VPBuilder Builder(this);
2704 VPlan &Plan = *getParent()->getPlan();
2705 VPValue *VFVal = getVFValue();
2706 VPTypeAnalysis TypeInfo(Plan);
2707 const DataLayout &DL =
2709 Type *IndexTy = DL.getIndexType(TypeInfo.inferScalarType(getPointer()));
2710 VPValue *Stride =
2711 Plan.getConstantInt(IndexTy, getStride(), /*IsSigned=*/true);
2712 Type *VFTy = TypeInfo.inferScalarType(VFVal);
2713 VPValue *VF = Builder.createScalarZExtOrTrunc(VFVal, IndexTy, VFTy,
2715
2716 // Offset for Part0 = Offset0 = Stride * (VF - 1).
2717 VPInstruction *VFMinusOne =
2718 Builder.createSub(VF, Plan.getConstantInt(IndexTy, 1u),
2719 DebugLoc::getUnknown(), "", {true, true});
2720 VPInstruction *Offset0 =
2721 Builder.createOverflowingOp(Instruction::Mul, {VFMinusOne, Stride});
2722
2723 // Offset for PartN = Offset0 + Part * Stride * VF.
2724 VPValue *PartxStride =
2725 Plan.getConstantInt(IndexTy, Part * getStride(), /*IsSigned=*/true);
2726 VPValue *Offset = Builder.createAdd(
2727 Offset0,
2728 Builder.createOverflowingOp(Instruction::Mul, {PartxStride, VF}));
2730}
2731
2733 auto &Builder = State.Builder;
2734 assert(getOffset() && "Expected prior materialization of offset");
2735 Value *Ptr = State.get(getPointer(), true);
2736 Value *Offset = State.get(getOffset(), true);
2737 Value *ResultPtr = Builder.CreateGEP(getSourceElementType(), Ptr, Offset, "",
2739 State.set(this, ResultPtr, /*IsScalar*/ true);
2740}
2741
2742#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2744 VPSlotTracker &SlotTracker) const {
2745 O << Indent;
2747 O << " = vector-end-pointer";
2748 printFlags(O);
2750}
2751#endif
2752
2754 auto &Builder = State.Builder;
2755 assert(getOffset() &&
2756 "Expected prior simplification of recipe without offset");
2757 Value *Ptr = State.get(getOperand(0), VPLane(0));
2758 Value *Offset = State.get(getOffset(), true);
2759 Value *ResultPtr = Builder.CreateGEP(getSourceElementType(), Ptr, Offset, "",
2761 State.set(this, ResultPtr, /*IsScalar*/ true);
2762}
2763
2764#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2766 VPSlotTracker &SlotTracker) const {
2767 O << Indent;
2769 O << " = vector-pointer";
2770 printFlags(O);
2772}
2773#endif
2774
2776 VPCostContext &Ctx) const {
2777 // A blend will be expanded to a select VPInstruction, which will generate a
2778 // scalar select if only the first lane is used.
2780 VF = ElementCount::getFixed(1);
2781
2782 Type *ResultTy = toVectorTy(Ctx.Types.inferScalarType(this), VF);
2783 Type *CmpTy = toVectorTy(Type::getInt1Ty(Ctx.Types.getContext()), VF);
2784 return (getNumIncomingValues() - 1) *
2785 Ctx.TTI.getCmpSelInstrCost(Instruction::Select, ResultTy, CmpTy,
2786 CmpInst::BAD_ICMP_PREDICATE, Ctx.CostKind);
2787}
2788
2789#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2791 VPSlotTracker &SlotTracker) const {
2792 O << Indent << "BLEND ";
2794 O << " =";
2795 printFlags(O);
2796 if (getNumIncomingValues() == 1) {
2797 // Not a User of any mask: not really blending, this is a
2798 // single-predecessor phi.
2799 getIncomingValue(0)->printAsOperand(O, SlotTracker);
2800 } else {
2801 for (unsigned I = 0, E = getNumIncomingValues(); I < E; ++I) {
2802 if (I != 0)
2803 O << " ";
2804 getIncomingValue(I)->printAsOperand(O, SlotTracker);
2805 if (I == 0 && isNormalized())
2806 continue;
2807 O << "/";
2808 getMask(I)->printAsOperand(O, SlotTracker);
2809 }
2810 }
2811}
2812#endif
2813
2815 assert(!State.Lane && "Reduction being replicated.");
2818 "In-loop AnyOf reductions aren't currently supported");
2819 // Propagate the fast-math flags carried by the underlying instruction.
2820 IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder);
2821 State.Builder.setFastMathFlags(getFastMathFlags());
2822 Value *NewVecOp = State.get(getVecOp());
2823 if (VPValue *Cond = getCondOp()) {
2824 Value *NewCond = State.get(Cond, State.VF.isScalar());
2825 VectorType *VecTy = dyn_cast<VectorType>(NewVecOp->getType());
2826 Type *ElementTy = VecTy ? VecTy->getElementType() : NewVecOp->getType();
2827
2828 Value *Start = getRecurrenceIdentity(Kind, ElementTy, getFastMathFlags());
2829 if (State.VF.isVector())
2830 Start = State.Builder.CreateVectorSplat(VecTy->getElementCount(), Start);
2831
2832 Value *Select = State.Builder.CreateSelect(NewCond, NewVecOp, Start);
2833 NewVecOp = Select;
2834 }
2835 Value *NewRed;
2836 Value *NextInChain;
2837 if (isOrdered()) {
2838 Value *PrevInChain = State.get(getChainOp(), /*IsScalar*/ true);
2839 if (State.VF.isVector())
2840 NewRed =
2841 createOrderedReduction(State.Builder, Kind, NewVecOp, PrevInChain);
2842 else
2843 NewRed = State.Builder.CreateBinOp(
2845 PrevInChain, NewVecOp);
2846 PrevInChain = NewRed;
2847 NextInChain = NewRed;
2848 } else if (isPartialReduction()) {
2849 assert((Kind == RecurKind::Add || Kind == RecurKind::FAdd) &&
2850 "Unexpected partial reduction kind");
2851 Value *PrevInChain = State.get(getChainOp(), /*IsScalar*/ false);
2852 NewRed = State.Builder.CreateIntrinsic(
2853 PrevInChain->getType(),
2854 Kind == RecurKind::Add ? Intrinsic::vector_partial_reduce_add
2855 : Intrinsic::vector_partial_reduce_fadd,
2856 {PrevInChain, NewVecOp}, State.Builder.getFastMathFlags(),
2857 "partial.reduce");
2858 PrevInChain = NewRed;
2859 NextInChain = NewRed;
2860 } else {
2861 assert(isInLoop() &&
2862 "The reduction must either be ordered, partial or in-loop");
2863 Value *PrevInChain = State.get(getChainOp(), /*IsScalar*/ true);
2864 NewRed = createSimpleReduction(State.Builder, NewVecOp, Kind);
2866 NextInChain = createMinMaxOp(State.Builder, Kind, NewRed, PrevInChain);
2867 else
2868 NextInChain = State.Builder.CreateBinOp(
2870 PrevInChain, NewRed);
2871 }
2872 State.set(this, NextInChain, /*IsScalar*/ !isPartialReduction());
2873}
2874
2876 assert(!State.Lane && "Reduction being replicated.");
2877
2878 auto &Builder = State.Builder;
2879 // Propagate the fast-math flags carried by the underlying instruction.
2880 IRBuilderBase::FastMathFlagGuard FMFGuard(Builder);
2881 Builder.setFastMathFlags(getFastMathFlags());
2882
2884 Value *Prev = State.get(getChainOp(), /*IsScalar*/ true);
2885 Value *VecOp = State.get(getVecOp());
2886 Value *EVL = State.get(getEVL(), VPLane(0));
2887
2888 Value *Mask;
2889 if (VPValue *CondOp = getCondOp())
2890 Mask = State.get(CondOp);
2891 else
2892 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
2893
2894 Value *NewRed;
2895 if (isOrdered()) {
2896 NewRed = createOrderedReduction(Builder, Kind, VecOp, Prev, Mask, EVL);
2897 } else {
2898 NewRed = createSimpleReduction(Builder, VecOp, Kind, Mask, EVL);
2900 NewRed = createMinMaxOp(Builder, Kind, NewRed, Prev);
2901 else
2902 NewRed = Builder.CreateBinOp(
2904 Prev);
2905 }
2906 State.set(this, NewRed, /*IsScalar*/ true);
2907}
2908
2910 VPCostContext &Ctx) const {
2911 RecurKind RdxKind = getRecurrenceKind();
2912 Type *ElementTy = Ctx.Types.inferScalarType(this);
2913 auto *VectorTy = cast<VectorType>(toVectorTy(ElementTy, VF));
2914 unsigned Opcode = RecurrenceDescriptor::getOpcode(RdxKind);
2916 std::optional<FastMathFlags> OptionalFMF =
2917 ElementTy->isFloatingPointTy() ? std::make_optional(FMFs) : std::nullopt;
2918
2919 if (isPartialReduction()) {
2920 InstructionCost CondCost = 0;
2921 if (isConditional()) {
2923 auto *CondTy = cast<VectorType>(
2924 toVectorTy(Ctx.Types.inferScalarType(getCondOp()), VF));
2925 CondCost = Ctx.TTI.getCmpSelInstrCost(Instruction::Select, VectorTy,
2926 CondTy, Pred, Ctx.CostKind);
2927 }
2928 return CondCost + Ctx.TTI.getPartialReductionCost(
2929 Opcode, ElementTy, ElementTy, ElementTy, VF,
2930 TTI::PR_None, TTI::PR_None, {}, Ctx.CostKind,
2931 OptionalFMF);
2932 }
2933
2934 // TODO: Support any-of reductions.
2935 assert(
2937 ForceTargetInstructionCost.getNumOccurrences() > 0) &&
2938 "Any-of reduction not implemented in VPlan-based cost model currently.");
2939
2940 // Note that TTI should model the cost of moving result to the scalar register
2941 // and the BinOp cost in the getMinMaxReductionCost().
2944 return Ctx.TTI.getMinMaxReductionCost(Id, VectorTy, FMFs, Ctx.CostKind);
2945 }
2946
2947 // Note that TTI should model the cost of moving result to the scalar register
2948 // and the BinOp cost in the getArithmeticReductionCost().
2949 return Ctx.TTI.getArithmeticReductionCost(Opcode, VectorTy, OptionalFMF,
2950 Ctx.CostKind);
2951}
2952
2953VPExpressionRecipe::VPExpressionRecipe(
2954 ExpressionTypes ExpressionType,
2955 ArrayRef<VPSingleDefRecipe *> ExpressionRecipes)
2956 : VPSingleDefRecipe(VPRecipeBase::VPExpressionSC, {}, {}),
2957 ExpressionRecipes(ExpressionRecipes), ExpressionType(ExpressionType) {
2958 assert(!ExpressionRecipes.empty() && "Nothing to combine?");
2959 assert(
2960 none_of(ExpressionRecipes,
2961 [](VPSingleDefRecipe *R) { return R->mayHaveSideEffects(); }) &&
2962 "expression cannot contain recipes with side-effects");
2963
2964 // Maintain a copy of the expression recipes as a set of users.
2965 SmallPtrSet<VPUser *, 4> ExpressionRecipesAsSetOfUsers;
2966 for (auto *R : ExpressionRecipes)
2967 ExpressionRecipesAsSetOfUsers.insert(R);
2968
2969 // Recipes in the expression, except the last one, must only be used by
2970 // (other) recipes inside the expression. If there are other users, external
2971 // to the expression, use a clone of the recipe for external users.
2972 for (VPSingleDefRecipe *R : reverse(ExpressionRecipes)) {
2973 if (R != ExpressionRecipes.back() &&
2974 any_of(R->users(), [&ExpressionRecipesAsSetOfUsers](VPUser *U) {
2975 return !ExpressionRecipesAsSetOfUsers.contains(U);
2976 })) {
2977 // There are users outside of the expression. Clone the recipe and use the
2978 // clone those external users.
2979 VPSingleDefRecipe *CopyForExtUsers = R->clone();
2980 R->replaceUsesWithIf(CopyForExtUsers, [&ExpressionRecipesAsSetOfUsers](
2981 VPUser &U, unsigned) {
2982 return !ExpressionRecipesAsSetOfUsers.contains(&U);
2983 });
2984 CopyForExtUsers->insertBefore(R);
2985 }
2986 if (R->getParent())
2987 R->removeFromParent();
2988 }
2989
2990 // Internalize all external operands to the expression recipes. To do so,
2991 // create new temporary VPValues for all operands defined by a recipe outside
2992 // the expression. The original operands are added as operands of the
2993 // VPExpressionRecipe itself.
2994 for (auto *R : ExpressionRecipes) {
2995 for (const auto &[Idx, Op] : enumerate(R->operands())) {
2996 auto *Def = Op->getDefiningRecipe();
2997 if (Def && ExpressionRecipesAsSetOfUsers.contains(Def))
2998 continue;
2999 addOperand(Op);
3000 LiveInPlaceholders.push_back(new VPSymbolicValue());
3001 }
3002 }
3003
3004 // Replace each external operand with the first one created for it in
3005 // LiveInPlaceholders.
3006 for (auto *R : ExpressionRecipes)
3007 for (auto const &[LiveIn, Tmp] : zip(operands(), LiveInPlaceholders))
3008 R->replaceUsesOfWith(LiveIn, Tmp);
3009}
3010
3012 for (auto *R : ExpressionRecipes)
3013 // Since the list could contain duplicates, make sure the recipe hasn't
3014 // already been inserted.
3015 if (!R->getParent())
3016 R->insertBefore(this);
3017
3018 for (const auto &[Idx, Op] : enumerate(operands()))
3019 LiveInPlaceholders[Idx]->replaceAllUsesWith(Op);
3020
3021 replaceAllUsesWith(ExpressionRecipes.back());
3022 ExpressionRecipes.clear();
3023}
3024
3026 VPCostContext &Ctx) const {
3027 Type *RedTy = Ctx.Types.inferScalarType(this);
3028 auto *SrcVecTy = cast<VectorType>(
3029 toVectorTy(Ctx.Types.inferScalarType(getOperand(0)), VF));
3030 unsigned Opcode = RecurrenceDescriptor::getOpcode(
3031 cast<VPReductionRecipe>(ExpressionRecipes.back())->getRecurrenceKind());
3032 switch (ExpressionType) {
3033 case ExpressionTypes::ExtendedReduction: {
3034 unsigned Opcode = RecurrenceDescriptor::getOpcode(
3035 cast<VPReductionRecipe>(ExpressionRecipes[1])->getRecurrenceKind());
3036 auto *ExtR = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3037 auto *RedR = cast<VPReductionRecipe>(ExpressionRecipes.back());
3038
3039 if (RedR->isPartialReduction())
3040 return Ctx.TTI.getPartialReductionCost(
3041 Opcode, Ctx.Types.inferScalarType(getOperand(0)), nullptr, RedTy, VF,
3043 TargetTransformInfo::PR_None, std::nullopt, Ctx.CostKind,
3044 RedTy->isFloatingPointTy() ? std::optional{RedR->getFastMathFlags()}
3045 : std::nullopt);
3046 else if (!RedTy->isFloatingPointTy())
3047 // TTI::getExtendedReductionCost only supports integer types.
3048 return Ctx.TTI.getExtendedReductionCost(
3049 Opcode, ExtR->getOpcode() == Instruction::ZExt, RedTy, SrcVecTy,
3050 std::nullopt, Ctx.CostKind);
3051 else
3053 }
3054 case ExpressionTypes::MulAccReduction:
3055 return Ctx.TTI.getMulAccReductionCost(false, Opcode, RedTy, SrcVecTy,
3056 Ctx.CostKind);
3057
3058 case ExpressionTypes::ExtNegatedMulAccReduction:
3059 assert(Opcode == Instruction::Add && "Unexpected opcode");
3060 Opcode = Instruction::Sub;
3061 [[fallthrough]];
3062 case ExpressionTypes::ExtMulAccReduction: {
3063 auto *RedR = cast<VPReductionRecipe>(ExpressionRecipes.back());
3064 if (RedR->isPartialReduction()) {
3065 auto *Ext0R = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3066 auto *Ext1R = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
3067 auto *Mul = cast<VPWidenRecipe>(ExpressionRecipes[2]);
3068 return Ctx.TTI.getPartialReductionCost(
3069 Opcode, Ctx.Types.inferScalarType(getOperand(0)),
3070 Ctx.Types.inferScalarType(getOperand(1)), RedTy, VF,
3072 Ext0R->getOpcode()),
3074 Ext1R->getOpcode()),
3075 Mul->getOpcode(), Ctx.CostKind,
3076 RedTy->isFloatingPointTy() ? std::optional{RedR->getFastMathFlags()}
3077 : std::nullopt);
3078 }
3079 return Ctx.TTI.getMulAccReductionCost(
3080 cast<VPWidenCastRecipe>(ExpressionRecipes.front())->getOpcode() ==
3081 Instruction::ZExt,
3082 Opcode, RedTy, SrcVecTy, Ctx.CostKind);
3083 }
3084 }
3085 llvm_unreachable("Unknown VPExpressionRecipe::ExpressionTypes enum");
3086}
3087
3089 return any_of(ExpressionRecipes, [](VPSingleDefRecipe *R) {
3090 return R->mayReadFromMemory() || R->mayWriteToMemory();
3091 });
3092}
3093
3095 assert(
3096 none_of(ExpressionRecipes,
3097 [](VPSingleDefRecipe *R) { return R->mayHaveSideEffects(); }) &&
3098 "expression cannot contain recipes with side-effects");
3099 return false;
3100}
3101
3103 // Cannot use vputils::isSingleScalar(), because all external operands
3104 // of the expression will be live-ins while bundled.
3105 auto *RR = dyn_cast<VPReductionRecipe>(ExpressionRecipes.back());
3106 return RR && !RR->isPartialReduction();
3107}
3108
3109#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3110
3112 VPSlotTracker &SlotTracker) const {
3113 O << Indent << "EXPRESSION ";
3115 O << " = ";
3116 auto *Red = cast<VPReductionRecipe>(ExpressionRecipes.back());
3117 unsigned Opcode = RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind());
3118
3119 switch (ExpressionType) {
3120 case ExpressionTypes::ExtendedReduction: {
3122 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
3123 O << Instruction::getOpcodeName(Opcode) << " (";
3125 Red->printFlags(O);
3126
3127 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3128 O << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
3129 << *Ext0->getResultType();
3130 if (Red->isConditional()) {
3131 O << ", ";
3132 Red->getCondOp()->printAsOperand(O, SlotTracker);
3133 }
3134 O << ")";
3135 break;
3136 }
3137 case ExpressionTypes::ExtNegatedMulAccReduction: {
3139 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
3141 RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind()))
3142 << " (sub (0, mul";
3143 auto *Mul = cast<VPWidenRecipe>(ExpressionRecipes[2]);
3144 Mul->printFlags(O);
3145 O << "(";
3147 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3148 O << " " << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
3149 << *Ext0->getResultType() << "), (";
3151 auto *Ext1 = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
3152 O << " " << Instruction::getOpcodeName(Ext1->getOpcode()) << " to "
3153 << *Ext1->getResultType() << ")";
3154 if (Red->isConditional()) {
3155 O << ", ";
3156 Red->getCondOp()->printAsOperand(O, SlotTracker);
3157 }
3158 O << "))";
3159 break;
3160 }
3161 case ExpressionTypes::MulAccReduction:
3162 case ExpressionTypes::ExtMulAccReduction: {
3164 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
3166 RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind()))
3167 << " (";
3168 O << "mul";
3169 bool IsExtended = ExpressionType == ExpressionTypes::ExtMulAccReduction;
3170 auto *Mul = cast<VPWidenRecipe>(IsExtended ? ExpressionRecipes[2]
3171 : ExpressionRecipes[0]);
3172 Mul->printFlags(O);
3173 if (IsExtended)
3174 O << "(";
3176 if (IsExtended) {
3177 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3178 O << " " << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
3179 << *Ext0->getResultType() << "), (";
3180 } else {
3181 O << ", ";
3182 }
3184 if (IsExtended) {
3185 auto *Ext1 = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
3186 O << " " << Instruction::getOpcodeName(Ext1->getOpcode()) << " to "
3187 << *Ext1->getResultType() << ")";
3188 }
3189 if (Red->isConditional()) {
3190 O << ", ";
3191 Red->getCondOp()->printAsOperand(O, SlotTracker);
3192 }
3193 O << ")";
3194 break;
3195 }
3196 }
3197}
3198
3200 VPSlotTracker &SlotTracker) const {
3201 if (isPartialReduction())
3202 O << Indent << "PARTIAL-REDUCE ";
3203 else
3204 O << Indent << "REDUCE ";
3206 O << " = ";
3208 O << " +";
3209 printFlags(O);
3210 O << " reduce."
3213 << " (";
3215 if (isConditional()) {
3216 O << ", ";
3218 }
3219 O << ")";
3220}
3221
3223 VPSlotTracker &SlotTracker) const {
3224 O << Indent << "REDUCE ";
3226 O << " = ";
3228 O << " +";
3229 printFlags(O);
3230 O << " vp.reduce."
3233 << " (";
3235 O << ", ";
3237 if (isConditional()) {
3238 O << ", ";
3240 }
3241 O << ")";
3242}
3243
3244#endif
3245
3246/// A helper function to scalarize a single Instruction in the innermost loop.
3247/// Generates a sequence of scalar instances for lane \p Lane. Uses the VPValue
3248/// operands from \p RepRecipe instead of \p Instr's operands.
3249static void scalarizeInstruction(const Instruction *Instr,
3250 VPReplicateRecipe *RepRecipe,
3251 const VPLane &Lane, VPTransformState &State) {
3252 assert((!Instr->getType()->isAggregateType() ||
3253 canVectorizeTy(Instr->getType())) &&
3254 "Expected vectorizable or non-aggregate type.");
3255
3256 // Does this instruction return a value ?
3257 bool IsVoidRetTy = Instr->getType()->isVoidTy();
3258
3259 Instruction *Cloned = Instr->clone();
3260 if (!IsVoidRetTy) {
3261 Cloned->setName(Instr->getName() + ".cloned");
3262 Type *ResultTy = State.TypeAnalysis.inferScalarType(RepRecipe);
3263 // The operands of the replicate recipe may have been narrowed, resulting in
3264 // a narrower result type. Update the type of the cloned instruction to the
3265 // correct type.
3266 if (ResultTy != Cloned->getType())
3267 Cloned->mutateType(ResultTy);
3268 }
3269
3270 RepRecipe->applyFlags(*Cloned);
3271 RepRecipe->applyMetadata(*Cloned);
3272
3273 if (RepRecipe->hasPredicate())
3274 cast<CmpInst>(Cloned)->setPredicate(RepRecipe->getPredicate());
3275
3276 if (auto DL = RepRecipe->getDebugLoc())
3277 State.setDebugLocFrom(DL);
3278
3279 // Replace the operands of the cloned instructions with their scalar
3280 // equivalents in the new loop.
3281 for (const auto &I : enumerate(RepRecipe->operands())) {
3282 auto InputLane = Lane;
3283 VPValue *Operand = I.value();
3284 if (vputils::isSingleScalar(Operand))
3285 InputLane = VPLane::getFirstLane();
3286 Cloned->setOperand(I.index(), State.get(Operand, InputLane));
3287 }
3288
3289 // Place the cloned scalar in the new loop.
3290 State.Builder.Insert(Cloned);
3291
3292 State.set(RepRecipe, Cloned, Lane);
3293
3294 // If we just cloned a new assumption, add it the assumption cache.
3295 if (auto *II = dyn_cast<AssumeInst>(Cloned))
3296 State.AC->registerAssumption(II);
3297
3298 assert(
3299 (RepRecipe->getRegion() ||
3300 !RepRecipe->getParent()->getPlan()->getVectorLoopRegion() ||
3301 all_of(RepRecipe->operands(),
3302 [](VPValue *Op) { return Op->isDefinedOutsideLoopRegions(); })) &&
3303 "Expected a recipe is either within a region or all of its operands "
3304 "are defined outside the vectorized region.");
3305}
3306
3309
3310 if (!State.Lane) {
3311 assert(IsSingleScalar && "VPReplicateRecipes outside replicate regions "
3312 "must have already been unrolled");
3313 scalarizeInstruction(UI, this, VPLane(0), State);
3314 return;
3315 }
3316
3317 assert((State.VF.isScalar() || !isSingleScalar()) &&
3318 "uniform recipe shouldn't be predicated");
3319 assert(!State.VF.isScalable() && "Can't scalarize a scalable vector");
3320 scalarizeInstruction(UI, this, *State.Lane, State);
3321 // Insert scalar instance packing it into a vector.
3322 if (State.VF.isVector() && shouldPack()) {
3323 Value *WideValue =
3324 State.Lane->isFirstLane()
3325 ? PoisonValue::get(toVectorizedTy(UI->getType(), State.VF))
3326 : State.get(this);
3327 State.set(this, State.packScalarIntoVectorizedValue(this, WideValue,
3328 *State.Lane));
3329 }
3330}
3331
3333 // Find if the recipe is used by a widened recipe via an intervening
3334 // VPPredInstPHIRecipe. In this case, also pack the scalar values in a vector.
3335 return any_of(users(), [](const VPUser *U) {
3336 if (auto *PredR = dyn_cast<VPPredInstPHIRecipe>(U))
3337 return !vputils::onlyScalarValuesUsed(PredR);
3338 return false;
3339 });
3340}
3341
3342/// Returns a SCEV expression for \p Ptr if it is a pointer computation for
3343/// which the legacy cost model computes a SCEV expression when computing the
3344/// address cost. Computing SCEVs for VPValues is incomplete and returns
3345/// SCEVCouldNotCompute in cases the legacy cost model can compute SCEVs. In
3346/// those cases we fall back to the legacy cost model. Otherwise return nullptr.
3347static const SCEV *getAddressAccessSCEV(const VPValue *Ptr,
3349 const Loop *L) {
3350 const SCEV *Addr = vputils::getSCEVExprForVPValue(Ptr, PSE, L);
3351 if (isa<SCEVCouldNotCompute>(Addr))
3352 return Addr;
3353
3354 return vputils::isAddressSCEVForCost(Addr, *PSE.getSE(), L) ? Addr : nullptr;
3355}
3356
3357/// Returns true if \p V is used as part of the address of another load or
3358/// store.
3359static bool isUsedByLoadStoreAddress(const VPUser *V) {
3361 SmallVector<const VPUser *> WorkList = {V};
3362
3363 while (!WorkList.empty()) {
3364 auto *Cur = dyn_cast<VPSingleDefRecipe>(WorkList.pop_back_val());
3365 if (!Cur || !Seen.insert(Cur).second)
3366 continue;
3367
3368 auto *Blend = dyn_cast<VPBlendRecipe>(Cur);
3369 // Skip blends that use V only through a compare by checking if any incoming
3370 // value was already visited.
3371 if (Blend && none_of(seq<unsigned>(0, Blend->getNumIncomingValues()),
3372 [&](unsigned I) {
3373 return Seen.contains(
3374 Blend->getIncomingValue(I)->getDefiningRecipe());
3375 }))
3376 continue;
3377
3378 for (VPUser *U : Cur->users()) {
3379 if (auto *InterleaveR = dyn_cast<VPInterleaveBase>(U))
3380 if (InterleaveR->getAddr() == Cur)
3381 return true;
3382 if (auto *RepR = dyn_cast<VPReplicateRecipe>(U)) {
3383 if (RepR->getOpcode() == Instruction::Load &&
3384 RepR->getOperand(0) == Cur)
3385 return true;
3386 if (RepR->getOpcode() == Instruction::Store &&
3387 RepR->getOperand(1) == Cur)
3388 return true;
3389 }
3390 if (auto *MemR = dyn_cast<VPWidenMemoryRecipe>(U)) {
3391 if (MemR->getAddr() == Cur && MemR->isConsecutive())
3392 return true;
3393 }
3394 }
3395
3396 // The legacy cost model only supports scalarization loads/stores with phi
3397 // addresses, if the phi is directly used as load/store address. Don't
3398 // traverse further for Blends.
3399 if (Blend)
3400 continue;
3401
3402 append_range(WorkList, Cur->users());
3403 }
3404 return false;
3405}
3406
3408 VPCostContext &Ctx) const {
3410 // VPReplicateRecipe may be cloned as part of an existing VPlan-to-VPlan
3411 // transform, avoid computing their cost multiple times for now.
3412 Ctx.SkipCostComputation.insert(UI);
3413
3414 if (VF.isScalable() && !isSingleScalar())
3416
3417 switch (UI->getOpcode()) {
3418 case Instruction::Alloca:
3419 if (VF.isScalable())
3421 return Ctx.TTI.getArithmeticInstrCost(
3422 Instruction::Mul, Ctx.Types.inferScalarType(this), Ctx.CostKind);
3423 case Instruction::GetElementPtr:
3424 // We mark this instruction as zero-cost because the cost of GEPs in
3425 // vectorized code depends on whether the corresponding memory instruction
3426 // is scalarized or not. Therefore, we handle GEPs with the memory
3427 // instruction cost.
3428 return 0;
3429 case Instruction::Call: {
3430 auto *CalledFn =
3432
3435 for (const VPValue *ArgOp : ArgOps)
3436 Tys.push_back(Ctx.Types.inferScalarType(ArgOp));
3437
3438 if (CalledFn->isIntrinsic())
3439 // Various pseudo-intrinsics with costs of 0 are scalarized instead of
3440 // vectorized via VPWidenIntrinsicRecipe. Return 0 for them early.
3441 switch (CalledFn->getIntrinsicID()) {
3442 case Intrinsic::assume:
3443 case Intrinsic::lifetime_end:
3444 case Intrinsic::lifetime_start:
3445 case Intrinsic::sideeffect:
3446 case Intrinsic::pseudoprobe:
3447 case Intrinsic::experimental_noalias_scope_decl: {
3448 assert(getCostForIntrinsics(CalledFn->getIntrinsicID(), ArgOps, *this,
3449 ElementCount::getFixed(1), Ctx) == 0 &&
3450 "scalarizing intrinsic should be free");
3451 return InstructionCost(0);
3452 }
3453 default:
3454 break;
3455 }
3456
3457 Type *ResultTy = Ctx.Types.inferScalarType(this);
3458 InstructionCost ScalarCallCost =
3459 Ctx.TTI.getCallInstrCost(CalledFn, ResultTy, Tys, Ctx.CostKind);
3460 if (isSingleScalar()) {
3461 if (CalledFn->isIntrinsic())
3462 ScalarCallCost = std::min(
3463 ScalarCallCost,
3464 getCostForIntrinsics(CalledFn->getIntrinsicID(), ArgOps, *this,
3465 ElementCount::getFixed(1), Ctx));
3466 return ScalarCallCost;
3467 }
3468
3469 return ScalarCallCost * VF.getFixedValue() +
3470 Ctx.getScalarizationOverhead(ResultTy, ArgOps, VF);
3471 }
3472 case Instruction::Add:
3473 case Instruction::Sub:
3474 case Instruction::FAdd:
3475 case Instruction::FSub:
3476 case Instruction::Mul:
3477 case Instruction::FMul:
3478 case Instruction::FDiv:
3479 case Instruction::FRem:
3480 case Instruction::Shl:
3481 case Instruction::LShr:
3482 case Instruction::AShr:
3483 case Instruction::And:
3484 case Instruction::Or:
3485 case Instruction::Xor:
3486 case Instruction::ICmp:
3487 case Instruction::FCmp:
3489 Ctx) *
3490 (isSingleScalar() ? 1 : VF.getFixedValue());
3491 case Instruction::SDiv:
3492 case Instruction::UDiv:
3493 case Instruction::SRem:
3494 case Instruction::URem: {
3495 InstructionCost ScalarCost =
3497 if (isSingleScalar())
3498 return ScalarCost;
3499
3500 // If any of the operands is from a different replicate region and has its
3501 // cost skipped, it may have been forced to scalar. Fall back to legacy cost
3502 // model to avoid cost mis-match.
3503 if (any_of(operands(), [&Ctx, VF](VPValue *Op) {
3504 auto *PredR = dyn_cast<VPPredInstPHIRecipe>(Op);
3505 if (!PredR)
3506 return false;
3507 return Ctx.skipCostComputation(
3509 PredR->getOperand(0)->getUnderlyingValue()),
3510 VF.isVector());
3511 }))
3512 break;
3513
3514 ScalarCost = ScalarCost * VF.getFixedValue() +
3515 Ctx.getScalarizationOverhead(Ctx.Types.inferScalarType(this),
3516 to_vector(operands()), VF);
3517 // If the recipe is not predicated (i.e. not in a replicate region), return
3518 // the scalar cost. Otherwise handle predicated cost.
3519 if (!getRegion()->isReplicator())
3520 return ScalarCost;
3521
3522 // Account for the phi nodes that we will create.
3523 ScalarCost += VF.getFixedValue() *
3524 Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
3525 // Scale the cost by the probability of executing the predicated blocks.
3526 // This assumes the predicated block for each vector lane is equally
3527 // likely.
3528 ScalarCost /= Ctx.getPredBlockCostDivisor(UI->getParent());
3529 return ScalarCost;
3530 }
3531 case Instruction::Load:
3532 case Instruction::Store: {
3533 bool IsLoad = UI->getOpcode() == Instruction::Load;
3534 const VPValue *PtrOp = getOperand(!IsLoad);
3535 const SCEV *PtrSCEV = getAddressAccessSCEV(PtrOp, Ctx.PSE, Ctx.L);
3537 break;
3538
3539 Type *ValTy = Ctx.Types.inferScalarType(IsLoad ? this : getOperand(0));
3540 Type *ScalarPtrTy = Ctx.Types.inferScalarType(PtrOp);
3541 const Align Alignment = getLoadStoreAlignment(UI);
3542 unsigned AS = cast<PointerType>(ScalarPtrTy)->getAddressSpace();
3544 bool PreferVectorizedAddressing = Ctx.TTI.prefersVectorizedAddressing();
3545 bool UsedByLoadStoreAddress =
3546 !PreferVectorizedAddressing && isUsedByLoadStoreAddress(this);
3547 InstructionCost ScalarMemOpCost = Ctx.TTI.getMemoryOpCost(
3548 UI->getOpcode(), ValTy, Alignment, AS, Ctx.CostKind, OpInfo,
3549 UsedByLoadStoreAddress ? UI : nullptr);
3550
3551 Type *PtrTy = isSingleScalar() ? ScalarPtrTy : toVectorTy(ScalarPtrTy, VF);
3552 InstructionCost ScalarCost =
3553 ScalarMemOpCost +
3554 Ctx.TTI.getAddressComputationCost(
3555 PtrTy, UsedByLoadStoreAddress ? nullptr : Ctx.PSE.getSE(), PtrSCEV,
3556 Ctx.CostKind);
3557 if (isSingleScalar())
3558 return ScalarCost;
3559
3560 SmallVector<const VPValue *> OpsToScalarize;
3561 Type *ResultTy = Type::getVoidTy(PtrTy->getContext());
3562 // Set ResultTy and OpsToScalarize, if scalarization is needed. Currently we
3563 // don't assign scalarization overhead in general, if the target prefers
3564 // vectorized addressing or the loaded value is used as part of an address
3565 // of another load or store.
3566 if (!UsedByLoadStoreAddress) {
3567 bool EfficientVectorLoadStore =
3568 Ctx.TTI.supportsEfficientVectorElementLoadStore();
3569 if (!(IsLoad && !PreferVectorizedAddressing) &&
3570 !(!IsLoad && EfficientVectorLoadStore))
3571 append_range(OpsToScalarize, operands());
3572
3573 if (!EfficientVectorLoadStore)
3574 ResultTy = Ctx.Types.inferScalarType(this);
3575 }
3576
3580 (ScalarCost * VF.getFixedValue()) +
3581 Ctx.getScalarizationOverhead(ResultTy, OpsToScalarize, VF, VIC, true);
3582
3583 const VPRegionBlock *ParentRegion = getRegion();
3584 if (ParentRegion && ParentRegion->isReplicator()) {
3585 // TODO: Handle loop-invariant pointers in predicated blocks. For now,
3586 // fall back to the legacy cost model.
3587 if (!PtrSCEV || Ctx.PSE.getSE()->isLoopInvariant(PtrSCEV, Ctx.L))
3588 break;
3589 Cost /= Ctx.getPredBlockCostDivisor(UI->getParent());
3590 Cost += Ctx.TTI.getCFInstrCost(Instruction::CondBr, Ctx.CostKind);
3591
3592 auto *VecI1Ty = VectorType::get(
3593 IntegerType::getInt1Ty(Ctx.L->getHeader()->getContext()), VF);
3594 Cost += Ctx.TTI.getScalarizationOverhead(
3595 VecI1Ty, APInt::getAllOnes(VF.getFixedValue()),
3596 /*Insert=*/false, /*Extract=*/true, Ctx.CostKind);
3597
3598 if (Ctx.useEmulatedMaskMemRefHack(this, VF)) {
3599 // Artificially setting to a high enough value to practically disable
3600 // vectorization with such operations.
3601 return 3000000;
3602 }
3603 }
3604 return Cost;
3605 }
3606 case Instruction::SExt:
3607 case Instruction::ZExt:
3608 case Instruction::FPToUI:
3609 case Instruction::FPToSI:
3610 case Instruction::FPExt:
3611 case Instruction::PtrToInt:
3612 case Instruction::PtrToAddr:
3613 case Instruction::IntToPtr:
3614 case Instruction::SIToFP:
3615 case Instruction::UIToFP:
3616 case Instruction::Trunc:
3617 case Instruction::FPTrunc:
3618 case Instruction::AddrSpaceCast: {
3620 Ctx) *
3621 (isSingleScalar() ? 1 : VF.getFixedValue());
3622 }
3623 case Instruction::ExtractValue:
3624 case Instruction::InsertValue:
3625 return Ctx.TTI.getInsertExtractValueCost(getOpcode(), Ctx.CostKind);
3626 }
3627
3628 return Ctx.getLegacyCost(UI, VF);
3629}
3630
3631#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3633 VPSlotTracker &SlotTracker) const {
3634 O << Indent << (IsSingleScalar ? "CLONE " : "REPLICATE ");
3635
3636 if (!getUnderlyingInstr()->getType()->isVoidTy()) {
3638 O << " = ";
3639 }
3640 if (auto *CB = dyn_cast<CallBase>(getUnderlyingInstr())) {
3641 O << "call";
3642 printFlags(O);
3643 O << "@" << CB->getCalledFunction()->getName() << "(";
3645 O, [&O, &SlotTracker](VPValue *Op) {
3646 Op->printAsOperand(O, SlotTracker);
3647 });
3648 O << ")";
3649 } else {
3651 printFlags(O);
3653 }
3654
3655 if (shouldPack())
3656 O << " (S->V)";
3657}
3658#endif
3659
3661 assert(State.Lane && "Branch on Mask works only on single instance.");
3662
3663 VPValue *BlockInMask = getOperand(0);
3664 Value *ConditionBit = State.get(BlockInMask, *State.Lane);
3665
3666 // Replace the temporary unreachable terminator with a new conditional branch,
3667 // whose two destinations will be set later when they are created.
3668 auto *CurrentTerminator = State.CFG.PrevBB->getTerminator();
3669 assert(isa<UnreachableInst>(CurrentTerminator) &&
3670 "Expected to replace unreachable terminator with conditional branch.");
3671 auto CondBr =
3672 State.Builder.CreateCondBr(ConditionBit, State.CFG.PrevBB, nullptr);
3673 CondBr->setSuccessor(0, nullptr);
3674 CurrentTerminator->eraseFromParent();
3675}
3676
3678 VPCostContext &Ctx) const {
3679 // The legacy cost model doesn't assign costs to branches for individual
3680 // replicate regions. Match the current behavior in the VPlan cost model for
3681 // now.
3682 return 0;
3683}
3684
3686 assert(State.Lane && "Predicated instruction PHI works per instance.");
3687 Instruction *ScalarPredInst =
3688 cast<Instruction>(State.get(getOperand(0), *State.Lane));
3689 BasicBlock *PredicatedBB = ScalarPredInst->getParent();
3690 BasicBlock *PredicatingBB = PredicatedBB->getSinglePredecessor();
3691 assert(PredicatingBB && "Predicated block has no single predecessor.");
3693 "operand must be VPReplicateRecipe");
3694
3695 // By current pack/unpack logic we need to generate only a single phi node: if
3696 // a vector value for the predicated instruction exists at this point it means
3697 // the instruction has vector users only, and a phi for the vector value is
3698 // needed. In this case the recipe of the predicated instruction is marked to
3699 // also do that packing, thereby "hoisting" the insert-element sequence.
3700 // Otherwise, a phi node for the scalar value is needed.
3701 if (State.hasVectorValue(getOperand(0))) {
3702 auto *VecI = cast<Instruction>(State.get(getOperand(0)));
3704 "Packed operands must generate an insertelement or insertvalue");
3705
3706 // If VectorI is a struct, it will be a sequence like:
3707 // %1 = insertvalue %unmodified, %x, 0
3708 // %2 = insertvalue %1, %y, 1
3709 // %VectorI = insertvalue %2, %z, 2
3710 // To get the unmodified vector we need to look through the chain.
3711 if (auto *StructTy = dyn_cast<StructType>(VecI->getType()))
3712 for (unsigned I = 0; I < StructTy->getNumContainedTypes() - 1; I++)
3713 VecI = cast<InsertValueInst>(VecI->getOperand(0));
3714
3715 PHINode *VPhi = State.Builder.CreatePHI(VecI->getType(), 2);
3716 VPhi->addIncoming(VecI->getOperand(0), PredicatingBB); // Unmodified vector.
3717 VPhi->addIncoming(VecI, PredicatedBB); // New vector with inserted element.
3718 if (State.hasVectorValue(this))
3719 State.reset(this, VPhi);
3720 else
3721 State.set(this, VPhi);
3722 // NOTE: Currently we need to update the value of the operand, so the next
3723 // predicated iteration inserts its generated value in the correct vector.
3724 State.reset(getOperand(0), VPhi);
3725 } else {
3726 if (vputils::onlyFirstLaneUsed(this) && !State.Lane->isFirstLane())
3727 return;
3728
3729 Type *PredInstType = State.TypeAnalysis.inferScalarType(getOperand(0));
3730 PHINode *Phi = State.Builder.CreatePHI(PredInstType, 2);
3731 Phi->addIncoming(PoisonValue::get(ScalarPredInst->getType()),
3732 PredicatingBB);
3733 Phi->addIncoming(ScalarPredInst, PredicatedBB);
3734 if (State.hasScalarValue(this, *State.Lane))
3735 State.reset(this, Phi, *State.Lane);
3736 else
3737 State.set(this, Phi, *State.Lane);
3738 // NOTE: Currently we need to update the value of the operand, so the next
3739 // predicated iteration inserts its generated value in the correct vector.
3740 State.reset(getOperand(0), Phi, *State.Lane);
3741 }
3742}
3743
3744#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3746 VPSlotTracker &SlotTracker) const {
3747 O << Indent << "PHI-PREDICATED-INSTRUCTION ";
3749 O << " = ";
3751}
3752#endif
3753
3755 VPCostContext &Ctx) const {
3757 unsigned AS = cast<PointerType>(Ctx.Types.inferScalarType(getAddr()))
3758 ->getAddressSpace();
3759 unsigned Opcode = isa<VPWidenLoadRecipe, VPWidenLoadEVLRecipe>(this)
3760 ? Instruction::Load
3761 : Instruction::Store;
3762
3763 if (!Consecutive) {
3764 // TODO: Using the original IR may not be accurate.
3765 // Currently, ARM will use the underlying IR to calculate gather/scatter
3766 // instruction cost.
3767 assert(!Reverse &&
3768 "Inconsecutive memory access should not have the order.");
3769
3771 Type *PtrTy = Ptr->getType();
3772
3773 // If the address value is uniform across all lanes, then the address can be
3774 // calculated with scalar type and broadcast.
3776 PtrTy = toVectorTy(PtrTy, VF);
3777
3778 unsigned IID = isa<VPWidenLoadRecipe>(this) ? Intrinsic::masked_gather
3779 : isa<VPWidenStoreRecipe>(this) ? Intrinsic::masked_scatter
3780 : isa<VPWidenLoadEVLRecipe>(this) ? Intrinsic::vp_gather
3781 : Intrinsic::vp_scatter;
3782 return Ctx.TTI.getAddressComputationCost(PtrTy, nullptr, nullptr,
3783 Ctx.CostKind) +
3784 Ctx.TTI.getMemIntrinsicInstrCost(
3786 &Ingredient),
3787 Ctx.CostKind);
3788 }
3789
3791 if (IsMasked) {
3792 unsigned IID = isa<VPWidenLoadRecipe>(this) ? Intrinsic::masked_load
3793 : Intrinsic::masked_store;
3794 Cost += Ctx.TTI.getMemIntrinsicInstrCost(
3795 MemIntrinsicCostAttributes(IID, Ty, Alignment, AS), Ctx.CostKind);
3796 } else {
3797 TTI::OperandValueInfo OpInfo = Ctx.getOperandInfo(
3799 : getOperand(1));
3800 Cost += Ctx.TTI.getMemoryOpCost(Opcode, Ty, Alignment, AS, Ctx.CostKind,
3801 OpInfo, &Ingredient);
3802 }
3803 return Cost;
3804}
3805
3807 Type *ScalarDataTy = getLoadStoreType(&Ingredient);
3808 auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
3809 bool CreateGather = !isConsecutive();
3810
3811 auto &Builder = State.Builder;
3812 Value *Mask = nullptr;
3813 if (auto *VPMask = getMask()) {
3814 // Mask reversal is only needed for non-all-one (null) masks, as reverse
3815 // of a null all-one mask is a null mask.
3816 Mask = State.get(VPMask);
3817 if (isReverse())
3818 Mask = Builder.CreateVectorReverse(Mask, "reverse");
3819 }
3820
3821 Value *Addr = State.get(getAddr(), /*IsScalar*/ !CreateGather);
3822 Value *NewLI;
3823 if (CreateGather) {
3824 NewLI = Builder.CreateMaskedGather(DataTy, Addr, Alignment, Mask, nullptr,
3825 "wide.masked.gather");
3826 } else if (Mask) {
3827 NewLI =
3828 Builder.CreateMaskedLoad(DataTy, Addr, Alignment, Mask,
3829 PoisonValue::get(DataTy), "wide.masked.load");
3830 } else {
3831 NewLI = Builder.CreateAlignedLoad(DataTy, Addr, Alignment, "wide.load");
3832 }
3834 State.set(this, NewLI);
3835}
3836
3837#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3839 VPSlotTracker &SlotTracker) const {
3840 O << Indent << "WIDEN ";
3842 O << " = load ";
3844}
3845#endif
3846
3847/// Use all-true mask for reverse rather than actual mask, as it avoids a
3848/// dependence w/o affecting the result.
3850 Value *EVL, const Twine &Name) {
3851 VectorType *ValTy = cast<VectorType>(Operand->getType());
3852 Value *AllTrueMask =
3853 Builder.CreateVectorSplat(ValTy->getElementCount(), Builder.getTrue());
3854 return Builder.CreateIntrinsic(ValTy, Intrinsic::experimental_vp_reverse,
3855 {Operand, AllTrueMask, EVL}, nullptr, Name);
3856}
3857
3859 Type *ScalarDataTy = getLoadStoreType(&Ingredient);
3860 auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
3861 bool CreateGather = !isConsecutive();
3862
3863 auto &Builder = State.Builder;
3864 CallInst *NewLI;
3865 Value *EVL = State.get(getEVL(), VPLane(0));
3866 Value *Addr = State.get(getAddr(), !CreateGather);
3867 Value *Mask = nullptr;
3868 if (VPValue *VPMask = getMask()) {
3869 Mask = State.get(VPMask);
3870 if (isReverse())
3871 Mask = createReverseEVL(Builder, Mask, EVL, "vp.reverse.mask");
3872 } else {
3873 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
3874 }
3875
3876 if (CreateGather) {
3877 NewLI =
3878 Builder.CreateIntrinsic(DataTy, Intrinsic::vp_gather, {Addr, Mask, EVL},
3879 nullptr, "wide.masked.gather");
3880 } else {
3881 NewLI = Builder.CreateIntrinsic(DataTy, Intrinsic::vp_load,
3882 {Addr, Mask, EVL}, nullptr, "vp.op.load");
3883 }
3884 NewLI->addParamAttr(
3886 applyMetadata(*NewLI);
3887 Instruction *Res = NewLI;
3888 State.set(this, Res);
3889}
3890
3892 VPCostContext &Ctx) const {
3893 if (!Consecutive || IsMasked)
3894 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
3895
3896 // We need to use the getMemIntrinsicInstrCost() instead of getMemoryOpCost()
3897 // here because the EVL recipes using EVL to replace the tail mask. But in the
3898 // legacy model, it will always calculate the cost of mask.
3899 // TODO: Using getMemoryOpCost() instead of getMemIntrinsicInstrCost when we
3900 // don't need to compare to the legacy cost model.
3902 unsigned AS = cast<PointerType>(Ctx.Types.inferScalarType(getAddr()))
3903 ->getAddressSpace();
3904 return Ctx.TTI.getMemIntrinsicInstrCost(
3905 MemIntrinsicCostAttributes(Intrinsic::vp_load, Ty, Alignment, AS),
3906 Ctx.CostKind);
3907}
3908
3909#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3911 VPSlotTracker &SlotTracker) const {
3912 O << Indent << "WIDEN ";
3914 O << " = vp.load ";
3916}
3917#endif
3918
3920 VPValue *StoredVPValue = getStoredValue();
3921 bool CreateScatter = !isConsecutive();
3922
3923 auto &Builder = State.Builder;
3924
3925 Value *Mask = nullptr;
3926 if (auto *VPMask = getMask()) {
3927 // Mask reversal is only needed for non-all-one (null) masks, as reverse
3928 // of a null all-one mask is a null mask.
3929 Mask = State.get(VPMask);
3930 if (isReverse())
3931 Mask = Builder.CreateVectorReverse(Mask, "reverse");
3932 }
3933
3934 Value *StoredVal = State.get(StoredVPValue);
3935 Value *Addr = State.get(getAddr(), /*IsScalar*/ !CreateScatter);
3936 Instruction *NewSI = nullptr;
3937 if (CreateScatter)
3938 NewSI = Builder.CreateMaskedScatter(StoredVal, Addr, Alignment, Mask);
3939 else if (Mask)
3940 NewSI = Builder.CreateMaskedStore(StoredVal, Addr, Alignment, Mask);
3941 else
3942 NewSI = Builder.CreateAlignedStore(StoredVal, Addr, Alignment);
3943 applyMetadata(*NewSI);
3944}
3945
3946#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3948 VPSlotTracker &SlotTracker) const {
3949 O << Indent << "WIDEN store ";
3951}
3952#endif
3953
3955 VPValue *StoredValue = getStoredValue();
3956 bool CreateScatter = !isConsecutive();
3957
3958 auto &Builder = State.Builder;
3959
3960 CallInst *NewSI = nullptr;
3961 Value *StoredVal = State.get(StoredValue);
3962 Value *EVL = State.get(getEVL(), VPLane(0));
3963 Value *Mask = nullptr;
3964 if (VPValue *VPMask = getMask()) {
3965 Mask = State.get(VPMask);
3966 if (isReverse())
3967 Mask = createReverseEVL(Builder, Mask, EVL, "vp.reverse.mask");
3968 } else {
3969 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
3970 }
3971 Value *Addr = State.get(getAddr(), !CreateScatter);
3972 if (CreateScatter) {
3973 NewSI = Builder.CreateIntrinsic(Type::getVoidTy(EVL->getContext()),
3974 Intrinsic::vp_scatter,
3975 {StoredVal, Addr, Mask, EVL});
3976 } else {
3977 NewSI = Builder.CreateIntrinsic(Type::getVoidTy(EVL->getContext()),
3978 Intrinsic::vp_store,
3979 {StoredVal, Addr, Mask, EVL});
3980 }
3981 NewSI->addParamAttr(
3983 applyMetadata(*NewSI);
3984}
3985
3987 VPCostContext &Ctx) const {
3988 if (!Consecutive || IsMasked)
3989 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
3990
3991 // We need to use the getMemIntrinsicInstrCost() instead of getMemoryOpCost()
3992 // here because the EVL recipes using EVL to replace the tail mask. But in the
3993 // legacy model, it will always calculate the cost of mask.
3994 // TODO: Using getMemoryOpCost() instead of getMemIntrinsicInstrCost when we
3995 // don't need to compare to the legacy cost model.
3997 unsigned AS = cast<PointerType>(Ctx.Types.inferScalarType(getAddr()))
3998 ->getAddressSpace();
3999 return Ctx.TTI.getMemIntrinsicInstrCost(
4000 MemIntrinsicCostAttributes(Intrinsic::vp_store, Ty, Alignment, AS),
4001 Ctx.CostKind);
4002}
4003
4004#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4006 VPSlotTracker &SlotTracker) const {
4007 O << Indent << "WIDEN vp.store ";
4009}
4010#endif
4011
4013 VectorType *DstVTy, const DataLayout &DL) {
4014 // Verify that V is a vector type with same number of elements as DstVTy.
4015 auto VF = DstVTy->getElementCount();
4016 auto *SrcVecTy = cast<VectorType>(V->getType());
4017 assert(VF == SrcVecTy->getElementCount() && "Vector dimensions do not match");
4018 Type *SrcElemTy = SrcVecTy->getElementType();
4019 Type *DstElemTy = DstVTy->getElementType();
4020 assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&
4021 "Vector elements must have same size");
4022
4023 // Do a direct cast if element types are castable.
4024 if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
4025 return Builder.CreateBitOrPointerCast(V, DstVTy);
4026 }
4027 // V cannot be directly casted to desired vector type.
4028 // May happen when V is a floating point vector but DstVTy is a vector of
4029 // pointers or vice-versa. Handle this using a two-step bitcast using an
4030 // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
4031 assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&
4032 "Only one type should be a pointer type");
4033 assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&
4034 "Only one type should be a floating point type");
4035 Type *IntTy =
4036 IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy));
4037 auto *VecIntTy = VectorType::get(IntTy, VF);
4038 Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
4039 return Builder.CreateBitOrPointerCast(CastVal, DstVTy);
4040}
4041
4042/// Return a vector containing interleaved elements from multiple
4043/// smaller input vectors.
4045 const Twine &Name) {
4046 unsigned Factor = Vals.size();
4047 assert(Factor > 1 && "Tried to interleave invalid number of vectors");
4048
4049 VectorType *VecTy = cast<VectorType>(Vals[0]->getType());
4050#ifndef NDEBUG
4051 for (Value *Val : Vals)
4052 assert(Val->getType() == VecTy && "Tried to interleave mismatched types");
4053#endif
4054
4055 // Scalable vectors cannot use arbitrary shufflevectors (only splats), so
4056 // must use intrinsics to interleave.
4057 if (VecTy->isScalableTy()) {
4058 assert(Factor <= 8 && "Unsupported interleave factor for scalable vectors");
4059 return Builder.CreateVectorInterleave(Vals, Name);
4060 }
4061
4062 // Fixed length. Start by concatenating all vectors into a wide vector.
4063 Value *WideVec = concatenateVectors(Builder, Vals);
4064
4065 // Interleave the elements into the wide vector.
4066 const unsigned NumElts = VecTy->getElementCount().getFixedValue();
4067 return Builder.CreateShuffleVector(
4068 WideVec, createInterleaveMask(NumElts, Factor), Name);
4069}
4070
4071// Try to vectorize the interleave group that \p Instr belongs to.
4072//
4073// E.g. Translate following interleaved load group (factor = 3):
4074// for (i = 0; i < N; i+=3) {
4075// R = Pic[i]; // Member of index 0
4076// G = Pic[i+1]; // Member of index 1
4077// B = Pic[i+2]; // Member of index 2
4078// ... // do something to R, G, B
4079// }
4080// To:
4081// %wide.vec = load <12 x i32> ; Read 4 tuples of R,G,B
4082// %R.vec = shuffle %wide.vec, poison, <0, 3, 6, 9> ; R elements
4083// %G.vec = shuffle %wide.vec, poison, <1, 4, 7, 10> ; G elements
4084// %B.vec = shuffle %wide.vec, poison, <2, 5, 8, 11> ; B elements
4085//
4086// Or translate following interleaved store group (factor = 3):
4087// for (i = 0; i < N; i+=3) {
4088// ... do something to R, G, B
4089// Pic[i] = R; // Member of index 0
4090// Pic[i+1] = G; // Member of index 1
4091// Pic[i+2] = B; // Member of index 2
4092// }
4093// To:
4094// %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
4095// %B_U.vec = shuffle %B.vec, poison, <0, 1, 2, 3, u, u, u, u>
4096// %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
4097// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> ; Interleave R,G,B elements
4098// store <12 x i32> %interleaved.vec ; Write 4 tuples of R,G,B
4100 assert(!State.Lane && "Interleave group being replicated.");
4101 assert((!needsMaskForGaps() || !State.VF.isScalable()) &&
4102 "Masking gaps for scalable vectors is not yet supported.");
4104 Instruction *Instr = Group->getInsertPos();
4105
4106 // Prepare for the vector type of the interleaved load/store.
4107 Type *ScalarTy = getLoadStoreType(Instr);
4108 unsigned InterleaveFactor = Group->getFactor();
4109 auto *VecTy = VectorType::get(ScalarTy, State.VF * InterleaveFactor);
4110
4111 VPValue *BlockInMask = getMask();
4112 VPValue *Addr = getAddr();
4113 Value *ResAddr = State.get(Addr, VPLane(0));
4114
4115 auto CreateGroupMask = [&BlockInMask, &State,
4116 &InterleaveFactor](Value *MaskForGaps) -> Value * {
4117 if (State.VF.isScalable()) {
4118 assert(!MaskForGaps && "Interleaved groups with gaps are not supported.");
4119 assert(InterleaveFactor <= 8 &&
4120 "Unsupported deinterleave factor for scalable vectors");
4121 auto *ResBlockInMask = State.get(BlockInMask);
4122 SmallVector<Value *> Ops(InterleaveFactor, ResBlockInMask);
4123 return interleaveVectors(State.Builder, Ops, "interleaved.mask");
4124 }
4125
4126 if (!BlockInMask)
4127 return MaskForGaps;
4128
4129 Value *ResBlockInMask = State.get(BlockInMask);
4130 Value *ShuffledMask = State.Builder.CreateShuffleVector(
4131 ResBlockInMask,
4132 createReplicatedMask(InterleaveFactor, State.VF.getFixedValue()),
4133 "interleaved.mask");
4134 return MaskForGaps ? State.Builder.CreateBinOp(Instruction::And,
4135 ShuffledMask, MaskForGaps)
4136 : ShuffledMask;
4137 };
4138
4139 const DataLayout &DL = Instr->getDataLayout();
4140 // Vectorize the interleaved load group.
4141 if (isa<LoadInst>(Instr)) {
4142 Value *MaskForGaps = nullptr;
4143 if (needsMaskForGaps()) {
4144 MaskForGaps =
4145 createBitMaskForGaps(State.Builder, State.VF.getFixedValue(), *Group);
4146 assert(MaskForGaps && "Mask for Gaps is required but it is null");
4147 }
4148
4149 Instruction *NewLoad;
4150 if (BlockInMask || MaskForGaps) {
4151 Value *GroupMask = CreateGroupMask(MaskForGaps);
4152 Value *PoisonVec = PoisonValue::get(VecTy);
4153 NewLoad = State.Builder.CreateMaskedLoad(VecTy, ResAddr,
4154 Group->getAlign(), GroupMask,
4155 PoisonVec, "wide.masked.vec");
4156 } else
4157 NewLoad = State.Builder.CreateAlignedLoad(VecTy, ResAddr,
4158 Group->getAlign(), "wide.vec");
4159 applyMetadata(*NewLoad);
4160 // TODO: Also manage existing metadata using VPIRMetadata.
4161 Group->addMetadata(NewLoad);
4162
4164 if (VecTy->isScalableTy()) {
4165 // Scalable vectors cannot use arbitrary shufflevectors (only splats),
4166 // so must use intrinsics to deinterleave.
4167 assert(InterleaveFactor <= 8 &&
4168 "Unsupported deinterleave factor for scalable vectors");
4169 NewLoad = State.Builder.CreateIntrinsic(
4170 Intrinsic::getDeinterleaveIntrinsicID(InterleaveFactor),
4171 NewLoad->getType(), NewLoad,
4172 /*FMFSource=*/nullptr, "strided.vec");
4173 }
4174
4175 auto CreateStridedVector = [&InterleaveFactor, &State,
4176 &NewLoad](unsigned Index) -> Value * {
4177 assert(Index < InterleaveFactor && "Illegal group index");
4178 if (State.VF.isScalable())
4179 return State.Builder.CreateExtractValue(NewLoad, Index);
4180
4181 // For fixed length VF, use shuffle to extract the sub-vectors from the
4182 // wide load.
4183 auto StrideMask =
4184 createStrideMask(Index, InterleaveFactor, State.VF.getFixedValue());
4185 return State.Builder.CreateShuffleVector(NewLoad, StrideMask,
4186 "strided.vec");
4187 };
4188
4189 for (unsigned I = 0, J = 0; I < InterleaveFactor; ++I) {
4190 Instruction *Member = Group->getMember(I);
4191
4192 // Skip the gaps in the group.
4193 if (!Member)
4194 continue;
4195
4196 Value *StridedVec = CreateStridedVector(I);
4197
4198 // If this member has different type, cast the result type.
4199 if (Member->getType() != ScalarTy) {
4200 VectorType *OtherVTy = VectorType::get(Member->getType(), State.VF);
4201 StridedVec =
4202 createBitOrPointerCast(State.Builder, StridedVec, OtherVTy, DL);
4203 }
4204
4205 if (Group->isReverse())
4206 StridedVec = State.Builder.CreateVectorReverse(StridedVec, "reverse");
4207
4208 State.set(VPDefs[J], StridedVec);
4209 ++J;
4210 }
4211 return;
4212 }
4213
4214 // The sub vector type for current instruction.
4215 auto *SubVT = VectorType::get(ScalarTy, State.VF);
4216
4217 // Vectorize the interleaved store group.
4218 Value *MaskForGaps =
4219 createBitMaskForGaps(State.Builder, State.VF.getKnownMinValue(), *Group);
4220 assert(((MaskForGaps != nullptr) == needsMaskForGaps()) &&
4221 "Mismatch between NeedsMaskForGaps and MaskForGaps");
4222 ArrayRef<VPValue *> StoredValues = getStoredValues();
4223 // Collect the stored vector from each member.
4224 SmallVector<Value *, 4> StoredVecs;
4225 unsigned StoredIdx = 0;
4226 for (unsigned i = 0; i < InterleaveFactor; i++) {
4227 assert((Group->getMember(i) || MaskForGaps) &&
4228 "Fail to get a member from an interleaved store group");
4229 Instruction *Member = Group->getMember(i);
4230
4231 // Skip the gaps in the group.
4232 if (!Member) {
4233 Value *Undef = PoisonValue::get(SubVT);
4234 StoredVecs.push_back(Undef);
4235 continue;
4236 }
4237
4238 Value *StoredVec = State.get(StoredValues[StoredIdx]);
4239 ++StoredIdx;
4240
4241 if (Group->isReverse())
4242 StoredVec = State.Builder.CreateVectorReverse(StoredVec, "reverse");
4243
4244 // If this member has different type, cast it to a unified type.
4245
4246 if (StoredVec->getType() != SubVT)
4247 StoredVec = createBitOrPointerCast(State.Builder, StoredVec, SubVT, DL);
4248
4249 StoredVecs.push_back(StoredVec);
4250 }
4251
4252 // Interleave all the smaller vectors into one wider vector.
4253 Value *IVec = interleaveVectors(State.Builder, StoredVecs, "interleaved.vec");
4254 Instruction *NewStoreInstr;
4255 if (BlockInMask || MaskForGaps) {
4256 Value *GroupMask = CreateGroupMask(MaskForGaps);
4257 NewStoreInstr = State.Builder.CreateMaskedStore(
4258 IVec, ResAddr, Group->getAlign(), GroupMask);
4259 } else
4260 NewStoreInstr =
4261 State.Builder.CreateAlignedStore(IVec, ResAddr, Group->getAlign());
4262
4263 applyMetadata(*NewStoreInstr);
4264 // TODO: Also manage existing metadata using VPIRMetadata.
4265 Group->addMetadata(NewStoreInstr);
4266}
4267
4268#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4270 VPSlotTracker &SlotTracker) const {
4272 O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << " at ";
4273 IG->getInsertPos()->printAsOperand(O, false);
4274 O << ", ";
4276 VPValue *Mask = getMask();
4277 if (Mask) {
4278 O << ", ";
4279 Mask->printAsOperand(O, SlotTracker);
4280 }
4281
4282 unsigned OpIdx = 0;
4283 for (unsigned i = 0; i < IG->getFactor(); ++i) {
4284 if (!IG->getMember(i))
4285 continue;
4286 if (getNumStoreOperands() > 0) {
4287 O << "\n" << Indent << " store ";
4289 O << " to index " << i;
4290 } else {
4291 O << "\n" << Indent << " ";
4293 O << " = load from index " << i;
4294 }
4295 ++OpIdx;
4296 }
4297}
4298#endif
4299
4301 assert(!State.Lane && "Interleave group being replicated.");
4302 assert(State.VF.isScalable() &&
4303 "Only support scalable VF for EVL tail-folding.");
4305 "Masking gaps for scalable vectors is not yet supported.");
4307 Instruction *Instr = Group->getInsertPos();
4308
4309 // Prepare for the vector type of the interleaved load/store.
4310 Type *ScalarTy = getLoadStoreType(Instr);
4311 unsigned InterleaveFactor = Group->getFactor();
4312 assert(InterleaveFactor <= 8 &&
4313 "Unsupported deinterleave/interleave factor for scalable vectors");
4314 ElementCount WideVF = State.VF * InterleaveFactor;
4315 auto *VecTy = VectorType::get(ScalarTy, WideVF);
4316
4317 VPValue *Addr = getAddr();
4318 Value *ResAddr = State.get(Addr, VPLane(0));
4319 Value *EVL = State.get(getEVL(), VPLane(0));
4320 Value *InterleaveEVL = State.Builder.CreateMul(
4321 EVL, ConstantInt::get(EVL->getType(), InterleaveFactor), "interleave.evl",
4322 /* NUW= */ true, /* NSW= */ true);
4323 LLVMContext &Ctx = State.Builder.getContext();
4324
4325 Value *GroupMask = nullptr;
4326 if (VPValue *BlockInMask = getMask()) {
4327 SmallVector<Value *> Ops(InterleaveFactor, State.get(BlockInMask));
4328 GroupMask = interleaveVectors(State.Builder, Ops, "interleaved.mask");
4329 } else {
4330 GroupMask =
4331 State.Builder.CreateVectorSplat(WideVF, State.Builder.getTrue());
4332 }
4333
4334 // Vectorize the interleaved load group.
4335 if (isa<LoadInst>(Instr)) {
4336 CallInst *NewLoad = State.Builder.CreateIntrinsic(
4337 VecTy, Intrinsic::vp_load, {ResAddr, GroupMask, InterleaveEVL}, nullptr,
4338 "wide.vp.load");
4339 NewLoad->addParamAttr(0,
4340 Attribute::getWithAlignment(Ctx, Group->getAlign()));
4341
4342 applyMetadata(*NewLoad);
4343 // TODO: Also manage existing metadata using VPIRMetadata.
4344 Group->addMetadata(NewLoad);
4345
4346 // Scalable vectors cannot use arbitrary shufflevectors (only splats),
4347 // so must use intrinsics to deinterleave.
4348 NewLoad = State.Builder.CreateIntrinsic(
4349 Intrinsic::getDeinterleaveIntrinsicID(InterleaveFactor),
4350 NewLoad->getType(), NewLoad,
4351 /*FMFSource=*/nullptr, "strided.vec");
4352
4353 const DataLayout &DL = Instr->getDataLayout();
4354 for (unsigned I = 0, J = 0; I < InterleaveFactor; ++I) {
4355 Instruction *Member = Group->getMember(I);
4356 // Skip the gaps in the group.
4357 if (!Member)
4358 continue;
4359
4360 Value *StridedVec = State.Builder.CreateExtractValue(NewLoad, I);
4361 // If this member has different type, cast the result type.
4362 if (Member->getType() != ScalarTy) {
4363 VectorType *OtherVTy = VectorType::get(Member->getType(), State.VF);
4364 StridedVec =
4365 createBitOrPointerCast(State.Builder, StridedVec, OtherVTy, DL);
4366 }
4367
4368 State.set(getVPValue(J), StridedVec);
4369 ++J;
4370 }
4371 return;
4372 } // End for interleaved load.
4373
4374 // The sub vector type for current instruction.
4375 auto *SubVT = VectorType::get(ScalarTy, State.VF);
4376 // Vectorize the interleaved store group.
4377 ArrayRef<VPValue *> StoredValues = getStoredValues();
4378 // Collect the stored vector from each member.
4379 SmallVector<Value *, 4> StoredVecs;
4380 const DataLayout &DL = Instr->getDataLayout();
4381 for (unsigned I = 0, StoredIdx = 0; I < InterleaveFactor; I++) {
4382 Instruction *Member = Group->getMember(I);
4383 // Skip the gaps in the group.
4384 if (!Member) {
4385 StoredVecs.push_back(PoisonValue::get(SubVT));
4386 continue;
4387 }
4388
4389 Value *StoredVec = State.get(StoredValues[StoredIdx]);
4390 // If this member has different type, cast it to a unified type.
4391 if (StoredVec->getType() != SubVT)
4392 StoredVec = createBitOrPointerCast(State.Builder, StoredVec, SubVT, DL);
4393
4394 StoredVecs.push_back(StoredVec);
4395 ++StoredIdx;
4396 }
4397
4398 // Interleave all the smaller vectors into one wider vector.
4399 Value *IVec = interleaveVectors(State.Builder, StoredVecs, "interleaved.vec");
4400 CallInst *NewStore =
4401 State.Builder.CreateIntrinsic(Type::getVoidTy(Ctx), Intrinsic::vp_store,
4402 {IVec, ResAddr, GroupMask, InterleaveEVL});
4403 NewStore->addParamAttr(1,
4404 Attribute::getWithAlignment(Ctx, Group->getAlign()));
4405
4406 applyMetadata(*NewStore);
4407 // TODO: Also manage existing metadata using VPIRMetadata.
4408 Group->addMetadata(NewStore);
4409}
4410
4411#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4413 VPSlotTracker &SlotTracker) const {
4415 O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << " at ";
4416 IG->getInsertPos()->printAsOperand(O, false);
4417 O << ", ";
4419 O << ", ";
4421 if (VPValue *Mask = getMask()) {
4422 O << ", ";
4423 Mask->printAsOperand(O, SlotTracker);
4424 }
4425
4426 unsigned OpIdx = 0;
4427 for (unsigned i = 0; i < IG->getFactor(); ++i) {
4428 if (!IG->getMember(i))
4429 continue;
4430 if (getNumStoreOperands() > 0) {
4431 O << "\n" << Indent << " vp.store ";
4433 O << " to index " << i;
4434 } else {
4435 O << "\n" << Indent << " ";
4437 O << " = vp.load from index " << i;
4438 }
4439 ++OpIdx;
4440 }
4441}
4442#endif
4443
4445 VPCostContext &Ctx) const {
4446 Instruction *InsertPos = getInsertPos();
4447 // Find the VPValue index of the interleave group. We need to skip gaps.
4448 unsigned InsertPosIdx = 0;
4449 for (unsigned Idx = 0; IG->getFactor(); ++Idx)
4450 if (auto *Member = IG->getMember(Idx)) {
4451 if (Member == InsertPos)
4452 break;
4453 InsertPosIdx++;
4454 }
4455 Type *ValTy = Ctx.Types.inferScalarType(
4456 getNumDefinedValues() > 0 ? getVPValue(InsertPosIdx)
4457 : getStoredValues()[InsertPosIdx]);
4458 auto *VectorTy = cast<VectorType>(toVectorTy(ValTy, VF));
4459 unsigned AS = cast<PointerType>(Ctx.Types.inferScalarType(getAddr()))
4460 ->getAddressSpace();
4461
4462 unsigned InterleaveFactor = IG->getFactor();
4463 auto *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
4464
4465 // Holds the indices of existing members in the interleaved group.
4467 for (unsigned IF = 0; IF < InterleaveFactor; IF++)
4468 if (IG->getMember(IF))
4469 Indices.push_back(IF);
4470
4471 // Calculate the cost of the whole interleaved group.
4472 InstructionCost Cost = Ctx.TTI.getInterleavedMemoryOpCost(
4473 InsertPos->getOpcode(), WideVecTy, IG->getFactor(), Indices,
4474 IG->getAlign(), AS, Ctx.CostKind, getMask(), NeedsMaskForGaps);
4475
4476 if (!IG->isReverse())
4477 return Cost;
4478
4479 return Cost + IG->getNumMembers() *
4480 Ctx.TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
4481 VectorTy, VectorTy, {}, Ctx.CostKind,
4482 0);
4483}
4484
4485#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4487 VPSlotTracker &SlotTracker) const {
4488 O << Indent << "EMIT ";
4490 O << " = CANONICAL-INDUCTION ";
4492}
4493#endif
4494
4496 return vputils::onlyScalarValuesUsed(this) &&
4497 (!IsScalable || vputils::onlyFirstLaneUsed(this));
4498}
4499
4500#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4502 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
4503 assert((getNumOperands() == 3 || getNumOperands() == 5) &&
4504 "unexpected number of operands");
4505 O << Indent << "EMIT ";
4507 O << " = WIDEN-POINTER-INDUCTION ";
4509 O << ", ";
4511 O << ", ";
4513 if (getNumOperands() == 5) {
4514 O << ", ";
4516 O << ", ";
4518 }
4519}
4520
4522 VPSlotTracker &SlotTracker) const {
4523 O << Indent << "EMIT ";
4525 O << " = EXPAND SCEV " << *Expr;
4526}
4527#endif
4528
4530 Value *CanonicalIV = State.get(getOperand(0), /*IsScalar*/ true);
4531 Type *STy = CanonicalIV->getType();
4532 IRBuilder<> Builder(State.CFG.PrevBB->getTerminator());
4533 ElementCount VF = State.VF;
4534 Value *VStart = VF.isScalar()
4535 ? CanonicalIV
4536 : Builder.CreateVectorSplat(VF, CanonicalIV, "broadcast");
4537 Value *VStep = createStepForVF(Builder, STy, VF, getUnrollPart(*this));
4538 if (VF.isVector()) {
4539 VStep = Builder.CreateVectorSplat(VF, VStep);
4540 VStep =
4541 Builder.CreateAdd(VStep, Builder.CreateStepVector(VStep->getType()));
4542 }
4543 Value *CanonicalVectorIV = Builder.CreateAdd(VStart, VStep, "vec.iv");
4544 State.set(this, CanonicalVectorIV);
4545}
4546
4547#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4549 VPSlotTracker &SlotTracker) const {
4550 O << Indent << "EMIT ";
4552 O << " = WIDEN-CANONICAL-INDUCTION ";
4554}
4555#endif
4556
4558 auto &Builder = State.Builder;
4559 // Create a vector from the initial value.
4560 auto *VectorInit = getStartValue()->getLiveInIRValue();
4561
4562 Type *VecTy = State.VF.isScalar()
4563 ? VectorInit->getType()
4564 : VectorType::get(VectorInit->getType(), State.VF);
4565
4566 BasicBlock *VectorPH =
4567 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
4568 if (State.VF.isVector()) {
4569 auto *IdxTy = Builder.getInt32Ty();
4570 auto *One = ConstantInt::get(IdxTy, 1);
4571 IRBuilder<>::InsertPointGuard Guard(Builder);
4572 Builder.SetInsertPoint(VectorPH->getTerminator());
4573 auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, State.VF);
4574 auto *LastIdx = Builder.CreateSub(RuntimeVF, One);
4575 VectorInit = Builder.CreateInsertElement(
4576 PoisonValue::get(VecTy), VectorInit, LastIdx, "vector.recur.init");
4577 }
4578
4579 // Create a phi node for the new recurrence.
4580 PHINode *Phi = PHINode::Create(VecTy, 2, "vector.recur");
4581 Phi->insertBefore(State.CFG.PrevBB->getFirstInsertionPt());
4582 Phi->addIncoming(VectorInit, VectorPH);
4583 State.set(this, Phi);
4584}
4585
4588 VPCostContext &Ctx) const {
4589 if (VF.isScalar())
4590 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
4591
4592 return 0;
4593}
4594
4595#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4597 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
4598 O << Indent << "FIRST-ORDER-RECURRENCE-PHI ";
4600 O << " = phi ";
4602}
4603#endif
4604
4606 // Reductions do not have to start at zero. They can start with
4607 // any loop invariant values.
4608 VPValue *StartVPV = getStartValue();
4609
4610 // In order to support recurrences we need to be able to vectorize Phi nodes.
4611 // Phi nodes have cycles, so we need to vectorize them in two stages. This is
4612 // stage #1: We create a new vector PHI node with no incoming edges. We'll use
4613 // this value when we vectorize all of the instructions that use the PHI.
4614 BasicBlock *VectorPH =
4615 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
4616 bool ScalarPHI = State.VF.isScalar() || isInLoop();
4617 Value *StartV = State.get(StartVPV, ScalarPHI);
4618 Type *VecTy = StartV->getType();
4619
4620 BasicBlock *HeaderBB = State.CFG.PrevBB;
4621 assert(State.CurrentParentLoop->getHeader() == HeaderBB &&
4622 "recipe must be in the vector loop header");
4623 auto *Phi = PHINode::Create(VecTy, 2, "vec.phi");
4624 Phi->insertBefore(HeaderBB->getFirstInsertionPt());
4625 State.set(this, Phi, isInLoop());
4626
4627 Phi->addIncoming(StartV, VectorPH);
4628}
4629
4630#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4632 VPSlotTracker &SlotTracker) const {
4633 O << Indent << "WIDEN-REDUCTION-PHI ";
4634
4636 O << " = phi";
4637 printFlags(O);
4639 if (getVFScaleFactor() > 1)
4640 O << " (VF scaled by 1/" << getVFScaleFactor() << ")";
4641}
4642#endif
4643
4645 Value *Op0 = State.get(getOperand(0));
4646 Type *VecTy = Op0->getType();
4647 Instruction *VecPhi = State.Builder.CreatePHI(VecTy, 2, Name);
4648 State.set(this, VecPhi);
4649}
4650
4652 VPCostContext &Ctx) const {
4653 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
4654}
4655
4656#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4658 VPSlotTracker &SlotTracker) const {
4659 O << Indent << "WIDEN-PHI ";
4660
4662 O << " = phi ";
4664}
4665#endif
4666
4668 BasicBlock *VectorPH =
4669 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
4670 Value *StartMask = State.get(getOperand(0));
4671 PHINode *Phi =
4672 State.Builder.CreatePHI(StartMask->getType(), 2, "active.lane.mask");
4673 Phi->addIncoming(StartMask, VectorPH);
4674 State.set(this, Phi);
4675}
4676
4677#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4679 VPSlotTracker &SlotTracker) const {
4680 O << Indent << "ACTIVE-LANE-MASK-PHI ";
4681
4683 O << " = phi ";
4685}
4686#endif
4687
4688#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4690 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
4691 O << Indent << "CURRENT-ITERATION-PHI ";
4692
4694 O << " = phi ";
4696}
4697#endif
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static MCDisassembler::DecodeStatus addOperand(MCInst &Inst, const MCOperand &Opnd)
AMDGPU Lower Kernel Arguments
AMDGPU Register Bank Select
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static const Function * getParent(const Value *V)
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Value * getPointer(Value *Ptr)
iv users
Definition IVUsers.cpp:48
static std::pair< Value *, APInt > getMask(Value *WideMask, unsigned Factor, ElementCount LeafValueEC)
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
This file provides a LoopVectorizationPlanner class.
static const SCEV * getAddressAccessSCEV(Value *Ptr, PredicatedScalarEvolution &PSE, const Loop *TheLoop)
Gets the address access SCEV for Ptr, if it should be used for cost modeling according to isAddressSC...
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static bool isOrdered(const Instruction *I)
MachineInstr unsigned OpIdx
uint64_t IntrinsicInst * II
const SmallVectorImpl< MachineOperand > & Cond
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:114
static TableGen::Emitter::OptClass< SkeletonEmitter > X("gen-skeleton-class", "Generate example skeleton class")
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
This file contains the declarations of different VPlan-related auxiliary helpers.
static Instruction * createReverseEVL(IRBuilderBase &Builder, Value *Operand, Value *EVL, const Twine &Name)
Use all-true mask for reverse rather than actual mask, as it avoids a dependence w/o affecting the re...
static Value * interleaveVectors(IRBuilderBase &Builder, ArrayRef< Value * > Vals, const Twine &Name)
Return a vector containing interleaved elements from multiple smaller input vectors.
static InstructionCost getCostForIntrinsics(Intrinsic::ID ID, ArrayRef< const VPValue * > Operands, const VPRecipeWithIRFlags &R, ElementCount VF, VPCostContext &Ctx)
Compute the cost for the intrinsic ID with Operands, produced by R.
static Value * createBitOrPointerCast(IRBuilderBase &Builder, Value *V, VectorType *DstVTy, const DataLayout &DL)
SmallVector< Value *, 2 > VectorParts
static bool isUsedByLoadStoreAddress(const VPUser *V)
Returns true if V is used as part of the address of another load or store.
static void scalarizeInstruction(const Instruction *Instr, VPReplicateRecipe *RepRecipe, const VPLane &Lane, VPTransformState &State)
A helper function to scalarize a single Instruction in the innermost loop.
static std::optional< unsigned > getOpcode(ArrayRef< VPValue * > Values)
Returns the opcode of Values or ~0 if they do not all agree.
Definition VPlanSLP.cpp:247
This file contains the declarations of the Vectorization Plan base classes:
static const uint32_t IV[8]
Definition blake3_impl.h:83
void printAsOperand(OutputBuffer &OB, Prec P=Prec::Default, bool StrictlyWorse=false) const
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:235
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
size - Get the array size.
Definition ArrayRef.h:142
bool empty() const
empty - Check if the array is empty.
Definition ArrayRef.h:137
static LLVM_ABI Attribute getWithAlignment(LLVMContext &Context, Align Alignment)
Return a uniquified Attribute object that has the specific alignment set.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition BasicBlock.h:233
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
Adds the attribute to the indicated argument.
This class represents a function call, abstracting a target machine's calling convention.
static LLVM_ABI bool isBitOrNoopPointerCastable(Type *SrcTy, Type *DestTy, const DataLayout &DL)
Check whether a bitcast, inttoptr, or ptrtoint cast between these types is valid and a no-op.
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
Definition InstrTypes.h:982
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:676
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:699
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:701
static LLVM_ABI StringRef getPredicateName(Predicate P)
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
A debug info location.
Definition DebugLoc.h:123
static DebugLoc getUnknown()
Definition DebugLoc.h:161
constexpr bool isVector() const
One or more elements.
Definition TypeSize.h:324
static constexpr ElementCount getScalable(ScalarTy MinVal)
Definition TypeSize.h:312
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:309
constexpr bool isScalar() const
Exactly one element.
Definition TypeSize.h:320
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
LLVM_ABI void print(raw_ostream &O) const
Print fast-math flags to O.
Definition Operator.cpp:283
void setAllowContract(bool B=true)
Definition FMF.h:93
bool noSignedZeros() const
Definition FMF.h:70
bool noInfs() const
Definition FMF.h:69
void setAllowReciprocal(bool B=true)
Definition FMF.h:90
bool allowReciprocal() const
Definition FMF.h:71
void setNoSignedZeros(bool B=true)
Definition FMF.h:87
bool allowReassoc() const
Flag queries.
Definition FMF.h:67
bool approxFunc() const
Definition FMF.h:73
void setNoNaNs(bool B=true)
Definition FMF.h:81
void setAllowReassoc(bool B=true)
Flag setters.
Definition FMF.h:78
bool noNaNs() const
Definition FMF.h:68
void setApproxFunc(bool B=true)
Definition FMF.h:96
void setNoInfs(bool B=true)
Definition FMF.h:84
bool allowContract() const
Definition FMF.h:72
Class to represent function types.
Type * getParamType(unsigned i) const
Parameter type accessors.
bool willReturn() const
Determine if the function will return.
Definition Function.h:669
bool doesNotThrow() const
Determine if the function cannot unwind.
Definition Function.h:602
Type * getReturnType() const
Returns the type of the ret val.
Definition Function.h:216
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:2561
IntegerType * getInt1Ty()
Fetch the type representing a single bit.
Definition IRBuilder.h:546
Value * CreateInsertValue(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &Name="")
Definition IRBuilder.h:2615
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2549
LLVM_ABI Value * CreateVectorSpliceRight(Value *V1, Value *V2, Value *Offset, const Twine &Name="")
Create a vector.splice.right intrinsic call, or a shufflevector that produces the same result if the ...
LLVM_ABI Value * CreateSelectFMF(Value *C, Value *True, Value *False, FMFSource FMFSource, const Twine &Name="", Instruction *MDFrom=nullptr)
LLVM_ABI Value * CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name="")
Return a vector value that contains.
Value * CreateExtractValue(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &Name="")
Definition IRBuilder.h:2608
LLVM_ABI Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
Value * CreateFreeze(Value *V, const Twine &Name="")
Definition IRBuilder.h:2627
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
Definition IRBuilder.h:561
Value * CreatePtrAdd(Value *Ptr, Value *Offset, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Definition IRBuilder.h:2025
void setFastMathFlags(FastMathFlags NewFMF)
Set the fast-math flags to be used with generated fp-math operators.
Definition IRBuilder.h:345
IntegerType * getInt64Ty()
Fetch the type representing a 64-bit integer.
Definition IRBuilder.h:566
LLVM_ABI Value * CreateVectorReverse(Value *V, const Twine &Name="")
Return a vector value that contains the vector V reversed.
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2312
ConstantInt * getInt64(uint64_t C)
Get a constant 64-bit value.
Definition IRBuilder.h:527
LLVM_ABI CallInst * CreateOrReduce(Value *Src)
Create a vector int OR reduction intrinsic of the source vector.
Value * CreateLogicalAnd(Value *Cond1, Value *Cond2, const Twine &Name="", Instruction *MDFrom=nullptr)
Definition IRBuilder.h:1728
LLVM_ABI CallInst * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > Types, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="")
Create a call to intrinsic ID with Args, mangled using Types.
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition IRBuilder.h:522
Value * CreateCmp(CmpInst::Predicate Pred, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2442
Value * CreateNot(Value *V, const Twine &Name="")
Definition IRBuilder.h:1812
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2308
Value * CreateCountTrailingZeroElems(Type *ResTy, Value *Mask, bool ZeroIsPoison=true, const Twine &Name="")
Create a call to llvm.experimental_cttz_elts.
Definition IRBuilder.h:1137
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1423
BranchInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a conditional 'br Cond, TrueDest, FalseDest' instruction.
Definition IRBuilder.h:1200
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNeg=false)
Definition IRBuilder.h:2054
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1406
ConstantInt * getFalse()
Get the constant value for i1 false.
Definition IRBuilder.h:507
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:1711
Value * CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2320
Value * CreateLogicalOr(Value *Cond1, Value *Cond2, const Twine &Name="", Instruction *MDFrom=nullptr)
Definition IRBuilder.h:1736
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2418
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
Definition IRBuilder.h:1576
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1440
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2788
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:45
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:297
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:273
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:61
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:296
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:267
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:280
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:352
bool isStructTy() const
True if this is an instance of StructType.
Definition Type.h:261
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:128
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:230
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:293
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:184
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:240
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:300
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:139
value_op_iterator value_op_end()
Definition User.h:288
void setOperand(unsigned i, Value *Val)
Definition User.h:212
Value * getOperand(unsigned i) const
Definition User.h:207
value_op_iterator value_op_begin()
Definition User.h:285
void execute(VPTransformState &State) override
Generate the active lane mask phi of the vector loop.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph.
Definition VPlan.h:4237
RecipeListTy & getRecipeList()
Returns a reference to the list of recipes.
Definition VPlan.h:4290
iterator end()
Definition VPlan.h:4274
void insert(VPRecipeBase *Recipe, iterator InsertPt)
Definition VPlan.h:4303
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:2793
unsigned getNumIncomingValues() const
Return the number of incoming values, taking into account when normalized the first incoming value wi...
Definition VPlan.h:2788
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:2784
VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
Definition VPlan.h:82
const VPBlocksTy & getPredecessors() const
Definition VPlan.h:205
VPlan * getPlan()
Definition VPlan.cpp:177
void printAsOperand(raw_ostream &OS, bool PrintType=false) const
Definition VPlan.h:350
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPBranchOnMaskRecipe.
void execute(VPTransformState &State) override
Generate the extraction of the appropriate bit from the block mask and the conditional branch.
VPlan-based builder utility analogous to IRBuilder.
LLVM_ABI_FOR_TEST void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
LLVM_ABI_FOR_TEST void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
unsigned getNumDefinedValues() const
Returns the number of values defined by the VPDef.
Definition VPlanValue.h:427
VPValue * getVPSingleValue()
Returns the only VPValue defined by the VPDef.
Definition VPlanValue.h:400
VPValue * getVPValue(unsigned I)
Returns the VPValue with index I defined by the VPDef.
Definition VPlanValue.h:412
ArrayRef< VPRecipeValue * > definedValues()
Returns an ArrayRef of the values defined by the VPDef.
Definition VPlanValue.h:422
void execute(VPTransformState &State) override
Generate the transformed value of the induction at offset StartValue (1.
VPIRValue * getStartValue() const
Definition VPlan.h:4016
VPValue * getStepValue() const
Definition VPlan.h:4017
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:2305
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:2045
BasicBlock * getIRBasicBlock() const
Definition VPlan.h:4414
Class to record and manage LLVM IR flags.
Definition VPlan.h:672
FastMathFlagsTy FMFs
Definition VPlan.h:760
ReductionFlagsTy ReductionFlags
Definition VPlan.h:762
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:754
void printFlags(raw_ostream &O) const
bool hasFastMathFlags() const
Returns true if the recipe has fast-math flags.
Definition VPlan.h:977
LLVM_ABI_FOR_TEST FastMathFlags getFastMathFlags() const
bool isReductionOrdered() const
Definition VPlan.h:1027
TruncFlagsTy TruncFlags
Definition VPlan.h:755
CmpInst::Predicate getPredicate() const
Definition VPlan.h:949
ExactFlagsTy ExactFlags
Definition VPlan.h:757
bool hasNoSignedWrap() const
Definition VPlan.h:1004
void intersectFlags(const VPIRFlags &Other)
Only keep flags also present in Other.
uint8_t GEPFlagsStorage
Definition VPlan.h:758
GEPNoWrapFlags getGEPNoWrapFlags() const
Definition VPlan.h:967
bool hasPredicate() const
Returns true if the recipe has a comparison predicate.
Definition VPlan.h:972
DisjointFlagsTy DisjointFlags
Definition VPlan.h:756
bool hasNoUnsignedWrap() const
Definition VPlan.h:993
FCmpFlagsTy FCmpFlags
Definition VPlan.h:761
NonNegFlagsTy NonNegFlags
Definition VPlan.h:759
bool isReductionInLoop() const
Definition VPlan.h:1033
void applyFlags(Instruction &I) const
Apply the IR flags to I.
Definition VPlan.h:906
uint8_t CmpPredStorage
Definition VPlan.h:753
RecurKind getRecurKind() const
Definition VPlan.h:1021
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:1662
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:1193
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:1304
@ ExtractLane
Extracts a single lane (first operand) from a set of vector operands.
Definition VPlan.h:1295
@ ExitingIVValue
Compute the exiting value of a wide induction after vectorization, that is the value of the last lane...
Definition VPlan.h:1311
@ ComputeAnyOfResult
Compute the final result of a AnyOf reduction with select(cmp(),x,y), where one of (x,...
Definition VPlan.h:1240
@ WideIVStep
Scale the first operand (vector step) by the second operand (scalar-step).
Definition VPlan.h:1285
@ ResumeForEpilogue
Explicit user for the resume phi of the canonical induction in the main VPlan, used by the epilogue v...
Definition VPlan.h:1298
@ Unpack
Extracts all lanes from its (non-scalable) vector operand.
Definition VPlan.h:1237
@ ReductionStartVector
Start vector for reductions with 3 operands: the original start value, the identity value for the red...
Definition VPlan.h:1289
@ BuildVector
Creates a fixed-width vector containing all operands.
Definition VPlan.h:1232
@ BuildStructVector
Given operands of (the same) struct type, creates a struct of fixed- width vectors each containing a ...
Definition VPlan.h:1229
@ VScale
Returns the value for vscale.
Definition VPlan.h:1307
@ CanonicalIVIncrementForPart
Definition VPlan.h:1213
bool hasResult() const
Definition VPlan.h:1389
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:1469
unsigned getOpcode() const
Definition VPlan.h:1373
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:1414
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:2905
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this recipe.
Instruction * getInsertPos() const
Definition VPlan.h:2909
const InterleaveGroup< Instruction > * getInterleaveGroup() const
Definition VPlan.h:2907
VPValue * getMask() const
Return the mask used by this recipe.
Definition VPlan.h:2899
ArrayRef< VPValue * > getStoredValues() const
Return the VPValues stored by this interleave group.
Definition VPlan.h:2928
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition VPlan.h:2893
VPValue * getEVL() const
The VPValue of the explicit vector length.
Definition VPlan.h:3002
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:3015
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:2965
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:1576
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:4381
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:1601
VPValue * getIncomingValue(unsigned Idx) const
Returns the incoming VPValue with index Idx.
Definition VPlan.h:1561
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:388
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:4542
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:463
DebugLoc getDebugLoc() const
Returns the debug location of the recipe.
Definition VPlan.h:537
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:509
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:453
friend class VPValue
Definition VPlanValue.h:233
void execute(VPTransformState &State) override
Generate the reduction in the loop.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPValue * getEVL() const
The VPValue of the explicit vector length.
Definition VPlan.h:3163
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:2708
bool isInLoop() const
Returns true if the phi is part of an in-loop reduction.
Definition VPlan.h:2732
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:3105
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:3116
VPValue * getCondOp() const
The VPValue of the condition for the block.
Definition VPlan.h:3118
RecurKind getRecurrenceKind() const
Return the recurrence kind for the in-loop reduction.
Definition VPlan.h:3101
bool isPartialReduction() const
Returns true if the reduction outputs a vector with a scaled down VF.
Definition VPlan.h:3107
VPValue * getChainOp() const
The VPValue of the scalar Chain being accumulated.
Definition VPlan.h:3114
bool isInLoop() const
Returns true if the reduction is in-loop.
Definition VPlan.h:3109
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:4425
bool isReplicator() const
An indicator whether this region is to generate multiple replicated instances of output IR correspond...
Definition VPlan.h:4493
VPReplicateRecipe replicates a given instruction producing multiple scalar copies of the original sca...
Definition VPlan.h:3185
void execute(VPTransformState &State) override
Generate replicas of the desired Ingredient.
bool isSingleScalar() const
Definition VPlan.h:3226
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:3255
bool shouldPack() const
Returns true if the recipe is used by a widened recipe via an intervening VPPredInstPHIRecipe.
VPValue * getStepValue() const
Definition VPlan.h:4085
VPValue * getStartIndex() const
Return the StartIndex, or null if known to be zero, valid only after unrolling.
Definition VPlan.h:4093
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:589
Instruction * getUnderlyingInstr()
Returns the underlying instruction.
Definition VPlan.h:657
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:591
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:1126
VPValue * getUnrollPartOperand(const VPUser &U) const
Return the VPValue operand containing the unroll part or null if there is no such operand.
unsigned getUnrollPart(const VPUser &U) const
Return the unroll part.
This class augments VPValue with operands which provide the inverse def-use edges from VPValue's user...
Definition VPlanValue.h:258
void printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const
Print the operands to O.
Definition VPlan.cpp:1451
operand_range operands()
Definition VPlanValue.h:326
unsigned getNumOperands() const
Definition VPlanValue.h:296
operand_iterator op_begin()
Definition VPlanValue.h:322
VPValue * getOperand(unsigned N) const
Definition VPlanValue.h:297
virtual bool usesFirstLaneOnly(const VPValue *Op) const
Returns true if the VPUser only uses the first lane of operand Op.
Definition VPlanValue.h:341
This is the base class of the VPlan Def/Use graph, used for modeling the data flow into,...
Definition VPlanValue.h:46
Value * getLiveInIRValue() const
Return the underlying IR value for a VPIRValue.
Definition VPlan.cpp:137
bool isDefinedOutsideLoopRegions() const
Returns true if the VPValue is defined outside any loop.
Definition VPlan.cpp: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:1447
Value * getUnderlyingValue() const
Return the underlying Value attached to this VPValue.
Definition VPlanValue.h:71
void replaceAllUsesWith(VPValue *New)
Definition VPlan.cpp:1408
VPValue * getVFValue() const
Definition VPlan.h:2143
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:2140
int64_t getStride() const
Definition VPlan.h:2141
VPValue * getPointer() const
Definition VPlan.h:2142
void materializeOffset(unsigned Part=0)
Adds the offset operand to the recipe.
Type * getSourceElementType() const
Definition VPlan.h:2212
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:2000
Function * getCalledScalarFunction() const
Definition VPlan.h:1996
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:1849
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:2097
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:2368
VPValue * getStepValue()
Returns the step value of the induction.
Definition VPlan.h:2371
VPIRValue * getStartValue() const
Returns the start value of the induction.
Definition VPlan.h:2469
TruncInst * getTruncInst()
Returns the first defined value as TruncInst, if it is one or nullptr otherwise.
Definition VPlan.h:2484
Type * getScalarType() const
Returns the scalar type of the induction.
Definition VPlan.h:2493
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:1931
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:1934
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:3510
bool Reverse
Whether the consecutive accessed addresses are in reverse order.
Definition VPlan.h:3507
bool isConsecutive() const
Return whether the loaded-from / stored-to addresses are consecutive.
Definition VPlan.h:3550
Instruction & Ingredient
Definition VPlan.h:3498
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:3504
VPValue * getMask() const
Return the mask used by this recipe.
Definition VPlan.h:3564
Align Alignment
Alignment information for this memory access.
Definition VPlan.h:3501
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition VPlan.h:3557
bool isReverse() const
Return whether the consecutive loaded/stored addresses are in reverse order.
Definition VPlan.h:3554
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:4555
LLVM_ABI_FOR_TEST VPRegionBlock * getVectorLoopRegion()
Returns the VPRegionBlock of the vector loop.
Definition VPlan.cpp:1038
VPIRBasicBlock * getScalarHeader() const
Return the VPIRBasicBlock wrapping the header of the scalar loop.
Definition VPlan.h:4691
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:4841
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:1720
PHINode & getIRPhi()
Definition VPlan.h:1733
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:1080
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:1081
A symbolic live-in VPValue, used for values like vector trip count, VF, and VFxUF.
Definition VPlanValue.h:223
SmallDenseMap< const VPBasicBlock *, BasicBlock * > VPBB2IRBB
A mapping of each VPBasicBlock to the corresponding BasicBlock.
VPTransformState holds information passed down when "executing" a VPlan, needed for generating the ou...
VPTypeAnalysis TypeAnalysis
VPlan-based type analysis.
struct llvm::VPTransformState::CFGState CFG
Value * get(const VPValue *Def, bool IsScalar=false)
Get the generated vector Value for a given VPValue Def if IsScalar is false, otherwise return the gen...
Definition VPlan.cpp:279
IRBuilderBase & Builder
Hold a reference to the IRBuilder used to generate output IR code.
ElementCount VF
The chosen Vectorization Factor of the loop being vectorized.
LLVM_ABI_FOR_TEST void execute(VPTransformState &State) override
Generate the wide load or gather.
LLVM_ABI_FOR_TEST void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
LLVM_ABI_FOR_TEST InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenLoadEVLRecipe.
VPValue * getEVL() const
Return the EVL operand.
Definition VPlan.h:3642
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:3726
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:3729
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:3689