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"
23#include "llvm/ADT/Twine.h"
28#include "llvm/IR/BasicBlock.h"
29#include "llvm/IR/IRBuilder.h"
30#include "llvm/IR/Instruction.h"
32#include "llvm/IR/Intrinsics.h"
33#include "llvm/IR/Type.h"
34#include "llvm/IR/Value.h"
37#include "llvm/Support/Debug.h"
41#include <cassert>
42
43using namespace llvm;
44using namespace llvm::VPlanPatternMatch;
45
47
48#define LV_NAME "loop-vectorize"
49#define DEBUG_TYPE LV_NAME
50
52 switch (getVPRecipeID()) {
53 case VPExpressionSC:
54 return cast<VPExpressionRecipe>(this)->mayReadOrWriteMemory();
55 case VPInstructionSC: {
56 auto *VPI = cast<VPInstruction>(this);
57 // Loads read from memory but don't write to memory.
58 if (VPI->getOpcode() == Instruction::Load)
59 return false;
60 return VPI->opcodeMayReadOrWriteFromMemory();
61 }
62 case VPInterleaveEVLSC:
63 case VPInterleaveSC:
64 return cast<VPInterleaveBase>(this)->getNumStoreOperands() > 0;
65 case VPWidenStoreEVLSC:
66 case VPWidenStoreSC:
67 return true;
68 case VPReplicateSC:
69 return cast<Instruction>(getVPSingleValue()->getUnderlyingValue())
70 ->mayWriteToMemory();
71 case VPWidenCallSC:
72 return !cast<VPWidenCallRecipe>(this)
73 ->getCalledScalarFunction()
74 ->onlyReadsMemory();
75 case VPWidenMemIntrinsicSC:
76 case VPWidenIntrinsicSC:
77 return cast<VPWidenIntrinsicRecipe>(this)->mayWriteToMemory();
78 case VPActiveLaneMaskPHISC:
79 case VPCurrentIterationPHISC:
80 case VPBranchOnMaskSC:
81 case VPDerivedIVSC:
82 case VPFirstOrderRecurrencePHISC:
83 case VPReductionPHISC:
84 case VPScalarIVStepsSC:
85 case VPPredInstPHISC:
86 return false;
87 case VPBlendSC:
88 case VPReductionEVLSC:
89 case VPReductionSC:
90 case VPVectorPointerSC:
91 case VPWidenCanonicalIVSC:
92 case VPWidenCastSC:
93 case VPWidenGEPSC:
94 case VPWidenIntOrFpInductionSC:
95 case VPWidenLoadEVLSC:
96 case VPWidenLoadSC:
97 case VPWidenPHISC:
98 case VPWidenPointerInductionSC:
99 case VPWidenSC: {
100 const Instruction *I =
101 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
102 (void)I;
103 assert((!I || !I->mayWriteToMemory()) &&
104 "underlying instruction may write to memory");
105 return false;
106 }
107 default:
108 return true;
109 }
110}
111
113 switch (getVPRecipeID()) {
114 case VPExpressionSC:
115 return cast<VPExpressionRecipe>(this)->mayReadOrWriteMemory();
116 case VPInstructionSC:
117 return cast<VPInstruction>(this)->opcodeMayReadOrWriteFromMemory();
118 case VPWidenLoadEVLSC:
119 case VPWidenLoadSC:
120 return true;
121 case VPReplicateSC:
122 return cast<Instruction>(getVPSingleValue()->getUnderlyingValue())
123 ->mayReadFromMemory();
124 case VPWidenCallSC:
125 return !cast<VPWidenCallRecipe>(this)
126 ->getCalledScalarFunction()
127 ->onlyWritesMemory();
128 case VPWidenMemIntrinsicSC:
129 case VPWidenIntrinsicSC:
130 return cast<VPWidenIntrinsicRecipe>(this)->mayReadFromMemory();
131 case VPBranchOnMaskSC:
132 case VPDerivedIVSC:
133 case VPCurrentIterationPHISC:
134 case VPFirstOrderRecurrencePHISC:
135 case VPReductionPHISC:
136 case VPPredInstPHISC:
137 case VPScalarIVStepsSC:
138 case VPWidenStoreEVLSC:
139 case VPWidenStoreSC:
140 return false;
141 case VPBlendSC:
142 case VPReductionEVLSC:
143 case VPReductionSC:
144 case VPVectorPointerSC:
145 case VPWidenCanonicalIVSC:
146 case VPWidenCastSC:
147 case VPWidenGEPSC:
148 case VPWidenIntOrFpInductionSC:
149 case VPWidenPHISC:
150 case VPWidenPointerInductionSC:
151 case VPWidenSC: {
152 const Instruction *I =
153 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
154 (void)I;
155 assert((!I || !I->mayReadFromMemory()) &&
156 "underlying instruction may read from memory");
157 return false;
158 }
159 default:
160 // FIXME: Return false if the recipe represents an interleaved store.
161 return true;
162 }
163}
164
166 switch (getVPRecipeID()) {
167 case VPExpressionSC:
168 return cast<VPExpressionRecipe>(this)->mayHaveSideEffects();
169 case VPActiveLaneMaskPHISC:
170 case VPDerivedIVSC:
171 case VPCurrentIterationPHISC:
172 case VPFirstOrderRecurrencePHISC:
173 case VPReductionPHISC:
174 case VPPredInstPHISC:
175 case VPVectorEndPointerSC:
176 return false;
177 case VPInstructionSC: {
178 auto *VPI = cast<VPInstruction>(this);
179 return mayWriteToMemory() ||
180 VPI->getOpcode() == VPInstruction::BranchOnCount ||
181 VPI->getOpcode() == VPInstruction::BranchOnCond ||
182 VPI->getOpcode() == VPInstruction::BranchOnTwoConds;
183 }
184 case VPWidenCallSC: {
185 Function *Fn = cast<VPWidenCallRecipe>(this)->getCalledScalarFunction();
186 return mayWriteToMemory() || !Fn->doesNotThrow() || !Fn->willReturn();
187 }
188 case VPWidenMemIntrinsicSC:
189 case VPWidenIntrinsicSC:
190 return cast<VPWidenIntrinsicRecipe>(this)->mayHaveSideEffects();
191 case VPBlendSC:
192 case VPReductionEVLSC:
193 case VPReductionSC:
194 case VPScalarIVStepsSC:
195 case VPVectorPointerSC:
196 case VPWidenCanonicalIVSC:
197 case VPWidenCastSC:
198 case VPWidenGEPSC:
199 case VPWidenIntOrFpInductionSC:
200 case VPWidenPHISC:
201 case VPWidenPointerInductionSC:
202 case VPWidenSC: {
203 const Instruction *I =
204 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
205 (void)I;
206 assert((!I || !I->mayHaveSideEffects()) &&
207 "underlying instruction has side-effects");
208 return false;
209 }
210 case VPInterleaveEVLSC:
211 case VPInterleaveSC:
212 return mayWriteToMemory();
213 case VPWidenLoadEVLSC:
214 case VPWidenLoadSC:
215 case VPWidenStoreEVLSC:
216 case VPWidenStoreSC:
217 assert(
218 cast<VPWidenMemoryRecipe>(this)->getIngredient().mayHaveSideEffects() ==
220 "mayHaveSideffects result for ingredient differs from this "
221 "implementation");
222 return mayWriteToMemory();
223 case VPReplicateSC: {
224 auto *R = cast<VPReplicateRecipe>(this);
225 return R->getUnderlyingInstr()->mayHaveSideEffects();
226 }
227 default:
228 return true;
229 }
230}
231
233 switch (getVPRecipeID()) {
234 default:
235 return false;
236 case VPInstructionSC: {
237 unsigned Opcode = cast<VPInstruction>(this)->getOpcode();
238 if (Instruction::isCast(Opcode))
239 return true;
240
241 switch (Opcode) {
242 default:
243 return false;
244 case Instruction::Add:
245 case Instruction::Sub:
246 case Instruction::Mul:
247 case Instruction::GetElementPtr:
248 return true;
249 }
250 }
251 }
252}
253
255 assert(!Parent && "Recipe already in some VPBasicBlock");
256 assert(InsertPos->getParent() &&
257 "Insertion position not in any VPBasicBlock");
258 InsertPos->getParent()->insert(this, InsertPos->getIterator());
259}
260
261void VPRecipeBase::insertBefore(VPBasicBlock &BB,
263 assert(!Parent && "Recipe already in some VPBasicBlock");
264 assert(I == BB.end() || I->getParent() == &BB);
265 BB.insert(this, I);
266}
267
269 assert(!Parent && "Recipe already in some VPBasicBlock");
270 assert(InsertPos->getParent() &&
271 "Insertion position not in any VPBasicBlock");
272 InsertPos->getParent()->insert(this, std::next(InsertPos->getIterator()));
273}
274
276 assert(getParent() && "Recipe not in any VPBasicBlock");
278 Parent = nullptr;
279}
280
282 assert(getParent() && "Recipe not in any VPBasicBlock");
284}
285
288 insertAfter(InsertPos);
289}
290
296
298 // Get the underlying instruction for the recipe, if there is one. It is used
299 // to
300 // * decide if cost computation should be skipped for this recipe,
301 // * apply forced target instruction cost.
302 Instruction *UI = nullptr;
303 if (auto *S = dyn_cast<VPSingleDefRecipe>(this))
304 UI = dyn_cast_or_null<Instruction>(S->getUnderlyingValue());
305 else if (auto *IG = dyn_cast<VPInterleaveBase>(this))
306 UI = IG->getInsertPos();
307 else if (auto *WidenMem = dyn_cast<VPWidenMemoryRecipe>(this))
308 UI = &WidenMem->getIngredient();
309
310 InstructionCost RecipeCost;
311 if (UI && Ctx.skipCostComputation(UI, VF.isVector())) {
312 RecipeCost = 0;
313 } else {
314 RecipeCost = computeCost(VF, Ctx);
315 if (ForceTargetInstructionCost.getNumOccurrences() > 0 &&
316 RecipeCost.isValid()) {
317 if (UI)
319 else
320 RecipeCost = InstructionCost(0);
321 }
322 }
323
324 LLVM_DEBUG({
325 dbgs() << "Cost of " << RecipeCost << " for VF " << VF << ": ";
326 dump();
327 });
328 return RecipeCost;
329}
330
332 VPCostContext &Ctx) const {
333 llvm_unreachable("subclasses should implement computeCost");
334}
335
337 return (getVPRecipeID() >= VPFirstPHISC && getVPRecipeID() <= VPLastPHISC) ||
339}
340
342 assert(OpType == Other.OpType && "OpType must match");
343 switch (OpType) {
344 case OperationType::OverflowingBinOp:
345 WrapFlags.HasNUW &= Other.WrapFlags.HasNUW;
346 WrapFlags.HasNSW &= Other.WrapFlags.HasNSW;
347 break;
348 case OperationType::Trunc:
349 TruncFlags.HasNUW &= Other.TruncFlags.HasNUW;
350 TruncFlags.HasNSW &= Other.TruncFlags.HasNSW;
351 break;
352 case OperationType::DisjointOp:
353 DisjointFlags.IsDisjoint &= Other.DisjointFlags.IsDisjoint;
354 break;
355 case OperationType::PossiblyExactOp:
356 ExactFlags.IsExact &= Other.ExactFlags.IsExact;
357 break;
358 case OperationType::GEPOp:
359 GEPFlagsStorage &= Other.GEPFlagsStorage;
360 break;
361 case OperationType::FPMathOp:
362 case OperationType::FCmp:
363 assert((OpType != OperationType::FCmp ||
364 FCmpFlags.CmpPredStorage == Other.FCmpFlags.CmpPredStorage) &&
365 "Cannot drop CmpPredicate");
366 getFMFsRef().NoNaNs &= Other.getFMFsRef().NoNaNs;
367 getFMFsRef().NoInfs &= Other.getFMFsRef().NoInfs;
368 break;
369 case OperationType::NonNegOp:
370 NonNegFlags.NonNeg &= Other.NonNegFlags.NonNeg;
371 break;
372 case OperationType::Cmp:
373 assert(CmpPredStorage == Other.CmpPredStorage &&
374 "Cannot drop CmpPredicate");
375 break;
376 case OperationType::ReductionOp:
377 assert(ReductionFlags.Kind == Other.ReductionFlags.Kind &&
378 "Cannot change RecurKind");
379 assert(ReductionFlags.IsOrdered == Other.ReductionFlags.IsOrdered &&
380 "Cannot change IsOrdered");
381 assert(ReductionFlags.IsInLoop == Other.ReductionFlags.IsInLoop &&
382 "Cannot change IsInLoop");
383 getFMFsRef().NoNaNs &= Other.getFMFsRef().NoNaNs;
384 getFMFsRef().NoInfs &= Other.getFMFsRef().NoInfs;
385 break;
386 case OperationType::Other:
387 break;
388 }
389}
390
392 assert((OpType == OperationType::FPMathOp || OpType == OperationType::FCmp ||
393 OpType == OperationType::ReductionOp ||
394 OpType == OperationType::Other) &&
395 "recipe doesn't have fast math flags");
396 if (OpType == OperationType::Other)
397 return FastMathFlags();
398 const FastMathFlagsTy &F = getFMFsRef();
399 FastMathFlags Res;
400 Res.setAllowReassoc(F.AllowReassoc);
401 Res.setNoNaNs(F.NoNaNs);
402 Res.setNoInfs(F.NoInfs);
403 Res.setNoSignedZeros(F.NoSignedZeros);
404 Res.setAllowReciprocal(F.AllowReciprocal);
405 Res.setAllowContract(F.AllowContract);
406 Res.setApproxFunc(F.ApproxFunc);
407 return Res;
408}
409
410#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
412
413void VPRecipeBase::print(raw_ostream &O, const Twine &Indent,
414 VPSlotTracker &SlotTracker) const {
415 printRecipe(O, Indent, SlotTracker);
416 if (auto DL = getDebugLoc()) {
417 O << ", !dbg ";
418 DL.print(O);
419 }
420
421 if (auto *Metadata = dyn_cast<VPIRMetadata>(this))
423}
424#endif
425
427 if (Type *Ty = V->getScalarType())
428 return Ty;
429 auto *Recipe = V->getDefiningRecipe();
430 assert(Recipe && Recipe->getParent() &&
431 "operand without scalar type must be a recipe in a plan");
432 VPTypeAnalysis TypeInfo(*Recipe->getParent()->getPlan());
433 return TypeInfo.inferScalarType(V);
434}
435
437 : VPSingleDefRecipe(VPRecipeBase::VPExpandSCEVSC, {}, Expr->getType()),
438 Expr(Expr) {}
439
441 const VPIRFlags &Flags, const VPIRMetadata &MD,
442 DebugLoc DL, const Twine &Name)
443 : VPRecipeWithIRFlags(VPRecipeBase::VPInstructionSC, Operands, Flags, DL),
444 VPIRMetadata(MD), Opcode(Opcode), Name(Name.str()) {
446 "Set flags not supported for the provided opcode");
448 "Opcode requires specific flags to be set");
452 "number of operands does not match opcode");
453}
454
455/// For call VPInstructions, return the operand index of the called function.
456/// The function is either the last operand (for unmasked calls) or the
457/// second-to-last operand (for masked calls).
458static unsigned getCalledFnOperandIndex(const VPInstruction &VPI) {
459 assert(VPI.getOpcode() == Instruction::Call && "must be a call");
460 unsigned NumOps = VPI.getNumOperands();
461 auto *LastOp = dyn_cast<VPIRValue>(VPI.getOperand(NumOps - 1));
462 if (LastOp && isa<Function>(LastOp->getValue()))
463 return NumOps - 1;
464 assert(
465 isa<Function>(cast<VPIRValue>(VPI.getOperand(NumOps - 2))->getValue()) &&
466 "expected function operand");
467 return NumOps - 2;
468}
469
470/// For call VPInstructions, return the called function.
472 unsigned Idx = getCalledFnOperandIndex(VPI);
473 return cast<Function>(cast<VPIRValue>(VPI.getOperand(Idx))->getValue());
474}
475
477 if (Instruction::isUnaryOp(Opcode) || Instruction::isCast(Opcode))
478 return 1;
479
480 if (Instruction::isBinaryOp(Opcode))
481 return 2;
482
483 switch (Opcode) {
486 return 0;
487 case Instruction::Alloca:
488 case Instruction::ExtractValue:
489 case Instruction::Freeze:
490 case Instruction::Load:
503 return 1;
504 case Instruction::ICmp:
505 case Instruction::FCmp:
506 case Instruction::ExtractElement:
507 case Instruction::Store:
517 return 2;
518 case Instruction::InsertElement:
519 case Instruction::Select:
522 return 3;
523 case Instruction::Call:
524 return getCalledFnOperandIndex(*this) + 1;
525 case Instruction::GetElementPtr:
526 case Instruction::PHI:
527 case Instruction::Switch:
537 // Cannot determine the number of operands from the opcode.
538 return -1u;
539 }
540 llvm_unreachable("all cases should be handled above");
541}
542
546
547bool VPInstruction::canGenerateScalarForFirstLane() const {
549 return true;
551 return true;
552 switch (Opcode) {
553 case Instruction::Freeze:
554 case Instruction::ICmp:
555 case Instruction::PHI:
556 case Instruction::Select:
566 return true;
567 default:
568 return false;
569 }
570}
571
573 if (Kind == RecurKind::Sub)
574 return Instruction::Add;
575 if (Kind == RecurKind::FSub)
576 return Instruction::FAdd;
577 llvm_unreachable("RecurKind should be Sub/FSub.");
578}
579
580Value *VPInstruction::generate(VPTransformState &State) {
581 IRBuilderBase &Builder = State.Builder;
582
584 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
585 Value *A = State.get(getOperand(0), OnlyFirstLaneUsed);
586 Value *B = State.get(getOperand(1), OnlyFirstLaneUsed);
587 auto *Res =
588 Builder.CreateBinOp((Instruction::BinaryOps)getOpcode(), A, B, Name);
589 if (auto *I = dyn_cast<Instruction>(Res))
590 applyFlags(*I);
591 return Res;
592 }
593
594 switch (getOpcode()) {
595 case VPInstruction::Not: {
596 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
597 Value *A = State.get(getOperand(0), OnlyFirstLaneUsed);
598 return Builder.CreateNot(A, Name);
599 }
600 case Instruction::ExtractElement: {
601 assert(State.VF.isVector() && "Only extract elements from vectors");
602 if (auto *Idx = dyn_cast<VPConstantInt>(getOperand(1)))
603 return State.get(getOperand(0), VPLane(Idx->getZExtValue()));
604 Value *Vec = State.get(getOperand(0));
605 Value *Idx = State.get(getOperand(1), /*IsScalar=*/true);
606 return Builder.CreateExtractElement(Vec, Idx, Name);
607 }
608 case Instruction::InsertElement: {
609 assert(State.VF.isVector() && "Can only insert elements into vectors");
610 Value *Vec = State.get(getOperand(0), /*IsScalar=*/false);
611 Value *Elt = State.get(getOperand(1), /*IsScalar=*/true);
612 Value *Idx = State.get(getOperand(2), /*IsScalar=*/true);
613 return Builder.CreateInsertElement(Vec, Elt, Idx, Name);
614 }
615 case Instruction::Freeze: {
617 return Builder.CreateFreeze(Op, Name);
618 }
619 case Instruction::FCmp:
620 case Instruction::ICmp: {
621 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
622 Value *A = State.get(getOperand(0), OnlyFirstLaneUsed);
623 Value *B = State.get(getOperand(1), OnlyFirstLaneUsed);
624 return Builder.CreateCmp(getPredicate(), A, B, Name);
625 }
626 case Instruction::PHI: {
627 llvm_unreachable("should be handled by VPPhi::execute");
628 }
629 case Instruction::Select: {
630 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
631 Value *Cond =
632 State.get(getOperand(0),
633 OnlyFirstLaneUsed || vputils::isSingleScalar(getOperand(0)));
634 Value *Op1 = State.get(getOperand(1), OnlyFirstLaneUsed);
635 Value *Op2 = State.get(getOperand(2), OnlyFirstLaneUsed);
636 return Builder.CreateSelectFMF(Cond, Op1, Op2, getFastMathFlags(), Name);
637 }
639 // Get first lane of vector induction variable.
640 Value *VIVElem0 = State.get(getOperand(0), VPLane(0));
641 // Get the original loop tripcount.
642 Value *ScalarTC = State.get(getOperand(1), VPLane(0));
643
644 // If this part of the active lane mask is scalar, generate the CMP directly
645 // to avoid unnecessary extracts.
646 if (State.VF.isScalar())
647 return Builder.CreateCmp(CmpInst::Predicate::ICMP_ULT, VIVElem0, ScalarTC,
648 Name);
649
650 ElementCount EC = State.VF.multiplyCoefficientBy(
651 cast<VPConstantInt>(getOperand(2))->getZExtValue());
652 auto *PredTy = VectorType::get(Builder.getInt1Ty(), EC);
653 return Builder.CreateIntrinsic(Intrinsic::get_active_lane_mask,
654 {PredTy, ScalarTC->getType()},
655 {VIVElem0, ScalarTC}, nullptr, Name);
656 }
658 // Generate code to combine the previous and current values in vector v3.
659 //
660 // vector.ph:
661 // v_init = vector(..., ..., ..., a[-1])
662 // br vector.body
663 //
664 // vector.body
665 // i = phi [0, vector.ph], [i+4, vector.body]
666 // v1 = phi [v_init, vector.ph], [v2, vector.body]
667 // v2 = a[i, i+1, i+2, i+3];
668 // v3 = vector(v1(3), v2(0, 1, 2))
669
670 auto *V1 = State.get(getOperand(0));
671 if (!V1->getType()->isVectorTy())
672 return V1;
673 Value *V2 = State.get(getOperand(1));
674 return Builder.CreateVectorSpliceRight(V1, V2, 1, Name);
675 }
677 Value *ScalarTC = State.get(getOperand(0), VPLane(0));
678 Value *VFxUF = State.get(getOperand(1), VPLane(0));
679 Value *Sub = Builder.CreateSub(ScalarTC, VFxUF);
680 Value *Cmp =
681 Builder.CreateICmp(CmpInst::Predicate::ICMP_UGT, ScalarTC, VFxUF);
683 return Builder.CreateSelect(Cmp, Sub, Zero);
684 }
686 // TODO: Restructure this code with an explicit remainder loop, vsetvli can
687 // be outside of the main loop.
688 Value *AVL = State.get(getOperand(0), /*IsScalar*/ true);
689 // Compute EVL
690 assert(AVL->getType()->isIntegerTy() &&
691 "Requested vector length should be an integer.");
692
693 assert(State.VF.isScalable() && "Expected scalable vector factor.");
694 Value *VFArg = Builder.getInt32(State.VF.getKnownMinValue());
695
696 Value *EVL = Builder.CreateIntrinsic(
697 Builder.getInt32Ty(), Intrinsic::experimental_get_vector_length,
698 {AVL, VFArg, Builder.getTrue()});
699 return EVL;
700 }
702 Value *Cond = State.get(getOperand(0), VPLane(0));
703 // Replace the temporary unreachable terminator with a new conditional
704 // branch, hooking it up to backward destination for latch blocks now, and
705 // to forward destination(s) later when they are created.
706 // Second successor may be backwards - iff it is already in VPBB2IRBB.
707 VPBasicBlock *SecondVPSucc =
708 cast<VPBasicBlock>(getParent()->getSuccessors()[1]);
709 BasicBlock *SecondIRSucc = State.CFG.VPBB2IRBB.lookup(SecondVPSucc);
710 BasicBlock *IRBB = State.CFG.VPBB2IRBB[getParent()];
711 auto *Br = Builder.CreateCondBr(Cond, IRBB, SecondIRSucc);
712 // First successor is always forward, reset it to nullptr.
713 Br->setSuccessor(0, nullptr);
715 applyMetadata(*Br);
716 return Br;
717 }
719 return Builder.CreateVectorSplat(
720 State.VF, State.get(getOperand(0), /*IsScalar*/ true), "broadcast");
721 }
723 // For struct types, we need to build a new 'wide' struct type, where each
724 // element is widened, i.e., we create a struct of vectors.
725 auto *StructTy =
727 Value *Res = PoisonValue::get(toVectorizedTy(StructTy, State.VF));
728 for (const auto &[LaneIndex, Op] : enumerate(operands())) {
729 for (unsigned FieldIndex = 0; FieldIndex != StructTy->getNumElements();
730 FieldIndex++) {
731 Value *ScalarValue =
732 Builder.CreateExtractValue(State.get(Op, true), FieldIndex);
733 Value *VectorValue = Builder.CreateExtractValue(Res, FieldIndex);
734 VectorValue =
735 Builder.CreateInsertElement(VectorValue, ScalarValue, LaneIndex);
736 Res = Builder.CreateInsertValue(Res, VectorValue, FieldIndex);
737 }
738 }
739 return Res;
740 }
742 auto *ScalarTy = State.TypeAnalysis.inferScalarType(getOperand(0));
743 auto NumOfElements = ElementCount::getFixed(getNumOperands());
744 Value *Res = PoisonValue::get(toVectorizedTy(ScalarTy, NumOfElements));
745 for (const auto &[Idx, Op] : enumerate(operands()))
746 Res = Builder.CreateInsertElement(Res, State.get(Op, true),
747 Builder.getInt32(Idx));
748 return Res;
749 }
751 if (State.VF.isScalar())
752 return State.get(getOperand(0), true);
753 IRBuilderBase::FastMathFlagGuard FMFG(Builder);
755 // If this start vector is scaled then it should produce a vector with fewer
756 // elements than the VF.
757 ElementCount VF = State.VF.divideCoefficientBy(
758 cast<VPConstantInt>(getOperand(2))->getZExtValue());
759 auto *Iden = Builder.CreateVectorSplat(VF, State.get(getOperand(1), true));
760 return Builder.CreateInsertElement(Iden, State.get(getOperand(0), true),
761 Builder.getInt32(0));
762 }
764 RecurKind RK = getRecurKind();
765 bool IsOrdered = isReductionOrdered();
766 bool IsInLoop = isReductionInLoop();
768 "FindIV should use min/max reduction kinds");
769
770 // The recipe may have multiple operands to be reduced together.
771 unsigned NumOperandsToReduce = getNumOperands();
772 VectorParts RdxParts(NumOperandsToReduce);
773 for (unsigned Part = 0; Part < NumOperandsToReduce; ++Part)
774 RdxParts[Part] = State.get(getOperand(Part), IsInLoop);
775
776 IRBuilderBase::FastMathFlagGuard FMFG(Builder);
778
779 // Reduce multiple operands into one.
780 Value *ReducedPartRdx = RdxParts[0];
781 if (IsOrdered) {
782 ReducedPartRdx = RdxParts[NumOperandsToReduce - 1];
783 } else {
784 // Floating-point operations should have some FMF to enable the reduction.
785 for (unsigned Part = 1; Part < NumOperandsToReduce; ++Part) {
786 Value *RdxPart = RdxParts[Part];
788 ReducedPartRdx = createMinMaxOp(Builder, RK, ReducedPartRdx, RdxPart);
789 else {
790 // For sub-recurrences, each part's reduction variable is already
791 // negative, we need to do: reduce.add(-acc_uf0 + -acc_uf1)
795 : (Instruction::BinaryOps)RecurrenceDescriptor::getOpcode(RK);
796 ReducedPartRdx =
797 Builder.CreateBinOp(Opcode, RdxPart, ReducedPartRdx, "bin.rdx");
798 }
799 }
800 }
801
802 // Create the reduction after the loop. Note that inloop reductions create
803 // the target reduction in the loop using a Reduction recipe.
804 if (State.VF.isVector() && !IsInLoop) {
805 // TODO: Support in-order reductions based on the recurrence descriptor.
806 // All ops in the reduction inherit fast-math-flags from the recurrence
807 // descriptor.
808 ReducedPartRdx = createSimpleReduction(Builder, ReducedPartRdx, RK);
809 }
810
811 return ReducedPartRdx;
812 }
815 unsigned Offset =
817 Value *Res;
818 if (State.VF.isVector()) {
819 assert(Offset <= State.VF.getKnownMinValue() &&
820 "invalid offset to extract from");
821 // Extract lane VF - Offset from the operand.
822 Res = State.get(getOperand(0), VPLane::getLaneFromEnd(State.VF, Offset));
823 } else {
824 // TODO: Remove ExtractLastLane for scalar VFs.
825 assert(Offset <= 1 && "invalid offset to extract from");
826 Res = State.get(getOperand(0));
827 }
829 Res->setName(Name);
830 return Res;
831 }
833 Value *A = State.get(getOperand(0));
834 Value *B = State.get(getOperand(1));
835 return Builder.CreateLogicalAnd(A, B, Name);
836 }
838 Value *A = State.get(getOperand(0));
839 Value *B = State.get(getOperand(1));
840 return Builder.CreateLogicalOr(A, B, Name);
841 }
843 assert((State.VF.isScalar() || vputils::onlyFirstLaneUsed(this)) &&
844 "can only generate first lane for PtrAdd");
845 Value *Ptr = State.get(getOperand(0), VPLane(0));
846 Value *Addend = State.get(getOperand(1), VPLane(0));
847 return Builder.CreatePtrAdd(Ptr, Addend, Name, getGEPNoWrapFlags());
848 }
850 Value *Ptr =
852 Value *Addend = State.get(getOperand(1));
853 return Builder.CreatePtrAdd(Ptr, Addend, Name, getGEPNoWrapFlags());
854 }
856 Value *Res = Builder.CreateFreeze(State.get(getOperand(0)));
857 for (VPValue *Op : drop_begin(operands()))
858 Res = Builder.CreateOr(Res, Builder.CreateFreeze(State.get(Op)));
859 return State.VF.isScalar() ? Res : Builder.CreateOrReduce(Res);
860 }
862 assert(getNumOperands() != 2 && "ExtractLane from single source should be "
863 "simplified to ExtractElement.");
864 Value *LaneToExtract = State.get(getOperand(0), true);
865 Type *IdxTy = State.TypeAnalysis.inferScalarType(getOperand(0));
866 Value *Res = nullptr;
867 Value *RuntimeVF = getRuntimeVF(Builder, IdxTy, State.VF);
868
869 for (unsigned Idx = 1; Idx != getNumOperands(); ++Idx) {
870 Value *VectorStart =
871 Builder.CreateMul(RuntimeVF, ConstantInt::get(IdxTy, Idx - 1));
872 Value *VectorIdx = Idx == 1
873 ? LaneToExtract
874 : Builder.CreateSub(LaneToExtract, VectorStart);
875 Value *Ext = State.VF.isScalar()
876 ? State.get(getOperand(Idx))
877 : Builder.CreateExtractElement(
878 State.get(getOperand(Idx)), VectorIdx);
879 if (Res) {
880 Value *Cmp = Builder.CreateICmpUGE(LaneToExtract, VectorStart);
881 Res = Builder.CreateSelect(Cmp, Ext, Res);
882 } else {
883 Res = Ext;
884 }
885 }
886 return Res;
887 }
889 Type *Ty = State.TypeAnalysis.inferScalarType(this);
890 if (getNumOperands() == 1) {
891 Value *Mask = State.get(getOperand(0));
892 return Builder.CreateCountTrailingZeroElems(Ty, Mask,
893 /*ZeroIsPoison=*/false, Name);
894 }
895 // If there are multiple operands, create a chain of selects to pick the
896 // first operand with an active lane and add the number of lanes of the
897 // preceding operands.
898 Value *RuntimeVF = getRuntimeVF(Builder, Ty, State.VF);
899 unsigned LastOpIdx = getNumOperands() - 1;
900 Value *Res = nullptr;
901 for (int Idx = LastOpIdx; Idx >= 0; --Idx) {
902 Value *TrailingZeros =
903 State.VF.isScalar()
904 ? Builder.CreateZExt(
905 Builder.CreateICmpEQ(State.get(getOperand(Idx)),
906 Builder.getFalse()),
907 Ty)
909 Ty, State.get(getOperand(Idx)),
910 /*ZeroIsPoison=*/false, Name);
911 Value *Current = Builder.CreateAdd(
912 Builder.CreateMul(RuntimeVF, ConstantInt::get(Ty, Idx)),
913 TrailingZeros);
914 if (Res) {
915 Value *Cmp = Builder.CreateICmpNE(TrailingZeros, RuntimeVF);
916 Res = Builder.CreateSelect(Cmp, Current, Res);
917 } else {
918 Res = Current;
919 }
920 }
921
922 return Res;
923 }
925 return State.get(getOperand(0), true);
927 return Builder.CreateVectorReverse(State.get(getOperand(0)), "reverse");
929 Value *Result = State.get(getOperand(0), /*IsScalar=*/true);
930 for (unsigned Idx = 1; Idx < getNumOperands(); Idx += 2) {
931 Value *Data = State.get(getOperand(Idx));
932 Value *Mask = State.get(getOperand(Idx + 1));
933 Type *VTy = Data->getType();
934
935 if (State.VF.isScalar())
936 Result = Builder.CreateSelect(Mask, Data, Result);
937 else
938 Result = Builder.CreateIntrinsic(
939 Intrinsic::experimental_vector_extract_last_active, {VTy},
940 {Data, Mask, Result});
941 }
942
943 return Result;
944 }
945 default:
946 llvm_unreachable("Unsupported opcode for instruction");
947 }
948}
949
951 unsigned Opcode, ElementCount VF, VPCostContext &Ctx) const {
952 Type *ScalarTy = Ctx.Types.inferScalarType(this);
953 Type *ResultTy = VF.isVector() ? toVectorTy(ScalarTy, VF) : ScalarTy;
954 switch (Opcode) {
955 case Instruction::FNeg:
956 return Ctx.TTI.getArithmeticInstrCost(Opcode, ResultTy, Ctx.CostKind);
957 case Instruction::UDiv:
958 case Instruction::SDiv:
959 case Instruction::SRem:
960 case Instruction::URem:
961 case Instruction::Add:
962 case Instruction::FAdd:
963 case Instruction::Sub:
964 case Instruction::FSub:
965 case Instruction::Mul:
966 case Instruction::FMul:
967 case Instruction::FDiv:
968 case Instruction::FRem:
969 case Instruction::Shl:
970 case Instruction::LShr:
971 case Instruction::AShr:
972 case Instruction::And:
973 case Instruction::Or:
974 case Instruction::Xor: {
975 // Certain instructions can be cheaper if they have a constant second
976 // operand. One example of this are shifts on x86.
977 VPValue *RHS = getOperand(1);
978 TargetTransformInfo::OperandValueInfo RHSInfo = Ctx.getOperandInfo(RHS);
979
980 if (RHSInfo.Kind == TargetTransformInfo::OK_AnyValue &&
983
986 if (CtxI)
987 Operands.append(CtxI->value_op_begin(), CtxI->value_op_end());
988 return Ctx.TTI.getArithmeticInstrCost(
989 Opcode, ResultTy, Ctx.CostKind,
990 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
991 RHSInfo, Operands, CtxI, &Ctx.TLI);
992 }
993 case Instruction::Freeze:
994 // NOTE: The only way to ask for the cost is via getInstructionCost, which
995 // requires the actual vector instruction. Instead, both here and in the
996 // LoopVectorizationCostModel::getInstructionCost the costs mirror the
997 // current behaviour in llvm/Analysis/TargetTransformInfoImpl.h to keep
998 // them in sync.
999 return TTI::TCC_Free;
1000 case Instruction::ExtractValue:
1001 return Ctx.TTI.getInsertExtractValueCost(Instruction::ExtractValue,
1002 Ctx.CostKind);
1003 case Instruction::ICmp:
1004 case Instruction::FCmp: {
1005 Type *ScalarOpTy = Ctx.Types.inferScalarType(getOperand(0));
1006 Type *OpTy = VF.isVector() ? toVectorTy(ScalarOpTy, VF) : ScalarOpTy;
1008 return Ctx.TTI.getCmpSelInstrCost(
1009 Opcode, OpTy, CmpInst::makeCmpResultType(OpTy), getPredicate(),
1010 Ctx.CostKind, {TTI::OK_AnyValue, TTI::OP_None},
1011 {TTI::OK_AnyValue, TTI::OP_None}, CtxI);
1012 }
1013 case Instruction::BitCast: {
1014 Type *ScalarTy = Ctx.Types.inferScalarType(this);
1015 if (ScalarTy->isPointerTy())
1016 return 0;
1017 [[fallthrough]];
1018 }
1019 case Instruction::SExt:
1020 case Instruction::ZExt:
1021 case Instruction::FPToUI:
1022 case Instruction::FPToSI:
1023 case Instruction::FPExt:
1024 case Instruction::PtrToInt:
1025 case Instruction::PtrToAddr:
1026 case Instruction::IntToPtr:
1027 case Instruction::SIToFP:
1028 case Instruction::UIToFP:
1029 case Instruction::Trunc:
1030 case Instruction::FPTrunc:
1031 case Instruction::AddrSpaceCast: {
1032 // Computes the CastContextHint from a recipe that may access memory.
1033 auto ComputeCCH = [&](const VPRecipeBase *R) -> TTI::CastContextHint {
1034 if (isa<VPInterleaveBase>(R))
1036 if (const auto *ReplicateRecipe = dyn_cast<VPReplicateRecipe>(R)) {
1037 // Only compute CCH for memory operations, matching the legacy model
1038 // which only considers loads/stores for cast context hints.
1039 auto *UI = cast<Instruction>(ReplicateRecipe->getUnderlyingValue());
1040 if (!isa<LoadInst, StoreInst>(UI))
1042 return ReplicateRecipe->isPredicated() ? TTI::CastContextHint::Masked
1044 }
1045 const auto *WidenMemoryRecipe = dyn_cast<VPWidenMemoryRecipe>(R);
1046 if (WidenMemoryRecipe == nullptr)
1048 if (VF.isScalar())
1050 if (!WidenMemoryRecipe->isConsecutive())
1052 if (WidenMemoryRecipe->isMasked())
1055 };
1056
1057 VPValue *Operand = getOperand(0);
1059 bool IsReverse = false;
1060 // For Trunc/FPTrunc, get the context from the only user.
1061 if (Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) {
1062 auto GetOnlyUser = [](const VPSingleDefRecipe *R) -> VPRecipeBase * {
1063 if (R->getNumUsers() == 0 || R->hasMoreThanOneUniqueUser())
1064 return nullptr;
1065 return dyn_cast<VPRecipeBase>(*R->user_begin());
1066 };
1067 if (VPRecipeBase *Recipe = GetOnlyUser(this)) {
1068 if (match(Recipe,
1072 Recipe = GetOnlyUser(cast<VPSingleDefRecipe>(Recipe));
1073 IsReverse = true;
1074 }
1075 if (Recipe)
1076 CCH = ComputeCCH(Recipe);
1077 }
1078 }
1079 // For Z/Sext, get the context from the operand.
1080 else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt ||
1081 Opcode == Instruction::FPExt) {
1082 if (auto *Recipe = Operand->getDefiningRecipe()) {
1083 VPValue *ReverseOp;
1084 if (match(Recipe,
1085 m_CombineOr(m_Reverse(m_VPValue(ReverseOp)),
1087 m_VPValue(ReverseOp))))) {
1088 Recipe = ReverseOp->getDefiningRecipe();
1089 IsReverse = true;
1090 }
1091 if (Recipe)
1092 CCH = ComputeCCH(Recipe);
1093 }
1094 }
1095 if (IsReverse && CCH != TTI::CastContextHint::None)
1097
1098 auto *ScalarSrcTy = Ctx.Types.inferScalarType(Operand);
1099 Type *SrcTy = VF.isVector() ? toVectorTy(ScalarSrcTy, VF) : ScalarSrcTy;
1100 // Arm TTI will use the underlying instruction to determine the cost.
1101 return Ctx.TTI.getCastInstrCost(
1102 Opcode, ResultTy, SrcTy, CCH, Ctx.CostKind,
1104 }
1105 case Instruction::Select: {
1107 bool IsScalarCond = getOperand(0)->isDefinedOutsideLoopRegions();
1108 Type *ScalarTy = Ctx.Types.inferScalarType(this);
1109
1110 VPValue *Op0, *Op1;
1111 bool IsLogicalAnd =
1112 match(this, m_c_LogicalAnd(m_VPValue(Op0), m_VPValue(Op1)));
1113 bool IsLogicalOr =
1114 match(this, m_c_LogicalOr(m_VPValue(Op0), m_VPValue(Op1)));
1115 // Also match the inverted forms:
1116 // select x, false, y --> !x & y (still AND)
1117 // select x, y, true --> !x | y (still OR)
1118 IsLogicalAnd |=
1119 match(this, m_Select(m_VPValue(Op0), m_False(), m_VPValue(Op1)));
1120 IsLogicalOr |=
1121 match(this, m_Select(m_VPValue(Op0), m_VPValue(Op1), m_True()));
1122
1123 if (!IsScalarCond && ScalarTy->getScalarSizeInBits() == 1 &&
1124 (IsLogicalAnd || IsLogicalOr)) {
1125 // select x, y, false --> x & y
1126 // select x, true, y --> x | y
1127 const auto [Op1VK, Op1VP] = Ctx.getOperandInfo(Op0);
1128 const auto [Op2VK, Op2VP] = Ctx.getOperandInfo(Op1);
1129
1131 if (SI && all_of(operands(),
1132 [](VPValue *Op) { return Op->getUnderlyingValue(); }))
1133 append_range(Operands, SI->operands());
1134 return Ctx.TTI.getArithmeticInstrCost(
1135 IsLogicalOr ? Instruction::Or : Instruction::And, ResultTy,
1136 Ctx.CostKind, {Op1VK, Op1VP}, {Op2VK, Op2VP}, Operands, SI);
1137 }
1138
1139 Type *CondTy = Ctx.Types.inferScalarType(getOperand(0));
1140 if (!IsScalarCond && VF.isVector())
1141 CondTy = VectorType::get(CondTy, VF);
1142
1143 llvm::CmpPredicate Pred;
1144 if (!match(getOperand(0), m_Cmp(Pred, m_VPValue(), m_VPValue())))
1145 if (auto *CondIRV = dyn_cast<VPIRValue>(getOperand(0)))
1146 if (auto *Cmp = dyn_cast<CmpInst>(CondIRV->getValue()))
1147 Pred = Cmp->getPredicate();
1148 Type *VectorTy = toVectorTy(Ctx.Types.inferScalarType(this), VF);
1149 return Ctx.TTI.getCmpSelInstrCost(
1150 Instruction::Select, VectorTy, CondTy, Pred, Ctx.CostKind,
1151 {TTI::OK_AnyValue, TTI::OP_None}, {TTI::OK_AnyValue, TTI::OP_None}, SI);
1152 }
1153 }
1154 llvm_unreachable("called for unsupported opcode");
1155}
1156
1158 VPCostContext &Ctx) const {
1160 if (!getUnderlyingValue() && getOpcode() != Instruction::FMul) {
1161 // TODO: Compute cost for VPInstructions without underlying values once
1162 // the legacy cost model has been retired.
1163 return 0;
1164 }
1165
1167 "Should only generate a vector value or single scalar, not scalars "
1168 "for all lanes.");
1170 getOpcode(),
1172 }
1173
1174 switch (getOpcode()) {
1175 case Instruction::Select: {
1177 match(getOperand(0), m_Cmp(Pred, m_VPValue(), m_VPValue()));
1178 auto *CondTy = Ctx.Types.inferScalarType(getOperand(0));
1179 auto *VecTy = Ctx.Types.inferScalarType(getOperand(1));
1180 if (!vputils::onlyFirstLaneUsed(this)) {
1181 CondTy = toVectorTy(CondTy, VF);
1182 VecTy = toVectorTy(VecTy, VF);
1183 }
1184 return Ctx.TTI.getCmpSelInstrCost(Instruction::Select, VecTy, CondTy, Pred,
1185 Ctx.CostKind);
1186 }
1187 case Instruction::ExtractElement:
1189 if (VF.isScalar()) {
1190 // ExtractLane with VF=1 takes care of handling extracting across multiple
1191 // parts.
1192 return 0;
1193 }
1194
1195 // Add on the cost of extracting the element.
1196 auto *VecTy = toVectorTy(Ctx.Types.inferScalarType(getOperand(0)), VF);
1197 return Ctx.TTI.getVectorInstrCost(Instruction::ExtractElement, VecTy,
1198 Ctx.CostKind);
1199 }
1200 case VPInstruction::AnyOf: {
1201 auto *VecTy = toVectorTy(Ctx.Types.inferScalarType(this), VF);
1202 return Ctx.TTI.getArithmeticReductionCost(
1203 Instruction::Or, cast<VectorType>(VecTy), std::nullopt, Ctx.CostKind);
1204 }
1206 Type *Ty = Ctx.Types.inferScalarType(this);
1207 Type *ScalarTy = Ctx.Types.inferScalarType(getOperand(0));
1208 if (VF.isScalar())
1209 return Ctx.TTI.getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
1211 CmpInst::ICMP_EQ, Ctx.CostKind);
1212 // Calculate the cost of determining the lane index.
1213 auto *PredTy = toVectorTy(ScalarTy, VF);
1214 IntrinsicCostAttributes Attrs(Intrinsic::experimental_cttz_elts, Ty,
1215 {PredTy, Type::getInt1Ty(Ctx.LLVMCtx)});
1216 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1217 }
1219 Type *Ty = Ctx.Types.inferScalarType(this);
1220 Type *ScalarTy = Ctx.Types.inferScalarType(getOperand(0));
1221 if (VF.isScalar())
1222 return Ctx.TTI.getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
1224 CmpInst::ICMP_EQ, Ctx.CostKind);
1225 // Calculate the cost of determining the lane index: NOT + cttz_elts + SUB.
1226 auto *PredTy = toVectorTy(ScalarTy, VF);
1227 IntrinsicCostAttributes Attrs(Intrinsic::experimental_cttz_elts, Ty,
1228 {PredTy, Type::getInt1Ty(Ctx.LLVMCtx)});
1229 InstructionCost Cost = Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1230 // Add cost of NOT operation on the predicate.
1231 Cost += Ctx.TTI.getArithmeticInstrCost(
1232 Instruction::Xor, PredTy, Ctx.CostKind,
1233 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
1234 {TargetTransformInfo::OK_UniformConstantValue,
1235 TargetTransformInfo::OP_None});
1236 // Add cost of SUB operation on the index.
1237 Cost += Ctx.TTI.getArithmeticInstrCost(Instruction::Sub, Ty, Ctx.CostKind);
1238 return Cost;
1239 }
1241 Type *ScalarTy = Ctx.Types.inferScalarType(this);
1242 Type *VecTy = toVectorTy(ScalarTy, VF);
1243 Type *MaskTy = toVectorTy(Type::getInt1Ty(Ctx.LLVMCtx), VF);
1245 Intrinsic::experimental_vector_extract_last_active, ScalarTy,
1246 {VecTy, MaskTy, ScalarTy});
1247 return Ctx.TTI.getIntrinsicInstrCost(ICA, Ctx.CostKind);
1248 }
1250 assert(VF.isVector() && "Scalar FirstOrderRecurrenceSplice?");
1251 Type *VectorTy = toVectorTy(Ctx.Types.inferScalarType(this), VF);
1252 return Ctx.TTI.getShuffleCost(
1254 cast<VectorType>(VectorTy), {}, Ctx.CostKind, -1);
1255 }
1257 Type *ArgTy = Ctx.Types.inferScalarType(getOperand(0));
1258 unsigned Multiplier = cast<VPConstantInt>(getOperand(2))->getZExtValue();
1259 Type *RetTy = toVectorTy(Type::getInt1Ty(Ctx.LLVMCtx), VF * Multiplier);
1260 IntrinsicCostAttributes Attrs(Intrinsic::get_active_lane_mask, RetTy,
1261 {ArgTy, ArgTy});
1262 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1263 }
1265 Type *Arg0Ty = Ctx.Types.inferScalarType(getOperand(0));
1266 Type *I32Ty = Type::getInt32Ty(Ctx.LLVMCtx);
1267 Type *I1Ty = Type::getInt1Ty(Ctx.LLVMCtx);
1268 IntrinsicCostAttributes Attrs(Intrinsic::experimental_get_vector_length,
1269 I32Ty, {Arg0Ty, I32Ty, I1Ty});
1270 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1271 }
1273 assert(VF.isVector() && "Reverse operation must be vector type");
1274 Type *EltTy = Ctx.Types.inferScalarType(this);
1275 // Skip the reverse operation cost for the mask.
1276 // FIXME: Remove this once redundant mask reverse operations can be
1277 // eliminated by VPlanTransforms::cse before cost computation.
1278 if (EltTy->isIntegerTy(1))
1279 return 0;
1280 auto *VectorTy = cast<VectorType>(toVectorTy(EltTy, VF));
1281 return Ctx.TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy,
1282 VectorTy, /*Mask=*/{}, Ctx.CostKind,
1283 /*Index=*/0);
1284 }
1286 // Add on the cost of extracting the element.
1287 auto *VecTy = toVectorTy(Ctx.Types.inferScalarType(getOperand(0)), VF);
1288 return Ctx.TTI.getIndexedVectorInstrCostFromEnd(Instruction::ExtractElement,
1289 VecTy, Ctx.CostKind, 0);
1290 }
1291 case Instruction::FCmp:
1292 case Instruction::ICmp: {
1293 // FIXME: We don't handle scalar compares inside the loop here yet, as loop
1294 // exit conditions are handled by the legacy cost model and avoiding all
1295 // scalar compares is the simplest way to avoid double-counting compares
1296 // that compute the loop exit condition.
1297 bool IsScalar = vputils::onlyFirstLaneUsed(this);
1298 const VPRegionBlock *Region = getRegion();
1299 if (IsScalar && Region &&
1300 Region == Region->getPlan()->getVectorLoopRegion())
1301 return 0;
1303 getOpcode(), IsScalar ? ElementCount::getFixed(1) : VF, Ctx);
1304 }
1306 if (VF == ElementCount::getScalable(1))
1308 [[fallthrough]];
1309 default:
1310 // TODO: Compute cost other VPInstructions once the legacy cost model has
1311 // been retired.
1313 "unexpected VPInstruction witht underlying value");
1314 return 0;
1315 }
1316}
1317
1329
1331 switch (getOpcode()) {
1332 case Instruction::Load:
1333 case Instruction::PHI:
1337 return true;
1338 default:
1340 }
1341}
1342
1344 assert(!isMasked() && "cannot execute masked VPInstruction");
1345 IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder);
1347 "Set flags not supported for the provided opcode");
1349 "Opcode requires specific flags to be set");
1350 if (hasFastMathFlags())
1351 State.Builder.setFastMathFlags(getFastMathFlags());
1352 Value *GeneratedValue = generate(State);
1353 if (!hasResult())
1354 return;
1355 assert(GeneratedValue && "generate must produce a value");
1356 bool GeneratesPerFirstLaneOnly = canGenerateScalarForFirstLane() &&
1359 assert((((GeneratedValue->getType()->isVectorTy() ||
1360 GeneratedValue->getType()->isStructTy()) ==
1361 !GeneratesPerFirstLaneOnly) ||
1362 State.VF.isScalar()) &&
1363 "scalar value but not only first lane defined");
1364 State.set(this, GeneratedValue,
1365 /*IsScalar*/ GeneratesPerFirstLaneOnly);
1367 // FIXME: This is a workaround to enable reliable updates of the scalar loop
1368 // resume phis, when vectorizing the epilogue. Must be removed once epilogue
1369 // vectorization explicitly connects VPlans.
1370 setUnderlyingValue(GeneratedValue);
1371 }
1372}
1373
1377 return false;
1378 switch (getOpcode()) {
1379 case Instruction::ExtractValue:
1380 case Instruction::InsertValue:
1381 case Instruction::GetElementPtr:
1382 case Instruction::ExtractElement:
1383 case Instruction::InsertElement:
1384 case Instruction::Freeze:
1385 case Instruction::FCmp:
1386 case Instruction::ICmp:
1387 case Instruction::Select:
1388 case Instruction::PHI:
1412 case VPInstruction::Not:
1421 return false;
1422 case Instruction::Call:
1423 return !getCalledFunction(*this)->doesNotAccessMemory();
1424 default:
1425 return true;
1426 }
1427}
1428
1430 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
1432 return vputils::onlyFirstLaneUsed(this);
1433
1434 switch (getOpcode()) {
1435 default:
1436 return false;
1437 case Instruction::ExtractElement:
1438 return Op == getOperand(1);
1439 case Instruction::InsertElement:
1440 return Op == getOperand(1) || Op == getOperand(2);
1441 case Instruction::PHI:
1442 return true;
1443 case Instruction::FCmp:
1444 case Instruction::ICmp:
1445 case Instruction::Select:
1446 case Instruction::Or:
1447 case Instruction::Freeze:
1448 case VPInstruction::Not:
1449 // TODO: Cover additional opcodes.
1450 return vputils::onlyFirstLaneUsed(this);
1451 case Instruction::Load:
1461 return true;
1464 // Before replicating by VF, Build(Struct)Vector uses all lanes of the
1465 // operand, after replicating its operands only the first lane is used.
1466 // Before replicating, it will have only a single operand.
1467 return getNumOperands() > 1;
1469 return Op == getOperand(0) || vputils::onlyFirstLaneUsed(this);
1471 // WidePtrAdd supports scalar and vector base addresses.
1472 return false;
1475 return Op == getOperand(0);
1476 };
1477 llvm_unreachable("switch should return");
1478}
1479
1481 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
1483 return vputils::onlyFirstPartUsed(this);
1484
1485 switch (getOpcode()) {
1486 default:
1487 return false;
1488 case Instruction::FCmp:
1489 case Instruction::ICmp:
1490 case Instruction::Select:
1491 return vputils::onlyFirstPartUsed(this);
1496 return true;
1497 };
1498 llvm_unreachable("switch should return");
1499}
1500
1501#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1503 VPSlotTracker SlotTracker(getParent()->getPlan());
1505}
1506
1508 VPSlotTracker &SlotTracker) const {
1509 O << Indent << "EMIT" << (isSingleScalar() ? "-SCALAR" : "") << " ";
1510
1511 if (hasResult()) {
1513 O << " = ";
1514 }
1515
1516 switch (getOpcode()) {
1517 case VPInstruction::Not:
1518 O << "not";
1519 break;
1521 O << "active lane mask";
1522 break;
1524 O << "EXPLICIT-VECTOR-LENGTH";
1525 break;
1527 O << "first-order splice";
1528 break;
1530 O << "branch-on-cond";
1531 break;
1533 O << "branch-on-two-conds";
1534 break;
1536 O << "TC > VF ? TC - VF : 0";
1537 break;
1539 O << "VF * Part +";
1540 break;
1542 O << "branch-on-count";
1543 break;
1545 O << "broadcast";
1546 break;
1548 O << "buildstructvector";
1549 break;
1551 O << "buildvector";
1552 break;
1554 O << "exiting-iv-value";
1555 break;
1557 O << "masked-cond";
1558 break;
1560 O << "extract-lane";
1561 break;
1563 O << "extract-last-lane";
1564 break;
1566 O << "extract-last-part";
1567 break;
1569 O << "extract-penultimate-element";
1570 break;
1572 O << "compute-reduction-result";
1573 break;
1575 O << "logical-and";
1576 break;
1578 O << "logical-or";
1579 break;
1581 O << "ptradd";
1582 break;
1584 O << "wide-ptradd";
1585 break;
1587 O << "any-of";
1588 break;
1590 O << "first-active-lane";
1591 break;
1593 O << "last-active-lane";
1594 break;
1596 O << "reduction-start-vector";
1597 break;
1599 O << "resume-for-epilogue";
1600 break;
1602 O << "reverse";
1603 break;
1605 O << "unpack";
1606 break;
1608 O << "extract-last-active";
1609 break;
1610 default:
1612 }
1613
1614 printFlags(O);
1616}
1617#endif
1618
1621 Value *Op = State.get(getOperand(0), VPLane(0));
1622 Value *Cast = State.Builder.CreateCast(Instruction::CastOps(getOpcode()),
1623 Op, ResultTy);
1624 if (auto *CastOp = dyn_cast<Instruction>(Cast)) {
1625 applyFlags(*CastOp);
1626 applyMetadata(*CastOp);
1627 }
1628 State.set(this, Cast, VPLane(0));
1629 return;
1630 }
1631 switch (getOpcode()) {
1633 Value *StepVector =
1634 State.Builder.CreateStepVector(VectorType::get(ResultTy, State.VF));
1635 State.set(this, StepVector);
1636 break;
1637 }
1638 case VPInstruction::VScale: {
1639 Value *VScale = State.Builder.CreateVScale(ResultTy);
1640 State.set(this, VScale, true);
1641 break;
1642 }
1643
1644 default:
1645 llvm_unreachable("opcode not implemented yet");
1646 }
1647}
1648
1649#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1651 VPSlotTracker &SlotTracker) const {
1652 O << Indent << "EMIT" << (isSingleScalar() ? "-SCALAR" : "") << " ";
1654 O << " = ";
1655
1656 switch (getOpcode()) {
1658 O << "wide-iv-step ";
1660 break;
1662 O << "step-vector " << *ResultTy;
1663 break;
1665 O << "vscale " << *ResultTy;
1666 break;
1667 case Instruction::Load:
1668 O << "load ";
1670 break;
1671 default:
1672 assert(Instruction::isCast(getOpcode()) && "unhandled opcode");
1675 O << " to " << *ResultTy;
1676 }
1677}
1678#endif
1679
1681 PHINode *NewPhi = State.Builder.CreatePHI(
1682 State.TypeAnalysis.inferScalarType(this), 2, getName());
1683 unsigned NumIncoming = getNumIncoming();
1684 // Detect header phis: the parent block dominates its second incoming block
1685 // (the latch). Those IR incoming values have not been generated yet and need
1686 // to be added after they have been executed.
1687 if (NumIncoming == 2 &&
1688 State.VPDT.dominates(getParent(), getIncomingBlock(1))) {
1689 NumIncoming = 1;
1690 }
1691 for (unsigned Idx = 0; Idx != NumIncoming; ++Idx) {
1692 Value *IncV = State.get(getIncomingValue(Idx), VPLane(0));
1693 BasicBlock *PredBB = State.CFG.VPBB2IRBB.at(getIncomingBlock(Idx));
1694 NewPhi->addIncoming(IncV, PredBB);
1695 }
1696 State.set(this, NewPhi, VPLane(0));
1697}
1698
1699#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1700void VPPhi::printRecipe(raw_ostream &O, const Twine &Indent,
1701 VPSlotTracker &SlotTracker) const {
1702 O << Indent << "EMIT" << (isSingleScalar() ? "-SCALAR" : "") << " ";
1704 O << " = phi";
1705 printFlags(O);
1707}
1708#endif
1709
1710VPIRInstruction *VPIRInstruction ::create(Instruction &I) {
1711 if (auto *Phi = dyn_cast<PHINode>(&I))
1712 return new VPIRPhi(*Phi);
1713 return new VPIRInstruction(I);
1714}
1715
1717 assert(!isa<VPIRPhi>(this) && getNumOperands() == 0 &&
1718 "PHINodes must be handled by VPIRPhi");
1719 // Advance the insert point after the wrapped IR instruction. This allows
1720 // interleaving VPIRInstructions and other recipes.
1721 State.Builder.SetInsertPoint(I.getParent(), std::next(I.getIterator()));
1722}
1723
1725 VPCostContext &Ctx) const {
1726 // The recipe wraps an existing IR instruction on the border of VPlan's scope,
1727 // hence it does not contribute to the cost-modeling for the VPlan.
1728 return 0;
1729}
1730
1731#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1733 VPSlotTracker &SlotTracker) const {
1734 O << Indent << "IR " << I;
1735}
1736#endif
1737
1739 PHINode *Phi = &getIRPhi();
1740 for (const auto &[Idx, Op] : enumerate(operands())) {
1741 VPValue *ExitValue = Op;
1742 auto Lane = vputils::isSingleScalar(ExitValue)
1744 : VPLane::getLastLaneForVF(State.VF);
1745 VPBlockBase *Pred = getParent()->getPredecessors()[Idx];
1746 auto *PredVPBB = Pred->getExitingBasicBlock();
1747 BasicBlock *PredBB = State.CFG.VPBB2IRBB[PredVPBB];
1748 // Set insertion point in PredBB in case an extract needs to be generated.
1749 // TODO: Model extracts explicitly.
1750 State.Builder.SetInsertPoint(PredBB->getTerminator());
1751 Value *V = State.get(ExitValue, VPLane(Lane));
1752 // If there is no existing block for PredBB in the phi, add a new incoming
1753 // value. Otherwise update the existing incoming value for PredBB.
1754 if (Phi->getBasicBlockIndex(PredBB) == -1)
1755 Phi->addIncoming(V, PredBB);
1756 else
1757 Phi->setIncomingValueForBlock(PredBB, V);
1758 }
1759
1760 // Advance the insert point after the wrapped IR instruction. This allows
1761 // interleaving VPIRInstructions and other recipes.
1762 State.Builder.SetInsertPoint(Phi->getParent(), std::next(Phi->getIterator()));
1763}
1764
1766 VPRecipeBase *R = const_cast<VPRecipeBase *>(getAsRecipe());
1767 assert(R->getNumOperands() == R->getParent()->getNumPredecessors() &&
1768 "Number of phi operands must match number of predecessors");
1769 unsigned Position = R->getParent()->getIndexForPredecessor(IncomingBlock);
1770 R->removeOperand(Position);
1771}
1772
1773VPValue *
1775 VPRecipeBase *R = const_cast<VPRecipeBase *>(getAsRecipe());
1776 return getIncomingValue(R->getParent()->getIndexForPredecessor(VPBB));
1777}
1778
1780 VPValue *V) const {
1781 VPRecipeBase *R = const_cast<VPRecipeBase *>(getAsRecipe());
1782 R->setOperand(R->getParent()->getIndexForPredecessor(VPBB), V);
1783}
1784
1785#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1787 VPSlotTracker &SlotTracker) const {
1788 interleaveComma(enumerate(getAsRecipe()->operands()), O,
1789 [this, &O, &SlotTracker](auto Op) {
1790 O << "[ ";
1791 Op.value()->printAsOperand(O, SlotTracker);
1792 O << ", ";
1793 getIncomingBlock(Op.index())->printAsOperand(O);
1794 O << " ]";
1795 });
1796}
1797#endif
1798
1799#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1801 VPSlotTracker &SlotTracker) const {
1803
1804 if (getNumOperands() != 0) {
1805 O << " (extra operand" << (getNumOperands() > 1 ? "s" : "") << ": ";
1807 [&O, &SlotTracker](auto Op) {
1808 std::get<0>(Op)->printAsOperand(O, SlotTracker);
1809 O << " from ";
1810 std::get<1>(Op)->printAsOperand(O);
1811 });
1812 O << ")";
1813 }
1814}
1815#endif
1816
1818 for (const auto &[Kind, Node] : Metadata)
1819 I.setMetadata(Kind, Node);
1820}
1821
1823 SmallVector<std::pair<unsigned, MDNode *>> MetadataIntersection;
1824 for (const auto &[KindA, MDA] : Metadata) {
1825 for (const auto &[KindB, MDB] : Other.Metadata) {
1826 if (KindA == KindB && MDA == MDB) {
1827 MetadataIntersection.emplace_back(KindA, MDA);
1828 break;
1829 }
1830 }
1831 }
1832 Metadata = std::move(MetadataIntersection);
1833}
1834
1835#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1837 const Module *M = SlotTracker.getModule();
1838 if (Metadata.empty() || !M)
1839 return;
1840
1841 ArrayRef<StringRef> MDNames = SlotTracker.getMDNames();
1842 O << " (";
1843 interleaveComma(Metadata, O, [&](const auto &KindNodePair) {
1844 auto [Kind, Node] = KindNodePair;
1845 assert(Kind < MDNames.size() && !MDNames[Kind].empty() &&
1846 "Unexpected unnamed metadata kind");
1847 O << "!" << MDNames[Kind] << " ";
1848 Node->printAsOperand(O, M);
1849 });
1850 O << ")";
1851}
1852#endif
1853
1855 assert(State.VF.isVector() && "not widening");
1856 assert(Variant != nullptr && "Can't create vector function.");
1857
1858 FunctionType *VFTy = Variant->getFunctionType();
1859 // Add return type if intrinsic is overloaded on it.
1861 for (const auto &I : enumerate(args())) {
1862 Value *Arg;
1863 // Some vectorized function variants may also take a scalar argument,
1864 // e.g. linear parameters for pointers. This needs to be the scalar value
1865 // from the start of the respective part when interleaving.
1866 if (!VFTy->getParamType(I.index())->isVectorTy())
1867 Arg = State.get(I.value(), VPLane(0));
1868 else
1869 Arg = State.get(I.value(), usesFirstLaneOnly(I.value()));
1870 Args.push_back(Arg);
1871 }
1872
1875 if (CI)
1876 CI->getOperandBundlesAsDefs(OpBundles);
1877
1878 CallInst *V = State.Builder.CreateCall(Variant, Args, OpBundles);
1879 applyFlags(*V);
1880 applyMetadata(*V);
1881 V->setCallingConv(Variant->getCallingConv());
1882
1883 if (!V->getType()->isVoidTy())
1884 State.set(this, V);
1885}
1886
1888 VPCostContext &Ctx) const {
1889 assert(getVectorizedTypeVF(Variant->getReturnType()) == VF &&
1890 "Variant return type must match VF");
1891 return computeCallCost(Variant, Ctx);
1892}
1893
1895 VPCostContext &Ctx) {
1896 return Ctx.TTI.getCallInstrCost(nullptr, Variant->getReturnType(),
1897 Variant->getFunctionType()->params(),
1898 Ctx.CostKind);
1899}
1900
1902 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
1903 assert(Variant && "Variant not set");
1904 FunctionType *VFTy = Variant->getFunctionType();
1905 return all_of(enumerate(args()), [VFTy, &Op](const auto &Arg) {
1906 auto [Idx, V] = Arg;
1907 Type *ArgTy = VFTy->getParamType(Idx);
1908 return V != Op || ArgTy->isIntegerTy() || ArgTy->isFloatingPointTy() ||
1909 ArgTy->isPointerTy() || ArgTy->isByteTy();
1910 });
1911}
1912
1913#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1915 VPSlotTracker &SlotTracker) const {
1916 O << Indent << "WIDEN-CALL ";
1917
1918 Function *CalledFn = getCalledScalarFunction();
1919 if (CalledFn->getReturnType()->isVoidTy())
1920 O << "void ";
1921 else {
1923 O << " = ";
1924 }
1925
1926 O << "call";
1927 printFlags(O);
1928 O << " @" << CalledFn->getName() << "(";
1929 interleaveComma(args(), O, [&O, &SlotTracker](VPValue *Op) {
1930 Op->printAsOperand(O, SlotTracker);
1931 });
1932 O << ")";
1933
1934 O << " (using library function";
1935 if (Variant->hasName())
1936 O << ": " << Variant->getName();
1937 O << ")";
1938}
1939#endif
1940
1942 assert(State.VF.isVector() && "not widening");
1943
1944 SmallVector<Type *, 2> TysForDecl;
1945 // Add return type if intrinsic is overloaded on it.
1946 if (isVectorIntrinsicWithOverloadTypeAtArg(VectorIntrinsicID, -1,
1947 State.TTI)) {
1948 Type *RetTy = toVectorizedTy(getScalarType(), State.VF);
1949 ArrayRef<Type *> ContainedTys = getContainedTypes(RetTy);
1950 for (auto [Idx, Ty] : enumerate(ContainedTys)) {
1952 Idx, State.TTI))
1953 TysForDecl.push_back(Ty);
1954 }
1955 }
1957 for (const auto &I : enumerate(operands())) {
1958 // Some intrinsics have a scalar argument - don't replace it with a
1959 // vector.
1960 Value *Arg;
1961 if (isVectorIntrinsicWithScalarOpAtArg(VectorIntrinsicID, I.index(),
1962 State.TTI))
1963 Arg = State.get(I.value(), VPLane(0));
1964 else
1965 Arg = State.get(I.value(), usesFirstLaneOnly(I.value()));
1966 if (isVectorIntrinsicWithOverloadTypeAtArg(VectorIntrinsicID, I.index(),
1967 State.TTI))
1968 TysForDecl.push_back(Arg->getType());
1969 Args.push_back(Arg);
1970 }
1971
1972 // Use vector version of the intrinsic.
1973 Module *M = State.Builder.GetInsertBlock()->getModule();
1974 Function *VectorF =
1975 Intrinsic::getOrInsertDeclaration(M, VectorIntrinsicID, TysForDecl);
1976 assert(VectorF &&
1977 "Can't retrieve vector intrinsic or vector-predication intrinsics.");
1978
1981 if (CI)
1982 CI->getOperandBundlesAsDefs(OpBundles);
1983
1984 CallInst *V = State.Builder.CreateCall(VectorF, Args, OpBundles);
1985
1986 applyFlags(*V);
1987 applyMetadata(*V);
1988
1989 return V;
1990}
1991
1993 CallInst *V = createVectorCall(State);
1994 if (!V->getType()->isVoidTy())
1995 State.set(this, V);
1996}
1997
2000 const VPRecipeWithIRFlags &R, ElementCount VF, VPCostContext &Ctx) {
2001 Type *ScalarRetTy = Ctx.Types.inferScalarType(&R);
2002 // Skip the reverse operation cost for the mask.
2003 // FIXME: Remove this once redundant mask reverse operations can be eliminated
2004 // by VPlanTransforms::cse before cost computation.
2005 if (ID == Intrinsic::experimental_vp_reverse && ScalarRetTy->isIntegerTy(1))
2006 return InstructionCost(0);
2007
2008 // Some backends analyze intrinsic arguments to determine cost. Use the
2009 // underlying value for the operand if it has one. Otherwise try to use the
2010 // operand of the underlying call instruction, if there is one. Otherwise
2011 // clear Arguments.
2012 // TODO: Rework TTI interface to be independent of concrete IR values.
2014 for (const auto &[Idx, Op] : enumerate(Operands)) {
2015 auto *V = Op->getUnderlyingValue();
2016 if (!V) {
2017 if (auto *UI = dyn_cast_or_null<CallBase>(R.getUnderlyingValue())) {
2018 Arguments.push_back(UI->getArgOperand(Idx));
2019 continue;
2020 }
2021 Arguments.clear();
2022 break;
2023 }
2024 Arguments.push_back(V);
2025 }
2026
2027 Type *RetTy = VF.isVector() ? toVectorizedTy(ScalarRetTy, VF) : ScalarRetTy;
2028 SmallVector<Type *> ParamTys =
2029 map_to_vector(Operands, [&](const VPValue *Op) {
2030 return toVectorTy(Ctx.Types.inferScalarType(Op), VF);
2031 });
2032
2033 // TODO: Rework TTI interface to avoid reliance on underlying IntrinsicInst.
2034 IntrinsicCostAttributes CostAttrs(
2035 ID, RetTy, Arguments, ParamTys, R.getFastMathFlags(),
2036 dyn_cast_or_null<IntrinsicInst>(R.getUnderlyingValue()),
2038 return Ctx.TTI.getIntrinsicInstrCost(CostAttrs, Ctx.CostKind);
2039}
2040
2042 VPCostContext &Ctx) const {
2044 return computeCallCost(VectorIntrinsicID, ArgOps, *this, VF, Ctx);
2045}
2046
2048 return Intrinsic::getBaseName(VectorIntrinsicID);
2049}
2050
2052 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
2053 return all_of(enumerate(operands()), [this, &Op](const auto &X) {
2054 auto [Idx, V] = X;
2056 Idx, nullptr);
2057 });
2058}
2059
2060#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2062 VPSlotTracker &SlotTracker) const {
2063 O << Indent << "WIDEN-INTRINSIC ";
2064 if (getScalarType()->isVoidTy()) {
2065 O << "void ";
2066 } else {
2068 O << " = ";
2069 }
2070
2071 O << "call";
2072 printFlags(O);
2073 O << getIntrinsicName() << "(";
2074
2076 Op->printAsOperand(O, SlotTracker);
2077 });
2078 O << ")";
2079}
2080#endif
2081
2083 CallInst *MemI = createVectorCall(State);
2084 MemI->addParamAttr(
2085 0, Attribute::getWithAlignment(MemI->getContext(), Alignment));
2086 State.set(this, MemI);
2087}
2088
2090 Intrinsic::ID IID, Type *Ty, bool IsMasked, Align Alignment,
2091 VPCostContext &Ctx) {
2092 return Ctx.TTI.getMemIntrinsicInstrCost(
2093 MemIntrinsicCostAttributes(IID, Ty, /*Ptr=*/nullptr, IsMasked, Alignment),
2094 Ctx.CostKind);
2095}
2096
2099 VPCostContext &Ctx) const {
2100 Type *Ty = toVectorTy(getScalarType(), VF);
2102 !match(getOperand(2), m_True()), Alignment,
2103 Ctx);
2104}
2105
2107 IRBuilderBase &Builder = State.Builder;
2108
2109 Value *Address = State.get(getOperand(0));
2110 Value *IncAmt = State.get(getOperand(1), /*IsScalar=*/true);
2111 VectorType *VTy = cast<VectorType>(Address->getType());
2112
2113 // The histogram intrinsic requires a mask even if the recipe doesn't;
2114 // if the mask operand was omitted then all lanes should be executed and
2115 // we just need to synthesize an all-true mask.
2116 Value *Mask = nullptr;
2117 if (VPValue *VPMask = getMask())
2118 Mask = State.get(VPMask);
2119 else
2120 Mask =
2121 Builder.CreateVectorSplat(VTy->getElementCount(), Builder.getInt1(1));
2122
2123 // If this is a subtract, we want to invert the increment amount. We may
2124 // add a separate intrinsic in future, but for now we'll try this.
2125 if (Opcode == Instruction::Sub)
2126 IncAmt = Builder.CreateNeg(IncAmt);
2127 else
2128 assert(Opcode == Instruction::Add && "only add or sub supported for now");
2129
2130 State.Builder.CreateIntrinsic(Intrinsic::experimental_vector_histogram_add,
2131 {VTy, IncAmt->getType()},
2132 {Address, IncAmt, Mask});
2133}
2134
2136 VPCostContext &Ctx) const {
2137 // FIXME: Take the gather and scatter into account as well. For now we're
2138 // generating the same cost as the fallback path, but we'll likely
2139 // need to create a new TTI method for determining the cost, including
2140 // whether we can use base + vec-of-smaller-indices or just
2141 // vec-of-pointers.
2142 assert(VF.isVector() && "Invalid VF for histogram cost");
2143 Type *AddressTy = Ctx.Types.inferScalarType(getOperand(0));
2144 VPValue *IncAmt = getOperand(1);
2145 Type *IncTy = Ctx.Types.inferScalarType(IncAmt);
2146 VectorType *VTy = VectorType::get(IncTy, VF);
2147
2148 // Assume that a non-constant update value (or a constant != 1) requires
2149 // a multiply, and add that into the cost.
2150 InstructionCost MulCost =
2151 Ctx.TTI.getArithmeticInstrCost(Instruction::Mul, VTy, Ctx.CostKind);
2152 if (match(IncAmt, m_One()))
2153 MulCost = TTI::TCC_Free;
2154
2155 // Find the cost of the histogram operation itself.
2156 Type *PtrTy = VectorType::get(AddressTy, VF);
2157 Type *MaskTy = VectorType::get(Type::getInt1Ty(Ctx.LLVMCtx), VF);
2158 IntrinsicCostAttributes ICA(Intrinsic::experimental_vector_histogram_add,
2159 Type::getVoidTy(Ctx.LLVMCtx),
2160 {PtrTy, IncTy, MaskTy});
2161
2162 // Add the costs together with the add/sub operation.
2163 return Ctx.TTI.getIntrinsicInstrCost(ICA, Ctx.CostKind) + MulCost +
2164 Ctx.TTI.getArithmeticInstrCost(Opcode, VTy, Ctx.CostKind);
2165}
2166
2167#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2169 VPSlotTracker &SlotTracker) const {
2170 O << Indent << "WIDEN-HISTOGRAM buckets: ";
2172
2173 if (Opcode == Instruction::Sub)
2174 O << ", dec: ";
2175 else {
2176 assert(Opcode == Instruction::Add);
2177 O << ", inc: ";
2178 }
2180
2181 if (VPValue *Mask = getMask()) {
2182 O << ", mask: ";
2183 Mask->printAsOperand(O, SlotTracker);
2184 }
2185}
2186#endif
2187
2188VPIRFlags::FastMathFlagsTy::FastMathFlagsTy(const FastMathFlags &FMF) {
2189 AllowReassoc = FMF.allowReassoc();
2190 NoNaNs = FMF.noNaNs();
2191 NoInfs = FMF.noInfs();
2192 NoSignedZeros = FMF.noSignedZeros();
2193 AllowReciprocal = FMF.allowReciprocal();
2194 AllowContract = FMF.allowContract();
2195 ApproxFunc = FMF.approxFunc();
2196}
2197
2199 switch (Opcode) {
2200 case Instruction::Add:
2201 case Instruction::Sub:
2202 case Instruction::Mul:
2203 case Instruction::Shl:
2205 return WrapFlagsTy(false, false);
2206 case Instruction::Trunc:
2207 return TruncFlagsTy(false, false);
2208 case Instruction::Or:
2209 return DisjointFlagsTy(false);
2210 case Instruction::AShr:
2211 case Instruction::LShr:
2212 case Instruction::UDiv:
2213 case Instruction::SDiv:
2214 return ExactFlagsTy(false);
2215 case Instruction::GetElementPtr:
2218 return GEPNoWrapFlags::none();
2219 case Instruction::ZExt:
2220 case Instruction::UIToFP:
2221 return NonNegFlagsTy(false);
2222 case Instruction::FAdd:
2223 case Instruction::FSub:
2224 case Instruction::FMul:
2225 case Instruction::FDiv:
2226 case Instruction::FRem:
2227 case Instruction::FNeg:
2228 case Instruction::FPExt:
2229 case Instruction::FPTrunc:
2230 return FastMathFlags();
2231 case Instruction::ICmp:
2232 case Instruction::FCmp:
2234 llvm_unreachable("opcode requires explicit flags");
2235 default:
2236 return VPIRFlags();
2237 }
2238}
2239
2240#if !defined(NDEBUG)
2241bool VPIRFlags::flagsValidForOpcode(unsigned Opcode) const {
2242 switch (OpType) {
2243 case OperationType::OverflowingBinOp:
2244 return Opcode == Instruction::Add || Opcode == Instruction::Sub ||
2245 Opcode == Instruction::Mul || Opcode == Instruction::Shl ||
2246 Opcode == VPInstruction::VPInstruction::CanonicalIVIncrementForPart;
2247 case OperationType::Trunc:
2248 return Opcode == Instruction::Trunc;
2249 case OperationType::DisjointOp:
2250 return Opcode == Instruction::Or;
2251 case OperationType::PossiblyExactOp:
2252 return Opcode == Instruction::AShr || Opcode == Instruction::LShr ||
2253 Opcode == Instruction::UDiv || Opcode == Instruction::SDiv;
2254 case OperationType::GEPOp:
2255 return Opcode == Instruction::GetElementPtr ||
2256 Opcode == VPInstruction::PtrAdd ||
2257 Opcode == VPInstruction::WidePtrAdd;
2258 case OperationType::FPMathOp:
2259 return Opcode == Instruction::Call || Opcode == Instruction::FAdd ||
2260 Opcode == Instruction::FMul || Opcode == Instruction::FSub ||
2261 Opcode == Instruction::FNeg || Opcode == Instruction::FDiv ||
2262 Opcode == Instruction::FRem || Opcode == Instruction::FPExt ||
2263 Opcode == Instruction::FPTrunc || Opcode == Instruction::PHI ||
2264 Opcode == Instruction::Select ||
2265 Opcode == VPInstruction::WideIVStep ||
2267 case OperationType::FCmp:
2268 return Opcode == Instruction::FCmp;
2269 case OperationType::NonNegOp:
2270 return Opcode == Instruction::ZExt || Opcode == Instruction::UIToFP;
2271 case OperationType::Cmp:
2272 return Opcode == Instruction::FCmp || Opcode == Instruction::ICmp;
2273 case OperationType::ReductionOp:
2275 case OperationType::Other:
2276 return true;
2277 }
2278 llvm_unreachable("Unknown OperationType enum");
2279}
2280
2281bool VPIRFlags::hasRequiredFlagsForOpcode(unsigned Opcode) const {
2282 // Handle opcodes without default flags.
2283 if (Opcode == Instruction::ICmp)
2284 return OpType == OperationType::Cmp;
2285 if (Opcode == Instruction::FCmp)
2286 return OpType == OperationType::FCmp;
2288 return OpType == OperationType::ReductionOp;
2289
2290 OperationType Required = getDefaultFlags(Opcode).OpType;
2291 return Required == OperationType::Other || Required == OpType;
2292}
2293#endif
2294
2295#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2296static void printRecurrenceKind(raw_ostream &OS, const RecurKind &Kind) {
2297 switch (Kind) {
2298 case RecurKind::None:
2299 OS << "none";
2300 break;
2301 case RecurKind::Add:
2302 OS << "add";
2303 break;
2304 case RecurKind::Sub:
2305 OS << "sub";
2306 break;
2308 OS << "add-chain-with-subs";
2309 break;
2310 case RecurKind::Mul:
2311 OS << "mul";
2312 break;
2313 case RecurKind::Or:
2314 OS << "or";
2315 break;
2316 case RecurKind::And:
2317 OS << "and";
2318 break;
2319 case RecurKind::Xor:
2320 OS << "xor";
2321 break;
2322 case RecurKind::SMin:
2323 OS << "smin";
2324 break;
2325 case RecurKind::SMax:
2326 OS << "smax";
2327 break;
2328 case RecurKind::UMin:
2329 OS << "umin";
2330 break;
2331 case RecurKind::UMax:
2332 OS << "umax";
2333 break;
2334 case RecurKind::FAdd:
2335 OS << "fadd";
2336 break;
2338 OS << "fadd-chain-with-subs";
2339 break;
2340 case RecurKind::FSub:
2341 OS << "fsub";
2342 break;
2343 case RecurKind::FMul:
2344 OS << "fmul";
2345 break;
2346 case RecurKind::FMin:
2347 OS << "fmin";
2348 break;
2349 case RecurKind::FMax:
2350 OS << "fmax";
2351 break;
2352 case RecurKind::FMinNum:
2353 OS << "fminnum";
2354 break;
2355 case RecurKind::FMaxNum:
2356 OS << "fmaxnum";
2357 break;
2359 OS << "fminimum";
2360 break;
2362 OS << "fmaximum";
2363 break;
2365 OS << "fminimumnum";
2366 break;
2368 OS << "fmaximumnum";
2369 break;
2370 case RecurKind::FMulAdd:
2371 OS << "fmuladd";
2372 break;
2373 case RecurKind::AnyOf:
2374 OS << "any-of";
2375 break;
2376 case RecurKind::FindIV:
2377 OS << "find-iv";
2378 break;
2380 OS << "find-last";
2381 break;
2382 }
2383}
2384
2386 switch (OpType) {
2387 case OperationType::Cmp:
2389 break;
2390 case OperationType::FCmp:
2393 break;
2394 case OperationType::DisjointOp:
2395 if (DisjointFlags.IsDisjoint)
2396 O << " disjoint";
2397 break;
2398 case OperationType::PossiblyExactOp:
2399 if (ExactFlags.IsExact)
2400 O << " exact";
2401 break;
2402 case OperationType::OverflowingBinOp:
2403 if (WrapFlags.HasNUW)
2404 O << " nuw";
2405 if (WrapFlags.HasNSW)
2406 O << " nsw";
2407 break;
2408 case OperationType::Trunc:
2409 if (TruncFlags.HasNUW)
2410 O << " nuw";
2411 if (TruncFlags.HasNSW)
2412 O << " nsw";
2413 break;
2414 case OperationType::FPMathOp:
2416 break;
2417 case OperationType::GEPOp: {
2419 if (Flags.isInBounds())
2420 O << " inbounds";
2421 else if (Flags.hasNoUnsignedSignedWrap())
2422 O << " nusw";
2423 if (Flags.hasNoUnsignedWrap())
2424 O << " nuw";
2425 break;
2426 }
2427 case OperationType::NonNegOp:
2428 if (NonNegFlags.NonNeg)
2429 O << " nneg";
2430 break;
2431 case OperationType::ReductionOp: {
2432 O << " (";
2434 if (isReductionInLoop())
2435 O << ", in-loop";
2436 if (isReductionOrdered())
2437 O << ", ordered";
2438 O << ")";
2440 break;
2441 }
2442 case OperationType::Other:
2443 break;
2444 }
2445 O << " ";
2446}
2447#endif
2448
2450 auto &Builder = State.Builder;
2451 switch (Opcode) {
2452 case Instruction::Call:
2453 case Instruction::UncondBr:
2454 case Instruction::CondBr:
2455 case Instruction::PHI:
2456 case Instruction::GetElementPtr:
2457 llvm_unreachable("This instruction is handled by a different recipe.");
2458 case Instruction::UDiv:
2459 case Instruction::SDiv:
2460 case Instruction::SRem:
2461 case Instruction::URem:
2462 case Instruction::Add:
2463 case Instruction::FAdd:
2464 case Instruction::Sub:
2465 case Instruction::FSub:
2466 case Instruction::FNeg:
2467 case Instruction::Mul:
2468 case Instruction::FMul:
2469 case Instruction::FDiv:
2470 case Instruction::FRem:
2471 case Instruction::Shl:
2472 case Instruction::LShr:
2473 case Instruction::AShr:
2474 case Instruction::And:
2475 case Instruction::Or:
2476 case Instruction::Xor: {
2477 // Just widen unops and binops.
2479 for (VPValue *VPOp : operands())
2480 Ops.push_back(State.get(VPOp));
2481
2482 Value *V = Builder.CreateNAryOp(Opcode, Ops);
2483
2484 if (auto *VecOp = dyn_cast<Instruction>(V)) {
2485 applyFlags(*VecOp);
2486 applyMetadata(*VecOp);
2487 }
2488
2489 // Use this vector value for all users of the original instruction.
2490 State.set(this, V);
2491 break;
2492 }
2493 case Instruction::ExtractValue: {
2494 assert(getNumOperands() == 2 && "expected single level extractvalue");
2495 Value *Op = State.get(getOperand(0));
2496 Value *Extract = Builder.CreateExtractValue(
2497 Op, cast<VPConstantInt>(getOperand(1))->getZExtValue());
2498 State.set(this, Extract);
2499 break;
2500 }
2501 case Instruction::Freeze: {
2502 Value *Op = State.get(getOperand(0));
2503 Value *Freeze = Builder.CreateFreeze(Op);
2504 State.set(this, Freeze);
2505 break;
2506 }
2507 case Instruction::ICmp:
2508 case Instruction::FCmp: {
2509 // Widen compares. Generate vector compares.
2510 bool FCmp = Opcode == Instruction::FCmp;
2511 Value *A = State.get(getOperand(0));
2512 Value *B = State.get(getOperand(1));
2513 Value *C = nullptr;
2514 if (FCmp) {
2515 C = Builder.CreateFCmp(getPredicate(), A, B);
2516 } else {
2517 C = Builder.CreateICmp(getPredicate(), A, B);
2518 }
2519 if (auto *I = dyn_cast<Instruction>(C)) {
2520 applyFlags(*I);
2521 applyMetadata(*I);
2522 }
2523 State.set(this, C);
2524 break;
2525 }
2526 case Instruction::Select: {
2527 VPValue *CondOp = getOperand(0);
2528 Value *Cond = State.get(CondOp, vputils::isSingleScalar(CondOp));
2529 Value *Op0 = State.get(getOperand(1));
2530 Value *Op1 = State.get(getOperand(2));
2531 Value *Sel = State.Builder.CreateSelect(Cond, Op0, Op1);
2532 State.set(this, Sel);
2533 if (auto *I = dyn_cast<Instruction>(Sel)) {
2535 applyFlags(*I);
2536 applyMetadata(*I);
2537 }
2538 break;
2539 }
2540 default:
2541 // This instruction is not vectorized by simple widening.
2542 LLVM_DEBUG(dbgs() << "LV: Found an unhandled opcode : "
2543 << Instruction::getOpcodeName(Opcode));
2544 llvm_unreachable("Unhandled instruction!");
2545 } // end of switch.
2546
2547#if !defined(NDEBUG)
2548 // Verify that VPlan type inference results agree with the type of the
2549 // generated values.
2550 assert(VectorType::get(State.TypeAnalysis.inferScalarType(this), State.VF) ==
2551 State.get(this)->getType() &&
2552 "inferred type and type from generated instructions do not match");
2553#endif
2554}
2555
2557 VPCostContext &Ctx) const {
2558 switch (Opcode) {
2559 case Instruction::UDiv:
2560 case Instruction::SDiv:
2561 case Instruction::SRem:
2562 case Instruction::URem:
2563 // If the div/rem operation isn't safe to speculate and requires
2564 // predication, then the only way we can even create a vplan is to insert
2565 // a select on the second input operand to ensure we use the value of 1
2566 // for the inactive lanes. The select will be costed separately.
2567 case Instruction::FNeg:
2568 case Instruction::Add:
2569 case Instruction::FAdd:
2570 case Instruction::Sub:
2571 case Instruction::FSub:
2572 case Instruction::Mul:
2573 case Instruction::FMul:
2574 case Instruction::FDiv:
2575 case Instruction::FRem:
2576 case Instruction::Shl:
2577 case Instruction::LShr:
2578 case Instruction::AShr:
2579 case Instruction::And:
2580 case Instruction::Or:
2581 case Instruction::Xor:
2582 case Instruction::Freeze:
2583 case Instruction::ExtractValue:
2584 case Instruction::ICmp:
2585 case Instruction::FCmp:
2586 case Instruction::Select:
2587 return getCostForRecipeWithOpcode(getOpcode(), VF, Ctx);
2588 default:
2589 llvm_unreachable("Unsupported opcode for instruction");
2590 }
2591}
2592
2593#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2595 VPSlotTracker &SlotTracker) const {
2596 O << Indent << "WIDEN ";
2598 O << " = " << Instruction::getOpcodeName(Opcode);
2599 printFlags(O);
2601}
2602#endif
2603
2605 auto &Builder = State.Builder;
2606 /// Vectorize casts.
2607 assert(State.VF.isVector() && "Not vectorizing?");
2608 Type *DestTy = VectorType::get(getScalarType(), State.VF);
2609 VPValue *Op = getOperand(0);
2610 Value *A = State.get(Op);
2611 Value *Cast = Builder.CreateCast(Instruction::CastOps(Opcode), A, DestTy);
2612 State.set(this, Cast);
2613 if (auto *CastOp = dyn_cast<Instruction>(Cast)) {
2614 applyFlags(*CastOp);
2615 applyMetadata(*CastOp);
2616 }
2617}
2618
2623
2624#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2626 VPSlotTracker &SlotTracker) const {
2627 O << Indent << "WIDEN-CAST ";
2629 O << " = " << Instruction::getOpcodeName(Opcode);
2630 printFlags(O);
2632 O << " to " << *getScalarType();
2633}
2634#endif
2635
2637 VPCostContext &Ctx) const {
2638 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
2639}
2640
2641#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2643 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
2644 O << Indent;
2646 O << " = WIDEN-INDUCTION";
2647 printFlags(O);
2649
2650 if (auto *TI = getTruncInst())
2651 O << " (truncated to " << *TI->getType() << ")";
2652}
2653#endif
2654
2656 // The step may be defined by a recipe in the preheader (e.g. if it requires
2657 // SCEV expansion), but for the canonical induction the step is required to be
2658 // 1, which is represented as live-in.
2659 return match(getStartValue(), m_ZeroInt()) &&
2660 match(getStepValue(), m_One()) &&
2661 getScalarType() == getRegion()->getCanonicalIVType();
2662}
2663
2664#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2666 VPSlotTracker &SlotTracker) const {
2667 O << Indent;
2669 O << " = DERIVED-IV ";
2670 getStartValue()->printAsOperand(O, SlotTracker);
2671 O << " + ";
2672 getOperand(1)->printAsOperand(O, SlotTracker);
2673 O << " * ";
2674 getStepValue()->printAsOperand(O, SlotTracker);
2675}
2676#endif
2677
2679 // Fast-math-flags propagate from the original induction instruction.
2680 IRBuilder<>::FastMathFlagGuard FMFG(State.Builder);
2681 State.Builder.setFastMathFlags(getFastMathFlags());
2682
2683 /// Compute scalar induction steps. \p ScalarIV is the scalar induction
2684 /// variable on which to base the steps, \p Step is the size of the step.
2685
2686 Value *BaseIV = State.get(getOperand(0), VPLane(0));
2687 Value *Step = State.get(getStepValue(), VPLane(0));
2688 IRBuilderBase &Builder = State.Builder;
2689
2690 // Ensure step has the same type as that of scalar IV.
2691 Type *BaseIVTy = BaseIV->getType()->getScalarType();
2692 assert(BaseIVTy == Step->getType() && "Types of BaseIV and Step must match!");
2693
2694 // We build scalar steps for both integer and floating-point induction
2695 // variables. Here, we determine the kind of arithmetic we will perform.
2698 if (BaseIVTy->isIntegerTy()) {
2699 AddOp = Instruction::Add;
2700 MulOp = Instruction::Mul;
2701 } else {
2702 AddOp = InductionOpcode;
2703 MulOp = Instruction::FMul;
2704 }
2705
2706 // Determine the number of scalars we need to generate.
2707 bool FirstLaneOnly = vputils::onlyFirstLaneUsed(this);
2708 // Compute the scalar steps and save the results in State.
2709
2710 unsigned EndLane = FirstLaneOnly ? 1 : State.VF.getKnownMinValue();
2711 Value *StartIdx0 = getStartIndex() ? State.get(getStartIndex(), true)
2712 : Constant::getNullValue(BaseIVTy);
2713
2714 for (unsigned Lane = 0; Lane < EndLane; ++Lane) {
2715 // It is okay if the induction variable type cannot hold the lane number,
2716 // we expect truncation in this case.
2717 Constant *LaneValue =
2718 BaseIVTy->isIntegerTy()
2719 ? ConstantInt::get(BaseIVTy, Lane, /*IsSigned=*/false,
2720 /*ImplicitTrunc=*/true)
2721 : ConstantFP::get(BaseIVTy, Lane);
2722 Value *StartIdx = Builder.CreateBinOp(AddOp, StartIdx0, LaneValue);
2723 assert((State.VF.isScalable() || isa<Constant>(StartIdx)) &&
2724 "Expected StartIdx to be folded to a constant when VF is not "
2725 "scalable");
2726 auto *Mul = Builder.CreateBinOp(MulOp, StartIdx, Step);
2727 auto *Add = Builder.CreateBinOp(AddOp, BaseIV, Mul);
2728 State.set(this, Add, VPLane(Lane));
2729 }
2730}
2731
2732#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2734 VPSlotTracker &SlotTracker) const {
2735 O << Indent;
2737 O << " = SCALAR-STEPS ";
2739}
2740#endif
2741
2743 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
2745}
2746
2748 assert(State.VF.isVector() && "not widening");
2749 // Construct a vector GEP by widening the operands of the scalar GEP as
2750 // necessary. We mark the vector GEP 'inbounds' if appropriate. A GEP
2751 // results in a vector of pointers when at least one operand of the GEP
2752 // is vector-typed. Thus, to keep the representation compact, we only use
2753 // vector-typed operands for loop-varying values.
2754
2755 bool AllOperandsAreInvariant = all_of(operands(), [](VPValue *Op) {
2756 return Op->isDefinedOutsideLoopRegions();
2757 });
2758 if (AllOperandsAreInvariant) {
2759 // If we are vectorizing, but the GEP has only loop-invariant operands,
2760 // the GEP we build (by only using vector-typed operands for
2761 // loop-varying values) would be a scalar pointer. Thus, to ensure we
2762 // produce a vector of pointers, we need to either arbitrarily pick an
2763 // operand to broadcast, or broadcast a clone of the original GEP.
2764 // Here, we broadcast a clone of the original.
2765
2767 for (unsigned I = 0, E = getNumOperands(); I != E; I++)
2768 Ops.push_back(State.get(getOperand(I), VPLane(0)));
2769
2770 auto *NewGEP =
2771 State.Builder.CreateGEP(getSourceElementType(), Ops[0], drop_begin(Ops),
2772 "", getGEPNoWrapFlags());
2773 Value *Splat = State.Builder.CreateVectorSplat(State.VF, NewGEP);
2774 State.set(this, Splat);
2775 return;
2776 }
2777
2778 // If the GEP has at least one loop-varying operand, we are sure to
2779 // produce a vector of pointers unless VF is scalar.
2780 // The pointer operand of the new GEP. If it's loop-invariant, we
2781 // won't broadcast it.
2782 auto *Ptr = State.get(getOperand(0), isPointerLoopInvariant());
2783
2784 // Collect all the indices for the new GEP. If any index is
2785 // loop-invariant, we won't broadcast it.
2787 for (unsigned I = 1, E = getNumOperands(); I < E; I++) {
2788 VPValue *Operand = getOperand(I);
2789 Indices.push_back(State.get(Operand, isIndexLoopInvariant(I - 1)));
2790 }
2791
2792 // Create the new GEP. Note that this GEP may be a scalar if VF == 1,
2793 // but it should be a vector, otherwise.
2794 auto *NewGEP = State.Builder.CreateGEP(getSourceElementType(), Ptr, Indices,
2795 "", getGEPNoWrapFlags());
2796 assert((State.VF.isScalar() || NewGEP->getType()->isVectorTy()) &&
2797 "NewGEP is not a pointer vector");
2798 State.set(this, NewGEP);
2799}
2800
2801#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2803 VPSlotTracker &SlotTracker) const {
2804 O << Indent << "WIDEN-GEP ";
2805 O << (isPointerLoopInvariant() ? "Inv" : "Var");
2806 for (size_t I = 0; I < getNumOperands() - 1; ++I)
2807 O << "[" << (isIndexLoopInvariant(I) ? "Inv" : "Var") << "]";
2808
2809 O << " ";
2811 O << " = getelementptr";
2812 printFlags(O);
2814}
2815#endif
2816
2818 assert(!getOffset() && "Unexpected offset operand");
2819 VPBuilder Builder(this);
2820 VPlan &Plan = *getParent()->getPlan();
2821 VPValue *VFVal = getVFValue();
2822 VPTypeAnalysis TypeInfo(Plan);
2823 const DataLayout &DL = Plan.getDataLayout();
2824 Type *IndexTy = DL.getIndexType(TypeInfo.inferScalarType(this));
2825 VPValue *Stride =
2826 Plan.getConstantInt(IndexTy, getStride(), /*IsSigned=*/true);
2827 Type *VFTy = TypeInfo.inferScalarType(VFVal);
2828 VPValue *VF = Builder.createScalarZExtOrTrunc(VFVal, IndexTy, VFTy,
2830
2831 // Offset for Part0 = Offset0 = Stride * (VF - 1).
2832 VPInstruction *VFMinusOne =
2833 Builder.createSub(VF, Plan.getConstantInt(IndexTy, 1u),
2834 DebugLoc::getUnknown(), "", {true, true});
2835 VPInstruction *Offset0 =
2836 Builder.createOverflowingOp(Instruction::Mul, {VFMinusOne, Stride});
2837
2838 // Offset for PartN = Offset0 + Part * Stride * VF.
2839 VPValue *PartxStride =
2840 Plan.getConstantInt(IndexTy, Part * getStride(), /*IsSigned=*/true);
2841 VPValue *Offset = Builder.createAdd(
2842 Offset0,
2843 Builder.createOverflowingOp(Instruction::Mul, {PartxStride, VF}));
2845}
2846
2848 auto &Builder = State.Builder;
2849 assert(getOffset() && "Expected prior materialization of offset");
2850 Value *Ptr = State.get(getPointer(), true);
2851 Value *Offset = State.get(getOffset(), true);
2852 Value *ResultPtr = Builder.CreateGEP(getSourceElementType(), Ptr, Offset, "",
2854 State.set(this, ResultPtr, /*IsScalar*/ true);
2855}
2856
2857#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2859 VPSlotTracker &SlotTracker) const {
2860 O << Indent;
2862 O << " = vector-end-pointer";
2863 printFlags(O);
2865}
2866#endif
2867
2869 assert(getVFxPart() &&
2870 "Expected prior simplification of recipe without VFxPart");
2871
2872 auto &Builder = State.Builder;
2873 Value *Ptr = State.get(getOperand(0), VPLane(0));
2874 Value *Offset = State.get(getVFxPart(), true);
2875 // TODO: Expand to VPInstruction to support constant folding.
2876 if (!match(getStride(), m_One())) {
2877 Value *Stride = Builder.CreateZExtOrTrunc(State.get(getStride(), true),
2878 Offset->getType());
2879 Offset = Builder.CreateMul(Offset, Stride);
2880 }
2881 Value *ResultPtr = Builder.CreateGEP(getSourceElementType(), Ptr, Offset, "",
2883 State.set(this, ResultPtr, /*IsScalar*/ true);
2884}
2885
2886#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2888 VPSlotTracker &SlotTracker) const {
2889 O << Indent;
2891 O << " = vector-pointer";
2892 printFlags(O);
2894}
2895#endif
2896
2898 VPCostContext &Ctx) const {
2899 // A blend will be expanded to a select VPInstruction, which will generate a
2900 // scalar select if only the first lane is used.
2902 VF = ElementCount::getFixed(1);
2903
2904 Type *ResultTy = toVectorTy(Ctx.Types.inferScalarType(this), VF);
2905 Type *CmpTy = toVectorTy(Type::getInt1Ty(Ctx.Types.getContext()), VF);
2906 return (getNumIncomingValues() - 1) *
2907 Ctx.TTI.getCmpSelInstrCost(Instruction::Select, ResultTy, CmpTy,
2908 CmpInst::BAD_ICMP_PREDICATE, Ctx.CostKind);
2909}
2910
2911#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2913 VPSlotTracker &SlotTracker) const {
2914 O << Indent << "BLEND ";
2916 O << " =";
2917 printFlags(O);
2918 if (getNumIncomingValues() == 1) {
2919 // Not a User of any mask: not really blending, this is a
2920 // single-predecessor phi.
2921 getIncomingValue(0)->printAsOperand(O, SlotTracker);
2922 } else {
2923 for (unsigned I = 0, E = getNumIncomingValues(); I < E; ++I) {
2924 if (I != 0)
2925 O << " ";
2926 getIncomingValue(I)->printAsOperand(O, SlotTracker);
2927 if (I == 0 && isNormalized())
2928 continue;
2929 O << "/";
2930 getMask(I)->printAsOperand(O, SlotTracker);
2931 }
2932 }
2933}
2934#endif
2935
2939 "In-loop AnyOf reductions aren't currently supported");
2940 // Propagate the fast-math flags carried by the underlying instruction.
2941 IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder);
2942 State.Builder.setFastMathFlags(getFastMathFlags());
2943 Value *NewVecOp = State.get(getVecOp());
2944 if (VPValue *Cond = getCondOp()) {
2945 Value *NewCond = State.get(Cond, State.VF.isScalar());
2946 VectorType *VecTy = dyn_cast<VectorType>(NewVecOp->getType());
2947 Type *ElementTy = VecTy ? VecTy->getElementType() : NewVecOp->getType();
2948
2949 Value *Start = getRecurrenceIdentity(Kind, ElementTy, getFastMathFlags());
2950 if (State.VF.isVector())
2951 Start = State.Builder.CreateVectorSplat(VecTy->getElementCount(), Start);
2952
2953 Value *Select = State.Builder.CreateSelect(NewCond, NewVecOp, Start);
2954 NewVecOp = Select;
2955 }
2956 Value *NewRed;
2957 Value *NextInChain;
2958 if (isOrdered()) {
2959 Value *PrevInChain = State.get(getChainOp(), /*IsScalar*/ true);
2960 if (State.VF.isVector())
2961 NewRed =
2962 createOrderedReduction(State.Builder, Kind, NewVecOp, PrevInChain);
2963 else
2964 NewRed = State.Builder.CreateBinOp(
2966 PrevInChain, NewVecOp);
2967 PrevInChain = NewRed;
2968 NextInChain = NewRed;
2969 } else if (isPartialReduction()) {
2970 assert((Kind == RecurKind::Add || Kind == RecurKind::FAdd) &&
2971 "Unexpected partial reduction kind");
2972 Value *PrevInChain = State.get(getChainOp(), /*IsScalar*/ false);
2973 NewRed = State.Builder.CreateIntrinsic(
2974 PrevInChain->getType(),
2975 Kind == RecurKind::Add ? Intrinsic::vector_partial_reduce_add
2976 : Intrinsic::vector_partial_reduce_fadd,
2977 {PrevInChain, NewVecOp}, State.Builder.getFastMathFlags(),
2978 "partial.reduce");
2979 PrevInChain = NewRed;
2980 NextInChain = NewRed;
2981 } else {
2982 assert(isInLoop() &&
2983 "The reduction must either be ordered, partial or in-loop");
2984 Value *PrevInChain = State.get(getChainOp(), /*IsScalar*/ true);
2985 NewRed = createSimpleReduction(State.Builder, NewVecOp, Kind);
2987 NextInChain = createMinMaxOp(State.Builder, Kind, NewRed, PrevInChain);
2988 else
2989 NextInChain = State.Builder.CreateBinOp(
2991 PrevInChain, NewRed);
2992 }
2993 State.set(this, NextInChain, /*IsScalar*/ !isPartialReduction());
2994}
2995
2997
2998 auto &Builder = State.Builder;
2999 // Propagate the fast-math flags carried by the underlying instruction.
3000 IRBuilderBase::FastMathFlagGuard FMFGuard(Builder);
3001 Builder.setFastMathFlags(getFastMathFlags());
3002
3004 Value *Prev = State.get(getChainOp(), /*IsScalar*/ true);
3005 Value *VecOp = State.get(getVecOp());
3006 Value *EVL = State.get(getEVL(), VPLane(0));
3007
3008 Value *Mask;
3009 if (VPValue *CondOp = getCondOp())
3010 Mask = State.get(CondOp);
3011 else
3012 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
3013
3014 Value *NewRed;
3015 if (isOrdered()) {
3016 NewRed = createOrderedReduction(Builder, Kind, VecOp, Prev, Mask, EVL);
3017 } else {
3018 NewRed = createSimpleReduction(Builder, VecOp, Kind, Mask, EVL);
3020 NewRed = createMinMaxOp(Builder, Kind, NewRed, Prev);
3021 else
3022 NewRed = Builder.CreateBinOp(
3024 Prev);
3025 }
3026 State.set(this, NewRed, /*IsScalar*/ true);
3027}
3028
3030 VPCostContext &Ctx) const {
3031 RecurKind RdxKind = getRecurrenceKind();
3032 Type *ElementTy = Ctx.Types.inferScalarType(this);
3033 auto *VectorTy = cast<VectorType>(toVectorTy(ElementTy, VF));
3034 unsigned Opcode = RecurrenceDescriptor::getOpcode(RdxKind);
3036 std::optional<FastMathFlags> OptionalFMF =
3037 ElementTy->isFloatingPointTy() ? std::make_optional(FMFs) : std::nullopt;
3038
3039 if (isPartialReduction()) {
3040 InstructionCost CondCost = 0;
3041 if (isConditional()) {
3043 auto *CondTy = cast<VectorType>(
3044 toVectorTy(Ctx.Types.inferScalarType(getCondOp()), VF));
3045 CondCost = Ctx.TTI.getCmpSelInstrCost(Instruction::Select, VectorTy,
3046 CondTy, Pred, Ctx.CostKind);
3047 }
3048 return CondCost + Ctx.TTI.getPartialReductionCost(
3049 Opcode, ElementTy, ElementTy, ElementTy, VF,
3050 TTI::PR_None, TTI::PR_None, {}, Ctx.CostKind,
3051 OptionalFMF);
3052 }
3053
3054 // TODO: Support any-of reductions.
3055 assert(
3057 ForceTargetInstructionCost.getNumOccurrences() > 0) &&
3058 "Any-of reduction not implemented in VPlan-based cost model currently.");
3059
3060 // Note that TTI should model the cost of moving result to the scalar register
3061 // and the BinOp cost in the getMinMaxReductionCost().
3064 return Ctx.TTI.getMinMaxReductionCost(Id, VectorTy, FMFs, Ctx.CostKind);
3065 }
3066
3067 // Note that TTI should model the cost of moving result to the scalar register
3068 // and the BinOp cost in the getArithmeticReductionCost().
3069 return Ctx.TTI.getArithmeticReductionCost(Opcode, VectorTy, OptionalFMF,
3070 Ctx.CostKind);
3071}
3072
3073VPExpressionRecipe::VPExpressionRecipe(
3074 ExpressionTypes ExpressionType,
3075 ArrayRef<VPSingleDefRecipe *> ExpressionRecipes)
3076 : VPSingleDefRecipe(VPRecipeBase::VPExpressionSC, {}),
3077 ExpressionRecipes(ExpressionRecipes), ExpressionType(ExpressionType) {
3078 assert(!ExpressionRecipes.empty() && "Nothing to combine?");
3079 assert(
3080 none_of(ExpressionRecipes,
3081 [](VPSingleDefRecipe *R) { return R->mayHaveSideEffects(); }) &&
3082 "expression cannot contain recipes with side-effects");
3083
3084 // Maintain a copy of the expression recipes as a set of users.
3085 SmallPtrSet<VPUser *, 4> ExpressionRecipesAsSetOfUsers;
3086 for (auto *R : ExpressionRecipes)
3087 ExpressionRecipesAsSetOfUsers.insert(R);
3088
3089 // Recipes in the expression, except the last one, must only be used by
3090 // (other) recipes inside the expression. If there are other users, external
3091 // to the expression, use a clone of the recipe for external users.
3092 for (VPSingleDefRecipe *R : reverse(ExpressionRecipes)) {
3093 if (R != ExpressionRecipes.back() &&
3094 any_of(R->users(), [&ExpressionRecipesAsSetOfUsers](VPUser *U) {
3095 return !ExpressionRecipesAsSetOfUsers.contains(U);
3096 })) {
3097 // There are users outside of the expression. Clone the recipe and use the
3098 // clone those external users.
3099 VPSingleDefRecipe *CopyForExtUsers = R->clone();
3100 R->replaceUsesWithIf(CopyForExtUsers, [&ExpressionRecipesAsSetOfUsers](
3101 VPUser &U, unsigned) {
3102 return !ExpressionRecipesAsSetOfUsers.contains(&U);
3103 });
3104 CopyForExtUsers->insertBefore(R);
3105 }
3106 if (R->getParent())
3107 R->removeFromParent();
3108 }
3109
3110 // Internalize all external operands to the expression recipes. To do so,
3111 // create new temporary VPValues for all operands defined by a recipe outside
3112 // the expression. The original operands are added as operands of the
3113 // VPExpressionRecipe itself.
3114 for (auto *R : ExpressionRecipes) {
3115 for (const auto &[Idx, Op] : enumerate(R->operands())) {
3116 auto *Def = Op->getDefiningRecipe();
3117 if (Def && ExpressionRecipesAsSetOfUsers.contains(Def))
3118 continue;
3119 addOperand(Op);
3120 LiveInPlaceholders.push_back(new VPSymbolicValue(nullptr));
3121 }
3122 }
3123
3124 // Replace each external operand with the first one created for it in
3125 // LiveInPlaceholders.
3126 for (auto *R : ExpressionRecipes)
3127 for (auto const &[LiveIn, Tmp] : zip(operands(), LiveInPlaceholders))
3128 R->replaceUsesOfWith(LiveIn, Tmp);
3129}
3130
3132 for (auto *R : ExpressionRecipes)
3133 // Since the list could contain duplicates, make sure the recipe hasn't
3134 // already been inserted.
3135 if (!R->getParent())
3136 R->insertBefore(this);
3137
3138 for (const auto &[Idx, Op] : enumerate(operands()))
3139 LiveInPlaceholders[Idx]->replaceAllUsesWith(Op);
3140
3141 replaceAllUsesWith(ExpressionRecipes.back());
3142 ExpressionRecipes.clear();
3143}
3144
3146 VPCostContext &Ctx) const {
3147 Type *RedTy = Ctx.Types.inferScalarType(this);
3148 auto *SrcVecTy = cast<VectorType>(
3149 toVectorTy(Ctx.Types.inferScalarType(getOperand(0)), VF));
3150 unsigned Opcode = RecurrenceDescriptor::getOpcode(
3151 cast<VPReductionRecipe>(ExpressionRecipes.back())->getRecurrenceKind());
3152 switch (ExpressionType) {
3153 case ExpressionTypes::ExtendedReduction: {
3154 unsigned Opcode = RecurrenceDescriptor::getOpcode(
3155 cast<VPReductionRecipe>(ExpressionRecipes[1])->getRecurrenceKind());
3156 auto *ExtR = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3157 auto *RedR = cast<VPReductionRecipe>(ExpressionRecipes.back());
3158
3159 if (RedR->isPartialReduction())
3160 return Ctx.TTI.getPartialReductionCost(
3161 Opcode, Ctx.Types.inferScalarType(getOperand(0)), nullptr, RedTy, VF,
3163 TargetTransformInfo::PR_None, std::nullopt, Ctx.CostKind,
3164 RedTy->isFloatingPointTy() ? std::optional{RedR->getFastMathFlags()}
3165 : std::nullopt);
3166 else if (!RedTy->isFloatingPointTy())
3167 // TTI::getExtendedReductionCost only supports integer types.
3168 return Ctx.TTI.getExtendedReductionCost(
3169 Opcode, ExtR->getOpcode() == Instruction::ZExt, RedTy, SrcVecTy,
3170 std::nullopt, Ctx.CostKind);
3171 else
3173 }
3174 case ExpressionTypes::MulAccReduction:
3175 return Ctx.TTI.getMulAccReductionCost(false, Opcode, RedTy, SrcVecTy,
3176 Ctx.CostKind);
3177
3178 case ExpressionTypes::ExtNegatedMulAccReduction:
3179 assert(Opcode == Instruction::Add && "Unexpected opcode");
3180 Opcode = Instruction::Sub;
3181 [[fallthrough]];
3182 case ExpressionTypes::ExtMulAccReduction: {
3183 auto *RedR = cast<VPReductionRecipe>(ExpressionRecipes.back());
3184 if (RedR->isPartialReduction()) {
3185 auto *Ext0R = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3186 auto *Ext1R = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
3187 auto *Mul = cast<VPWidenRecipe>(ExpressionRecipes[2]);
3188 return Ctx.TTI.getPartialReductionCost(
3189 Opcode, Ctx.Types.inferScalarType(getOperand(0)),
3190 Ctx.Types.inferScalarType(getOperand(1)), RedTy, VF,
3192 Ext0R->getOpcode()),
3194 Ext1R->getOpcode()),
3195 Mul->getOpcode(), Ctx.CostKind,
3196 RedTy->isFloatingPointTy() ? std::optional{RedR->getFastMathFlags()}
3197 : std::nullopt);
3198 }
3199 return Ctx.TTI.getMulAccReductionCost(
3200 cast<VPWidenCastRecipe>(ExpressionRecipes.front())->getOpcode() ==
3201 Instruction::ZExt,
3202 Opcode, RedTy, SrcVecTy, Ctx.CostKind);
3203 }
3204 }
3205 llvm_unreachable("Unknown VPExpressionRecipe::ExpressionTypes enum");
3206}
3207
3209 return any_of(ExpressionRecipes, [](VPSingleDefRecipe *R) {
3210 return R->mayReadFromMemory() || R->mayWriteToMemory();
3211 });
3212}
3213
3215 assert(
3216 none_of(ExpressionRecipes,
3217 [](VPSingleDefRecipe *R) { return R->mayHaveSideEffects(); }) &&
3218 "expression cannot contain recipes with side-effects");
3219 return false;
3220}
3221
3223 // Cannot use vputils::isSingleScalar(), because all external operands
3224 // of the expression will be live-ins while bundled.
3225 auto *RR = dyn_cast<VPReductionRecipe>(ExpressionRecipes.back());
3226 return RR && !RR->isPartialReduction();
3227}
3228
3229#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3230
3232 VPSlotTracker &SlotTracker) const {
3233 O << Indent << "EXPRESSION ";
3235 O << " = ";
3236 auto *Red = cast<VPReductionRecipe>(ExpressionRecipes.back());
3237 unsigned Opcode = RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind());
3238
3239 switch (ExpressionType) {
3240 case ExpressionTypes::ExtendedReduction: {
3242 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
3243 O << Instruction::getOpcodeName(Opcode) << " (";
3245 Red->printFlags(O);
3246
3247 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3248 O << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
3249 << *Ext0->getScalarType();
3250 if (Red->isConditional()) {
3251 O << ", ";
3252 Red->getCondOp()->printAsOperand(O, SlotTracker);
3253 }
3254 O << ")";
3255 break;
3256 }
3257 case ExpressionTypes::ExtNegatedMulAccReduction: {
3259 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
3261 RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind()))
3262 << " (sub (0, mul";
3263 auto *Mul = cast<VPWidenRecipe>(ExpressionRecipes[2]);
3264 Mul->printFlags(O);
3265 O << "(";
3267 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3268 O << " " << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
3269 << *Ext0->getScalarType() << "), (";
3271 auto *Ext1 = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
3272 O << " " << Instruction::getOpcodeName(Ext1->getOpcode()) << " to "
3273 << *Ext1->getScalarType() << ")";
3274 if (Red->isConditional()) {
3275 O << ", ";
3276 Red->getCondOp()->printAsOperand(O, SlotTracker);
3277 }
3278 O << "))";
3279 break;
3280 }
3281 case ExpressionTypes::MulAccReduction:
3282 case ExpressionTypes::ExtMulAccReduction: {
3284 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
3286 RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind()))
3287 << " (";
3288 O << "mul";
3289 bool IsExtended = ExpressionType == ExpressionTypes::ExtMulAccReduction;
3290 auto *Mul = cast<VPWidenRecipe>(IsExtended ? ExpressionRecipes[2]
3291 : ExpressionRecipes[0]);
3292 Mul->printFlags(O);
3293 if (IsExtended)
3294 O << "(";
3296 if (IsExtended) {
3297 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3298 O << " " << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
3299 << *Ext0->getScalarType() << "), (";
3300 } else {
3301 O << ", ";
3302 }
3304 if (IsExtended) {
3305 auto *Ext1 = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
3306 O << " " << Instruction::getOpcodeName(Ext1->getOpcode()) << " to "
3307 << *Ext1->getScalarType() << ")";
3308 }
3309 if (Red->isConditional()) {
3310 O << ", ";
3311 Red->getCondOp()->printAsOperand(O, SlotTracker);
3312 }
3313 O << ")";
3314 break;
3315 }
3316 }
3317}
3318
3320 VPSlotTracker &SlotTracker) const {
3321 if (isPartialReduction())
3322 O << Indent << "PARTIAL-REDUCE ";
3323 else
3324 O << Indent << "REDUCE ";
3326 O << " = ";
3328 O << " +";
3329 printFlags(O);
3330 O << " reduce.";
3332 O << " (";
3334 if (isConditional()) {
3335 O << ", ";
3337 }
3338 O << ")";
3339}
3340
3342 VPSlotTracker &SlotTracker) const {
3343 O << Indent << "REDUCE ";
3345 O << " = ";
3347 O << " +";
3348 printFlags(O);
3349 O << " vp.reduce."
3352 << " (";
3354 O << ", ";
3356 if (isConditional()) {
3357 O << ", ";
3359 }
3360 O << ")";
3361}
3362
3363#endif
3364
3366 assert(IsSingleScalar &&
3367 "VPReplicateRecipes must be unrolled before ::execute");
3368 auto *Instr = getUnderlyingInstr();
3369 Instruction *Cloned = Instr->clone();
3370 Type *ResultTy = State.TypeAnalysis.inferScalarType(this);
3371 if (!ResultTy->isVoidTy()) {
3372 Cloned->setName(Instr->getName() + ".cloned");
3373 // The operands of the replicate recipe may have been narrowed, resulting in
3374 // a narrower result type. Update the type of the cloned instruction to the
3375 // correct type.
3376 if (ResultTy != Cloned->getType())
3377 Cloned->mutateType(ResultTy);
3378 }
3379
3380 applyFlags(*Cloned);
3381 applyMetadata(*Cloned);
3382
3383 if (hasPredicate())
3384 cast<CmpInst>(Cloned)->setPredicate(getPredicate());
3385
3386 // Replace the operands of the cloned instructions with their scalar
3387 // equivalents in the new loop.
3388 for (const auto &[Idx, V] : enumerate(operands()))
3389 Cloned->setOperand(Idx, State.get(V, true));
3390
3391 // Place the cloned scalar in the new loop.
3392 State.Builder.Insert(Cloned);
3393
3394 State.set(this, Cloned, true);
3395
3396 // If we just cloned a new assumption, add it the assumption cache.
3397 if (auto *II = dyn_cast<AssumeInst>(Cloned))
3398 State.AC->registerAssumption(II);
3399}
3400
3401/// Returns a SCEV expression for \p Ptr if it is a pointer computation for
3402/// which the legacy cost model computes a SCEV expression when computing the
3403/// address cost. Computing SCEVs for VPValues is incomplete and returns
3404/// SCEVCouldNotCompute in cases the legacy cost model can compute SCEVs. In
3405/// those cases we fall back to the legacy cost model. Otherwise return nullptr.
3406static const SCEV *getAddressAccessSCEV(const VPValue *Ptr,
3408 const Loop *L) {
3409 const SCEV *Addr = vputils::getSCEVExprForVPValue(Ptr, PSE, L);
3410 if (isa<SCEVCouldNotCompute>(Addr))
3411 return Addr;
3412
3413 return vputils::isAddressSCEVForCost(Addr, *PSE.getSE(), L) ? Addr : nullptr;
3414}
3415
3416/// Return true if \p R is a predicated load/store with a loop-invariant address
3417/// only masked by the header mask.
3419 const SCEV *PtrSCEV,
3420 VPCostContext &Ctx) {
3421 const VPRegionBlock *ParentRegion = R.getRegion();
3422 if (!ParentRegion || !ParentRegion->isReplicator() || !PtrSCEV ||
3423 !Ctx.PSE.getSE()->isLoopInvariant(PtrSCEV, Ctx.L))
3424 return false;
3425 auto *BOM =
3427 return vputils::isHeaderMask(BOM->getOperand(0), *ParentRegion->getPlan());
3428}
3429
3431 VPCostContext &Ctx) const {
3433 // VPReplicateRecipe may be cloned as part of an existing VPlan-to-VPlan
3434 // transform, avoid computing their cost multiple times for now.
3435 Ctx.SkipCostComputation.insert(UI);
3436
3437 if (VF.isScalable() && !isSingleScalar())
3439
3440 switch (UI->getOpcode()) {
3441 case Instruction::Alloca:
3442 if (VF.isScalable())
3444 return Ctx.TTI.getArithmeticInstrCost(
3445 Instruction::Mul, Ctx.Types.inferScalarType(this), Ctx.CostKind);
3446 case Instruction::GetElementPtr:
3447 // We mark this instruction as zero-cost because the cost of GEPs in
3448 // vectorized code depends on whether the corresponding memory instruction
3449 // is scalarized or not. Therefore, we handle GEPs with the memory
3450 // instruction cost.
3451 return 0;
3452 case Instruction::Call: {
3453 auto *CalledFn =
3455 Type *ResultTy = Ctx.Types.inferScalarType(this);
3457 return computeCallCost(CalledFn, ResultTy, ArgOps, isSingleScalar(), VF,
3458 Ctx);
3459 }
3460 case Instruction::Add:
3461 case Instruction::Sub:
3462 case Instruction::FAdd:
3463 case Instruction::FSub:
3464 case Instruction::Mul:
3465 case Instruction::FMul:
3466 case Instruction::FDiv:
3467 case Instruction::FRem:
3468 case Instruction::Shl:
3469 case Instruction::LShr:
3470 case Instruction::AShr:
3471 case Instruction::And:
3472 case Instruction::Or:
3473 case Instruction::Xor:
3474 case Instruction::ICmp:
3475 case Instruction::FCmp:
3477 Ctx) *
3478 (isSingleScalar() ? 1 : VF.getFixedValue());
3479 case Instruction::SDiv:
3480 case Instruction::UDiv:
3481 case Instruction::SRem:
3482 case Instruction::URem: {
3483 InstructionCost ScalarCost =
3485 if (isSingleScalar())
3486 return ScalarCost;
3487
3488 // If any of the operands is from a different replicate region and has its
3489 // cost skipped, it may have been forced to scalar. Fall back to legacy cost
3490 // model to avoid cost mis-match.
3491 if (any_of(operands(), [&Ctx, VF](VPValue *Op) {
3492 auto *PredR = dyn_cast<VPPredInstPHIRecipe>(Op);
3493 if (!PredR)
3494 return false;
3495 return Ctx.skipCostComputation(
3497 PredR->getOperand(0)->getUnderlyingValue()),
3498 VF.isVector());
3499 }))
3500 break;
3501
3502 ScalarCost = ScalarCost * VF.getFixedValue() +
3503 Ctx.getScalarizationOverhead(Ctx.Types.inferScalarType(this),
3504 to_vector(operands()), VF);
3505 // If the recipe is not predicated (i.e. not in a replicate region), return
3506 // the scalar cost. Otherwise handle predicated cost.
3507 if (!getRegion()->isReplicator())
3508 return ScalarCost;
3509
3510 // Account for the phi nodes that we will create.
3511 ScalarCost += VF.getFixedValue() *
3512 Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
3513 // Scale the cost by the probability of executing the predicated blocks.
3514 // This assumes the predicated block for each vector lane is equally
3515 // likely.
3516 ScalarCost /= Ctx.getPredBlockCostDivisor(UI->getParent());
3517 return ScalarCost;
3518 }
3519 case Instruction::Load:
3520 case Instruction::Store: {
3521 bool IsLoad = UI->getOpcode() == Instruction::Load;
3522 const VPValue *PtrOp = getOperand(!IsLoad);
3523 const SCEV *PtrSCEV = getAddressAccessSCEV(PtrOp, Ctx.PSE, Ctx.L);
3525 break;
3526
3527 Type *ValTy = Ctx.Types.inferScalarType(IsLoad ? this : getOperand(0));
3528 Type *ScalarPtrTy = Ctx.Types.inferScalarType(PtrOp);
3529 const Align Alignment = getLoadStoreAlignment(UI);
3530 unsigned AS = cast<PointerType>(ScalarPtrTy)->getAddressSpace();
3532 bool PreferVectorizedAddressing = Ctx.TTI.prefersVectorizedAddressing();
3533 bool UsedByLoadStoreAddress =
3534 !PreferVectorizedAddressing && vputils::isUsedByLoadStoreAddress(this);
3535 InstructionCost ScalarMemOpCost = Ctx.TTI.getMemoryOpCost(
3536 UI->getOpcode(), ValTy, Alignment, AS, Ctx.CostKind, OpInfo,
3537 UsedByLoadStoreAddress ? UI : nullptr);
3538
3539 // Check if this is a predicated load/store with a loop-invariant address
3540 // only masked by the header mask. If so, return the uniform mem op cost.
3541 if (isPredicatedUniformMemOpAfterTailFolding(*this, PtrSCEV, Ctx)) {
3542 InstructionCost UniformCost =
3543 ScalarMemOpCost +
3544 Ctx.TTI.getAddressComputationCost(ScalarPtrTy, /*SE=*/nullptr,
3545 /*Ptr=*/nullptr, Ctx.CostKind);
3546 auto *VectorTy = cast<VectorType>(toVectorTy(ValTy, VF));
3547 if (IsLoad) {
3548 return UniformCost +
3549 Ctx.TTI.getShuffleCost(TargetTransformInfo::SK_Broadcast,
3550 VectorTy, VectorTy, {}, Ctx.CostKind);
3551 }
3552
3553 VPValue *StoredVal = getOperand(0);
3554 if (!StoredVal->isDefinedOutsideLoopRegions())
3555 UniformCost += Ctx.TTI.getIndexedVectorInstrCostFromEnd(
3556 Instruction::ExtractElement, VectorTy, Ctx.CostKind, 0);
3557 return UniformCost;
3558 }
3559
3560 Type *PtrTy = isSingleScalar() ? ScalarPtrTy : toVectorTy(ScalarPtrTy, VF);
3561 InstructionCost ScalarCost =
3562 ScalarMemOpCost +
3563 Ctx.TTI.getAddressComputationCost(
3564 PtrTy, UsedByLoadStoreAddress ? nullptr : Ctx.PSE.getSE(), PtrSCEV,
3565 Ctx.CostKind);
3566 if (isSingleScalar())
3567 return ScalarCost;
3568
3569 SmallVector<const VPValue *> OpsToScalarize;
3570 Type *ResultTy = Type::getVoidTy(PtrTy->getContext());
3571 // Set ResultTy and OpsToScalarize, if scalarization is needed. Currently we
3572 // don't assign scalarization overhead in general, if the target prefers
3573 // vectorized addressing or the loaded value is used as part of an address
3574 // of another load or store.
3575 if (!UsedByLoadStoreAddress) {
3576 bool EfficientVectorLoadStore =
3577 Ctx.TTI.supportsEfficientVectorElementLoadStore();
3578 if (!(IsLoad && !PreferVectorizedAddressing) &&
3579 !(!IsLoad && EfficientVectorLoadStore))
3580 append_range(OpsToScalarize, operands());
3581
3582 if (!EfficientVectorLoadStore)
3583 ResultTy = Ctx.Types.inferScalarType(this);
3584 }
3585
3589 (ScalarCost * VF.getFixedValue()) +
3590 Ctx.getScalarizationOverhead(ResultTy, OpsToScalarize, VF, VIC, true);
3591
3592 const VPRegionBlock *ParentRegion = getRegion();
3593 if (ParentRegion && ParentRegion->isReplicator()) {
3594 if (!PtrSCEV)
3595 break;
3596 Cost /= Ctx.getPredBlockCostDivisor(UI->getParent());
3597 Cost += Ctx.TTI.getCFInstrCost(Instruction::CondBr, Ctx.CostKind);
3598
3599 auto *VecI1Ty = VectorType::get(
3600 IntegerType::getInt1Ty(Ctx.L->getHeader()->getContext()), VF);
3601 Cost += Ctx.TTI.getScalarizationOverhead(
3602 VecI1Ty, APInt::getAllOnes(VF.getFixedValue()),
3603 /*Insert=*/false, /*Extract=*/true, Ctx.CostKind);
3604
3605 if (Ctx.useEmulatedMaskMemRefHack(this, VF)) {
3606 // Artificially setting to a high enough value to practically disable
3607 // vectorization with such operations.
3608 return 3000000;
3609 }
3610 }
3611 return Cost;
3612 }
3613 case Instruction::SExt:
3614 case Instruction::ZExt:
3615 case Instruction::FPToUI:
3616 case Instruction::FPToSI:
3617 case Instruction::FPExt:
3618 case Instruction::PtrToInt:
3619 case Instruction::PtrToAddr:
3620 case Instruction::IntToPtr:
3621 case Instruction::SIToFP:
3622 case Instruction::UIToFP:
3623 case Instruction::Trunc:
3624 case Instruction::FPTrunc:
3625 case Instruction::Select:
3626 case Instruction::AddrSpaceCast: {
3628 Ctx) *
3629 (isSingleScalar() ? 1 : VF.getFixedValue());
3630 }
3631 case Instruction::ExtractValue:
3632 case Instruction::InsertValue:
3633 return Ctx.TTI.getInsertExtractValueCost(getOpcode(), Ctx.CostKind);
3634 }
3635
3636 return Ctx.getLegacyCost(UI, VF);
3637}
3638
3640 Function *CalledFn, Type *ResultTy, ArrayRef<const VPValue *> ArgOps,
3641 bool IsSingleScalar, ElementCount VF, VPCostContext &Ctx) {
3643 ArgOps, [&](const VPValue *Op) { return Ctx.Types.inferScalarType(Op); });
3644
3645 Intrinsic::ID IntrinID = CalledFn->getIntrinsicID();
3646 auto GetIntrinsicCost = [&] {
3647 if (!IntrinID)
3649 return Ctx.TTI.getIntrinsicInstrCost(
3650 IntrinsicCostAttributes(IntrinID, ResultTy, Tys), Ctx.CostKind);
3651 };
3652
3653 if (IntrinID && VPCostContext::isFreeScalarIntrinsic(IntrinID)) {
3654 assert(GetIntrinsicCost() == 0 && "scalarizing intrinsic should be free");
3655 return 0;
3656 }
3657
3658 InstructionCost ScalarCallCost =
3659 Ctx.TTI.getCallInstrCost(CalledFn, ResultTy, Tys, Ctx.CostKind);
3660 if (IsSingleScalar) {
3661 ScalarCallCost = std::min(ScalarCallCost, GetIntrinsicCost());
3662 return ScalarCallCost;
3663 }
3664
3665 // Scalarization overhead is undefined for scalable VFs.
3666 if (VF.isScalable())
3668
3669 return ScalarCallCost * VF.getFixedValue() +
3670 Ctx.getScalarizationOverhead(ResultTy, ArgOps, VF);
3671}
3672
3673#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3675 VPSlotTracker &SlotTracker) const {
3676 O << Indent << (IsSingleScalar ? "CLONE " : "REPLICATE ");
3677
3678 VPTypeAnalysis TypeInfo(*getParent()->getPlan());
3679 if (!TypeInfo.inferScalarType(this)->isVoidTy()) {
3681 O << " = ";
3682 }
3683 if (auto *CB = dyn_cast<CallBase>(getUnderlyingInstr())) {
3684 O << "call";
3685 printFlags(O);
3686 O << "@" << CB->getCalledFunction()->getName() << "(";
3688 O, [&O, &SlotTracker](VPValue *Op) {
3689 Op->printAsOperand(O, SlotTracker);
3690 });
3691 O << ")";
3692 } else {
3694 printFlags(O);
3696 }
3697
3698 // Find if the recipe is used by a widened recipe via an intervening
3699 // VPPredInstPHIRecipe. In this case, also pack the scalar values in a vector.
3700 if (any_of(users(), [](const VPUser *U) {
3701 if (auto *PredR = dyn_cast<VPPredInstPHIRecipe>(U))
3702 return !vputils::onlyScalarValuesUsed(PredR);
3703 return false;
3704 }))
3705 O << " (S->V)";
3706}
3707#endif
3708
3710 llvm_unreachable("recipe must be removed when dissolving replicate region");
3711}
3712
3714 VPCostContext &Ctx) const {
3715 // The legacy cost model doesn't assign costs to branches for individual
3716 // replicate regions. Match the current behavior in the VPlan cost model for
3717 // now.
3718 return 0;
3719}
3720
3722 llvm_unreachable("recipe must be removed when dissolving replicate region");
3723}
3724
3725#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3727 VPSlotTracker &SlotTracker) const {
3728 O << Indent << "PHI-PREDICATED-INSTRUCTION ";
3730 O << " = ";
3732}
3733#endif
3734
3736 VPCostContext &Ctx) const {
3737 const VPRecipeBase *R = getAsRecipe();
3739 unsigned AS = cast<PointerType>(Ctx.Types.inferScalarType(getAddr()))
3740 ->getAddressSpace();
3742 ? Instruction::Load
3743 : Instruction::Store;
3744
3745 if (!Consecutive) {
3746 // TODO: Using the original IR may not be accurate.
3747 // Currently, ARM will use the underlying IR to calculate gather/scatter
3748 // instruction cost.
3749 [[maybe_unused]] auto IsReverseMask = [this, R]() {
3750 VPValue *Mask = getMask();
3751 if (!Mask)
3752 return false;
3753
3756
3757 return match(Mask, m_Reverse(m_VPValue()));
3758 };
3759 assert(!IsReverseMask() &&
3760 "Inconsecutive memory access should not have reverse order");
3762 Type *PtrTy = Ptr->getType();
3763
3764 // If the address value is uniform across all lanes, then the address can be
3765 // calculated with scalar type and broadcast.
3767 PtrTy = toVectorTy(PtrTy, VF);
3768
3769 unsigned IID = isa<VPWidenLoadRecipe>(R) ? Intrinsic::masked_gather
3770 : isa<VPWidenStoreRecipe>(R) ? Intrinsic::masked_scatter
3771 : isa<VPWidenLoadEVLRecipe>(R) ? Intrinsic::vp_gather
3772 : Intrinsic::vp_scatter;
3773 return Ctx.TTI.getAddressComputationCost(PtrTy, nullptr, nullptr,
3774 Ctx.CostKind) +
3775 Ctx.TTI.getMemIntrinsicInstrCost(
3777 &Ingredient),
3778 Ctx.CostKind);
3779 }
3780
3782 if (IsMasked) {
3783 unsigned IID = isa<VPWidenLoadRecipe>(R) ? Intrinsic::masked_load
3784 : Intrinsic::masked_store;
3785 Cost += Ctx.TTI.getMemIntrinsicInstrCost(
3786 MemIntrinsicCostAttributes(IID, Ty, Alignment, AS), Ctx.CostKind);
3787 } else {
3788 TTI::OperandValueInfo OpInfo = Ctx.getOperandInfo(
3790 : R->getOperand(1));
3791 Cost += Ctx.TTI.getMemoryOpCost(Opcode, Ty, Alignment, AS, Ctx.CostKind,
3792 OpInfo, &Ingredient);
3793 }
3794 return Cost;
3795}
3796
3798 Type *ScalarDataTy = getLoadStoreType(&Ingredient);
3799 auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
3800 bool CreateGather = !isConsecutive();
3801
3802 auto &Builder = State.Builder;
3803 Value *Mask = nullptr;
3804 if (auto *VPMask = getMask())
3805 Mask = State.get(VPMask);
3806
3807 Value *Addr = State.get(getAddr(), /*IsScalar*/ !CreateGather);
3808 Value *NewLI;
3809 if (CreateGather) {
3810 NewLI = Builder.CreateMaskedGather(DataTy, Addr, Alignment, Mask, nullptr,
3811 "wide.masked.gather");
3812 } else if (Mask) {
3813 NewLI =
3814 Builder.CreateMaskedLoad(DataTy, Addr, Alignment, Mask,
3815 PoisonValue::get(DataTy), "wide.masked.load");
3816 } else {
3817 NewLI = Builder.CreateAlignedLoad(DataTy, Addr, Alignment, "wide.load");
3818 }
3820 State.set(this, NewLI);
3821}
3822
3823#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3825 VPSlotTracker &SlotTracker) const {
3826 O << Indent << "WIDEN ";
3828 O << " = load ";
3830}
3831#endif
3832
3834 Type *ScalarDataTy = getLoadStoreType(&Ingredient);
3835 auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
3836 bool CreateGather = !isConsecutive();
3837
3838 auto &Builder = State.Builder;
3839 CallInst *NewLI;
3840 Value *EVL = State.get(getEVL(), VPLane(0));
3841 Value *Addr = State.get(getAddr(), !CreateGather);
3842 Value *Mask = nullptr;
3843 if (VPValue *VPMask = getMask())
3844 Mask = State.get(VPMask);
3845 else
3846 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
3847
3848 if (CreateGather) {
3849 NewLI =
3850 Builder.CreateIntrinsic(DataTy, Intrinsic::vp_gather, {Addr, Mask, EVL},
3851 nullptr, "wide.masked.gather");
3852 } else {
3853 NewLI = Builder.CreateIntrinsic(DataTy, Intrinsic::vp_load,
3854 {Addr, Mask, EVL}, nullptr, "vp.op.load");
3855 }
3856 NewLI->addParamAttr(
3858 applyMetadata(*NewLI);
3859 Instruction *Res = NewLI;
3860 State.set(this, Res);
3861}
3862
3864 VPCostContext &Ctx) const {
3865 if (!Consecutive || IsMasked)
3866 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
3867
3868 // We need to use the getMemIntrinsicInstrCost() instead of getMemoryOpCost()
3869 // here because the EVL recipes using EVL to replace the tail mask. But in the
3870 // legacy model, it will always calculate the cost of mask.
3871 // TODO: Using getMemoryOpCost() instead of getMemIntrinsicInstrCost when we
3872 // don't need to compare to the legacy cost model.
3874 unsigned AS = cast<PointerType>(Ctx.Types.inferScalarType(getAddr()))
3875 ->getAddressSpace();
3876 return Ctx.TTI.getMemIntrinsicInstrCost(
3877 MemIntrinsicCostAttributes(Intrinsic::vp_load, Ty, Alignment, AS),
3878 Ctx.CostKind);
3879}
3880
3881#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3883 VPSlotTracker &SlotTracker) const {
3884 O << Indent << "WIDEN ";
3886 O << " = vp.load ";
3888}
3889#endif
3890
3892 VPValue *StoredVPValue = getStoredValue();
3893 bool CreateScatter = !isConsecutive();
3894
3895 auto &Builder = State.Builder;
3896
3897 Value *Mask = nullptr;
3898 if (auto *VPMask = getMask())
3899 Mask = State.get(VPMask);
3900
3901 Value *StoredVal = State.get(StoredVPValue);
3902 Value *Addr = State.get(getAddr(), /*IsScalar*/ !CreateScatter);
3903 Instruction *NewSI = nullptr;
3904 if (CreateScatter)
3905 NewSI = Builder.CreateMaskedScatter(StoredVal, Addr, Alignment, Mask);
3906 else if (Mask)
3907 NewSI = Builder.CreateMaskedStore(StoredVal, Addr, Alignment, Mask);
3908 else
3909 NewSI = Builder.CreateAlignedStore(StoredVal, Addr, Alignment);
3910 applyMetadata(*NewSI);
3911}
3912
3913#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3915 VPSlotTracker &SlotTracker) const {
3916 O << Indent << "WIDEN store ";
3918}
3919#endif
3920
3922 VPValue *StoredValue = getStoredValue();
3923 bool CreateScatter = !isConsecutive();
3924
3925 auto &Builder = State.Builder;
3926
3927 CallInst *NewSI = nullptr;
3928 Value *StoredVal = State.get(StoredValue);
3929 Value *EVL = State.get(getEVL(), VPLane(0));
3930 Value *Mask = nullptr;
3931 if (VPValue *VPMask = getMask())
3932 Mask = State.get(VPMask);
3933 else
3934 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
3935
3936 Value *Addr = State.get(getAddr(), !CreateScatter);
3937 if (CreateScatter) {
3938 NewSI = Builder.CreateIntrinsic(Type::getVoidTy(EVL->getContext()),
3939 Intrinsic::vp_scatter,
3940 {StoredVal, Addr, Mask, EVL});
3941 } else {
3942 NewSI = Builder.CreateIntrinsic(Type::getVoidTy(EVL->getContext()),
3943 Intrinsic::vp_store,
3944 {StoredVal, Addr, Mask, EVL});
3945 }
3946 NewSI->addParamAttr(
3948 applyMetadata(*NewSI);
3949}
3950
3952 VPCostContext &Ctx) const {
3953 if (!Consecutive || IsMasked)
3954 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
3955
3956 // We need to use the getMemIntrinsicInstrCost() instead of getMemoryOpCost()
3957 // here because the EVL recipes using EVL to replace the tail mask. But in the
3958 // legacy model, it will always calculate the cost of mask.
3959 // TODO: Using getMemoryOpCost() instead of getMemIntrinsicInstrCost when we
3960 // don't need to compare to the legacy cost model.
3962 unsigned AS = cast<PointerType>(Ctx.Types.inferScalarType(getAddr()))
3963 ->getAddressSpace();
3964 return Ctx.TTI.getMemIntrinsicInstrCost(
3965 MemIntrinsicCostAttributes(Intrinsic::vp_store, Ty, Alignment, AS),
3966 Ctx.CostKind);
3967}
3968
3969#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3971 VPSlotTracker &SlotTracker) const {
3972 O << Indent << "WIDEN vp.store ";
3974}
3975#endif
3976
3978 VectorType *DstVTy, const DataLayout &DL) {
3979 // Verify that V is a vector type with same number of elements as DstVTy.
3980 auto VF = DstVTy->getElementCount();
3981 auto *SrcVecTy = cast<VectorType>(V->getType());
3982 assert(VF == SrcVecTy->getElementCount() && "Vector dimensions do not match");
3983 Type *SrcElemTy = SrcVecTy->getElementType();
3984 Type *DstElemTy = DstVTy->getElementType();
3985 assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&
3986 "Vector elements must have same size");
3987
3988 // Do a direct cast if element types are castable.
3989 if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
3990 return Builder.CreateBitOrPointerCast(V, DstVTy);
3991 }
3992 // V cannot be directly casted to desired vector type.
3993 // May happen when V is a floating point vector but DstVTy is a vector of
3994 // pointers or vice-versa. Handle this using a two-step bitcast using an
3995 // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
3996 assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&
3997 "Only one type should be a pointer type");
3998 assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&
3999 "Only one type should be a floating point type");
4000 Type *IntTy =
4001 IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy));
4002 auto *VecIntTy = VectorType::get(IntTy, VF);
4003 Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
4004 return Builder.CreateBitOrPointerCast(CastVal, DstVTy);
4005}
4006
4007/// Return a vector containing interleaved elements from multiple
4008/// smaller input vectors.
4010 const Twine &Name) {
4011 unsigned Factor = Vals.size();
4012 assert(Factor > 1 && "Tried to interleave invalid number of vectors");
4013
4014 VectorType *VecTy = cast<VectorType>(Vals[0]->getType());
4015#ifndef NDEBUG
4016 for (Value *Val : Vals)
4017 assert(Val->getType() == VecTy && "Tried to interleave mismatched types");
4018#endif
4019
4020 // Scalable vectors cannot use arbitrary shufflevectors (only splats), so
4021 // must use intrinsics to interleave.
4022 if (VecTy->isScalableTy()) {
4023 assert(Factor <= 8 && "Unsupported interleave factor for scalable vectors");
4024 return Builder.CreateVectorInterleave(Vals, Name);
4025 }
4026
4027 // Fixed length. Start by concatenating all vectors into a wide vector.
4028 Value *WideVec = concatenateVectors(Builder, Vals);
4029
4030 // Interleave the elements into the wide vector.
4031 const unsigned NumElts = VecTy->getElementCount().getFixedValue();
4032 return Builder.CreateShuffleVector(
4033 WideVec, createInterleaveMask(NumElts, Factor), Name);
4034}
4035
4036// Try to vectorize the interleave group that \p Instr belongs to.
4037//
4038// E.g. Translate following interleaved load group (factor = 3):
4039// for (i = 0; i < N; i+=3) {
4040// R = Pic[i]; // Member of index 0
4041// G = Pic[i+1]; // Member of index 1
4042// B = Pic[i+2]; // Member of index 2
4043// ... // do something to R, G, B
4044// }
4045// To:
4046// %wide.vec = load <12 x i32> ; Read 4 tuples of R,G,B
4047// %R.vec = shuffle %wide.vec, poison, <0, 3, 6, 9> ; R elements
4048// %G.vec = shuffle %wide.vec, poison, <1, 4, 7, 10> ; G elements
4049// %B.vec = shuffle %wide.vec, poison, <2, 5, 8, 11> ; B elements
4050//
4051// Or translate following interleaved store group (factor = 3):
4052// for (i = 0; i < N; i+=3) {
4053// ... do something to R, G, B
4054// Pic[i] = R; // Member of index 0
4055// Pic[i+1] = G; // Member of index 1
4056// Pic[i+2] = B; // Member of index 2
4057// }
4058// To:
4059// %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
4060// %B_U.vec = shuffle %B.vec, poison, <0, 1, 2, 3, u, u, u, u>
4061// %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
4062// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> ; Interleave R,G,B elements
4063// store <12 x i32> %interleaved.vec ; Write 4 tuples of R,G,B
4065 assert((!needsMaskForGaps() || !State.VF.isScalable()) &&
4066 "Masking gaps for scalable vectors is not yet supported.");
4068 Instruction *Instr = Group->getInsertPos();
4069
4070 // Prepare for the vector type of the interleaved load/store.
4071 Type *ScalarTy = getLoadStoreType(Instr);
4072 unsigned InterleaveFactor = Group->getFactor();
4073 auto *VecTy = VectorType::get(ScalarTy, State.VF * InterleaveFactor);
4074
4075 VPValue *BlockInMask = getMask();
4076 VPValue *Addr = getAddr();
4077 Value *ResAddr = State.get(Addr, VPLane(0));
4078
4079 auto CreateGroupMask = [&BlockInMask, &State,
4080 &InterleaveFactor](Value *MaskForGaps) -> Value * {
4081 if (State.VF.isScalable()) {
4082 assert(!MaskForGaps && "Interleaved groups with gaps are not supported.");
4083 assert(InterleaveFactor <= 8 &&
4084 "Unsupported deinterleave factor for scalable vectors");
4085 auto *ResBlockInMask = State.get(BlockInMask);
4086 SmallVector<Value *> Ops(InterleaveFactor, ResBlockInMask);
4087 return interleaveVectors(State.Builder, Ops, "interleaved.mask");
4088 }
4089
4090 if (!BlockInMask)
4091 return MaskForGaps;
4092
4093 Value *ResBlockInMask = State.get(BlockInMask);
4094 Value *ShuffledMask = State.Builder.CreateShuffleVector(
4095 ResBlockInMask,
4096 createReplicatedMask(InterleaveFactor, State.VF.getFixedValue()),
4097 "interleaved.mask");
4098 return MaskForGaps ? State.Builder.CreateBinOp(Instruction::And,
4099 ShuffledMask, MaskForGaps)
4100 : ShuffledMask;
4101 };
4102
4103 const DataLayout &DL = Instr->getDataLayout();
4104 // Vectorize the interleaved load group.
4105 if (isa<LoadInst>(Instr)) {
4106 Value *MaskForGaps = nullptr;
4107 if (needsMaskForGaps()) {
4108 MaskForGaps =
4109 createBitMaskForGaps(State.Builder, State.VF.getFixedValue(), *Group);
4110 assert(MaskForGaps && "Mask for Gaps is required but it is null");
4111 }
4112
4113 Instruction *NewLoad;
4114 if (BlockInMask || MaskForGaps) {
4115 Value *GroupMask = CreateGroupMask(MaskForGaps);
4116 Value *PoisonVec = PoisonValue::get(VecTy);
4117 NewLoad = State.Builder.CreateMaskedLoad(VecTy, ResAddr,
4118 Group->getAlign(), GroupMask,
4119 PoisonVec, "wide.masked.vec");
4120 } else
4121 NewLoad = State.Builder.CreateAlignedLoad(VecTy, ResAddr,
4122 Group->getAlign(), "wide.vec");
4123 applyMetadata(*NewLoad);
4124 // TODO: Also manage existing metadata using VPIRMetadata.
4125 Group->addMetadata(NewLoad);
4126
4128 if (VecTy->isScalableTy()) {
4129 // Scalable vectors cannot use arbitrary shufflevectors (only splats),
4130 // so must use intrinsics to deinterleave.
4131 assert(InterleaveFactor <= 8 &&
4132 "Unsupported deinterleave factor for scalable vectors");
4133 NewLoad = State.Builder.CreateIntrinsic(
4134 Intrinsic::getDeinterleaveIntrinsicID(InterleaveFactor),
4135 NewLoad->getType(), NewLoad,
4136 /*FMFSource=*/nullptr, "strided.vec");
4137 }
4138
4139 auto CreateStridedVector = [&InterleaveFactor, &State,
4140 &NewLoad](unsigned Index) -> Value * {
4141 assert(Index < InterleaveFactor && "Illegal group index");
4142 if (State.VF.isScalable())
4143 return State.Builder.CreateExtractValue(NewLoad, Index);
4144
4145 // For fixed length VF, use shuffle to extract the sub-vectors from the
4146 // wide load.
4147 auto StrideMask =
4148 createStrideMask(Index, InterleaveFactor, State.VF.getFixedValue());
4149 return State.Builder.CreateShuffleVector(NewLoad, StrideMask,
4150 "strided.vec");
4151 };
4152
4153 for (unsigned I = 0, J = 0; I < InterleaveFactor; ++I) {
4154 Instruction *Member = Group->getMember(I);
4155
4156 // Skip the gaps in the group.
4157 if (!Member)
4158 continue;
4159
4160 Value *StridedVec = CreateStridedVector(I);
4161
4162 // If this member has different type, cast the result type.
4163 if (Member->getType() != ScalarTy) {
4164 VectorType *OtherVTy = VectorType::get(Member->getType(), State.VF);
4165 StridedVec =
4166 createBitOrPointerCast(State.Builder, StridedVec, OtherVTy, DL);
4167 }
4168
4169 if (Group->isReverse())
4170 StridedVec = State.Builder.CreateVectorReverse(StridedVec, "reverse");
4171
4172 State.set(VPDefs[J], StridedVec);
4173 ++J;
4174 }
4175 return;
4176 }
4177
4178 // The sub vector type for current instruction.
4179 auto *SubVT = VectorType::get(ScalarTy, State.VF);
4180
4181 // Vectorize the interleaved store group.
4182 Value *MaskForGaps =
4183 createBitMaskForGaps(State.Builder, State.VF.getKnownMinValue(), *Group);
4184 assert(((MaskForGaps != nullptr) == needsMaskForGaps()) &&
4185 "Mismatch between NeedsMaskForGaps and MaskForGaps");
4186 ArrayRef<VPValue *> StoredValues = getStoredValues();
4187 // Collect the stored vector from each member.
4188 SmallVector<Value *, 4> StoredVecs;
4189 unsigned StoredIdx = 0;
4190 for (unsigned i = 0; i < InterleaveFactor; i++) {
4191 assert((Group->getMember(i) || MaskForGaps) &&
4192 "Fail to get a member from an interleaved store group");
4193 Instruction *Member = Group->getMember(i);
4194
4195 // Skip the gaps in the group.
4196 if (!Member) {
4197 Value *Undef = PoisonValue::get(SubVT);
4198 StoredVecs.push_back(Undef);
4199 continue;
4200 }
4201
4202 Value *StoredVec = State.get(StoredValues[StoredIdx]);
4203 ++StoredIdx;
4204
4205 if (Group->isReverse())
4206 StoredVec = State.Builder.CreateVectorReverse(StoredVec, "reverse");
4207
4208 // If this member has different type, cast it to a unified type.
4209
4210 if (StoredVec->getType() != SubVT)
4211 StoredVec = createBitOrPointerCast(State.Builder, StoredVec, SubVT, DL);
4212
4213 StoredVecs.push_back(StoredVec);
4214 }
4215
4216 // Interleave all the smaller vectors into one wider vector.
4217 Value *IVec = interleaveVectors(State.Builder, StoredVecs, "interleaved.vec");
4218 Instruction *NewStoreInstr;
4219 if (BlockInMask || MaskForGaps) {
4220 Value *GroupMask = CreateGroupMask(MaskForGaps);
4221 NewStoreInstr = State.Builder.CreateMaskedStore(
4222 IVec, ResAddr, Group->getAlign(), GroupMask);
4223 } else
4224 NewStoreInstr =
4225 State.Builder.CreateAlignedStore(IVec, ResAddr, Group->getAlign());
4226
4227 applyMetadata(*NewStoreInstr);
4228 // TODO: Also manage existing metadata using VPIRMetadata.
4229 Group->addMetadata(NewStoreInstr);
4230}
4231
4232#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4234 VPSlotTracker &SlotTracker) const {
4236 O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << " at ";
4237 IG->getInsertPos()->printAsOperand(O, false);
4238 O << ", ";
4240 VPValue *Mask = getMask();
4241 if (Mask) {
4242 O << ", ";
4243 Mask->printAsOperand(O, SlotTracker);
4244 }
4245
4246 unsigned OpIdx = 0;
4247 for (unsigned i = 0; i < IG->getFactor(); ++i) {
4248 if (!IG->getMember(i))
4249 continue;
4250 if (getNumStoreOperands() > 0) {
4251 O << "\n" << Indent << " store ";
4253 O << " to index " << i;
4254 } else {
4255 O << "\n" << Indent << " ";
4257 O << " = load from index " << i;
4258 }
4259 ++OpIdx;
4260 }
4261}
4262#endif
4263
4265 assert(State.VF.isScalable() &&
4266 "Only support scalable VF for EVL tail-folding.");
4268 "Masking gaps for scalable vectors is not yet supported.");
4270 Instruction *Instr = Group->getInsertPos();
4271
4272 // Prepare for the vector type of the interleaved load/store.
4273 Type *ScalarTy = getLoadStoreType(Instr);
4274 unsigned InterleaveFactor = Group->getFactor();
4275 assert(InterleaveFactor <= 8 &&
4276 "Unsupported deinterleave/interleave factor for scalable vectors");
4277 ElementCount WideVF = State.VF * InterleaveFactor;
4278 auto *VecTy = VectorType::get(ScalarTy, WideVF);
4279
4280 VPValue *Addr = getAddr();
4281 Value *ResAddr = State.get(Addr, VPLane(0));
4282 Value *EVL = State.get(getEVL(), VPLane(0));
4283 Value *InterleaveEVL = State.Builder.CreateMul(
4284 EVL, ConstantInt::get(EVL->getType(), InterleaveFactor), "interleave.evl",
4285 /* NUW= */ true, /* NSW= */ true);
4286 LLVMContext &Ctx = State.Builder.getContext();
4287
4288 Value *GroupMask = nullptr;
4289 if (VPValue *BlockInMask = getMask()) {
4290 SmallVector<Value *> Ops(InterleaveFactor, State.get(BlockInMask));
4291 GroupMask = interleaveVectors(State.Builder, Ops, "interleaved.mask");
4292 } else {
4293 GroupMask =
4294 State.Builder.CreateVectorSplat(WideVF, State.Builder.getTrue());
4295 }
4296
4297 // Vectorize the interleaved load group.
4298 if (isa<LoadInst>(Instr)) {
4299 CallInst *NewLoad = State.Builder.CreateIntrinsic(
4300 VecTy, Intrinsic::vp_load, {ResAddr, GroupMask, InterleaveEVL}, nullptr,
4301 "wide.vp.load");
4302 NewLoad->addParamAttr(0,
4303 Attribute::getWithAlignment(Ctx, Group->getAlign()));
4304
4305 applyMetadata(*NewLoad);
4306 // TODO: Also manage existing metadata using VPIRMetadata.
4307 Group->addMetadata(NewLoad);
4308
4309 // Scalable vectors cannot use arbitrary shufflevectors (only splats),
4310 // so must use intrinsics to deinterleave.
4311 NewLoad = State.Builder.CreateIntrinsic(
4312 Intrinsic::getDeinterleaveIntrinsicID(InterleaveFactor),
4313 NewLoad->getType(), NewLoad,
4314 /*FMFSource=*/nullptr, "strided.vec");
4315
4316 const DataLayout &DL = Instr->getDataLayout();
4317 for (unsigned I = 0, J = 0; I < InterleaveFactor; ++I) {
4318 Instruction *Member = Group->getMember(I);
4319 // Skip the gaps in the group.
4320 if (!Member)
4321 continue;
4322
4323 Value *StridedVec = State.Builder.CreateExtractValue(NewLoad, I);
4324 // If this member has different type, cast the result type.
4325 if (Member->getType() != ScalarTy) {
4326 VectorType *OtherVTy = VectorType::get(Member->getType(), State.VF);
4327 StridedVec =
4328 createBitOrPointerCast(State.Builder, StridedVec, OtherVTy, DL);
4329 }
4330
4331 State.set(getVPValue(J), StridedVec);
4332 ++J;
4333 }
4334 return;
4335 } // End for interleaved load.
4336
4337 // The sub vector type for current instruction.
4338 auto *SubVT = VectorType::get(ScalarTy, State.VF);
4339 // Vectorize the interleaved store group.
4340 ArrayRef<VPValue *> StoredValues = getStoredValues();
4341 // Collect the stored vector from each member.
4342 SmallVector<Value *, 4> StoredVecs;
4343 const DataLayout &DL = Instr->getDataLayout();
4344 for (unsigned I = 0, StoredIdx = 0; I < InterleaveFactor; I++) {
4345 Instruction *Member = Group->getMember(I);
4346 // Skip the gaps in the group.
4347 if (!Member) {
4348 StoredVecs.push_back(PoisonValue::get(SubVT));
4349 continue;
4350 }
4351
4352 Value *StoredVec = State.get(StoredValues[StoredIdx]);
4353 // If this member has different type, cast it to a unified type.
4354 if (StoredVec->getType() != SubVT)
4355 StoredVec = createBitOrPointerCast(State.Builder, StoredVec, SubVT, DL);
4356
4357 StoredVecs.push_back(StoredVec);
4358 ++StoredIdx;
4359 }
4360
4361 // Interleave all the smaller vectors into one wider vector.
4362 Value *IVec = interleaveVectors(State.Builder, StoredVecs, "interleaved.vec");
4363 CallInst *NewStore =
4364 State.Builder.CreateIntrinsic(Type::getVoidTy(Ctx), Intrinsic::vp_store,
4365 {IVec, ResAddr, GroupMask, InterleaveEVL});
4366 NewStore->addParamAttr(1,
4367 Attribute::getWithAlignment(Ctx, Group->getAlign()));
4368
4369 applyMetadata(*NewStore);
4370 // TODO: Also manage existing metadata using VPIRMetadata.
4371 Group->addMetadata(NewStore);
4372}
4373
4374#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4376 VPSlotTracker &SlotTracker) const {
4378 O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << " at ";
4379 IG->getInsertPos()->printAsOperand(O, false);
4380 O << ", ";
4382 O << ", ";
4384 if (VPValue *Mask = getMask()) {
4385 O << ", ";
4386 Mask->printAsOperand(O, SlotTracker);
4387 }
4388
4389 unsigned OpIdx = 0;
4390 for (unsigned i = 0; i < IG->getFactor(); ++i) {
4391 if (!IG->getMember(i))
4392 continue;
4393 if (getNumStoreOperands() > 0) {
4394 O << "\n" << Indent << " vp.store ";
4396 O << " to index " << i;
4397 } else {
4398 O << "\n" << Indent << " ";
4400 O << " = vp.load from index " << i;
4401 }
4402 ++OpIdx;
4403 }
4404}
4405#endif
4406
4408 VPCostContext &Ctx) const {
4409 Instruction *InsertPos = getInsertPos();
4410 // Find the VPValue index of the interleave group. We need to skip gaps.
4411 unsigned InsertPosIdx = 0;
4412 for (unsigned Idx = 0; IG->getFactor(); ++Idx)
4413 if (auto *Member = IG->getMember(Idx)) {
4414 if (Member == InsertPos)
4415 break;
4416 InsertPosIdx++;
4417 }
4418 Type *ValTy = Ctx.Types.inferScalarType(
4419 getNumDefinedValues() > 0 ? getVPValue(InsertPosIdx)
4420 : getStoredValues()[InsertPosIdx]);
4421 auto *VectorTy = cast<VectorType>(toVectorTy(ValTy, VF));
4422 unsigned AS = cast<PointerType>(Ctx.Types.inferScalarType(getAddr()))
4423 ->getAddressSpace();
4424
4425 unsigned InterleaveFactor = IG->getFactor();
4426 auto *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
4427
4428 // Holds the indices of existing members in the interleaved group.
4430 for (unsigned IF = 0; IF < InterleaveFactor; IF++)
4431 if (IG->getMember(IF))
4432 Indices.push_back(IF);
4433
4434 // Calculate the cost of the whole interleaved group.
4435 InstructionCost Cost = Ctx.TTI.getInterleavedMemoryOpCost(
4436 InsertPos->getOpcode(), WideVecTy, IG->getFactor(), Indices,
4437 IG->getAlign(), AS, Ctx.CostKind, getMask(), NeedsMaskForGaps);
4438
4439 if (!IG->isReverse())
4440 return Cost;
4441
4442 return Cost + IG->getNumMembers() *
4443 Ctx.TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
4444 VectorTy, VectorTy, {}, Ctx.CostKind,
4445 0);
4446}
4447
4449 return vputils::onlyScalarValuesUsed(this) &&
4450 (!IsScalable || vputils::onlyFirstLaneUsed(this));
4451}
4452
4453#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4455 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
4456 assert((getNumOperands() == 3 || getNumOperands() == 5) &&
4457 "unexpected number of operands");
4458 O << Indent << "EMIT ";
4460 O << " = WIDEN-POINTER-INDUCTION ";
4462 O << ", ";
4464 O << ", ";
4466 if (getNumOperands() == 5) {
4467 O << ", ";
4469 O << ", ";
4471 }
4472}
4473
4475 VPSlotTracker &SlotTracker) const {
4476 O << Indent << "EMIT ";
4478 O << " = EXPAND SCEV " << *Expr;
4479}
4480#endif
4481
4482#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4484 VPSlotTracker &SlotTracker) const {
4485 O << Indent << "EMIT ";
4487 O << " = WIDEN-CANONICAL-INDUCTION ";
4489}
4490#endif
4491
4493 auto &Builder = State.Builder;
4494 // Create a vector from the initial value.
4495 auto *VectorInit = getStartValue()->getLiveInIRValue();
4496
4497 Type *VecTy = State.VF.isScalar()
4498 ? VectorInit->getType()
4499 : VectorType::get(VectorInit->getType(), State.VF);
4500
4501 BasicBlock *VectorPH =
4502 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
4503 if (State.VF.isVector()) {
4504 auto *IdxTy = Builder.getInt32Ty();
4505 auto *One = ConstantInt::get(IdxTy, 1);
4506 IRBuilder<>::InsertPointGuard Guard(Builder);
4507 Builder.SetInsertPoint(VectorPH->getTerminator());
4508 auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, State.VF);
4509 auto *LastIdx = Builder.CreateSub(RuntimeVF, One);
4510 VectorInit = Builder.CreateInsertElement(
4511 PoisonValue::get(VecTy), VectorInit, LastIdx, "vector.recur.init");
4512 }
4513
4514 // Create a phi node for the new recurrence.
4515 PHINode *Phi = PHINode::Create(VecTy, 2, "vector.recur");
4516 Phi->insertBefore(State.CFG.PrevBB->getFirstInsertionPt());
4517 Phi->addIncoming(VectorInit, VectorPH);
4518 State.set(this, Phi);
4519}
4520
4523 VPCostContext &Ctx) const {
4524 if (VF.isScalar())
4525 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
4526
4527 return 0;
4528}
4529
4530#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4532 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
4533 O << Indent << "FIRST-ORDER-RECURRENCE-PHI ";
4535 O << " = phi ";
4537}
4538#endif
4539
4541 // Reductions do not have to start at zero. They can start with
4542 // any loop invariant values.
4543 VPValue *StartVPV = getStartValue();
4544
4545 // In order to support recurrences we need to be able to vectorize Phi nodes.
4546 // Phi nodes have cycles, so we need to vectorize them in two stages. This is
4547 // stage #1: We create a new vector PHI node with no incoming edges. We'll use
4548 // this value when we vectorize all of the instructions that use the PHI.
4549 BasicBlock *VectorPH =
4550 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
4551 bool ScalarPHI = State.VF.isScalar() || isInLoop();
4552 Value *StartV = State.get(StartVPV, ScalarPHI);
4553 Type *VecTy = StartV->getType();
4554
4555 BasicBlock *HeaderBB = State.CFG.PrevBB;
4556 assert(State.CurrentParentLoop->getHeader() == HeaderBB &&
4557 "recipe must be in the vector loop header");
4558 auto *Phi = PHINode::Create(VecTy, 2, "vec.phi");
4559 Phi->insertBefore(HeaderBB->getFirstInsertionPt());
4560 State.set(this, Phi, isInLoop());
4561
4562 Phi->addIncoming(StartV, VectorPH);
4563}
4564
4565#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4567 VPSlotTracker &SlotTracker) const {
4568 O << Indent << "WIDEN-REDUCTION-PHI ";
4569
4571 O << " = phi (";
4572 printRecurrenceKind(O, Kind);
4573 O << ")";
4574 printFlags(O);
4576 if (getVFScaleFactor() > 1)
4577 O << " (VF scaled by 1/" << getVFScaleFactor() << ")";
4578}
4579#endif
4580
4582 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
4583 return vputils::onlyFirstLaneUsed(this);
4584}
4585
4587 Value *Op0 = State.get(getOperand(0));
4588 Type *VecTy = Op0->getType();
4589 Instruction *VecPhi = State.Builder.CreatePHI(VecTy, 2, Name);
4590 State.set(this, VecPhi);
4591}
4592
4594 VPCostContext &Ctx) const {
4595 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
4596}
4597
4598#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4600 VPSlotTracker &SlotTracker) const {
4601 O << Indent << "WIDEN-PHI ";
4602
4604 O << " = phi ";
4606}
4607#endif
4608
4610 BasicBlock *VectorPH =
4611 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
4612 Value *StartMask = State.get(getOperand(0));
4613 PHINode *Phi =
4614 State.Builder.CreatePHI(StartMask->getType(), 2, "active.lane.mask");
4615 Phi->addIncoming(StartMask, VectorPH);
4616 State.set(this, Phi);
4617}
4618
4619#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4621 VPSlotTracker &SlotTracker) const {
4622 O << Indent << "ACTIVE-LANE-MASK-PHI ";
4623
4625 O << " = phi ";
4627}
4628#endif
4629
4630#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4632 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
4633 O << Indent << "CURRENT-ITERATION-PHI ";
4634
4636 O << " = phi ";
4638}
4639#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:853
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static void replaceAllUsesWith(Value *Old, Value *New, SmallPtrSet< BasicBlock *, 32 > &FreshBBs, bool IsHuge)
Replace all old uses with new ones, and push the updated BBs into FreshBBs.
Value * getPointer(Value *Ptr)
iv users
Definition IVUsers.cpp:48
static std::pair< Value *, APInt > getMask(Value *WideMask, unsigned Factor, ElementCount LeafValueEC)
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
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 const Function * getCalledFunction(const Value *V)
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 less commonly used SmallVector utilities.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
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 Value * interleaveVectors(IRBuilderBase &Builder, ArrayRef< Value * > Vals, const Twine &Name)
Return a vector containing interleaved elements from multiple smaller input vectors.
static Value * createBitOrPointerCast(IRBuilderBase &Builder, Value *V, VectorType *DstVTy, const DataLayout &DL)
static Instruction::BinaryOps getSubRecurOpcode(RecurKind Kind)
SmallVector< Value *, 2 > VectorParts
static unsigned getCalledFnOperandIndex(const VPInstruction &VPI)
For call VPInstructions, return the operand index of the called function.
static void printRecurrenceKind(raw_ostream &OS, const RecurKind &Kind)
This file contains the declarations of the Vectorization Plan base classes:
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
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
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...
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.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
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
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
Definition Function.h:246
bool doesNotThrow() const
Determine if the function cannot unwind.
Definition Function.h:602
bool doesNotAccessMemory() const
Determine if the function does not access memory.
Definition Function.cpp:867
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:2627
IntegerType * getInt1Ty()
Fetch the type representing a single bit.
Definition IRBuilder.h:571
Value * CreateInsertValue(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &Name="")
Definition IRBuilder.h:2681
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2615
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:1238
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:2674
LLVM_ABI CallInst * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > OverloadTypes, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="", ArrayRef< OperandBundleDef > OpBundles={})
Create a call to intrinsic ID with Args, mangled using OverloadTypes.
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:2693
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
Definition IRBuilder.h:586
Value * CreatePtrAdd(Value *Ptr, Value *Offset, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Definition IRBuilder.h:2091
void setFastMathFlags(FastMathFlags NewFMF)
Set the fast-math flags to be used with generated fp-math operators.
Definition IRBuilder.h:352
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:2378
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:1782
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition IRBuilder.h:529
Value * CreateCmp(CmpInst::Predicate Pred, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2508
Value * CreateNot(Value *V, const Twine &Name="")
Definition IRBuilder.h:1866
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2374
Value * CreateCountTrailingZeroElems(Type *ResTy, Value *Mask, bool ZeroIsPoison=true, const Twine &Name="")
Create a call to llvm.experimental_cttz_elts.
Definition IRBuilder.h:1176
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1461
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNeg=false)
Definition IRBuilder.h:2120
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1444
ConstantInt * getFalse()
Get the constant value for i1 false.
Definition IRBuilder.h:514
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:1753
Value * CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2386
Value * CreateLogicalOr(Value *Cond1, Value *Cond2, const Twine &Name="", Instruction *MDFrom=nullptr)
Definition IRBuilder.h:1790
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2484
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
Definition IRBuilder.h:1614
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1478
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 LLVM_ABI bool isSubRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is for a sub operation.
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.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
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).
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.
@ TCC_Free
Expected to fold away in lowering.
@ SK_Splice
Concatenates elements from the first input vector with elements of the second input vector.
@ SK_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 isByteTy() const
True if this is an instance of ByteType.
Definition Type.h:242
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:290
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:4245
RecipeListTy & getRecipeList()
Returns a reference to the list of recipes.
Definition VPlan.h:4298
iterator end()
Definition VPlan.h:4282
const VPRecipeBase & front() const
Definition VPlan.h:4292
void insert(VPRecipeBase *Recipe, iterator InsertPt)
Definition VPlan.h:4311
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:2903
unsigned getNumIncomingValues() const
Return the number of incoming values, taking into account when normalized the first incoming value wi...
Definition VPlan.h:2898
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
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:2894
VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
Definition VPlan.h:93
const VPBlocksTy & getPredecessors() const
Definition VPlan.h:221
VPlan * getPlan()
Definition VPlan.cpp:211
void printAsOperand(raw_ostream &OS, bool PrintType=false) const
Definition VPlan.h:363
const VPBasicBlock * getEntryBasicBlock() const
Definition VPlan.cpp:216
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.
unsigned getNumDefinedValues() const
Returns the number of values defined by the VPDef.
Definition VPlanValue.h:556
VPValue * getVPSingleValue()
Returns the only VPValue defined by the VPDef.
Definition VPlanValue.h:529
VPValue * getVPValue(unsigned I)
Returns the VPValue with index I defined by the VPDef.
Definition VPlanValue.h:541
ArrayRef< VPRecipeValue * > definedValues()
Returns an ArrayRef of the values defined by the VPDef.
Definition VPlanValue.h:551
VPIRValue * getStartValue() const
Definition VPlan.h:4062
VPValue * getStepValue() const
Definition VPlan.h:4064
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.
VPExpandSCEVRecipe(const SCEV *Expr)
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:2421
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:2157
Class to record and manage LLVM IR flags.
Definition VPlan.h:696
FastMathFlagsTy FMFs
Definition VPlan.h:784
ReductionFlagsTy ReductionFlags
Definition VPlan.h:786
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:778
void printFlags(raw_ostream &O) const
bool hasFastMathFlags() const
Returns true if the recipe has fast-math flags.
Definition VPlan.h:1001
LLVM_ABI_FOR_TEST FastMathFlags getFastMathFlags() const
bool isReductionOrdered() const
Definition VPlan.h:1065
TruncFlagsTy TruncFlags
Definition VPlan.h:779
CmpInst::Predicate getPredicate() const
Definition VPlan.h:973
ExactFlagsTy ExactFlags
Definition VPlan.h:781
void intersectFlags(const VPIRFlags &Other)
Only keep flags also present in Other.
uint8_t GEPFlagsStorage
Definition VPlan.h:782
GEPNoWrapFlags getGEPNoWrapFlags() const
Definition VPlan.h:991
bool hasPredicate() const
Returns true if the recipe has a comparison predicate.
Definition VPlan.h:996
DisjointFlagsTy DisjointFlags
Definition VPlan.h:780
FCmpFlagsTy FCmpFlags
Definition VPlan.h:785
NonNegFlagsTy NonNegFlags
Definition VPlan.h:783
bool isReductionInLoop() const
Definition VPlan.h:1071
void applyFlags(Instruction &I) const
Apply the IR flags to I.
Definition VPlan.h:930
uint8_t CmpPredStorage
Definition VPlan.h:777
RecurKind getRecurKind() const
Definition VPlan.h:1059
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:1697
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:1226
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:1324
@ ExtractLane
Extracts a single lane (first operand) from a set of vector operands.
Definition VPlan.h:1315
@ ExitingIVValue
Compute the exiting value of a wide induction after vectorization, that is the value of the last lane...
Definition VPlan.h:1328
@ WideIVStep
Scale the first operand (vector step) by the second operand (scalar-step).
Definition VPlan.h:1340
@ ResumeForEpilogue
Explicit user for the resume phi of the canonical induction in the main VPlan, used by the epilogue v...
Definition VPlan.h:1318
@ Unpack
Extracts all lanes from its (non-scalable) vector operand.
Definition VPlan.h:1266
@ ReductionStartVector
Start vector for reductions with 3 operands: the original start value, the identity value for the red...
Definition VPlan.h:1311
@ BuildVector
Creates a fixed-width vector containing all operands.
Definition VPlan.h:1261
@ BuildStructVector
Given operands of (the same) struct type, creates a struct of fixed- width vectors each containing a ...
Definition VPlan.h:1258
@ VScale
Returns the value for vscale.
Definition VPlan.h:1344
@ CanonicalIVIncrementForPart
Definition VPlan.h:1242
@ ComputeReductionResult
Reduce the operands to the final reduction result using the operation specified via the operation's V...
Definition VPlan.h:1269
bool hasResult() const
Definition VPlan.h:1423
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:1503
unsigned getOpcode() const
Definition VPlan.h:1407
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:1448
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:3007
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this recipe.
Instruction * getInsertPos() const
Definition VPlan.h:3011
const InterleaveGroup< Instruction > * getInterleaveGroup() const
Definition VPlan.h:3009
VPValue * getMask() const
Return the mask used by this recipe.
Definition VPlan.h:3001
ArrayRef< VPValue * > getStoredValues() const
Return the VPValues stored by this interleave group.
Definition VPlan.h:3030
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition VPlan.h:2995
VPValue * getEVL() const
The VPValue of the explicit vector length.
Definition VPlan.h:3104
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:3117
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:3067
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:1611
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:4389
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:1636
VPValue * getIncomingValue(unsigned Idx) const
Returns the incoming VPValue with index Idx.
Definition VPlan.h:1596
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:401
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:4590
LLVM_ABI_FOR_TEST void dump() const
Dump the recipe to stderr (for debugging).
Definition VPlan.cpp:117
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:476
DebugLoc getDebugLoc() const
Returns the debug location of the recipe.
Definition VPlan.h:554
void moveBefore(VPBasicBlock &BB, iplist< VPRecipeBase >::iterator I)
Unlink this recipe and insert into BB before I.
bool isSafeToSpeculativelyExecute() const
Return true if we can safely execute this recipe unconditionally even if it is masked originally.
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...
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:522
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:466
Type * getScalarType() const
Returns the scalar type of this VPRecipeValue.
Definition VPlanValue.h:337
friend class VPValue
Definition VPlanValue.h:316
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:3265
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:2818
bool isInLoop() const
Returns true if the phi is part of an in-loop reduction.
Definition VPlan.h:2842
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:3207
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:3218
VPValue * getCondOp() const
The VPValue of the condition for the block.
Definition VPlan.h:3220
RecurKind getRecurrenceKind() const
Return the recurrence kind for the in-loop reduction.
Definition VPlan.h:3203
bool isPartialReduction() const
Returns true if the reduction outputs a vector with a scaled down VF.
Definition VPlan.h:3209
VPValue * getChainOp() const
The VPValue of the scalar Chain being accumulated.
Definition VPlan.h:3216
bool isInLoop() const
Returns true if the reduction is in-loop.
Definition VPlan.h:3211
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:4455
bool isReplicator() const
An indicator whether this region is to generate multiple replicated instances of output IR correspond...
Definition VPlan.h:4531
VPReplicateRecipe replicates a given instruction producing multiple scalar copies of the original sca...
Definition VPlan.h:3287
void execute(VPTransformState &State) override
Generate replicas of the desired Ingredient.
bool isSingleScalar() const
Definition VPlan.h:3335
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.
static InstructionCost computeCallCost(Function *CalledFn, Type *ResultTy, ArrayRef< const VPValue * > ArgOps, bool IsSingleScalar, ElementCount VF, VPCostContext &Ctx)
Return the cost of scalarizing a call to CalledFn with argument operands ArgOps for a given VF.
unsigned getOpcode() const
Definition VPlan.h:3359
VPValue * getStepValue() const
Definition VPlan.h:4134
VPValue * getStartIndex() const
Return the StartIndex, or null if known to be zero, valid only after unrolling.
Definition VPlan.h:4142
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.
VPSingleDefRecipe is a base class for recipes that model a sequence of one or more output IR that def...
Definition VPlan.h:610
Instruction * getUnderlyingInstr()
Returns the underlying instruction.
Definition VPlan.h:681
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:612
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.
This class augments VPValue with operands which provide the inverse def-use edges from VPValue's user...
Definition VPlanValue.h:384
void printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const
Print the operands to O.
Definition VPlan.cpp:1557
operand_range operands()
Definition VPlanValue.h:452
unsigned getNumOperands() const
Definition VPlanValue.h:422
operand_iterator op_begin()
Definition VPlanValue.h:448
VPValue * getOperand(unsigned N) const
Definition VPlanValue.h:423
This is the base class of the VPlan Def/Use graph, used for modeling the data flow into,...
Definition VPlanValue.h:50
Value * getLiveInIRValue() const
Return the underlying IR value for a VPIRValue.
Definition VPlan.cpp:143
bool isDefinedOutsideLoopRegions() const
Returns true if the VPValue is defined outside any loop.
Definition VPlan.cpp:1508
VPRecipeBase * getDefiningRecipe()
Returns the recipe defining this VPValue or nullptr if it is not defined by a recipe,...
Definition VPlan.cpp:130
void printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const
Definition VPlan.cpp:1553
Value * getUnderlyingValue() const
Return the underlying Value attached to this VPValue.
Definition VPlanValue.h:75
void setUnderlyingValue(Value *Val)
Definition VPlanValue.h:208
VPValue * getVFValue() const
Definition VPlan.h:2256
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:2253
int64_t getStride() const
Definition VPlan.h:2254
void materializeOffset(unsigned Part=0)
Adds the offset operand to the recipe.
VPValue * getStride() const
Definition VPlan.h:2322
Type * getSourceElementType() const
Definition VPlan.h:2330
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,...
VPValue * getVFxPart() const
Definition VPlan.h:2324
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
operand_range args()
Definition VPlan.h:2109
Function * getCalledScalarFunction() const
Definition VPlan.h:2105
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.
static InstructionCost computeCallCost(Function *Variant, VPCostContext &Ctx)
Return the cost of widening a call using the vector function Variant.
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.
Instruction::CastOps getOpcode() const
Definition VPlan.h:1879
LLVM_ABI_FOR_TEST void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
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:2210
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:2484
VPValue * getStepValue()
Returns the step value of the induction.
Definition VPlan.h:2487
VPIRValue * getStartValue() const
Returns the start value of the induction.
Definition VPlan.h:2585
TruncInst * getTruncInst()
Returns the first defined value as TruncInst, if it is one or nullptr otherwise.
Definition VPlan.h:2600
Type * getScalarType() const
Returns the scalar type of the induction.
Definition VPlan.h:2609
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.
CallInst * createVectorCall(VPTransformState &State)
Helper function to produce the widened intrinsic call.
Intrinsic::ID getVectorIntrinsicID() const
Return the ID of the intrinsic.
Definition VPlan.h:1994
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.
static InstructionCost computeCallCost(Intrinsic::ID ID, ArrayRef< const VPValue * > Operands, const VPRecipeWithIRFlags &R, ElementCount VF, VPCostContext &Ctx)
Compute the cost of a vector intrinsic with ID and Operands.
LLVM_ABI_FOR_TEST bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the VPUser only uses the first lane of operand Op.
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.
static InstructionCost computeMemIntrinsicCost(Intrinsic::ID IID, Type *Ty, bool IsMasked, Align Alignment, VPCostContext &Ctx)
Helper function for computing the cost of vector memory intrinsic.
void execute(VPTransformState &State) override
Produce a widened version of the vector memory intrinsic.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this vector memory intrinsic.
bool IsMasked
Whether the memory access is masked.
Definition VPlan.h:3604
bool isConsecutive() const
Return whether the loaded-from / stored-to addresses are consecutive.
Definition VPlan.h:3627
Instruction & Ingredient
Definition VPlan.h:3595
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const
Return the cost of this VPWidenMemoryRecipe.
bool Consecutive
Whether the accessed addresses are consecutive.
Definition VPlan.h:3601
VPValue * getMask() const
Return the mask used by this recipe.
Definition VPlan.h:3637
Align Alignment
Alignment information for this memory access.
Definition VPlan.h:3598
virtual VPRecipeBase * getAsRecipe()=0
Return a VPRecipeBase* to the current object.
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition VPlan.h:3630
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenPHIRecipe.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate the phi/select nodes.
bool onlyScalarsGenerated(bool IsScalable)
Returns true if only scalar values will be generated.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenRecipe.
void execute(VPTransformState &State) override
Produce a widened instruction using the opcode and operands of the recipe, processing State....
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
unsigned getOpcode() const
Definition VPlan.h:1824
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition VPlan.h:4603
const DataLayout & getDataLayout() const
Definition VPlan.h:4808
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:4910
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 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 Intrinsic::ID getDeinterleaveIntrinsicID(unsigned Factor)
Returns the corresponding llvm.vector.deinterleaveN intrinsic for factor N.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
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.
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
auto m_Cmp()
Matches any compare instruction and ignore it.
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.
IntrinsicID_match m_Intrinsic()
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
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
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
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.
bool isUsedByLoadStoreAddress(const VPValue *V)
Returns true if V is used as part of the address of another load or store.
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:315
LLVM_ABI Value * createSimpleReduction(IRBuilderBase &B, Value *Src, RecurKind RdxKind)
Create a reduction of the given vector.
@ Offset
Definition DWP.cpp:558
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:830
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1738
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:2553
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.
auto map_to_vector(ContainerTy &&C, FuncTy &&F)
Map a range to a SmallVector with element types deduced from the mapping.
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:2207
void interleaveComma(const Container &c, StreamT &os, UnaryFunctor each_fn)
Definition STLExtras.h:2312
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:1745
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:407
ElementCount getVectorizedTypeVF(Type *Ty)
Returns the number of vector elements for a vectorized type.
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:209
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:1752
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:322
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
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.
@ FindIV
FindIV reduction with select(icmp(),x,y) where one of (x,y) is a loop induction variable (increasing ...
@ Or
Bitwise or logical OR of integers.
@ FMinimum
FP min with llvm.minimum semantics.
@ FMaxNum
FP max with llvm.maxnum semantics including NaNs.
@ Mul
Product of integers.
@ FSub
Subtraction of floats.
@ FAddChainWithSubs
A chain of fadds and fsubs.
@ None
Not a recurrence.
@ AnyOf
AnyOf reduction with select(cmp(),x,y) where one of (x,y) is loop invariant, and both x and y are int...
@ Xor
Bitwise or logical XOR of integers.
@ FindLast
FindLast reduction with select(cmp(),x,y) where x and y.
@ FMax
FP max implemented in terms of select(cmp()).
@ FMaximum
FP max with llvm.maximum semantics.
@ FMulAdd
Sum of float products with llvm.fmuladd(a * b + sum).
@ FMul
Product of floats.
@ SMax
Signed integer max implemented in terms of select(cmp()).
@ And
Bitwise or logical AND of integers.
@ SMin
Signed integer min implemented in terms of select(cmp()).
@ FMin
FP min implemented in terms of select(cmp()).
@ FMinNum
FP min with llvm.minnum semantics including NaNs.
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
@ AddChainWithSubs
A chain of adds and subs.
@ 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
LLVM_ABI Type * getScalarTypeOrInfer(VPValue *V)
Return the scalar type of V.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1946
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.
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.
static bool isFreeScalarIntrinsic(Intrinsic::ID ID)
Returns true if ID is a pseudo intrinsic that is dropped via scalarization rather than widened.
Definition VPlan.cpp:1978
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:1755
PHINode & getIRPhi()
Definition VPlan.h:1768
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.
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:1119
A symbolic live-in VPValue, used for values like vector trip count, VF, and VFxUF.
Definition VPlanValue.h:286
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:313
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:3721
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:3822
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:3825
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:3771