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:
479 return 3;
480 case Instruction::Call:
481 case Instruction::GetElementPtr:
482 case Instruction::PHI:
483 case Instruction::Switch:
490 // Cannot determine the number of operands from the opcode.
491 return -1u;
492 }
493 llvm_unreachable("all cases should be handled above");
494}
495#endif
496
500
501bool VPInstruction::canGenerateScalarForFirstLane() const {
503 return true;
505 return true;
506 switch (Opcode) {
507 case Instruction::Freeze:
508 case Instruction::ICmp:
509 case Instruction::PHI:
510 case Instruction::Select:
520 return true;
521 default:
522 return false;
523 }
524}
525
526Value *VPInstruction::generate(VPTransformState &State) {
527 IRBuilderBase &Builder = State.Builder;
528
530 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
531 Value *A = State.get(getOperand(0), OnlyFirstLaneUsed);
532 Value *B = State.get(getOperand(1), OnlyFirstLaneUsed);
533 auto *Res =
534 Builder.CreateBinOp((Instruction::BinaryOps)getOpcode(), A, B, Name);
535 if (auto *I = dyn_cast<Instruction>(Res))
536 applyFlags(*I);
537 return Res;
538 }
539
540 switch (getOpcode()) {
541 case VPInstruction::Not: {
542 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
543 Value *A = State.get(getOperand(0), OnlyFirstLaneUsed);
544 return Builder.CreateNot(A, Name);
545 }
546 case Instruction::ExtractElement: {
547 assert(State.VF.isVector() && "Only extract elements from vectors");
548 if (auto *Idx = dyn_cast<VPConstantInt>(getOperand(1)))
549 return State.get(getOperand(0), VPLane(Idx->getZExtValue()));
550 Value *Vec = State.get(getOperand(0));
551 Value *Idx = State.get(getOperand(1), /*IsScalar=*/true);
552 return Builder.CreateExtractElement(Vec, Idx, Name);
553 }
554 case Instruction::Freeze: {
556 return Builder.CreateFreeze(Op, Name);
557 }
558 case Instruction::FCmp:
559 case Instruction::ICmp: {
560 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
561 Value *A = State.get(getOperand(0), OnlyFirstLaneUsed);
562 Value *B = State.get(getOperand(1), OnlyFirstLaneUsed);
563 return Builder.CreateCmp(getPredicate(), A, B, Name);
564 }
565 case Instruction::PHI: {
566 llvm_unreachable("should be handled by VPPhi::execute");
567 }
568 case Instruction::Select: {
569 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
570 Value *Cond =
571 State.get(getOperand(0),
572 OnlyFirstLaneUsed || vputils::isSingleScalar(getOperand(0)));
573 Value *Op1 = State.get(getOperand(1), OnlyFirstLaneUsed);
574 Value *Op2 = State.get(getOperand(2), OnlyFirstLaneUsed);
575 return Builder.CreateSelect(Cond, Op1, Op2, Name);
576 }
578 // Get first lane of vector induction variable.
579 Value *VIVElem0 = State.get(getOperand(0), VPLane(0));
580 // Get the original loop tripcount.
581 Value *ScalarTC = State.get(getOperand(1), VPLane(0));
582
583 // If this part of the active lane mask is scalar, generate the CMP directly
584 // to avoid unnecessary extracts.
585 if (State.VF.isScalar())
586 return Builder.CreateCmp(CmpInst::Predicate::ICMP_ULT, VIVElem0, ScalarTC,
587 Name);
588
589 ElementCount EC = State.VF.multiplyCoefficientBy(
590 cast<VPConstantInt>(getOperand(2))->getZExtValue());
591 auto *PredTy = VectorType::get(Builder.getInt1Ty(), EC);
592 return Builder.CreateIntrinsic(Intrinsic::get_active_lane_mask,
593 {PredTy, ScalarTC->getType()},
594 {VIVElem0, ScalarTC}, nullptr, Name);
595 }
597 // Generate code to combine the previous and current values in vector v3.
598 //
599 // vector.ph:
600 // v_init = vector(..., ..., ..., a[-1])
601 // br vector.body
602 //
603 // vector.body
604 // i = phi [0, vector.ph], [i+4, vector.body]
605 // v1 = phi [v_init, vector.ph], [v2, vector.body]
606 // v2 = a[i, i+1, i+2, i+3];
607 // v3 = vector(v1(3), v2(0, 1, 2))
608
609 auto *V1 = State.get(getOperand(0));
610 if (!V1->getType()->isVectorTy())
611 return V1;
612 Value *V2 = State.get(getOperand(1));
613 return Builder.CreateVectorSplice(V1, V2, -1, Name);
614 }
616 unsigned UF = getParent()->getPlan()->getUF();
617 Value *ScalarTC = State.get(getOperand(0), VPLane(0));
618 Value *Step = createStepForVF(Builder, ScalarTC->getType(), State.VF, UF);
619 Value *Sub = Builder.CreateSub(ScalarTC, Step);
620 Value *Cmp = Builder.CreateICmp(CmpInst::Predicate::ICMP_UGT, ScalarTC, Step);
622 return Builder.CreateSelect(Cmp, Sub, Zero);
623 }
625 // TODO: Restructure this code with an explicit remainder loop, vsetvli can
626 // be outside of the main loop.
627 Value *AVL = State.get(getOperand(0), /*IsScalar*/ true);
628 // Compute EVL
629 assert(AVL->getType()->isIntegerTy() &&
630 "Requested vector length should be an integer.");
631
632 assert(State.VF.isScalable() && "Expected scalable vector factor.");
633 Value *VFArg = Builder.getInt32(State.VF.getKnownMinValue());
634
635 Value *EVL = Builder.CreateIntrinsic(
636 Builder.getInt32Ty(), Intrinsic::experimental_get_vector_length,
637 {AVL, VFArg, Builder.getTrue()});
638 return EVL;
639 }
641 unsigned Part = getUnrollPart(*this);
642 auto *IV = State.get(getOperand(0), VPLane(0));
643 assert(Part != 0 && "Must have a positive part");
644 // The canonical IV is incremented by the vectorization factor (num of
645 // SIMD elements) times the unroll part.
646 Value *Step = createStepForVF(Builder, IV->getType(), State.VF, Part);
647 return Builder.CreateAdd(IV, Step, Name, hasNoUnsignedWrap(),
649 }
651 Value *Cond = State.get(getOperand(0), VPLane(0));
652 // Replace the temporary unreachable terminator with a new conditional
653 // branch, hooking it up to backward destination for latch blocks now, and
654 // to forward destination(s) later when they are created.
655 // Second successor may be backwards - iff it is already in VPBB2IRBB.
656 VPBasicBlock *SecondVPSucc =
657 cast<VPBasicBlock>(getParent()->getSuccessors()[1]);
658 BasicBlock *SecondIRSucc = State.CFG.VPBB2IRBB.lookup(SecondVPSucc);
659 BasicBlock *IRBB = State.CFG.VPBB2IRBB[getParent()];
660 auto *Br = Builder.CreateCondBr(Cond, IRBB, SecondIRSucc);
661 // First successor is always forward, reset it to nullptr.
662 Br->setSuccessor(0, nullptr);
664 applyMetadata(*Br);
665 return Br;
666 }
668 return Builder.CreateVectorSplat(
669 State.VF, State.get(getOperand(0), /*IsScalar*/ true), "broadcast");
670 }
672 // For struct types, we need to build a new 'wide' struct type, where each
673 // element is widened, i.e., we create a struct of vectors.
674 auto *StructTy =
676 Value *Res = PoisonValue::get(toVectorizedTy(StructTy, State.VF));
677 for (const auto &[LaneIndex, Op] : enumerate(operands())) {
678 for (unsigned FieldIndex = 0; FieldIndex != StructTy->getNumElements();
679 FieldIndex++) {
680 Value *ScalarValue =
681 Builder.CreateExtractValue(State.get(Op, true), FieldIndex);
682 Value *VectorValue = Builder.CreateExtractValue(Res, FieldIndex);
683 VectorValue =
684 Builder.CreateInsertElement(VectorValue, ScalarValue, LaneIndex);
685 Res = Builder.CreateInsertValue(Res, VectorValue, FieldIndex);
686 }
687 }
688 return Res;
689 }
691 auto *ScalarTy = State.TypeAnalysis.inferScalarType(getOperand(0));
692 auto NumOfElements = ElementCount::getFixed(getNumOperands());
693 Value *Res = PoisonValue::get(toVectorizedTy(ScalarTy, NumOfElements));
694 for (const auto &[Idx, Op] : enumerate(operands()))
695 Res = Builder.CreateInsertElement(Res, State.get(Op, true),
696 Builder.getInt32(Idx));
697 return Res;
698 }
700 if (State.VF.isScalar())
701 return State.get(getOperand(0), true);
702 IRBuilderBase::FastMathFlagGuard FMFG(Builder);
704 // If this start vector is scaled then it should produce a vector with fewer
705 // elements than the VF.
706 ElementCount VF = State.VF.divideCoefficientBy(
707 cast<VPConstantInt>(getOperand(2))->getZExtValue());
708 auto *Iden = Builder.CreateVectorSplat(VF, State.get(getOperand(1), true));
709 return Builder.CreateInsertElement(Iden, State.get(getOperand(0), true),
710 Builder.getInt32(0));
711 }
713 // FIXME: The cross-recipe dependency on VPReductionPHIRecipe is temporary
714 // and will be removed by breaking up the recipe further.
715 auto *PhiR = cast<VPReductionPHIRecipe>(getOperand(0));
716 auto *OrigPhi = cast<PHINode>(PhiR->getUnderlyingValue());
717 Value *ReducedPartRdx = State.get(getOperand(2));
718 for (unsigned Idx = 3; Idx < getNumOperands(); ++Idx)
719 ReducedPartRdx =
720 Builder.CreateBinOp(Instruction::Or, State.get(getOperand(Idx)),
721 ReducedPartRdx, "bin.rdx");
722 return createAnyOfReduction(Builder, ReducedPartRdx,
723 State.get(getOperand(1), VPLane(0)), OrigPhi);
724 }
726 // The recipe's operands are the start value, the sentinel value, followed
727 // by one operand for each part of the reduction.
728 unsigned UF = getNumOperands() - 2;
729 Value *ReducedResult = State.get(getOperand(2));
730 RecurKind MinMaxKind = getRecurKind();
731 assert((MinMaxKind == RecurKind::SMin || MinMaxKind == RecurKind::SMax ||
732 MinMaxKind == RecurKind::UMin || MinMaxKind == RecurKind::UMax) &&
733 "unexpected recurrence kind for ComputeFindIVResult");
734 for (unsigned Part = 1; Part < UF; ++Part)
735 ReducedResult = createMinMaxOp(Builder, MinMaxKind, ReducedResult,
736 State.get(getOperand(2 + Part)));
737
738 // Reduce the vector to a scalar.
739 bool IsMaxRdx =
740 MinMaxKind == RecurKind::SMax || MinMaxKind == RecurKind::UMax;
741 bool IsSigned =
742 MinMaxKind == RecurKind::SMin || MinMaxKind == RecurKind::SMax;
743 if (ReducedResult->getType()->isVectorTy())
744 ReducedResult = IsMaxRdx
745 ? Builder.CreateIntMaxReduce(ReducedResult, IsSigned)
746 : Builder.CreateIntMinReduce(ReducedResult, IsSigned);
747 // Correct the final reduction result back to the start value if the
748 // reduction result is the sentinel value.
749 Value *Start = State.get(getOperand(0), true);
751 Value *Cmp =
752 Builder.CreateICmpNE(ReducedResult, Sentinel, "rdx.select.cmp");
753 return Builder.CreateSelect(Cmp, ReducedResult, Start, "rdx.select");
754 }
756 RecurKind RK = getRecurKind();
757 bool IsOrdered = isReductionOrdered();
758 bool IsInLoop = isReductionInLoop();
760 "should be handled by ComputeFindIVResult");
761
762 // The recipe may have multiple operands to be reduced together.
763 unsigned NumOperandsToReduce = getNumOperands();
764 VectorParts RdxParts(NumOperandsToReduce);
765 for (unsigned Part = 0; Part < NumOperandsToReduce; ++Part)
766 RdxParts[Part] = State.get(getOperand(Part), IsInLoop);
767
768 IRBuilderBase::FastMathFlagGuard FMFG(Builder);
769 if (hasFastMathFlags())
771
772 // Reduce multiple operands into one.
773 Value *ReducedPartRdx = RdxParts[0];
774 if (IsOrdered) {
775 ReducedPartRdx = RdxParts[NumOperandsToReduce - 1];
776 } else {
777 // Floating-point operations should have some FMF to enable the reduction.
778 for (unsigned Part = 1; Part < NumOperandsToReduce; ++Part) {
779 Value *RdxPart = RdxParts[Part];
781 ReducedPartRdx = createMinMaxOp(Builder, RK, ReducedPartRdx, RdxPart);
782 else {
783 // For sub-recurrences, each part's reduction variable is already
784 // negative, we need to do: reduce.add(-acc_uf0 + -acc_uf1)
786 RK == RecurKind::Sub
787 ? Instruction::Add
789 ReducedPartRdx =
790 Builder.CreateBinOp(Opcode, RdxPart, ReducedPartRdx, "bin.rdx");
791 }
792 }
793 }
794
795 // Create the reduction after the loop. Note that inloop reductions create
796 // the target reduction in the loop using a Reduction recipe.
797 if (State.VF.isVector() && !IsInLoop) {
798 // TODO: Support in-order reductions based on the recurrence descriptor.
799 // All ops in the reduction inherit fast-math-flags from the recurrence
800 // descriptor.
801 ReducedPartRdx = createSimpleReduction(Builder, ReducedPartRdx, RK);
802 }
803
804 return ReducedPartRdx;
805 }
808 unsigned Offset =
810 Value *Res;
811 if (State.VF.isVector()) {
812 assert(Offset <= State.VF.getKnownMinValue() &&
813 "invalid offset to extract from");
814 // Extract lane VF - Offset from the operand.
815 Res = State.get(getOperand(0), VPLane::getLaneFromEnd(State.VF, Offset));
816 } else {
817 // TODO: Remove ExtractLastLane for scalar VFs.
818 assert(Offset <= 1 && "invalid offset to extract from");
819 Res = State.get(getOperand(0));
820 }
822 Res->setName(Name);
823 return Res;
824 }
826 Value *A = State.get(getOperand(0));
827 Value *B = State.get(getOperand(1));
828 return Builder.CreateLogicalAnd(A, B, Name);
829 }
832 "can only generate first lane for PtrAdd");
833 Value *Ptr = State.get(getOperand(0), VPLane(0));
834 Value *Addend = State.get(getOperand(1), VPLane(0));
835 return Builder.CreatePtrAdd(Ptr, Addend, Name, getGEPNoWrapFlags());
836 }
838 Value *Ptr =
840 Value *Addend = State.get(getOperand(1));
841 return Builder.CreatePtrAdd(Ptr, Addend, Name, getGEPNoWrapFlags());
842 }
844 Value *Res = Builder.CreateFreeze(State.get(getOperand(0)));
845 for (VPValue *Op : drop_begin(operands()))
846 Res = Builder.CreateOr(Res, Builder.CreateFreeze(State.get(Op)));
847 return State.VF.isScalar() ? Res : Builder.CreateOrReduce(Res);
848 }
850 assert(getNumOperands() != 2 && "ExtractLane from single source should be "
851 "simplified to ExtractElement.");
852 Value *LaneToExtract = State.get(getOperand(0), true);
853 Type *IdxTy = State.TypeAnalysis.inferScalarType(getOperand(0));
854 Value *Res = nullptr;
855 Value *RuntimeVF = getRuntimeVF(Builder, IdxTy, State.VF);
856
857 for (unsigned Idx = 1; Idx != getNumOperands(); ++Idx) {
858 Value *VectorStart =
859 Builder.CreateMul(RuntimeVF, ConstantInt::get(IdxTy, Idx - 1));
860 Value *VectorIdx = Idx == 1
861 ? LaneToExtract
862 : Builder.CreateSub(LaneToExtract, VectorStart);
863 Value *Ext = State.VF.isScalar()
864 ? State.get(getOperand(Idx))
865 : Builder.CreateExtractElement(
866 State.get(getOperand(Idx)), VectorIdx);
867 if (Res) {
868 Value *Cmp = Builder.CreateICmpUGE(LaneToExtract, VectorStart);
869 Res = Builder.CreateSelect(Cmp, Ext, Res);
870 } else {
871 Res = Ext;
872 }
873 }
874 return Res;
875 }
877 if (getNumOperands() == 1) {
878 Value *Mask = State.get(getOperand(0));
879 return Builder.CreateCountTrailingZeroElems(Builder.getInt64Ty(), Mask,
880 /*ZeroIsPoison=*/false, Name);
881 }
882 // If there are multiple operands, create a chain of selects to pick the
883 // first operand with an active lane and add the number of lanes of the
884 // preceding operands.
885 Value *RuntimeVF = getRuntimeVF(Builder, Builder.getInt64Ty(), State.VF);
886 unsigned LastOpIdx = getNumOperands() - 1;
887 Value *Res = nullptr;
888 for (int Idx = LastOpIdx; Idx >= 0; --Idx) {
889 Value *TrailingZeros =
890 State.VF.isScalar()
891 ? Builder.CreateZExt(
892 Builder.CreateICmpEQ(State.get(getOperand(Idx)),
893 Builder.getFalse()),
894 Builder.getInt64Ty())
896 Builder.getInt64Ty(), State.get(getOperand(Idx)),
897 /*ZeroIsPoison=*/false, Name);
898 Value *Current = Builder.CreateAdd(
899 Builder.CreateMul(RuntimeVF, Builder.getInt64(Idx)), TrailingZeros);
900 if (Res) {
901 Value *Cmp = Builder.CreateICmpNE(TrailingZeros, RuntimeVF);
902 Res = Builder.CreateSelect(Cmp, Current, Res);
903 } else {
904 Res = Current;
905 }
906 }
907
908 return Res;
909 }
911 return State.get(getOperand(0), true);
913 return Builder.CreateVectorReverse(State.get(getOperand(0)), "reverse");
915 Value *Data = State.get(getOperand(0));
916 Value *Mask = State.get(getOperand(1));
917 Value *Default = State.get(getOperand(2), /*IsScalar=*/true);
918 Type *VTy = Data->getType();
919 return Builder.CreateIntrinsic(
920 Intrinsic::experimental_vector_extract_last_active, {VTy},
921 {Data, Mask, Default});
922 }
923 default:
924 llvm_unreachable("Unsupported opcode for instruction");
925 }
926}
927
929 unsigned Opcode, ElementCount VF, VPCostContext &Ctx) const {
930 Type *ScalarTy = Ctx.Types.inferScalarType(this);
931 Type *ResultTy = VF.isVector() ? toVectorTy(ScalarTy, VF) : ScalarTy;
932 switch (Opcode) {
933 case Instruction::FNeg:
934 return Ctx.TTI.getArithmeticInstrCost(Opcode, ResultTy, Ctx.CostKind);
935 case Instruction::UDiv:
936 case Instruction::SDiv:
937 case Instruction::SRem:
938 case Instruction::URem:
939 case Instruction::Add:
940 case Instruction::FAdd:
941 case Instruction::Sub:
942 case Instruction::FSub:
943 case Instruction::Mul:
944 case Instruction::FMul:
945 case Instruction::FDiv:
946 case Instruction::FRem:
947 case Instruction::Shl:
948 case Instruction::LShr:
949 case Instruction::AShr:
950 case Instruction::And:
951 case Instruction::Or:
952 case Instruction::Xor: {
955
956 if (VF.isVector()) {
957 // Certain instructions can be cheaper to vectorize if they have a
958 // constant second vector operand. One example of this are shifts on x86.
959 VPValue *RHS = getOperand(1);
960 RHSInfo = Ctx.getOperandInfo(RHS);
961
962 if (RHSInfo.Kind == TargetTransformInfo::OK_AnyValue &&
965 }
966
969 if (CtxI)
970 Operands.append(CtxI->value_op_begin(), CtxI->value_op_end());
971 return Ctx.TTI.getArithmeticInstrCost(
972 Opcode, ResultTy, Ctx.CostKind,
973 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
974 RHSInfo, Operands, CtxI, &Ctx.TLI);
975 }
976 case Instruction::Freeze:
977 // This opcode is unknown. Assume that it is the same as 'mul'.
978 return Ctx.TTI.getArithmeticInstrCost(Instruction::Mul, ResultTy,
979 Ctx.CostKind);
980 case Instruction::ExtractValue:
981 return Ctx.TTI.getInsertExtractValueCost(Instruction::ExtractValue,
982 Ctx.CostKind);
983 case Instruction::ICmp:
984 case Instruction::FCmp: {
985 Type *ScalarOpTy = Ctx.Types.inferScalarType(getOperand(0));
986 Type *OpTy = VF.isVector() ? toVectorTy(ScalarOpTy, VF) : ScalarOpTy;
988 return Ctx.TTI.getCmpSelInstrCost(
989 Opcode, OpTy, CmpInst::makeCmpResultType(OpTy), getPredicate(),
990 Ctx.CostKind, {TTI::OK_AnyValue, TTI::OP_None},
991 {TTI::OK_AnyValue, TTI::OP_None}, CtxI);
992 }
993 case Instruction::BitCast: {
994 Type *ScalarTy = Ctx.Types.inferScalarType(this);
995 if (ScalarTy->isPointerTy())
996 return 0;
997 [[fallthrough]];
998 }
999 case Instruction::SExt:
1000 case Instruction::ZExt:
1001 case Instruction::FPToUI:
1002 case Instruction::FPToSI:
1003 case Instruction::FPExt:
1004 case Instruction::PtrToInt:
1005 case Instruction::PtrToAddr:
1006 case Instruction::IntToPtr:
1007 case Instruction::SIToFP:
1008 case Instruction::UIToFP:
1009 case Instruction::Trunc:
1010 case Instruction::FPTrunc:
1011 case Instruction::AddrSpaceCast: {
1012 // Computes the CastContextHint from a recipe that may access memory.
1013 auto ComputeCCH = [&](const VPRecipeBase *R) -> TTI::CastContextHint {
1014 if (isa<VPInterleaveBase>(R))
1016 if (const auto *ReplicateRecipe = dyn_cast<VPReplicateRecipe>(R)) {
1017 // Only compute CCH for memory operations, matching the legacy model
1018 // which only considers loads/stores for cast context hints.
1019 auto *UI = cast<Instruction>(ReplicateRecipe->getUnderlyingValue());
1020 if (!isa<LoadInst, StoreInst>(UI))
1022 return ReplicateRecipe->isPredicated() ? TTI::CastContextHint::Masked
1025 const auto *WidenMemoryRecipe = dyn_cast<VPWidenMemoryRecipe>(R);
1026 if (WidenMemoryRecipe == nullptr)
1028 if (VF.isScalar())
1030 if (!WidenMemoryRecipe->isConsecutive())
1032 if (WidenMemoryRecipe->isReverse())
1034 if (WidenMemoryRecipe->isMasked())
1037 };
1038
1039 VPValue *Operand = getOperand(0);
1041 // For Trunc/FPTrunc, get the context from the only user.
1042 if (Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) {
1043 auto GetOnlyUser = [](const VPSingleDefRecipe *R) -> VPRecipeBase * {
1044 if (R->getNumUsers() == 0 || R->hasMoreThanOneUniqueUser())
1045 return nullptr;
1046 return dyn_cast<VPRecipeBase>(*R->user_begin());
1047 };
1048 if (VPRecipeBase *Recipe = GetOnlyUser(this)) {
1049 if (match(Recipe, m_Reverse(m_VPValue())))
1050 Recipe = GetOnlyUser(cast<VPInstruction>(Recipe));
1051 if (Recipe)
1052 CCH = ComputeCCH(Recipe);
1053 }
1054 }
1055 // For Z/Sext, get the context from the operand.
1056 else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt ||
1057 Opcode == Instruction::FPExt) {
1058 if (auto *Recipe = Operand->getDefiningRecipe()) {
1059 VPValue *ReverseOp;
1060 if (match(Recipe, m_Reverse(m_VPValue(ReverseOp))))
1061 Recipe = ReverseOp->getDefiningRecipe();
1062 if (Recipe)
1063 CCH = ComputeCCH(Recipe);
1064 }
1065 }
1066
1067 auto *ScalarSrcTy = Ctx.Types.inferScalarType(Operand);
1068 Type *SrcTy = VF.isVector() ? toVectorTy(ScalarSrcTy, VF) : ScalarSrcTy;
1069 // Arm TTI will use the underlying instruction to determine the cost.
1070 return Ctx.TTI.getCastInstrCost(
1071 Opcode, ResultTy, SrcTy, CCH, Ctx.CostKind,
1073 }
1074 case Instruction::Select: {
1076 bool IsScalarCond = getOperand(0)->isDefinedOutsideLoopRegions();
1077 Type *ScalarTy = Ctx.Types.inferScalarType(this);
1078
1079 VPValue *Op0, *Op1;
1080 bool IsLogicalAnd =
1081 match(this, m_LogicalAnd(m_VPValue(Op0), m_VPValue(Op1)));
1082 bool IsLogicalOr = match(this, m_LogicalOr(m_VPValue(Op0), m_VPValue(Op1)));
1083
1084 if (!IsScalarCond && ScalarTy->getScalarSizeInBits() == 1 &&
1085 (IsLogicalAnd || IsLogicalOr)) {
1086 // select x, y, false --> x & y
1087 // select x, true, y --> x | y
1088 const auto [Op1VK, Op1VP] = Ctx.getOperandInfo(Op0);
1089 const auto [Op2VK, Op2VP] = Ctx.getOperandInfo(Op1);
1090
1091 SmallVector<const Value *, 2> Operands;
1092 if (SI && all_of(operands(),
1093 [](VPValue *Op) { return Op->getUnderlyingValue(); }))
1094 append_range(Operands, SI->operands());
1095 return Ctx.TTI.getArithmeticInstrCost(
1096 IsLogicalOr ? Instruction::Or : Instruction::And, ResultTy,
1097 Ctx.CostKind, {Op1VK, Op1VP}, {Op2VK, Op2VP}, Operands, SI);
1098 }
1099
1100 Type *CondTy = Ctx.Types.inferScalarType(getOperand(0));
1101 if (!IsScalarCond)
1102 CondTy = VectorType::get(CondTy, VF);
1103
1104 llvm::CmpPredicate Pred;
1105 if (!match(getOperand(0), m_Cmp(Pred, m_VPValue(), m_VPValue())))
1106 if (auto *CondIRV = dyn_cast<VPIRValue>(getOperand(0)))
1107 if (auto *Cmp = dyn_cast<CmpInst>(CondIRV->getValue()))
1108 Pred = Cmp->getPredicate();
1109 Type *VectorTy = toVectorTy(Ctx.Types.inferScalarType(this), VF);
1110 return Ctx.TTI.getCmpSelInstrCost(
1111 Instruction::Select, VectorTy, CondTy, Pred, Ctx.CostKind,
1112 {TTI::OK_AnyValue, TTI::OP_None}, {TTI::OK_AnyValue, TTI::OP_None}, SI);
1113 }
1114 }
1115 llvm_unreachable("called for unsupported opcode");
1116}
1117
1119 VPCostContext &Ctx) const {
1121 if (!getUnderlyingValue() && getOpcode() != Instruction::FMul) {
1122 // TODO: Compute cost for VPInstructions without underlying values once
1123 // the legacy cost model has been retired.
1124 return 0;
1125 }
1126
1128 "Should only generate a vector value or single scalar, not scalars "
1129 "for all lanes.");
1131 getOpcode(),
1133 }
1134
1135 switch (getOpcode()) {
1136 case Instruction::Select: {
1138 match(getOperand(0), m_Cmp(Pred, m_VPValue(), m_VPValue()));
1139 auto *CondTy = Ctx.Types.inferScalarType(getOperand(0));
1140 auto *VecTy = Ctx.Types.inferScalarType(getOperand(1));
1141 if (!vputils::onlyFirstLaneUsed(this)) {
1142 CondTy = toVectorTy(CondTy, VF);
1143 VecTy = toVectorTy(VecTy, VF);
1144 }
1145 return Ctx.TTI.getCmpSelInstrCost(Instruction::Select, VecTy, CondTy, Pred,
1146 Ctx.CostKind);
1147 }
1148 case Instruction::ExtractElement:
1150 if (VF.isScalar()) {
1151 // ExtractLane with VF=1 takes care of handling extracting across multiple
1152 // parts.
1153 return 0;
1154 }
1155
1156 // Add on the cost of extracting the element.
1157 auto *VecTy = toVectorTy(Ctx.Types.inferScalarType(getOperand(0)), VF);
1158 return Ctx.TTI.getVectorInstrCost(Instruction::ExtractElement, VecTy,
1159 Ctx.CostKind);
1160 }
1161 case VPInstruction::AnyOf: {
1162 auto *VecTy = toVectorTy(Ctx.Types.inferScalarType(this), VF);
1163 return Ctx.TTI.getArithmeticReductionCost(
1164 Instruction::Or, cast<VectorType>(VecTy), std::nullopt, Ctx.CostKind);
1165 }
1167 Type *ScalarTy = Ctx.Types.inferScalarType(getOperand(0));
1168 if (VF.isScalar())
1169 return Ctx.TTI.getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
1171 CmpInst::ICMP_EQ, Ctx.CostKind);
1172 // Calculate the cost of determining the lane index.
1173 auto *PredTy = toVectorTy(ScalarTy, VF);
1174 IntrinsicCostAttributes Attrs(Intrinsic::experimental_cttz_elts,
1175 Type::getInt64Ty(Ctx.LLVMCtx),
1176 {PredTy, Type::getInt1Ty(Ctx.LLVMCtx)});
1177 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1178 }
1180 Type *ScalarTy = Ctx.Types.inferScalarType(getOperand(0));
1181 if (VF.isScalar())
1182 return Ctx.TTI.getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
1184 CmpInst::ICMP_EQ, Ctx.CostKind);
1185 // Calculate the cost of determining the lane index: NOT + cttz_elts + SUB.
1186 auto *PredTy = toVectorTy(ScalarTy, VF);
1187 IntrinsicCostAttributes Attrs(Intrinsic::experimental_cttz_elts,
1188 Type::getInt64Ty(Ctx.LLVMCtx),
1189 {PredTy, Type::getInt1Ty(Ctx.LLVMCtx)});
1190 InstructionCost Cost = Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1191 // Add cost of NOT operation on the predicate.
1192 Cost += Ctx.TTI.getArithmeticInstrCost(
1193 Instruction::Xor, PredTy, Ctx.CostKind,
1194 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
1195 {TargetTransformInfo::OK_UniformConstantValue,
1196 TargetTransformInfo::OP_None});
1197 // Add cost of SUB operation on the index.
1198 Cost += Ctx.TTI.getArithmeticInstrCost(
1199 Instruction::Sub, Type::getInt64Ty(Ctx.LLVMCtx), Ctx.CostKind);
1200 return Cost;
1201 }
1203 Type *ScalarTy = Ctx.Types.inferScalarType(this);
1204 Type *VecTy = toVectorTy(ScalarTy, VF);
1205 Type *MaskTy = toVectorTy(Type::getInt1Ty(Ctx.LLVMCtx), VF);
1207 Intrinsic::experimental_vector_extract_last_active, ScalarTy,
1208 {VecTy, MaskTy, ScalarTy});
1209 return Ctx.TTI.getIntrinsicInstrCost(ICA, Ctx.CostKind);
1210 }
1212 assert(VF.isVector() && "Scalar FirstOrderRecurrenceSplice?");
1214 std::iota(Mask.begin(), Mask.end(), VF.getKnownMinValue() - 1);
1215 Type *VectorTy = toVectorTy(Ctx.Types.inferScalarType(this), VF);
1216
1217 return Ctx.TTI.getShuffleCost(TargetTransformInfo::SK_Splice,
1218 cast<VectorType>(VectorTy),
1219 cast<VectorType>(VectorTy), Mask,
1220 Ctx.CostKind, VF.getKnownMinValue() - 1);
1221 }
1223 Type *ArgTy = Ctx.Types.inferScalarType(getOperand(0));
1224 unsigned Multiplier = cast<VPConstantInt>(getOperand(2))->getZExtValue();
1225 Type *RetTy = toVectorTy(Type::getInt1Ty(Ctx.LLVMCtx), VF * Multiplier);
1226 IntrinsicCostAttributes Attrs(Intrinsic::get_active_lane_mask, RetTy,
1227 {ArgTy, ArgTy});
1228 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1229 }
1231 Type *Arg0Ty = Ctx.Types.inferScalarType(getOperand(0));
1232 Type *I32Ty = Type::getInt32Ty(Ctx.LLVMCtx);
1233 Type *I1Ty = Type::getInt1Ty(Ctx.LLVMCtx);
1234 IntrinsicCostAttributes Attrs(Intrinsic::experimental_get_vector_length,
1235 I32Ty, {Arg0Ty, I32Ty, I1Ty});
1236 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1237 }
1239 assert(VF.isVector() && "Reverse operation must be vector type");
1240 auto *VectorTy = cast<VectorType>(
1241 toVectorTy(Ctx.Types.inferScalarType(getOperand(0)), VF));
1242 return Ctx.TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy,
1243 VectorTy, /*Mask=*/{}, Ctx.CostKind,
1244 /*Index=*/0);
1245 }
1247 // Add on the cost of extracting the element.
1248 auto *VecTy = toVectorTy(Ctx.Types.inferScalarType(getOperand(0)), VF);
1249 return Ctx.TTI.getIndexedVectorInstrCostFromEnd(Instruction::ExtractElement,
1250 VecTy, Ctx.CostKind, 0);
1251 }
1253 if (VF == ElementCount::getScalable(1))
1255 [[fallthrough]];
1256 default:
1257 // TODO: Compute cost other VPInstructions once the legacy cost model has
1258 // been retired.
1260 "unexpected VPInstruction witht underlying value");
1261 return 0;
1262 }
1263}
1264
1278
1280 switch (getOpcode()) {
1281 case Instruction::PHI:
1285 return true;
1286 default:
1287 return isScalarCast();
1288 }
1289}
1290
1292 assert(!State.Lane && "VPInstruction executing an Lane");
1293 IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder);
1295 "Set flags not supported for the provided opcode");
1296 if (hasFastMathFlags())
1297 State.Builder.setFastMathFlags(getFastMathFlags());
1298 Value *GeneratedValue = generate(State);
1299 if (!hasResult())
1300 return;
1301 assert(GeneratedValue && "generate must produce a value");
1302 bool GeneratesPerFirstLaneOnly = canGenerateScalarForFirstLane() &&
1305 assert((((GeneratedValue->getType()->isVectorTy() ||
1306 GeneratedValue->getType()->isStructTy()) ==
1307 !GeneratesPerFirstLaneOnly) ||
1308 State.VF.isScalar()) &&
1309 "scalar value but not only first lane defined");
1310 State.set(this, GeneratedValue,
1311 /*IsScalar*/ GeneratesPerFirstLaneOnly);
1312}
1313
1316 return false;
1317 switch (getOpcode()) {
1318 case Instruction::GetElementPtr:
1319 case Instruction::ExtractElement:
1320 case Instruction::Freeze:
1321 case Instruction::FCmp:
1322 case Instruction::ICmp:
1323 case Instruction::Select:
1324 case Instruction::PHI:
1345 case VPInstruction::Not:
1354 return false;
1355 default:
1356 return true;
1357 }
1358}
1359
1361 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
1363 return vputils::onlyFirstLaneUsed(this);
1364
1365 switch (getOpcode()) {
1366 default:
1367 return false;
1368 case Instruction::ExtractElement:
1369 return Op == getOperand(1);
1370 case Instruction::PHI:
1371 return true;
1372 case Instruction::FCmp:
1373 case Instruction::ICmp:
1374 case Instruction::Select:
1375 case Instruction::Or:
1376 case Instruction::Freeze:
1377 case VPInstruction::Not:
1378 // TODO: Cover additional opcodes.
1379 return vputils::onlyFirstLaneUsed(this);
1388 return true;
1391 // Before replicating by VF, Build(Struct)Vector uses all lanes of the
1392 // operand, after replicating its operands only the first lane is used.
1393 // Before replicating, it will have only a single operand.
1394 return getNumOperands() > 1;
1396 return Op == getOperand(0) || vputils::onlyFirstLaneUsed(this);
1398 // WidePtrAdd supports scalar and vector base addresses.
1399 return false;
1401 return Op == getOperand(1);
1403 return Op == getOperand(0);
1405 return Op == getOperand(0);
1406 };
1407 llvm_unreachable("switch should return");
1408}
1409
1411 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
1413 return vputils::onlyFirstPartUsed(this);
1414
1415 switch (getOpcode()) {
1416 default:
1417 return false;
1418 case Instruction::FCmp:
1419 case Instruction::ICmp:
1420 case Instruction::Select:
1421 return vputils::onlyFirstPartUsed(this);
1426 return true;
1427 };
1428 llvm_unreachable("switch should return");
1429}
1430
1431#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1433 VPSlotTracker SlotTracker(getParent()->getPlan());
1435}
1436
1438 VPSlotTracker &SlotTracker) const {
1439 O << Indent << "EMIT" << (isSingleScalar() ? "-SCALAR" : "") << " ";
1440
1441 if (hasResult()) {
1443 O << " = ";
1444 }
1445
1446 switch (getOpcode()) {
1447 case VPInstruction::Not:
1448 O << "not";
1449 break;
1451 O << "combined load";
1452 break;
1454 O << "combined store";
1455 break;
1457 O << "active lane mask";
1458 break;
1460 O << "EXPLICIT-VECTOR-LENGTH";
1461 break;
1463 O << "first-order splice";
1464 break;
1466 O << "branch-on-cond";
1467 break;
1469 O << "branch-on-two-conds";
1470 break;
1472 O << "TC > VF ? TC - VF : 0";
1473 break;
1475 O << "VF * Part +";
1476 break;
1478 O << "branch-on-count";
1479 break;
1481 O << "broadcast";
1482 break;
1484 O << "buildstructvector";
1485 break;
1487 O << "buildvector";
1488 break;
1490 O << "extract-lane";
1491 break;
1493 O << "extract-last-lane";
1494 break;
1496 O << "extract-last-part";
1497 break;
1499 O << "extract-penultimate-element";
1500 break;
1502 O << "compute-anyof-result";
1503 break;
1505 O << "compute-find-iv-result";
1506 break;
1508 O << "compute-reduction-result";
1509 break;
1511 O << "logical-and";
1512 break;
1514 O << "ptradd";
1515 break;
1517 O << "wide-ptradd";
1518 break;
1520 O << "any-of";
1521 break;
1523 O << "first-active-lane";
1524 break;
1526 O << "last-active-lane";
1527 break;
1529 O << "reduction-start-vector";
1530 break;
1532 O << "resume-for-epilogue";
1533 break;
1535 O << "reverse";
1536 break;
1538 O << "unpack";
1539 break;
1541 O << "extract-last-active";
1542 break;
1543 default:
1545 }
1546
1547 printFlags(O);
1549}
1550#endif
1551
1553 State.setDebugLocFrom(getDebugLoc());
1554 if (isScalarCast()) {
1555 Value *Op = State.get(getOperand(0), VPLane(0));
1556 Value *Cast = State.Builder.CreateCast(Instruction::CastOps(getOpcode()),
1557 Op, ResultTy);
1558 State.set(this, Cast, VPLane(0));
1559 return;
1560 }
1561 switch (getOpcode()) {
1563 Value *StepVector =
1564 State.Builder.CreateStepVector(VectorType::get(ResultTy, State.VF));
1565 State.set(this, StepVector);
1566 break;
1567 }
1568 case VPInstruction::VScale: {
1569 Value *VScale = State.Builder.CreateVScale(ResultTy);
1570 State.set(this, VScale, true);
1571 break;
1572 }
1573
1574 default:
1575 llvm_unreachable("opcode not implemented yet");
1576 }
1577}
1578
1579#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1581 VPSlotTracker &SlotTracker) const {
1582 O << Indent << "EMIT" << (isSingleScalar() ? "-SCALAR" : "") << " ";
1584 O << " = ";
1585
1586 switch (getOpcode()) {
1588 O << "wide-iv-step ";
1590 break;
1592 O << "step-vector " << *ResultTy;
1593 break;
1595 O << "vscale " << *ResultTy;
1596 break;
1597 default:
1598 assert(Instruction::isCast(getOpcode()) && "unhandled opcode");
1601 O << " to " << *ResultTy;
1602 }
1603}
1604#endif
1605
1607 State.setDebugLocFrom(getDebugLoc());
1608 PHINode *NewPhi = State.Builder.CreatePHI(
1609 State.TypeAnalysis.inferScalarType(this), 2, getName());
1610 unsigned NumIncoming = getNumIncoming();
1611 if (getParent() != getParent()->getPlan()->getScalarPreheader()) {
1612 // TODO: Fixup all incoming values of header phis once recipes defining them
1613 // are introduced.
1614 NumIncoming = 1;
1615 }
1616 for (unsigned Idx = 0; Idx != NumIncoming; ++Idx) {
1617 Value *IncV = State.get(getIncomingValue(Idx), VPLane(0));
1618 BasicBlock *PredBB = State.CFG.VPBB2IRBB.at(getIncomingBlock(Idx));
1619 NewPhi->addIncoming(IncV, PredBB);
1620 }
1621 State.set(this, NewPhi, VPLane(0));
1622}
1623
1624#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1625void VPPhi::printRecipe(raw_ostream &O, const Twine &Indent,
1626 VPSlotTracker &SlotTracker) const {
1627 O << Indent << "EMIT" << (isSingleScalar() ? "-SCALAR" : "") << " ";
1629 O << " = phi ";
1631}
1632#endif
1633
1634VPIRInstruction *VPIRInstruction ::create(Instruction &I) {
1635 if (auto *Phi = dyn_cast<PHINode>(&I))
1636 return new VPIRPhi(*Phi);
1637 return new VPIRInstruction(I);
1638}
1639
1641 assert(!isa<VPIRPhi>(this) && getNumOperands() == 0 &&
1642 "PHINodes must be handled by VPIRPhi");
1643 // Advance the insert point after the wrapped IR instruction. This allows
1644 // interleaving VPIRInstructions and other recipes.
1645 State.Builder.SetInsertPoint(I.getParent(), std::next(I.getIterator()));
1646}
1647
1649 VPCostContext &Ctx) const {
1650 // The recipe wraps an existing IR instruction on the border of VPlan's scope,
1651 // hence it does not contribute to the cost-modeling for the VPlan.
1652 return 0;
1653}
1654
1656 VPBuilder &Builder) {
1658 "can only update exiting operands to phi nodes");
1659 assert(getNumOperands() > 0 && "must have at least one operand");
1660 VPValue *Exiting = getOperand(0);
1661 if (isa<VPIRValue>(Exiting))
1662 return;
1663
1664 Exiting = Builder.createNaryOp(VPInstruction::ExtractLastPart, Exiting);
1665 Exiting = Builder.createNaryOp(VPInstruction::ExtractLastLane, Exiting);
1666 setOperand(0, Exiting);
1667}
1668
1669#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1671 VPSlotTracker &SlotTracker) const {
1672 O << Indent << "IR " << I;
1673}
1674#endif
1675
1677 PHINode *Phi = &getIRPhi();
1678 for (const auto &[Idx, Op] : enumerate(operands())) {
1679 VPValue *ExitValue = Op;
1680 auto Lane = vputils::isSingleScalar(ExitValue)
1682 : VPLane::getLastLaneForVF(State.VF);
1683 VPBlockBase *Pred = getParent()->getPredecessors()[Idx];
1684 auto *PredVPBB = Pred->getExitingBasicBlock();
1685 BasicBlock *PredBB = State.CFG.VPBB2IRBB[PredVPBB];
1686 // Set insertion point in PredBB in case an extract needs to be generated.
1687 // TODO: Model extracts explicitly.
1688 State.Builder.SetInsertPoint(PredBB, PredBB->getFirstNonPHIIt());
1689 Value *V = State.get(ExitValue, VPLane(Lane));
1690 // If there is no existing block for PredBB in the phi, add a new incoming
1691 // value. Otherwise update the existing incoming value for PredBB.
1692 if (Phi->getBasicBlockIndex(PredBB) == -1)
1693 Phi->addIncoming(V, PredBB);
1694 else
1695 Phi->setIncomingValueForBlock(PredBB, V);
1696 }
1697
1698 // Advance the insert point after the wrapped IR instruction. This allows
1699 // interleaving VPIRInstructions and other recipes.
1700 State.Builder.SetInsertPoint(Phi->getParent(), std::next(Phi->getIterator()));
1701}
1702
1704 VPRecipeBase *R = const_cast<VPRecipeBase *>(getAsRecipe());
1705 assert(R->getNumOperands() == R->getParent()->getNumPredecessors() &&
1706 "Number of phi operands must match number of predecessors");
1707 unsigned Position = R->getParent()->getIndexForPredecessor(IncomingBlock);
1708 R->removeOperand(Position);
1709}
1710
1711#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1713 VPSlotTracker &SlotTracker) const {
1714 interleaveComma(enumerate(getAsRecipe()->operands()), O,
1715 [this, &O, &SlotTracker](auto Op) {
1716 O << "[ ";
1717 Op.value()->printAsOperand(O, SlotTracker);
1718 O << ", ";
1719 getIncomingBlock(Op.index())->printAsOperand(O);
1720 O << " ]";
1721 });
1722}
1723#endif
1724
1725#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1727 VPSlotTracker &SlotTracker) const {
1729
1730 if (getNumOperands() != 0) {
1731 O << " (extra operand" << (getNumOperands() > 1 ? "s" : "") << ": ";
1733 [&O, &SlotTracker](auto Op) {
1734 std::get<0>(Op)->printAsOperand(O, SlotTracker);
1735 O << " from ";
1736 std::get<1>(Op)->printAsOperand(O);
1737 });
1738 O << ")";
1739 }
1740}
1741#endif
1742
1744 for (const auto &[Kind, Node] : Metadata)
1745 I.setMetadata(Kind, Node);
1746}
1747
1749 SmallVector<std::pair<unsigned, MDNode *>> MetadataIntersection;
1750 for (const auto &[KindA, MDA] : Metadata) {
1751 for (const auto &[KindB, MDB] : Other.Metadata) {
1752 if (KindA == KindB && MDA == MDB) {
1753 MetadataIntersection.emplace_back(KindA, MDA);
1754 break;
1755 }
1756 }
1757 }
1758 Metadata = std::move(MetadataIntersection);
1759}
1760
1761#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1763 const Module *M = SlotTracker.getModule();
1764 if (Metadata.empty() || !M)
1765 return;
1766
1767 ArrayRef<StringRef> MDNames = SlotTracker.getMDNames();
1768 O << " (";
1769 interleaveComma(Metadata, O, [&](const auto &KindNodePair) {
1770 auto [Kind, Node] = KindNodePair;
1771 assert(Kind < MDNames.size() && !MDNames[Kind].empty() &&
1772 "Unexpected unnamed metadata kind");
1773 O << "!" << MDNames[Kind] << " ";
1774 Node->printAsOperand(O, M);
1775 });
1776 O << ")";
1777}
1778#endif
1779
1781 assert(State.VF.isVector() && "not widening");
1782 assert(Variant != nullptr && "Can't create vector function.");
1783
1784 FunctionType *VFTy = Variant->getFunctionType();
1785 // Add return type if intrinsic is overloaded on it.
1787 for (const auto &I : enumerate(args())) {
1788 Value *Arg;
1789 // Some vectorized function variants may also take a scalar argument,
1790 // e.g. linear parameters for pointers. This needs to be the scalar value
1791 // from the start of the respective part when interleaving.
1792 if (!VFTy->getParamType(I.index())->isVectorTy())
1793 Arg = State.get(I.value(), VPLane(0));
1794 else
1795 Arg = State.get(I.value(), usesFirstLaneOnly(I.value()));
1796 Args.push_back(Arg);
1797 }
1798
1801 if (CI)
1802 CI->getOperandBundlesAsDefs(OpBundles);
1803
1804 CallInst *V = State.Builder.CreateCall(Variant, Args, OpBundles);
1805 applyFlags(*V);
1806 applyMetadata(*V);
1807 V->setCallingConv(Variant->getCallingConv());
1808
1809 if (!V->getType()->isVoidTy())
1810 State.set(this, V);
1811}
1812
1814 VPCostContext &Ctx) const {
1815 return Ctx.TTI.getCallInstrCost(nullptr, Variant->getReturnType(),
1816 Variant->getFunctionType()->params(),
1817 Ctx.CostKind);
1818}
1819
1820#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1822 VPSlotTracker &SlotTracker) const {
1823 O << Indent << "WIDEN-CALL ";
1824
1825 Function *CalledFn = getCalledScalarFunction();
1826 if (CalledFn->getReturnType()->isVoidTy())
1827 O << "void ";
1828 else {
1830 O << " = ";
1831 }
1832
1833 O << "call";
1834 printFlags(O);
1835 O << " @" << CalledFn->getName() << "(";
1836 interleaveComma(args(), O, [&O, &SlotTracker](VPValue *Op) {
1837 Op->printAsOperand(O, SlotTracker);
1838 });
1839 O << ")";
1840
1841 O << " (using library function";
1842 if (Variant->hasName())
1843 O << ": " << Variant->getName();
1844 O << ")";
1845}
1846#endif
1847
1849 assert(State.VF.isVector() && "not widening");
1850
1851 SmallVector<Type *, 2> TysForDecl;
1852 // Add return type if intrinsic is overloaded on it.
1853 if (isVectorIntrinsicWithOverloadTypeAtArg(VectorIntrinsicID, -1,
1854 State.TTI)) {
1855 Type *RetTy = toVectorizedTy(getResultType(), State.VF);
1856 ArrayRef<Type *> ContainedTys = getContainedTypes(RetTy);
1857 for (auto [Idx, Ty] : enumerate(ContainedTys)) {
1859 Idx, State.TTI))
1860 TysForDecl.push_back(Ty);
1861 }
1862 }
1864 for (const auto &I : enumerate(operands())) {
1865 // Some intrinsics have a scalar argument - don't replace it with a
1866 // vector.
1867 Value *Arg;
1868 if (isVectorIntrinsicWithScalarOpAtArg(VectorIntrinsicID, I.index(),
1869 State.TTI))
1870 Arg = State.get(I.value(), VPLane(0));
1871 else
1872 Arg = State.get(I.value(), usesFirstLaneOnly(I.value()));
1873 if (isVectorIntrinsicWithOverloadTypeAtArg(VectorIntrinsicID, I.index(),
1874 State.TTI))
1875 TysForDecl.push_back(Arg->getType());
1876 Args.push_back(Arg);
1877 }
1878
1879 // Use vector version of the intrinsic.
1880 Module *M = State.Builder.GetInsertBlock()->getModule();
1881 Function *VectorF =
1882 Intrinsic::getOrInsertDeclaration(M, VectorIntrinsicID, TysForDecl);
1883 assert(VectorF &&
1884 "Can't retrieve vector intrinsic or vector-predication intrinsics.");
1885
1888 if (CI)
1889 CI->getOperandBundlesAsDefs(OpBundles);
1890
1891 CallInst *V = State.Builder.CreateCall(VectorF, Args, OpBundles);
1892
1893 applyFlags(*V);
1894 applyMetadata(*V);
1895
1896 if (!V->getType()->isVoidTy())
1897 State.set(this, V);
1898}
1899
1900/// Compute the cost for the intrinsic \p ID with \p Operands, produced by \p R.
1903 const VPRecipeWithIRFlags &R,
1904 ElementCount VF,
1905 VPCostContext &Ctx) {
1906 // Some backends analyze intrinsic arguments to determine cost. Use the
1907 // underlying value for the operand if it has one. Otherwise try to use the
1908 // operand of the underlying call instruction, if there is one. Otherwise
1909 // clear Arguments.
1910 // TODO: Rework TTI interface to be independent of concrete IR values.
1912 for (const auto &[Idx, Op] : enumerate(Operands)) {
1913 auto *V = Op->getUnderlyingValue();
1914 if (!V) {
1915 if (auto *UI = dyn_cast_or_null<CallBase>(R.getUnderlyingValue())) {
1916 Arguments.push_back(UI->getArgOperand(Idx));
1917 continue;
1918 }
1919 Arguments.clear();
1920 break;
1921 }
1922 Arguments.push_back(V);
1923 }
1924
1925 Type *ScalarRetTy = Ctx.Types.inferScalarType(&R);
1926 Type *RetTy = VF.isVector() ? toVectorizedTy(ScalarRetTy, VF) : ScalarRetTy;
1927 SmallVector<Type *> ParamTys;
1928 for (const VPValue *Op : Operands) {
1929 ParamTys.push_back(VF.isVector()
1930 ? toVectorTy(Ctx.Types.inferScalarType(Op), VF)
1931 : Ctx.Types.inferScalarType(Op));
1932 }
1933
1934 // TODO: Rework TTI interface to avoid reliance on underlying IntrinsicInst.
1935 FastMathFlags FMF =
1936 R.hasFastMathFlags() ? R.getFastMathFlags() : FastMathFlags();
1937 IntrinsicCostAttributes CostAttrs(
1938 ID, RetTy, Arguments, ParamTys, FMF,
1939 dyn_cast_or_null<IntrinsicInst>(R.getUnderlyingValue()),
1940 InstructionCost::getInvalid(), &Ctx.TLI);
1941 return Ctx.TTI.getIntrinsicInstrCost(CostAttrs, Ctx.CostKind);
1942}
1943
1945 VPCostContext &Ctx) const {
1947 return getCostForIntrinsics(VectorIntrinsicID, ArgOps, *this, VF, Ctx);
1948}
1949
1951 return Intrinsic::getBaseName(VectorIntrinsicID);
1952}
1953
1955 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
1956 return all_of(enumerate(operands()), [this, &Op](const auto &X) {
1957 auto [Idx, V] = X;
1959 Idx, nullptr);
1960 });
1961}
1962
1963#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1965 VPSlotTracker &SlotTracker) const {
1966 O << Indent << "WIDEN-INTRINSIC ";
1967 if (ResultTy->isVoidTy()) {
1968 O << "void ";
1969 } else {
1971 O << " = ";
1972 }
1973
1974 O << "call";
1975 printFlags(O);
1976 O << getIntrinsicName() << "(";
1977
1979 Op->printAsOperand(O, SlotTracker);
1980 });
1981 O << ")";
1982}
1983#endif
1984
1986 IRBuilderBase &Builder = State.Builder;
1987
1988 Value *Address = State.get(getOperand(0));
1989 Value *IncAmt = State.get(getOperand(1), /*IsScalar=*/true);
1990 VectorType *VTy = cast<VectorType>(Address->getType());
1991
1992 // The histogram intrinsic requires a mask even if the recipe doesn't;
1993 // if the mask operand was omitted then all lanes should be executed and
1994 // we just need to synthesize an all-true mask.
1995 Value *Mask = nullptr;
1996 if (VPValue *VPMask = getMask())
1997 Mask = State.get(VPMask);
1998 else
1999 Mask =
2000 Builder.CreateVectorSplat(VTy->getElementCount(), Builder.getInt1(1));
2001
2002 // If this is a subtract, we want to invert the increment amount. We may
2003 // add a separate intrinsic in future, but for now we'll try this.
2004 if (Opcode == Instruction::Sub)
2005 IncAmt = Builder.CreateNeg(IncAmt);
2006 else
2007 assert(Opcode == Instruction::Add && "only add or sub supported for now");
2008
2009 State.Builder.CreateIntrinsic(Intrinsic::experimental_vector_histogram_add,
2010 {VTy, IncAmt->getType()},
2011 {Address, IncAmt, Mask});
2012}
2013
2015 VPCostContext &Ctx) const {
2016 // FIXME: Take the gather and scatter into account as well. For now we're
2017 // generating the same cost as the fallback path, but we'll likely
2018 // need to create a new TTI method for determining the cost, including
2019 // whether we can use base + vec-of-smaller-indices or just
2020 // vec-of-pointers.
2021 assert(VF.isVector() && "Invalid VF for histogram cost");
2022 Type *AddressTy = Ctx.Types.inferScalarType(getOperand(0));
2023 VPValue *IncAmt = getOperand(1);
2024 Type *IncTy = Ctx.Types.inferScalarType(IncAmt);
2025 VectorType *VTy = VectorType::get(IncTy, VF);
2026
2027 // Assume that a non-constant update value (or a constant != 1) requires
2028 // a multiply, and add that into the cost.
2029 InstructionCost MulCost =
2030 Ctx.TTI.getArithmeticInstrCost(Instruction::Mul, VTy, Ctx.CostKind);
2031 if (auto *CI = dyn_cast<VPConstantInt>(IncAmt))
2032 if (CI->isOne())
2033 MulCost = TTI::TCC_Free;
2034
2035 // Find the cost of the histogram operation itself.
2036 Type *PtrTy = VectorType::get(AddressTy, VF);
2037 Type *MaskTy = VectorType::get(Type::getInt1Ty(Ctx.LLVMCtx), VF);
2038 IntrinsicCostAttributes ICA(Intrinsic::experimental_vector_histogram_add,
2039 Type::getVoidTy(Ctx.LLVMCtx),
2040 {PtrTy, IncTy, MaskTy});
2041
2042 // Add the costs together with the add/sub operation.
2043 return Ctx.TTI.getIntrinsicInstrCost(ICA, Ctx.CostKind) + MulCost +
2044 Ctx.TTI.getArithmeticInstrCost(Opcode, VTy, Ctx.CostKind);
2045}
2046
2047#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2049 VPSlotTracker &SlotTracker) const {
2050 O << Indent << "WIDEN-HISTOGRAM buckets: ";
2052
2053 if (Opcode == Instruction::Sub)
2054 O << ", dec: ";
2055 else {
2056 assert(Opcode == Instruction::Add);
2057 O << ", inc: ";
2058 }
2060
2061 if (VPValue *Mask = getMask()) {
2062 O << ", mask: ";
2063 Mask->printAsOperand(O, SlotTracker);
2064 }
2065}
2066#endif
2067
2068VPIRFlags::FastMathFlagsTy::FastMathFlagsTy(const FastMathFlags &FMF) {
2069 AllowReassoc = FMF.allowReassoc();
2070 NoNaNs = FMF.noNaNs();
2071 NoInfs = FMF.noInfs();
2072 NoSignedZeros = FMF.noSignedZeros();
2073 AllowReciprocal = FMF.allowReciprocal();
2074 AllowContract = FMF.allowContract();
2075 ApproxFunc = FMF.approxFunc();
2076}
2077
2078#if !defined(NDEBUG)
2079bool VPIRFlags::flagsValidForOpcode(unsigned Opcode) const {
2080 switch (OpType) {
2081 case OperationType::OverflowingBinOp:
2082 return Opcode == Instruction::Add || Opcode == Instruction::Sub ||
2083 Opcode == Instruction::Mul || Opcode == Instruction::Shl ||
2084 Opcode == VPInstruction::VPInstruction::CanonicalIVIncrementForPart;
2085 case OperationType::Trunc:
2086 return Opcode == Instruction::Trunc;
2087 case OperationType::DisjointOp:
2088 return Opcode == Instruction::Or;
2089 case OperationType::PossiblyExactOp:
2090 return Opcode == Instruction::AShr || Opcode == Instruction::LShr ||
2091 Opcode == Instruction::UDiv || Opcode == Instruction::SDiv;
2092 case OperationType::GEPOp:
2093 return Opcode == Instruction::GetElementPtr ||
2094 Opcode == VPInstruction::PtrAdd ||
2095 Opcode == VPInstruction::WidePtrAdd;
2096 case OperationType::FPMathOp:
2097 return Opcode == Instruction::Call || Opcode == Instruction::FAdd ||
2098 Opcode == Instruction::FMul || Opcode == Instruction::FSub ||
2099 Opcode == Instruction::FNeg || Opcode == Instruction::FDiv ||
2100 Opcode == Instruction::FRem || Opcode == Instruction::FPExt ||
2101 Opcode == Instruction::FPTrunc || Opcode == Instruction::Select ||
2102 Opcode == VPInstruction::WideIVStep ||
2104 case OperationType::FCmp:
2105 return Opcode == Instruction::FCmp;
2106 case OperationType::NonNegOp:
2107 return Opcode == Instruction::ZExt || Opcode == Instruction::UIToFP;
2108 case OperationType::Cmp:
2109 return Opcode == Instruction::FCmp || Opcode == Instruction::ICmp;
2110 case OperationType::ReductionOp:
2111 return Opcode == VPInstruction::ComputeReductionResult ||
2113 case OperationType::Other:
2114 return true;
2115 }
2116 llvm_unreachable("Unknown OperationType enum");
2117}
2118#endif
2119
2120#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2122 switch (OpType) {
2123 case OperationType::Cmp:
2125 break;
2126 case OperationType::FCmp:
2129 break;
2130 case OperationType::DisjointOp:
2131 if (DisjointFlags.IsDisjoint)
2132 O << " disjoint";
2133 break;
2134 case OperationType::PossiblyExactOp:
2135 if (ExactFlags.IsExact)
2136 O << " exact";
2137 break;
2138 case OperationType::OverflowingBinOp:
2139 if (WrapFlags.HasNUW)
2140 O << " nuw";
2141 if (WrapFlags.HasNSW)
2142 O << " nsw";
2143 break;
2144 case OperationType::Trunc:
2145 if (TruncFlags.HasNUW)
2146 O << " nuw";
2147 if (TruncFlags.HasNSW)
2148 O << " nsw";
2149 break;
2150 case OperationType::FPMathOp:
2152 break;
2153 case OperationType::GEPOp:
2154 if (GEPFlags.isInBounds())
2155 O << " inbounds";
2156 else if (GEPFlags.hasNoUnsignedSignedWrap())
2157 O << " nusw";
2158 if (GEPFlags.hasNoUnsignedWrap())
2159 O << " nuw";
2160 break;
2161 case OperationType::NonNegOp:
2162 if (NonNegFlags.NonNeg)
2163 O << " nneg";
2164 break;
2165 case OperationType::ReductionOp: {
2166 RecurKind RK = getRecurKind();
2167 O << " (";
2168 switch (RK) {
2169 case RecurKind::SMax:
2170 O << "smax";
2171 break;
2172 case RecurKind::SMin:
2173 O << "smin";
2174 break;
2175 case RecurKind::UMax:
2176 O << "umax";
2177 break;
2178 case RecurKind::UMin:
2179 O << "umin";
2180 break;
2181 case RecurKind::FMinNum:
2182 O << "fminnum";
2183 break;
2184 case RecurKind::FMaxNum:
2185 O << "fmaxnum";
2186 break;
2188 O << "fminimum";
2189 break;
2191 O << "fmaximum";
2192 break;
2194 O << "fminimumnum";
2195 break;
2197 O << "fmaximumnum";
2198 break;
2199 default:
2201 break;
2202 }
2203 if (isReductionInLoop())
2204 O << ", in-loop";
2205 if (isReductionOrdered())
2206 O << ", ordered";
2207 O << ")";
2209 break;
2210 }
2211 case OperationType::Other:
2212 break;
2213 }
2214 O << " ";
2215}
2216#endif
2217
2219 auto &Builder = State.Builder;
2220 switch (Opcode) {
2221 case Instruction::Call:
2222 case Instruction::Br:
2223 case Instruction::PHI:
2224 case Instruction::GetElementPtr:
2225 llvm_unreachable("This instruction is handled by a different recipe.");
2226 case Instruction::UDiv:
2227 case Instruction::SDiv:
2228 case Instruction::SRem:
2229 case Instruction::URem:
2230 case Instruction::Add:
2231 case Instruction::FAdd:
2232 case Instruction::Sub:
2233 case Instruction::FSub:
2234 case Instruction::FNeg:
2235 case Instruction::Mul:
2236 case Instruction::FMul:
2237 case Instruction::FDiv:
2238 case Instruction::FRem:
2239 case Instruction::Shl:
2240 case Instruction::LShr:
2241 case Instruction::AShr:
2242 case Instruction::And:
2243 case Instruction::Or:
2244 case Instruction::Xor: {
2245 // Just widen unops and binops.
2247 for (VPValue *VPOp : operands())
2248 Ops.push_back(State.get(VPOp));
2249
2250 Value *V = Builder.CreateNAryOp(Opcode, Ops);
2251
2252 if (auto *VecOp = dyn_cast<Instruction>(V)) {
2253 applyFlags(*VecOp);
2254 applyMetadata(*VecOp);
2255 }
2256
2257 // Use this vector value for all users of the original instruction.
2258 State.set(this, V);
2259 break;
2260 }
2261 case Instruction::ExtractValue: {
2262 assert(getNumOperands() == 2 && "expected single level extractvalue");
2263 Value *Op = State.get(getOperand(0));
2264 Value *Extract = Builder.CreateExtractValue(
2265 Op, cast<VPConstantInt>(getOperand(1))->getZExtValue());
2266 State.set(this, Extract);
2267 break;
2268 }
2269 case Instruction::Freeze: {
2270 Value *Op = State.get(getOperand(0));
2271 Value *Freeze = Builder.CreateFreeze(Op);
2272 State.set(this, Freeze);
2273 break;
2274 }
2275 case Instruction::ICmp:
2276 case Instruction::FCmp: {
2277 // Widen compares. Generate vector compares.
2278 bool FCmp = Opcode == Instruction::FCmp;
2279 Value *A = State.get(getOperand(0));
2280 Value *B = State.get(getOperand(1));
2281 Value *C = nullptr;
2282 if (FCmp) {
2283 C = Builder.CreateFCmp(getPredicate(), A, B);
2284 } else {
2285 C = Builder.CreateICmp(getPredicate(), A, B);
2286 }
2287 if (auto *I = dyn_cast<Instruction>(C)) {
2288 applyFlags(*I);
2289 applyMetadata(*I);
2290 }
2291 State.set(this, C);
2292 break;
2293 }
2294 case Instruction::Select: {
2295 VPValue *CondOp = getOperand(0);
2296 Value *Cond = State.get(CondOp, vputils::isSingleScalar(CondOp));
2297 Value *Op0 = State.get(getOperand(1));
2298 Value *Op1 = State.get(getOperand(2));
2299 Value *Sel = State.Builder.CreateSelect(Cond, Op0, Op1);
2300 State.set(this, Sel);
2301 if (auto *I = dyn_cast<Instruction>(Sel)) {
2303 applyFlags(*I);
2304 applyMetadata(*I);
2305 }
2306 break;
2307 }
2308 default:
2309 // This instruction is not vectorized by simple widening.
2310 LLVM_DEBUG(dbgs() << "LV: Found an unhandled opcode : "
2311 << Instruction::getOpcodeName(Opcode));
2312 llvm_unreachable("Unhandled instruction!");
2313 } // end of switch.
2314
2315#if !defined(NDEBUG)
2316 // Verify that VPlan type inference results agree with the type of the
2317 // generated values.
2318 assert(VectorType::get(State.TypeAnalysis.inferScalarType(this), State.VF) ==
2319 State.get(this)->getType() &&
2320 "inferred type and type from generated instructions do not match");
2321#endif
2322}
2323
2325 VPCostContext &Ctx) const {
2326 switch (Opcode) {
2327 case Instruction::UDiv:
2328 case Instruction::SDiv:
2329 case Instruction::SRem:
2330 case Instruction::URem:
2331 // If the div/rem operation isn't safe to speculate and requires
2332 // predication, then the only way we can even create a vplan is to insert
2333 // a select on the second input operand to ensure we use the value of 1
2334 // for the inactive lanes. The select will be costed separately.
2335 case Instruction::FNeg:
2336 case Instruction::Add:
2337 case Instruction::FAdd:
2338 case Instruction::Sub:
2339 case Instruction::FSub:
2340 case Instruction::Mul:
2341 case Instruction::FMul:
2342 case Instruction::FDiv:
2343 case Instruction::FRem:
2344 case Instruction::Shl:
2345 case Instruction::LShr:
2346 case Instruction::AShr:
2347 case Instruction::And:
2348 case Instruction::Or:
2349 case Instruction::Xor:
2350 case Instruction::Freeze:
2351 case Instruction::ExtractValue:
2352 case Instruction::ICmp:
2353 case Instruction::FCmp:
2354 case Instruction::Select:
2355 return getCostForRecipeWithOpcode(getOpcode(), VF, Ctx);
2356 default:
2357 llvm_unreachable("Unsupported opcode for instruction");
2358 }
2359}
2360
2361#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2363 VPSlotTracker &SlotTracker) const {
2364 O << Indent << "WIDEN ";
2366 O << " = " << Instruction::getOpcodeName(Opcode);
2367 printFlags(O);
2369}
2370#endif
2371
2373 auto &Builder = State.Builder;
2374 /// Vectorize casts.
2375 assert(State.VF.isVector() && "Not vectorizing?");
2376 Type *DestTy = VectorType::get(getResultType(), State.VF);
2377 VPValue *Op = getOperand(0);
2378 Value *A = State.get(Op);
2379 Value *Cast = Builder.CreateCast(Instruction::CastOps(Opcode), A, DestTy);
2380 State.set(this, Cast);
2381 if (auto *CastOp = dyn_cast<Instruction>(Cast)) {
2382 applyFlags(*CastOp);
2383 applyMetadata(*CastOp);
2384 }
2385}
2386
2388 VPCostContext &Ctx) const {
2389 // TODO: In some cases, VPWidenCastRecipes are created but not considered in
2390 // the legacy cost model, including truncates/extends when evaluating a
2391 // reduction in a smaller type.
2392 if (!getUnderlyingValue())
2393 return 0;
2394 return getCostForRecipeWithOpcode(getOpcode(), VF, Ctx);
2395}
2396
2397#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2399 VPSlotTracker &SlotTracker) const {
2400 O << Indent << "WIDEN-CAST ";
2402 O << " = " << Instruction::getOpcodeName(Opcode);
2403 printFlags(O);
2405 O << " to " << *getResultType();
2406}
2407#endif
2408
2410 VPCostContext &Ctx) const {
2411 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
2412}
2413
2414#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2416 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
2417 O << Indent;
2419 O << " = WIDEN-INDUCTION";
2420 printFlags(O);
2422
2423 if (auto *TI = getTruncInst())
2424 O << " (truncated to " << *TI->getType() << ")";
2425}
2426#endif
2427
2429 // The step may be defined by a recipe in the preheader (e.g. if it requires
2430 // SCEV expansion), but for the canonical induction the step is required to be
2431 // 1, which is represented as live-in.
2432 auto *StepC = dyn_cast<VPConstantInt>(getStepValue());
2433 auto *StartC = dyn_cast<VPConstantInt>(getStartValue());
2434 return StartC && StartC->isZero() && StepC && StepC->isOne() &&
2435 getScalarType() == getRegion()->getCanonicalIVType();
2436}
2437
2438#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2440 VPSlotTracker &SlotTracker) const {
2441 O << Indent;
2443 O << " = DERIVED-IV ";
2444 getStartValue()->printAsOperand(O, SlotTracker);
2445 O << " + ";
2446 getOperand(1)->printAsOperand(O, SlotTracker);
2447 O << " * ";
2448 getStepValue()->printAsOperand(O, SlotTracker);
2449}
2450#endif
2451
2453 // Fast-math-flags propagate from the original induction instruction.
2454 IRBuilder<>::FastMathFlagGuard FMFG(State.Builder);
2455 if (hasFastMathFlags())
2456 State.Builder.setFastMathFlags(getFastMathFlags());
2457
2458 /// Compute scalar induction steps. \p ScalarIV is the scalar induction
2459 /// variable on which to base the steps, \p Step is the size of the step.
2460
2461 Value *BaseIV = State.get(getOperand(0), VPLane(0));
2462 Value *Step = State.get(getStepValue(), VPLane(0));
2463 IRBuilderBase &Builder = State.Builder;
2464
2465 // Ensure step has the same type as that of scalar IV.
2466 Type *BaseIVTy = BaseIV->getType()->getScalarType();
2467 assert(BaseIVTy == Step->getType() && "Types of BaseIV and Step must match!");
2468
2469 // We build scalar steps for both integer and floating-point induction
2470 // variables. Here, we determine the kind of arithmetic we will perform.
2473 if (BaseIVTy->isIntegerTy()) {
2474 AddOp = Instruction::Add;
2475 MulOp = Instruction::Mul;
2476 } else {
2477 AddOp = InductionOpcode;
2478 MulOp = Instruction::FMul;
2479 }
2480
2481 // Determine the number of scalars we need to generate for each unroll
2482 // iteration.
2483 bool FirstLaneOnly = vputils::onlyFirstLaneUsed(this);
2484 // Compute the scalar steps and save the results in State.
2485 Type *IntStepTy =
2486 IntegerType::get(BaseIVTy->getContext(), BaseIVTy->getScalarSizeInBits());
2487
2488 unsigned StartLane = 0;
2489 unsigned EndLane = FirstLaneOnly ? 1 : State.VF.getKnownMinValue();
2490 if (State.Lane) {
2491 StartLane = State.Lane->getKnownLane();
2492 EndLane = StartLane + 1;
2493 }
2494 Value *StartIdx0;
2495 if (getUnrollPart(*this) == 0)
2496 StartIdx0 = ConstantInt::get(IntStepTy, 0);
2497 else {
2498 StartIdx0 = State.get(getOperand(2), true);
2499 if (getUnrollPart(*this) != 1) {
2500 StartIdx0 =
2501 Builder.CreateMul(StartIdx0, ConstantInt::get(StartIdx0->getType(),
2502 getUnrollPart(*this)));
2503 }
2504 StartIdx0 = Builder.CreateSExtOrTrunc(StartIdx0, IntStepTy);
2505 }
2506
2507 if (BaseIVTy->isFloatingPointTy())
2508 StartIdx0 = Builder.CreateSIToFP(StartIdx0, BaseIVTy);
2509
2510 for (unsigned Lane = StartLane; Lane < EndLane; ++Lane) {
2511 // It is okay if the induction variable type cannot hold the lane number,
2512 // we expect truncation in this case.
2513 Constant *LaneValue =
2514 BaseIVTy->isIntegerTy()
2515 ? ConstantInt::get(BaseIVTy, Lane, /*IsSigned=*/false,
2516 /*ImplicitTrunc=*/true)
2517 : ConstantFP::get(BaseIVTy, Lane);
2518 Value *StartIdx = Builder.CreateBinOp(AddOp, StartIdx0, LaneValue);
2519 // The step returned by `createStepForVF` is a runtime-evaluated value
2520 // when VF is scalable. Otherwise, it should be folded into a Constant.
2521 assert((State.VF.isScalable() || isa<Constant>(StartIdx)) &&
2522 "Expected StartIdx to be folded to a constant when VF is not "
2523 "scalable");
2524 auto *Mul = Builder.CreateBinOp(MulOp, StartIdx, Step);
2525 auto *Add = Builder.CreateBinOp(AddOp, BaseIV, Mul);
2526 State.set(this, Add, VPLane(Lane));
2527 }
2528}
2529
2530#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2532 VPSlotTracker &SlotTracker) const {
2533 O << Indent;
2535 O << " = SCALAR-STEPS ";
2537}
2538#endif
2539
2541 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
2543}
2544
2546 assert(State.VF.isVector() && "not widening");
2547 // Construct a vector GEP by widening the operands of the scalar GEP as
2548 // necessary. We mark the vector GEP 'inbounds' if appropriate. A GEP
2549 // results in a vector of pointers when at least one operand of the GEP
2550 // is vector-typed. Thus, to keep the representation compact, we only use
2551 // vector-typed operands for loop-varying values.
2552
2553 bool AllOperandsAreInvariant = all_of(operands(), [](VPValue *Op) {
2554 return Op->isDefinedOutsideLoopRegions();
2555 });
2556 if (AllOperandsAreInvariant) {
2557 // If we are vectorizing, but the GEP has only loop-invariant operands,
2558 // the GEP we build (by only using vector-typed operands for
2559 // loop-varying values) would be a scalar pointer. Thus, to ensure we
2560 // produce a vector of pointers, we need to either arbitrarily pick an
2561 // operand to broadcast, or broadcast a clone of the original GEP.
2562 // Here, we broadcast a clone of the original.
2563
2565 for (unsigned I = 0, E = getNumOperands(); I != E; I++)
2566 Ops.push_back(State.get(getOperand(I), VPLane(0)));
2567
2568 auto *NewGEP =
2569 State.Builder.CreateGEP(getSourceElementType(), Ops[0], drop_begin(Ops),
2570 "", getGEPNoWrapFlags());
2571 Value *Splat = State.Builder.CreateVectorSplat(State.VF, NewGEP);
2572 State.set(this, Splat);
2573 return;
2574 }
2575
2576 // If the GEP has at least one loop-varying operand, we are sure to
2577 // produce a vector of pointers unless VF is scalar.
2578 // The pointer operand of the new GEP. If it's loop-invariant, we
2579 // won't broadcast it.
2580 auto *Ptr = State.get(getOperand(0), isPointerLoopInvariant());
2581
2582 // Collect all the indices for the new GEP. If any index is
2583 // loop-invariant, we won't broadcast it.
2585 for (unsigned I = 1, E = getNumOperands(); I < E; I++) {
2586 VPValue *Operand = getOperand(I);
2587 Indices.push_back(State.get(Operand, isIndexLoopInvariant(I - 1)));
2588 }
2589
2590 // Create the new GEP. Note that this GEP may be a scalar if VF == 1,
2591 // but it should be a vector, otherwise.
2592 auto *NewGEP = State.Builder.CreateGEP(getSourceElementType(), Ptr, Indices,
2593 "", getGEPNoWrapFlags());
2594 assert((State.VF.isScalar() || NewGEP->getType()->isVectorTy()) &&
2595 "NewGEP is not a pointer vector");
2596 State.set(this, NewGEP);
2597}
2598
2599#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2601 VPSlotTracker &SlotTracker) const {
2602 O << Indent << "WIDEN-GEP ";
2603 O << (isPointerLoopInvariant() ? "Inv" : "Var");
2604 for (size_t I = 0; I < getNumOperands() - 1; ++I)
2605 O << "[" << (isIndexLoopInvariant(I) ? "Inv" : "Var") << "]";
2606
2607 O << " ";
2609 O << " = getelementptr";
2610 printFlags(O);
2612}
2613#endif
2614
2616 auto &Builder = State.Builder;
2617 unsigned CurrentPart = getUnrollPart(*this);
2618 const DataLayout &DL = Builder.GetInsertBlock()->getDataLayout();
2619 Type *IndexTy = DL.getIndexType(State.TypeAnalysis.inferScalarType(this));
2620
2621 // The wide store needs to start at the last vector element.
2622 Value *RunTimeVF = State.get(getVFValue(), VPLane(0));
2623 if (IndexTy != RunTimeVF->getType())
2624 RunTimeVF = Builder.CreateZExtOrTrunc(RunTimeVF, IndexTy);
2625 // NumElt = Stride * CurrentPart * RunTimeVF
2626 Value *NumElt = Builder.CreateMul(
2627 ConstantInt::getSigned(IndexTy, Stride * (int64_t)CurrentPart),
2628 RunTimeVF);
2629 // LastLane = Stride * (RunTimeVF - 1)
2630 Value *LastLane = Builder.CreateSub(RunTimeVF, ConstantInt::get(IndexTy, 1));
2631 if (Stride != 1)
2632 LastLane =
2633 Builder.CreateMul(ConstantInt::getSigned(IndexTy, Stride), LastLane);
2634 Value *Ptr = State.get(getOperand(0), VPLane(0));
2635 Value *ResultPtr =
2636 Builder.CreateGEP(IndexedTy, Ptr, NumElt, "", getGEPNoWrapFlags());
2637 ResultPtr = Builder.CreateGEP(IndexedTy, ResultPtr, LastLane, "",
2639
2640 State.set(this, ResultPtr, /*IsScalar*/ true);
2641}
2642
2643#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2645 VPSlotTracker &SlotTracker) const {
2646 O << Indent;
2648 O << " = vector-end-pointer";
2649 printFlags(O);
2651}
2652#endif
2653
2655 auto &Builder = State.Builder;
2656 assert(getOffset() &&
2657 "Expected prior simplification of recipe without offset");
2658 Value *Ptr = State.get(getOperand(0), VPLane(0));
2659 Value *Offset = State.get(getOffset(), true);
2660 Value *ResultPtr = Builder.CreateGEP(getSourceElementType(), Ptr, Offset, "",
2662 State.set(this, ResultPtr, /*IsScalar*/ true);
2663}
2664
2665#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2667 VPSlotTracker &SlotTracker) const {
2668 O << Indent;
2670 O << " = vector-pointer";
2671 printFlags(O);
2673}
2674#endif
2675
2677 VPCostContext &Ctx) const {
2678 // A blend will be expanded to a select VPInstruction, which will generate a
2679 // scalar select if only the first lane is used.
2681 VF = ElementCount::getFixed(1);
2682
2683 Type *ResultTy = toVectorTy(Ctx.Types.inferScalarType(this), VF);
2684 Type *CmpTy = toVectorTy(Type::getInt1Ty(Ctx.Types.getContext()), VF);
2685 return (getNumIncomingValues() - 1) *
2686 Ctx.TTI.getCmpSelInstrCost(Instruction::Select, ResultTy, CmpTy,
2687 CmpInst::BAD_ICMP_PREDICATE, Ctx.CostKind);
2688}
2689
2690#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2692 VPSlotTracker &SlotTracker) const {
2693 O << Indent << "BLEND ";
2695 O << " =";
2696 if (getNumIncomingValues() == 1) {
2697 // Not a User of any mask: not really blending, this is a
2698 // single-predecessor phi.
2699 O << " ";
2700 getIncomingValue(0)->printAsOperand(O, SlotTracker);
2701 } else {
2702 for (unsigned I = 0, E = getNumIncomingValues(); I < E; ++I) {
2703 O << " ";
2704 getIncomingValue(I)->printAsOperand(O, SlotTracker);
2705 if (I == 0)
2706 continue;
2707 O << "/";
2708 getMask(I)->printAsOperand(O, SlotTracker);
2709 }
2710 }
2711}
2712#endif
2713
2715 assert(!State.Lane && "Reduction being replicated.");
2718 "In-loop AnyOf reductions aren't currently supported");
2719 // Propagate the fast-math flags carried by the underlying instruction.
2720 IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder);
2721 State.Builder.setFastMathFlags(getFastMathFlags());
2722 Value *NewVecOp = State.get(getVecOp());
2723 if (VPValue *Cond = getCondOp()) {
2724 Value *NewCond = State.get(Cond, State.VF.isScalar());
2725 VectorType *VecTy = dyn_cast<VectorType>(NewVecOp->getType());
2726 Type *ElementTy = VecTy ? VecTy->getElementType() : NewVecOp->getType();
2727
2728 Value *Start = getRecurrenceIdentity(Kind, ElementTy, getFastMathFlags());
2729 if (State.VF.isVector())
2730 Start = State.Builder.CreateVectorSplat(VecTy->getElementCount(), Start);
2731
2732 Value *Select = State.Builder.CreateSelect(NewCond, NewVecOp, Start);
2733 NewVecOp = Select;
2734 }
2735 Value *NewRed;
2736 Value *NextInChain;
2737 if (isOrdered()) {
2738 Value *PrevInChain = State.get(getChainOp(), /*IsScalar*/ true);
2739 if (State.VF.isVector())
2740 NewRed =
2741 createOrderedReduction(State.Builder, Kind, NewVecOp, PrevInChain);
2742 else
2743 NewRed = State.Builder.CreateBinOp(
2745 PrevInChain, NewVecOp);
2746 PrevInChain = NewRed;
2747 NextInChain = NewRed;
2748 } else if (isPartialReduction()) {
2749 assert(Kind == RecurKind::Add && "Unexpected partial reduction kind");
2750 Value *PrevInChain = State.get(getChainOp(), /*IsScalar*/ false);
2751 NewRed = State.Builder.CreateIntrinsic(
2752 PrevInChain->getType(), Intrinsic::vector_partial_reduce_add,
2753 {PrevInChain, NewVecOp}, nullptr, "partial.reduce");
2754 PrevInChain = NewRed;
2755 NextInChain = NewRed;
2756 } else {
2757 assert(isInLoop() &&
2758 "The reduction must either be ordered, partial or in-loop");
2759 Value *PrevInChain = State.get(getChainOp(), /*IsScalar*/ true);
2760 NewRed = createSimpleReduction(State.Builder, NewVecOp, Kind);
2762 NextInChain = createMinMaxOp(State.Builder, Kind, NewRed, PrevInChain);
2763 else
2764 NextInChain = State.Builder.CreateBinOp(
2766 PrevInChain, NewRed);
2767 }
2768 State.set(this, NextInChain, /*IsScalar*/ !isPartialReduction());
2769}
2770
2772 assert(!State.Lane && "Reduction being replicated.");
2773
2774 auto &Builder = State.Builder;
2775 // Propagate the fast-math flags carried by the underlying instruction.
2776 IRBuilderBase::FastMathFlagGuard FMFGuard(Builder);
2777 Builder.setFastMathFlags(getFastMathFlags());
2778
2780 Value *Prev = State.get(getChainOp(), /*IsScalar*/ true);
2781 Value *VecOp = State.get(getVecOp());
2782 Value *EVL = State.get(getEVL(), VPLane(0));
2783
2784 Value *Mask;
2785 if (VPValue *CondOp = getCondOp())
2786 Mask = State.get(CondOp);
2787 else
2788 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
2789
2790 Value *NewRed;
2791 if (isOrdered()) {
2792 NewRed = createOrderedReduction(Builder, Kind, VecOp, Prev, Mask, EVL);
2793 } else {
2794 NewRed = createSimpleReduction(Builder, VecOp, Kind, Mask, EVL);
2796 NewRed = createMinMaxOp(Builder, Kind, NewRed, Prev);
2797 else
2798 NewRed = Builder.CreateBinOp(
2800 Prev);
2801 }
2802 State.set(this, NewRed, /*IsScalar*/ true);
2803}
2804
2806 VPCostContext &Ctx) const {
2807 RecurKind RdxKind = getRecurrenceKind();
2808 Type *ElementTy = Ctx.Types.inferScalarType(this);
2809 auto *VectorTy = cast<VectorType>(toVectorTy(ElementTy, VF));
2810 unsigned Opcode = RecurrenceDescriptor::getOpcode(RdxKind);
2812 std::optional<FastMathFlags> OptionalFMF =
2813 ElementTy->isFloatingPointTy() ? std::make_optional(FMFs) : std::nullopt;
2814
2815 if (isPartialReduction()) {
2816 InstructionCost CondCost = 0;
2817 if (isConditional()) {
2819 auto *CondTy = cast<VectorType>(
2820 toVectorTy(Ctx.Types.inferScalarType(getCondOp()), VF));
2821 CondCost = Ctx.TTI.getCmpSelInstrCost(Instruction::Select, VectorTy,
2822 CondTy, Pred, Ctx.CostKind);
2823 }
2824 return CondCost + Ctx.TTI.getPartialReductionCost(
2825 Opcode, ElementTy, ElementTy, ElementTy, VF,
2827 TargetTransformInfo::PR_None, std::nullopt,
2828 Ctx.CostKind);
2829 }
2830
2831 // TODO: Support any-of reductions.
2832 assert(
2834 ForceTargetInstructionCost.getNumOccurrences() > 0) &&
2835 "Any-of reduction not implemented in VPlan-based cost model currently.");
2836
2837 // Note that TTI should model the cost of moving result to the scalar register
2838 // and the BinOp cost in the getMinMaxReductionCost().
2841 return Ctx.TTI.getMinMaxReductionCost(Id, VectorTy, FMFs, Ctx.CostKind);
2842 }
2843
2844 // Note that TTI should model the cost of moving result to the scalar register
2845 // and the BinOp cost in the getArithmeticReductionCost().
2846 return Ctx.TTI.getArithmeticReductionCost(Opcode, VectorTy, OptionalFMF,
2847 Ctx.CostKind);
2848}
2849
2850VPExpressionRecipe::VPExpressionRecipe(
2851 ExpressionTypes ExpressionType,
2852 ArrayRef<VPSingleDefRecipe *> ExpressionRecipes)
2853 : VPSingleDefRecipe(VPDef::VPExpressionSC, {}, {}),
2854 ExpressionRecipes(ExpressionRecipes), ExpressionType(ExpressionType) {
2855 assert(!ExpressionRecipes.empty() && "Nothing to combine?");
2856 assert(
2857 none_of(ExpressionRecipes,
2858 [](VPSingleDefRecipe *R) { return R->mayHaveSideEffects(); }) &&
2859 "expression cannot contain recipes with side-effects");
2860
2861 // Maintain a copy of the expression recipes as a set of users.
2862 SmallPtrSet<VPUser *, 4> ExpressionRecipesAsSetOfUsers;
2863 for (auto *R : ExpressionRecipes)
2864 ExpressionRecipesAsSetOfUsers.insert(R);
2865
2866 // Recipes in the expression, except the last one, must only be used by
2867 // (other) recipes inside the expression. If there are other users, external
2868 // to the expression, use a clone of the recipe for external users.
2869 for (VPSingleDefRecipe *R : reverse(ExpressionRecipes)) {
2870 if (R != ExpressionRecipes.back() &&
2871 any_of(R->users(), [&ExpressionRecipesAsSetOfUsers](VPUser *U) {
2872 return !ExpressionRecipesAsSetOfUsers.contains(U);
2873 })) {
2874 // There are users outside of the expression. Clone the recipe and use the
2875 // clone those external users.
2876 VPSingleDefRecipe *CopyForExtUsers = R->clone();
2877 R->replaceUsesWithIf(CopyForExtUsers, [&ExpressionRecipesAsSetOfUsers](
2878 VPUser &U, unsigned) {
2879 return !ExpressionRecipesAsSetOfUsers.contains(&U);
2880 });
2881 CopyForExtUsers->insertBefore(R);
2882 }
2883 if (R->getParent())
2884 R->removeFromParent();
2885 }
2886
2887 // Internalize all external operands to the expression recipes. To do so,
2888 // create new temporary VPValues for all operands defined by a recipe outside
2889 // the expression. The original operands are added as operands of the
2890 // VPExpressionRecipe itself.
2891 for (auto *R : ExpressionRecipes) {
2892 for (const auto &[Idx, Op] : enumerate(R->operands())) {
2893 auto *Def = Op->getDefiningRecipe();
2894 if (Def && ExpressionRecipesAsSetOfUsers.contains(Def))
2895 continue;
2896 addOperand(Op);
2897 LiveInPlaceholders.push_back(new VPSymbolicValue());
2898 }
2899 }
2900
2901 // Replace each external operand with the first one created for it in
2902 // LiveInPlaceholders.
2903 for (auto *R : ExpressionRecipes)
2904 for (auto const &[LiveIn, Tmp] : zip(operands(), LiveInPlaceholders))
2905 R->replaceUsesOfWith(LiveIn, Tmp);
2906}
2907
2909 for (auto *R : ExpressionRecipes)
2910 // Since the list could contain duplicates, make sure the recipe hasn't
2911 // already been inserted.
2912 if (!R->getParent())
2913 R->insertBefore(this);
2914
2915 for (const auto &[Idx, Op] : enumerate(operands()))
2916 LiveInPlaceholders[Idx]->replaceAllUsesWith(Op);
2917
2918 replaceAllUsesWith(ExpressionRecipes.back());
2919 ExpressionRecipes.clear();
2920}
2921
2923 VPCostContext &Ctx) const {
2924 Type *RedTy = Ctx.Types.inferScalarType(this);
2925 auto *SrcVecTy = cast<VectorType>(
2926 toVectorTy(Ctx.Types.inferScalarType(getOperand(0)), VF));
2927 assert(RedTy->isIntegerTy() &&
2928 "VPExpressionRecipe only supports integer types currently.");
2929 unsigned Opcode = RecurrenceDescriptor::getOpcode(
2930 cast<VPReductionRecipe>(ExpressionRecipes.back())->getRecurrenceKind());
2931 switch (ExpressionType) {
2932 case ExpressionTypes::ExtendedReduction: {
2933 unsigned Opcode = RecurrenceDescriptor::getOpcode(
2934 cast<VPReductionRecipe>(ExpressionRecipes[1])->getRecurrenceKind());
2935 auto *ExtR = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
2936
2937 return cast<VPReductionRecipe>(ExpressionRecipes.back())
2938 ->isPartialReduction()
2939 ? Ctx.TTI.getPartialReductionCost(
2940 Opcode, Ctx.Types.inferScalarType(getOperand(0)), nullptr,
2941 RedTy, VF,
2943 ExtR->getOpcode()),
2944 TargetTransformInfo::PR_None, std::nullopt, Ctx.CostKind)
2945 : Ctx.TTI.getExtendedReductionCost(
2946 Opcode, ExtR->getOpcode() == Instruction::ZExt, RedTy,
2947 SrcVecTy, std::nullopt, Ctx.CostKind);
2948 }
2949 case ExpressionTypes::MulAccReduction:
2950 return Ctx.TTI.getMulAccReductionCost(false, Opcode, RedTy, SrcVecTy,
2951 Ctx.CostKind);
2952
2953 case ExpressionTypes::ExtNegatedMulAccReduction:
2954 assert(Opcode == Instruction::Add && "Unexpected opcode");
2955 Opcode = Instruction::Sub;
2956 [[fallthrough]];
2957 case ExpressionTypes::ExtMulAccReduction: {
2958 auto *RedR = cast<VPReductionRecipe>(ExpressionRecipes.back());
2959 if (RedR->isPartialReduction()) {
2960 auto *Ext0R = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
2961 auto *Ext1R = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
2962 auto *Mul = cast<VPWidenRecipe>(ExpressionRecipes[2]);
2963 return Ctx.TTI.getPartialReductionCost(
2964 Opcode, Ctx.Types.inferScalarType(getOperand(0)),
2965 Ctx.Types.inferScalarType(getOperand(1)), RedTy, VF,
2967 Ext0R->getOpcode()),
2969 Ext1R->getOpcode()),
2970 Mul->getOpcode(), Ctx.CostKind);
2971 }
2972 return Ctx.TTI.getMulAccReductionCost(
2973 cast<VPWidenCastRecipe>(ExpressionRecipes.front())->getOpcode() ==
2974 Instruction::ZExt,
2975 Opcode, RedTy, SrcVecTy, Ctx.CostKind);
2976 }
2977 }
2978 llvm_unreachable("Unknown VPExpressionRecipe::ExpressionTypes enum");
2979}
2980
2982 return any_of(ExpressionRecipes, [](VPSingleDefRecipe *R) {
2983 return R->mayReadFromMemory() || R->mayWriteToMemory();
2984 });
2985}
2986
2988 assert(
2989 none_of(ExpressionRecipes,
2990 [](VPSingleDefRecipe *R) { return R->mayHaveSideEffects(); }) &&
2991 "expression cannot contain recipes with side-effects");
2992 return false;
2993}
2994
2996 // Cannot use vputils::isSingleScalar(), because all external operands
2997 // of the expression will be live-ins while bundled.
2998 auto *RR = dyn_cast<VPReductionRecipe>(ExpressionRecipes.back());
2999 return RR && !RR->isPartialReduction();
3000}
3001
3002#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3003
3005 VPSlotTracker &SlotTracker) const {
3006 O << Indent << "EXPRESSION ";
3008 O << " = ";
3009 auto *Red = cast<VPReductionRecipe>(ExpressionRecipes.back());
3010 unsigned Opcode = RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind());
3011
3012 switch (ExpressionType) {
3013 case ExpressionTypes::ExtendedReduction: {
3015 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
3016 O << Instruction::getOpcodeName(Opcode) << " (";
3018 Red->printFlags(O);
3019
3020 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3021 O << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
3022 << *Ext0->getResultType();
3023 if (Red->isConditional()) {
3024 O << ", ";
3025 Red->getCondOp()->printAsOperand(O, SlotTracker);
3026 }
3027 O << ")";
3028 break;
3029 }
3030 case ExpressionTypes::ExtNegatedMulAccReduction: {
3032 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
3034 RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind()))
3035 << " (sub (0, mul";
3036 auto *Mul = cast<VPWidenRecipe>(ExpressionRecipes[2]);
3037 Mul->printFlags(O);
3038 O << "(";
3040 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3041 O << " " << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
3042 << *Ext0->getResultType() << "), (";
3044 auto *Ext1 = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
3045 O << " " << Instruction::getOpcodeName(Ext1->getOpcode()) << " to "
3046 << *Ext1->getResultType() << ")";
3047 if (Red->isConditional()) {
3048 O << ", ";
3049 Red->getCondOp()->printAsOperand(O, SlotTracker);
3050 }
3051 O << "))";
3052 break;
3053 }
3054 case ExpressionTypes::MulAccReduction:
3055 case ExpressionTypes::ExtMulAccReduction: {
3057 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
3059 RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind()))
3060 << " (";
3061 O << "mul";
3062 bool IsExtended = ExpressionType == ExpressionTypes::ExtMulAccReduction;
3063 auto *Mul = cast<VPWidenRecipe>(IsExtended ? ExpressionRecipes[2]
3064 : ExpressionRecipes[0]);
3065 Mul->printFlags(O);
3066 if (IsExtended)
3067 O << "(";
3069 if (IsExtended) {
3070 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3071 O << " " << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
3072 << *Ext0->getResultType() << "), (";
3073 } else {
3074 O << ", ";
3075 }
3077 if (IsExtended) {
3078 auto *Ext1 = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
3079 O << " " << Instruction::getOpcodeName(Ext1->getOpcode()) << " to "
3080 << *Ext1->getResultType() << ")";
3081 }
3082 if (Red->isConditional()) {
3083 O << ", ";
3084 Red->getCondOp()->printAsOperand(O, SlotTracker);
3085 }
3086 O << ")";
3087 break;
3088 }
3089 }
3090}
3091
3093 VPSlotTracker &SlotTracker) const {
3094 if (isPartialReduction())
3095 O << Indent << "PARTIAL-REDUCE ";
3096 else
3097 O << Indent << "REDUCE ";
3099 O << " = ";
3101 O << " +";
3102 printFlags(O);
3103 O << " reduce."
3106 << " (";
3108 if (isConditional()) {
3109 O << ", ";
3111 }
3112 O << ")";
3113}
3114
3116 VPSlotTracker &SlotTracker) const {
3117 O << Indent << "REDUCE ";
3119 O << " = ";
3121 O << " +";
3122 printFlags(O);
3123 O << " vp.reduce."
3126 << " (";
3128 O << ", ";
3130 if (isConditional()) {
3131 O << ", ";
3133 }
3134 O << ")";
3135}
3136
3137#endif
3138
3139/// A helper function to scalarize a single Instruction in the innermost loop.
3140/// Generates a sequence of scalar instances for lane \p Lane. Uses the VPValue
3141/// operands from \p RepRecipe instead of \p Instr's operands.
3142static void scalarizeInstruction(const Instruction *Instr,
3143 VPReplicateRecipe *RepRecipe,
3144 const VPLane &Lane, VPTransformState &State) {
3145 assert((!Instr->getType()->isAggregateType() ||
3146 canVectorizeTy(Instr->getType())) &&
3147 "Expected vectorizable or non-aggregate type.");
3148
3149 // Does this instruction return a value ?
3150 bool IsVoidRetTy = Instr->getType()->isVoidTy();
3151
3152 Instruction *Cloned = Instr->clone();
3153 if (!IsVoidRetTy) {
3154 Cloned->setName(Instr->getName() + ".cloned");
3155 Type *ResultTy = State.TypeAnalysis.inferScalarType(RepRecipe);
3156 // The operands of the replicate recipe may have been narrowed, resulting in
3157 // a narrower result type. Update the type of the cloned instruction to the
3158 // correct type.
3159 if (ResultTy != Cloned->getType())
3160 Cloned->mutateType(ResultTy);
3161 }
3162
3163 RepRecipe->applyFlags(*Cloned);
3164 RepRecipe->applyMetadata(*Cloned);
3165
3166 if (RepRecipe->hasPredicate())
3167 cast<CmpInst>(Cloned)->setPredicate(RepRecipe->getPredicate());
3168
3169 if (auto DL = RepRecipe->getDebugLoc())
3170 State.setDebugLocFrom(DL);
3171
3172 // Replace the operands of the cloned instructions with their scalar
3173 // equivalents in the new loop.
3174 for (const auto &I : enumerate(RepRecipe->operands())) {
3175 auto InputLane = Lane;
3176 VPValue *Operand = I.value();
3177 if (vputils::isSingleScalar(Operand))
3178 InputLane = VPLane::getFirstLane();
3179 Cloned->setOperand(I.index(), State.get(Operand, InputLane));
3180 }
3181
3182 // Place the cloned scalar in the new loop.
3183 State.Builder.Insert(Cloned);
3184
3185 State.set(RepRecipe, Cloned, Lane);
3186
3187 // If we just cloned a new assumption, add it the assumption cache.
3188 if (auto *II = dyn_cast<AssumeInst>(Cloned))
3189 State.AC->registerAssumption(II);
3190
3191 assert(
3192 (RepRecipe->getRegion() ||
3193 !RepRecipe->getParent()->getPlan()->getVectorLoopRegion() ||
3194 all_of(RepRecipe->operands(),
3195 [](VPValue *Op) { return Op->isDefinedOutsideLoopRegions(); })) &&
3196 "Expected a recipe is either within a region or all of its operands "
3197 "are defined outside the vectorized region.");
3198}
3199
3202
3203 if (!State.Lane) {
3204 assert(IsSingleScalar && "VPReplicateRecipes outside replicate regions "
3205 "must have already been unrolled");
3206 scalarizeInstruction(UI, this, VPLane(0), State);
3207 return;
3208 }
3209
3210 assert((State.VF.isScalar() || !isSingleScalar()) &&
3211 "uniform recipe shouldn't be predicated");
3212 assert(!State.VF.isScalable() && "Can't scalarize a scalable vector");
3213 scalarizeInstruction(UI, this, *State.Lane, State);
3214 // Insert scalar instance packing it into a vector.
3215 if (State.VF.isVector() && shouldPack()) {
3216 Value *WideValue =
3217 State.Lane->isFirstLane()
3218 ? PoisonValue::get(toVectorizedTy(UI->getType(), State.VF))
3219 : State.get(this);
3220 State.set(this, State.packScalarIntoVectorizedValue(this, WideValue,
3221 *State.Lane));
3222 }
3223}
3224
3226 // Find if the recipe is used by a widened recipe via an intervening
3227 // VPPredInstPHIRecipe. In this case, also pack the scalar values in a vector.
3228 return any_of(users(), [](const VPUser *U) {
3229 if (auto *PredR = dyn_cast<VPPredInstPHIRecipe>(U))
3230 return !vputils::onlyScalarValuesUsed(PredR);
3231 return false;
3232 });
3233}
3234
3235/// Returns a SCEV expression for \p Ptr if it is a pointer computation for
3236/// which the legacy cost model computes a SCEV expression when computing the
3237/// address cost. Computing SCEVs for VPValues is incomplete and returns
3238/// SCEVCouldNotCompute in cases the legacy cost model can compute SCEVs. In
3239/// those cases we fall back to the legacy cost model. Otherwise return nullptr.
3240static const SCEV *getAddressAccessSCEV(const VPValue *Ptr,
3242 const Loop *L) {
3243 const SCEV *Addr = vputils::getSCEVExprForVPValue(Ptr, PSE, L);
3244 if (isa<SCEVCouldNotCompute>(Addr))
3245 return Addr;
3246
3247 return vputils::isAddressSCEVForCost(Addr, *PSE.getSE(), L) ? Addr : nullptr;
3248}
3249
3250/// Returns true if \p V is used as part of the address of another load or
3251/// store.
3252static bool isUsedByLoadStoreAddress(const VPUser *V) {
3254 SmallVector<const VPUser *> WorkList = {V};
3255
3256 while (!WorkList.empty()) {
3257 auto *Cur = dyn_cast<VPSingleDefRecipe>(WorkList.pop_back_val());
3258 if (!Cur || !Seen.insert(Cur).second)
3259 continue;
3260
3261 auto *Blend = dyn_cast<VPBlendRecipe>(Cur);
3262 // Skip blends that use V only through a compare by checking if any incoming
3263 // value was already visited.
3264 if (Blend && none_of(seq<unsigned>(0, Blend->getNumIncomingValues()),
3265 [&](unsigned I) {
3266 return Seen.contains(
3267 Blend->getIncomingValue(I)->getDefiningRecipe());
3268 }))
3269 continue;
3270
3271 for (VPUser *U : Cur->users()) {
3272 if (auto *InterleaveR = dyn_cast<VPInterleaveBase>(U))
3273 if (InterleaveR->getAddr() == Cur)
3274 return true;
3275 if (auto *RepR = dyn_cast<VPReplicateRecipe>(U)) {
3276 if (RepR->getOpcode() == Instruction::Load &&
3277 RepR->getOperand(0) == Cur)
3278 return true;
3279 if (RepR->getOpcode() == Instruction::Store &&
3280 RepR->getOperand(1) == Cur)
3281 return true;
3282 }
3283 if (auto *MemR = dyn_cast<VPWidenMemoryRecipe>(U)) {
3284 if (MemR->getAddr() == Cur && MemR->isConsecutive())
3285 return true;
3286 }
3287 }
3288
3289 // The legacy cost model only supports scalarization loads/stores with phi
3290 // addresses, if the phi is directly used as load/store address. Don't
3291 // traverse further for Blends.
3292 if (Blend)
3293 continue;
3294
3295 append_range(WorkList, Cur->users());
3296 }
3297 return false;
3298}
3299
3301 VPCostContext &Ctx) const {
3303 // VPReplicateRecipe may be cloned as part of an existing VPlan-to-VPlan
3304 // transform, avoid computing their cost multiple times for now.
3305 Ctx.SkipCostComputation.insert(UI);
3306
3307 if (VF.isScalable() && !isSingleScalar())
3309
3310 switch (UI->getOpcode()) {
3311 case Instruction::Alloca:
3312 if (VF.isScalable())
3314 return Ctx.TTI.getArithmeticInstrCost(
3315 Instruction::Mul, Ctx.Types.inferScalarType(this), Ctx.CostKind);
3316 case Instruction::GetElementPtr:
3317 // We mark this instruction as zero-cost because the cost of GEPs in
3318 // vectorized code depends on whether the corresponding memory instruction
3319 // is scalarized or not. Therefore, we handle GEPs with the memory
3320 // instruction cost.
3321 return 0;
3322 case Instruction::Call: {
3323 auto *CalledFn =
3325
3328 for (const VPValue *ArgOp : ArgOps)
3329 Tys.push_back(Ctx.Types.inferScalarType(ArgOp));
3330
3331 if (CalledFn->isIntrinsic())
3332 // Various pseudo-intrinsics with costs of 0 are scalarized instead of
3333 // vectorized via VPWidenIntrinsicRecipe. Return 0 for them early.
3334 switch (CalledFn->getIntrinsicID()) {
3335 case Intrinsic::assume:
3336 case Intrinsic::lifetime_end:
3337 case Intrinsic::lifetime_start:
3338 case Intrinsic::sideeffect:
3339 case Intrinsic::pseudoprobe:
3340 case Intrinsic::experimental_noalias_scope_decl: {
3341 assert(getCostForIntrinsics(CalledFn->getIntrinsicID(), ArgOps, *this,
3342 ElementCount::getFixed(1), Ctx) == 0 &&
3343 "scalarizing intrinsic should be free");
3344 return InstructionCost(0);
3345 }
3346 default:
3347 break;
3348 }
3349
3350 Type *ResultTy = Ctx.Types.inferScalarType(this);
3351 InstructionCost ScalarCallCost =
3352 Ctx.TTI.getCallInstrCost(CalledFn, ResultTy, Tys, Ctx.CostKind);
3353 if (isSingleScalar()) {
3354 if (CalledFn->isIntrinsic())
3355 ScalarCallCost = std::min(
3356 ScalarCallCost,
3357 getCostForIntrinsics(CalledFn->getIntrinsicID(), ArgOps, *this,
3358 ElementCount::getFixed(1), Ctx));
3359 return ScalarCallCost;
3360 }
3361
3362 return ScalarCallCost * VF.getFixedValue() +
3363 Ctx.getScalarizationOverhead(ResultTy, ArgOps, VF);
3364 }
3365 case Instruction::Add:
3366 case Instruction::Sub:
3367 case Instruction::FAdd:
3368 case Instruction::FSub:
3369 case Instruction::Mul:
3370 case Instruction::FMul:
3371 case Instruction::FDiv:
3372 case Instruction::FRem:
3373 case Instruction::Shl:
3374 case Instruction::LShr:
3375 case Instruction::AShr:
3376 case Instruction::And:
3377 case Instruction::Or:
3378 case Instruction::Xor:
3379 case Instruction::ICmp:
3380 case Instruction::FCmp:
3382 Ctx) *
3383 (isSingleScalar() ? 1 : VF.getFixedValue());
3384 case Instruction::SDiv:
3385 case Instruction::UDiv:
3386 case Instruction::SRem:
3387 case Instruction::URem: {
3388 InstructionCost ScalarCost =
3390 if (isSingleScalar())
3391 return ScalarCost;
3392
3393 ScalarCost = ScalarCost * VF.getFixedValue() +
3394 Ctx.getScalarizationOverhead(Ctx.Types.inferScalarType(this),
3395 to_vector(operands()), VF);
3396 // If the recipe is not predicated (i.e. not in a replicate region), return
3397 // the scalar cost. Otherwise handle predicated cost.
3398 if (!getRegion()->isReplicator())
3399 return ScalarCost;
3400
3401 // Account for the phi nodes that we will create.
3402 ScalarCost += VF.getFixedValue() *
3403 Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
3404 // Scale the cost by the probability of executing the predicated blocks.
3405 // This assumes the predicated block for each vector lane is equally
3406 // likely.
3407 ScalarCost /= Ctx.getPredBlockCostDivisor(UI->getParent());
3408 return ScalarCost;
3409 }
3410 case Instruction::Load:
3411 case Instruction::Store: {
3412 // TODO: See getMemInstScalarizationCost for how to handle replicating and
3413 // predicated cases.
3414 const VPRegionBlock *ParentRegion = getRegion();
3415 if (ParentRegion && ParentRegion->isReplicator())
3416 break;
3417
3418 bool IsLoad = UI->getOpcode() == Instruction::Load;
3419 const VPValue *PtrOp = getOperand(!IsLoad);
3420 const SCEV *PtrSCEV = getAddressAccessSCEV(PtrOp, Ctx.PSE, Ctx.L);
3422 break;
3423
3424 Type *ValTy = Ctx.Types.inferScalarType(IsLoad ? this : getOperand(0));
3425 Type *ScalarPtrTy = Ctx.Types.inferScalarType(PtrOp);
3426 const Align Alignment = getLoadStoreAlignment(UI);
3427 unsigned AS = cast<PointerType>(ScalarPtrTy)->getAddressSpace();
3429 InstructionCost ScalarMemOpCost = Ctx.TTI.getMemoryOpCost(
3430 UI->getOpcode(), ValTy, Alignment, AS, Ctx.CostKind, OpInfo);
3431
3432 Type *PtrTy = isSingleScalar() ? ScalarPtrTy : toVectorTy(ScalarPtrTy, VF);
3433 bool PreferVectorizedAddressing = Ctx.TTI.prefersVectorizedAddressing();
3434 bool UsedByLoadStoreAddress =
3435 !PreferVectorizedAddressing && isUsedByLoadStoreAddress(this);
3436 InstructionCost ScalarCost =
3437 ScalarMemOpCost +
3438 Ctx.TTI.getAddressComputationCost(
3439 PtrTy, UsedByLoadStoreAddress ? nullptr : Ctx.PSE.getSE(), PtrSCEV,
3440 Ctx.CostKind);
3441 if (isSingleScalar())
3442 return ScalarCost;
3443
3444 SmallVector<const VPValue *> OpsToScalarize;
3445 Type *ResultTy = Type::getVoidTy(PtrTy->getContext());
3446 // Set ResultTy and OpsToScalarize, if scalarization is needed. Currently we
3447 // don't assign scalarization overhead in general, if the target prefers
3448 // vectorized addressing or the loaded value is used as part of an address
3449 // of another load or store.
3450 if (!UsedByLoadStoreAddress) {
3451 bool EfficientVectorLoadStore =
3452 Ctx.TTI.supportsEfficientVectorElementLoadStore();
3453 if (!(IsLoad && !PreferVectorizedAddressing) &&
3454 !(!IsLoad && EfficientVectorLoadStore))
3455 append_range(OpsToScalarize, operands());
3456
3457 if (!EfficientVectorLoadStore)
3458 ResultTy = Ctx.Types.inferScalarType(this);
3459 }
3460
3461 return (ScalarCost * VF.getFixedValue()) +
3462 Ctx.getScalarizationOverhead(ResultTy, OpsToScalarize, VF, true);
3463 }
3464 case Instruction::SExt:
3465 case Instruction::ZExt:
3466 case Instruction::FPToUI:
3467 case Instruction::FPToSI:
3468 case Instruction::FPExt:
3469 case Instruction::PtrToInt:
3470 case Instruction::PtrToAddr:
3471 case Instruction::IntToPtr:
3472 case Instruction::SIToFP:
3473 case Instruction::UIToFP:
3474 case Instruction::Trunc:
3475 case Instruction::FPTrunc:
3476 case Instruction::AddrSpaceCast: {
3478 Ctx) *
3479 (isSingleScalar() ? 1 : VF.getFixedValue());
3480 }
3481 case Instruction::ExtractValue:
3482 case Instruction::InsertValue:
3483 return Ctx.TTI.getInsertExtractValueCost(getOpcode(), Ctx.CostKind);
3484 }
3485
3486 return Ctx.getLegacyCost(UI, VF);
3487}
3488
3489#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3491 VPSlotTracker &SlotTracker) const {
3492 O << Indent << (IsSingleScalar ? "CLONE " : "REPLICATE ");
3493
3494 if (!getUnderlyingInstr()->getType()->isVoidTy()) {
3496 O << " = ";
3497 }
3498 if (auto *CB = dyn_cast<CallBase>(getUnderlyingInstr())) {
3499 O << "call";
3500 printFlags(O);
3501 O << "@" << CB->getCalledFunction()->getName() << "(";
3503 O, [&O, &SlotTracker](VPValue *Op) {
3504 Op->printAsOperand(O, SlotTracker);
3505 });
3506 O << ")";
3507 } else {
3509 printFlags(O);
3511 }
3512
3513 if (shouldPack())
3514 O << " (S->V)";
3515}
3516#endif
3517
3519 assert(State.Lane && "Branch on Mask works only on single instance.");
3520
3521 VPValue *BlockInMask = getOperand(0);
3522 Value *ConditionBit = State.get(BlockInMask, *State.Lane);
3523
3524 // Replace the temporary unreachable terminator with a new conditional branch,
3525 // whose two destinations will be set later when they are created.
3526 auto *CurrentTerminator = State.CFG.PrevBB->getTerminator();
3527 assert(isa<UnreachableInst>(CurrentTerminator) &&
3528 "Expected to replace unreachable terminator with conditional branch.");
3529 auto CondBr =
3530 State.Builder.CreateCondBr(ConditionBit, State.CFG.PrevBB, nullptr);
3531 CondBr->setSuccessor(0, nullptr);
3532 CurrentTerminator->eraseFromParent();
3533}
3534
3536 VPCostContext &Ctx) const {
3537 // The legacy cost model doesn't assign costs to branches for individual
3538 // replicate regions. Match the current behavior in the VPlan cost model for
3539 // now.
3540 return 0;
3541}
3542
3544 assert(State.Lane && "Predicated instruction PHI works per instance.");
3545 Instruction *ScalarPredInst =
3546 cast<Instruction>(State.get(getOperand(0), *State.Lane));
3547 BasicBlock *PredicatedBB = ScalarPredInst->getParent();
3548 BasicBlock *PredicatingBB = PredicatedBB->getSinglePredecessor();
3549 assert(PredicatingBB && "Predicated block has no single predecessor.");
3551 "operand must be VPReplicateRecipe");
3552
3553 // By current pack/unpack logic we need to generate only a single phi node: if
3554 // a vector value for the predicated instruction exists at this point it means
3555 // the instruction has vector users only, and a phi for the vector value is
3556 // needed. In this case the recipe of the predicated instruction is marked to
3557 // also do that packing, thereby "hoisting" the insert-element sequence.
3558 // Otherwise, a phi node for the scalar value is needed.
3559 if (State.hasVectorValue(getOperand(0))) {
3560 auto *VecI = cast<Instruction>(State.get(getOperand(0)));
3562 "Packed operands must generate an insertelement or insertvalue");
3563
3564 // If VectorI is a struct, it will be a sequence like:
3565 // %1 = insertvalue %unmodified, %x, 0
3566 // %2 = insertvalue %1, %y, 1
3567 // %VectorI = insertvalue %2, %z, 2
3568 // To get the unmodified vector we need to look through the chain.
3569 if (auto *StructTy = dyn_cast<StructType>(VecI->getType()))
3570 for (unsigned I = 0; I < StructTy->getNumContainedTypes() - 1; I++)
3571 VecI = cast<InsertValueInst>(VecI->getOperand(0));
3572
3573 PHINode *VPhi = State.Builder.CreatePHI(VecI->getType(), 2);
3574 VPhi->addIncoming(VecI->getOperand(0), PredicatingBB); // Unmodified vector.
3575 VPhi->addIncoming(VecI, PredicatedBB); // New vector with inserted element.
3576 if (State.hasVectorValue(this))
3577 State.reset(this, VPhi);
3578 else
3579 State.set(this, VPhi);
3580 // NOTE: Currently we need to update the value of the operand, so the next
3581 // predicated iteration inserts its generated value in the correct vector.
3582 State.reset(getOperand(0), VPhi);
3583 } else {
3584 if (vputils::onlyFirstLaneUsed(this) && !State.Lane->isFirstLane())
3585 return;
3586
3587 Type *PredInstType = State.TypeAnalysis.inferScalarType(getOperand(0));
3588 PHINode *Phi = State.Builder.CreatePHI(PredInstType, 2);
3589 Phi->addIncoming(PoisonValue::get(ScalarPredInst->getType()),
3590 PredicatingBB);
3591 Phi->addIncoming(ScalarPredInst, PredicatedBB);
3592 if (State.hasScalarValue(this, *State.Lane))
3593 State.reset(this, Phi, *State.Lane);
3594 else
3595 State.set(this, Phi, *State.Lane);
3596 // NOTE: Currently we need to update the value of the operand, so the next
3597 // predicated iteration inserts its generated value in the correct vector.
3598 State.reset(getOperand(0), Phi, *State.Lane);
3599 }
3600}
3601
3602#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3604 VPSlotTracker &SlotTracker) const {
3605 O << Indent << "PHI-PREDICATED-INSTRUCTION ";
3607 O << " = ";
3609}
3610#endif
3611
3613 VPCostContext &Ctx) const {
3615 unsigned AS = cast<PointerType>(Ctx.Types.inferScalarType(getAddr()))
3616 ->getAddressSpace();
3617 unsigned Opcode = isa<VPWidenLoadRecipe, VPWidenLoadEVLRecipe>(this)
3618 ? Instruction::Load
3619 : Instruction::Store;
3620
3621 if (!Consecutive) {
3622 // TODO: Using the original IR may not be accurate.
3623 // Currently, ARM will use the underlying IR to calculate gather/scatter
3624 // instruction cost.
3625 assert(!Reverse &&
3626 "Inconsecutive memory access should not have the order.");
3627
3629 Type *PtrTy = Ptr->getType();
3630
3631 // If the address value is uniform across all lanes, then the address can be
3632 // calculated with scalar type and broadcast.
3634 PtrTy = toVectorTy(PtrTy, VF);
3635
3636 unsigned IID = isa<VPWidenLoadRecipe>(this) ? Intrinsic::masked_gather
3637 : isa<VPWidenStoreRecipe>(this) ? Intrinsic::masked_scatter
3638 : isa<VPWidenLoadEVLRecipe>(this) ? Intrinsic::vp_gather
3639 : Intrinsic::vp_scatter;
3640 return Ctx.TTI.getAddressComputationCost(PtrTy, nullptr, nullptr,
3641 Ctx.CostKind) +
3642 Ctx.TTI.getMemIntrinsicInstrCost(
3644 &Ingredient),
3645 Ctx.CostKind);
3646 }
3647
3649 if (IsMasked) {
3650 unsigned IID = isa<VPWidenLoadRecipe>(this) ? Intrinsic::masked_load
3651 : Intrinsic::masked_store;
3652 Cost += Ctx.TTI.getMemIntrinsicInstrCost(
3653 MemIntrinsicCostAttributes(IID, Ty, Alignment, AS), Ctx.CostKind);
3654 } else {
3655 TTI::OperandValueInfo OpInfo = Ctx.getOperandInfo(
3657 : getOperand(1));
3658 Cost += Ctx.TTI.getMemoryOpCost(Opcode, Ty, Alignment, AS, Ctx.CostKind,
3659 OpInfo, &Ingredient);
3660 }
3661 return Cost;
3662}
3663
3665 Type *ScalarDataTy = getLoadStoreType(&Ingredient);
3666 auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
3667 bool CreateGather = !isConsecutive();
3668
3669 auto &Builder = State.Builder;
3670 Value *Mask = nullptr;
3671 if (auto *VPMask = getMask()) {
3672 // Mask reversal is only needed for non-all-one (null) masks, as reverse
3673 // of a null all-one mask is a null mask.
3674 Mask = State.get(VPMask);
3675 if (isReverse())
3676 Mask = Builder.CreateVectorReverse(Mask, "reverse");
3677 }
3678
3679 Value *Addr = State.get(getAddr(), /*IsScalar*/ !CreateGather);
3680 Value *NewLI;
3681 if (CreateGather) {
3682 NewLI = Builder.CreateMaskedGather(DataTy, Addr, Alignment, Mask, nullptr,
3683 "wide.masked.gather");
3684 } else if (Mask) {
3685 NewLI =
3686 Builder.CreateMaskedLoad(DataTy, Addr, Alignment, Mask,
3687 PoisonValue::get(DataTy), "wide.masked.load");
3688 } else {
3689 NewLI = Builder.CreateAlignedLoad(DataTy, Addr, Alignment, "wide.load");
3690 }
3692 State.set(this, NewLI);
3693}
3694
3695#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3697 VPSlotTracker &SlotTracker) const {
3698 O << Indent << "WIDEN ";
3700 O << " = load ";
3702}
3703#endif
3704
3705/// Use all-true mask for reverse rather than actual mask, as it avoids a
3706/// dependence w/o affecting the result.
3708 Value *EVL, const Twine &Name) {
3709 VectorType *ValTy = cast<VectorType>(Operand->getType());
3710 Value *AllTrueMask =
3711 Builder.CreateVectorSplat(ValTy->getElementCount(), Builder.getTrue());
3712 return Builder.CreateIntrinsic(ValTy, Intrinsic::experimental_vp_reverse,
3713 {Operand, AllTrueMask, EVL}, nullptr, Name);
3714}
3715
3717 Type *ScalarDataTy = getLoadStoreType(&Ingredient);
3718 auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
3719 bool CreateGather = !isConsecutive();
3720
3721 auto &Builder = State.Builder;
3722 CallInst *NewLI;
3723 Value *EVL = State.get(getEVL(), VPLane(0));
3724 Value *Addr = State.get(getAddr(), !CreateGather);
3725 Value *Mask = nullptr;
3726 if (VPValue *VPMask = getMask()) {
3727 Mask = State.get(VPMask);
3728 if (isReverse())
3729 Mask = createReverseEVL(Builder, Mask, EVL, "vp.reverse.mask");
3730 } else {
3731 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
3732 }
3733
3734 if (CreateGather) {
3735 NewLI =
3736 Builder.CreateIntrinsic(DataTy, Intrinsic::vp_gather, {Addr, Mask, EVL},
3737 nullptr, "wide.masked.gather");
3738 } else {
3739 NewLI = Builder.CreateIntrinsic(DataTy, Intrinsic::vp_load,
3740 {Addr, Mask, EVL}, nullptr, "vp.op.load");
3741 }
3742 NewLI->addParamAttr(
3744 applyMetadata(*NewLI);
3745 Instruction *Res = NewLI;
3746 State.set(this, Res);
3747}
3748
3750 VPCostContext &Ctx) const {
3751 if (!Consecutive || IsMasked)
3752 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
3753
3754 // We need to use the getMemIntrinsicInstrCost() instead of getMemoryOpCost()
3755 // here because the EVL recipes using EVL to replace the tail mask. But in the
3756 // legacy model, it will always calculate the cost of mask.
3757 // TODO: Using getMemoryOpCost() instead of getMemIntrinsicInstrCost when we
3758 // don't need to compare to the legacy cost model.
3760 unsigned AS = cast<PointerType>(Ctx.Types.inferScalarType(getAddr()))
3761 ->getAddressSpace();
3762 return Ctx.TTI.getMemIntrinsicInstrCost(
3763 MemIntrinsicCostAttributes(Intrinsic::vp_load, Ty, Alignment, AS),
3764 Ctx.CostKind);
3765}
3766
3767#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3769 VPSlotTracker &SlotTracker) const {
3770 O << Indent << "WIDEN ";
3772 O << " = vp.load ";
3774}
3775#endif
3776
3778 VPValue *StoredVPValue = getStoredValue();
3779 bool CreateScatter = !isConsecutive();
3780
3781 auto &Builder = State.Builder;
3782
3783 Value *Mask = nullptr;
3784 if (auto *VPMask = getMask()) {
3785 // Mask reversal is only needed for non-all-one (null) masks, as reverse
3786 // of a null all-one mask is a null mask.
3787 Mask = State.get(VPMask);
3788 if (isReverse())
3789 Mask = Builder.CreateVectorReverse(Mask, "reverse");
3790 }
3791
3792 Value *StoredVal = State.get(StoredVPValue);
3793 Value *Addr = State.get(getAddr(), /*IsScalar*/ !CreateScatter);
3794 Instruction *NewSI = nullptr;
3795 if (CreateScatter)
3796 NewSI = Builder.CreateMaskedScatter(StoredVal, Addr, Alignment, Mask);
3797 else if (Mask)
3798 NewSI = Builder.CreateMaskedStore(StoredVal, Addr, Alignment, Mask);
3799 else
3800 NewSI = Builder.CreateAlignedStore(StoredVal, Addr, Alignment);
3801 applyMetadata(*NewSI);
3802}
3803
3804#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3806 VPSlotTracker &SlotTracker) const {
3807 O << Indent << "WIDEN store ";
3809}
3810#endif
3811
3813 VPValue *StoredValue = getStoredValue();
3814 bool CreateScatter = !isConsecutive();
3815
3816 auto &Builder = State.Builder;
3817
3818 CallInst *NewSI = nullptr;
3819 Value *StoredVal = State.get(StoredValue);
3820 Value *EVL = State.get(getEVL(), VPLane(0));
3821 Value *Mask = nullptr;
3822 if (VPValue *VPMask = getMask()) {
3823 Mask = State.get(VPMask);
3824 if (isReverse())
3825 Mask = createReverseEVL(Builder, Mask, EVL, "vp.reverse.mask");
3826 } else {
3827 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
3828 }
3829 Value *Addr = State.get(getAddr(), !CreateScatter);
3830 if (CreateScatter) {
3831 NewSI = Builder.CreateIntrinsic(Type::getVoidTy(EVL->getContext()),
3832 Intrinsic::vp_scatter,
3833 {StoredVal, Addr, Mask, EVL});
3834 } else {
3835 NewSI = Builder.CreateIntrinsic(Type::getVoidTy(EVL->getContext()),
3836 Intrinsic::vp_store,
3837 {StoredVal, Addr, Mask, EVL});
3838 }
3839 NewSI->addParamAttr(
3841 applyMetadata(*NewSI);
3842}
3843
3845 VPCostContext &Ctx) const {
3846 if (!Consecutive || IsMasked)
3847 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
3848
3849 // We need to use the getMemIntrinsicInstrCost() instead of getMemoryOpCost()
3850 // here because the EVL recipes using EVL to replace the tail mask. But in the
3851 // legacy model, it will always calculate the cost of mask.
3852 // TODO: Using getMemoryOpCost() instead of getMemIntrinsicInstrCost when we
3853 // don't need to compare to the legacy cost model.
3855 unsigned AS = cast<PointerType>(Ctx.Types.inferScalarType(getAddr()))
3856 ->getAddressSpace();
3857 return Ctx.TTI.getMemIntrinsicInstrCost(
3858 MemIntrinsicCostAttributes(Intrinsic::vp_store, Ty, Alignment, AS),
3859 Ctx.CostKind);
3860}
3861
3862#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3864 VPSlotTracker &SlotTracker) const {
3865 O << Indent << "WIDEN vp.store ";
3867}
3868#endif
3869
3871 VectorType *DstVTy, const DataLayout &DL) {
3872 // Verify that V is a vector type with same number of elements as DstVTy.
3873 auto VF = DstVTy->getElementCount();
3874 auto *SrcVecTy = cast<VectorType>(V->getType());
3875 assert(VF == SrcVecTy->getElementCount() && "Vector dimensions do not match");
3876 Type *SrcElemTy = SrcVecTy->getElementType();
3877 Type *DstElemTy = DstVTy->getElementType();
3878 assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&
3879 "Vector elements must have same size");
3880
3881 // Do a direct cast if element types are castable.
3882 if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
3883 return Builder.CreateBitOrPointerCast(V, DstVTy);
3884 }
3885 // V cannot be directly casted to desired vector type.
3886 // May happen when V is a floating point vector but DstVTy is a vector of
3887 // pointers or vice-versa. Handle this using a two-step bitcast using an
3888 // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
3889 assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&
3890 "Only one type should be a pointer type");
3891 assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&
3892 "Only one type should be a floating point type");
3893 Type *IntTy =
3894 IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy));
3895 auto *VecIntTy = VectorType::get(IntTy, VF);
3896 Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
3897 return Builder.CreateBitOrPointerCast(CastVal, DstVTy);
3898}
3899
3900/// Return a vector containing interleaved elements from multiple
3901/// smaller input vectors.
3903 const Twine &Name) {
3904 unsigned Factor = Vals.size();
3905 assert(Factor > 1 && "Tried to interleave invalid number of vectors");
3906
3907 VectorType *VecTy = cast<VectorType>(Vals[0]->getType());
3908#ifndef NDEBUG
3909 for (Value *Val : Vals)
3910 assert(Val->getType() == VecTy && "Tried to interleave mismatched types");
3911#endif
3912
3913 // Scalable vectors cannot use arbitrary shufflevectors (only splats), so
3914 // must use intrinsics to interleave.
3915 if (VecTy->isScalableTy()) {
3916 assert(Factor <= 8 && "Unsupported interleave factor for scalable vectors");
3917 return Builder.CreateVectorInterleave(Vals, Name);
3918 }
3919
3920 // Fixed length. Start by concatenating all vectors into a wide vector.
3921 Value *WideVec = concatenateVectors(Builder, Vals);
3922
3923 // Interleave the elements into the wide vector.
3924 const unsigned NumElts = VecTy->getElementCount().getFixedValue();
3925 return Builder.CreateShuffleVector(
3926 WideVec, createInterleaveMask(NumElts, Factor), Name);
3927}
3928
3929// Try to vectorize the interleave group that \p Instr belongs to.
3930//
3931// E.g. Translate following interleaved load group (factor = 3):
3932// for (i = 0; i < N; i+=3) {
3933// R = Pic[i]; // Member of index 0
3934// G = Pic[i+1]; // Member of index 1
3935// B = Pic[i+2]; // Member of index 2
3936// ... // do something to R, G, B
3937// }
3938// To:
3939// %wide.vec = load <12 x i32> ; Read 4 tuples of R,G,B
3940// %R.vec = shuffle %wide.vec, poison, <0, 3, 6, 9> ; R elements
3941// %G.vec = shuffle %wide.vec, poison, <1, 4, 7, 10> ; G elements
3942// %B.vec = shuffle %wide.vec, poison, <2, 5, 8, 11> ; B elements
3943//
3944// Or translate following interleaved store group (factor = 3):
3945// for (i = 0; i < N; i+=3) {
3946// ... do something to R, G, B
3947// Pic[i] = R; // Member of index 0
3948// Pic[i+1] = G; // Member of index 1
3949// Pic[i+2] = B; // Member of index 2
3950// }
3951// To:
3952// %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
3953// %B_U.vec = shuffle %B.vec, poison, <0, 1, 2, 3, u, u, u, u>
3954// %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
3955// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> ; Interleave R,G,B elements
3956// store <12 x i32> %interleaved.vec ; Write 4 tuples of R,G,B
3958 assert(!State.Lane && "Interleave group being replicated.");
3959 assert((!needsMaskForGaps() || !State.VF.isScalable()) &&
3960 "Masking gaps for scalable vectors is not yet supported.");
3962 Instruction *Instr = Group->getInsertPos();
3963
3964 // Prepare for the vector type of the interleaved load/store.
3965 Type *ScalarTy = getLoadStoreType(Instr);
3966 unsigned InterleaveFactor = Group->getFactor();
3967 auto *VecTy = VectorType::get(ScalarTy, State.VF * InterleaveFactor);
3968
3969 VPValue *BlockInMask = getMask();
3970 VPValue *Addr = getAddr();
3971 Value *ResAddr = State.get(Addr, VPLane(0));
3972
3973 auto CreateGroupMask = [&BlockInMask, &State,
3974 &InterleaveFactor](Value *MaskForGaps) -> Value * {
3975 if (State.VF.isScalable()) {
3976 assert(!MaskForGaps && "Interleaved groups with gaps are not supported.");
3977 assert(InterleaveFactor <= 8 &&
3978 "Unsupported deinterleave factor for scalable vectors");
3979 auto *ResBlockInMask = State.get(BlockInMask);
3980 SmallVector<Value *> Ops(InterleaveFactor, ResBlockInMask);
3981 return interleaveVectors(State.Builder, Ops, "interleaved.mask");
3982 }
3983
3984 if (!BlockInMask)
3985 return MaskForGaps;
3986
3987 Value *ResBlockInMask = State.get(BlockInMask);
3988 Value *ShuffledMask = State.Builder.CreateShuffleVector(
3989 ResBlockInMask,
3990 createReplicatedMask(InterleaveFactor, State.VF.getFixedValue()),
3991 "interleaved.mask");
3992 return MaskForGaps ? State.Builder.CreateBinOp(Instruction::And,
3993 ShuffledMask, MaskForGaps)
3994 : ShuffledMask;
3995 };
3996
3997 const DataLayout &DL = Instr->getDataLayout();
3998 // Vectorize the interleaved load group.
3999 if (isa<LoadInst>(Instr)) {
4000 Value *MaskForGaps = nullptr;
4001 if (needsMaskForGaps()) {
4002 MaskForGaps =
4003 createBitMaskForGaps(State.Builder, State.VF.getFixedValue(), *Group);
4004 assert(MaskForGaps && "Mask for Gaps is required but it is null");
4005 }
4006
4007 Instruction *NewLoad;
4008 if (BlockInMask || MaskForGaps) {
4009 Value *GroupMask = CreateGroupMask(MaskForGaps);
4010 Value *PoisonVec = PoisonValue::get(VecTy);
4011 NewLoad = State.Builder.CreateMaskedLoad(VecTy, ResAddr,
4012 Group->getAlign(), GroupMask,
4013 PoisonVec, "wide.masked.vec");
4014 } else
4015 NewLoad = State.Builder.CreateAlignedLoad(VecTy, ResAddr,
4016 Group->getAlign(), "wide.vec");
4017 applyMetadata(*NewLoad);
4018 // TODO: Also manage existing metadata using VPIRMetadata.
4019 Group->addMetadata(NewLoad);
4020
4022 if (VecTy->isScalableTy()) {
4023 // Scalable vectors cannot use arbitrary shufflevectors (only splats),
4024 // so must use intrinsics to deinterleave.
4025 assert(InterleaveFactor <= 8 &&
4026 "Unsupported deinterleave factor for scalable vectors");
4027 NewLoad = State.Builder.CreateIntrinsic(
4028 Intrinsic::getDeinterleaveIntrinsicID(InterleaveFactor),
4029 NewLoad->getType(), NewLoad,
4030 /*FMFSource=*/nullptr, "strided.vec");
4031 }
4032
4033 auto CreateStridedVector = [&InterleaveFactor, &State,
4034 &NewLoad](unsigned Index) -> Value * {
4035 assert(Index < InterleaveFactor && "Illegal group index");
4036 if (State.VF.isScalable())
4037 return State.Builder.CreateExtractValue(NewLoad, Index);
4038
4039 // For fixed length VF, use shuffle to extract the sub-vectors from the
4040 // wide load.
4041 auto StrideMask =
4042 createStrideMask(Index, InterleaveFactor, State.VF.getFixedValue());
4043 return State.Builder.CreateShuffleVector(NewLoad, StrideMask,
4044 "strided.vec");
4045 };
4046
4047 for (unsigned I = 0, J = 0; I < InterleaveFactor; ++I) {
4048 Instruction *Member = Group->getMember(I);
4049
4050 // Skip the gaps in the group.
4051 if (!Member)
4052 continue;
4053
4054 Value *StridedVec = CreateStridedVector(I);
4055
4056 // If this member has different type, cast the result type.
4057 if (Member->getType() != ScalarTy) {
4058 VectorType *OtherVTy = VectorType::get(Member->getType(), State.VF);
4059 StridedVec =
4060 createBitOrPointerCast(State.Builder, StridedVec, OtherVTy, DL);
4061 }
4062
4063 if (Group->isReverse())
4064 StridedVec = State.Builder.CreateVectorReverse(StridedVec, "reverse");
4065
4066 State.set(VPDefs[J], StridedVec);
4067 ++J;
4068 }
4069 return;
4070 }
4071
4072 // The sub vector type for current instruction.
4073 auto *SubVT = VectorType::get(ScalarTy, State.VF);
4074
4075 // Vectorize the interleaved store group.
4076 Value *MaskForGaps =
4077 createBitMaskForGaps(State.Builder, State.VF.getKnownMinValue(), *Group);
4078 assert(((MaskForGaps != nullptr) == needsMaskForGaps()) &&
4079 "Mismatch between NeedsMaskForGaps and MaskForGaps");
4080 ArrayRef<VPValue *> StoredValues = getStoredValues();
4081 // Collect the stored vector from each member.
4082 SmallVector<Value *, 4> StoredVecs;
4083 unsigned StoredIdx = 0;
4084 for (unsigned i = 0; i < InterleaveFactor; i++) {
4085 assert((Group->getMember(i) || MaskForGaps) &&
4086 "Fail to get a member from an interleaved store group");
4087 Instruction *Member = Group->getMember(i);
4088
4089 // Skip the gaps in the group.
4090 if (!Member) {
4091 Value *Undef = PoisonValue::get(SubVT);
4092 StoredVecs.push_back(Undef);
4093 continue;
4094 }
4095
4096 Value *StoredVec = State.get(StoredValues[StoredIdx]);
4097 ++StoredIdx;
4098
4099 if (Group->isReverse())
4100 StoredVec = State.Builder.CreateVectorReverse(StoredVec, "reverse");
4101
4102 // If this member has different type, cast it to a unified type.
4103
4104 if (StoredVec->getType() != SubVT)
4105 StoredVec = createBitOrPointerCast(State.Builder, StoredVec, SubVT, DL);
4106
4107 StoredVecs.push_back(StoredVec);
4108 }
4109
4110 // Interleave all the smaller vectors into one wider vector.
4111 Value *IVec = interleaveVectors(State.Builder, StoredVecs, "interleaved.vec");
4112 Instruction *NewStoreInstr;
4113 if (BlockInMask || MaskForGaps) {
4114 Value *GroupMask = CreateGroupMask(MaskForGaps);
4115 NewStoreInstr = State.Builder.CreateMaskedStore(
4116 IVec, ResAddr, Group->getAlign(), GroupMask);
4117 } else
4118 NewStoreInstr =
4119 State.Builder.CreateAlignedStore(IVec, ResAddr, Group->getAlign());
4120
4121 applyMetadata(*NewStoreInstr);
4122 // TODO: Also manage existing metadata using VPIRMetadata.
4123 Group->addMetadata(NewStoreInstr);
4124}
4125
4126#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4128 VPSlotTracker &SlotTracker) const {
4130 O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << " at ";
4131 IG->getInsertPos()->printAsOperand(O, false);
4132 O << ", ";
4134 VPValue *Mask = getMask();
4135 if (Mask) {
4136 O << ", ";
4137 Mask->printAsOperand(O, SlotTracker);
4138 }
4139
4140 unsigned OpIdx = 0;
4141 for (unsigned i = 0; i < IG->getFactor(); ++i) {
4142 if (!IG->getMember(i))
4143 continue;
4144 if (getNumStoreOperands() > 0) {
4145 O << "\n" << Indent << " store ";
4147 O << " to index " << i;
4148 } else {
4149 O << "\n" << Indent << " ";
4151 O << " = load from index " << i;
4152 }
4153 ++OpIdx;
4154 }
4155}
4156#endif
4157
4159 assert(!State.Lane && "Interleave group being replicated.");
4160 assert(State.VF.isScalable() &&
4161 "Only support scalable VF for EVL tail-folding.");
4163 "Masking gaps for scalable vectors is not yet supported.");
4165 Instruction *Instr = Group->getInsertPos();
4166
4167 // Prepare for the vector type of the interleaved load/store.
4168 Type *ScalarTy = getLoadStoreType(Instr);
4169 unsigned InterleaveFactor = Group->getFactor();
4170 assert(InterleaveFactor <= 8 &&
4171 "Unsupported deinterleave/interleave factor for scalable vectors");
4172 ElementCount WideVF = State.VF * InterleaveFactor;
4173 auto *VecTy = VectorType::get(ScalarTy, WideVF);
4174
4175 VPValue *Addr = getAddr();
4176 Value *ResAddr = State.get(Addr, VPLane(0));
4177 Value *EVL = State.get(getEVL(), VPLane(0));
4178 Value *InterleaveEVL = State.Builder.CreateMul(
4179 EVL, ConstantInt::get(EVL->getType(), InterleaveFactor), "interleave.evl",
4180 /* NUW= */ true, /* NSW= */ true);
4181 LLVMContext &Ctx = State.Builder.getContext();
4182
4183 Value *GroupMask = nullptr;
4184 if (VPValue *BlockInMask = getMask()) {
4185 SmallVector<Value *> Ops(InterleaveFactor, State.get(BlockInMask));
4186 GroupMask = interleaveVectors(State.Builder, Ops, "interleaved.mask");
4187 } else {
4188 GroupMask =
4189 State.Builder.CreateVectorSplat(WideVF, State.Builder.getTrue());
4190 }
4191
4192 // Vectorize the interleaved load group.
4193 if (isa<LoadInst>(Instr)) {
4194 CallInst *NewLoad = State.Builder.CreateIntrinsic(
4195 VecTy, Intrinsic::vp_load, {ResAddr, GroupMask, InterleaveEVL}, nullptr,
4196 "wide.vp.load");
4197 NewLoad->addParamAttr(0,
4198 Attribute::getWithAlignment(Ctx, Group->getAlign()));
4199
4200 applyMetadata(*NewLoad);
4201 // TODO: Also manage existing metadata using VPIRMetadata.
4202 Group->addMetadata(NewLoad);
4203
4204 // Scalable vectors cannot use arbitrary shufflevectors (only splats),
4205 // so must use intrinsics to deinterleave.
4206 NewLoad = State.Builder.CreateIntrinsic(
4207 Intrinsic::getDeinterleaveIntrinsicID(InterleaveFactor),
4208 NewLoad->getType(), NewLoad,
4209 /*FMFSource=*/nullptr, "strided.vec");
4210
4211 const DataLayout &DL = Instr->getDataLayout();
4212 for (unsigned I = 0, J = 0; I < InterleaveFactor; ++I) {
4213 Instruction *Member = Group->getMember(I);
4214 // Skip the gaps in the group.
4215 if (!Member)
4216 continue;
4217
4218 Value *StridedVec = State.Builder.CreateExtractValue(NewLoad, I);
4219 // If this member has different type, cast the result type.
4220 if (Member->getType() != ScalarTy) {
4221 VectorType *OtherVTy = VectorType::get(Member->getType(), State.VF);
4222 StridedVec =
4223 createBitOrPointerCast(State.Builder, StridedVec, OtherVTy, DL);
4224 }
4225
4226 State.set(getVPValue(J), StridedVec);
4227 ++J;
4228 }
4229 return;
4230 } // End for interleaved load.
4231
4232 // The sub vector type for current instruction.
4233 auto *SubVT = VectorType::get(ScalarTy, State.VF);
4234 // Vectorize the interleaved store group.
4235 ArrayRef<VPValue *> StoredValues = getStoredValues();
4236 // Collect the stored vector from each member.
4237 SmallVector<Value *, 4> StoredVecs;
4238 const DataLayout &DL = Instr->getDataLayout();
4239 for (unsigned I = 0, StoredIdx = 0; I < InterleaveFactor; I++) {
4240 Instruction *Member = Group->getMember(I);
4241 // Skip the gaps in the group.
4242 if (!Member) {
4243 StoredVecs.push_back(PoisonValue::get(SubVT));
4244 continue;
4245 }
4246
4247 Value *StoredVec = State.get(StoredValues[StoredIdx]);
4248 // If this member has different type, cast it to a unified type.
4249 if (StoredVec->getType() != SubVT)
4250 StoredVec = createBitOrPointerCast(State.Builder, StoredVec, SubVT, DL);
4251
4252 StoredVecs.push_back(StoredVec);
4253 ++StoredIdx;
4254 }
4255
4256 // Interleave all the smaller vectors into one wider vector.
4257 Value *IVec = interleaveVectors(State.Builder, StoredVecs, "interleaved.vec");
4258 CallInst *NewStore =
4259 State.Builder.CreateIntrinsic(Type::getVoidTy(Ctx), Intrinsic::vp_store,
4260 {IVec, ResAddr, GroupMask, InterleaveEVL});
4261 NewStore->addParamAttr(1,
4262 Attribute::getWithAlignment(Ctx, Group->getAlign()));
4263
4264 applyMetadata(*NewStore);
4265 // TODO: Also manage existing metadata using VPIRMetadata.
4266 Group->addMetadata(NewStore);
4267}
4268
4269#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4271 VPSlotTracker &SlotTracker) const {
4273 O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << " at ";
4274 IG->getInsertPos()->printAsOperand(O, false);
4275 O << ", ";
4277 O << ", ";
4279 if (VPValue *Mask = getMask()) {
4280 O << ", ";
4281 Mask->printAsOperand(O, SlotTracker);
4282 }
4283
4284 unsigned OpIdx = 0;
4285 for (unsigned i = 0; i < IG->getFactor(); ++i) {
4286 if (!IG->getMember(i))
4287 continue;
4288 if (getNumStoreOperands() > 0) {
4289 O << "\n" << Indent << " vp.store ";
4291 O << " to index " << i;
4292 } else {
4293 O << "\n" << Indent << " ";
4295 O << " = vp.load from index " << i;
4296 }
4297 ++OpIdx;
4298 }
4299}
4300#endif
4301
4303 VPCostContext &Ctx) const {
4304 Instruction *InsertPos = getInsertPos();
4305 // Find the VPValue index of the interleave group. We need to skip gaps.
4306 unsigned InsertPosIdx = 0;
4307 for (unsigned Idx = 0; IG->getFactor(); ++Idx)
4308 if (auto *Member = IG->getMember(Idx)) {
4309 if (Member == InsertPos)
4310 break;
4311 InsertPosIdx++;
4312 }
4313 Type *ValTy = Ctx.Types.inferScalarType(
4314 getNumDefinedValues() > 0 ? getVPValue(InsertPosIdx)
4315 : getStoredValues()[InsertPosIdx]);
4316 auto *VectorTy = cast<VectorType>(toVectorTy(ValTy, VF));
4317 unsigned AS = cast<PointerType>(Ctx.Types.inferScalarType(getAddr()))
4318 ->getAddressSpace();
4319
4320 unsigned InterleaveFactor = IG->getFactor();
4321 auto *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
4322
4323 // Holds the indices of existing members in the interleaved group.
4325 for (unsigned IF = 0; IF < InterleaveFactor; IF++)
4326 if (IG->getMember(IF))
4327 Indices.push_back(IF);
4328
4329 // Calculate the cost of the whole interleaved group.
4330 InstructionCost Cost = Ctx.TTI.getInterleavedMemoryOpCost(
4331 InsertPos->getOpcode(), WideVecTy, IG->getFactor(), Indices,
4332 IG->getAlign(), AS, Ctx.CostKind, getMask(), NeedsMaskForGaps);
4333
4334 if (!IG->isReverse())
4335 return Cost;
4336
4337 return Cost + IG->getNumMembers() *
4338 Ctx.TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
4339 VectorTy, VectorTy, {}, Ctx.CostKind,
4340 0);
4341}
4342
4343#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4345 VPSlotTracker &SlotTracker) const {
4346 O << Indent << "EMIT ";
4348 O << " = CANONICAL-INDUCTION ";
4350}
4351#endif
4352
4354 return vputils::onlyScalarValuesUsed(this) &&
4355 (!IsScalable || vputils::onlyFirstLaneUsed(this));
4356}
4357
4358#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4360 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
4361 assert((getNumOperands() == 3 || getNumOperands() == 5) &&
4362 "unexpected number of operands");
4363 O << Indent << "EMIT ";
4365 O << " = WIDEN-POINTER-INDUCTION ";
4367 O << ", ";
4369 O << ", ";
4371 if (getNumOperands() == 5) {
4372 O << ", ";
4374 O << ", ";
4376 }
4377}
4378
4380 VPSlotTracker &SlotTracker) const {
4381 O << Indent << "EMIT ";
4383 O << " = EXPAND SCEV " << *Expr;
4384}
4385#endif
4386
4388 Value *CanonicalIV = State.get(getOperand(0), /*IsScalar*/ true);
4389 Type *STy = CanonicalIV->getType();
4390 IRBuilder<> Builder(State.CFG.PrevBB->getTerminator());
4391 ElementCount VF = State.VF;
4392 Value *VStart = VF.isScalar()
4393 ? CanonicalIV
4394 : Builder.CreateVectorSplat(VF, CanonicalIV, "broadcast");
4395 Value *VStep = createStepForVF(Builder, STy, VF, getUnrollPart(*this));
4396 if (VF.isVector()) {
4397 VStep = Builder.CreateVectorSplat(VF, VStep);
4398 VStep =
4399 Builder.CreateAdd(VStep, Builder.CreateStepVector(VStep->getType()));
4400 }
4401 Value *CanonicalVectorIV = Builder.CreateAdd(VStart, VStep, "vec.iv");
4402 State.set(this, CanonicalVectorIV);
4403}
4404
4405#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4407 VPSlotTracker &SlotTracker) const {
4408 O << Indent << "EMIT ";
4410 O << " = WIDEN-CANONICAL-INDUCTION ";
4412}
4413#endif
4414
4416 auto &Builder = State.Builder;
4417 // Create a vector from the initial value.
4418 auto *VectorInit = getStartValue()->getLiveInIRValue();
4419
4420 Type *VecTy = State.VF.isScalar()
4421 ? VectorInit->getType()
4422 : VectorType::get(VectorInit->getType(), State.VF);
4423
4424 BasicBlock *VectorPH =
4425 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
4426 if (State.VF.isVector()) {
4427 auto *IdxTy = Builder.getInt32Ty();
4428 auto *One = ConstantInt::get(IdxTy, 1);
4429 IRBuilder<>::InsertPointGuard Guard(Builder);
4430 Builder.SetInsertPoint(VectorPH->getTerminator());
4431 auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, State.VF);
4432 auto *LastIdx = Builder.CreateSub(RuntimeVF, One);
4433 VectorInit = Builder.CreateInsertElement(
4434 PoisonValue::get(VecTy), VectorInit, LastIdx, "vector.recur.init");
4435 }
4436
4437 // Create a phi node for the new recurrence.
4438 PHINode *Phi = PHINode::Create(VecTy, 2, "vector.recur");
4439 Phi->insertBefore(State.CFG.PrevBB->getFirstInsertionPt());
4440 Phi->addIncoming(VectorInit, VectorPH);
4441 State.set(this, Phi);
4442}
4443
4446 VPCostContext &Ctx) const {
4447 if (VF.isScalar())
4448 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
4449
4450 return 0;
4451}
4452
4453#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4455 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
4456 O << Indent << "FIRST-ORDER-RECURRENCE-PHI ";
4458 O << " = phi ";
4460}
4461#endif
4462
4464 // Reductions do not have to start at zero. They can start with
4465 // any loop invariant values.
4466 VPValue *StartVPV = getStartValue();
4467
4468 // In order to support recurrences we need to be able to vectorize Phi nodes.
4469 // Phi nodes have cycles, so we need to vectorize them in two stages. This is
4470 // stage #1: We create a new vector PHI node with no incoming edges. We'll use
4471 // this value when we vectorize all of the instructions that use the PHI.
4472 BasicBlock *VectorPH =
4473 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
4474 bool ScalarPHI = State.VF.isScalar() || isInLoop();
4475 Value *StartV = State.get(StartVPV, ScalarPHI);
4476 Type *VecTy = StartV->getType();
4477
4478 BasicBlock *HeaderBB = State.CFG.PrevBB;
4479 assert(State.CurrentParentLoop->getHeader() == HeaderBB &&
4480 "recipe must be in the vector loop header");
4481 auto *Phi = PHINode::Create(VecTy, 2, "vec.phi");
4482 Phi->insertBefore(HeaderBB->getFirstInsertionPt());
4483 State.set(this, Phi, isInLoop());
4484
4485 Phi->addIncoming(StartV, VectorPH);
4486}
4487
4488#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4490 VPSlotTracker &SlotTracker) const {
4491 O << Indent << "WIDEN-REDUCTION-PHI ";
4492
4494 O << " = phi ";
4496 if (getVFScaleFactor() > 1)
4497 O << " (VF scaled by 1/" << getVFScaleFactor() << ")";
4498}
4499#endif
4500
4502 Value *Op0 = State.get(getOperand(0));
4503 Type *VecTy = Op0->getType();
4504 Instruction *VecPhi = State.Builder.CreatePHI(VecTy, 2, Name);
4505 State.set(this, VecPhi);
4506}
4507
4509 VPCostContext &Ctx) const {
4510 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
4511}
4512
4513#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4515 VPSlotTracker &SlotTracker) const {
4516 O << Indent << "WIDEN-PHI ";
4517
4519 O << " = phi ";
4521}
4522#endif
4523
4525 BasicBlock *VectorPH =
4526 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
4527 Value *StartMask = State.get(getOperand(0));
4528 PHINode *Phi =
4529 State.Builder.CreatePHI(StartMask->getType(), 2, "active.lane.mask");
4530 Phi->addIncoming(StartMask, VectorPH);
4531 State.set(this, Phi);
4532}
4533
4534#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4536 VPSlotTracker &SlotTracker) const {
4537 O << Indent << "ACTIVE-LANE-MASK-PHI ";
4538
4540 O << " = phi ";
4542}
4543#endif
4544
4545#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4547 VPSlotTracker &SlotTracker) const {
4548 O << Indent << "EXPLICIT-VECTOR-LENGTH-BASED-IV-PHI ";
4549
4551 O << " = phi ";
4553}
4554#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, LoopVectorizationLegality *Legal, PredicatedScalarEvolution &PSE, const Loop *TheLoop)
Gets Address Access SCEV after verifying that the access pattern is loop invariant except the inducti...
#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:661
bool doesNotThrow() const
Determine if the function cannot unwind.
Definition Function.h:594
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:2553
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:2607
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2541
LLVM_ABI Value * CreateVectorSplice(Value *V1, Value *V2, int64_t Imm, const Twine &Name="")
Return a vector splice intrinsic if using scalable vectors, otherwise return a shufflevector.
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:2600
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:2619
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:2007
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:2304
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:2434
Value * CreateNot(Value *V, const Twine &Name="")
Definition IRBuilder.h:1808
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2300
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:2053
LLVM_ABI CallInst * CreateIntMaxReduce(Value *Src, bool IsSigned=false)
Create a vector integer max reduction intrinsic of the source vector.
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:2312
LLVM_ABI CallInst * CreateIntMinReduce(Value *Src, bool IsSigned=false)
Create a vector integer min reduction intrinsic of the source vector.
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2410
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:2762
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
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:318
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:4062
iterator end()
Definition VPlan.h:4046
void insert(VPRecipeBase *Recipe, iterator InsertPt)
Definition VPlan.h:4075
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:2587
unsigned getNumIncomingValues() const
Return the number of incoming values, taking into account when normalized the first incoming value wi...
Definition VPlan.h:2582
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:477
VPValue * getVPSingleValue()
Returns the only VPValue defined by the VPDef.
Definition VPlanValue.h:450
VPValue * getVPValue(unsigned I)
Returns the VPValue with index I defined by the VPDef.
Definition VPlanValue.h:462
ArrayRef< VPRecipeValue * > definedValues()
Returns an ArrayRef of the values defined by the VPDef.
Definition VPlanValue.h:472
unsigned getVPDefID() const
Definition VPlanValue.h:482
VPIRValue * getStartValue() const
Definition VPlan.h:3810
VPValue * getStepValue() const
Definition VPlan.h:3811
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:2107
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:1858
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:882
LLVM_ABI_FOR_TEST FastMathFlags getFastMathFlags() const
bool isReductionOrdered() const
Definition VPlan.h:932
TruncFlagsTy TruncFlags
Definition VPlan.h:690
CmpInst::Predicate getPredicate() const
Definition VPlan.h:859
ExactFlagsTy ExactFlags
Definition VPlan.h:692
bool hasNoSignedWrap() const
Definition VPlan.h:909
void intersectFlags(const VPIRFlags &Other)
Only keep flags also present in Other.
GEPNoWrapFlags getGEPNoWrapFlags() const
Definition VPlan.h:874
bool hasPredicate() const
Returns true if the recipe has a comparison predicate.
Definition VPlan.h:877
DisjointFlagsTy DisjointFlags
Definition VPlan.h:691
unsigned AllFlags
Definition VPlan.h:698
bool hasNoUnsignedWrap() const
Definition VPlan.h:898
FCmpFlagsTy FCmpFlags
Definition VPlan.h:696
NonNegFlagsTy NonNegFlags
Definition VPlan.h:694
bool isReductionInLoop() const
Definition VPlan.h:938
void applyFlags(Instruction &I) const
Apply the IR flags to I.
Definition VPlan.h:816
RecurKind getRecurKind() const
Definition VPlan.h:926
Instruction & getInstruction() const
Definition VPlan.h:1512
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:1487
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:1195
@ ExtractLane
Extracts a single lane (first operand) from a set of vector operands.
Definition VPlan.h:1188
@ ComputeAnyOfResult
Compute the final result of a AnyOf reduction with select(cmp(),x,y), where one of (x,...
Definition VPlan.h:1133
@ WideIVStep
Scale the first operand (vector step) by the second operand (scalar-step).
Definition VPlan.h:1178
@ ResumeForEpilogue
Explicit user for the resume phi of the canonical induction in the main VPlan, used by the epilogue v...
Definition VPlan.h:1191
@ Unpack
Extracts all lanes from its (non-scalable) vector operand.
Definition VPlan.h:1130
@ ReductionStartVector
Start vector for reductions with 3 operands: the original start value, the identity value for the red...
Definition VPlan.h:1182
@ BuildVector
Creates a fixed-width vector containing all operands.
Definition VPlan.h:1125
@ BuildStructVector
Given operands of (the same) struct type, creates a struct of fixed- width vectors each containing a ...
Definition VPlan.h:1122
@ VScale
Returns the value for vscale.
Definition VPlan.h:1198
@ CanonicalIVIncrementForPart
Definition VPlan.h:1106
bool hasResult() const
Definition VPlan.h:1262
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:1303
unsigned getOpcode() const
Definition VPlan.h:1246
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:2699
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this recipe.
Instruction * getInsertPos() const
Definition VPlan.h:2703
const InterleaveGroup< Instruction > * getInterleaveGroup() const
Definition VPlan.h:2701
VPValue * getMask() const
Return the mask used by this recipe.
Definition VPlan.h:2693
ArrayRef< VPValue * > getStoredValues() const
Return the VPValues stored by this interleave group.
Definition VPlan.h:2722
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition VPlan.h:2687
VPValue * getEVL() const
The VPValue of the explicit vector length.
Definition VPlan.h:2797
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:2810
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:2760
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:1402
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:4153
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:1427
VPValue * getIncomingValue(unsigned Idx) const
Returns the incoming VPValue with index Idx.
Definition VPlan.h:1394
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:4314
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:2960
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:2504
bool isInLoop() const
Returns true if the phi is part of an in-loop reduction.
Definition VPlan.h:2528
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:2902
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:2913
VPValue * getCondOp() const
The VPValue of the condition for the block.
Definition VPlan.h:2915
RecurKind getRecurrenceKind() const
Return the recurrence kind for the in-loop reduction.
Definition VPlan.h:2898
bool isPartialReduction() const
Returns true if the reduction outputs a vector with a scaled down VF.
Definition VPlan.h:2904
VPValue * getChainOp() const
The VPValue of the scalar Chain being accumulated.
Definition VPlan.h:2911
bool isInLoop() const
Returns true if the reduction is in-loop.
Definition VPlan.h:2906
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:4197
bool isReplicator() const
An indicator whether this region is to generate multiple replicated instances of output IR correspond...
Definition VPlan.h:4265
VPReplicateRecipe replicates a given instruction producing multiple scalar copies of the original sca...
Definition VPlan.h:2982
void execute(VPTransformState &State) override
Generate replicas of the desired Ingredient.
bool isSingleScalar() const
Definition VPlan.h:3023
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:3052
bool shouldPack() const
Returns true if the recipe is used by a widened recipe via an intervening VPPredInstPHIRecipe.
VPValue * getStepValue() const
Definition VPlan.h:3877
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:1020
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:2012
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:1814
Function * getCalledScalarFunction() const
Definition VPlan.h:1810
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:1664
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:1910
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:2170
VPValue * getStepValue()
Returns the step value of the induction.
Definition VPlan.h:2173
VPIRValue * getStartValue() const
Returns the start value of the induction.
Definition VPlan.h:2268
TruncInst * getTruncInst()
Returns the first defined value as TruncInst, if it is one or nullptr otherwise.
Definition VPlan.h:2283
Type * getScalarType() const
Returns the scalar type of the induction.
Definition VPlan.h:2292
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:1746
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:1749
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:3307
bool Reverse
Whether the consecutive accessed addresses are in reverse order.
Definition VPlan.h:3304
bool isConsecutive() const
Return whether the loaded-from / stored-to addresses are consecutive.
Definition VPlan.h:3347
Instruction & Ingredient
Definition VPlan.h:3295
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:3301
VPValue * getMask() const
Return the mask used by this recipe.
Definition VPlan.h:3361
Align Alignment
Alignment information for this memory access.
Definition VPlan.h:3298
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition VPlan.h:3354
bool isReverse() const
Return whether the consecutive loaded/stored addresses are in reverse order.
Definition VPlan.h:3351
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:4544
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
LLVM_ABI LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.cpp:1106
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)
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.
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
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
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.
@ 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
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 Value * createAnyOfReduction(IRBuilderBase &B, Value *Src, Value *InitVal, PHINode *OrigPhi)
Create a reduction of the given vector Src for a reduction of kind RecurKind::AnyOf.
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:1550
PHINode & getIRPhi()
Definition VPlan.h:1558
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:974
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:975
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:3439
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:3522
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:3525
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:3485