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