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