LLVM 20.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 "VPlanPatternMatch.h"
18#include "VPlanUtils.h"
19#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/Twine.h"
23#include "llvm/IR/BasicBlock.h"
24#include "llvm/IR/IRBuilder.h"
25#include "llvm/IR/Instruction.h"
27#include "llvm/IR/Intrinsics.h"
28#include "llvm/IR/Type.h"
29#include "llvm/IR/Value.h"
33#include "llvm/Support/Debug.h"
38#include <cassert>
39
40using namespace llvm;
41
43
44namespace llvm {
46}
48
49#define LV_NAME "loop-vectorize"
50#define DEBUG_TYPE LV_NAME
51
53 switch (getVPDefID()) {
54 case VPInstructionSC:
55 return cast<VPInstruction>(this)->opcodeMayReadOrWriteFromMemory();
56 case VPInterleaveSC:
57 return cast<VPInterleaveRecipe>(this)->getNumStoreOperands() > 0;
58 case VPWidenStoreEVLSC:
59 case VPWidenStoreSC:
60 return true;
61 case VPReplicateSC:
62 return cast<Instruction>(getVPSingleValue()->getUnderlyingValue())
63 ->mayWriteToMemory();
64 case VPWidenCallSC:
65 return !cast<VPWidenCallRecipe>(this)
66 ->getCalledScalarFunction()
67 ->onlyReadsMemory();
68 case VPWidenIntrinsicSC:
69 return cast<VPWidenIntrinsicRecipe>(this)->mayWriteToMemory();
70 case VPBranchOnMaskSC:
71 case VPScalarIVStepsSC:
72 case VPPredInstPHISC:
73 return false;
74 case VPBlendSC:
75 case VPReductionEVLSC:
76 case VPReductionSC:
77 case VPVectorPointerSC:
78 case VPWidenCanonicalIVSC:
79 case VPWidenCastSC:
80 case VPWidenGEPSC:
81 case VPWidenIntOrFpInductionSC:
82 case VPWidenLoadEVLSC:
83 case VPWidenLoadSC:
84 case VPWidenPHISC:
85 case VPWidenSC:
86 case VPWidenEVLSC:
87 case VPWidenSelectSC: {
88 const Instruction *I =
89 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
90 (void)I;
91 assert((!I || !I->mayWriteToMemory()) &&
92 "underlying instruction may write to memory");
93 return false;
94 }
95 default:
96 return true;
97 }
98}
99
101 switch (getVPDefID()) {
102 case VPInstructionSC:
103 return cast<VPInstruction>(this)->opcodeMayReadOrWriteFromMemory();
104 case VPWidenLoadEVLSC:
105 case VPWidenLoadSC:
106 return true;
107 case VPReplicateSC:
108 return cast<Instruction>(getVPSingleValue()->getUnderlyingValue())
109 ->mayReadFromMemory();
110 case VPWidenCallSC:
111 return !cast<VPWidenCallRecipe>(this)
112 ->getCalledScalarFunction()
113 ->onlyWritesMemory();
114 case VPWidenIntrinsicSC:
115 return cast<VPWidenIntrinsicRecipe>(this)->mayReadFromMemory();
116 case VPBranchOnMaskSC:
117 case VPPredInstPHISC:
118 case VPScalarIVStepsSC:
119 case VPWidenStoreEVLSC:
120 case VPWidenStoreSC:
121 return false;
122 case VPBlendSC:
123 case VPReductionEVLSC:
124 case VPReductionSC:
125 case VPVectorPointerSC:
126 case VPWidenCanonicalIVSC:
127 case VPWidenCastSC:
128 case VPWidenGEPSC:
129 case VPWidenIntOrFpInductionSC:
130 case VPWidenPHISC:
131 case VPWidenSC:
132 case VPWidenEVLSC:
133 case VPWidenSelectSC: {
134 const Instruction *I =
135 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
136 (void)I;
137 assert((!I || !I->mayReadFromMemory()) &&
138 "underlying instruction may read from memory");
139 return false;
140 }
141 default:
142 return true;
143 }
144}
145
147 switch (getVPDefID()) {
148 case VPDerivedIVSC:
149 case VPPredInstPHISC:
150 case VPScalarCastSC:
151 case VPReverseVectorPointerSC:
152 return false;
153 case VPInstructionSC:
154 return mayWriteToMemory();
155 case VPWidenCallSC: {
156 Function *Fn = cast<VPWidenCallRecipe>(this)->getCalledScalarFunction();
157 return mayWriteToMemory() || !Fn->doesNotThrow() || !Fn->willReturn();
158 }
159 case VPWidenIntrinsicSC:
160 return cast<VPWidenIntrinsicRecipe>(this)->mayHaveSideEffects();
161 case VPBlendSC:
162 case VPReductionEVLSC:
163 case VPReductionSC:
164 case VPScalarIVStepsSC:
165 case VPVectorPointerSC:
166 case VPWidenCanonicalIVSC:
167 case VPWidenCastSC:
168 case VPWidenGEPSC:
169 case VPWidenIntOrFpInductionSC:
170 case VPWidenPHISC:
171 case VPWidenPointerInductionSC:
172 case VPWidenSC:
173 case VPWidenEVLSC:
174 case VPWidenSelectSC: {
175 const Instruction *I =
176 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
177 (void)I;
178 assert((!I || !I->mayHaveSideEffects()) &&
179 "underlying instruction has side-effects");
180 return false;
181 }
182 case VPInterleaveSC:
183 return mayWriteToMemory();
184 case VPWidenLoadEVLSC:
185 case VPWidenLoadSC:
186 case VPWidenStoreEVLSC:
187 case VPWidenStoreSC:
188 assert(
189 cast<VPWidenMemoryRecipe>(this)->getIngredient().mayHaveSideEffects() ==
191 "mayHaveSideffects result for ingredient differs from this "
192 "implementation");
193 return mayWriteToMemory();
194 case VPReplicateSC: {
195 auto *R = cast<VPReplicateRecipe>(this);
196 return R->getUnderlyingInstr()->mayHaveSideEffects();
197 }
198 default:
199 return true;
200 }
201}
202
204 assert(!Parent && "Recipe already in some VPBasicBlock");
205 assert(InsertPos->getParent() &&
206 "Insertion position not in any VPBasicBlock");
207 InsertPos->getParent()->insert(this, InsertPos->getIterator());
208}
209
212 assert(!Parent && "Recipe already in some VPBasicBlock");
213 assert(I == BB.end() || I->getParent() == &BB);
214 BB.insert(this, I);
215}
216
218 assert(!Parent && "Recipe already in some VPBasicBlock");
219 assert(InsertPos->getParent() &&
220 "Insertion position not in any VPBasicBlock");
221 InsertPos->getParent()->insert(this, std::next(InsertPos->getIterator()));
222}
223
225 assert(getParent() && "Recipe not in any VPBasicBlock");
227 Parent = nullptr;
228}
229
231 assert(getParent() && "Recipe not in any VPBasicBlock");
233}
234
237 insertAfter(InsertPos);
238}
239
243 insertBefore(BB, I);
244}
245
247 // Get the underlying instruction for the recipe, if there is one. It is used
248 // to
249 // * decide if cost computation should be skipped for this recipe,
250 // * apply forced target instruction cost.
251 Instruction *UI = nullptr;
252 if (auto *S = dyn_cast<VPSingleDefRecipe>(this))
253 UI = dyn_cast_or_null<Instruction>(S->getUnderlyingValue());
254 else if (auto *IG = dyn_cast<VPInterleaveRecipe>(this))
255 UI = IG->getInsertPos();
256 else if (auto *WidenMem = dyn_cast<VPWidenMemoryRecipe>(this))
257 UI = &WidenMem->getIngredient();
258
259 InstructionCost RecipeCost;
260 if (UI && Ctx.skipCostComputation(UI, VF.isVector())) {
261 RecipeCost = 0;
262 } else {
263 RecipeCost = computeCost(VF, Ctx);
264 if (UI && ForceTargetInstructionCost.getNumOccurrences() > 0 &&
265 RecipeCost.isValid())
267 }
268
269 LLVM_DEBUG({
270 dbgs() << "Cost of " << RecipeCost << " for VF " << VF << ": ";
271 dump();
272 });
273 return RecipeCost;
274}
275
277 VPCostContext &Ctx) const {
278 llvm_unreachable("subclasses should implement computeCost");
279}
280
283 VPCostContext &Ctx) const {
284 std::optional<unsigned> Opcode = std::nullopt;
286 if (auto *WidenR = dyn_cast<VPWidenRecipe>(BinOpR))
287 Opcode = std::make_optional(WidenR->getOpcode());
288
289 VPRecipeBase *ExtAR = BinOpR->getOperand(0)->getDefiningRecipe();
290 VPRecipeBase *ExtBR = BinOpR->getOperand(1)->getDefiningRecipe();
291
292 auto *PhiType = Ctx.Types.inferScalarType(getOperand(1));
293 auto *InputTypeA = Ctx.Types.inferScalarType(ExtAR ? ExtAR->getOperand(0)
294 : BinOpR->getOperand(0));
295 auto *InputTypeB = Ctx.Types.inferScalarType(ExtBR ? ExtBR->getOperand(0)
296 : BinOpR->getOperand(1));
297
298 auto GetExtendKind = [](VPRecipeBase *R) {
299 // The extend could come from outside the plan.
300 if (!R)
302 auto *WidenCastR = dyn_cast<VPWidenCastRecipe>(R);
303 if (!WidenCastR)
305 if (WidenCastR->getOpcode() == Instruction::CastOps::ZExt)
307 if (WidenCastR->getOpcode() == Instruction::CastOps::SExt)
310 };
311
312 return Ctx.TTI.getPartialReductionCost(getOpcode(), InputTypeA, InputTypeB,
313 PhiType, VF, GetExtendKind(ExtAR),
314 GetExtendKind(ExtBR), Opcode);
315}
316
319 auto &Builder = State.Builder;
320
321 assert(getOpcode() == Instruction::Add &&
322 "Unhandled partial reduction opcode");
323
324 Value *BinOpVal = State.get(getOperand(0));
325 Value *PhiVal = State.get(getOperand(1));
326 assert(PhiVal && BinOpVal && "Phi and Mul must be set");
327
328 Type *RetTy = PhiVal->getType();
329
330 CallInst *V = Builder.CreateIntrinsic(
331 RetTy, Intrinsic::experimental_vector_partial_reduce_add,
332 {PhiVal, BinOpVal}, nullptr, "partial.reduce");
333
334 State.set(this, V);
335}
336
337#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
339 VPSlotTracker &SlotTracker) const {
340 O << Indent << "PARTIAL-REDUCE ";
342 O << " = " << Instruction::getOpcodeName(getOpcode()) << " ";
344}
345#endif
346
348 assert(OpType == OperationType::FPMathOp &&
349 "recipe doesn't have fast math flags");
350 FastMathFlags Res;
351 Res.setAllowReassoc(FMFs.AllowReassoc);
352 Res.setNoNaNs(FMFs.NoNaNs);
353 Res.setNoInfs(FMFs.NoInfs);
354 Res.setNoSignedZeros(FMFs.NoSignedZeros);
355 Res.setAllowReciprocal(FMFs.AllowReciprocal);
356 Res.setAllowContract(FMFs.AllowContract);
357 Res.setApproxFunc(FMFs.ApproxFunc);
358 return Res;
359}
360
361#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
363#endif
364
365template <unsigned PartOpIdx>
366VPValue *
368 if (U.getNumOperands() == PartOpIdx + 1)
369 return U.getOperand(PartOpIdx);
370 return nullptr;
371}
372
373template <unsigned PartOpIdx>
375 if (auto *UnrollPartOp = getUnrollPartOperand(U))
376 return cast<ConstantInt>(UnrollPartOp->getLiveInIRValue())->getZExtValue();
377 return 0;
378}
379
382 const Twine &Name)
383 : VPRecipeWithIRFlags(VPDef::VPInstructionSC, ArrayRef<VPValue *>({A, B}),
384 Pred, DL),
385 Opcode(Opcode), Name(Name.str()) {
386 assert(Opcode == Instruction::ICmp &&
387 "only ICmp predicates supported at the moment");
388}
389
391 std::initializer_list<VPValue *> Operands,
392 FastMathFlags FMFs, DebugLoc DL, const Twine &Name)
393 : VPRecipeWithIRFlags(VPDef::VPInstructionSC, Operands, FMFs, DL),
394 Opcode(Opcode), Name(Name.str()) {
395 // Make sure the VPInstruction is a floating-point operation.
396 assert(isFPMathOp() && "this op can't take fast-math flags");
397}
398
399bool VPInstruction::doesGeneratePerAllLanes() const {
400 return Opcode == VPInstruction::PtrAdd && !vputils::onlyFirstLaneUsed(this);
401}
402
403bool VPInstruction::canGenerateScalarForFirstLane() const {
405 return true;
407 return true;
408 switch (Opcode) {
409 case Instruction::ICmp:
410 case Instruction::Select:
418 return true;
419 default:
420 return false;
421 }
422}
423
424Value *VPInstruction::generatePerLane(VPTransformState &State,
425 const VPLane &Lane) {
426 IRBuilderBase &Builder = State.Builder;
427
429 "only PtrAdd opcodes are supported for now");
430 return Builder.CreatePtrAdd(State.get(getOperand(0), Lane),
431 State.get(getOperand(1), Lane), Name);
432}
433
434Value *VPInstruction::generate(VPTransformState &State) {
435 IRBuilderBase &Builder = State.Builder;
436
438 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
439 Value *A = State.get(getOperand(0), OnlyFirstLaneUsed);
440 Value *B = State.get(getOperand(1), OnlyFirstLaneUsed);
441 auto *Res =
442 Builder.CreateBinOp((Instruction::BinaryOps)getOpcode(), A, B, Name);
443 if (auto *I = dyn_cast<Instruction>(Res))
444 setFlags(I);
445 return Res;
446 }
447
448 switch (getOpcode()) {
449 case VPInstruction::Not: {
450 Value *A = State.get(getOperand(0));
451 return Builder.CreateNot(A, Name);
452 }
453 case Instruction::ICmp: {
454 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
455 Value *A = State.get(getOperand(0), OnlyFirstLaneUsed);
456 Value *B = State.get(getOperand(1), OnlyFirstLaneUsed);
457 return Builder.CreateCmp(getPredicate(), A, B, Name);
458 }
459 case Instruction::Select: {
460 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
461 Value *Cond = State.get(getOperand(0), OnlyFirstLaneUsed);
462 Value *Op1 = State.get(getOperand(1), OnlyFirstLaneUsed);
463 Value *Op2 = State.get(getOperand(2), OnlyFirstLaneUsed);
464 return Builder.CreateSelect(Cond, Op1, Op2, Name);
465 }
467 // Get first lane of vector induction variable.
468 Value *VIVElem0 = State.get(getOperand(0), VPLane(0));
469 // Get the original loop tripcount.
470 Value *ScalarTC = State.get(getOperand(1), VPLane(0));
471
472 // If this part of the active lane mask is scalar, generate the CMP directly
473 // to avoid unnecessary extracts.
474 if (State.VF.isScalar())
475 return Builder.CreateCmp(CmpInst::Predicate::ICMP_ULT, VIVElem0, ScalarTC,
476 Name);
477
478 auto *Int1Ty = Type::getInt1Ty(Builder.getContext());
479 auto *PredTy = VectorType::get(Int1Ty, State.VF);
480 return Builder.CreateIntrinsic(Intrinsic::get_active_lane_mask,
481 {PredTy, ScalarTC->getType()},
482 {VIVElem0, ScalarTC}, nullptr, Name);
483 }
485 // Generate code to combine the previous and current values in vector v3.
486 //
487 // vector.ph:
488 // v_init = vector(..., ..., ..., a[-1])
489 // br vector.body
490 //
491 // vector.body
492 // i = phi [0, vector.ph], [i+4, vector.body]
493 // v1 = phi [v_init, vector.ph], [v2, vector.body]
494 // v2 = a[i, i+1, i+2, i+3];
495 // v3 = vector(v1(3), v2(0, 1, 2))
496
497 auto *V1 = State.get(getOperand(0));
498 if (!V1->getType()->isVectorTy())
499 return V1;
500 Value *V2 = State.get(getOperand(1));
501 return Builder.CreateVectorSplice(V1, V2, -1, Name);
502 }
504 unsigned UF = getParent()->getPlan()->getUF();
505 Value *ScalarTC = State.get(getOperand(0), VPLane(0));
506 Value *Step = createStepForVF(Builder, ScalarTC->getType(), State.VF, UF);
507 Value *Sub = Builder.CreateSub(ScalarTC, Step);
508 Value *Cmp = Builder.CreateICmp(CmpInst::Predicate::ICMP_UGT, ScalarTC, Step);
509 Value *Zero = ConstantInt::get(ScalarTC->getType(), 0);
510 return Builder.CreateSelect(Cmp, Sub, Zero);
511 }
513 // TODO: Restructure this code with an explicit remainder loop, vsetvli can
514 // be outside of the main loop.
515 Value *AVL = State.get(getOperand(0), /*IsScalar*/ true);
516 // Compute EVL
517 assert(AVL->getType()->isIntegerTy() &&
518 "Requested vector length should be an integer.");
519
520 assert(State.VF.isScalable() && "Expected scalable vector factor.");
521 Value *VFArg = State.Builder.getInt32(State.VF.getKnownMinValue());
522
523 Value *EVL = State.Builder.CreateIntrinsic(
524 State.Builder.getInt32Ty(), Intrinsic::experimental_get_vector_length,
525 {AVL, VFArg, State.Builder.getTrue()});
526 return EVL;
527 }
529 unsigned Part = getUnrollPart(*this);
530 auto *IV = State.get(getOperand(0), VPLane(0));
531 assert(Part != 0 && "Must have a positive part");
532 // The canonical IV is incremented by the vectorization factor (num of
533 // SIMD elements) times the unroll part.
534 Value *Step = createStepForVF(Builder, IV->getType(), State.VF, Part);
535 return Builder.CreateAdd(IV, Step, Name, hasNoUnsignedWrap(),
537 }
539 Value *Cond = State.get(getOperand(0), VPLane(0));
540 // Replace the temporary unreachable terminator with a new conditional
541 // branch, hooking it up to backward destination for exiting blocks now and
542 // to forward destination(s) later when they are created.
543 BranchInst *CondBr =
544 Builder.CreateCondBr(Cond, Builder.GetInsertBlock(), nullptr);
545 CondBr->setSuccessor(0, nullptr);
547
548 if (!getParent()->isExiting())
549 return CondBr;
550
551 VPRegionBlock *ParentRegion = getParent()->getParent();
552 VPBasicBlock *Header = ParentRegion->getEntryBasicBlock();
553 CondBr->setSuccessor(1, State.CFG.VPBB2IRBB[Header]);
554 return CondBr;
555 }
557 // First create the compare.
558 Value *IV = State.get(getOperand(0), /*IsScalar*/ true);
559 Value *TC = State.get(getOperand(1), /*IsScalar*/ true);
560 Value *Cond = Builder.CreateICmpEQ(IV, TC);
561
562 // Now create the branch.
563 auto *Plan = getParent()->getPlan();
564 VPRegionBlock *TopRegion = Plan->getVectorLoopRegion();
565 VPBasicBlock *Header = TopRegion->getEntry()->getEntryBasicBlock();
566
567 // Replace the temporary unreachable terminator with a new conditional
568 // branch, hooking it up to backward destination (the header) now and to the
569 // forward destination (the exit/middle block) later when it is created.
570 // Note that CreateCondBr expects a valid BB as first argument, so we need
571 // to set it to nullptr later.
572 BranchInst *CondBr = Builder.CreateCondBr(Cond, Builder.GetInsertBlock(),
573 State.CFG.VPBB2IRBB[Header]);
574 CondBr->setSuccessor(0, nullptr);
576 return CondBr;
577 }
579 // FIXME: The cross-recipe dependency on VPReductionPHIRecipe is temporary
580 // and will be removed by breaking up the recipe further.
581 auto *PhiR = cast<VPReductionPHIRecipe>(getOperand(0));
582 auto *OrigPhi = cast<PHINode>(PhiR->getUnderlyingValue());
583 // Get its reduction variable descriptor.
584 const RecurrenceDescriptor &RdxDesc = PhiR->getRecurrenceDescriptor();
585
586 RecurKind RK = RdxDesc.getRecurrenceKind();
587
588 Type *PhiTy = OrigPhi->getType();
589 // The recipe's operands are the reduction phi, followed by one operand for
590 // each part of the reduction.
591 unsigned UF = getNumOperands() - 1;
592 VectorParts RdxParts(UF);
593 for (unsigned Part = 0; Part < UF; ++Part)
594 RdxParts[Part] = State.get(getOperand(1 + Part), PhiR->isInLoop());
595
596 // If the vector reduction can be performed in a smaller type, we truncate
597 // then extend the loop exit value to enable InstCombine to evaluate the
598 // entire expression in the smaller type.
599 // TODO: Handle this in truncateToMinBW.
600 if (State.VF.isVector() && PhiTy != RdxDesc.getRecurrenceType()) {
601 Type *RdxVecTy = VectorType::get(RdxDesc.getRecurrenceType(), State.VF);
602 for (unsigned Part = 0; Part < UF; ++Part)
603 RdxParts[Part] = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
604 }
605 // Reduce all of the unrolled parts into a single vector.
606 Value *ReducedPartRdx = RdxParts[0];
607 unsigned Op = RdxDesc.getOpcode();
609 Op = Instruction::Or;
610
611 if (PhiR->isOrdered()) {
612 ReducedPartRdx = RdxParts[UF - 1];
613 } else {
614 // Floating-point operations should have some FMF to enable the reduction.
616 Builder.setFastMathFlags(RdxDesc.getFastMathFlags());
617 for (unsigned Part = 1; Part < UF; ++Part) {
618 Value *RdxPart = RdxParts[Part];
619 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
620 ReducedPartRdx = Builder.CreateBinOp(
621 (Instruction::BinaryOps)Op, RdxPart, ReducedPartRdx, "bin.rdx");
623 ReducedPartRdx =
624 createMinMaxOp(Builder, RecurKind::SMax, ReducedPartRdx, RdxPart);
625 else
626 ReducedPartRdx = createMinMaxOp(Builder, RK, ReducedPartRdx, RdxPart);
627 }
628 }
629
630 // Create the reduction after the loop. Note that inloop reductions create
631 // the target reduction in the loop using a Reduction recipe.
632 if ((State.VF.isVector() ||
635 !PhiR->isInLoop()) {
636 ReducedPartRdx =
637 createReduction(Builder, RdxDesc, ReducedPartRdx, OrigPhi);
638 // If the reduction can be performed in a smaller type, we need to extend
639 // the reduction to the wider type before we branch to the original loop.
640 if (PhiTy != RdxDesc.getRecurrenceType())
641 ReducedPartRdx = RdxDesc.isSigned()
642 ? Builder.CreateSExt(ReducedPartRdx, PhiTy)
643 : Builder.CreateZExt(ReducedPartRdx, PhiTy);
644 }
645
646 return ReducedPartRdx;
647 }
649 auto *CI = cast<ConstantInt>(getOperand(1)->getLiveInIRValue());
650 unsigned Offset = CI->getZExtValue();
651 assert(Offset > 0 && "Offset from end must be positive");
652 Value *Res;
653 if (State.VF.isVector()) {
654 assert(Offset <= State.VF.getKnownMinValue() &&
655 "invalid offset to extract from");
656 // Extract lane VF - Offset from the operand.
657 Res = State.get(getOperand(0), VPLane::getLaneFromEnd(State.VF, Offset));
658 } else {
659 assert(Offset <= 1 && "invalid offset to extract from");
660 Res = State.get(getOperand(0));
661 }
662 if (isa<ExtractElementInst>(Res))
663 Res->setName(Name);
664 return Res;
665 }
667 Value *A = State.get(getOperand(0));
668 Value *B = State.get(getOperand(1));
669 return Builder.CreateLogicalAnd(A, B, Name);
670 }
673 "can only generate first lane for PtrAdd");
674 Value *Ptr = State.get(getOperand(0), VPLane(0));
675 Value *Addend = State.get(getOperand(1), VPLane(0));
676 return Builder.CreatePtrAdd(Ptr, Addend, Name, getGEPNoWrapFlags());
677 }
679 Value *IncomingFromVPlanPred =
680 State.get(getOperand(0), /* IsScalar */ true);
681 Value *IncomingFromOtherPreds =
682 State.get(getOperand(1), /* IsScalar */ true);
683 auto *NewPhi =
684 Builder.CreatePHI(State.TypeAnalysis.inferScalarType(this), 2, Name);
685 BasicBlock *VPlanPred =
686 State.CFG
687 .VPBB2IRBB[cast<VPBasicBlock>(getParent()->getPredecessors()[0])];
688 NewPhi->addIncoming(IncomingFromVPlanPred, VPlanPred);
689 for (auto *OtherPred : predecessors(Builder.GetInsertBlock())) {
690 if (OtherPred == VPlanPred)
691 continue;
692 NewPhi->addIncoming(IncomingFromOtherPreds, OtherPred);
693 }
694 return NewPhi;
695 }
697 Value *A = State.get(getOperand(0));
698 return Builder.CreateOrReduce(A);
699 }
700
701 default:
702 llvm_unreachable("Unsupported opcode for instruction");
703 }
704}
705
710}
711
714}
715
716#if !defined(NDEBUG)
717bool VPInstruction::isFPMathOp() const {
718 // Inspired by FPMathOperator::classof. Notable differences are that we don't
719 // support Call, PHI and Select opcodes here yet.
720 return Opcode == Instruction::FAdd || Opcode == Instruction::FMul ||
721 Opcode == Instruction::FNeg || Opcode == Instruction::FSub ||
722 Opcode == Instruction::FDiv || Opcode == Instruction::FRem ||
723 Opcode == Instruction::FCmp || Opcode == Instruction::Select;
724}
725#endif
726
728 assert(!State.Lane && "VPInstruction executing an Lane");
730 assert((hasFastMathFlags() == isFPMathOp() ||
731 getOpcode() == Instruction::Select) &&
732 "Recipe not a FPMathOp but has fast-math flags?");
733 if (hasFastMathFlags())
736 bool GeneratesPerFirstLaneOnly = canGenerateScalarForFirstLane() &&
739 bool GeneratesPerAllLanes = doesGeneratePerAllLanes();
740 if (GeneratesPerAllLanes) {
741 for (unsigned Lane = 0, NumLanes = State.VF.getKnownMinValue();
742 Lane != NumLanes; ++Lane) {
743 Value *GeneratedValue = generatePerLane(State, VPLane(Lane));
744 assert(GeneratedValue && "generatePerLane must produce a value");
745 State.set(this, GeneratedValue, VPLane(Lane));
746 }
747 return;
748 }
749
750 Value *GeneratedValue = generate(State);
751 if (!hasResult())
752 return;
753 assert(GeneratedValue && "generate must produce a value");
754 assert(
755 (GeneratedValue->getType()->isVectorTy() == !GeneratesPerFirstLaneOnly ||
756 State.VF.isScalar()) &&
757 "scalar value but not only first lane defined");
758 State.set(this, GeneratedValue,
759 /*IsScalar*/ GeneratesPerFirstLaneOnly);
760}
761
764 return false;
765 switch (getOpcode()) {
766 case Instruction::ICmp:
767 case Instruction::Select:
776 return false;
777 default:
778 return true;
779 }
780}
781
783 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
785 return vputils::onlyFirstLaneUsed(this);
786
787 switch (getOpcode()) {
788 default:
789 return false;
790 case Instruction::ICmp:
791 case Instruction::Select:
792 case Instruction::Or:
794 // TODO: Cover additional opcodes.
795 return vputils::onlyFirstLaneUsed(this);
803 return true;
804 };
805 llvm_unreachable("switch should return");
806}
807
809 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
811 return vputils::onlyFirstPartUsed(this);
812
813 switch (getOpcode()) {
814 default:
815 return false;
816 case Instruction::ICmp:
817 case Instruction::Select:
818 return vputils::onlyFirstPartUsed(this);
822 return true;
823 };
824 llvm_unreachable("switch should return");
825}
826
827#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
829 VPSlotTracker SlotTracker(getParent()->getPlan());
830 print(dbgs(), "", SlotTracker);
831}
832
834 VPSlotTracker &SlotTracker) const {
835 O << Indent << "EMIT ";
836
837 if (hasResult()) {
839 O << " = ";
840 }
841
842 switch (getOpcode()) {
844 O << "not";
845 break;
847 O << "combined load";
848 break;
850 O << "combined store";
851 break;
853 O << "active lane mask";
854 break;
856 O << "resume-phi";
857 break;
859 O << "EXPLICIT-VECTOR-LENGTH";
860 break;
862 O << "first-order splice";
863 break;
865 O << "branch-on-cond";
866 break;
868 O << "TC > VF ? TC - VF : 0";
869 break;
871 O << "VF * Part +";
872 break;
874 O << "branch-on-count";
875 break;
877 O << "extract-from-end";
878 break;
880 O << "compute-reduction-result";
881 break;
883 O << "logical-and";
884 break;
886 O << "ptradd";
887 break;
889 O << "any-of";
890 break;
891 default:
893 }
894
895 printFlags(O);
897
898 if (auto DL = getDebugLoc()) {
899 O << ", !dbg ";
900 DL.print(O);
901 }
902}
903#endif
904
906 assert((isa<PHINode>(&I) || getNumOperands() == 0) &&
907 "Only PHINodes can have extra operands");
908 for (const auto &[Idx, Op] : enumerate(operands())) {
909 VPValue *ExitValue = Op;
910 auto Lane = vputils::isUniformAfterVectorization(ExitValue)
914 auto *PredVPBB = Pred->getExitingBasicBlock();
915 BasicBlock *PredBB = State.CFG.VPBB2IRBB[PredVPBB];
916 // Set insertion point in PredBB in case an extract needs to be generated.
917 // TODO: Model extracts explicitly.
918 State.Builder.SetInsertPoint(PredBB, PredBB->getFirstNonPHIIt());
919 Value *V = State.get(ExitValue, VPLane(Lane));
920 auto *Phi = cast<PHINode>(&I);
921 // If there is no existing block for PredBB in the phi, add a new incoming
922 // value. Otherwise update the existing incoming value for PredBB.
923 if (Phi->getBasicBlockIndex(PredBB) == -1)
924 Phi->addIncoming(V, PredBB);
925 else
926 Phi->setIncomingValueForBlock(PredBB, V);
927 }
928
929 // Advance the insert point after the wrapped IR instruction. This allows
930 // interleaving VPIRInstructions and other recipes.
931 State.Builder.SetInsertPoint(I.getParent(), std::next(I.getIterator()));
932}
933
935 VPCostContext &Ctx) const {
936 // The recipe wraps an existing IR instruction on the border of VPlan's scope,
937 // hence it does not contribute to the cost-modeling for the VPlan.
938 return 0;
939}
940
942 assert(isa<PHINode>(getInstruction()) &&
943 "can only add exiting operands to phi nodes");
944 assert(getNumOperands() == 1 && "must have a single operand");
945 VPValue *Exiting = getOperand(0);
946 if (!Exiting->isLiveIn()) {
948 auto &Plan = *getParent()->getPlan();
949 Exiting = Builder.createNaryOp(
951 {Exiting,
952 Plan.getOrAddLiveIn(ConstantInt::get(IntegerType::get(Ctx, 32), 1))});
953 }
954 setOperand(0, Exiting);
955}
956
957#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
959 VPSlotTracker &SlotTracker) const {
960 O << Indent << "IR " << I;
961
962 if (getNumOperands() != 0) {
963 O << " (extra operand" << (getNumOperands() > 1 ? "s" : "") << ": ";
965 enumerate(operands()), O, [this, &O, &SlotTracker](auto Op) {
966 Op.value()->printAsOperand(O, SlotTracker);
967 O << " from ";
968 getParent()->getPredecessors()[Op.index()]->printAsOperand(O);
969 });
970 O << ")";
971 }
972}
973#endif
974
976 assert(State.VF.isVector() && "not widening");
978
979 FunctionType *VFTy = Variant->getFunctionType();
980 // Add return type if intrinsic is overloaded on it.
982 for (const auto &I : enumerate(arg_operands())) {
983 Value *Arg;
984 // Some vectorized function variants may also take a scalar argument,
985 // e.g. linear parameters for pointers. This needs to be the scalar value
986 // from the start of the respective part when interleaving.
987 if (!VFTy->getParamType(I.index())->isVectorTy())
988 Arg = State.get(I.value(), VPLane(0));
989 else
990 Arg = State.get(I.value(), onlyFirstLaneUsed(I.value()));
991 Args.push_back(Arg);
992 }
993
994 assert(Variant != nullptr && "Can't create vector function.");
995
996 auto *CI = cast_or_null<CallInst>(getUnderlyingValue());
998 if (CI)
999 CI->getOperandBundlesAsDefs(OpBundles);
1000
1001 CallInst *V = State.Builder.CreateCall(Variant, Args, OpBundles);
1002 setFlags(V);
1003
1004 if (!V->getType()->isVoidTy())
1005 State.set(this, V);
1006 State.addMetadata(V, CI);
1007}
1008
1010 VPCostContext &Ctx) const {
1011 return Ctx.TTI.getCallInstrCost(nullptr, Variant->getReturnType(),
1012 Variant->getFunctionType()->params(),
1013 Ctx.CostKind);
1014}
1015
1016#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1018 VPSlotTracker &SlotTracker) const {
1019 O << Indent << "WIDEN-CALL ";
1020
1021 Function *CalledFn = getCalledScalarFunction();
1022 if (CalledFn->getReturnType()->isVoidTy())
1023 O << "void ";
1024 else {
1026 O << " = ";
1027 }
1028
1029 O << "call";
1030 printFlags(O);
1031 O << " @" << CalledFn->getName() << "(";
1033 Op->printAsOperand(O, SlotTracker);
1034 });
1035 O << ")";
1036
1037 O << " (using library function";
1038 if (Variant->hasName())
1039 O << ": " << Variant->getName();
1040 O << ")";
1041}
1042#endif
1043
1045 assert(State.VF.isVector() && "not widening");
1047
1048 SmallVector<Type *, 2> TysForDecl;
1049 // Add return type if intrinsic is overloaded on it.
1050 if (isVectorIntrinsicWithOverloadTypeAtArg(VectorIntrinsicID, -1, State.TTI))
1051 TysForDecl.push_back(VectorType::get(getResultType(), State.VF));
1053 for (const auto &I : enumerate(operands())) {
1054 // Some intrinsics have a scalar argument - don't replace it with a
1055 // vector.
1056 Value *Arg;
1057 if (isVectorIntrinsicWithScalarOpAtArg(VectorIntrinsicID, I.index(),
1058 State.TTI))
1059 Arg = State.get(I.value(), VPLane(0));
1060 else
1061 Arg = State.get(I.value(), onlyFirstLaneUsed(I.value()));
1062 if (isVectorIntrinsicWithOverloadTypeAtArg(VectorIntrinsicID, I.index(),
1063 State.TTI))
1064 TysForDecl.push_back(Arg->getType());
1065 Args.push_back(Arg);
1066 }
1067
1068 // Use vector version of the intrinsic.
1069 Module *M = State.Builder.GetInsertBlock()->getModule();
1070 Function *VectorF =
1071 Intrinsic::getOrInsertDeclaration(M, VectorIntrinsicID, TysForDecl);
1072 assert(VectorF &&
1073 "Can't retrieve vector intrinsic or vector-predication intrinsics.");
1074
1075 auto *CI = cast_or_null<CallInst>(getUnderlyingValue());
1077 if (CI)
1078 CI->getOperandBundlesAsDefs(OpBundles);
1079
1080 CallInst *V = State.Builder.CreateCall(VectorF, Args, OpBundles);
1081
1082 setFlags(V);
1083
1084 if (!V->getType()->isVoidTy())
1085 State.set(this, V);
1086 State.addMetadata(V, CI);
1087}
1088
1090 VPCostContext &Ctx) const {
1091 // Some backends analyze intrinsic arguments to determine cost. Use the
1092 // underlying value for the operand if it has one. Otherwise try to use the
1093 // operand of the underlying call instruction, if there is one. Otherwise
1094 // clear Arguments.
1095 // TODO: Rework TTI interface to be independent of concrete IR values.
1097 for (const auto &[Idx, Op] : enumerate(operands())) {
1098 auto *V = Op->getUnderlyingValue();
1099 if (!V) {
1100 // Push all the VP Intrinsic's ops into the Argments even if is nullptr.
1101 // Some VP Intrinsic's cost will assert the number of parameters.
1102 // Mainly appears in the following two scenarios:
1103 // 1. EVL Op is nullptr
1104 // 2. The Argmunt of the VP Intrinsic is also the VP Intrinsic
1105 if (VPIntrinsic::isVPIntrinsic(VectorIntrinsicID)) {
1106 Arguments.push_back(V);
1107 continue;
1108 }
1109 if (auto *UI = dyn_cast_or_null<CallBase>(getUnderlyingValue())) {
1110 Arguments.push_back(UI->getArgOperand(Idx));
1111 continue;
1112 }
1113 Arguments.clear();
1114 break;
1115 }
1116 Arguments.push_back(V);
1117 }
1118
1119 Type *RetTy = toVectorTy(Ctx.Types.inferScalarType(this), VF);
1120 SmallVector<Type *> ParamTys;
1121 for (unsigned I = 0; I != getNumOperands(); ++I)
1122 ParamTys.push_back(
1124
1125 // TODO: Rework TTI interface to avoid reliance on underlying IntrinsicInst.
1127 IntrinsicCostAttributes CostAttrs(
1128 VectorIntrinsicID, RetTy, Arguments, ParamTys, FMF,
1129 dyn_cast_or_null<IntrinsicInst>(getUnderlyingValue()));
1130 return Ctx.TTI.getIntrinsicInstrCost(CostAttrs, Ctx.CostKind);
1131}
1132
1134 return Intrinsic::getBaseName(VectorIntrinsicID);
1135}
1136
1138 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
1139 // Vector predication intrinsics only demand the the first lane the last
1140 // operand (the EVL operand).
1141 return VPIntrinsic::isVPIntrinsic(VectorIntrinsicID) &&
1142 Op == getOperand(getNumOperands() - 1);
1143}
1144
1145#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1147 VPSlotTracker &SlotTracker) const {
1148 O << Indent << "WIDEN-INTRINSIC ";
1149 if (ResultTy->isVoidTy()) {
1150 O << "void ";
1151 } else {
1153 O << " = ";
1154 }
1155
1156 O << "call";
1157 printFlags(O);
1158 O << getIntrinsicName() << "(";
1159
1161 Op->printAsOperand(O, SlotTracker);
1162 });
1163 O << ")";
1164}
1165#endif
1166
1169 IRBuilderBase &Builder = State.Builder;
1170
1171 Value *Address = State.get(getOperand(0));
1172 Value *IncAmt = State.get(getOperand(1), /*IsScalar=*/true);
1173 VectorType *VTy = cast<VectorType>(Address->getType());
1174
1175 // The histogram intrinsic requires a mask even if the recipe doesn't;
1176 // if the mask operand was omitted then all lanes should be executed and
1177 // we just need to synthesize an all-true mask.
1178 Value *Mask = nullptr;
1179 if (VPValue *VPMask = getMask())
1180 Mask = State.get(VPMask);
1181 else
1182 Mask =
1183 Builder.CreateVectorSplat(VTy->getElementCount(), Builder.getInt1(1));
1184
1185 // If this is a subtract, we want to invert the increment amount. We may
1186 // add a separate intrinsic in future, but for now we'll try this.
1187 if (Opcode == Instruction::Sub)
1188 IncAmt = Builder.CreateNeg(IncAmt);
1189 else
1190 assert(Opcode == Instruction::Add && "only add or sub supported for now");
1191
1192 State.Builder.CreateIntrinsic(Intrinsic::experimental_vector_histogram_add,
1193 {VTy, IncAmt->getType()},
1194 {Address, IncAmt, Mask});
1195}
1196
1198 VPCostContext &Ctx) const {
1199 // FIXME: Take the gather and scatter into account as well. For now we're
1200 // generating the same cost as the fallback path, but we'll likely
1201 // need to create a new TTI method for determining the cost, including
1202 // whether we can use base + vec-of-smaller-indices or just
1203 // vec-of-pointers.
1204 assert(VF.isVector() && "Invalid VF for histogram cost");
1205 Type *AddressTy = Ctx.Types.inferScalarType(getOperand(0));
1206 VPValue *IncAmt = getOperand(1);
1207 Type *IncTy = Ctx.Types.inferScalarType(IncAmt);
1208 VectorType *VTy = VectorType::get(IncTy, VF);
1209
1210 // Assume that a non-constant update value (or a constant != 1) requires
1211 // a multiply, and add that into the cost.
1212 InstructionCost MulCost =
1213 Ctx.TTI.getArithmeticInstrCost(Instruction::Mul, VTy, Ctx.CostKind);
1214 if (IncAmt->isLiveIn()) {
1215 ConstantInt *CI = dyn_cast<ConstantInt>(IncAmt->getLiveInIRValue());
1216
1217 if (CI && CI->getZExtValue() == 1)
1218 MulCost = TTI::TCC_Free;
1219 }
1220
1221 // Find the cost of the histogram operation itself.
1222 Type *PtrTy = VectorType::get(AddressTy, VF);
1223 Type *MaskTy = VectorType::get(Type::getInt1Ty(Ctx.LLVMCtx), VF);
1224 IntrinsicCostAttributes ICA(Intrinsic::experimental_vector_histogram_add,
1226 {PtrTy, IncTy, MaskTy});
1227
1228 // Add the costs together with the add/sub operation.
1229 return Ctx.TTI.getIntrinsicInstrCost(ICA, Ctx.CostKind) + MulCost +
1230 Ctx.TTI.getArithmeticInstrCost(Opcode, VTy, Ctx.CostKind);
1231}
1232
1233#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1235 VPSlotTracker &SlotTracker) const {
1236 O << Indent << "WIDEN-HISTOGRAM buckets: ";
1238
1239 if (Opcode == Instruction::Sub)
1240 O << ", dec: ";
1241 else {
1242 assert(Opcode == Instruction::Add);
1243 O << ", inc: ";
1244 }
1246
1247 if (VPValue *Mask = getMask()) {
1248 O << ", mask: ";
1249 Mask->printAsOperand(O, SlotTracker);
1250 }
1251}
1252
1254 VPSlotTracker &SlotTracker) const {
1255 O << Indent << "WIDEN-SELECT ";
1257 O << " = select ";
1258 printFlags(O);
1260 O << ", ";
1262 O << ", ";
1264 O << (isInvariantCond() ? " (condition is loop invariant)" : "");
1265}
1266#endif
1267
1270
1271 // The condition can be loop invariant but still defined inside the
1272 // loop. This means that we can't just use the original 'cond' value.
1273 // We have to take the 'vectorized' value and pick the first lane.
1274 // Instcombine will make this a no-op.
1275 auto *InvarCond =
1276 isInvariantCond() ? State.get(getCond(), VPLane(0)) : nullptr;
1277
1278 Value *Cond = InvarCond ? InvarCond : State.get(getCond());
1279 Value *Op0 = State.get(getOperand(1));
1280 Value *Op1 = State.get(getOperand(2));
1281 Value *Sel = State.Builder.CreateSelect(Cond, Op0, Op1);
1282 State.set(this, Sel);
1283 if (isa<FPMathOperator>(Sel))
1284 setFlags(cast<Instruction>(Sel));
1285 State.addMetadata(Sel, dyn_cast_or_null<Instruction>(getUnderlyingValue()));
1286}
1287
1289 VPCostContext &Ctx) const {
1290 SelectInst *SI = cast<SelectInst>(getUnderlyingValue());
1291 bool ScalarCond = getOperand(0)->isDefinedOutsideLoopRegions();
1292 Type *ScalarTy = Ctx.Types.inferScalarType(this);
1293 Type *VectorTy = toVectorTy(Ctx.Types.inferScalarType(this), VF);
1294
1295 VPValue *Op0, *Op1;
1296 using namespace llvm::VPlanPatternMatch;
1297 if (!ScalarCond && ScalarTy->getScalarSizeInBits() == 1 &&
1298 (match(this, m_LogicalAnd(m_VPValue(Op0), m_VPValue(Op1))) ||
1299 match(this, m_LogicalOr(m_VPValue(Op0), m_VPValue(Op1))))) {
1300 // select x, y, false --> x & y
1301 // select x, true, y --> x | y
1302 const auto [Op1VK, Op1VP] = Ctx.getOperandInfo(Op0);
1303 const auto [Op2VK, Op2VP] = Ctx.getOperandInfo(Op1);
1304
1306 if (all_of(operands(),
1307 [](VPValue *Op) { return Op->getUnderlyingValue(); }))
1308 Operands.append(SI->op_begin(), SI->op_end());
1309 bool IsLogicalOr = match(this, m_LogicalOr(m_VPValue(Op0), m_VPValue(Op1)));
1310 return Ctx.TTI.getArithmeticInstrCost(
1311 IsLogicalOr ? Instruction::Or : Instruction::And, VectorTy,
1312 Ctx.CostKind, {Op1VK, Op1VP}, {Op2VK, Op2VP}, Operands, SI);
1313 }
1314
1315 Type *CondTy = Ctx.Types.inferScalarType(getOperand(0));
1316 if (!ScalarCond)
1317 CondTy = VectorType::get(CondTy, VF);
1318
1320 if (auto *Cmp = dyn_cast<CmpInst>(SI->getCondition()))
1321 Pred = Cmp->getPredicate();
1322 return Ctx.TTI.getCmpSelInstrCost(
1323 Instruction::Select, VectorTy, CondTy, Pred, Ctx.CostKind,
1324 {TTI::OK_AnyValue, TTI::OP_None}, {TTI::OK_AnyValue, TTI::OP_None}, SI);
1325}
1326
1327VPRecipeWithIRFlags::FastMathFlagsTy::FastMathFlagsTy(
1328 const FastMathFlags &FMF) {
1329 AllowReassoc = FMF.allowReassoc();
1330 NoNaNs = FMF.noNaNs();
1331 NoInfs = FMF.noInfs();
1332 NoSignedZeros = FMF.noSignedZeros();
1333 AllowReciprocal = FMF.allowReciprocal();
1334 AllowContract = FMF.allowContract();
1335 ApproxFunc = FMF.approxFunc();
1336}
1337
1338#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1340 switch (OpType) {
1341 case OperationType::Cmp:
1343 break;
1344 case OperationType::DisjointOp:
1346 O << " disjoint";
1347 break;
1348 case OperationType::PossiblyExactOp:
1349 if (ExactFlags.IsExact)
1350 O << " exact";
1351 break;
1352 case OperationType::OverflowingBinOp:
1353 if (WrapFlags.HasNUW)
1354 O << " nuw";
1355 if (WrapFlags.HasNSW)
1356 O << " nsw";
1357 break;
1358 case OperationType::FPMathOp:
1360 break;
1361 case OperationType::GEPOp:
1362 if (GEPFlags.isInBounds())
1363 O << " inbounds";
1365 O << " nusw";
1367 O << " nuw";
1368 break;
1369 case OperationType::NonNegOp:
1370 if (NonNegFlags.NonNeg)
1371 O << " nneg";
1372 break;
1373 case OperationType::Other:
1374 break;
1375 }
1376 if (getNumOperands() > 0)
1377 O << " ";
1378}
1379#endif
1380
1383 auto &Builder = State.Builder;
1384 switch (Opcode) {
1385 case Instruction::Call:
1386 case Instruction::Br:
1387 case Instruction::PHI:
1388 case Instruction::GetElementPtr:
1389 case Instruction::Select:
1390 llvm_unreachable("This instruction is handled by a different recipe.");
1391 case Instruction::UDiv:
1392 case Instruction::SDiv:
1393 case Instruction::SRem:
1394 case Instruction::URem:
1395 case Instruction::Add:
1396 case Instruction::FAdd:
1397 case Instruction::Sub:
1398 case Instruction::FSub:
1399 case Instruction::FNeg:
1400 case Instruction::Mul:
1401 case Instruction::FMul:
1402 case Instruction::FDiv:
1403 case Instruction::FRem:
1404 case Instruction::Shl:
1405 case Instruction::LShr:
1406 case Instruction::AShr:
1407 case Instruction::And:
1408 case Instruction::Or:
1409 case Instruction::Xor: {
1410 // Just widen unops and binops.
1412 for (VPValue *VPOp : operands())
1413 Ops.push_back(State.get(VPOp));
1414
1415 Value *V = Builder.CreateNAryOp(Opcode, Ops);
1416
1417 if (auto *VecOp = dyn_cast<Instruction>(V))
1418 setFlags(VecOp);
1419
1420 // Use this vector value for all users of the original instruction.
1421 State.set(this, V);
1422 State.addMetadata(V, dyn_cast_or_null<Instruction>(getUnderlyingValue()));
1423 break;
1424 }
1425 case Instruction::Freeze: {
1426 Value *Op = State.get(getOperand(0));
1427
1428 Value *Freeze = Builder.CreateFreeze(Op);
1429 State.set(this, Freeze);
1430 break;
1431 }
1432 case Instruction::ICmp:
1433 case Instruction::FCmp: {
1434 // Widen compares. Generate vector compares.
1435 bool FCmp = Opcode == Instruction::FCmp;
1436 Value *A = State.get(getOperand(0));
1437 Value *B = State.get(getOperand(1));
1438 Value *C = nullptr;
1439 if (FCmp) {
1440 // Propagate fast math flags.
1441 C = Builder.CreateFCmpFMF(
1442 getPredicate(), A, B,
1443 dyn_cast_or_null<Instruction>(getUnderlyingValue()));
1444 } else {
1445 C = Builder.CreateICmp(getPredicate(), A, B);
1446 }
1447 State.set(this, C);
1448 State.addMetadata(C, dyn_cast_or_null<Instruction>(getUnderlyingValue()));
1449 break;
1450 }
1451 default:
1452 // This instruction is not vectorized by simple widening.
1453 LLVM_DEBUG(dbgs() << "LV: Found an unhandled opcode : "
1454 << Instruction::getOpcodeName(Opcode));
1455 llvm_unreachable("Unhandled instruction!");
1456 } // end of switch.
1457
1458#if !defined(NDEBUG)
1459 // Verify that VPlan type inference results agree with the type of the
1460 // generated values.
1462 State.get(this)->getType() &&
1463 "inferred type and type from generated instructions do not match");
1464#endif
1465}
1466
1468 VPCostContext &Ctx) const {
1469 switch (Opcode) {
1470 case Instruction::FNeg: {
1471 Type *VectorTy = toVectorTy(Ctx.Types.inferScalarType(this), VF);
1472 return Ctx.TTI.getArithmeticInstrCost(
1473 Opcode, VectorTy, Ctx.CostKind,
1474 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
1475 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None});
1476 }
1477
1478 case Instruction::UDiv:
1479 case Instruction::SDiv:
1480 case Instruction::SRem:
1481 case Instruction::URem:
1482 // More complex computation, let the legacy cost-model handle this for now.
1483 return Ctx.getLegacyCost(cast<Instruction>(getUnderlyingValue()), VF);
1484 case Instruction::Add:
1485 case Instruction::FAdd:
1486 case Instruction::Sub:
1487 case Instruction::FSub:
1488 case Instruction::Mul:
1489 case Instruction::FMul:
1490 case Instruction::FDiv:
1491 case Instruction::FRem:
1492 case Instruction::Shl:
1493 case Instruction::LShr:
1494 case Instruction::AShr:
1495 case Instruction::And:
1496 case Instruction::Or:
1497 case Instruction::Xor: {
1498 VPValue *RHS = getOperand(1);
1499 // Certain instructions can be cheaper to vectorize if they have a constant
1500 // second vector operand. One example of this are shifts on x86.
1503 if (RHS->isLiveIn())
1504 RHSInfo = Ctx.TTI.getOperandInfo(RHS->getLiveInIRValue());
1505
1506 if (RHSInfo.Kind == TargetTransformInfo::OK_AnyValue &&
1509 Type *VectorTy = toVectorTy(Ctx.Types.inferScalarType(this), VF);
1510 Instruction *CtxI = dyn_cast_or_null<Instruction>(getUnderlyingValue());
1511
1513 if (CtxI)
1514 Operands.append(CtxI->value_op_begin(), CtxI->value_op_end());
1515 return Ctx.TTI.getArithmeticInstrCost(
1516 Opcode, VectorTy, Ctx.CostKind,
1517 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
1518 RHSInfo, Operands, CtxI, &Ctx.TLI);
1519 }
1520 case Instruction::Freeze: {
1521 // This opcode is unknown. Assume that it is the same as 'mul'.
1522 Type *VectorTy = toVectorTy(Ctx.Types.inferScalarType(this), VF);
1523 return Ctx.TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy,
1524 Ctx.CostKind);
1525 }
1526 case Instruction::ICmp:
1527 case Instruction::FCmp: {
1528 Instruction *CtxI = dyn_cast_or_null<Instruction>(getUnderlyingValue());
1529 Type *VectorTy = toVectorTy(Ctx.Types.inferScalarType(getOperand(0)), VF);
1530 return Ctx.TTI.getCmpSelInstrCost(Opcode, VectorTy, nullptr, getPredicate(),
1531 Ctx.CostKind,
1532 {TTI::OK_AnyValue, TTI::OP_None},
1533 {TTI::OK_AnyValue, TTI::OP_None}, CtxI);
1534 }
1535 default:
1536 llvm_unreachable("Unsupported opcode for instruction");
1537 }
1538}
1539
1541 unsigned Opcode = getOpcode();
1542 // TODO: Support other opcodes
1543 if (!Instruction::isBinaryOp(Opcode) && !Instruction::isUnaryOp(Opcode))
1544 llvm_unreachable("Unsupported opcode in VPWidenEVLRecipe::execute");
1545
1547
1548 assert(State.get(getOperand(0))->getType()->isVectorTy() &&
1549 "VPWidenEVLRecipe should not be used for scalars");
1550
1551 VPValue *EVL = getEVL();
1552 Value *EVLArg = State.get(EVL, /*NeedsScalar=*/true);
1553 IRBuilderBase &BuilderIR = State.Builder;
1554 VectorBuilder Builder(BuilderIR);
1555 Value *Mask = BuilderIR.CreateVectorSplat(State.VF, BuilderIR.getTrue());
1556
1558 for (unsigned I = 0, E = getNumOperands() - 1; I < E; ++I) {
1559 VPValue *VPOp = getOperand(I);
1560 Ops.push_back(State.get(VPOp));
1561 }
1562
1563 Builder.setMask(Mask).setEVL(EVLArg);
1564 Value *VPInst =
1565 Builder.createVectorInstruction(Opcode, Ops[0]->getType(), Ops, "vp.op");
1566 // Currently vp-intrinsics only accept FMF flags.
1567 // TODO: Enable other flags when support is added.
1568 if (isa<FPMathOperator>(VPInst))
1569 setFlags(cast<Instruction>(VPInst));
1570
1571 State.set(this, VPInst);
1572 State.addMetadata(VPInst,
1573 dyn_cast_or_null<Instruction>(getUnderlyingValue()));
1574}
1575
1576#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1578 VPSlotTracker &SlotTracker) const {
1579 O << Indent << "WIDEN ";
1581 O << " = " << Instruction::getOpcodeName(Opcode);
1582 printFlags(O);
1584}
1585
1587 VPSlotTracker &SlotTracker) const {
1588 O << Indent << "WIDEN ";
1590 O << " = vp." << Instruction::getOpcodeName(getOpcode());
1591 printFlags(O);
1593}
1594#endif
1595
1598 auto &Builder = State.Builder;
1599 /// Vectorize casts.
1600 assert(State.VF.isVector() && "Not vectorizing?");
1601 Type *DestTy = VectorType::get(getResultType(), State.VF);
1602 VPValue *Op = getOperand(0);
1603 Value *A = State.get(Op);
1604 Value *Cast = Builder.CreateCast(Instruction::CastOps(Opcode), A, DestTy);
1605 State.set(this, Cast);
1606 State.addMetadata(Cast, cast_or_null<Instruction>(getUnderlyingValue()));
1607 if (auto *CastOp = dyn_cast<Instruction>(Cast))
1608 setFlags(CastOp);
1609}
1610
1612 VPCostContext &Ctx) const {
1613 // TODO: In some cases, VPWidenCastRecipes are created but not considered in
1614 // the legacy cost model, including truncates/extends when evaluating a
1615 // reduction in a smaller type.
1616 if (!getUnderlyingValue())
1617 return 0;
1618 // Computes the CastContextHint from a recipes that may access memory.
1619 auto ComputeCCH = [&](const VPRecipeBase *R) -> TTI::CastContextHint {
1620 if (VF.isScalar())
1622 if (isa<VPInterleaveRecipe>(R))
1624 if (const auto *ReplicateRecipe = dyn_cast<VPReplicateRecipe>(R))
1625 return ReplicateRecipe->isPredicated() ? TTI::CastContextHint::Masked
1627 const auto *WidenMemoryRecipe = dyn_cast<VPWidenMemoryRecipe>(R);
1628 if (WidenMemoryRecipe == nullptr)
1630 if (!WidenMemoryRecipe->isConsecutive())
1632 if (WidenMemoryRecipe->isReverse())
1634 if (WidenMemoryRecipe->isMasked())
1637 };
1638
1639 VPValue *Operand = getOperand(0);
1641 // For Trunc/FPTrunc, get the context from the only user.
1642 if ((Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) &&
1644 if (auto *StoreRecipe = dyn_cast<VPRecipeBase>(*user_begin()))
1645 CCH = ComputeCCH(StoreRecipe);
1646 }
1647 // For Z/Sext, get the context from the operand.
1648 else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt ||
1649 Opcode == Instruction::FPExt) {
1650 if (Operand->isLiveIn())
1652 else if (Operand->getDefiningRecipe())
1653 CCH = ComputeCCH(Operand->getDefiningRecipe());
1654 }
1655
1656 auto *SrcTy =
1657 cast<VectorType>(toVectorTy(Ctx.Types.inferScalarType(Operand), VF));
1658 auto *DestTy = cast<VectorType>(toVectorTy(getResultType(), VF));
1659 // Arm TTI will use the underlying instruction to determine the cost.
1660 return Ctx.TTI.getCastInstrCost(
1661 Opcode, DestTy, SrcTy, CCH, Ctx.CostKind,
1662 dyn_cast_if_present<Instruction>(getUnderlyingValue()));
1663}
1664
1665#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1667 VPSlotTracker &SlotTracker) const {
1668 O << Indent << "WIDEN-CAST ";
1670 O << " = " << Instruction::getOpcodeName(Opcode);
1671 printFlags(O);
1673 O << " to " << *getResultType();
1674}
1675#endif
1676
1678 VPCostContext &Ctx) const {
1679 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
1680}
1681
1682/// This function adds
1683/// (0 * Step, 1 * Step, 2 * Step, ...)
1684/// to each vector element of Val.
1685/// \p Opcode is relevant for FP induction variable.
1686static Value *getStepVector(Value *Val, Value *Step,
1688 IRBuilderBase &Builder) {
1689 assert(VF.isVector() && "only vector VFs are supported");
1690
1691 // Create and check the types.
1692 auto *ValVTy = cast<VectorType>(Val->getType());
1693 ElementCount VLen = ValVTy->getElementCount();
1694
1695 Type *STy = Val->getType()->getScalarType();
1696 assert((STy->isIntegerTy() || STy->isFloatingPointTy()) &&
1697 "Induction Step must be an integer or FP");
1698 assert(Step->getType() == STy && "Step has wrong type");
1699
1701
1702 // Create a vector of consecutive numbers from zero to VF.
1703 VectorType *InitVecValVTy = ValVTy;
1704 if (STy->isFloatingPointTy()) {
1705 Type *InitVecValSTy =
1707 InitVecValVTy = VectorType::get(InitVecValSTy, VLen);
1708 }
1709 Value *InitVec = Builder.CreateStepVector(InitVecValVTy);
1710
1711 if (STy->isIntegerTy()) {
1712 Step = Builder.CreateVectorSplat(VLen, Step);
1713 assert(Step->getType() == Val->getType() && "Invalid step vec");
1714 // FIXME: The newly created binary instructions should contain nsw/nuw
1715 // flags, which can be found from the original scalar operations.
1716 Step = Builder.CreateMul(InitVec, Step);
1717 return Builder.CreateAdd(Val, Step, "induction");
1718 }
1719
1720 // Floating point induction.
1721 assert((BinOp == Instruction::FAdd || BinOp == Instruction::FSub) &&
1722 "Binary Opcode should be specified for FP induction");
1723 InitVec = Builder.CreateUIToFP(InitVec, ValVTy);
1724
1725 Step = Builder.CreateVectorSplat(VLen, Step);
1726 Value *MulOp = Builder.CreateFMul(InitVec, Step);
1727 return Builder.CreateBinOp(BinOp, Val, MulOp, "induction");
1728}
1729
1730/// A helper function that returns an integer or floating-point constant with
1731/// value C.
1733 return Ty->isIntegerTy() ? ConstantInt::getSigned(Ty, C)
1734 : ConstantFP::get(Ty, C);
1735}
1736
1738 assert(!State.Lane && "Int or FP induction being replicated.");
1739
1740 Value *Start = getStartValue()->getLiveInIRValue();
1742 TruncInst *Trunc = getTruncInst();
1743 IRBuilderBase &Builder = State.Builder;
1744 assert(getPHINode()->getType() == ID.getStartValue()->getType() &&
1745 "Types must match");
1746 assert(State.VF.isVector() && "must have vector VF");
1747
1748 // The value from the original loop to which we are mapping the new induction
1749 // variable.
1750 Instruction *EntryVal = Trunc ? cast<Instruction>(Trunc) : getPHINode();
1751
1752 // Fast-math-flags propagate from the original induction instruction.
1753 IRBuilder<>::FastMathFlagGuard FMFG(Builder);
1754 if (ID.getInductionBinOp() && isa<FPMathOperator>(ID.getInductionBinOp()))
1755 Builder.setFastMathFlags(ID.getInductionBinOp()->getFastMathFlags());
1756
1757 // Now do the actual transformations, and start with fetching the step value.
1758 Value *Step = State.get(getStepValue(), VPLane(0));
1759
1760 assert((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) &&
1761 "Expected either an induction phi-node or a truncate of it!");
1762
1763 // Construct the initial value of the vector IV in the vector loop preheader
1764 auto CurrIP = Builder.saveIP();
1765 BasicBlock *VectorPH = State.CFG.getPreheaderBBFor(this);
1766 Builder.SetInsertPoint(VectorPH->getTerminator());
1767 if (isa<TruncInst>(EntryVal)) {
1768 assert(Start->getType()->isIntegerTy() &&
1769 "Truncation requires an integer type");
1770 auto *TruncType = cast<IntegerType>(EntryVal->getType());
1771 Step = Builder.CreateTrunc(Step, TruncType);
1772 Start = Builder.CreateCast(Instruction::Trunc, Start, TruncType);
1773 }
1774
1775 Value *SplatStart = Builder.CreateVectorSplat(State.VF, Start);
1776 Value *SteppedStart = getStepVector(SplatStart, Step, ID.getInductionOpcode(),
1777 State.VF, State.Builder);
1778
1779 // We create vector phi nodes for both integer and floating-point induction
1780 // variables. Here, we determine the kind of arithmetic we will perform.
1783 if (Step->getType()->isIntegerTy()) {
1784 AddOp = Instruction::Add;
1785 MulOp = Instruction::Mul;
1786 } else {
1787 AddOp = ID.getInductionOpcode();
1788 MulOp = Instruction::FMul;
1789 }
1790
1791 Value *SplatVF;
1792 if (VPValue *SplatVFOperand = getSplatVFValue()) {
1793 // The recipe has been unrolled. In that case, fetch the splat value for the
1794 // induction increment.
1795 SplatVF = State.get(SplatVFOperand);
1796 } else {
1797 // Multiply the vectorization factor by the step using integer or
1798 // floating-point arithmetic as appropriate.
1799 Type *StepType = Step->getType();
1800 Value *RuntimeVF = State.get(getVFValue(), VPLane(0));
1801 if (Step->getType()->isFloatingPointTy())
1802 RuntimeVF = Builder.CreateUIToFP(RuntimeVF, StepType);
1803 else
1804 RuntimeVF = Builder.CreateZExtOrTrunc(RuntimeVF, StepType);
1805 Value *Mul = Builder.CreateBinOp(MulOp, Step, RuntimeVF);
1806
1807 // Create a vector splat to use in the induction update.
1808 SplatVF = Builder.CreateVectorSplat(State.VF, Mul);
1809 }
1810
1811 Builder.restoreIP(CurrIP);
1812
1813 // We may need to add the step a number of times, depending on the unroll
1814 // factor. The last of those goes into the PHI.
1815 PHINode *VecInd = PHINode::Create(SteppedStart->getType(), 2, "vec.ind");
1816 VecInd->insertBefore(State.CFG.PrevBB->getFirstInsertionPt());
1817 VecInd->setDebugLoc(getDebugLoc());
1818 State.set(this, VecInd);
1819
1820 Instruction *LastInduction = cast<Instruction>(
1821 Builder.CreateBinOp(AddOp, VecInd, SplatVF, "vec.ind.next"));
1822 if (isa<TruncInst>(EntryVal))
1823 State.addMetadata(LastInduction, EntryVal);
1824 LastInduction->setDebugLoc(getDebugLoc());
1825
1826 VecInd->addIncoming(SteppedStart, VectorPH);
1827 // Add induction update using an incorrect block temporarily. The phi node
1828 // will be fixed after VPlan execution. Note that at this point the latch
1829 // block cannot be used, as it does not exist yet.
1830 // TODO: Model increment value in VPlan, by turning the recipe into a
1831 // multi-def and a subclass of VPHeaderPHIRecipe.
1832 VecInd->addIncoming(LastInduction, VectorPH);
1833}
1834
1835#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1837 VPSlotTracker &SlotTracker) const {
1838 O << Indent;
1840 O << " = WIDEN-INDUCTION ";
1842
1843 if (auto *TI = getTruncInst())
1844 O << " (truncated to " << *TI->getType() << ")";
1845}
1846#endif
1847
1849 // The step may be defined by a recipe in the preheader (e.g. if it requires
1850 // SCEV expansion), but for the canonical induction the step is required to be
1851 // 1, which is represented as live-in.
1853 return false;
1854 auto *StepC = dyn_cast<ConstantInt>(getStepValue()->getLiveInIRValue());
1855 auto *StartC = dyn_cast<ConstantInt>(getStartValue()->getLiveInIRValue());
1856 auto *CanIV = cast<VPCanonicalIVPHIRecipe>(&*getParent()->begin());
1857 return StartC && StartC->isZero() && StepC && StepC->isOne() &&
1858 getScalarType() == CanIV->getScalarType();
1859}
1860
1861#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1863 VPSlotTracker &SlotTracker) const {
1864 O << Indent;
1866 O << " = DERIVED-IV ";
1868 O << " + ";
1870 O << " * ";
1872}
1873#endif
1874
1876 // Fast-math-flags propagate from the original induction instruction.
1878 if (hasFastMathFlags())
1880
1881 /// Compute scalar induction steps. \p ScalarIV is the scalar induction
1882 /// variable on which to base the steps, \p Step is the size of the step.
1883
1884 Value *BaseIV = State.get(getOperand(0), VPLane(0));
1885 Value *Step = State.get(getStepValue(), VPLane(0));
1886 IRBuilderBase &Builder = State.Builder;
1887
1888 // Ensure step has the same type as that of scalar IV.
1889 Type *BaseIVTy = BaseIV->getType()->getScalarType();
1890 assert(BaseIVTy == Step->getType() && "Types of BaseIV and Step must match!");
1891
1892 // We build scalar steps for both integer and floating-point induction
1893 // variables. Here, we determine the kind of arithmetic we will perform.
1896 if (BaseIVTy->isIntegerTy()) {
1897 AddOp = Instruction::Add;
1898 MulOp = Instruction::Mul;
1899 } else {
1900 AddOp = InductionOpcode;
1901 MulOp = Instruction::FMul;
1902 }
1903
1904 // Determine the number of scalars we need to generate for each unroll
1905 // iteration.
1906 bool FirstLaneOnly = vputils::onlyFirstLaneUsed(this);
1907 // Compute the scalar steps and save the results in State.
1908 Type *IntStepTy =
1909 IntegerType::get(BaseIVTy->getContext(), BaseIVTy->getScalarSizeInBits());
1910 Type *VecIVTy = nullptr;
1911 Value *UnitStepVec = nullptr, *SplatStep = nullptr, *SplatIV = nullptr;
1912 if (!FirstLaneOnly && State.VF.isScalable()) {
1913 VecIVTy = VectorType::get(BaseIVTy, State.VF);
1914 UnitStepVec =
1915 Builder.CreateStepVector(VectorType::get(IntStepTy, State.VF));
1916 SplatStep = Builder.CreateVectorSplat(State.VF, Step);
1917 SplatIV = Builder.CreateVectorSplat(State.VF, BaseIV);
1918 }
1919
1920 unsigned StartLane = 0;
1921 unsigned EndLane = FirstLaneOnly ? 1 : State.VF.getKnownMinValue();
1922 if (State.Lane) {
1923 StartLane = State.Lane->getKnownLane();
1924 EndLane = StartLane + 1;
1925 }
1926 Value *StartIdx0 =
1927 createStepForVF(Builder, IntStepTy, State.VF, getUnrollPart(*this));
1928
1929 if (!FirstLaneOnly && State.VF.isScalable()) {
1930 auto *SplatStartIdx = Builder.CreateVectorSplat(State.VF, StartIdx0);
1931 auto *InitVec = Builder.CreateAdd(SplatStartIdx, UnitStepVec);
1932 if (BaseIVTy->isFloatingPointTy())
1933 InitVec = Builder.CreateSIToFP(InitVec, VecIVTy);
1934 auto *Mul = Builder.CreateBinOp(MulOp, InitVec, SplatStep);
1935 auto *Add = Builder.CreateBinOp(AddOp, SplatIV, Mul);
1936 State.set(this, Add);
1937 // It's useful to record the lane values too for the known minimum number
1938 // of elements so we do those below. This improves the code quality when
1939 // trying to extract the first element, for example.
1940 }
1941
1942 if (BaseIVTy->isFloatingPointTy())
1943 StartIdx0 = Builder.CreateSIToFP(StartIdx0, BaseIVTy);
1944
1945 for (unsigned Lane = StartLane; Lane < EndLane; ++Lane) {
1946 Value *StartIdx = Builder.CreateBinOp(
1947 AddOp, StartIdx0, getSignedIntOrFpConstant(BaseIVTy, Lane));
1948 // The step returned by `createStepForVF` is a runtime-evaluated value
1949 // when VF is scalable. Otherwise, it should be folded into a Constant.
1950 assert((State.VF.isScalable() || isa<Constant>(StartIdx)) &&
1951 "Expected StartIdx to be folded to a constant when VF is not "
1952 "scalable");
1953 auto *Mul = Builder.CreateBinOp(MulOp, StartIdx, Step);
1954 auto *Add = Builder.CreateBinOp(AddOp, BaseIV, Mul);
1955 State.set(this, Add, VPLane(Lane));
1956 }
1957}
1958
1959#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1961 VPSlotTracker &SlotTracker) const {
1962 O << Indent;
1964 O << " = SCALAR-STEPS ";
1966}
1967#endif
1968
1970 assert(State.VF.isVector() && "not widening");
1971 auto *GEP = cast<GetElementPtrInst>(getUnderlyingInstr());
1972 // Construct a vector GEP by widening the operands of the scalar GEP as
1973 // necessary. We mark the vector GEP 'inbounds' if appropriate. A GEP
1974 // results in a vector of pointers when at least one operand of the GEP
1975 // is vector-typed. Thus, to keep the representation compact, we only use
1976 // vector-typed operands for loop-varying values.
1977
1978 if (areAllOperandsInvariant()) {
1979 // If we are vectorizing, but the GEP has only loop-invariant operands,
1980 // the GEP we build (by only using vector-typed operands for
1981 // loop-varying values) would be a scalar pointer. Thus, to ensure we
1982 // produce a vector of pointers, we need to either arbitrarily pick an
1983 // operand to broadcast, or broadcast a clone of the original GEP.
1984 // Here, we broadcast a clone of the original.
1985 //
1986 // TODO: If at some point we decide to scalarize instructions having
1987 // loop-invariant operands, this special case will no longer be
1988 // required. We would add the scalarization decision to
1989 // collectLoopScalars() and teach getVectorValue() to broadcast
1990 // the lane-zero scalar value.
1992 for (unsigned I = 0, E = getNumOperands(); I != E; I++)
1993 Ops.push_back(State.get(getOperand(I), VPLane(0)));
1994
1995 auto *NewGEP = State.Builder.CreateGEP(GEP->getSourceElementType(), Ops[0],
1996 ArrayRef(Ops).drop_front(), "",
1998 Value *Splat = State.Builder.CreateVectorSplat(State.VF, NewGEP);
1999 State.set(this, Splat);
2000 State.addMetadata(Splat, GEP);
2001 } else {
2002 // If the GEP has at least one loop-varying operand, we are sure to
2003 // produce a vector of pointers unless VF is scalar.
2004 // The pointer operand of the new GEP. If it's loop-invariant, we
2005 // won't broadcast it.
2006 auto *Ptr = isPointerLoopInvariant() ? State.get(getOperand(0), VPLane(0))
2007 : State.get(getOperand(0));
2008
2009 // Collect all the indices for the new GEP. If any index is
2010 // loop-invariant, we won't broadcast it.
2012 for (unsigned I = 1, E = getNumOperands(); I < E; I++) {
2013 VPValue *Operand = getOperand(I);
2014 if (isIndexLoopInvariant(I - 1))
2015 Indices.push_back(State.get(Operand, VPLane(0)));
2016 else
2017 Indices.push_back(State.get(Operand));
2018 }
2019
2020 // Create the new GEP. Note that this GEP may be a scalar if VF == 1,
2021 // but it should be a vector, otherwise.
2022 auto *NewGEP = State.Builder.CreateGEP(GEP->getSourceElementType(), Ptr,
2023 Indices, "", getGEPNoWrapFlags());
2024 assert((State.VF.isScalar() || NewGEP->getType()->isVectorTy()) &&
2025 "NewGEP is not a pointer vector");
2026 State.set(this, NewGEP);
2027 State.addMetadata(NewGEP, GEP);
2028 }
2029}
2030
2031#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2033 VPSlotTracker &SlotTracker) const {
2034 O << Indent << "WIDEN-GEP ";
2035 O << (isPointerLoopInvariant() ? "Inv" : "Var");
2036 for (size_t I = 0; I < getNumOperands() - 1; ++I)
2037 O << "[" << (isIndexLoopInvariant(I) ? "Inv" : "Var") << "]";
2038
2039 O << " ";
2041 O << " = getelementptr";
2042 printFlags(O);
2044}
2045#endif
2046
2047static Type *getGEPIndexTy(bool IsScalable, bool IsReverse,
2048 unsigned CurrentPart, IRBuilderBase &Builder) {
2049 // Use i32 for the gep index type when the value is constant,
2050 // or query DataLayout for a more suitable index type otherwise.
2051 const DataLayout &DL = Builder.GetInsertBlock()->getDataLayout();
2052 return IsScalable && (IsReverse || CurrentPart > 0)
2053 ? DL.getIndexType(Builder.getPtrTy(0))
2054 : Builder.getInt32Ty();
2055}
2056
2058 auto &Builder = State.Builder;
2060 unsigned CurrentPart = getUnrollPart(*this);
2061 Type *IndexTy = getGEPIndexTy(State.VF.isScalable(), /*IsReverse*/ true,
2062 CurrentPart, Builder);
2063
2064 // The wide store needs to start at the last vector element.
2065 Value *RunTimeVF = State.get(getVFValue(), VPLane(0));
2066 if (IndexTy != RunTimeVF->getType())
2067 RunTimeVF = Builder.CreateZExtOrTrunc(RunTimeVF, IndexTy);
2068 // NumElt = -CurrentPart * RunTimeVF
2069 Value *NumElt = Builder.CreateMul(
2070 ConstantInt::get(IndexTy, -(int64_t)CurrentPart), RunTimeVF);
2071 // LastLane = 1 - RunTimeVF
2072 Value *LastLane = Builder.CreateSub(ConstantInt::get(IndexTy, 1), RunTimeVF);
2073 Value *Ptr = State.get(getOperand(0), VPLane(0));
2074 Value *ResultPtr =
2075 Builder.CreateGEP(IndexedTy, Ptr, NumElt, "", getGEPNoWrapFlags());
2076 ResultPtr = Builder.CreateGEP(IndexedTy, ResultPtr, LastLane, "",
2078
2079 State.set(this, ResultPtr, /*IsScalar*/ true);
2080}
2081
2082#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2084 VPSlotTracker &SlotTracker) const {
2085 O << Indent;
2087 O << " = reverse-vector-pointer";
2088 printFlags(O);
2090}
2091#endif
2092
2094 auto &Builder = State.Builder;
2096 unsigned CurrentPart = getUnrollPart(*this);
2097 Type *IndexTy = getGEPIndexTy(State.VF.isScalable(), /*IsReverse*/ false,
2098 CurrentPart, Builder);
2099 Value *Ptr = State.get(getOperand(0), VPLane(0));
2100
2101 Value *Increment = createStepForVF(Builder, IndexTy, State.VF, CurrentPart);
2102 Value *ResultPtr =
2103 Builder.CreateGEP(IndexedTy, Ptr, Increment, "", getGEPNoWrapFlags());
2104
2105 State.set(this, ResultPtr, /*IsScalar*/ true);
2106}
2107
2108#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2110 VPSlotTracker &SlotTracker) const {
2111 O << Indent;
2113 O << " = vector-pointer ";
2114
2116}
2117#endif
2118
2120 assert(isNormalized() && "Expected blend to be normalized!");
2122 // We know that all PHIs in non-header blocks are converted into
2123 // selects, so we don't have to worry about the insertion order and we
2124 // can just use the builder.
2125 // At this point we generate the predication tree. There may be
2126 // duplications since this is a simple recursive scan, but future
2127 // optimizations will clean it up.
2128
2129 unsigned NumIncoming = getNumIncomingValues();
2130
2131 // Generate a sequence of selects of the form:
2132 // SELECT(Mask3, In3,
2133 // SELECT(Mask2, In2,
2134 // SELECT(Mask1, In1,
2135 // In0)))
2136 // Note that Mask0 is never used: lanes for which no path reaches this phi and
2137 // are essentially undef are taken from In0.
2138 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
2139 Value *Result = nullptr;
2140 for (unsigned In = 0; In < NumIncoming; ++In) {
2141 // We might have single edge PHIs (blocks) - use an identity
2142 // 'select' for the first PHI operand.
2143 Value *In0 = State.get(getIncomingValue(In), OnlyFirstLaneUsed);
2144 if (In == 0)
2145 Result = In0; // Initialize with the first incoming value.
2146 else {
2147 // Select between the current value and the previous incoming edge
2148 // based on the incoming mask.
2149 Value *Cond = State.get(getMask(In), OnlyFirstLaneUsed);
2150 Result = State.Builder.CreateSelect(Cond, In0, Result, "predphi");
2151 }
2152 }
2153 State.set(this, Result, OnlyFirstLaneUsed);
2154}
2155
2157 VPCostContext &Ctx) const {
2158 // Handle cases where only the first lane is used the same way as the legacy
2159 // cost model.
2161 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
2162
2163 Type *ResultTy = toVectorTy(Ctx.Types.inferScalarType(this), VF);
2164 Type *CmpTy = toVectorTy(Type::getInt1Ty(Ctx.Types.getContext()), VF);
2165 return (getNumIncomingValues() - 1) *
2166 Ctx.TTI.getCmpSelInstrCost(Instruction::Select, ResultTy, CmpTy,
2168}
2169
2170#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2172 VPSlotTracker &SlotTracker) const {
2173 O << Indent << "BLEND ";
2175 O << " =";
2176 if (getNumIncomingValues() == 1) {
2177 // Not a User of any mask: not really blending, this is a
2178 // single-predecessor phi.
2179 O << " ";
2181 } else {
2182 for (unsigned I = 0, E = getNumIncomingValues(); I < E; ++I) {
2183 O << " ";
2185 if (I == 0)
2186 continue;
2187 O << "/";
2189 }
2190 }
2191}
2192#endif
2193
2195 assert(!State.Lane && "Reduction being replicated.");
2196 Value *PrevInChain = State.get(getChainOp(), /*IsScalar*/ true);
2197 RecurKind Kind = RdxDesc.getRecurrenceKind();
2198 // Propagate the fast-math flags carried by the underlying instruction.
2200 State.Builder.setFastMathFlags(RdxDesc.getFastMathFlags());
2202 Value *NewVecOp = State.get(getVecOp());
2203 if (VPValue *Cond = getCondOp()) {
2204 Value *NewCond = State.get(Cond, State.VF.isScalar());
2205 VectorType *VecTy = dyn_cast<VectorType>(NewVecOp->getType());
2206 Type *ElementTy = VecTy ? VecTy->getElementType() : NewVecOp->getType();
2207
2208 Value *Start;
2210 Start = RdxDesc.getRecurrenceStartValue();
2211 else
2212 Start = llvm::getRecurrenceIdentity(Kind, ElementTy,
2213 RdxDesc.getFastMathFlags());
2214 if (State.VF.isVector())
2215 Start = State.Builder.CreateVectorSplat(VecTy->getElementCount(), Start);
2216
2217 Value *Select = State.Builder.CreateSelect(NewCond, NewVecOp, Start);
2218 NewVecOp = Select;
2219 }
2220 Value *NewRed;
2221 Value *NextInChain;
2222 if (IsOrdered) {
2223 if (State.VF.isVector())
2224 NewRed =
2225 createOrderedReduction(State.Builder, RdxDesc, NewVecOp, PrevInChain);
2226 else
2227 NewRed = State.Builder.CreateBinOp(
2228 (Instruction::BinaryOps)RdxDesc.getOpcode(), PrevInChain, NewVecOp);
2229 PrevInChain = NewRed;
2230 NextInChain = NewRed;
2231 } else {
2232 PrevInChain = State.get(getChainOp(), /*IsScalar*/ true);
2233 NewRed = createReduction(State.Builder, RdxDesc, NewVecOp);
2235 NextInChain = createMinMaxOp(State.Builder, RdxDesc.getRecurrenceKind(),
2236 NewRed, PrevInChain);
2237 else
2238 NextInChain = State.Builder.CreateBinOp(
2239 (Instruction::BinaryOps)RdxDesc.getOpcode(), NewRed, PrevInChain);
2240 }
2241 State.set(this, NextInChain, /*IsScalar*/ true);
2242}
2243
2245 assert(!State.Lane && "Reduction being replicated.");
2246
2247 auto &Builder = State.Builder;
2248 // Propagate the fast-math flags carried by the underlying instruction.
2249 IRBuilderBase::FastMathFlagGuard FMFGuard(Builder);
2251 Builder.setFastMathFlags(RdxDesc.getFastMathFlags());
2252
2253 RecurKind Kind = RdxDesc.getRecurrenceKind();
2254 Value *Prev = State.get(getChainOp(), /*IsScalar*/ true);
2255 Value *VecOp = State.get(getVecOp());
2256 Value *EVL = State.get(getEVL(), VPLane(0));
2257
2258 VectorBuilder VBuilder(Builder);
2259 VBuilder.setEVL(EVL);
2260 Value *Mask;
2261 // TODO: move the all-true mask generation into VectorBuilder.
2262 if (VPValue *CondOp = getCondOp())
2263 Mask = State.get(CondOp);
2264 else
2265 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
2266 VBuilder.setMask(Mask);
2267
2268 Value *NewRed;
2269 if (isOrdered()) {
2270 NewRed = createOrderedReduction(VBuilder, RdxDesc, VecOp, Prev);
2271 } else {
2272 NewRed = createSimpleReduction(VBuilder, VecOp, RdxDesc);
2274 NewRed = createMinMaxOp(Builder, Kind, NewRed, Prev);
2275 else
2276 NewRed = Builder.CreateBinOp((Instruction::BinaryOps)RdxDesc.getOpcode(),
2277 NewRed, Prev);
2278 }
2279 State.set(this, NewRed, /*IsScalar*/ true);
2280}
2281
2283 VPCostContext &Ctx) const {
2284 RecurKind RdxKind = RdxDesc.getRecurrenceKind();
2285 Type *ElementTy = Ctx.Types.inferScalarType(this);
2286 auto *VectorTy = cast<VectorType>(toVectorTy(ElementTy, VF));
2287 unsigned Opcode = RdxDesc.getOpcode();
2288
2289 // TODO: Support any-of and in-loop reductions.
2290 assert(
2292 ForceTargetInstructionCost.getNumOccurrences() > 0) &&
2293 "Any-of reduction not implemented in VPlan-based cost model currently.");
2294 assert(
2295 (!cast<VPReductionPHIRecipe>(getOperand(0))->isInLoop() ||
2296 ForceTargetInstructionCost.getNumOccurrences() > 0) &&
2297 "In-loop reduction not implemented in VPlan-based cost model currently.");
2298
2299 assert(ElementTy->getTypeID() == RdxDesc.getRecurrenceType()->getTypeID() &&
2300 "Inferred type and recurrence type mismatch.");
2301
2302 // Cost = Reduction cost + BinOp cost
2304 Ctx.TTI.getArithmeticInstrCost(Opcode, ElementTy, Ctx.CostKind);
2307 return Cost + Ctx.TTI.getMinMaxReductionCost(
2308 Id, VectorTy, RdxDesc.getFastMathFlags(), Ctx.CostKind);
2309 }
2310
2311 return Cost + Ctx.TTI.getArithmeticReductionCost(
2312 Opcode, VectorTy, RdxDesc.getFastMathFlags(), Ctx.CostKind);
2313}
2314
2315#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2317 VPSlotTracker &SlotTracker) const {
2318 O << Indent << "REDUCE ";
2320 O << " = ";
2322 O << " +";
2323 if (isa<FPMathOperator>(getUnderlyingInstr()))
2325 O << " reduce." << Instruction::getOpcodeName(RdxDesc.getOpcode()) << " (";
2327 if (isConditional()) {
2328 O << ", ";
2330 }
2331 O << ")";
2332 if (RdxDesc.IntermediateStore)
2333 O << " (with final reduction value stored in invariant address sank "
2334 "outside of loop)";
2335}
2336
2338 VPSlotTracker &SlotTracker) const {
2340 O << Indent << "REDUCE ";
2342 O << " = ";
2344 O << " +";
2345 if (isa<FPMathOperator>(getUnderlyingInstr()))
2347 O << " vp.reduce." << Instruction::getOpcodeName(RdxDesc.getOpcode()) << " (";
2349 O << ", ";
2351 if (isConditional()) {
2352 O << ", ";
2354 }
2355 O << ")";
2356 if (RdxDesc.IntermediateStore)
2357 O << " (with final reduction value stored in invariant address sank "
2358 "outside of loop)";
2359}
2360#endif
2361
2363 // Find if the recipe is used by a widened recipe via an intervening
2364 // VPPredInstPHIRecipe. In this case, also pack the scalar values in a vector.
2365 return any_of(users(), [](const VPUser *U) {
2366 if (auto *PredR = dyn_cast<VPPredInstPHIRecipe>(U))
2367 return any_of(PredR->users(), [PredR](const VPUser *U) {
2368 return !U->usesScalars(PredR);
2369 });
2370 return false;
2371 });
2372}
2373
2375 VPCostContext &Ctx) const {
2376 Instruction *UI = cast<Instruction>(getUnderlyingValue());
2377 // VPReplicateRecipe may be cloned as part of an existing VPlan-to-VPlan
2378 // transform, avoid computing their cost multiple times for now.
2379 Ctx.SkipCostComputation.insert(UI);
2380 return Ctx.getLegacyCost(UI, VF);
2381}
2382
2383#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2385 VPSlotTracker &SlotTracker) const {
2386 O << Indent << (IsUniform ? "CLONE " : "REPLICATE ");
2387
2388 if (!getUnderlyingInstr()->getType()->isVoidTy()) {
2390 O << " = ";
2391 }
2392 if (auto *CB = dyn_cast<CallBase>(getUnderlyingInstr())) {
2393 O << "call";
2394 printFlags(O);
2395 O << "@" << CB->getCalledFunction()->getName() << "(";
2397 O, [&O, &SlotTracker](VPValue *Op) {
2398 Op->printAsOperand(O, SlotTracker);
2399 });
2400 O << ")";
2401 } else {
2403 printFlags(O);
2405 }
2406
2407 if (shouldPack())
2408 O << " (S->V)";
2409}
2410#endif
2411
2412Value *VPScalarCastRecipe ::generate(VPTransformState &State) {
2415 "Codegen only implemented for first lane.");
2416 switch (Opcode) {
2417 case Instruction::SExt:
2418 case Instruction::ZExt:
2419 case Instruction::Trunc: {
2420 // Note: SExt/ZExt not used yet.
2421 Value *Op = State.get(getOperand(0), VPLane(0));
2422 return State.Builder.CreateCast(Instruction::CastOps(Opcode), Op, ResultTy);
2423 }
2424 default:
2425 llvm_unreachable("opcode not implemented yet");
2426 }
2427}
2428
2429void VPScalarCastRecipe ::execute(VPTransformState &State) {
2430 State.set(this, generate(State), VPLane(0));
2431}
2432
2433#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2434void VPScalarCastRecipe ::print(raw_ostream &O, const Twine &Indent,
2435 VPSlotTracker &SlotTracker) const {
2436 O << Indent << "SCALAR-CAST ";
2437 printAsOperand(O, SlotTracker);
2438 O << " = " << Instruction::getOpcodeName(Opcode) << " ";
2439 printOperands(O, SlotTracker);
2440 O << " to " << *ResultTy;
2441}
2442#endif
2443
2445 assert(State.Lane && "Branch on Mask works only on single instance.");
2446
2447 unsigned Lane = State.Lane->getKnownLane();
2448
2449 Value *ConditionBit = nullptr;
2450 VPValue *BlockInMask = getMask();
2451 if (BlockInMask) {
2452 ConditionBit = State.get(BlockInMask);
2453 if (ConditionBit->getType()->isVectorTy())
2454 ConditionBit = State.Builder.CreateExtractElement(
2455 ConditionBit, State.Builder.getInt32(Lane));
2456 } else // Block in mask is all-one.
2457 ConditionBit = State.Builder.getTrue();
2458
2459 // Replace the temporary unreachable terminator with a new conditional branch,
2460 // whose two destinations will be set later when they are created.
2461 auto *CurrentTerminator = State.CFG.PrevBB->getTerminator();
2462 assert(isa<UnreachableInst>(CurrentTerminator) &&
2463 "Expected to replace unreachable terminator with conditional branch.");
2464 auto *CondBr = BranchInst::Create(State.CFG.PrevBB, nullptr, ConditionBit);
2465 CondBr->setSuccessor(0, nullptr);
2466 ReplaceInstWithInst(CurrentTerminator, CondBr);
2467}
2468
2470 VPCostContext &Ctx) const {
2471 // The legacy cost model doesn't assign costs to branches for individual
2472 // replicate regions. Match the current behavior in the VPlan cost model for
2473 // now.
2474 return 0;
2475}
2476
2479 assert(State.Lane && "Predicated instruction PHI works per instance.");
2480 Instruction *ScalarPredInst =
2481 cast<Instruction>(State.get(getOperand(0), *State.Lane));
2482 BasicBlock *PredicatedBB = ScalarPredInst->getParent();
2483 BasicBlock *PredicatingBB = PredicatedBB->getSinglePredecessor();
2484 assert(PredicatingBB && "Predicated block has no single predecessor.");
2485 assert(isa<VPReplicateRecipe>(getOperand(0)) &&
2486 "operand must be VPReplicateRecipe");
2487
2488 // By current pack/unpack logic we need to generate only a single phi node: if
2489 // a vector value for the predicated instruction exists at this point it means
2490 // the instruction has vector users only, and a phi for the vector value is
2491 // needed. In this case the recipe of the predicated instruction is marked to
2492 // also do that packing, thereby "hoisting" the insert-element sequence.
2493 // Otherwise, a phi node for the scalar value is needed.
2494 if (State.hasVectorValue(getOperand(0))) {
2495 Value *VectorValue = State.get(getOperand(0));
2496 InsertElementInst *IEI = cast<InsertElementInst>(VectorValue);
2497 PHINode *VPhi = State.Builder.CreatePHI(IEI->getType(), 2);
2498 VPhi->addIncoming(IEI->getOperand(0), PredicatingBB); // Unmodified vector.
2499 VPhi->addIncoming(IEI, PredicatedBB); // New vector with inserted element.
2500 if (State.hasVectorValue(this))
2501 State.reset(this, VPhi);
2502 else
2503 State.set(this, VPhi);
2504 // NOTE: Currently we need to update the value of the operand, so the next
2505 // predicated iteration inserts its generated value in the correct vector.
2506 State.reset(getOperand(0), VPhi);
2507 } else {
2508 if (vputils::onlyFirstLaneUsed(this) && !State.Lane->isFirstLane())
2509 return;
2510
2511 Type *PredInstType = getOperand(0)->getUnderlyingValue()->getType();
2512 PHINode *Phi = State.Builder.CreatePHI(PredInstType, 2);
2513 Phi->addIncoming(PoisonValue::get(ScalarPredInst->getType()),
2514 PredicatingBB);
2515 Phi->addIncoming(ScalarPredInst, PredicatedBB);
2516 if (State.hasScalarValue(this, *State.Lane))
2517 State.reset(this, Phi, *State.Lane);
2518 else
2519 State.set(this, Phi, *State.Lane);
2520 // NOTE: Currently we need to update the value of the operand, so the next
2521 // predicated iteration inserts its generated value in the correct vector.
2522 State.reset(getOperand(0), Phi, *State.Lane);
2523 }
2524}
2525
2526#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2528 VPSlotTracker &SlotTracker) const {
2529 O << Indent << "PHI-PREDICATED-INSTRUCTION ";
2531 O << " = ";
2533}
2534#endif
2535
2537 VPCostContext &Ctx) const {
2539 const Align Alignment =
2541 unsigned AS =
2543
2544 if (!Consecutive) {
2545 // TODO: Using the original IR may not be accurate.
2546 // Currently, ARM will use the underlying IR to calculate gather/scatter
2547 // instruction cost.
2549 assert(!Reverse &&
2550 "Inconsecutive memory access should not have the order.");
2551 return Ctx.TTI.getAddressComputationCost(Ty) +
2553 IsMasked, Alignment, Ctx.CostKind,
2554 &Ingredient);
2555 }
2556
2558 if (IsMasked) {
2559 Cost += Ctx.TTI.getMaskedMemoryOpCost(Ingredient.getOpcode(), Ty, Alignment,
2560 AS, Ctx.CostKind);
2561 } else {
2562 TTI::OperandValueInfo OpInfo =
2564 Cost += Ctx.TTI.getMemoryOpCost(Ingredient.getOpcode(), Ty, Alignment, AS,
2565 Ctx.CostKind, OpInfo, &Ingredient);
2566 }
2567 if (!Reverse)
2568 return Cost;
2569
2570 return Cost +=
2572 cast<VectorType>(Ty), {}, Ctx.CostKind, 0);
2573}
2574
2576 auto *LI = cast<LoadInst>(&Ingredient);
2577
2578 Type *ScalarDataTy = getLoadStoreType(&Ingredient);
2579 auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
2580 const Align Alignment = getLoadStoreAlignment(&Ingredient);
2581 bool CreateGather = !isConsecutive();
2582
2583 auto &Builder = State.Builder;
2585 Value *Mask = nullptr;
2586 if (auto *VPMask = getMask()) {
2587 // Mask reversal is only needed for non-all-one (null) masks, as reverse
2588 // of a null all-one mask is a null mask.
2589 Mask = State.get(VPMask);
2590 if (isReverse())
2591 Mask = Builder.CreateVectorReverse(Mask, "reverse");
2592 }
2593
2594 Value *Addr = State.get(getAddr(), /*IsScalar*/ !CreateGather);
2595 Value *NewLI;
2596 if (CreateGather) {
2597 NewLI = Builder.CreateMaskedGather(DataTy, Addr, Alignment, Mask, nullptr,
2598 "wide.masked.gather");
2599 } else if (Mask) {
2600 NewLI =
2601 Builder.CreateMaskedLoad(DataTy, Addr, Alignment, Mask,
2602 PoisonValue::get(DataTy), "wide.masked.load");
2603 } else {
2604 NewLI = Builder.CreateAlignedLoad(DataTy, Addr, Alignment, "wide.load");
2605 }
2606 // Add metadata to the load, but setVectorValue to the reverse shuffle.
2607 State.addMetadata(NewLI, LI);
2608 if (Reverse)
2609 NewLI = Builder.CreateVectorReverse(NewLI, "reverse");
2610 State.set(this, NewLI);
2611}
2612
2613#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2615 VPSlotTracker &SlotTracker) const {
2616 O << Indent << "WIDEN ";
2618 O << " = load ";
2620}
2621#endif
2622
2623/// Use all-true mask for reverse rather than actual mask, as it avoids a
2624/// dependence w/o affecting the result.
2626 Value *EVL, const Twine &Name) {
2627 VectorType *ValTy = cast<VectorType>(Operand->getType());
2628 Value *AllTrueMask =
2629 Builder.CreateVectorSplat(ValTy->getElementCount(), Builder.getTrue());
2630 return Builder.CreateIntrinsic(ValTy, Intrinsic::experimental_vp_reverse,
2631 {Operand, AllTrueMask, EVL}, nullptr, Name);
2632}
2633
2635 auto *LI = cast<LoadInst>(&Ingredient);
2636
2637 Type *ScalarDataTy = getLoadStoreType(&Ingredient);
2638 auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
2639 const Align Alignment = getLoadStoreAlignment(&Ingredient);
2640 bool CreateGather = !isConsecutive();
2641
2642 auto &Builder = State.Builder;
2644 CallInst *NewLI;
2645 Value *EVL = State.get(getEVL(), VPLane(0));
2646 Value *Addr = State.get(getAddr(), !CreateGather);
2647 Value *Mask = nullptr;
2648 if (VPValue *VPMask = getMask()) {
2649 Mask = State.get(VPMask);
2650 if (isReverse())
2651 Mask = createReverseEVL(Builder, Mask, EVL, "vp.reverse.mask");
2652 } else {
2653 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
2654 }
2655
2656 if (CreateGather) {
2657 NewLI =
2658 Builder.CreateIntrinsic(DataTy, Intrinsic::vp_gather, {Addr, Mask, EVL},
2659 nullptr, "wide.masked.gather");
2660 } else {
2661 VectorBuilder VBuilder(Builder);
2662 VBuilder.setEVL(EVL).setMask(Mask);
2663 NewLI = cast<CallInst>(VBuilder.createVectorInstruction(
2664 Instruction::Load, DataTy, Addr, "vp.op.load"));
2665 }
2666 NewLI->addParamAttr(
2667 0, Attribute::getWithAlignment(NewLI->getContext(), Alignment));
2668 State.addMetadata(NewLI, LI);
2669 Instruction *Res = NewLI;
2670 if (isReverse())
2671 Res = createReverseEVL(Builder, Res, EVL, "vp.reverse");
2672 State.set(this, Res);
2673}
2674
2676 VPCostContext &Ctx) const {
2677 if (!Consecutive || IsMasked)
2678 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
2679
2680 // We need to use the getMaskedMemoryOpCost() instead of getMemoryOpCost()
2681 // here because the EVL recipes using EVL to replace the tail mask. But in the
2682 // legacy model, it will always calculate the cost of mask.
2683 // TODO: Using getMemoryOpCost() instead of getMaskedMemoryOpCost when we
2684 // don't need to compare to the legacy cost model.
2686 const Align Alignment =
2688 unsigned AS =
2691 Ingredient.getOpcode(), Ty, Alignment, AS, Ctx.CostKind);
2692 if (!Reverse)
2693 return Cost;
2694
2696 cast<VectorType>(Ty), {}, Ctx.CostKind,
2697 0);
2698}
2699
2700#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2702 VPSlotTracker &SlotTracker) const {
2703 O << Indent << "WIDEN ";
2705 O << " = vp.load ";
2707}
2708#endif
2709
2711 auto *SI = cast<StoreInst>(&Ingredient);
2712
2713 VPValue *StoredVPValue = getStoredValue();
2714 bool CreateScatter = !isConsecutive();
2715 const Align Alignment = getLoadStoreAlignment(&Ingredient);
2716
2717 auto &Builder = State.Builder;
2719
2720 Value *Mask = nullptr;
2721 if (auto *VPMask = getMask()) {
2722 // Mask reversal is only needed for non-all-one (null) masks, as reverse
2723 // of a null all-one mask is a null mask.
2724 Mask = State.get(VPMask);
2725 if (isReverse())
2726 Mask = Builder.CreateVectorReverse(Mask, "reverse");
2727 }
2728
2729 Value *StoredVal = State.get(StoredVPValue);
2730 if (isReverse()) {
2731 // If we store to reverse consecutive memory locations, then we need
2732 // to reverse the order of elements in the stored value.
2733 StoredVal = Builder.CreateVectorReverse(StoredVal, "reverse");
2734 // We don't want to update the value in the map as it might be used in
2735 // another expression. So don't call resetVectorValue(StoredVal).
2736 }
2737 Value *Addr = State.get(getAddr(), /*IsScalar*/ !CreateScatter);
2738 Instruction *NewSI = nullptr;
2739 if (CreateScatter)
2740 NewSI = Builder.CreateMaskedScatter(StoredVal, Addr, Alignment, Mask);
2741 else if (Mask)
2742 NewSI = Builder.CreateMaskedStore(StoredVal, Addr, Alignment, Mask);
2743 else
2744 NewSI = Builder.CreateAlignedStore(StoredVal, Addr, Alignment);
2745 State.addMetadata(NewSI, SI);
2746}
2747
2748#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2750 VPSlotTracker &SlotTracker) const {
2751 O << Indent << "WIDEN store ";
2753}
2754#endif
2755
2757 auto *SI = cast<StoreInst>(&Ingredient);
2758
2759 VPValue *StoredValue = getStoredValue();
2760 bool CreateScatter = !isConsecutive();
2761 const Align Alignment = getLoadStoreAlignment(&Ingredient);
2762
2763 auto &Builder = State.Builder;
2765
2766 CallInst *NewSI = nullptr;
2767 Value *StoredVal = State.get(StoredValue);
2768 Value *EVL = State.get(getEVL(), VPLane(0));
2769 if (isReverse())
2770 StoredVal = createReverseEVL(Builder, StoredVal, EVL, "vp.reverse");
2771 Value *Mask = nullptr;
2772 if (VPValue *VPMask = getMask()) {
2773 Mask = State.get(VPMask);
2774 if (isReverse())
2775 Mask = createReverseEVL(Builder, Mask, EVL, "vp.reverse.mask");
2776 } else {
2777 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
2778 }
2779 Value *Addr = State.get(getAddr(), !CreateScatter);
2780 if (CreateScatter) {
2781 NewSI = Builder.CreateIntrinsic(Type::getVoidTy(EVL->getContext()),
2782 Intrinsic::vp_scatter,
2783 {StoredVal, Addr, Mask, EVL});
2784 } else {
2785 VectorBuilder VBuilder(Builder);
2786 VBuilder.setEVL(EVL).setMask(Mask);
2787 NewSI = cast<CallInst>(VBuilder.createVectorInstruction(
2788 Instruction::Store, Type::getVoidTy(EVL->getContext()),
2789 {StoredVal, Addr}));
2790 }
2791 NewSI->addParamAttr(
2792 1, Attribute::getWithAlignment(NewSI->getContext(), Alignment));
2793 State.addMetadata(NewSI, SI);
2794}
2795
2797 VPCostContext &Ctx) const {
2798 if (!Consecutive || IsMasked)
2799 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
2800
2801 // We need to use the getMaskedMemoryOpCost() instead of getMemoryOpCost()
2802 // here because the EVL recipes using EVL to replace the tail mask. But in the
2803 // legacy model, it will always calculate the cost of mask.
2804 // TODO: Using getMemoryOpCost() instead of getMaskedMemoryOpCost when we
2805 // don't need to compare to the legacy cost model.
2807 const Align Alignment =
2809 unsigned AS =
2812 Ingredient.getOpcode(), Ty, Alignment, AS, Ctx.CostKind);
2813 if (!Reverse)
2814 return Cost;
2815
2817 cast<VectorType>(Ty), {}, Ctx.CostKind,
2818 0);
2819}
2820
2821#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2823 VPSlotTracker &SlotTracker) const {
2824 O << Indent << "WIDEN vp.store ";
2826}
2827#endif
2828
2830 VectorType *DstVTy, const DataLayout &DL) {
2831 // Verify that V is a vector type with same number of elements as DstVTy.
2832 auto VF = DstVTy->getElementCount();
2833 auto *SrcVecTy = cast<VectorType>(V->getType());
2834 assert(VF == SrcVecTy->getElementCount() && "Vector dimensions do not match");
2835 Type *SrcElemTy = SrcVecTy->getElementType();
2836 Type *DstElemTy = DstVTy->getElementType();
2837 assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&
2838 "Vector elements must have same size");
2839
2840 // Do a direct cast if element types are castable.
2841 if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
2842 return Builder.CreateBitOrPointerCast(V, DstVTy);
2843 }
2844 // V cannot be directly casted to desired vector type.
2845 // May happen when V is a floating point vector but DstVTy is a vector of
2846 // pointers or vice-versa. Handle this using a two-step bitcast using an
2847 // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
2848 assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&
2849 "Only one type should be a pointer type");
2850 assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&
2851 "Only one type should be a floating point type");
2852 Type *IntTy =
2853 IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy));
2854 auto *VecIntTy = VectorType::get(IntTy, VF);
2855 Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
2856 return Builder.CreateBitOrPointerCast(CastVal, DstVTy);
2857}
2858
2859/// Return a vector containing interleaved elements from multiple
2860/// smaller input vectors.
2862 const Twine &Name) {
2863 unsigned Factor = Vals.size();
2864 assert(Factor > 1 && "Tried to interleave invalid number of vectors");
2865
2866 VectorType *VecTy = cast<VectorType>(Vals[0]->getType());
2867#ifndef NDEBUG
2868 for (Value *Val : Vals)
2869 assert(Val->getType() == VecTy && "Tried to interleave mismatched types");
2870#endif
2871
2872 // Scalable vectors cannot use arbitrary shufflevectors (only splats), so
2873 // must use intrinsics to interleave.
2874 if (VecTy->isScalableTy()) {
2876 return Builder.CreateIntrinsic(WideVecTy, Intrinsic::vector_interleave2,
2877 Vals,
2878 /*FMFSource=*/nullptr, Name);
2879 }
2880
2881 // Fixed length. Start by concatenating all vectors into a wide vector.
2882 Value *WideVec = concatenateVectors(Builder, Vals);
2883
2884 // Interleave the elements into the wide vector.
2885 const unsigned NumElts = VecTy->getElementCount().getFixedValue();
2886 return Builder.CreateShuffleVector(
2887 WideVec, createInterleaveMask(NumElts, Factor), Name);
2888}
2889
2890// Try to vectorize the interleave group that \p Instr belongs to.
2891//
2892// E.g. Translate following interleaved load group (factor = 3):
2893// for (i = 0; i < N; i+=3) {
2894// R = Pic[i]; // Member of index 0
2895// G = Pic[i+1]; // Member of index 1
2896// B = Pic[i+2]; // Member of index 2
2897// ... // do something to R, G, B
2898// }
2899// To:
2900// %wide.vec = load <12 x i32> ; Read 4 tuples of R,G,B
2901// %R.vec = shuffle %wide.vec, poison, <0, 3, 6, 9> ; R elements
2902// %G.vec = shuffle %wide.vec, poison, <1, 4, 7, 10> ; G elements
2903// %B.vec = shuffle %wide.vec, poison, <2, 5, 8, 11> ; B elements
2904//
2905// Or translate following interleaved store group (factor = 3):
2906// for (i = 0; i < N; i+=3) {
2907// ... do something to R, G, B
2908// Pic[i] = R; // Member of index 0
2909// Pic[i+1] = G; // Member of index 1
2910// Pic[i+2] = B; // Member of index 2
2911// }
2912// To:
2913// %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
2914// %B_U.vec = shuffle %B.vec, poison, <0, 1, 2, 3, u, u, u, u>
2915// %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
2916// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> ; Interleave R,G,B elements
2917// store <12 x i32> %interleaved.vec ; Write 4 tuples of R,G,B
2919 assert(!State.Lane && "Interleave group being replicated.");
2920 const InterleaveGroup<Instruction> *Group = IG;
2921 Instruction *Instr = Group->getInsertPos();
2922
2923 // Prepare for the vector type of the interleaved load/store.
2924 Type *ScalarTy = getLoadStoreType(Instr);
2925 unsigned InterleaveFactor = Group->getFactor();
2926 auto *VecTy = VectorType::get(ScalarTy, State.VF * InterleaveFactor);
2927
2928 // TODO: extend the masked interleaved-group support to reversed access.
2929 VPValue *BlockInMask = getMask();
2930 assert((!BlockInMask || !Group->isReverse()) &&
2931 "Reversed masked interleave-group not supported.");
2932
2933 VPValue *Addr = getAddr();
2934 Value *ResAddr = State.get(Addr, VPLane(0));
2935 if (auto *I = dyn_cast<Instruction>(ResAddr))
2936 State.setDebugLocFrom(I->getDebugLoc());
2937
2938 // If the group is reverse, adjust the index to refer to the last vector lane
2939 // instead of the first. We adjust the index from the first vector lane,
2940 // rather than directly getting the pointer for lane VF - 1, because the
2941 // pointer operand of the interleaved access is supposed to be uniform.
2942 if (Group->isReverse()) {
2943 Value *RuntimeVF =
2944 getRuntimeVF(State.Builder, State.Builder.getInt32Ty(), State.VF);
2945 Value *Index =
2946 State.Builder.CreateSub(RuntimeVF, State.Builder.getInt32(1));
2947 Index = State.Builder.CreateMul(Index,
2948 State.Builder.getInt32(Group->getFactor()));
2949 Index = State.Builder.CreateNeg(Index);
2950
2951 bool InBounds = false;
2952 if (auto *Gep = dyn_cast<GetElementPtrInst>(ResAddr->stripPointerCasts()))
2953 InBounds = Gep->isInBounds();
2954 ResAddr = State.Builder.CreateGEP(ScalarTy, ResAddr, Index, "", InBounds);
2955 }
2956
2957 State.setDebugLocFrom(Instr->getDebugLoc());
2958 Value *PoisonVec = PoisonValue::get(VecTy);
2959
2960 auto CreateGroupMask = [&BlockInMask, &State,
2961 &InterleaveFactor](Value *MaskForGaps) -> Value * {
2962 if (State.VF.isScalable()) {
2963 assert(!MaskForGaps && "Interleaved groups with gaps are not supported.");
2964 assert(InterleaveFactor == 2 &&
2965 "Unsupported deinterleave factor for scalable vectors");
2966 auto *ResBlockInMask = State.get(BlockInMask);
2967 SmallVector<Value *, 2> Ops = {ResBlockInMask, ResBlockInMask};
2968 auto *MaskTy = VectorType::get(State.Builder.getInt1Ty(),
2969 State.VF.getKnownMinValue() * 2, true);
2970 return State.Builder.CreateIntrinsic(
2971 MaskTy, Intrinsic::vector_interleave2, Ops,
2972 /*FMFSource=*/nullptr, "interleaved.mask");
2973 }
2974
2975 if (!BlockInMask)
2976 return MaskForGaps;
2977
2978 Value *ResBlockInMask = State.get(BlockInMask);
2979 Value *ShuffledMask = State.Builder.CreateShuffleVector(
2980 ResBlockInMask,
2981 createReplicatedMask(InterleaveFactor, State.VF.getKnownMinValue()),
2982 "interleaved.mask");
2983 return MaskForGaps ? State.Builder.CreateBinOp(Instruction::And,
2984 ShuffledMask, MaskForGaps)
2985 : ShuffledMask;
2986 };
2987
2988 const DataLayout &DL = Instr->getDataLayout();
2989 // Vectorize the interleaved load group.
2990 if (isa<LoadInst>(Instr)) {
2991 Value *MaskForGaps = nullptr;
2992 if (NeedsMaskForGaps) {
2993 MaskForGaps = createBitMaskForGaps(State.Builder,
2994 State.VF.getKnownMinValue(), *Group);
2995 assert(MaskForGaps && "Mask for Gaps is required but it is null");
2996 }
2997
2998 Instruction *NewLoad;
2999 if (BlockInMask || MaskForGaps) {
3000 Value *GroupMask = CreateGroupMask(MaskForGaps);
3001 NewLoad = State.Builder.CreateMaskedLoad(VecTy, ResAddr,
3002 Group->getAlign(), GroupMask,
3003 PoisonVec, "wide.masked.vec");
3004 } else
3005 NewLoad = State.Builder.CreateAlignedLoad(VecTy, ResAddr,
3006 Group->getAlign(), "wide.vec");
3007 Group->addMetadata(NewLoad);
3008
3010 const DataLayout &DL = State.CFG.PrevBB->getDataLayout();
3011 if (VecTy->isScalableTy()) {
3012 assert(InterleaveFactor == 2 &&
3013 "Unsupported deinterleave factor for scalable vectors");
3014
3015 // Scalable vectors cannot use arbitrary shufflevectors (only splats),
3016 // so must use intrinsics to deinterleave.
3017 Value *DI = State.Builder.CreateIntrinsic(
3018 Intrinsic::vector_deinterleave2, VecTy, NewLoad,
3019 /*FMFSource=*/nullptr, "strided.vec");
3020 unsigned J = 0;
3021 for (unsigned I = 0; I < InterleaveFactor; ++I) {
3022 Instruction *Member = Group->getMember(I);
3023
3024 if (!Member)
3025 continue;
3026
3027 Value *StridedVec = State.Builder.CreateExtractValue(DI, I);
3028 // If this member has different type, cast the result type.
3029 if (Member->getType() != ScalarTy) {
3030 VectorType *OtherVTy = VectorType::get(Member->getType(), State.VF);
3031 StridedVec =
3032 createBitOrPointerCast(State.Builder, StridedVec, OtherVTy, DL);
3033 }
3034
3035 if (Group->isReverse())
3036 StridedVec = State.Builder.CreateVectorReverse(StridedVec, "reverse");
3037
3038 State.set(VPDefs[J], StridedVec);
3039 ++J;
3040 }
3041
3042 return;
3043 }
3044
3045 // For each member in the group, shuffle out the appropriate data from the
3046 // wide loads.
3047 unsigned J = 0;
3048 for (unsigned I = 0; I < InterleaveFactor; ++I) {
3049 Instruction *Member = Group->getMember(I);
3050
3051 // Skip the gaps in the group.
3052 if (!Member)
3053 continue;
3054
3055 auto StrideMask =
3056 createStrideMask(I, InterleaveFactor, State.VF.getKnownMinValue());
3057 Value *StridedVec =
3058 State.Builder.CreateShuffleVector(NewLoad, StrideMask, "strided.vec");
3059
3060 // If this member has different type, cast the result type.
3061 if (Member->getType() != ScalarTy) {
3062 assert(!State.VF.isScalable() && "VF is assumed to be non scalable.");
3063 VectorType *OtherVTy = VectorType::get(Member->getType(), State.VF);
3064 StridedVec =
3065 createBitOrPointerCast(State.Builder, StridedVec, OtherVTy, DL);
3066 }
3067
3068 if (Group->isReverse())
3069 StridedVec = State.Builder.CreateVectorReverse(StridedVec, "reverse");
3070
3071 State.set(VPDefs[J], StridedVec);
3072 ++J;
3073 }
3074 return;
3075 }
3076
3077 // The sub vector type for current instruction.
3078 auto *SubVT = VectorType::get(ScalarTy, State.VF);
3079
3080 // Vectorize the interleaved store group.
3081 Value *MaskForGaps =
3082 createBitMaskForGaps(State.Builder, State.VF.getKnownMinValue(), *Group);
3083 assert((!MaskForGaps || !State.VF.isScalable()) &&
3084 "masking gaps for scalable vectors is not yet supported.");
3085 ArrayRef<VPValue *> StoredValues = getStoredValues();
3086 // Collect the stored vector from each member.
3087 SmallVector<Value *, 4> StoredVecs;
3088 unsigned StoredIdx = 0;
3089 for (unsigned i = 0; i < InterleaveFactor; i++) {
3090 assert((Group->getMember(i) || MaskForGaps) &&
3091 "Fail to get a member from an interleaved store group");
3092 Instruction *Member = Group->getMember(i);
3093
3094 // Skip the gaps in the group.
3095 if (!Member) {
3096 Value *Undef = PoisonValue::get(SubVT);
3097 StoredVecs.push_back(Undef);
3098 continue;
3099 }
3100
3101 Value *StoredVec = State.get(StoredValues[StoredIdx]);
3102 ++StoredIdx;
3103
3104 if (Group->isReverse())
3105 StoredVec = State.Builder.CreateVectorReverse(StoredVec, "reverse");
3106
3107 // If this member has different type, cast it to a unified type.
3108
3109 if (StoredVec->getType() != SubVT)
3110 StoredVec = createBitOrPointerCast(State.Builder, StoredVec, SubVT, DL);
3111
3112 StoredVecs.push_back(StoredVec);
3113 }
3114
3115 // Interleave all the smaller vectors into one wider vector.
3116 Value *IVec = interleaveVectors(State.Builder, StoredVecs, "interleaved.vec");
3117 Instruction *NewStoreInstr;
3118 if (BlockInMask || MaskForGaps) {
3119 Value *GroupMask = CreateGroupMask(MaskForGaps);
3120 NewStoreInstr = State.Builder.CreateMaskedStore(
3121 IVec, ResAddr, Group->getAlign(), GroupMask);
3122 } else
3123 NewStoreInstr =
3124 State.Builder.CreateAlignedStore(IVec, ResAddr, Group->getAlign());
3125
3126 Group->addMetadata(NewStoreInstr);
3127}
3128
3129#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3131 VPSlotTracker &SlotTracker) const {
3132 O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << " at ";
3133 IG->getInsertPos()->printAsOperand(O, false);
3134 O << ", ";
3136 VPValue *Mask = getMask();
3137 if (Mask) {
3138 O << ", ";
3139 Mask->printAsOperand(O, SlotTracker);
3140 }
3141
3142 unsigned OpIdx = 0;
3143 for (unsigned i = 0; i < IG->getFactor(); ++i) {
3144 if (!IG->getMember(i))
3145 continue;
3146 if (getNumStoreOperands() > 0) {
3147 O << "\n" << Indent << " store ";
3148 getOperand(1 + OpIdx)->printAsOperand(O, SlotTracker);
3149 O << " to index " << i;
3150 } else {
3151 O << "\n" << Indent << " ";
3153 O << " = load from index " << i;
3154 }
3155 ++OpIdx;
3156 }
3157}
3158#endif
3159
3161 VPCostContext &Ctx) const {
3162 Instruction *InsertPos = getInsertPos();
3163 // Find the VPValue index of the interleave group. We need to skip gaps.
3164 unsigned InsertPosIdx = 0;
3165 for (unsigned Idx = 0; IG->getFactor(); ++Idx)
3166 if (auto *Member = IG->getMember(Idx)) {
3167 if (Member == InsertPos)
3168 break;
3169 InsertPosIdx++;
3170 }
3171 Type *ValTy = Ctx.Types.inferScalarType(
3172 getNumDefinedValues() > 0 ? getVPValue(InsertPosIdx)
3173 : getStoredValues()[InsertPosIdx]);
3174 auto *VectorTy = cast<VectorType>(toVectorTy(ValTy, VF));
3175 unsigned AS = getLoadStoreAddressSpace(InsertPos);
3176
3177 unsigned InterleaveFactor = IG->getFactor();
3178 auto *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
3179
3180 // Holds the indices of existing members in the interleaved group.
3182 for (unsigned IF = 0; IF < InterleaveFactor; IF++)
3183 if (IG->getMember(IF))
3184 Indices.push_back(IF);
3185
3186 // Calculate the cost of the whole interleaved group.
3188 InsertPos->getOpcode(), WideVecTy, IG->getFactor(), Indices,
3189 IG->getAlign(), AS, Ctx.CostKind, getMask(), NeedsMaskForGaps);
3190
3191 if (!IG->isReverse())
3192 return Cost;
3193
3194 return Cost + IG->getNumMembers() *
3196 VectorTy, std::nullopt, Ctx.CostKind,
3197 0);
3198}
3199
3200#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3202 VPSlotTracker &SlotTracker) const {
3203 O << Indent << "EMIT ";
3205 O << " = CANONICAL-INDUCTION ";
3207}
3208#endif
3209
3211 return IsScalarAfterVectorization &&
3212 (!IsScalable || vputils::onlyFirstLaneUsed(this));
3213}
3214
3216 assert(getInductionDescriptor().getKind() ==
3218 "Not a pointer induction according to InductionDescriptor!");
3219 assert(cast<PHINode>(getUnderlyingInstr())->getType()->isPointerTy() &&
3220 "Unexpected type.");
3222 "Recipe should have been replaced");
3223
3224 unsigned CurrentPart = getUnrollPart(*this);
3225
3226 // Build a pointer phi
3227 Value *ScalarStartValue = getStartValue()->getLiveInIRValue();
3228 Type *ScStValueType = ScalarStartValue->getType();
3229
3230 BasicBlock *VectorPH = State.CFG.getPreheaderBBFor(this);
3231 PHINode *NewPointerPhi = nullptr;
3232 if (CurrentPart == 0) {
3233 auto *IVR = cast<VPHeaderPHIRecipe>(&getParent()
3234 ->getPlan()
3235 ->getVectorLoopRegion()
3236 ->getEntryBasicBlock()
3237 ->front());
3238 PHINode *CanonicalIV = cast<PHINode>(State.get(IVR, /*IsScalar*/ true));
3239 NewPointerPhi = PHINode::Create(ScStValueType, 2, "pointer.phi",
3240 CanonicalIV->getIterator());
3241 NewPointerPhi->addIncoming(ScalarStartValue, VectorPH);
3242 NewPointerPhi->setDebugLoc(getDebugLoc());
3243 } else {
3244 // The recipe has been unrolled. In that case, fetch the single pointer phi
3245 // shared among all unrolled parts of the recipe.
3246 auto *GEP =
3247 cast<GetElementPtrInst>(State.get(getFirstUnrolledPartOperand()));
3248 NewPointerPhi = cast<PHINode>(GEP->getPointerOperand());
3249 }
3250
3251 // A pointer induction, performed by using a gep
3252 BasicBlock::iterator InductionLoc = State.Builder.GetInsertPoint();
3253 Value *ScalarStepValue = State.get(getStepValue(), VPLane(0));
3254 Type *PhiType = State.TypeAnalysis.inferScalarType(getStepValue());
3255 Value *RuntimeVF = getRuntimeVF(State.Builder, PhiType, State.VF);
3256 // Add induction update using an incorrect block temporarily. The phi node
3257 // will be fixed after VPlan execution. Note that at this point the latch
3258 // block cannot be used, as it does not exist yet.
3259 // TODO: Model increment value in VPlan, by turning the recipe into a
3260 // multi-def and a subclass of VPHeaderPHIRecipe.
3261 if (CurrentPart == 0) {
3262 // The recipe represents the first part of the pointer induction. Create the
3263 // GEP to increment the phi across all unrolled parts.
3264 unsigned UF = CurrentPart == 0 ? getParent()->getPlan()->getUF() : 1;
3265 Value *NumUnrolledElems =
3266 State.Builder.CreateMul(RuntimeVF, ConstantInt::get(PhiType, UF));
3267
3268 Value *InductionGEP = GetElementPtrInst::Create(
3269 State.Builder.getInt8Ty(), NewPointerPhi,
3270 State.Builder.CreateMul(ScalarStepValue, NumUnrolledElems), "ptr.ind",
3271 InductionLoc);
3272
3273 NewPointerPhi->addIncoming(InductionGEP, VectorPH);
3274 }
3275
3276 // Create actual address geps that use the pointer phi as base and a
3277 // vectorized version of the step value (<step*0, ..., step*N>) as offset.
3278 Type *VecPhiType = VectorType::get(PhiType, State.VF);
3279 Value *StartOffsetScalar = State.Builder.CreateMul(
3280 RuntimeVF, ConstantInt::get(PhiType, CurrentPart));
3281 Value *StartOffset =
3282 State.Builder.CreateVectorSplat(State.VF, StartOffsetScalar);
3283 // Create a vector of consecutive numbers from zero to VF.
3284 StartOffset = State.Builder.CreateAdd(
3285 StartOffset, State.Builder.CreateStepVector(VecPhiType));
3286
3287 assert(ScalarStepValue == State.get(getOperand(1), VPLane(0)) &&
3288 "scalar step must be the same across all parts");
3289 Value *GEP = State.Builder.CreateGEP(
3290 State.Builder.getInt8Ty(), NewPointerPhi,
3291 State.Builder.CreateMul(StartOffset, State.Builder.CreateVectorSplat(
3292 State.VF, ScalarStepValue)),
3293 "vector.gep");
3294 State.set(this, GEP);
3295}
3296
3297#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3299 VPSlotTracker &SlotTracker) const {
3300 assert((getNumOperands() == 2 || getNumOperands() == 4) &&
3301 "unexpected number of operands");
3302 O << Indent << "EMIT ";
3304 O << " = WIDEN-POINTER-INDUCTION ";
3306 O << ", ";
3308 if (getNumOperands() == 4) {
3309 O << ", ";
3311 O << ", ";
3313 }
3314}
3315#endif
3316
3318 assert(!State.Lane && "cannot be used in per-lane");
3319 if (State.ExpandedSCEVs.contains(Expr)) {
3320 // SCEV Expr has already been expanded, result must already be set. At the
3321 // moment we have to execute the entry block twice (once before skeleton
3322 // creation to get expanded SCEVs used by the skeleton and once during
3323 // regular VPlan execution).
3325 assert(State.get(this, VPLane(0)) == State.ExpandedSCEVs[Expr] &&
3326 "Results must match");
3327 return;
3328 }
3329
3330 const DataLayout &DL = State.CFG.PrevBB->getDataLayout();
3331 SCEVExpander Exp(SE, DL, "induction");
3332
3333 Value *Res = Exp.expandCodeFor(Expr, Expr->getType(),
3334 &*State.Builder.GetInsertPoint());
3335 State.ExpandedSCEVs[Expr] = Res;
3336 State.set(this, Res, VPLane(0));
3337}
3338
3339#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3341 VPSlotTracker &SlotTracker) const {
3342 O << Indent << "EMIT ";
3344 O << " = EXPAND SCEV " << *Expr;
3345}
3346#endif
3347
3349 Value *CanonicalIV = State.get(getOperand(0), /*IsScalar*/ true);
3350 Type *STy = CanonicalIV->getType();
3351 IRBuilder<> Builder(State.CFG.PrevBB->getTerminator());
3352 ElementCount VF = State.VF;
3353 Value *VStart = VF.isScalar()
3354 ? CanonicalIV
3355 : Builder.CreateVectorSplat(VF, CanonicalIV, "broadcast");
3356 Value *VStep = createStepForVF(Builder, STy, VF, getUnrollPart(*this));
3357 if (VF.isVector()) {
3358 VStep = Builder.CreateVectorSplat(VF, VStep);
3359 VStep =
3360 Builder.CreateAdd(VStep, Builder.CreateStepVector(VStep->getType()));
3361 }
3362 Value *CanonicalVectorIV = Builder.CreateAdd(VStart, VStep, "vec.iv");
3363 State.set(this, CanonicalVectorIV);
3364}
3365
3366#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3368 VPSlotTracker &SlotTracker) const {
3369 O << Indent << "EMIT ";
3371 O << " = WIDEN-CANONICAL-INDUCTION ";
3373}
3374#endif
3375
3377 auto &Builder = State.Builder;
3378 // Create a vector from the initial value.
3379 auto *VectorInit = getStartValue()->getLiveInIRValue();
3380
3381 Type *VecTy = State.VF.isScalar()
3382 ? VectorInit->getType()
3383 : VectorType::get(VectorInit->getType(), State.VF);
3384
3385 BasicBlock *VectorPH = State.CFG.getPreheaderBBFor(this);
3386 if (State.VF.isVector()) {
3387 auto *IdxTy = Builder.getInt32Ty();
3388 auto *One = ConstantInt::get(IdxTy, 1);
3389 IRBuilder<>::InsertPointGuard Guard(Builder);
3390 Builder.SetInsertPoint(VectorPH->getTerminator());
3391 auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, State.VF);
3392 auto *LastIdx = Builder.CreateSub(RuntimeVF, One);
3393 VectorInit = Builder.CreateInsertElement(
3394 PoisonValue::get(VecTy), VectorInit, LastIdx, "vector.recur.init");
3395 }
3396
3397 // Create a phi node for the new recurrence.
3398 PHINode *Phi = PHINode::Create(VecTy, 2, "vector.recur");
3399 Phi->insertBefore(State.CFG.PrevBB->getFirstInsertionPt());
3400 Phi->addIncoming(VectorInit, VectorPH);
3401 State.set(this, Phi);
3402}
3403
3406 VPCostContext &Ctx) const {
3407 if (VF.isScalar())
3408 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
3409
3410 if (VF.isScalable() && VF.getKnownMinValue() == 1)
3412
3414 std::iota(Mask.begin(), Mask.end(), VF.getKnownMinValue() - 1);
3415 Type *VectorTy =
3416 toVectorTy(Ctx.Types.inferScalarType(this->getVPSingleValue()), VF);
3417
3419 cast<VectorType>(VectorTy), Mask, Ctx.CostKind,
3420 VF.getKnownMinValue() - 1);
3421}
3422
3423#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3425 VPSlotTracker &SlotTracker) const {
3426 O << Indent << "FIRST-ORDER-RECURRENCE-PHI ";
3428 O << " = phi ";
3430}
3431#endif
3432
3434 auto &Builder = State.Builder;
3435
3436 // If this phi is fed by a scaled reduction then it should output a
3437 // vector with fewer elements than the VF.
3438 ElementCount VF = State.VF.divideCoefficientBy(VFScaleFactor);
3439
3440 // Reductions do not have to start at zero. They can start with
3441 // any loop invariant values.
3442 VPValue *StartVPV = getStartValue();
3443 Value *StartV = StartVPV->getLiveInIRValue();
3444
3445 // In order to support recurrences we need to be able to vectorize Phi nodes.
3446 // Phi nodes have cycles, so we need to vectorize them in two stages. This is
3447 // stage #1: We create a new vector PHI node with no incoming edges. We'll use
3448 // this value when we vectorize all of the instructions that use the PHI.
3449 bool ScalarPHI = State.VF.isScalar() || IsInLoop;
3450 Type *VecTy =
3451 ScalarPHI ? StartV->getType() : VectorType::get(StartV->getType(), VF);
3452
3453 BasicBlock *HeaderBB = State.CFG.PrevBB;
3454 assert(State.CurrentParentLoop->getHeader() == HeaderBB &&
3455 "recipe must be in the vector loop header");
3456 auto *Phi = PHINode::Create(VecTy, 2, "vec.phi");
3457 Phi->insertBefore(HeaderBB->getFirstInsertionPt());
3458 State.set(this, Phi, IsInLoop);
3459
3460 BasicBlock *VectorPH = State.CFG.getPreheaderBBFor(this);
3461
3462 Value *Iden = nullptr;
3463 RecurKind RK = RdxDesc.getRecurrenceKind();
3464 unsigned CurrentPart = getUnrollPart(*this);
3465
3468 // MinMax and AnyOf reductions have the start value as their identity.
3469 if (ScalarPHI) {
3470 Iden = StartV;
3471 } else {
3472 IRBuilderBase::InsertPointGuard IPBuilder(Builder);
3473 Builder.SetInsertPoint(VectorPH->getTerminator());
3474 StartV = Iden = State.get(StartVPV);
3475 }
3477 // [I|F]FindLastIV will use a sentinel value to initialize the reduction
3478 // phi or the resume value from the main vector loop when vectorizing the
3479 // epilogue loop. In the exit block, ComputeReductionResult will generate
3480 // checks to verify if the reduction result is the sentinel value. If the
3481 // result is the sentinel value, it will be corrected back to the start
3482 // value.
3483 // TODO: The sentinel value is not always necessary. When the start value is
3484 // a constant, and smaller than the start value of the induction variable,
3485 // the start value can be directly used to initialize the reduction phi.
3486 Iden = StartV;
3487 if (!ScalarPHI) {
3488 IRBuilderBase::InsertPointGuard IPBuilder(Builder);
3489 Builder.SetInsertPoint(VectorPH->getTerminator());
3490 StartV = Iden = Builder.CreateVectorSplat(State.VF, Iden);
3491 }
3492 } else {
3493 Iden = llvm::getRecurrenceIdentity(RK, VecTy->getScalarType(),
3494 RdxDesc.getFastMathFlags());
3495
3496 if (!ScalarPHI) {
3497 if (CurrentPart == 0) {
3498 // Create start and identity vector values for the reduction in the
3499 // preheader.
3500 // TODO: Introduce recipes in VPlan preheader to create initial values.
3501 Iden = Builder.CreateVectorSplat(VF, Iden);
3502 IRBuilderBase::InsertPointGuard IPBuilder(Builder);
3503 Builder.SetInsertPoint(VectorPH->getTerminator());
3504 Constant *Zero = Builder.getInt32(0);
3505 StartV = Builder.CreateInsertElement(Iden, StartV, Zero);
3506 } else {
3507 Iden = Builder.CreateVectorSplat(VF, Iden);
3508 }
3509 }
3510 }
3511
3512 Phi = cast<PHINode>(State.get(this, IsInLoop));
3513 Value *StartVal = (CurrentPart == 0) ? StartV : Iden;
3514 Phi->addIncoming(StartVal, VectorPH);
3515}
3516
3517#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3519 VPSlotTracker &SlotTracker) const {
3520 O << Indent << "WIDEN-REDUCTION-PHI ";
3521
3523 O << " = phi ";
3525 if (VFScaleFactor != 1)
3526 O << " (VF scaled by 1/" << VFScaleFactor << ")";
3527}
3528#endif
3529
3532 "Non-native vplans are not expected to have VPWidenPHIRecipes.");
3533
3535 Value *Op0 = State.get(getOperand(0));
3536 Type *VecTy = Op0->getType();
3537 Value *VecPhi = State.Builder.CreatePHI(VecTy, 2, "vec.phi");
3538 State.set(this, VecPhi);
3539}
3540
3541#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3543 VPSlotTracker &SlotTracker) const {
3544 O << Indent << "WIDEN-PHI ";
3545
3546 auto *OriginalPhi = cast<PHINode>(getUnderlyingValue());
3547 // Unless all incoming values are modeled in VPlan print the original PHI
3548 // directly.
3549 // TODO: Remove once all VPWidenPHIRecipe instances keep all relevant incoming
3550 // values as VPValues.
3551 if (getNumOperands() != OriginalPhi->getNumOperands()) {
3552 O << VPlanIngredient(OriginalPhi);
3553 return;
3554 }
3555
3557 O << " = phi ";
3559}
3560#endif
3561
3562// TODO: It would be good to use the existing VPWidenPHIRecipe instead and
3563// remove VPActiveLaneMaskPHIRecipe.
3565 BasicBlock *VectorPH = State.CFG.getPreheaderBBFor(this);
3566 Value *StartMask = State.get(getOperand(0));
3567 PHINode *Phi =
3568 State.Builder.CreatePHI(StartMask->getType(), 2, "active.lane.mask");
3569 Phi->addIncoming(StartMask, VectorPH);
3570 Phi->setDebugLoc(getDebugLoc());
3571 State.set(this, Phi);
3572}
3573
3574#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3576 VPSlotTracker &SlotTracker) const {
3577 O << Indent << "ACTIVE-LANE-MASK-PHI ";
3578
3580 O << " = phi ";
3582}
3583#endif
3584
3585#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3587 VPSlotTracker &SlotTracker) const {
3588 O << Indent << "EXPLICIT-VECTOR-LENGTH-BASED-IV-PHI ";
3589
3591 O << " = phi ";
3593}
3594#endif
3595
3597 BasicBlock *VectorPH = State.CFG.getPreheaderBBFor(this);
3598 Value *Start = State.get(getStartValue(), VPLane(0));
3599 PHINode *Phi = State.Builder.CreatePHI(Start->getType(), 2, Name);
3600 Phi->addIncoming(Start, VectorPH);
3601 Phi->setDebugLoc(getDebugLoc());
3602 State.set(this, Phi, /*IsScalar=*/true);
3603}
3604
3605#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3607 VPSlotTracker &SlotTracker) const {
3608 O << Indent << "SCALAR-PHI ";
3610 O << " = phi ";
3612}
3613#endif
AMDGPU Lower Kernel Arguments
AMDGPU Register Bank Select
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
return RetTy
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
#define LLVM_DEBUG(...)
Definition: Debug.h:106
uint64_t Addr
std::string Name
Hexagon Common GEP
This file provides a LoopVectorizationPlanner class.
cl::opt< unsigned > ForceTargetInstructionCost("force-target-instruction-cost", cl::init(0), cl::Hidden, cl::desc("A flag that overrides the target's expected cost for " "an instruction to a single constant value. Mostly " "useful for getting consistent testing."))
#define I(x, y, z)
Definition: MD5.cpp:58
mir Rename Register Operands
static DebugLoc getDebugLoc(MachineBasicBlock::instr_iterator FirstMI, MachineBasicBlock::instr_iterator LastMI)
Return the first found DebugLoc that has a DILocation, given a range of instructions.
const SmallVectorImpl< MachineOperand > & Cond
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallVector class.
static SymbolRef::Type getType(const Symbol *Sym)
Definition: TapiFile.cpp:39
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 Value * createBitOrPointerCast(IRBuilderBase &Builder, Value *V, VectorType *DstVTy, const DataLayout &DL)
cl::opt< unsigned > ForceTargetInstructionCost
static Value * getStepVector(Value *Val, Value *Step, Instruction::BinaryOps BinOp, ElementCount VF, IRBuilderBase &Builder)
This function adds (0 * Step, 1 * Step, 2 * Step, ...) to each vector element of Val.
static Type * getGEPIndexTy(bool IsScalable, bool IsReverse, unsigned CurrentPart, IRBuilderBase &Builder)
static Constant * getSignedIntOrFpConstant(Type *Ty, int64_t C)
A helper function that returns an integer or floating-point constant with value C.
This file contains the declarations of the Vectorization Plan base classes:
Value * RHS
static const uint32_t IV[8]
Definition: blake3_impl.h:78
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:168
static Attribute getWithAlignment(LLVMContext &Context, Align Alignment)
Return a uniquified Attribute object that has the specific alignment set.
Definition: Attributes.cpp:234
LLVM Basic Block Representation.
Definition: BasicBlock.h:61
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
Definition: BasicBlock.cpp:426
InstListType::const_iterator getFirstNonPHIIt() const
Iterator returning form of getFirstNonPHI.
Definition: BasicBlock.cpp:374
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
Definition: BasicBlock.cpp:471
const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
Definition: BasicBlock.cpp:296
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:177
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:240
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
Definition: BasicBlock.cpp:292
Conditional or Unconditional Branch instruction.
static BranchInst * Create(BasicBlock *IfTrue, InsertPosition InsertBefore=nullptr)
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
Adds the attribute to the indicated argument.
Definition: InstrTypes.h:1494
This class represents a function call, abstracting a target machine's calling convention.
static 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.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:673
@ ICMP_UGT
unsigned greater than
Definition: InstrTypes.h:696
@ ICMP_ULT
unsigned less than
Definition: InstrTypes.h:698
static StringRef getPredicateName(Predicate P)
This is the shared class of boolean and integer constants.
Definition: Constants.h:83
static ConstantInt * getSigned(IntegerType *Ty, int64_t V)
Return a ConstantInt with the specified value for the specified type.
Definition: Constants.h:126
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:157
This is an important base class in LLVM.
Definition: Constant.h:42
This class represents an Operation in the Expression.
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:63
A debug info location.
Definition: DebugLoc.h:33
constexpr bool isVector() const
One or more elements.
Definition: TypeSize.h:326
constexpr bool isScalar() const
Exactly one element.
Definition: TypeSize.h:322
Convenience struct for specifying and reasoning about fast-math flags.
Definition: FMF.h:20
void setAllowContract(bool B=true)
Definition: FMF.h:91
bool noSignedZeros() const
Definition: FMF.h:68
bool noInfs() const
Definition: FMF.h:67
void setAllowReciprocal(bool B=true)
Definition: FMF.h:88
bool allowReciprocal() const
Definition: FMF.h:69
void print(raw_ostream &O) const
Print fast-math flags to O.
Definition: Operator.cpp:271
void setNoSignedZeros(bool B=true)
Definition: FMF.h:85
bool allowReassoc() const
Flag queries.
Definition: FMF.h:65
bool approxFunc() const
Definition: FMF.h:71
void setNoNaNs(bool B=true)
Definition: FMF.h:79
void setAllowReassoc(bool B=true)
Flag setters.
Definition: FMF.h:76
bool noNaNs() const
Definition: FMF.h:66
void setApproxFunc(bool B=true)
Definition: FMF.h:94
void setNoInfs(bool B=true)
Definition: FMF.h:82
bool allowContract() const
Definition: FMF.h:70
Class to represent function types.
Definition: DerivedTypes.h:105
Type * getParamType(unsigned i) const
Parameter type accessors.
Definition: DerivedTypes.h:137
ArrayRef< Type * > params() const
Definition: DerivedTypes.h:132
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition: Function.h:216
bool willReturn() const
Determine if the function will return.
Definition: Function.h:662
bool doesNotThrow() const
Determine if the function cannot unwind.
Definition: Function.h:595
Type * getReturnType() const
Returns the type of the ret val.
Definition: Function.h:221
bool hasNoUnsignedSignedWrap() const
bool hasNoUnsignedWrap() const
bool isInBounds() const
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Definition: Instructions.h:956
Common base class shared among various IRBuilders.
Definition: IRBuilder.h:113
ConstantInt * getInt1(bool V)
Get a constant value representing either true or false.
Definition: IRBuilder.h:480
Value * CreateInsertElement(Type *VecTy, Value *NewElt, Value *Idx, const Twine &Name="")
Definition: IRBuilder.h:2511
IntegerType * getInt1Ty()
Fetch the type representing a single bit.
Definition: IRBuilder.h:530
Value * CreateSIToFP(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2106
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
Definition: IRBuilder.h:2499
LoadInst * CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align, const char *Name)
Definition: IRBuilder.h:1815
Value * CreateZExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a ZExt or Trunc from the integer value V to DestTy.
Definition: IRBuilder.h:2051
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.
Definition: IRBuilder.cpp:1135
Value * CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name="")
Return a vector value that contains.
Definition: IRBuilder.cpp:1163
Value * CreateExtractValue(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &Name="")
Definition: IRBuilder.h:2555
ConstantInt * getTrue()
Get the constant value for i1 true.
Definition: IRBuilder.h:485
CallInst * CreateMaskedLoad(Type *Ty, Value *Ptr, Align Alignment, Value *Mask, Value *PassThru=nullptr, const Twine &Name="")
Create a call to Masked Load intrinsic.
Definition: IRBuilder.cpp:546
Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
Definition: IRBuilder.cpp:1053
BasicBlock::iterator GetInsertPoint() const
Definition: IRBuilder.h:194
Value * CreateSExt(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2045
Value * CreateFreeze(Value *V, const Twine &Name="")
Definition: IRBuilder.h:2574
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
Definition: IRBuilder.h:545
Value * CreatePtrAdd(Value *Ptr, Value *Offset, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Definition: IRBuilder.h:1987
Value * CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy, const Twine &Name="", MDNode *FPMathTag=nullptr, FMFSource FMFSource={})
Definition: IRBuilder.h:2186
Value * CreateUIToFP(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNeg=false)
Definition: IRBuilder.h:2093
BasicBlock * GetInsertBlock() const
Definition: IRBuilder.h:193
void setFastMathFlags(FastMathFlags NewFMF)
Set the fast-math flags to be used with generated fp-math operators.
Definition: IRBuilder.h:330
Value * CreateVectorReverse(Value *V, const Twine &Name="")
Return a vector value that contains the vector V reversed.
Definition: IRBuilder.cpp:1119
Value * CreateFCmpFMF(CmpInst::Predicate P, Value *LHS, Value *RHS, FMFSource FMFSource, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:2398
Value * CreateGEP(Type *Ty, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Definition: IRBuilder.h:1874
Value * CreateNeg(Value *V, const Twine &Name="", bool HasNSW=false)
Definition: IRBuilder.h:1733
CallInst * CreateOrReduce(Value *Src)
Create a vector int OR reduction intrinsic of the source vector.
Definition: IRBuilder.cpp:424
InsertPoint saveIP() const
Returns the current insert point.
Definition: IRBuilder.h:296
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.
Definition: IRBuilder.cpp:900
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition: IRBuilder.h:505
Value * CreateBitOrPointerCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2234
Value * CreateCmp(CmpInst::Predicate Pred, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:2404
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
Definition: IRBuilder.h:2435
Value * CreateNot(Value *V, const Twine &Name="")
Definition: IRBuilder.h:1757
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2270
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1387
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:1164
Value * CreateNAryOp(unsigned Opc, ArrayRef< Value * > Ops, const Twine &Name="", MDNode *FPMathTag=nullptr)
Create either a UnaryOperator or BinaryOperator depending on Opc.
Definition: IRBuilder.cpp:968
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNeg=false)
Definition: IRBuilder.h:2033
Value * CreateShuffleVector(Value *V1, Value *V2, Value *Mask, const Twine &Name="")
Definition: IRBuilder.h:2533
LLVMContext & getContext() const
Definition: IRBuilder.h:195
CallInst * CreateMaskedStore(Value *Val, Value *Ptr, Align Alignment, Value *Mask)
Create a call to Masked Store intrinsic.
Definition: IRBuilder.cpp:566
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1370
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args={}, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:2449
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="", bool IsNUW=false, bool IsNSW=false)
Definition: IRBuilder.h:2019
PointerType * getPtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer.
Definition: IRBuilder.h:588
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:1671
Value * CreateLogicalAnd(Value *Cond1, Value *Cond2, const Twine &Name="")
Definition: IRBuilder.h:1688
void restoreIP(InsertPoint IP)
Sets the current insert point to a previously-saved location.
Definition: IRBuilder.h:308
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition: IRBuilder.h:199
StoreInst * CreateAlignedStore(Value *Val, Value *Ptr, MaybeAlign Align, bool isVolatile=false)
Definition: IRBuilder.h:1834
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2380
Value * CreateFMul(Value *L, Value *R, const Twine &Name="", MDNode *FPMD=nullptr)
Definition: IRBuilder.h:1614
IntegerType * getInt8Ty()
Fetch the type representing an 8-bit integer.
Definition: IRBuilder.h:535
Value * CreateStepVector(Type *DstType, const Twine &Name="")
Creates a vector of type DstType with the linear sequence <0, 1, ...>
Definition: IRBuilder.cpp:108
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1404
CallInst * CreateMaskedScatter(Value *Val, Value *Ptrs, Align Alignment, Value *Mask=nullptr)
Create a call to Masked Scatter intrinsic.
Definition: IRBuilder.cpp:627
CallInst * CreateMaskedGather(Type *Ty, Value *Ptrs, Align Alignment, Value *Mask=nullptr, Value *PassThru=nullptr, const Twine &Name="")
Create a call to Masked Gather intrinsic.
Definition: IRBuilder.cpp:596
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2705
A struct for saving information about induction variables.
@ IK_PtrInduction
Pointer induction var. Step = C.
This instruction inserts a single (scalar) element into a VectorType value.
VectorType * getType() const
Overload to return most specific vector type.
static InstructionCost getInvalid(CostType Val=0)
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction.
Definition: Instruction.cpp:99
bool isBinaryOp() const
Definition: Instruction.h:296
InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Definition: Instruction.cpp:94
FastMathFlags getFastMathFlags() const LLVM_READONLY
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
const char * getOpcodeName() const
Definition: Instruction.h:293
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Definition: Instruction.h:291
bool isUnaryOp() const
Definition: Instruction.h:295
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
Definition: Instruction.h:489
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition: Type.cpp:311
The group of interleaved loads/stores sharing the same stride and close to each other.
Definition: VectorUtils.h:488
uint32_t getFactor() const
Definition: VectorUtils.h:504
InstTy * getMember(uint32_t Index) const
Get the member with the given index Index.
Definition: VectorUtils.h:558
bool isReverse() const
Definition: VectorUtils.h:503
InstTy * getInsertPos() const
Definition: VectorUtils.h:574
void addMetadata(InstTy *NewInst) const
Add metadata (e.g.
Align getAlign() const
Definition: VectorUtils.h:505
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
BlockT * getHeader() const
void print(raw_ostream &OS, const SlotIndexes *=nullptr, bool IsStandalone=true) const
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
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 PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Definition: Constants.cpp:1878
The RecurrenceDescriptor is used to identify recurrences variables in a loop.
Definition: IVDescriptors.h:77
FastMathFlags getFastMathFlags() const
static unsigned getOpcode(RecurKind Kind)
Returns the opcode corresponding to the RecurrenceKind.
Type * getRecurrenceType() const
Returns the type of the recurrence.
TrackingVH< Value > getRecurrenceStartValue() const
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,...
bool isSigned() const
Returns true if all source operands of the recurrence are SExtInsts.
RecurKind getRecurrenceKind() const
StoreInst * IntermediateStore
Reductions may store temporary or final result to an invariant address.
static bool isMinMaxRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is any min/max kind.
This class uses information about analyze scalars to rewrite expressions in canonical form.
Type * getType() const
Return the LLVM type of this SCEV expression.
This class represents the LLVM 'select' instruction.
This class provides computation of slot numbers for LLVM Assembly writing.
Definition: AsmWriter.cpp:698
void push_back(const T &Elt)
Definition: SmallVector.h:413
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1196
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:51
InstructionCost getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy, CmpInst::Predicate VecPred, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput, OperandValueInfo Op1Info={OK_AnyValue, OP_None}, OperandValueInfo Op2Info={OK_AnyValue, OP_None}, const Instruction *I=nullptr) const
InstructionCost getAddressComputationCost(Type *Ty, ScalarEvolution *SE=nullptr, const SCEV *Ptr=nullptr) const
InstructionCost getMemoryOpCost(unsigned Opcode, Type *Src, Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput, OperandValueInfo OpdInfo={OK_AnyValue, OP_None}, const Instruction *I=nullptr) const
InstructionCost getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef< unsigned > Indices, Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput, bool UseMaskForCond=false, bool UseMaskForGaps=false) const
InstructionCost getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA, TTI::TargetCostKind CostKind) const
InstructionCost getArithmeticReductionCost(unsigned Opcode, VectorType *Ty, std::optional< FastMathFlags > FMF, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput) const
Calculate the cost of vector reduction intrinsics.
InstructionCost getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src, TTI::CastContextHint CCH, TTI::TargetCostKind CostKind=TTI::TCK_SizeAndLatency, const Instruction *I=nullptr) const
static OperandValueInfo getOperandInfo(const Value *V)
Collect properties of V used in cost analysis, e.g. OP_PowerOf2.
InstructionCost getMinMaxReductionCost(Intrinsic::ID IID, VectorType *Ty, FastMathFlags FMF=FastMathFlags(), TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput) const
InstructionCost getArithmeticInstrCost(unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput, TTI::OperandValueInfo Opd1Info={TTI::OK_AnyValue, TTI::OP_None}, TTI::OperandValueInfo Opd2Info={TTI::OK_AnyValue, TTI::OP_None}, ArrayRef< const Value * > Args={}, const Instruction *CxtI=nullptr, const TargetLibraryInfo *TLibInfo=nullptr) const
This is an approximation of reciprocal throughput of a math/logic op.
InstructionCost getMaskedMemoryOpCost(unsigned Opcode, Type *Src, Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput) const
InstructionCost getShuffleCost(ShuffleKind Kind, VectorType *Tp, ArrayRef< int > Mask={}, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput, int Index=0, VectorType *SubTp=nullptr, ArrayRef< const Value * > Args={}, const Instruction *CxtI=nullptr) const
InstructionCost getGatherScatterOpCost(unsigned Opcode, Type *DataTy, const Value *Ptr, bool VariableMask, Align Alignment, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput, const Instruction *I=nullptr) const
@ TCC_Free
Expected to fold away in lowering.
InstructionCost getPartialReductionCost(unsigned Opcode, Type *InputTypeA, Type *InputTypeB, Type *AccumType, ElementCount VF, PartialReductionExtendKind OpAExtend, PartialReductionExtendKind OpBExtend, std::optional< unsigned > BinOp=std::nullopt) const
@ SK_Splice
Concatenates elements from the first input vector with elements of the second input vector.
@ SK_Reverse
Reverse the order of the vector.
InstructionCost getCallInstrCost(Function *F, Type *RetTy, ArrayRef< Type * > Tys, TTI::TargetCostKind CostKind=TTI::TCK_SizeAndLatency) const
InstructionCost getCFInstrCost(unsigned Opcode, TTI::TargetCostKind CostKind=TTI::TCK_SizeAndLatency, const Instruction *I=nullptr) const
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.
This class represents a truncation of integer types.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
bool isVectorTy() const
True if this is an instance of VectorType.
Definition: Type.h:270
bool isPointerTy() const
True if this is an instance of PointerType.
Definition: Type.h:264
static IntegerType * getInt1Ty(LLVMContext &C)
static IntegerType * getIntNTy(LLVMContext &C, unsigned N)
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
static Type * getVoidTy(LLVMContext &C)
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition: Type.h:128
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:237
TypeID getTypeID() const
Return the type id for the type.
Definition: Type.h:136
bool isVoidTy() const
Return true if this is 'void'.
Definition: Type.h:139
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition: Type.h:355
value_op_iterator value_op_end()
Definition: User.h:309
Value * getOperand(unsigned i) const
Definition: User.h:228
value_op_iterator value_op_begin()
Definition: User.h:306
void execute(VPTransformState &State) override
Generate the active lane mask phi of the vector loop.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph.
Definition: VPlan.h:3538
RecipeListTy & getRecipeList()
Returns a reference to the list of recipes.
Definition: VPlan.h:3591
iterator end()
Definition: VPlan.h:3575
void insert(VPRecipeBase *Recipe, iterator InsertPt)
Definition: VPlan.h:3604
void print(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 VPWidenMemoryRecipe.
VPValue * getIncomingValue(unsigned Idx) const
Return incoming value number Idx.
Definition: VPlan.h:2525
VPValue * getMask(unsigned Idx) const
Return mask number Idx.
Definition: VPlan.h:2530
unsigned getNumIncomingValues() const
Return the number of incoming values, taking into account when normalized the first incoming value wi...
Definition: VPlan.h:2520
void execute(VPTransformState &State) override
Generate the phi/select nodes.
bool isNormalized() const
A normalized blend is one that has an odd number of operands, whereby the first operand does not have...
Definition: VPlan.h:2516
VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
Definition: VPlan.h:392
VPRegionBlock * getParent()
Definition: VPlan.h:484
const VPBasicBlock * getExitingBasicBlock() const
Definition: VPlan.cpp:178
const VPBlocksTy & getPredecessors() const
Definition: VPlan.h:515
VPlan * getPlan()
Definition: VPlan.cpp:153
const VPBasicBlock * getEntryBasicBlock() const
Definition: VPlan.cpp:158
VPValue * getMask() const
Return the mask used by this recipe.
Definition: VPlan.h:2892
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.
VPInstruction * createNaryOp(unsigned Opcode, ArrayRef< VPValue * > Operands, Instruction *Inst=nullptr, const Twine &Name="")
Create an N-ary operation with Opcode, Operands and set Inst as its underlying Instruction.
void print(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:298
void dump() const
Dump the VPDef to stderr (for debugging).
Definition: VPlan.cpp:114
unsigned getNumDefinedValues() const
Returns the number of values defined by the VPDef.
Definition: VPlanValue.h:421
ArrayRef< VPValue * > definedValues()
Returns an ArrayRef of the values defined by the VPDef.
Definition: VPlanValue.h:416
VPValue * getVPSingleValue()
Returns the only VPValue defined by the VPDef.
Definition: VPlanValue.h:394
VPValue * getVPValue(unsigned I)
Returns the VPValue with index I defined by the VPDef.
Definition: VPlanValue.h:406
unsigned getVPDefID() const
Definition: VPlanValue.h:426
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPValue * getStepValue() const
Definition: VPlan.h:3468
VPValue * getStartValue() const
Definition: VPlan.h:3467
void print(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.
void print(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:2070
void execute(VPTransformState &State) override
Produce a vectorized histogram operation.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPHistogramRecipe.
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:1812
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
Instruction & getInstruction() const
Definition: VPlan.h:1401
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPIRInstruction.
void extractLastLaneOfOperand(VPBuilder &Builder)
Update the recipes single operand to the last lane of the operand using Builder.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
bool hasResult() const
Definition: VPlan.h:1330
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).
unsigned getOpcode() const
Definition: VPlan.h:1307
bool onlyFirstPartUsed(const VPValue *Op) const override
Returns true if the recipe only uses the first part of operand Op.
@ ResumePhi
Creates a scalar phi in a leaf VPBB with a single predecessor in VPlan.
Definition: VPlan.h:1207
@ FirstOrderRecurrenceSplice
Definition: VPlan.h:1195
@ CanonicalIVIncrementForPart
Definition: VPlan.h:1210
@ CalculateTripCountMinusVF
Definition: VPlan.h:1208
bool isVectorToScalar() const
Returns true if this VPInstruction produces a scalar value from a vector, e.g.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the VPInstruction to O.
bool onlyFirstLaneUsed(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
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.
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition: VPlan.h:2604
VPValue * getMask() const
Return the mask used by this recipe.
Definition: VPlan.h:2610
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate the wide load or store, and shuffles.
ArrayRef< VPValue * > getStoredValues() const
Return the VPValues stored by this interleave group.
Definition: VPlan.h:2617
Instruction * getInsertPos() const
Definition: VPlan.h:2652
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPInterleaveRecipe.
unsigned getNumStoreOperands() const
Returns the number of stored operands of this interleave group.
Definition: VPlan.h:2641
static bool isVPIntrinsic(Intrinsic::ID)
In what follows, the term "input IR" refers to code that is fed into the vectorizer whereas the term ...
Definition: VPlan.h:154
static VPLane getLastLaneForVF(const ElementCount &VF)
Definition: VPlan.h:195
static VPLane getLaneFromEnd(const ElementCount &VF, unsigned Offset)
Definition: VPlan.h:181
static VPLane getFirstLane()
Definition: VPlan.h:179
void execute(VPTransformState &State) override
Generate the reduction in the loop.
void print(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 VPPartialReductionRecipe.
unsigned getOpcode() const
Get the binary op's opcode.
Definition: VPlan.h:2485
void execute(VPTransformState &State) override
Generates phi nodes for live-outs (from a replicate region) as needed to retain SSA form.
void print(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:711
bool mayReadFromMemory() const
Returns true if the recipe may read from memory.
bool mayHaveSideEffects() const
Returns true if the recipe may have side-effects.
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:736
DebugLoc getDebugLoc() const
Returns the debug location of the recipe.
Definition: VPlan.h:805
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...
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...
Class to record LLVM IR flag for a recipe along with it.
Definition: VPlan.h:922
ExactFlagsTy ExactFlags
Definition: VPlan.h:972
FastMathFlagsTy FMFs
Definition: VPlan.h:975
NonNegFlagsTy NonNegFlags
Definition: VPlan.h:974
GEPNoWrapFlags getGEPNoWrapFlags() const
Definition: VPlan.h:1142
void setFlags(Instruction *I) const
Set the IR flags for I.
Definition: VPlan.h:1103
bool hasFastMathFlags() const
Returns true if the recipe has fast-math flags.
Definition: VPlan.h:1145
DisjointFlagsTy DisjointFlags
Definition: VPlan.h:971
GEPNoWrapFlags GEPFlags
Definition: VPlan.h:973
WrapFlagsTy WrapFlags
Definition: VPlan.h:970
bool hasNoUnsignedWrap() const
Definition: VPlan.h:1149
void printFlags(raw_ostream &O) const
CmpInst::Predicate getPredicate() const
Definition: VPlan.h:1136
bool hasNoSignedWrap() const
Definition: VPlan.h:1155
FastMathFlags getFastMathFlags() const
void execute(VPTransformState &State) override
Generate the reduction in the loop.
VPValue * getEVL() const
The VPValue of the explicit vector length.
Definition: VPlan.h:2765
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void print(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:2723
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:2727
const RecurrenceDescriptor & getRecurrenceDescriptor() const
Return the recurrence decriptor for the in-loop reduction.
Definition: VPlan.h:2717
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPValue * getCondOp() const
The VPValue of the condition for the block.
Definition: VPlan.h:2729
bool isOrdered() const
Return true if the in-loop reduction is ordered.
Definition: VPlan.h:2721
VPValue * getChainOp() const
The VPValue of the scalar Chain being accumulated.
Definition: VPlan.h:2725
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:3715
const VPBlockBase * getEntry() const
Definition: VPlan.h:3751
void print(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 VPReplicateRecipe.
unsigned getOpcode() const
Definition: VPlan.h:2852
bool shouldPack() const
Returns true if the recipe is used by a widened recipe via an intervening VPPredInstPHIRecipe.
void print(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 print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPValue * getStepValue() const
Definition: VPlan.h:3525
void execute(VPTransformState &State) override
Generate the scalarized versions of the phi node as needed by their users.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate the phi/select nodes.
Instruction * getUnderlyingInstr()
Returns the underlying instruction.
Definition: VPlan.h:908
LLVM_DUMP_METHOD void dump() const
Print this VPSingleDefRecipe to dbgs() (for debugging).
This class can be used to assign names to VPValues.
Definition: VPlanValue.h:447
LLVMContext & getContext()
Return the LLVMContext used by the analysis.
Definition: VPlanAnalysis.h:65
Type * inferScalarType(const VPValue *V)
Infer the type of V. Returns the scalar type of V.
VPValue * getUnrollPartOperand(VPUser &U) const
Return the VPValue operand containing the unroll part or null if there is no such operand.
unsigned getUnrollPart(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:206
void printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const
Print the operands to O.
Definition: VPlan.cpp:1455
operand_range operands()
Definition: VPlanValue.h:263
void setOperand(unsigned I, VPValue *New)
Definition: VPlanValue.h:248
unsigned getNumOperands() const
Definition: VPlanValue.h:242
operand_iterator op_begin()
Definition: VPlanValue.h:259
VPValue * getOperand(unsigned N) const
Definition: VPlanValue.h:243
virtual bool onlyFirstLaneUsed(const VPValue *Op) const
Returns true if the VPUser only uses the first lane of operand Op.
Definition: VPlanValue.h:278
bool isDefinedOutsideLoopRegions() const
Returns true if the VPValue is defined outside any loop region.
Definition: VPlan.cpp:1416
VPRecipeBase * getDefiningRecipe()
Returns the recipe defining this VPValue or nullptr if it is not defined by a recipe,...
Definition: VPlan.cpp:123
void printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const
Definition: VPlan.cpp:1451
friend class VPInstruction
Definition: VPlanValue.h:50
bool hasMoreThanOneUniqueUser() const
Returns true if the value has more than one unique user.
Definition: VPlanValue.h:144
Value * getUnderlyingValue() const
Return the underlying Value attached to this VPValue.
Definition: VPlanValue.h:89
user_iterator user_begin()
Definition: VPlanValue.h:134
unsigned getNumUsers() const
Definition: VPlanValue.h:117
Value * getLiveInIRValue()
Returns the underlying IR value, if this VPValue is defined outside the scope of VPlan.
Definition: VPlanValue.h:178
bool isLiveIn() const
Returns true if this VPValue is a live-in, i.e. defined outside the VPlan.
Definition: VPlanValue.h:173
user_range users()
Definition: VPlanValue.h:138
void print(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 print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
Function * getCalledScalarFunction() const
Definition: VPlan.h:1760
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.
operand_range arg_operands()
Definition: VPlan.h:1764
void execute(VPTransformState &State) override
Generate a canonical vector induction variable of the vector loop, with start = {<Part*VF,...
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void print(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:1583
void execute(VPTransformState &State) override
Produce widened copies of the cast.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenCastRecipe.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override final
Print the recipe.
void execute(VPTransformState &State) override final
Produce a vp-intrinsic using the opcode and operands of the recipe, processing EVL elements.
VPValue * getEVL()
Definition: VPlan.h:1511
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate the gep nodes.
PHINode * getPHINode() const
Definition: VPlan.h:2126
VPValue * getStepValue()
Returns the step value of the induction.
Definition: VPlan.h:2123
const InductionDescriptor & getInductionDescriptor() const
Returns the induction descriptor for the recipe.
Definition: VPlan.h:2129
TruncInst * getTruncInst()
Returns the first defined value as TruncInst, if it is one or nullptr otherwise.
Definition: VPlan.h:2201
void execute(VPTransformState &State) override
Generate the vectorized and scalarized versions of the phi node as needed by their users.
Type * getScalarType() const
Returns the scalar type of the induction.
Definition: VPlan.h:2210
bool isCanonical() const
Returns true if the induction is canonical, i.e.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
bool onlyFirstLaneUsed(const VPValue *Op) const override
Returns true if the VPUser only uses the first lane of operand Op.
StringRef getIntrinsicName() const
Return to name of the intrinsic as string.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
Type * getResultType() const
Return the scalar return type of the intrinsic.
Definition: VPlan.h:1703
void execute(VPTransformState &State) override
Produce a widened version of the vector intrinsic.
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:2963
bool Reverse
Whether the consecutive accessed addresses are in reverse order.
Definition: VPlan.h:2960
bool isConsecutive() const
Return whether the loaded-from / stored-to addresses are consecutive.
Definition: VPlan.h:2999
Instruction & Ingredient
Definition: VPlan.h:2954
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:2957
VPValue * getMask() const
Return the mask used by this recipe.
Definition: VPlan.h:3013
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition: VPlan.h:3006
bool isReverse() const
Return whether the consecutive loaded/stored addresses are in reverse order.
Definition: VPlan.h:3003
void print(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.
VPValue * getFirstUnrolledPartOperand()
Returns the VPValue representing the value of this induction at the first unrolled part,...
Definition: VPlan.h:2255
void execute(VPTransformState &State) override
Generate vector values for the pointer induction.
void print(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 print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
unsigned getOpcode() const
Definition: VPlan.h:1477
unsigned getUF() const
Definition: VPlan.h:4020
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:377
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition: Value.cpp:694
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:1075
bool hasName() const
Definition: Value.h:261
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
VectorBuilder & setEVL(Value *NewExplicitVectorLength)
Definition: VectorBuilder.h:82
VectorBuilder & setMask(Value *NewMask)
Definition: VectorBuilder.h:78
Value * createVectorInstruction(unsigned Opcode, Type *ReturnTy, ArrayRef< Value * > VecOpArray, const Twine &Name=Twine())
Base class of all SIMD vector types.
Definition: DerivedTypes.h:427
ElementCount getElementCount() const
Return an ElementCount instance to represent the (possibly scalable) number of elements in the vector...
Definition: DerivedTypes.h:665
static VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
static VectorType * getDoubleElementsVectorType(VectorType *VTy)
This static method returns a VectorType with twice as many elements as the input type and the same el...
Definition: DerivedTypes.h:541
Type * getElementType() const
Definition: DerivedTypes.h:460
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition: TypeSize.h:171
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition: TypeSize.h:168
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:254
const ParentTy * getParent() const
Definition: ilist_node.h:32
self_iterator getIterator()
Definition: ilist_node.h:132
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:52
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > Tys={})
Look up the Function declaration of the intrinsic id in the Module M.
Definition: Intrinsics.cpp:731
StringRef getBaseName(ID id)
Return the LLVM name for an intrinsic, without encoded types for overloading, such as "llvm....
Definition: Intrinsics.cpp:41
bool match(Val *V, const Pattern &P)
Definition: PatternMatch.h:49
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
bool isUniformAfterVectorization(const VPValue *VPV)
Returns true if VPV is uniform after vectorization.
Definition: VPlanUtils.h:41
bool onlyFirstPartUsed(const VPValue *Def)
Returns true if only the first part of Def is used.
Definition: VPlanUtils.cpp:21
bool onlyFirstLaneUsed(const VPValue *Def)
Returns true if only the first lane of Def is used.
Definition: VPlanUtils.cpp:16
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
void ReplaceInstWithInst(BasicBlock *BB, BasicBlock::iterator &BI, Instruction *I)
Replace the instruction specified by BI with the instruction specified by I.
Value * createSimpleReduction(IRBuilderBase &B, Value *Src, RecurKind RdxKind)
Create a reduction of the given vector.
Definition: LoopUtils.cpp:1278
@ Offset
Definition: DWP.cpp:480
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1739
unsigned getLoadStoreAddressSpace(const Value *I)
A helper function that returns the address space of the pointer operand of load or store instruction.
Intrinsic::ID getMinMaxReductionIntrinsicOp(Intrinsic::ID RdxID)
Returns the min/max intrinsic used when expanding a min/max reduction.
Definition: LoopUtils.cpp:989
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:2448
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.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void interleaveComma(const Container &c, StreamT &os, UnaryFunctor each_fn)
Definition: STLExtras.h:2207
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.
Value * createMinMaxOp(IRBuilderBase &Builder, RecurKind RK, Value *Left, Value *Right)
Returns a Min/Max operation corresponding to MinMaxRecurrenceKind.
Definition: LoopUtils.cpp:1076
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1746
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::SmallVector< int, 16 > createStrideMask(unsigned Start, unsigned Stride, unsigned VF)
Create a stride shuffle mask.
cl::opt< bool > EnableVPlanNativePath("enable-vplan-native-path", cl::Hidden, cl::desc("Enable VPlan-native vectorization path with " "support for outer loop vectorization."))
Definition: VPlan.cpp:53
llvm::SmallVector< int, 16 > createReplicatedMask(unsigned ReplicationFactor, unsigned VF)
Create a mask with replicated elements.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
bool isPointerTy(const Type *T)
Definition: SPIRVUtils.h:256
Value * createOrderedReduction(IRBuilderBase &B, const RecurrenceDescriptor &Desc, Value *Src, Value *Start)
Create an ordered reduction intrinsic using the given recurrence descriptor Desc.
Definition: LoopUtils.cpp:1341
Value * createReduction(IRBuilderBase &B, const RecurrenceDescriptor &Desc, Value *Src, PHINode *OrigPhi=nullptr)
Create a generic reduction using a recurrence descriptor Desc Fast-math-flags are propagated using th...
Definition: LoopUtils.cpp:1323
llvm::SmallVector< int, 16 > createInterleaveMask(unsigned VF, unsigned NumVecs)
Create an interleave shuffle mask.
RecurKind
These are the kinds of recurrences that we support.
Definition: IVDescriptors.h:33
@ Mul
Product of integers.
@ SMax
Signed integer max implemented in terms of select(cmp()).
@ Add
Sum of integers.
bool isVectorIntrinsicWithScalarOpAtArg(Intrinsic::ID ID, unsigned ScalarOpdIdx, const TargetTransformInfo *TTI)
Identifies if the vector form of the intrinsic has a scalar operand.
Value * getRecurrenceIdentity(RecurKind K, Type *Tp, FastMathFlags FMF)
Given information about an recurrence kind, return the identity for the @llvm.vector....
Definition: LoopUtils.cpp:1270
DWARFExpression::Operation Op
Value * createStepForVF(IRBuilderBase &B, Type *Ty, ElementCount VF, int64_t Step)
Return a value for Step multiplied by VF.
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition: STLExtras.h:1903
Type * getLoadStoreType(const Value *I)
A helper function that returns the type of a load or store instruction.
InstructionCost Cost
Type * toVectorTy(Type *Scalar, ElementCount EC)
A helper function for converting Scalar types to vector types.
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.
Definition: VPlan.h:677
LLVMContext & LLVMCtx
Definition: VPlan.h:681
TargetTransformInfo::OperandValueInfo getOperandInfo(VPValue *V) const
Returns the OperandInfo for V, if it is a live-in.
Definition: VPlan.cpp:1667
bool skipCostComputation(Instruction *UI, bool IsVector) const
Return true if the cost for UI shouldn't be computed, e.g.
InstructionCost getLegacyCost(Instruction *UI, ElementCount VF) const
Return the cost for UI with VF using the legacy cost model as fallback until computing the cost of al...
TargetTransformInfo::TargetCostKind CostKind
Definition: VPlan.h:684
VPTypeAnalysis Types
Definition: VPlan.h:680
const TargetLibraryInfo & TLI
Definition: VPlan.h:679
const TargetTransformInfo & TTI
Definition: VPlan.h:678
SmallPtrSet< Instruction *, 8 > SkipCostComputation
Definition: VPlan.h:683
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 print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
BasicBlock * PrevBB
The previous IR BasicBlock created or used.
Definition: VPlan.h:339
SmallDenseMap< VPBasicBlock *, BasicBlock * > VPBB2IRBB
A mapping of each VPBasicBlock to the corresponding BasicBlock.
Definition: VPlan.h:347
BasicBlock * getPreheaderBBFor(VPRecipeBase *R)
Returns the BasicBlock* mapped to the pre-header of the loop region containing R.
Definition: VPlan.cpp:347
VPTransformState holds information passed down when "executing" a VPlan, needed for generating the ou...
Definition: VPlan.h:231
bool hasScalarValue(VPValue *Def, VPLane Lane)
Definition: VPlan.h:264
bool hasVectorValue(VPValue *Def)
Definition: VPlan.h:262
DenseMap< const SCEV *, Value * > ExpandedSCEVs
Map SCEVs to their expanded values.
Definition: VPlan.h:384
VPTypeAnalysis TypeAnalysis
VPlan-based type analysis.
Definition: VPlan.h:387
void addMetadata(Value *To, Instruction *From)
Add metadata from one instruction to another.
Definition: VPlan.cpp:360
Value * get(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:249
struct llvm::VPTransformState::CFGState CFG
std::optional< VPLane > Lane
Hold the index to generate specific scalar instructions.
Definition: VPlan.h:245
IRBuilderBase & Builder
Hold a reference to the IRBuilder used to generate output IR code.
Definition: VPlan.h:364
const TargetTransformInfo * TTI
Target Transform Info.
Definition: VPlan.h:237
void reset(VPValue *Def, Value *V)
Reset an existing vector value for Def and a given Part.
Definition: VPlan.h:285
ElementCount VF
The chosen Vectorization Factor of the loop being vectorized.
Definition: VPlan.h:240
void setDebugLocFrom(DebugLoc DL)
Set the debug location in the builder using the debug location DL.
Definition: VPlan.cpp:371
Loop * CurrentParentLoop
The parent loop object for the current scope, or nullptr.
Definition: VPlan.h:373
void set(VPValue *Def, Value *V, bool IsScalar=false)
Set the generated vector Value for a given VPValue, if IsScalar is false.
Definition: VPlan.h:274
void execute(VPTransformState &State) override
Generate the wide load or gather.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenLoadEVLRecipe.
VPValue * getEVL() const
Return the EVL operand.
Definition: VPlan.h:3083
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate a wide load or gather.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
bool isInvariantCond() const
Definition: VPlan.h:1855
VPValue * getCond() const
Definition: VPlan.h:1851
void print(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 VPWidenSelectRecipe.
void execute(VPTransformState &State) override
Produce a widened version of the select instruction.
VPValue * getStoredValue() const
Return the address accessed by this recipe.
Definition: VPlan.h:3162
void execute(VPTransformState &State) override
Generate the wide store or scatter.
void print(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 VPWidenStoreEVLRecipe.
VPValue * getEVL() const
Return the EVL operand.
Definition: VPlan.h:3165
void execute(VPTransformState &State) override
Generate a wide store or scatter.
VPValue * getStoredValue() const
Return the value stored by this recipe.
Definition: VPlan.h:3127
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.