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