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 assert((State.VF.isScalable() || isa<Constant>(StartIdx)) &&
2610 "Expected StartIdx to be folded to a constant when VF is not "
2611 "scalable");
2612 auto *Mul = Builder.CreateBinOp(MulOp, StartIdx, Step);
2613 auto *Add = Builder.CreateBinOp(AddOp, BaseIV, Mul);
2614 State.set(this, Add, VPLane(Lane));
2615 }
2616}
2617
2618#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2620 VPSlotTracker &SlotTracker) const {
2621 O << Indent;
2623 O << " = SCALAR-STEPS ";
2625}
2626#endif
2627
2629 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
2631}
2632
2634 assert(State.VF.isVector() && "not widening");
2635 // Construct a vector GEP by widening the operands of the scalar GEP as
2636 // necessary. We mark the vector GEP 'inbounds' if appropriate. A GEP
2637 // results in a vector of pointers when at least one operand of the GEP
2638 // is vector-typed. Thus, to keep the representation compact, we only use
2639 // vector-typed operands for loop-varying values.
2640
2641 bool AllOperandsAreInvariant = all_of(operands(), [](VPValue *Op) {
2642 return Op->isDefinedOutsideLoopRegions();
2643 });
2644 if (AllOperandsAreInvariant) {
2645 // If we are vectorizing, but the GEP has only loop-invariant operands,
2646 // the GEP we build (by only using vector-typed operands for
2647 // loop-varying values) would be a scalar pointer. Thus, to ensure we
2648 // produce a vector of pointers, we need to either arbitrarily pick an
2649 // operand to broadcast, or broadcast a clone of the original GEP.
2650 // Here, we broadcast a clone of the original.
2651
2653 for (unsigned I = 0, E = getNumOperands(); I != E; I++)
2654 Ops.push_back(State.get(getOperand(I), VPLane(0)));
2655
2656 auto *NewGEP =
2657 State.Builder.CreateGEP(getSourceElementType(), Ops[0], drop_begin(Ops),
2658 "", getGEPNoWrapFlags());
2659 Value *Splat = State.Builder.CreateVectorSplat(State.VF, NewGEP);
2660 State.set(this, Splat);
2661 return;
2662 }
2663
2664 // If the GEP has at least one loop-varying operand, we are sure to
2665 // produce a vector of pointers unless VF is scalar.
2666 // The pointer operand of the new GEP. If it's loop-invariant, we
2667 // won't broadcast it.
2668 auto *Ptr = State.get(getOperand(0), isPointerLoopInvariant());
2669
2670 // Collect all the indices for the new GEP. If any index is
2671 // loop-invariant, we won't broadcast it.
2673 for (unsigned I = 1, E = getNumOperands(); I < E; I++) {
2674 VPValue *Operand = getOperand(I);
2675 Indices.push_back(State.get(Operand, isIndexLoopInvariant(I - 1)));
2676 }
2677
2678 // Create the new GEP. Note that this GEP may be a scalar if VF == 1,
2679 // but it should be a vector, otherwise.
2680 auto *NewGEP = State.Builder.CreateGEP(getSourceElementType(), Ptr, Indices,
2681 "", getGEPNoWrapFlags());
2682 assert((State.VF.isScalar() || NewGEP->getType()->isVectorTy()) &&
2683 "NewGEP is not a pointer vector");
2684 State.set(this, NewGEP);
2685}
2686
2687#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2689 VPSlotTracker &SlotTracker) const {
2690 O << Indent << "WIDEN-GEP ";
2691 O << (isPointerLoopInvariant() ? "Inv" : "Var");
2692 for (size_t I = 0; I < getNumOperands() - 1; ++I)
2693 O << "[" << (isIndexLoopInvariant(I) ? "Inv" : "Var") << "]";
2694
2695 O << " ";
2697 O << " = getelementptr";
2698 printFlags(O);
2700}
2701#endif
2702
2704 assert(!getOffset() && "Unexpected offset operand");
2705 VPBuilder Builder(this);
2706 VPlan &Plan = *getParent()->getPlan();
2707 VPValue *VFVal = getVFValue();
2708 VPTypeAnalysis TypeInfo(Plan);
2709 const DataLayout &DL = Plan.getDataLayout();
2710 Type *IndexTy = DL.getIndexType(TypeInfo.inferScalarType(this));
2711 VPValue *Stride =
2712 Plan.getConstantInt(IndexTy, getStride(), /*IsSigned=*/true);
2713 Type *VFTy = TypeInfo.inferScalarType(VFVal);
2714 VPValue *VF = Builder.createScalarZExtOrTrunc(VFVal, IndexTy, VFTy,
2716
2717 // Offset for Part0 = Offset0 = Stride * (VF - 1).
2718 VPInstruction *VFMinusOne =
2719 Builder.createSub(VF, Plan.getConstantInt(IndexTy, 1u),
2720 DebugLoc::getUnknown(), "", {true, true});
2721 VPInstruction *Offset0 =
2722 Builder.createOverflowingOp(Instruction::Mul, {VFMinusOne, Stride});
2723
2724 // Offset for PartN = Offset0 + Part * Stride * VF.
2725 VPValue *PartxStride =
2726 Plan.getConstantInt(IndexTy, Part * getStride(), /*IsSigned=*/true);
2727 VPValue *Offset = Builder.createAdd(
2728 Offset0,
2729 Builder.createOverflowingOp(Instruction::Mul, {PartxStride, VF}));
2731}
2732
2734 auto &Builder = State.Builder;
2735 assert(getOffset() && "Expected prior materialization of offset");
2736 Value *Ptr = State.get(getPointer(), true);
2737 Value *Offset = State.get(getOffset(), true);
2738 Value *ResultPtr = Builder.CreateGEP(getSourceElementType(), Ptr, Offset, "",
2740 State.set(this, ResultPtr, /*IsScalar*/ true);
2741}
2742
2743#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2745 VPSlotTracker &SlotTracker) const {
2746 O << Indent;
2748 O << " = vector-end-pointer";
2749 printFlags(O);
2751}
2752#endif
2753
2755 auto &Builder = State.Builder;
2756 assert(getOffset() &&
2757 "Expected prior simplification of recipe without offset");
2758 Value *Ptr = State.get(getOperand(0), VPLane(0));
2759 Value *Offset = State.get(getOffset(), true);
2760 Value *ResultPtr = Builder.CreateGEP(getSourceElementType(), Ptr, Offset, "",
2762 State.set(this, ResultPtr, /*IsScalar*/ true);
2763}
2764
2765#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2767 VPSlotTracker &SlotTracker) const {
2768 O << Indent;
2770 O << " = vector-pointer";
2771 printFlags(O);
2773}
2774#endif
2775
2777 VPCostContext &Ctx) const {
2778 // A blend will be expanded to a select VPInstruction, which will generate a
2779 // scalar select if only the first lane is used.
2781 VF = ElementCount::getFixed(1);
2782
2783 Type *ResultTy = toVectorTy(Ctx.Types.inferScalarType(this), VF);
2784 Type *CmpTy = toVectorTy(Type::getInt1Ty(Ctx.Types.getContext()), VF);
2785 return (getNumIncomingValues() - 1) *
2786 Ctx.TTI.getCmpSelInstrCost(Instruction::Select, ResultTy, CmpTy,
2787 CmpInst::BAD_ICMP_PREDICATE, Ctx.CostKind);
2788}
2789
2790#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2792 VPSlotTracker &SlotTracker) const {
2793 O << Indent << "BLEND ";
2795 O << " =";
2796 printFlags(O);
2797 if (getNumIncomingValues() == 1) {
2798 // Not a User of any mask: not really blending, this is a
2799 // single-predecessor phi.
2800 getIncomingValue(0)->printAsOperand(O, SlotTracker);
2801 } else {
2802 for (unsigned I = 0, E = getNumIncomingValues(); I < E; ++I) {
2803 if (I != 0)
2804 O << " ";
2805 getIncomingValue(I)->printAsOperand(O, SlotTracker);
2806 if (I == 0 && isNormalized())
2807 continue;
2808 O << "/";
2809 getMask(I)->printAsOperand(O, SlotTracker);
2810 }
2811 }
2812}
2813#endif
2814
2816 assert(!State.Lane && "Reduction being replicated.");
2819 "In-loop AnyOf reductions aren't currently supported");
2820 // Propagate the fast-math flags carried by the underlying instruction.
2821 IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder);
2822 State.Builder.setFastMathFlags(getFastMathFlags());
2823 Value *NewVecOp = State.get(getVecOp());
2824 if (VPValue *Cond = getCondOp()) {
2825 Value *NewCond = State.get(Cond, State.VF.isScalar());
2826 VectorType *VecTy = dyn_cast<VectorType>(NewVecOp->getType());
2827 Type *ElementTy = VecTy ? VecTy->getElementType() : NewVecOp->getType();
2828
2829 Value *Start = getRecurrenceIdentity(Kind, ElementTy, getFastMathFlags());
2830 if (State.VF.isVector())
2831 Start = State.Builder.CreateVectorSplat(VecTy->getElementCount(), Start);
2832
2833 Value *Select = State.Builder.CreateSelect(NewCond, NewVecOp, Start);
2834 NewVecOp = Select;
2835 }
2836 Value *NewRed;
2837 Value *NextInChain;
2838 if (isOrdered()) {
2839 Value *PrevInChain = State.get(getChainOp(), /*IsScalar*/ true);
2840 if (State.VF.isVector())
2841 NewRed =
2842 createOrderedReduction(State.Builder, Kind, NewVecOp, PrevInChain);
2843 else
2844 NewRed = State.Builder.CreateBinOp(
2846 PrevInChain, NewVecOp);
2847 PrevInChain = NewRed;
2848 NextInChain = NewRed;
2849 } else if (isPartialReduction()) {
2850 assert((Kind == RecurKind::Add || Kind == RecurKind::FAdd) &&
2851 "Unexpected partial reduction kind");
2852 Value *PrevInChain = State.get(getChainOp(), /*IsScalar*/ false);
2853 NewRed = State.Builder.CreateIntrinsic(
2854 PrevInChain->getType(),
2855 Kind == RecurKind::Add ? Intrinsic::vector_partial_reduce_add
2856 : Intrinsic::vector_partial_reduce_fadd,
2857 {PrevInChain, NewVecOp}, State.Builder.getFastMathFlags(),
2858 "partial.reduce");
2859 PrevInChain = NewRed;
2860 NextInChain = NewRed;
2861 } else {
2862 assert(isInLoop() &&
2863 "The reduction must either be ordered, partial or in-loop");
2864 Value *PrevInChain = State.get(getChainOp(), /*IsScalar*/ true);
2865 NewRed = createSimpleReduction(State.Builder, NewVecOp, Kind);
2867 NextInChain = createMinMaxOp(State.Builder, Kind, NewRed, PrevInChain);
2868 else
2869 NextInChain = State.Builder.CreateBinOp(
2871 PrevInChain, NewRed);
2872 }
2873 State.set(this, NextInChain, /*IsScalar*/ !isPartialReduction());
2874}
2875
2877 assert(!State.Lane && "Reduction being replicated.");
2878
2879 auto &Builder = State.Builder;
2880 // Propagate the fast-math flags carried by the underlying instruction.
2881 IRBuilderBase::FastMathFlagGuard FMFGuard(Builder);
2882 Builder.setFastMathFlags(getFastMathFlags());
2883
2885 Value *Prev = State.get(getChainOp(), /*IsScalar*/ true);
2886 Value *VecOp = State.get(getVecOp());
2887 Value *EVL = State.get(getEVL(), VPLane(0));
2888
2889 Value *Mask;
2890 if (VPValue *CondOp = getCondOp())
2891 Mask = State.get(CondOp);
2892 else
2893 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
2894
2895 Value *NewRed;
2896 if (isOrdered()) {
2897 NewRed = createOrderedReduction(Builder, Kind, VecOp, Prev, Mask, EVL);
2898 } else {
2899 NewRed = createSimpleReduction(Builder, VecOp, Kind, Mask, EVL);
2901 NewRed = createMinMaxOp(Builder, Kind, NewRed, Prev);
2902 else
2903 NewRed = Builder.CreateBinOp(
2905 Prev);
2906 }
2907 State.set(this, NewRed, /*IsScalar*/ true);
2908}
2909
2911 VPCostContext &Ctx) const {
2912 RecurKind RdxKind = getRecurrenceKind();
2913 Type *ElementTy = Ctx.Types.inferScalarType(this);
2914 auto *VectorTy = cast<VectorType>(toVectorTy(ElementTy, VF));
2915 unsigned Opcode = RecurrenceDescriptor::getOpcode(RdxKind);
2917 std::optional<FastMathFlags> OptionalFMF =
2918 ElementTy->isFloatingPointTy() ? std::make_optional(FMFs) : std::nullopt;
2919
2920 if (isPartialReduction()) {
2921 InstructionCost CondCost = 0;
2922 if (isConditional()) {
2924 auto *CondTy = cast<VectorType>(
2925 toVectorTy(Ctx.Types.inferScalarType(getCondOp()), VF));
2926 CondCost = Ctx.TTI.getCmpSelInstrCost(Instruction::Select, VectorTy,
2927 CondTy, Pred, Ctx.CostKind);
2928 }
2929 return CondCost + Ctx.TTI.getPartialReductionCost(
2930 Opcode, ElementTy, ElementTy, ElementTy, VF,
2931 TTI::PR_None, TTI::PR_None, {}, Ctx.CostKind,
2932 OptionalFMF);
2933 }
2934
2935 // TODO: Support any-of reductions.
2936 assert(
2938 ForceTargetInstructionCost.getNumOccurrences() > 0) &&
2939 "Any-of reduction not implemented in VPlan-based cost model currently.");
2940
2941 // Note that TTI should model the cost of moving result to the scalar register
2942 // and the BinOp cost in the getMinMaxReductionCost().
2945 return Ctx.TTI.getMinMaxReductionCost(Id, VectorTy, FMFs, Ctx.CostKind);
2946 }
2947
2948 // Note that TTI should model the cost of moving result to the scalar register
2949 // and the BinOp cost in the getArithmeticReductionCost().
2950 return Ctx.TTI.getArithmeticReductionCost(Opcode, VectorTy, OptionalFMF,
2951 Ctx.CostKind);
2952}
2953
2954VPExpressionRecipe::VPExpressionRecipe(
2955 ExpressionTypes ExpressionType,
2956 ArrayRef<VPSingleDefRecipe *> ExpressionRecipes)
2957 : VPSingleDefRecipe(VPRecipeBase::VPExpressionSC, {}, {}),
2958 ExpressionRecipes(ExpressionRecipes), ExpressionType(ExpressionType) {
2959 assert(!ExpressionRecipes.empty() && "Nothing to combine?");
2960 assert(
2961 none_of(ExpressionRecipes,
2962 [](VPSingleDefRecipe *R) { return R->mayHaveSideEffects(); }) &&
2963 "expression cannot contain recipes with side-effects");
2964
2965 // Maintain a copy of the expression recipes as a set of users.
2966 SmallPtrSet<VPUser *, 4> ExpressionRecipesAsSetOfUsers;
2967 for (auto *R : ExpressionRecipes)
2968 ExpressionRecipesAsSetOfUsers.insert(R);
2969
2970 // Recipes in the expression, except the last one, must only be used by
2971 // (other) recipes inside the expression. If there are other users, external
2972 // to the expression, use a clone of the recipe for external users.
2973 for (VPSingleDefRecipe *R : reverse(ExpressionRecipes)) {
2974 if (R != ExpressionRecipes.back() &&
2975 any_of(R->users(), [&ExpressionRecipesAsSetOfUsers](VPUser *U) {
2976 return !ExpressionRecipesAsSetOfUsers.contains(U);
2977 })) {
2978 // There are users outside of the expression. Clone the recipe and use the
2979 // clone those external users.
2980 VPSingleDefRecipe *CopyForExtUsers = R->clone();
2981 R->replaceUsesWithIf(CopyForExtUsers, [&ExpressionRecipesAsSetOfUsers](
2982 VPUser &U, unsigned) {
2983 return !ExpressionRecipesAsSetOfUsers.contains(&U);
2984 });
2985 CopyForExtUsers->insertBefore(R);
2986 }
2987 if (R->getParent())
2988 R->removeFromParent();
2989 }
2990
2991 // Internalize all external operands to the expression recipes. To do so,
2992 // create new temporary VPValues for all operands defined by a recipe outside
2993 // the expression. The original operands are added as operands of the
2994 // VPExpressionRecipe itself.
2995 for (auto *R : ExpressionRecipes) {
2996 for (const auto &[Idx, Op] : enumerate(R->operands())) {
2997 auto *Def = Op->getDefiningRecipe();
2998 if (Def && ExpressionRecipesAsSetOfUsers.contains(Def))
2999 continue;
3000 addOperand(Op);
3001 LiveInPlaceholders.push_back(new VPSymbolicValue());
3002 }
3003 }
3004
3005 // Replace each external operand with the first one created for it in
3006 // LiveInPlaceholders.
3007 for (auto *R : ExpressionRecipes)
3008 for (auto const &[LiveIn, Tmp] : zip(operands(), LiveInPlaceholders))
3009 R->replaceUsesOfWith(LiveIn, Tmp);
3010}
3011
3013 for (auto *R : ExpressionRecipes)
3014 // Since the list could contain duplicates, make sure the recipe hasn't
3015 // already been inserted.
3016 if (!R->getParent())
3017 R->insertBefore(this);
3018
3019 for (const auto &[Idx, Op] : enumerate(operands()))
3020 LiveInPlaceholders[Idx]->replaceAllUsesWith(Op);
3021
3022 replaceAllUsesWith(ExpressionRecipes.back());
3023 ExpressionRecipes.clear();
3024}
3025
3027 VPCostContext &Ctx) const {
3028 Type *RedTy = Ctx.Types.inferScalarType(this);
3029 auto *SrcVecTy = cast<VectorType>(
3030 toVectorTy(Ctx.Types.inferScalarType(getOperand(0)), VF));
3031 unsigned Opcode = RecurrenceDescriptor::getOpcode(
3032 cast<VPReductionRecipe>(ExpressionRecipes.back())->getRecurrenceKind());
3033 switch (ExpressionType) {
3034 case ExpressionTypes::ExtendedReduction: {
3035 unsigned Opcode = RecurrenceDescriptor::getOpcode(
3036 cast<VPReductionRecipe>(ExpressionRecipes[1])->getRecurrenceKind());
3037 auto *ExtR = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3038 auto *RedR = cast<VPReductionRecipe>(ExpressionRecipes.back());
3039
3040 if (RedR->isPartialReduction())
3041 return Ctx.TTI.getPartialReductionCost(
3042 Opcode, Ctx.Types.inferScalarType(getOperand(0)), nullptr, RedTy, VF,
3044 TargetTransformInfo::PR_None, std::nullopt, Ctx.CostKind,
3045 RedTy->isFloatingPointTy() ? std::optional{RedR->getFastMathFlags()}
3046 : std::nullopt);
3047 else if (!RedTy->isFloatingPointTy())
3048 // TTI::getExtendedReductionCost only supports integer types.
3049 return Ctx.TTI.getExtendedReductionCost(
3050 Opcode, ExtR->getOpcode() == Instruction::ZExt, RedTy, SrcVecTy,
3051 std::nullopt, Ctx.CostKind);
3052 else
3054 }
3055 case ExpressionTypes::MulAccReduction:
3056 return Ctx.TTI.getMulAccReductionCost(false, Opcode, RedTy, SrcVecTy,
3057 Ctx.CostKind);
3058
3059 case ExpressionTypes::ExtNegatedMulAccReduction:
3060 assert(Opcode == Instruction::Add && "Unexpected opcode");
3061 Opcode = Instruction::Sub;
3062 [[fallthrough]];
3063 case ExpressionTypes::ExtMulAccReduction: {
3064 auto *RedR = cast<VPReductionRecipe>(ExpressionRecipes.back());
3065 if (RedR->isPartialReduction()) {
3066 auto *Ext0R = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3067 auto *Ext1R = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
3068 auto *Mul = cast<VPWidenRecipe>(ExpressionRecipes[2]);
3069 return Ctx.TTI.getPartialReductionCost(
3070 Opcode, Ctx.Types.inferScalarType(getOperand(0)),
3071 Ctx.Types.inferScalarType(getOperand(1)), RedTy, VF,
3073 Ext0R->getOpcode()),
3075 Ext1R->getOpcode()),
3076 Mul->getOpcode(), Ctx.CostKind,
3077 RedTy->isFloatingPointTy() ? std::optional{RedR->getFastMathFlags()}
3078 : std::nullopt);
3079 }
3080 return Ctx.TTI.getMulAccReductionCost(
3081 cast<VPWidenCastRecipe>(ExpressionRecipes.front())->getOpcode() ==
3082 Instruction::ZExt,
3083 Opcode, RedTy, SrcVecTy, Ctx.CostKind);
3084 }
3085 }
3086 llvm_unreachable("Unknown VPExpressionRecipe::ExpressionTypes enum");
3087}
3088
3090 return any_of(ExpressionRecipes, [](VPSingleDefRecipe *R) {
3091 return R->mayReadFromMemory() || R->mayWriteToMemory();
3092 });
3093}
3094
3096 assert(
3097 none_of(ExpressionRecipes,
3098 [](VPSingleDefRecipe *R) { return R->mayHaveSideEffects(); }) &&
3099 "expression cannot contain recipes with side-effects");
3100 return false;
3101}
3102
3104 // Cannot use vputils::isSingleScalar(), because all external operands
3105 // of the expression will be live-ins while bundled.
3106 auto *RR = dyn_cast<VPReductionRecipe>(ExpressionRecipes.back());
3107 return RR && !RR->isPartialReduction();
3108}
3109
3110#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3111
3113 VPSlotTracker &SlotTracker) const {
3114 O << Indent << "EXPRESSION ";
3116 O << " = ";
3117 auto *Red = cast<VPReductionRecipe>(ExpressionRecipes.back());
3118 unsigned Opcode = RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind());
3119
3120 switch (ExpressionType) {
3121 case ExpressionTypes::ExtendedReduction: {
3123 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
3124 O << Instruction::getOpcodeName(Opcode) << " (";
3126 Red->printFlags(O);
3127
3128 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3129 O << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
3130 << *Ext0->getResultType();
3131 if (Red->isConditional()) {
3132 O << ", ";
3133 Red->getCondOp()->printAsOperand(O, SlotTracker);
3134 }
3135 O << ")";
3136 break;
3137 }
3138 case ExpressionTypes::ExtNegatedMulAccReduction: {
3140 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
3142 RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind()))
3143 << " (sub (0, mul";
3144 auto *Mul = cast<VPWidenRecipe>(ExpressionRecipes[2]);
3145 Mul->printFlags(O);
3146 O << "(";
3148 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3149 O << " " << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
3150 << *Ext0->getResultType() << "), (";
3152 auto *Ext1 = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
3153 O << " " << Instruction::getOpcodeName(Ext1->getOpcode()) << " to "
3154 << *Ext1->getResultType() << ")";
3155 if (Red->isConditional()) {
3156 O << ", ";
3157 Red->getCondOp()->printAsOperand(O, SlotTracker);
3158 }
3159 O << "))";
3160 break;
3161 }
3162 case ExpressionTypes::MulAccReduction:
3163 case ExpressionTypes::ExtMulAccReduction: {
3165 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
3167 RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind()))
3168 << " (";
3169 O << "mul";
3170 bool IsExtended = ExpressionType == ExpressionTypes::ExtMulAccReduction;
3171 auto *Mul = cast<VPWidenRecipe>(IsExtended ? ExpressionRecipes[2]
3172 : ExpressionRecipes[0]);
3173 Mul->printFlags(O);
3174 if (IsExtended)
3175 O << "(";
3177 if (IsExtended) {
3178 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3179 O << " " << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
3180 << *Ext0->getResultType() << "), (";
3181 } else {
3182 O << ", ";
3183 }
3185 if (IsExtended) {
3186 auto *Ext1 = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
3187 O << " " << Instruction::getOpcodeName(Ext1->getOpcode()) << " to "
3188 << *Ext1->getResultType() << ")";
3189 }
3190 if (Red->isConditional()) {
3191 O << ", ";
3192 Red->getCondOp()->printAsOperand(O, SlotTracker);
3193 }
3194 O << ")";
3195 break;
3196 }
3197 }
3198}
3199
3201 VPSlotTracker &SlotTracker) const {
3202 if (isPartialReduction())
3203 O << Indent << "PARTIAL-REDUCE ";
3204 else
3205 O << Indent << "REDUCE ";
3207 O << " = ";
3209 O << " +";
3210 printFlags(O);
3211 O << " reduce."
3214 << " (";
3216 if (isConditional()) {
3217 O << ", ";
3219 }
3220 O << ")";
3221}
3222
3224 VPSlotTracker &SlotTracker) const {
3225 O << Indent << "REDUCE ";
3227 O << " = ";
3229 O << " +";
3230 printFlags(O);
3231 O << " vp.reduce."
3234 << " (";
3236 O << ", ";
3238 if (isConditional()) {
3239 O << ", ";
3241 }
3242 O << ")";
3243}
3244
3245#endif
3246
3247/// A helper function to scalarize a single Instruction in the innermost loop.
3248/// Generates a sequence of scalar instances for lane \p Lane. Uses the VPValue
3249/// operands from \p RepRecipe instead of \p Instr's operands.
3250static void scalarizeInstruction(const Instruction *Instr,
3251 VPReplicateRecipe *RepRecipe,
3252 const VPLane &Lane, VPTransformState &State) {
3253 assert((!Instr->getType()->isAggregateType() ||
3254 canVectorizeTy(Instr->getType())) &&
3255 "Expected vectorizable or non-aggregate type.");
3256
3257 // Does this instruction return a value ?
3258 bool IsVoidRetTy = Instr->getType()->isVoidTy();
3259
3260 Instruction *Cloned = Instr->clone();
3261 if (!IsVoidRetTy) {
3262 Cloned->setName(Instr->getName() + ".cloned");
3263 Type *ResultTy = State.TypeAnalysis.inferScalarType(RepRecipe);
3264 // The operands of the replicate recipe may have been narrowed, resulting in
3265 // a narrower result type. Update the type of the cloned instruction to the
3266 // correct type.
3267 if (ResultTy != Cloned->getType())
3268 Cloned->mutateType(ResultTy);
3269 }
3270
3271 RepRecipe->applyFlags(*Cloned);
3272 RepRecipe->applyMetadata(*Cloned);
3273
3274 if (RepRecipe->hasPredicate())
3275 cast<CmpInst>(Cloned)->setPredicate(RepRecipe->getPredicate());
3276
3277 if (auto DL = RepRecipe->getDebugLoc())
3278 State.setDebugLocFrom(DL);
3279
3280 // Replace the operands of the cloned instructions with their scalar
3281 // equivalents in the new loop.
3282 for (const auto &I : enumerate(RepRecipe->operands())) {
3283 auto InputLane = Lane;
3284 VPValue *Operand = I.value();
3285 if (vputils::isSingleScalar(Operand))
3286 InputLane = VPLane::getFirstLane();
3287 Cloned->setOperand(I.index(), State.get(Operand, InputLane));
3288 }
3289
3290 // Place the cloned scalar in the new loop.
3291 State.Builder.Insert(Cloned);
3292
3293 State.set(RepRecipe, Cloned, Lane);
3294
3295 // If we just cloned a new assumption, add it the assumption cache.
3296 if (auto *II = dyn_cast<AssumeInst>(Cloned))
3297 State.AC->registerAssumption(II);
3298
3299 assert(
3300 (RepRecipe->getRegion() ||
3301 !RepRecipe->getParent()->getPlan()->getVectorLoopRegion() ||
3302 all_of(RepRecipe->operands(),
3303 [](VPValue *Op) { return Op->isDefinedOutsideLoopRegions(); })) &&
3304 "Expected a recipe is either within a region or all of its operands "
3305 "are defined outside the vectorized region.");
3306}
3307
3310
3311 if (!State.Lane) {
3312 assert(IsSingleScalar && "VPReplicateRecipes outside replicate regions "
3313 "must have already been unrolled");
3314 scalarizeInstruction(UI, this, VPLane(0), State);
3315 return;
3316 }
3317
3318 assert((State.VF.isScalar() || !isSingleScalar()) &&
3319 "uniform recipe shouldn't be predicated");
3320 assert(!State.VF.isScalable() && "Can't scalarize a scalable vector");
3321 scalarizeInstruction(UI, this, *State.Lane, State);
3322 // Insert scalar instance packing it into a vector.
3323 if (State.VF.isVector() && shouldPack()) {
3324 Value *WideValue =
3325 State.Lane->isFirstLane()
3326 ? PoisonValue::get(toVectorizedTy(UI->getType(), State.VF))
3327 : State.get(this);
3328 State.set(this, State.packScalarIntoVectorizedValue(this, WideValue,
3329 *State.Lane));
3330 }
3331}
3332
3334 // Find if the recipe is used by a widened recipe via an intervening
3335 // VPPredInstPHIRecipe. In this case, also pack the scalar values in a vector.
3336 return any_of(users(), [](const VPUser *U) {
3337 if (auto *PredR = dyn_cast<VPPredInstPHIRecipe>(U))
3338 return !vputils::onlyScalarValuesUsed(PredR);
3339 return false;
3340 });
3341}
3342
3343/// Returns a SCEV expression for \p Ptr if it is a pointer computation for
3344/// which the legacy cost model computes a SCEV expression when computing the
3345/// address cost. Computing SCEVs for VPValues is incomplete and returns
3346/// SCEVCouldNotCompute in cases the legacy cost model can compute SCEVs. In
3347/// those cases we fall back to the legacy cost model. Otherwise return nullptr.
3348static const SCEV *getAddressAccessSCEV(const VPValue *Ptr,
3350 const Loop *L) {
3351 const SCEV *Addr = vputils::getSCEVExprForVPValue(Ptr, PSE, L);
3352 if (isa<SCEVCouldNotCompute>(Addr))
3353 return Addr;
3354
3355 return vputils::isAddressSCEVForCost(Addr, *PSE.getSE(), L) ? Addr : nullptr;
3356}
3357
3358/// Returns true if \p V is used as part of the address of another load or
3359/// store.
3360static bool isUsedByLoadStoreAddress(const VPUser *V) {
3362 SmallVector<const VPUser *> WorkList = {V};
3363
3364 while (!WorkList.empty()) {
3365 auto *Cur = dyn_cast<VPSingleDefRecipe>(WorkList.pop_back_val());
3366 if (!Cur || !Seen.insert(Cur).second)
3367 continue;
3368
3369 auto *Blend = dyn_cast<VPBlendRecipe>(Cur);
3370 // Skip blends that use V only through a compare by checking if any incoming
3371 // value was already visited.
3372 if (Blend && none_of(seq<unsigned>(0, Blend->getNumIncomingValues()),
3373 [&](unsigned I) {
3374 return Seen.contains(
3375 Blend->getIncomingValue(I)->getDefiningRecipe());
3376 }))
3377 continue;
3378
3379 for (VPUser *U : Cur->users()) {
3380 if (auto *InterleaveR = dyn_cast<VPInterleaveBase>(U))
3381 if (InterleaveR->getAddr() == Cur)
3382 return true;
3383 if (auto *RepR = dyn_cast<VPReplicateRecipe>(U)) {
3384 if (RepR->getOpcode() == Instruction::Load &&
3385 RepR->getOperand(0) == Cur)
3386 return true;
3387 if (RepR->getOpcode() == Instruction::Store &&
3388 RepR->getOperand(1) == Cur)
3389 return true;
3390 }
3391 if (auto *MemR = dyn_cast<VPWidenMemoryRecipe>(U)) {
3392 if (MemR->getAddr() == Cur && MemR->isConsecutive())
3393 return true;
3394 }
3395 }
3396
3397 // The legacy cost model only supports scalarization loads/stores with phi
3398 // addresses, if the phi is directly used as load/store address. Don't
3399 // traverse further for Blends.
3400 if (Blend)
3401 continue;
3402
3403 append_range(WorkList, Cur->users());
3404 }
3405 return false;
3406}
3407
3408/// Return true if \p R is a predicated load/store with a loop-invariant address
3409/// only masked by the header mask.
3411 const SCEV *PtrSCEV,
3412 VPCostContext &Ctx) {
3413 const VPRegionBlock *ParentRegion = R.getRegion();
3414 if (!ParentRegion || !ParentRegion->isReplicator() || !PtrSCEV ||
3415 !Ctx.PSE.getSE()->isLoopInvariant(PtrSCEV, Ctx.L))
3416 return false;
3417 auto *BOM =
3419 return vputils::isHeaderMask(BOM->getOperand(0), *ParentRegion->getPlan());
3420}
3421
3423 VPCostContext &Ctx) const {
3425 // VPReplicateRecipe may be cloned as part of an existing VPlan-to-VPlan
3426 // transform, avoid computing their cost multiple times for now.
3427 Ctx.SkipCostComputation.insert(UI);
3428
3429 if (VF.isScalable() && !isSingleScalar())
3431
3432 switch (UI->getOpcode()) {
3433 case Instruction::Alloca:
3434 if (VF.isScalable())
3436 return Ctx.TTI.getArithmeticInstrCost(
3437 Instruction::Mul, Ctx.Types.inferScalarType(this), Ctx.CostKind);
3438 case Instruction::GetElementPtr:
3439 // We mark this instruction as zero-cost because the cost of GEPs in
3440 // vectorized code depends on whether the corresponding memory instruction
3441 // is scalarized or not. Therefore, we handle GEPs with the memory
3442 // instruction cost.
3443 return 0;
3444 case Instruction::Call: {
3445 auto *CalledFn =
3447
3450 for (const VPValue *ArgOp : ArgOps)
3451 Tys.push_back(Ctx.Types.inferScalarType(ArgOp));
3452
3453 if (CalledFn->isIntrinsic())
3454 // Various pseudo-intrinsics with costs of 0 are scalarized instead of
3455 // vectorized via VPWidenIntrinsicRecipe. Return 0 for them early.
3456 switch (CalledFn->getIntrinsicID()) {
3457 case Intrinsic::assume:
3458 case Intrinsic::lifetime_end:
3459 case Intrinsic::lifetime_start:
3460 case Intrinsic::sideeffect:
3461 case Intrinsic::pseudoprobe:
3462 case Intrinsic::experimental_noalias_scope_decl: {
3463 assert(getCostForIntrinsics(CalledFn->getIntrinsicID(), ArgOps, *this,
3464 ElementCount::getFixed(1), Ctx) == 0 &&
3465 "scalarizing intrinsic should be free");
3466 return InstructionCost(0);
3467 }
3468 default:
3469 break;
3470 }
3471
3472 Type *ResultTy = Ctx.Types.inferScalarType(this);
3473 InstructionCost ScalarCallCost =
3474 Ctx.TTI.getCallInstrCost(CalledFn, ResultTy, Tys, Ctx.CostKind);
3475 if (isSingleScalar()) {
3476 if (CalledFn->isIntrinsic())
3477 ScalarCallCost = std::min(
3478 ScalarCallCost,
3479 getCostForIntrinsics(CalledFn->getIntrinsicID(), ArgOps, *this,
3480 ElementCount::getFixed(1), Ctx));
3481 return ScalarCallCost;
3482 }
3483
3484 return ScalarCallCost * VF.getFixedValue() +
3485 Ctx.getScalarizationOverhead(ResultTy, ArgOps, VF);
3486 }
3487 case Instruction::Add:
3488 case Instruction::Sub:
3489 case Instruction::FAdd:
3490 case Instruction::FSub:
3491 case Instruction::Mul:
3492 case Instruction::FMul:
3493 case Instruction::FDiv:
3494 case Instruction::FRem:
3495 case Instruction::Shl:
3496 case Instruction::LShr:
3497 case Instruction::AShr:
3498 case Instruction::And:
3499 case Instruction::Or:
3500 case Instruction::Xor:
3501 case Instruction::ICmp:
3502 case Instruction::FCmp:
3504 Ctx) *
3505 (isSingleScalar() ? 1 : VF.getFixedValue());
3506 case Instruction::SDiv:
3507 case Instruction::UDiv:
3508 case Instruction::SRem:
3509 case Instruction::URem: {
3510 InstructionCost ScalarCost =
3512 if (isSingleScalar())
3513 return ScalarCost;
3514
3515 // If any of the operands is from a different replicate region and has its
3516 // cost skipped, it may have been forced to scalar. Fall back to legacy cost
3517 // model to avoid cost mis-match.
3518 if (any_of(operands(), [&Ctx, VF](VPValue *Op) {
3519 auto *PredR = dyn_cast<VPPredInstPHIRecipe>(Op);
3520 if (!PredR)
3521 return false;
3522 return Ctx.skipCostComputation(
3524 PredR->getOperand(0)->getUnderlyingValue()),
3525 VF.isVector());
3526 }))
3527 break;
3528
3529 ScalarCost = ScalarCost * VF.getFixedValue() +
3530 Ctx.getScalarizationOverhead(Ctx.Types.inferScalarType(this),
3531 to_vector(operands()), VF);
3532 // If the recipe is not predicated (i.e. not in a replicate region), return
3533 // the scalar cost. Otherwise handle predicated cost.
3534 if (!getRegion()->isReplicator())
3535 return ScalarCost;
3536
3537 // Account for the phi nodes that we will create.
3538 ScalarCost += VF.getFixedValue() *
3539 Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
3540 // Scale the cost by the probability of executing the predicated blocks.
3541 // This assumes the predicated block for each vector lane is equally
3542 // likely.
3543 ScalarCost /= Ctx.getPredBlockCostDivisor(UI->getParent());
3544 return ScalarCost;
3545 }
3546 case Instruction::Load:
3547 case Instruction::Store: {
3548 bool IsLoad = UI->getOpcode() == Instruction::Load;
3549 const VPValue *PtrOp = getOperand(!IsLoad);
3550 const SCEV *PtrSCEV = getAddressAccessSCEV(PtrOp, Ctx.PSE, Ctx.L);
3552 break;
3553
3554 Type *ValTy = Ctx.Types.inferScalarType(IsLoad ? this : getOperand(0));
3555 Type *ScalarPtrTy = Ctx.Types.inferScalarType(PtrOp);
3556 const Align Alignment = getLoadStoreAlignment(UI);
3557 unsigned AS = cast<PointerType>(ScalarPtrTy)->getAddressSpace();
3559 bool PreferVectorizedAddressing = Ctx.TTI.prefersVectorizedAddressing();
3560 bool UsedByLoadStoreAddress =
3561 !PreferVectorizedAddressing && isUsedByLoadStoreAddress(this);
3562 InstructionCost ScalarMemOpCost = Ctx.TTI.getMemoryOpCost(
3563 UI->getOpcode(), ValTy, Alignment, AS, Ctx.CostKind, OpInfo,
3564 UsedByLoadStoreAddress ? UI : nullptr);
3565
3566 // Check if this is a predicated load/store with a loop-invariant address
3567 // only masked by the header mask. If so, return the uniform mem op cost.
3568 if (isPredicatedUniformMemOpAfterTailFolding(*this, PtrSCEV, Ctx)) {
3569 InstructionCost UniformCost =
3570 ScalarMemOpCost +
3571 Ctx.TTI.getAddressComputationCost(ScalarPtrTy, /*SE=*/nullptr,
3572 /*Ptr=*/nullptr, Ctx.CostKind);
3573 auto *VectorTy = cast<VectorType>(toVectorTy(ValTy, VF));
3574 if (IsLoad) {
3575 return UniformCost +
3576 Ctx.TTI.getShuffleCost(TargetTransformInfo::SK_Broadcast,
3577 VectorTy, VectorTy, {}, Ctx.CostKind);
3578 }
3579
3580 VPValue *StoredVal = getOperand(0);
3581 if (!StoredVal->isDefinedOutsideLoopRegions())
3582 UniformCost += Ctx.TTI.getIndexedVectorInstrCostFromEnd(
3583 Instruction::ExtractElement, VectorTy, Ctx.CostKind, 0);
3584 return UniformCost;
3585 }
3586
3587 Type *PtrTy = isSingleScalar() ? ScalarPtrTy : toVectorTy(ScalarPtrTy, VF);
3588 InstructionCost ScalarCost =
3589 ScalarMemOpCost +
3590 Ctx.TTI.getAddressComputationCost(
3591 PtrTy, UsedByLoadStoreAddress ? nullptr : Ctx.PSE.getSE(), PtrSCEV,
3592 Ctx.CostKind);
3593 if (isSingleScalar())
3594 return ScalarCost;
3595
3596 SmallVector<const VPValue *> OpsToScalarize;
3597 Type *ResultTy = Type::getVoidTy(PtrTy->getContext());
3598 // Set ResultTy and OpsToScalarize, if scalarization is needed. Currently we
3599 // don't assign scalarization overhead in general, if the target prefers
3600 // vectorized addressing or the loaded value is used as part of an address
3601 // of another load or store.
3602 if (!UsedByLoadStoreAddress) {
3603 bool EfficientVectorLoadStore =
3604 Ctx.TTI.supportsEfficientVectorElementLoadStore();
3605 if (!(IsLoad && !PreferVectorizedAddressing) &&
3606 !(!IsLoad && EfficientVectorLoadStore))
3607 append_range(OpsToScalarize, operands());
3608
3609 if (!EfficientVectorLoadStore)
3610 ResultTy = Ctx.Types.inferScalarType(this);
3611 }
3612
3616 (ScalarCost * VF.getFixedValue()) +
3617 Ctx.getScalarizationOverhead(ResultTy, OpsToScalarize, VF, VIC, true);
3618
3619 const VPRegionBlock *ParentRegion = getRegion();
3620 if (ParentRegion && ParentRegion->isReplicator()) {
3621 if (!PtrSCEV)
3622 break;
3623 Cost /= Ctx.getPredBlockCostDivisor(UI->getParent());
3624 Cost += Ctx.TTI.getCFInstrCost(Instruction::CondBr, Ctx.CostKind);
3625
3626 auto *VecI1Ty = VectorType::get(
3627 IntegerType::getInt1Ty(Ctx.L->getHeader()->getContext()), VF);
3628 Cost += Ctx.TTI.getScalarizationOverhead(
3629 VecI1Ty, APInt::getAllOnes(VF.getFixedValue()),
3630 /*Insert=*/false, /*Extract=*/true, Ctx.CostKind);
3631
3632 if (Ctx.useEmulatedMaskMemRefHack(this, VF)) {
3633 // Artificially setting to a high enough value to practically disable
3634 // vectorization with such operations.
3635 return 3000000;
3636 }
3637 }
3638 return Cost;
3639 }
3640 case Instruction::SExt:
3641 case Instruction::ZExt:
3642 case Instruction::FPToUI:
3643 case Instruction::FPToSI:
3644 case Instruction::FPExt:
3645 case Instruction::PtrToInt:
3646 case Instruction::PtrToAddr:
3647 case Instruction::IntToPtr:
3648 case Instruction::SIToFP:
3649 case Instruction::UIToFP:
3650 case Instruction::Trunc:
3651 case Instruction::FPTrunc:
3652 case Instruction::Select:
3653 case Instruction::AddrSpaceCast: {
3655 Ctx) *
3656 (isSingleScalar() ? 1 : VF.getFixedValue());
3657 }
3658 case Instruction::ExtractValue:
3659 case Instruction::InsertValue:
3660 return Ctx.TTI.getInsertExtractValueCost(getOpcode(), Ctx.CostKind);
3661 }
3662
3663 return Ctx.getLegacyCost(UI, VF);
3664}
3665
3666#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3668 VPSlotTracker &SlotTracker) const {
3669 O << Indent << (IsSingleScalar ? "CLONE " : "REPLICATE ");
3670
3671 if (!getUnderlyingInstr()->getType()->isVoidTy()) {
3673 O << " = ";
3674 }
3675 if (auto *CB = dyn_cast<CallBase>(getUnderlyingInstr())) {
3676 O << "call";
3677 printFlags(O);
3678 O << "@" << CB->getCalledFunction()->getName() << "(";
3680 O, [&O, &SlotTracker](VPValue *Op) {
3681 Op->printAsOperand(O, SlotTracker);
3682 });
3683 O << ")";
3684 } else {
3686 printFlags(O);
3688 }
3689
3690 if (shouldPack())
3691 O << " (S->V)";
3692}
3693#endif
3694
3696 assert(State.Lane && "Branch on Mask works only on single instance.");
3697
3698 VPValue *BlockInMask = getOperand(0);
3699 Value *ConditionBit = State.get(BlockInMask, *State.Lane);
3700
3701 // Replace the temporary unreachable terminator with a new conditional branch,
3702 // whose two destinations will be set later when they are created.
3703 auto *CurrentTerminator = State.CFG.PrevBB->getTerminator();
3704 assert(isa<UnreachableInst>(CurrentTerminator) &&
3705 "Expected to replace unreachable terminator with conditional branch.");
3706 auto CondBr =
3707 State.Builder.CreateCondBr(ConditionBit, State.CFG.PrevBB, nullptr);
3708 CondBr->setSuccessor(0, nullptr);
3709 CurrentTerminator->eraseFromParent();
3710}
3711
3713 VPCostContext &Ctx) const {
3714 // The legacy cost model doesn't assign costs to branches for individual
3715 // replicate regions. Match the current behavior in the VPlan cost model for
3716 // now.
3717 return 0;
3718}
3719
3721 assert(State.Lane && "Predicated instruction PHI works per instance.");
3722 Instruction *ScalarPredInst =
3723 cast<Instruction>(State.get(getOperand(0), *State.Lane));
3724 BasicBlock *PredicatedBB = ScalarPredInst->getParent();
3725 BasicBlock *PredicatingBB = PredicatedBB->getSinglePredecessor();
3726 assert(PredicatingBB && "Predicated block has no single predecessor.");
3728 "operand must be VPReplicateRecipe");
3729
3730 // By current pack/unpack logic we need to generate only a single phi node: if
3731 // a vector value for the predicated instruction exists at this point it means
3732 // the instruction has vector users only, and a phi for the vector value is
3733 // needed. In this case the recipe of the predicated instruction is marked to
3734 // also do that packing, thereby "hoisting" the insert-element sequence.
3735 // Otherwise, a phi node for the scalar value is needed.
3736 if (State.hasVectorValue(getOperand(0))) {
3737 auto *VecI = cast<Instruction>(State.get(getOperand(0)));
3739 "Packed operands must generate an insertelement or insertvalue");
3740
3741 // If VectorI is a struct, it will be a sequence like:
3742 // %1 = insertvalue %unmodified, %x, 0
3743 // %2 = insertvalue %1, %y, 1
3744 // %VectorI = insertvalue %2, %z, 2
3745 // To get the unmodified vector we need to look through the chain.
3746 if (auto *StructTy = dyn_cast<StructType>(VecI->getType()))
3747 for (unsigned I = 0; I < StructTy->getNumContainedTypes() - 1; I++)
3748 VecI = cast<InsertValueInst>(VecI->getOperand(0));
3749
3750 PHINode *VPhi = State.Builder.CreatePHI(VecI->getType(), 2);
3751 VPhi->addIncoming(VecI->getOperand(0), PredicatingBB); // Unmodified vector.
3752 VPhi->addIncoming(VecI, PredicatedBB); // New vector with inserted element.
3753 if (State.hasVectorValue(this))
3754 State.reset(this, VPhi);
3755 else
3756 State.set(this, VPhi);
3757 // NOTE: Currently we need to update the value of the operand, so the next
3758 // predicated iteration inserts its generated value in the correct vector.
3759 State.reset(getOperand(0), VPhi);
3760 } else {
3761 if (vputils::onlyFirstLaneUsed(this) && !State.Lane->isFirstLane())
3762 return;
3763
3764 Type *PredInstType = State.TypeAnalysis.inferScalarType(getOperand(0));
3765 PHINode *Phi = State.Builder.CreatePHI(PredInstType, 2);
3766 Phi->addIncoming(PoisonValue::get(ScalarPredInst->getType()),
3767 PredicatingBB);
3768 Phi->addIncoming(ScalarPredInst, PredicatedBB);
3769 if (State.hasScalarValue(this, *State.Lane))
3770 State.reset(this, Phi, *State.Lane);
3771 else
3772 State.set(this, Phi, *State.Lane);
3773 // NOTE: Currently we need to update the value of the operand, so the next
3774 // predicated iteration inserts its generated value in the correct vector.
3775 State.reset(getOperand(0), Phi, *State.Lane);
3776 }
3777}
3778
3779#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3781 VPSlotTracker &SlotTracker) const {
3782 O << Indent << "PHI-PREDICATED-INSTRUCTION ";
3784 O << " = ";
3786}
3787#endif
3788
3790 VPCostContext &Ctx) const {
3792 unsigned AS = cast<PointerType>(Ctx.Types.inferScalarType(getAddr()))
3793 ->getAddressSpace();
3794 unsigned Opcode = isa<VPWidenLoadRecipe, VPWidenLoadEVLRecipe>(this)
3795 ? Instruction::Load
3796 : Instruction::Store;
3797
3798 if (!Consecutive) {
3799 // TODO: Using the original IR may not be accurate.
3800 // Currently, ARM will use the underlying IR to calculate gather/scatter
3801 // instruction cost.
3802 assert(!Reverse &&
3803 "Inconsecutive memory access should not have the order.");
3804
3806 Type *PtrTy = Ptr->getType();
3807
3808 // If the address value is uniform across all lanes, then the address can be
3809 // calculated with scalar type and broadcast.
3811 PtrTy = toVectorTy(PtrTy, VF);
3812
3813 unsigned IID = isa<VPWidenLoadRecipe>(this) ? Intrinsic::masked_gather
3814 : isa<VPWidenStoreRecipe>(this) ? Intrinsic::masked_scatter
3815 : isa<VPWidenLoadEVLRecipe>(this) ? Intrinsic::vp_gather
3816 : Intrinsic::vp_scatter;
3817 return Ctx.TTI.getAddressComputationCost(PtrTy, nullptr, nullptr,
3818 Ctx.CostKind) +
3819 Ctx.TTI.getMemIntrinsicInstrCost(
3821 &Ingredient),
3822 Ctx.CostKind);
3823 }
3824
3826 if (IsMasked) {
3827 unsigned IID = isa<VPWidenLoadRecipe>(this) ? Intrinsic::masked_load
3828 : Intrinsic::masked_store;
3829 Cost += Ctx.TTI.getMemIntrinsicInstrCost(
3830 MemIntrinsicCostAttributes(IID, Ty, Alignment, AS), Ctx.CostKind);
3831 } else {
3832 TTI::OperandValueInfo OpInfo = Ctx.getOperandInfo(
3834 : getOperand(1));
3835 Cost += Ctx.TTI.getMemoryOpCost(Opcode, Ty, Alignment, AS, Ctx.CostKind,
3836 OpInfo, &Ingredient);
3837 }
3838 return Cost;
3839}
3840
3842 Type *ScalarDataTy = getLoadStoreType(&Ingredient);
3843 auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
3844 bool CreateGather = !isConsecutive();
3845
3846 auto &Builder = State.Builder;
3847 Value *Mask = nullptr;
3848 if (auto *VPMask = getMask()) {
3849 // Mask reversal is only needed for non-all-one (null) masks, as reverse
3850 // of a null all-one mask is a null mask.
3851 Mask = State.get(VPMask);
3852 if (isReverse())
3853 Mask = Builder.CreateVectorReverse(Mask, "reverse");
3854 }
3855
3856 Value *Addr = State.get(getAddr(), /*IsScalar*/ !CreateGather);
3857 Value *NewLI;
3858 if (CreateGather) {
3859 NewLI = Builder.CreateMaskedGather(DataTy, Addr, Alignment, Mask, nullptr,
3860 "wide.masked.gather");
3861 } else if (Mask) {
3862 NewLI =
3863 Builder.CreateMaskedLoad(DataTy, Addr, Alignment, Mask,
3864 PoisonValue::get(DataTy), "wide.masked.load");
3865 } else {
3866 NewLI = Builder.CreateAlignedLoad(DataTy, Addr, Alignment, "wide.load");
3867 }
3869 State.set(this, NewLI);
3870}
3871
3872#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3874 VPSlotTracker &SlotTracker) const {
3875 O << Indent << "WIDEN ";
3877 O << " = load ";
3879}
3880#endif
3881
3882/// Use all-true mask for reverse rather than actual mask, as it avoids a
3883/// dependence w/o affecting the result.
3885 Value *EVL, const Twine &Name) {
3886 VectorType *ValTy = cast<VectorType>(Operand->getType());
3887 Value *AllTrueMask =
3888 Builder.CreateVectorSplat(ValTy->getElementCount(), Builder.getTrue());
3889 return Builder.CreateIntrinsic(ValTy, Intrinsic::experimental_vp_reverse,
3890 {Operand, AllTrueMask, EVL}, nullptr, Name);
3891}
3892
3894 Type *ScalarDataTy = getLoadStoreType(&Ingredient);
3895 auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
3896 bool CreateGather = !isConsecutive();
3897
3898 auto &Builder = State.Builder;
3899 CallInst *NewLI;
3900 Value *EVL = State.get(getEVL(), VPLane(0));
3901 Value *Addr = State.get(getAddr(), !CreateGather);
3902 Value *Mask = nullptr;
3903 if (VPValue *VPMask = getMask()) {
3904 Mask = State.get(VPMask);
3905 if (isReverse())
3906 Mask = createReverseEVL(Builder, Mask, EVL, "vp.reverse.mask");
3907 } else {
3908 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
3909 }
3910
3911 if (CreateGather) {
3912 NewLI =
3913 Builder.CreateIntrinsic(DataTy, Intrinsic::vp_gather, {Addr, Mask, EVL},
3914 nullptr, "wide.masked.gather");
3915 } else {
3916 NewLI = Builder.CreateIntrinsic(DataTy, Intrinsic::vp_load,
3917 {Addr, Mask, EVL}, nullptr, "vp.op.load");
3918 }
3919 NewLI->addParamAttr(
3921 applyMetadata(*NewLI);
3922 Instruction *Res = NewLI;
3923 State.set(this, Res);
3924}
3925
3927 VPCostContext &Ctx) const {
3928 if (!Consecutive || IsMasked)
3929 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
3930
3931 // We need to use the getMemIntrinsicInstrCost() instead of getMemoryOpCost()
3932 // here because the EVL recipes using EVL to replace the tail mask. But in the
3933 // legacy model, it will always calculate the cost of mask.
3934 // TODO: Using getMemoryOpCost() instead of getMemIntrinsicInstrCost when we
3935 // don't need to compare to the legacy cost model.
3937 unsigned AS = cast<PointerType>(Ctx.Types.inferScalarType(getAddr()))
3938 ->getAddressSpace();
3939 return Ctx.TTI.getMemIntrinsicInstrCost(
3940 MemIntrinsicCostAttributes(Intrinsic::vp_load, Ty, Alignment, AS),
3941 Ctx.CostKind);
3942}
3943
3944#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3946 VPSlotTracker &SlotTracker) const {
3947 O << Indent << "WIDEN ";
3949 O << " = vp.load ";
3951}
3952#endif
3953
3955 VPValue *StoredVPValue = getStoredValue();
3956 bool CreateScatter = !isConsecutive();
3957
3958 auto &Builder = State.Builder;
3959
3960 Value *Mask = nullptr;
3961 if (auto *VPMask = getMask()) {
3962 // Mask reversal is only needed for non-all-one (null) masks, as reverse
3963 // of a null all-one mask is a null mask.
3964 Mask = State.get(VPMask);
3965 if (isReverse())
3966 Mask = Builder.CreateVectorReverse(Mask, "reverse");
3967 }
3968
3969 Value *StoredVal = State.get(StoredVPValue);
3970 Value *Addr = State.get(getAddr(), /*IsScalar*/ !CreateScatter);
3971 Instruction *NewSI = nullptr;
3972 if (CreateScatter)
3973 NewSI = Builder.CreateMaskedScatter(StoredVal, Addr, Alignment, Mask);
3974 else if (Mask)
3975 NewSI = Builder.CreateMaskedStore(StoredVal, Addr, Alignment, Mask);
3976 else
3977 NewSI = Builder.CreateAlignedStore(StoredVal, Addr, Alignment);
3978 applyMetadata(*NewSI);
3979}
3980
3981#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3983 VPSlotTracker &SlotTracker) const {
3984 O << Indent << "WIDEN store ";
3986}
3987#endif
3988
3990 VPValue *StoredValue = getStoredValue();
3991 bool CreateScatter = !isConsecutive();
3992
3993 auto &Builder = State.Builder;
3994
3995 CallInst *NewSI = nullptr;
3996 Value *StoredVal = State.get(StoredValue);
3997 Value *EVL = State.get(getEVL(), VPLane(0));
3998 Value *Mask = nullptr;
3999 if (VPValue *VPMask = getMask()) {
4000 Mask = State.get(VPMask);
4001 if (isReverse())
4002 Mask = createReverseEVL(Builder, Mask, EVL, "vp.reverse.mask");
4003 } else {
4004 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
4005 }
4006 Value *Addr = State.get(getAddr(), !CreateScatter);
4007 if (CreateScatter) {
4008 NewSI = Builder.CreateIntrinsic(Type::getVoidTy(EVL->getContext()),
4009 Intrinsic::vp_scatter,
4010 {StoredVal, Addr, Mask, EVL});
4011 } else {
4012 NewSI = Builder.CreateIntrinsic(Type::getVoidTy(EVL->getContext()),
4013 Intrinsic::vp_store,
4014 {StoredVal, Addr, Mask, EVL});
4015 }
4016 NewSI->addParamAttr(
4018 applyMetadata(*NewSI);
4019}
4020
4022 VPCostContext &Ctx) const {
4023 if (!Consecutive || IsMasked)
4024 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
4025
4026 // We need to use the getMemIntrinsicInstrCost() instead of getMemoryOpCost()
4027 // here because the EVL recipes using EVL to replace the tail mask. But in the
4028 // legacy model, it will always calculate the cost of mask.
4029 // TODO: Using getMemoryOpCost() instead of getMemIntrinsicInstrCost when we
4030 // don't need to compare to the legacy cost model.
4032 unsigned AS = cast<PointerType>(Ctx.Types.inferScalarType(getAddr()))
4033 ->getAddressSpace();
4034 return Ctx.TTI.getMemIntrinsicInstrCost(
4035 MemIntrinsicCostAttributes(Intrinsic::vp_store, Ty, Alignment, AS),
4036 Ctx.CostKind);
4037}
4038
4039#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4041 VPSlotTracker &SlotTracker) const {
4042 O << Indent << "WIDEN vp.store ";
4044}
4045#endif
4046
4048 VectorType *DstVTy, const DataLayout &DL) {
4049 // Verify that V is a vector type with same number of elements as DstVTy.
4050 auto VF = DstVTy->getElementCount();
4051 auto *SrcVecTy = cast<VectorType>(V->getType());
4052 assert(VF == SrcVecTy->getElementCount() && "Vector dimensions do not match");
4053 Type *SrcElemTy = SrcVecTy->getElementType();
4054 Type *DstElemTy = DstVTy->getElementType();
4055 assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&
4056 "Vector elements must have same size");
4057
4058 // Do a direct cast if element types are castable.
4059 if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
4060 return Builder.CreateBitOrPointerCast(V, DstVTy);
4061 }
4062 // V cannot be directly casted to desired vector type.
4063 // May happen when V is a floating point vector but DstVTy is a vector of
4064 // pointers or vice-versa. Handle this using a two-step bitcast using an
4065 // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
4066 assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&
4067 "Only one type should be a pointer type");
4068 assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&
4069 "Only one type should be a floating point type");
4070 Type *IntTy =
4071 IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy));
4072 auto *VecIntTy = VectorType::get(IntTy, VF);
4073 Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
4074 return Builder.CreateBitOrPointerCast(CastVal, DstVTy);
4075}
4076
4077/// Return a vector containing interleaved elements from multiple
4078/// smaller input vectors.
4080 const Twine &Name) {
4081 unsigned Factor = Vals.size();
4082 assert(Factor > 1 && "Tried to interleave invalid number of vectors");
4083
4084 VectorType *VecTy = cast<VectorType>(Vals[0]->getType());
4085#ifndef NDEBUG
4086 for (Value *Val : Vals)
4087 assert(Val->getType() == VecTy && "Tried to interleave mismatched types");
4088#endif
4089
4090 // Scalable vectors cannot use arbitrary shufflevectors (only splats), so
4091 // must use intrinsics to interleave.
4092 if (VecTy->isScalableTy()) {
4093 assert(Factor <= 8 && "Unsupported interleave factor for scalable vectors");
4094 return Builder.CreateVectorInterleave(Vals, Name);
4095 }
4096
4097 // Fixed length. Start by concatenating all vectors into a wide vector.
4098 Value *WideVec = concatenateVectors(Builder, Vals);
4099
4100 // Interleave the elements into the wide vector.
4101 const unsigned NumElts = VecTy->getElementCount().getFixedValue();
4102 return Builder.CreateShuffleVector(
4103 WideVec, createInterleaveMask(NumElts, Factor), Name);
4104}
4105
4106// Try to vectorize the interleave group that \p Instr belongs to.
4107//
4108// E.g. Translate following interleaved load group (factor = 3):
4109// for (i = 0; i < N; i+=3) {
4110// R = Pic[i]; // Member of index 0
4111// G = Pic[i+1]; // Member of index 1
4112// B = Pic[i+2]; // Member of index 2
4113// ... // do something to R, G, B
4114// }
4115// To:
4116// %wide.vec = load <12 x i32> ; Read 4 tuples of R,G,B
4117// %R.vec = shuffle %wide.vec, poison, <0, 3, 6, 9> ; R elements
4118// %G.vec = shuffle %wide.vec, poison, <1, 4, 7, 10> ; G elements
4119// %B.vec = shuffle %wide.vec, poison, <2, 5, 8, 11> ; B elements
4120//
4121// Or translate following interleaved store group (factor = 3):
4122// for (i = 0; i < N; i+=3) {
4123// ... do something to R, G, B
4124// Pic[i] = R; // Member of index 0
4125// Pic[i+1] = G; // Member of index 1
4126// Pic[i+2] = B; // Member of index 2
4127// }
4128// To:
4129// %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
4130// %B_U.vec = shuffle %B.vec, poison, <0, 1, 2, 3, u, u, u, u>
4131// %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
4132// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> ; Interleave R,G,B elements
4133// store <12 x i32> %interleaved.vec ; Write 4 tuples of R,G,B
4135 assert(!State.Lane && "Interleave group being replicated.");
4136 assert((!needsMaskForGaps() || !State.VF.isScalable()) &&
4137 "Masking gaps for scalable vectors is not yet supported.");
4139 Instruction *Instr = Group->getInsertPos();
4140
4141 // Prepare for the vector type of the interleaved load/store.
4142 Type *ScalarTy = getLoadStoreType(Instr);
4143 unsigned InterleaveFactor = Group->getFactor();
4144 auto *VecTy = VectorType::get(ScalarTy, State.VF * InterleaveFactor);
4145
4146 VPValue *BlockInMask = getMask();
4147 VPValue *Addr = getAddr();
4148 Value *ResAddr = State.get(Addr, VPLane(0));
4149
4150 auto CreateGroupMask = [&BlockInMask, &State,
4151 &InterleaveFactor](Value *MaskForGaps) -> Value * {
4152 if (State.VF.isScalable()) {
4153 assert(!MaskForGaps && "Interleaved groups with gaps are not supported.");
4154 assert(InterleaveFactor <= 8 &&
4155 "Unsupported deinterleave factor for scalable vectors");
4156 auto *ResBlockInMask = State.get(BlockInMask);
4157 SmallVector<Value *> Ops(InterleaveFactor, ResBlockInMask);
4158 return interleaveVectors(State.Builder, Ops, "interleaved.mask");
4159 }
4160
4161 if (!BlockInMask)
4162 return MaskForGaps;
4163
4164 Value *ResBlockInMask = State.get(BlockInMask);
4165 Value *ShuffledMask = State.Builder.CreateShuffleVector(
4166 ResBlockInMask,
4167 createReplicatedMask(InterleaveFactor, State.VF.getFixedValue()),
4168 "interleaved.mask");
4169 return MaskForGaps ? State.Builder.CreateBinOp(Instruction::And,
4170 ShuffledMask, MaskForGaps)
4171 : ShuffledMask;
4172 };
4173
4174 const DataLayout &DL = Instr->getDataLayout();
4175 // Vectorize the interleaved load group.
4176 if (isa<LoadInst>(Instr)) {
4177 Value *MaskForGaps = nullptr;
4178 if (needsMaskForGaps()) {
4179 MaskForGaps =
4180 createBitMaskForGaps(State.Builder, State.VF.getFixedValue(), *Group);
4181 assert(MaskForGaps && "Mask for Gaps is required but it is null");
4182 }
4183
4184 Instruction *NewLoad;
4185 if (BlockInMask || MaskForGaps) {
4186 Value *GroupMask = CreateGroupMask(MaskForGaps);
4187 Value *PoisonVec = PoisonValue::get(VecTy);
4188 NewLoad = State.Builder.CreateMaskedLoad(VecTy, ResAddr,
4189 Group->getAlign(), GroupMask,
4190 PoisonVec, "wide.masked.vec");
4191 } else
4192 NewLoad = State.Builder.CreateAlignedLoad(VecTy, ResAddr,
4193 Group->getAlign(), "wide.vec");
4194 applyMetadata(*NewLoad);
4195 // TODO: Also manage existing metadata using VPIRMetadata.
4196 Group->addMetadata(NewLoad);
4197
4199 if (VecTy->isScalableTy()) {
4200 // Scalable vectors cannot use arbitrary shufflevectors (only splats),
4201 // so must use intrinsics to deinterleave.
4202 assert(InterleaveFactor <= 8 &&
4203 "Unsupported deinterleave factor for scalable vectors");
4204 NewLoad = State.Builder.CreateIntrinsic(
4205 Intrinsic::getDeinterleaveIntrinsicID(InterleaveFactor),
4206 NewLoad->getType(), NewLoad,
4207 /*FMFSource=*/nullptr, "strided.vec");
4208 }
4209
4210 auto CreateStridedVector = [&InterleaveFactor, &State,
4211 &NewLoad](unsigned Index) -> Value * {
4212 assert(Index < InterleaveFactor && "Illegal group index");
4213 if (State.VF.isScalable())
4214 return State.Builder.CreateExtractValue(NewLoad, Index);
4215
4216 // For fixed length VF, use shuffle to extract the sub-vectors from the
4217 // wide load.
4218 auto StrideMask =
4219 createStrideMask(Index, InterleaveFactor, State.VF.getFixedValue());
4220 return State.Builder.CreateShuffleVector(NewLoad, StrideMask,
4221 "strided.vec");
4222 };
4223
4224 for (unsigned I = 0, J = 0; I < InterleaveFactor; ++I) {
4225 Instruction *Member = Group->getMember(I);
4226
4227 // Skip the gaps in the group.
4228 if (!Member)
4229 continue;
4230
4231 Value *StridedVec = CreateStridedVector(I);
4232
4233 // If this member has different type, cast the result type.
4234 if (Member->getType() != ScalarTy) {
4235 VectorType *OtherVTy = VectorType::get(Member->getType(), State.VF);
4236 StridedVec =
4237 createBitOrPointerCast(State.Builder, StridedVec, OtherVTy, DL);
4238 }
4239
4240 if (Group->isReverse())
4241 StridedVec = State.Builder.CreateVectorReverse(StridedVec, "reverse");
4242
4243 State.set(VPDefs[J], StridedVec);
4244 ++J;
4245 }
4246 return;
4247 }
4248
4249 // The sub vector type for current instruction.
4250 auto *SubVT = VectorType::get(ScalarTy, State.VF);
4251
4252 // Vectorize the interleaved store group.
4253 Value *MaskForGaps =
4254 createBitMaskForGaps(State.Builder, State.VF.getKnownMinValue(), *Group);
4255 assert(((MaskForGaps != nullptr) == needsMaskForGaps()) &&
4256 "Mismatch between NeedsMaskForGaps and MaskForGaps");
4257 ArrayRef<VPValue *> StoredValues = getStoredValues();
4258 // Collect the stored vector from each member.
4259 SmallVector<Value *, 4> StoredVecs;
4260 unsigned StoredIdx = 0;
4261 for (unsigned i = 0; i < InterleaveFactor; i++) {
4262 assert((Group->getMember(i) || MaskForGaps) &&
4263 "Fail to get a member from an interleaved store group");
4264 Instruction *Member = Group->getMember(i);
4265
4266 // Skip the gaps in the group.
4267 if (!Member) {
4268 Value *Undef = PoisonValue::get(SubVT);
4269 StoredVecs.push_back(Undef);
4270 continue;
4271 }
4272
4273 Value *StoredVec = State.get(StoredValues[StoredIdx]);
4274 ++StoredIdx;
4275
4276 if (Group->isReverse())
4277 StoredVec = State.Builder.CreateVectorReverse(StoredVec, "reverse");
4278
4279 // If this member has different type, cast it to a unified type.
4280
4281 if (StoredVec->getType() != SubVT)
4282 StoredVec = createBitOrPointerCast(State.Builder, StoredVec, SubVT, DL);
4283
4284 StoredVecs.push_back(StoredVec);
4285 }
4286
4287 // Interleave all the smaller vectors into one wider vector.
4288 Value *IVec = interleaveVectors(State.Builder, StoredVecs, "interleaved.vec");
4289 Instruction *NewStoreInstr;
4290 if (BlockInMask || MaskForGaps) {
4291 Value *GroupMask = CreateGroupMask(MaskForGaps);
4292 NewStoreInstr = State.Builder.CreateMaskedStore(
4293 IVec, ResAddr, Group->getAlign(), GroupMask);
4294 } else
4295 NewStoreInstr =
4296 State.Builder.CreateAlignedStore(IVec, ResAddr, Group->getAlign());
4297
4298 applyMetadata(*NewStoreInstr);
4299 // TODO: Also manage existing metadata using VPIRMetadata.
4300 Group->addMetadata(NewStoreInstr);
4301}
4302
4303#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4305 VPSlotTracker &SlotTracker) const {
4307 O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << " at ";
4308 IG->getInsertPos()->printAsOperand(O, false);
4309 O << ", ";
4311 VPValue *Mask = getMask();
4312 if (Mask) {
4313 O << ", ";
4314 Mask->printAsOperand(O, SlotTracker);
4315 }
4316
4317 unsigned OpIdx = 0;
4318 for (unsigned i = 0; i < IG->getFactor(); ++i) {
4319 if (!IG->getMember(i))
4320 continue;
4321 if (getNumStoreOperands() > 0) {
4322 O << "\n" << Indent << " store ";
4324 O << " to index " << i;
4325 } else {
4326 O << "\n" << Indent << " ";
4328 O << " = load from index " << i;
4329 }
4330 ++OpIdx;
4331 }
4332}
4333#endif
4334
4336 assert(!State.Lane && "Interleave group being replicated.");
4337 assert(State.VF.isScalable() &&
4338 "Only support scalable VF for EVL tail-folding.");
4340 "Masking gaps for scalable vectors is not yet supported.");
4342 Instruction *Instr = Group->getInsertPos();
4343
4344 // Prepare for the vector type of the interleaved load/store.
4345 Type *ScalarTy = getLoadStoreType(Instr);
4346 unsigned InterleaveFactor = Group->getFactor();
4347 assert(InterleaveFactor <= 8 &&
4348 "Unsupported deinterleave/interleave factor for scalable vectors");
4349 ElementCount WideVF = State.VF * InterleaveFactor;
4350 auto *VecTy = VectorType::get(ScalarTy, WideVF);
4351
4352 VPValue *Addr = getAddr();
4353 Value *ResAddr = State.get(Addr, VPLane(0));
4354 Value *EVL = State.get(getEVL(), VPLane(0));
4355 Value *InterleaveEVL = State.Builder.CreateMul(
4356 EVL, ConstantInt::get(EVL->getType(), InterleaveFactor), "interleave.evl",
4357 /* NUW= */ true, /* NSW= */ true);
4358 LLVMContext &Ctx = State.Builder.getContext();
4359
4360 Value *GroupMask = nullptr;
4361 if (VPValue *BlockInMask = getMask()) {
4362 SmallVector<Value *> Ops(InterleaveFactor, State.get(BlockInMask));
4363 GroupMask = interleaveVectors(State.Builder, Ops, "interleaved.mask");
4364 } else {
4365 GroupMask =
4366 State.Builder.CreateVectorSplat(WideVF, State.Builder.getTrue());
4367 }
4368
4369 // Vectorize the interleaved load group.
4370 if (isa<LoadInst>(Instr)) {
4371 CallInst *NewLoad = State.Builder.CreateIntrinsic(
4372 VecTy, Intrinsic::vp_load, {ResAddr, GroupMask, InterleaveEVL}, nullptr,
4373 "wide.vp.load");
4374 NewLoad->addParamAttr(0,
4375 Attribute::getWithAlignment(Ctx, Group->getAlign()));
4376
4377 applyMetadata(*NewLoad);
4378 // TODO: Also manage existing metadata using VPIRMetadata.
4379 Group->addMetadata(NewLoad);
4380
4381 // Scalable vectors cannot use arbitrary shufflevectors (only splats),
4382 // so must use intrinsics to deinterleave.
4383 NewLoad = State.Builder.CreateIntrinsic(
4384 Intrinsic::getDeinterleaveIntrinsicID(InterleaveFactor),
4385 NewLoad->getType(), NewLoad,
4386 /*FMFSource=*/nullptr, "strided.vec");
4387
4388 const DataLayout &DL = Instr->getDataLayout();
4389 for (unsigned I = 0, J = 0; I < InterleaveFactor; ++I) {
4390 Instruction *Member = Group->getMember(I);
4391 // Skip the gaps in the group.
4392 if (!Member)
4393 continue;
4394
4395 Value *StridedVec = State.Builder.CreateExtractValue(NewLoad, I);
4396 // If this member has different type, cast the result type.
4397 if (Member->getType() != ScalarTy) {
4398 VectorType *OtherVTy = VectorType::get(Member->getType(), State.VF);
4399 StridedVec =
4400 createBitOrPointerCast(State.Builder, StridedVec, OtherVTy, DL);
4401 }
4402
4403 State.set(getVPValue(J), StridedVec);
4404 ++J;
4405 }
4406 return;
4407 } // End for interleaved load.
4408
4409 // The sub vector type for current instruction.
4410 auto *SubVT = VectorType::get(ScalarTy, State.VF);
4411 // Vectorize the interleaved store group.
4412 ArrayRef<VPValue *> StoredValues = getStoredValues();
4413 // Collect the stored vector from each member.
4414 SmallVector<Value *, 4> StoredVecs;
4415 const DataLayout &DL = Instr->getDataLayout();
4416 for (unsigned I = 0, StoredIdx = 0; I < InterleaveFactor; I++) {
4417 Instruction *Member = Group->getMember(I);
4418 // Skip the gaps in the group.
4419 if (!Member) {
4420 StoredVecs.push_back(PoisonValue::get(SubVT));
4421 continue;
4422 }
4423
4424 Value *StoredVec = State.get(StoredValues[StoredIdx]);
4425 // If this member has different type, cast it to a unified type.
4426 if (StoredVec->getType() != SubVT)
4427 StoredVec = createBitOrPointerCast(State.Builder, StoredVec, SubVT, DL);
4428
4429 StoredVecs.push_back(StoredVec);
4430 ++StoredIdx;
4431 }
4432
4433 // Interleave all the smaller vectors into one wider vector.
4434 Value *IVec = interleaveVectors(State.Builder, StoredVecs, "interleaved.vec");
4435 CallInst *NewStore =
4436 State.Builder.CreateIntrinsic(Type::getVoidTy(Ctx), Intrinsic::vp_store,
4437 {IVec, ResAddr, GroupMask, InterleaveEVL});
4438 NewStore->addParamAttr(1,
4439 Attribute::getWithAlignment(Ctx, Group->getAlign()));
4440
4441 applyMetadata(*NewStore);
4442 // TODO: Also manage existing metadata using VPIRMetadata.
4443 Group->addMetadata(NewStore);
4444}
4445
4446#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4448 VPSlotTracker &SlotTracker) const {
4450 O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << " at ";
4451 IG->getInsertPos()->printAsOperand(O, false);
4452 O << ", ";
4454 O << ", ";
4456 if (VPValue *Mask = getMask()) {
4457 O << ", ";
4458 Mask->printAsOperand(O, SlotTracker);
4459 }
4460
4461 unsigned OpIdx = 0;
4462 for (unsigned i = 0; i < IG->getFactor(); ++i) {
4463 if (!IG->getMember(i))
4464 continue;
4465 if (getNumStoreOperands() > 0) {
4466 O << "\n" << Indent << " vp.store ";
4468 O << " to index " << i;
4469 } else {
4470 O << "\n" << Indent << " ";
4472 O << " = vp.load from index " << i;
4473 }
4474 ++OpIdx;
4475 }
4476}
4477#endif
4478
4480 VPCostContext &Ctx) const {
4481 Instruction *InsertPos = getInsertPos();
4482 // Find the VPValue index of the interleave group. We need to skip gaps.
4483 unsigned InsertPosIdx = 0;
4484 for (unsigned Idx = 0; IG->getFactor(); ++Idx)
4485 if (auto *Member = IG->getMember(Idx)) {
4486 if (Member == InsertPos)
4487 break;
4488 InsertPosIdx++;
4489 }
4490 Type *ValTy = Ctx.Types.inferScalarType(
4491 getNumDefinedValues() > 0 ? getVPValue(InsertPosIdx)
4492 : getStoredValues()[InsertPosIdx]);
4493 auto *VectorTy = cast<VectorType>(toVectorTy(ValTy, VF));
4494 unsigned AS = cast<PointerType>(Ctx.Types.inferScalarType(getAddr()))
4495 ->getAddressSpace();
4496
4497 unsigned InterleaveFactor = IG->getFactor();
4498 auto *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
4499
4500 // Holds the indices of existing members in the interleaved group.
4502 for (unsigned IF = 0; IF < InterleaveFactor; IF++)
4503 if (IG->getMember(IF))
4504 Indices.push_back(IF);
4505
4506 // Calculate the cost of the whole interleaved group.
4507 InstructionCost Cost = Ctx.TTI.getInterleavedMemoryOpCost(
4508 InsertPos->getOpcode(), WideVecTy, IG->getFactor(), Indices,
4509 IG->getAlign(), AS, Ctx.CostKind, getMask(), NeedsMaskForGaps);
4510
4511 if (!IG->isReverse())
4512 return Cost;
4513
4514 return Cost + IG->getNumMembers() *
4515 Ctx.TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
4516 VectorTy, VectorTy, {}, Ctx.CostKind,
4517 0);
4518}
4519
4520#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4522 VPSlotTracker &SlotTracker) const {
4523 O << Indent << "EMIT ";
4525 O << " = CANONICAL-INDUCTION ";
4527}
4528#endif
4529
4531 return vputils::onlyScalarValuesUsed(this) &&
4532 (!IsScalable || vputils::onlyFirstLaneUsed(this));
4533}
4534
4535#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4537 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
4538 assert((getNumOperands() == 3 || getNumOperands() == 5) &&
4539 "unexpected number of operands");
4540 O << Indent << "EMIT ";
4542 O << " = WIDEN-POINTER-INDUCTION ";
4544 O << ", ";
4546 O << ", ";
4548 if (getNumOperands() == 5) {
4549 O << ", ";
4551 O << ", ";
4553 }
4554}
4555
4557 VPSlotTracker &SlotTracker) const {
4558 O << Indent << "EMIT ";
4560 O << " = EXPAND SCEV " << *Expr;
4561}
4562#endif
4563
4565 Value *CanonicalIV = State.get(getOperand(0), /*IsScalar*/ true);
4566 Type *STy = CanonicalIV->getType();
4567 IRBuilder<> Builder(State.CFG.PrevBB->getTerminator());
4568 ElementCount VF = State.VF;
4569 Value *VStart = VF.isScalar()
4570 ? CanonicalIV
4571 : Builder.CreateVectorSplat(VF, CanonicalIV, "broadcast");
4572 Value *VStep = Builder.CreateElementCount(
4573 STy, VF.multiplyCoefficientBy(getUnrollPart(*this)));
4574 if (VF.isVector()) {
4575 VStep = Builder.CreateVectorSplat(VF, VStep);
4576 VStep =
4577 Builder.CreateAdd(VStep, Builder.CreateStepVector(VStep->getType()));
4578 }
4579 Value *CanonicalVectorIV = Builder.CreateAdd(VStart, VStep, "vec.iv");
4580 State.set(this, CanonicalVectorIV);
4581}
4582
4583#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4585 VPSlotTracker &SlotTracker) const {
4586 O << Indent << "EMIT ";
4588 O << " = WIDEN-CANONICAL-INDUCTION ";
4590}
4591#endif
4592
4594 auto &Builder = State.Builder;
4595 // Create a vector from the initial value.
4596 auto *VectorInit = getStartValue()->getLiveInIRValue();
4597
4598 Type *VecTy = State.VF.isScalar()
4599 ? VectorInit->getType()
4600 : VectorType::get(VectorInit->getType(), State.VF);
4601
4602 BasicBlock *VectorPH =
4603 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
4604 if (State.VF.isVector()) {
4605 auto *IdxTy = Builder.getInt32Ty();
4606 auto *One = ConstantInt::get(IdxTy, 1);
4607 IRBuilder<>::InsertPointGuard Guard(Builder);
4608 Builder.SetInsertPoint(VectorPH->getTerminator());
4609 auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, State.VF);
4610 auto *LastIdx = Builder.CreateSub(RuntimeVF, One);
4611 VectorInit = Builder.CreateInsertElement(
4612 PoisonValue::get(VecTy), VectorInit, LastIdx, "vector.recur.init");
4613 }
4614
4615 // Create a phi node for the new recurrence.
4616 PHINode *Phi = PHINode::Create(VecTy, 2, "vector.recur");
4617 Phi->insertBefore(State.CFG.PrevBB->getFirstInsertionPt());
4618 Phi->addIncoming(VectorInit, VectorPH);
4619 State.set(this, Phi);
4620}
4621
4624 VPCostContext &Ctx) const {
4625 if (VF.isScalar())
4626 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
4627
4628 return 0;
4629}
4630
4631#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4633 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
4634 O << Indent << "FIRST-ORDER-RECURRENCE-PHI ";
4636 O << " = phi ";
4638}
4639#endif
4640
4642 // Reductions do not have to start at zero. They can start with
4643 // any loop invariant values.
4644 VPValue *StartVPV = getStartValue();
4645
4646 // In order to support recurrences we need to be able to vectorize Phi nodes.
4647 // Phi nodes have cycles, so we need to vectorize them in two stages. This is
4648 // stage #1: We create a new vector PHI node with no incoming edges. We'll use
4649 // this value when we vectorize all of the instructions that use the PHI.
4650 BasicBlock *VectorPH =
4651 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
4652 bool ScalarPHI = State.VF.isScalar() || isInLoop();
4653 Value *StartV = State.get(StartVPV, ScalarPHI);
4654 Type *VecTy = StartV->getType();
4655
4656 BasicBlock *HeaderBB = State.CFG.PrevBB;
4657 assert(State.CurrentParentLoop->getHeader() == HeaderBB &&
4658 "recipe must be in the vector loop header");
4659 auto *Phi = PHINode::Create(VecTy, 2, "vec.phi");
4660 Phi->insertBefore(HeaderBB->getFirstInsertionPt());
4661 State.set(this, Phi, isInLoop());
4662
4663 Phi->addIncoming(StartV, VectorPH);
4664}
4665
4666#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4668 VPSlotTracker &SlotTracker) const {
4669 O << Indent << "WIDEN-REDUCTION-PHI ";
4670
4672 O << " = phi";
4673 printFlags(O);
4675 if (getVFScaleFactor() > 1)
4676 O << " (VF scaled by 1/" << getVFScaleFactor() << ")";
4677}
4678#endif
4679
4681 Value *Op0 = State.get(getOperand(0));
4682 Type *VecTy = Op0->getType();
4683 Instruction *VecPhi = State.Builder.CreatePHI(VecTy, 2, Name);
4684 State.set(this, VecPhi);
4685}
4686
4688 VPCostContext &Ctx) const {
4689 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
4690}
4691
4692#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4694 VPSlotTracker &SlotTracker) const {
4695 O << Indent << "WIDEN-PHI ";
4696
4698 O << " = phi ";
4700}
4701#endif
4702
4704 BasicBlock *VectorPH =
4705 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
4706 Value *StartMask = State.get(getOperand(0));
4707 PHINode *Phi =
4708 State.Builder.CreatePHI(StartMask->getType(), 2, "active.lane.mask");
4709 Phi->addIncoming(StartMask, VectorPH);
4710 State.set(this, Phi);
4711}
4712
4713#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4715 VPSlotTracker &SlotTracker) const {
4716 O << Indent << "ACTIVE-LANE-MASK-PHI ";
4717
4719 O << " = phi ";
4721}
4722#endif
4723
4724#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4726 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
4727 O << Indent << "CURRENT-ITERATION-PHI ";
4728
4730 O << " = phi ";
4732}
4733#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:851
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:255
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:393
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:258
void mutateType(Type *Ty)
Mutate the type of this Value to be of the specified type.
Definition Value.h:816
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:318
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()
auto 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
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