LLVM 24.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 "VPlanHelpers.h"
17#include "VPlanPatternMatch.h"
18#include "VPlanUtils.h"
19#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/Twine.h"
27#include "llvm/IR/BasicBlock.h"
28#include "llvm/IR/IRBuilder.h"
29#include "llvm/IR/Instruction.h"
31#include "llvm/IR/Intrinsics.h"
33#include "llvm/IR/Type.h"
34#include "llvm/IR/Value.h"
37#include "llvm/Support/Debug.h"
38#include "llvm/Support/Format.h"
42#include <cassert>
43
44using namespace llvm;
45using namespace llvm::VPlanPatternMatch;
46
47#define LV_NAME "loop-vectorize"
48#define DEBUG_TYPE LV_NAME
49
50#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
51// It is sometimes necessary to disable printing of metadata in tests in order
52// to avoid non-deterministic behaviour due to metadata introduced by VPlan
53// that wasn't present in the original scalar IR.
55 "vplan-print-metadata", cl::init(true), cl::Hidden,
56 cl::desc("Controls the printing of recipe metadata when debugging."));
57#endif
58
59namespace llvm {
61} // namespace llvm
62
64 switch (getVPRecipeID()) {
65 case VPExpressionSC:
66 return cast<VPExpressionRecipe>(this)->mayReadOrWriteMemory();
67 case VPInstructionSC: {
68 auto *VPI = cast<VPInstruction>(this);
69 // Loads read from memory but don't write to memory.
70 if (VPI->getOpcode() == Instruction::Load)
71 return false;
72 return VPI->opcodeMayReadOrWriteFromMemory();
73 }
74 case VPInterleaveEVLSC:
75 case VPInterleaveSC:
76 return cast<VPInterleaveBase>(this)->getNumStoreOperands() > 0;
77 case VPWidenStoreEVLSC:
78 case VPWidenStoreSC:
79 return true;
80 case VPReplicateSC:
81 return cast<Instruction>(getVPSingleValue()->getUnderlyingValue())
82 ->mayWriteToMemory();
83 case VPWidenCallSC:
84 return !cast<VPWidenCallRecipe>(this)
85 ->getCalledScalarFunction()
86 ->onlyReadsMemory();
87 case VPWidenMemIntrinsicSC:
88 case VPWidenIntrinsicSC:
89 return cast<VPWidenIntrinsicRecipe>(this)->mayWriteToMemory();
90 case VPActiveLaneMaskPHISC:
91 case VPCurrentIterationPHISC:
92 case VPBranchOnMaskSC:
93 case VPDerivedIVSC:
94 case VPFirstOrderRecurrencePHISC:
95 case VPReductionPHISC:
96 case VPScalarIVStepsSC:
97 case VPPredInstPHISC:
98 case VPExpandSCEVSC:
99 return false;
100 case VPBlendSC:
101 case VPReductionEVLSC:
102 case VPReductionSC:
103 case VPVectorPointerSC:
104 case VPWidenCanonicalIVSC:
105 case VPWidenCastSC:
106 case VPWidenGEPSC:
107 case VPWidenIntOrFpInductionSC:
108 case VPWidenLoadEVLSC:
109 case VPWidenLoadSC:
110 case VPWidenPHISC:
111 case VPWidenPointerInductionSC:
112 case VPWidenSC: {
113 const Instruction *I =
114 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
115 (void)I;
116 assert((!I || !I->mayWriteToMemory()) &&
117 "underlying instruction may write to memory");
118 return false;
119 }
120 default:
121 return true;
122 }
123}
124
126 switch (getVPRecipeID()) {
127 case VPExpressionSC:
128 return cast<VPExpressionRecipe>(this)->mayReadOrWriteMemory();
129 case VPInstructionSC:
130 return cast<VPInstruction>(this)->opcodeMayReadOrWriteFromMemory();
131 case VPWidenLoadEVLSC:
132 case VPWidenLoadSC:
133 return true;
134 case VPReplicateSC:
135 return cast<Instruction>(getVPSingleValue()->getUnderlyingValue())
136 ->mayReadFromMemory();
137 case VPWidenCallSC:
138 return !cast<VPWidenCallRecipe>(this)
139 ->getCalledScalarFunction()
140 ->onlyWritesMemory();
141 case VPWidenMemIntrinsicSC:
142 case VPWidenIntrinsicSC:
143 return cast<VPWidenIntrinsicRecipe>(this)->mayReadFromMemory();
144 case VPBranchOnMaskSC:
145 case VPDerivedIVSC:
146 case VPCurrentIterationPHISC:
147 case VPFirstOrderRecurrencePHISC:
148 case VPReductionPHISC:
149 case VPPredInstPHISC:
150 case VPScalarIVStepsSC:
151 case VPWidenStoreEVLSC:
152 case VPWidenStoreSC:
153 case VPExpandSCEVSC:
154 return false;
155 case VPBlendSC:
156 case VPReductionEVLSC:
157 case VPReductionSC:
158 case VPVectorPointerSC:
159 case VPWidenCanonicalIVSC:
160 case VPWidenCastSC:
161 case VPWidenGEPSC:
162 case VPWidenIntOrFpInductionSC:
163 case VPWidenPHISC:
164 case VPWidenPointerInductionSC:
165 case VPWidenSC: {
166 const Instruction *I =
167 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
168 (void)I;
169 assert((!I || !I->mayReadFromMemory()) &&
170 "underlying instruction may read from memory");
171 return false;
172 }
173 default:
174 // FIXME: Return false if the recipe represents an interleaved store.
175 return true;
176 }
177}
178
180 switch (getVPRecipeID()) {
181 case VPExpressionSC:
182 return cast<VPExpressionRecipe>(this)->mayHaveSideEffects();
183 case VPActiveLaneMaskPHISC:
184 case VPDerivedIVSC:
185 case VPCurrentIterationPHISC:
186 case VPFirstOrderRecurrencePHISC:
187 case VPReductionPHISC:
188 case VPPredInstPHISC:
189 case VPVectorEndPointerSC:
190 case VPExpandSCEVSC:
191 return false;
192 case VPInstructionSC: {
193 auto *VPI = cast<VPInstruction>(this);
194 return mayWriteToMemory() ||
195 VPI->getOpcode() == VPInstruction::BranchOnCount ||
196 VPI->getOpcode() == VPInstruction::BranchOnCond ||
197 VPI->getOpcode() == VPInstruction::BranchOnTwoConds;
198 }
199 case VPWidenCallSC: {
200 Function *Fn = cast<VPWidenCallRecipe>(this)->getCalledScalarFunction();
201 return mayWriteToMemory() || !Fn->doesNotThrow() || !Fn->willReturn();
202 }
203 case VPWidenMemIntrinsicSC:
204 case VPWidenIntrinsicSC:
205 return cast<VPWidenIntrinsicRecipe>(this)->mayHaveSideEffects();
206 case VPBlendSC:
207 case VPReductionEVLSC:
208 case VPReductionSC:
209 case VPScalarIVStepsSC:
210 case VPVectorPointerSC:
211 case VPWidenCanonicalIVSC:
212 case VPWidenCastSC:
213 case VPWidenGEPSC:
214 case VPWidenIntOrFpInductionSC:
215 case VPWidenPHISC:
216 case VPWidenPointerInductionSC:
217 case VPWidenSC: {
218 const Instruction *I =
219 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
220 (void)I;
221 assert((!I || !I->mayHaveSideEffects()) &&
222 "underlying instruction has side-effects");
223 return false;
224 }
225 case VPInterleaveEVLSC:
226 case VPInterleaveSC:
227 return mayWriteToMemory();
228 case VPWidenLoadEVLSC:
229 case VPWidenLoadSC:
230 case VPWidenStoreEVLSC:
231 case VPWidenStoreSC:
232 assert(
233 cast<VPWidenMemoryRecipe>(this)->getIngredient().mayHaveSideEffects() ==
235 "mayHaveSideffects result for ingredient differs from this "
236 "implementation");
237 return mayWriteToMemory();
238 case VPReplicateSC: {
239 auto *R = cast<VPReplicateRecipe>(this);
240 return R->getUnderlyingInstr()->mayHaveSideEffects();
241 }
242 default:
243 return true;
244 }
245}
246
248 switch (getVPRecipeID()) {
249 default:
250 return false;
251 case VPInstructionSC: {
252 unsigned Opcode = cast<VPInstruction>(this)->getOpcode();
253 if (Instruction::isCast(Opcode))
254 return true;
255
256 switch (Opcode) {
257 default:
258 return false;
259 case Instruction::Add:
260 case Instruction::Sub:
261 case Instruction::Mul:
262 case Instruction::GetElementPtr:
263 return true;
264 }
265 }
266 }
267}
268
270 assert(!Parent && "Recipe already in some VPBasicBlock");
271 assert(InsertPos->getParent() &&
272 "Insertion position not in any VPBasicBlock");
273 InsertPos->getParent()->insert(this, InsertPos->getIterator());
274}
275
276void VPRecipeBase::insertBefore(VPBasicBlock &BB,
278 assert(!Parent && "Recipe already in some VPBasicBlock");
279 assert(I == BB.end() || I->getParent() == &BB);
280 BB.insert(this, I);
281}
282
284 assert(!Parent && "Recipe already in some VPBasicBlock");
285 assert(InsertPos->getParent() &&
286 "Insertion position not in any VPBasicBlock");
287 InsertPos->getParent()->insert(this, std::next(InsertPos->getIterator()));
288}
289
291 assert(getParent() && "Recipe not in any VPBasicBlock");
293 Parent = nullptr;
294}
295
297 assert(getParent() && "Recipe not in any VPBasicBlock");
299}
300
303 insertAfter(InsertPos);
304}
305
311
313 // Get the underlying instruction for the recipe, if there is one. It is used
314 // to
315 // * decide if cost computation should be skipped for this recipe,
316 // * apply forced target instruction cost.
317 Instruction *UI = nullptr;
318 if (auto *S = dyn_cast<VPSingleDefRecipe>(this))
319 UI = dyn_cast_or_null<Instruction>(S->getUnderlyingValue());
320 else if (auto *IG = dyn_cast<VPInterleaveBase>(this))
321 UI = IG->getInsertPos();
322 else if (auto *WidenMem = dyn_cast<VPWidenMemoryRecipe>(this))
323 UI = &WidenMem->getIngredient();
324
325 InstructionCost RecipeCost;
326 if (UI && Ctx.skipCostComputation(UI, VF.isVector())) {
327 RecipeCost = 0;
328 } else {
329 RecipeCost = computeCost(VF, Ctx);
330 if (ForceTargetInstructionCost.getNumOccurrences() > 0 &&
331 RecipeCost.isValid()) {
332 // VPDerivedIVRecipe and VPScalarIVStepsRecipe never have underlying
333 // instructions.
336 else
337 RecipeCost = InstructionCost(0);
338 }
339 }
340
341 LLVM_DEBUG({
342 dbgs() << "Cost of " << RecipeCost << " for VF " << VF << ": ";
343 if (VPSlotTracker *SlotTracker = Ctx.getSlotTracker()) {
344 print(dbgs(), "", *SlotTracker);
345 dbgs() << "\n";
346 } else {
347 dump();
348 }
349 });
350 return RecipeCost;
351}
352
354 VPCostContext &Ctx) const {
355 llvm_unreachable("subclasses should implement computeCost");
356}
357
359 return (getVPRecipeID() >= VPFirstPHISC && getVPRecipeID() <= VPLastPHISC) ||
361}
362
364 assert(OpType == Other.OpType && "OpType must match");
365 switch (OpType) {
366 case OperationType::OverflowingBinOp:
367 WrapFlags.HasNUW &= Other.WrapFlags.HasNUW;
368 WrapFlags.HasNSW &= Other.WrapFlags.HasNSW;
369 break;
370 case OperationType::Trunc:
371 TruncFlags.HasNUW &= Other.TruncFlags.HasNUW;
372 TruncFlags.HasNSW &= Other.TruncFlags.HasNSW;
373 break;
374 case OperationType::DisjointOp:
375 DisjointFlags.IsDisjoint &= Other.DisjointFlags.IsDisjoint;
376 break;
377 case OperationType::PossiblyExactOp:
378 ExactFlags.IsExact &= Other.ExactFlags.IsExact;
379 break;
380 case OperationType::GEPOp:
381 GEPFlagsStorage &= Other.GEPFlagsStorage;
382 break;
383 case OperationType::FPMathOp:
384 case OperationType::FCmp:
385 assert((OpType != OperationType::FCmp ||
386 FCmpFlags.CmpPredStorage == Other.FCmpFlags.CmpPredStorage) &&
387 "Cannot drop CmpPredicate");
388 getFMFsRef() = getFastMathFlagsOrNone() & Other.getFastMathFlagsOrNone();
389 break;
390 case OperationType::NonNegOp:
391 NonNegFlags.NonNeg &= Other.NonNegFlags.NonNeg;
392 break;
393 case OperationType::Cmp:
394 assert(CmpPredStorage == Other.CmpPredStorage &&
395 "Cannot drop CmpPredicate");
396 break;
397 case OperationType::ReductionOp:
398 assert(ReductionFlags.Kind == Other.ReductionFlags.Kind &&
399 "Cannot change RecurKind");
400 assert(ReductionFlags.IsOrdered == Other.ReductionFlags.IsOrdered &&
401 "Cannot change IsOrdered");
402 assert(ReductionFlags.IsInLoop == Other.ReductionFlags.IsInLoop &&
403 "Cannot change IsInLoop");
404 getFMFsRef() = getFastMathFlagsOrNone() & Other.getFastMathFlagsOrNone();
405 break;
406 case OperationType::Other:
407 break;
408 }
409}
410
412 if (!hasFastMathFlags())
413 return {};
414 const FastMathFlagsTy &F = getFMFsRef();
415 FastMathFlags Res;
416 Res.setAllowReassoc(F.AllowReassoc);
417 Res.setNoNaNs(F.NoNaNs);
418 Res.setNoInfs(F.NoInfs);
419 Res.setNoSignedZeros(F.NoSignedZeros);
420 Res.setAllowReciprocal(F.AllowReciprocal);
421 Res.setAllowContract(F.AllowContract);
422 Res.setApproxFunc(F.ApproxFunc);
423 return Res;
424}
425
426#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
428
429void VPRecipeBase::print(raw_ostream &O, const Twine &Indent,
430 VPSlotTracker &SlotTracker) const {
431 printRecipe(O, Indent, SlotTracker);
432 if (auto DL = getDebugLoc()) {
433 O << ", !dbg ";
434 DL.print(O);
435 }
436
437 if (auto *Metadata = dyn_cast<VPIRMetadata>(this))
439}
440#endif
441
443 : VPSingleDefRecipe(VPRecipeBase::VPExpandSCEVSC, {}, Expr->getType()),
444 Expr(Expr) {}
445
446/// For call VPInstruction operands, return the operand index of the called
447/// function. The function is either the last operand (for unmasked calls) or
448/// the second-to-last operand (for masked calls).
450 unsigned NumOps = Operands.size();
451 auto *LastOp = dyn_cast<VPIRValue>(Operands[NumOps - 1]);
452 if (LastOp && isa<Function>(LastOp->getValue()))
453 return NumOps - 1;
455 "expected function operand");
456 return NumOps - 2;
457}
458
459/// For call VPInstruction operands, return the called function.
464
467 assert(!Operands.empty() &&
468 "zero-operand VPInstruction opcodes must pass explicit ResultTy");
469 // Assert operand \p Idx (if present and typed) has type \p ExpectedTy.
470 [[maybe_unused]] auto AssertOperandType = [&Operands](unsigned Idx,
471 Type *ExpectedTy) {
472 if (!ExpectedTy || Operands.size() <= Idx)
473 return;
474 [[maybe_unused]] Type *OpTy = Operands[Idx]->getScalarType();
475 assert((!OpTy || OpTy == ExpectedTy) &&
476 "different types inferred for different operands");
477 };
478
479 Type *Op0Ty = Operands[0]->getScalarType();
480 LLVMContext &Ctx = Op0Ty->getContext();
481 switch (Opcode) {
483 assert(Op0Ty->isIntegerTy(1) && "expected bool condition");
484 return Type::getVoidTy(Ctx);
486 assert(Op0Ty->isIntegerTy(1) && "expected bool condition");
487 AssertOperandType(1, IntegerType::get(Ctx, 1));
488 return Type::getVoidTy(Ctx);
490 assert(Op0Ty->isIntegerTy() && "expected integer operand");
491 AssertOperandType(1, Op0Ty);
492 return Type::getVoidTy(Ctx);
494 assert(Op0Ty->isIntegerTy() && "expected integer operand");
495 for (unsigned Idx = 1; Idx != Operands.size(); ++Idx)
496 AssertOperandType(Idx, Op0Ty);
497 return Op0Ty;
498 case Instruction::Switch:
499 for (unsigned Idx = 1; Idx != Operands.size(); ++Idx)
500 AssertOperandType(Idx, Op0Ty);
501 return Type::getVoidTy(Ctx);
502 case Instruction::Store:
503 return Type::getVoidTy(Ctx);
504 case Instruction::ICmp:
505 assert(Op0Ty->isIntOrPtrTy() && "expected integer or pointer operand");
506 AssertOperandType(1, Op0Ty);
507 return IntegerType::get(Ctx, 1);
508 case Instruction::FCmp:
509 assert(Op0Ty->isFloatingPointTy() && "expected floating-point operand");
510 AssertOperandType(1, Op0Ty);
511 return IntegerType::get(Ctx, 1);
514 assert(Op0Ty->isIntegerTy() && "expected integer operand");
515 AssertOperandType(1, Op0Ty);
516 return IntegerType::get(Ctx, 1);
518 assert(Op0Ty->isIntegerTy(1) && "expected bool operand");
519 return IntegerType::get(Ctx, 1);
522 assert(Op0Ty->isIntegerTy(1) && "expected bool operand");
523 AssertOperandType(1, Op0Ty);
524 return IntegerType::get(Ctx, 1);
526 assert(Op0Ty->isIntegerTy(1) && "expected bool operand");
527 for (unsigned Idx = 1; Idx != Operands.size(); ++Idx)
528 AssertOperandType(Idx, Op0Ty);
529 return IntegerType::get(Ctx, 1);
531 assert(Op0Ty->isIntegerTy() && "expected integer operand");
532 return IntegerType::get(Ctx, 32);
533 case Instruction::Select: {
534 assert((!Op0Ty || Op0Ty->isIntegerTy(1)) &&
535 "select condition must be bool");
536 Type *Op1Ty = Operands[1]->getScalarType();
537 AssertOperandType(2, Op1Ty);
538 return Op1Ty;
539 }
540 case Instruction::InsertElement:
541 // The inserted scalar (operand 1) must match the vector element type;
542 // operand 2 must be an integer.
543 AssertOperandType(1, Op0Ty);
544 assert(Operands[2]->getScalarType()->isIntegerTy() &&
545 "expected integer operand");
546 return Op0Ty;
548 // The start value and the identity value (operands 0 and 1) fill the same
549 // vector and must match in type; operand 2 is the scaling factor.
550 AssertOperandType(1, Op0Ty);
551 return Op0Ty;
553 assert(Operands.size() >= 2 && "ExtractLane requires a lane operand and "
554 "at least one source vector operand");
555 // Operand 0 is the lane index, used for integer arithmetic.
556 assert(Op0Ty->isIntegerTy() && "expected integer operand");
557 Type *Op1Ty = Operands[1]->getScalarType();
558 for (unsigned Idx = 2; Idx != Operands.size(); ++Idx)
559 AssertOperandType(Idx, Op1Ty);
560 return Op1Ty;
561 }
564 assert(Operands[0]->getScalarType()->isPointerTy() &&
565 "expected pointer operand");
566 assert(Operands[1]->getScalarType()->isIntegerTy() &&
567 "expected integer operand");
568 return Op0Ty;
569 case Instruction::ExtractValue: {
570 assert(Operands.size() == 2 && "expected single level extractvalue");
571 auto *StructTy = cast<StructType>(Op0Ty);
572 return StructTy->getTypeAtIndex(
573 cast<VPConstantInt>(Operands[1])->getZExtValue());
574 }
579 case Instruction::Load:
580 case Instruction::Alloca:
581 llvm_unreachable("type must be passed explicitly");
582 case Instruction::Call:
584 default:
585 if (Instruction::isCast(Opcode))
586 llvm_unreachable("type must be passed explicitly");
587 break;
588 }
589
590 // Opcodes that require all operands to share the same scalar type as the
591 // result.
592 bool AllOperandsSameType =
593 Instruction::isBinaryOp(Opcode) ||
597 Opcode);
598 if (AllOperandsSameType)
599 for (unsigned Idx = 1; Idx != Operands.size(); ++Idx)
600 AssertOperandType(Idx, Op0Ty);
601
602 return Op0Ty;
603}
604
607 unsigned Opcode = I->getOpcode();
608 if (Instruction::isCast(Opcode) ||
609 is_contained(ArrayRef<unsigned>({Instruction::ExtractValue,
610 Instruction::Load, Instruction::Alloca}),
611 Opcode))
612 return I->getType();
614}
615
617 const VPIRFlags &Flags, const VPIRMetadata &MD,
618 DebugLoc DL, const Twine &Name, Type *ResultTy)
620 VPRecipeBase::VPInstructionSC, Operands,
621 ResultTy ? ResultTy
623 Flags, DL),
624 VPIRMetadata(MD), Opcode(Opcode), Name(Name.str()) {
626 "Set flags not supported for the provided opcode");
628 "Opcode requires specific flags to be set");
632 "number of operands does not match opcode");
633}
634
636 if (Instruction::isUnaryOp(Opcode) || Instruction::isCast(Opcode))
637 return 1;
638
639 if (Instruction::isBinaryOp(Opcode))
640 return 2;
641
642 switch (Opcode) {
645 return 0;
646 case Instruction::Alloca:
647 case Instruction::ExtractValue:
648 case Instruction::Freeze:
649 case Instruction::Load:
662 return 1;
663 case Instruction::ICmp:
664 case Instruction::FCmp:
665 case Instruction::ExtractElement:
666 case Instruction::Store:
678 return 2;
679 case Instruction::InsertElement:
680 case Instruction::Select:
683 return 3;
684 case Instruction::Call:
685 return getCalledFnOperandIndex(operands()) + 1;
686 case Instruction::GetElementPtr:
687 case Instruction::PHI:
688 case Instruction::Switch:
689 case Instruction::AtomicRMW:
690 case Instruction::AtomicCmpXchg:
691 case Instruction::Fence:
702 // Cannot determine the number of operands from the opcode.
703 return -1u;
704 }
705 llvm_unreachable("all cases should be handled above");
706}
707
709 return Opcode == VPInstruction::Unpack ||
711}
712
713bool VPInstruction::canGenerateScalarForFirstLane() const {
715 return true;
717 return true;
718 switch (Opcode) {
719 case Instruction::Freeze:
720 case Instruction::ICmp:
721 case Instruction::PHI:
722 case Instruction::Select:
731 return true;
732 default:
733 return false;
734 }
735}
736
738 if (Kind == RecurKind::Sub)
739 return Instruction::Add;
740 if (Kind == RecurKind::FSub)
741 return Instruction::FAdd;
742 llvm_unreachable("RecurKind should be Sub/FSub.");
743}
744
745Value *VPInstruction::generate(VPTransformState &State) {
746 IRBuilderBase &Builder = State.Builder;
747
749 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
750 Value *A = State.get(getOperand(0), OnlyFirstLaneUsed);
751 Value *B = State.get(getOperand(1), OnlyFirstLaneUsed);
752 auto *Res =
753 Builder.CreateBinOp((Instruction::BinaryOps)getOpcode(), A, B, Name);
754 if (auto *I = dyn_cast<Instruction>(Res))
755 applyFlags(*I);
756 return Res;
757 }
759 Value *Op = State.get(getOperand(0), VPLane(0));
761 getScalarType());
762 if (auto *CastOp = dyn_cast<Instruction>(Res)) {
763 applyFlags(*CastOp);
764 applyMetadata(*CastOp);
765 }
766 return Res;
767 }
768
769 switch (getOpcode()) {
770 case VPInstruction::Not: {
771 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
772 Value *A = State.get(getOperand(0), OnlyFirstLaneUsed);
773 return Builder.CreateNot(A, Name);
774 }
775 case Instruction::ExtractElement: {
776 assert(State.VF.isVector() && "Only extract elements from vectors");
777 if (auto *Idx = dyn_cast<VPConstantInt>(getOperand(1)))
778 return State.get(getOperand(0), VPLane(Idx->getZExtValue()));
779 Value *Vec = State.get(getOperand(0));
780 Value *Idx = State.get(getOperand(1), /*IsScalar=*/true);
781 return Builder.CreateExtractElement(Vec, Idx, Name);
782 }
783 case Instruction::InsertElement: {
784 assert(State.VF.isVector() && "Can only insert elements into vectors");
785 Value *Vec = State.get(getOperand(0), /*IsScalar=*/false);
786 Value *Elt = State.get(getOperand(1), /*IsScalar=*/true);
787 Value *Idx = State.get(getOperand(2), /*IsScalar=*/true);
788 return Builder.CreateInsertElement(Vec, Elt, Idx, Name);
789 }
790 case Instruction::Freeze: {
792 return Builder.CreateFreeze(Op, Name);
793 }
794 case Instruction::FCmp:
795 case Instruction::ICmp: {
796 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
797 Value *A = State.get(getOperand(0), OnlyFirstLaneUsed);
798 Value *B = State.get(getOperand(1), OnlyFirstLaneUsed);
799 return Builder.CreateCmp(getPredicate(), A, B, Name);
800 }
801 case Instruction::PHI: {
802 llvm_unreachable("should be handled by VPPhi::execute");
803 }
804 case Instruction::Select: {
805 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
806 Value *Cond =
807 State.get(getOperand(0),
808 OnlyFirstLaneUsed || vputils::isSingleScalar(getOperand(0)));
809 Value *Op1 = State.get(getOperand(1), OnlyFirstLaneUsed);
810 Value *Op2 = State.get(getOperand(2), OnlyFirstLaneUsed);
811 return Builder.CreateSelectFMF(Cond, Op1, Op2, getFastMathFlagsOrNone(),
812 Name);
813 }
816 // Get first lane of vector induction variable.
817 Value *VIVElem0 = State.get(getOperand(0), VPLane(0));
818 // Get the original loop tripcount.
819 Value *ScalarTC = State.get(getOperand(1), VPLane(0));
820
821 uint64_t Multiplier =
823 ? cast<VPConstantInt>(getOperand(2))->getZExtValue()
824 : 1;
825
826 // If this part of the active lane mask is scalar, generate the CMP directly
827 // to avoid unnecessary extracts.
828 if (State.VF.isScalar() && Multiplier == 1)
829 return Builder.CreateCmp(CmpInst::Predicate::ICMP_ULT, VIVElem0, ScalarTC,
830 Name);
831
832 auto *PredTy = VectorType::get(Builder.getInt1Ty(), State.VF * Multiplier);
833 return Builder.CreateIntrinsic(Intrinsic::get_active_lane_mask,
834 {PredTy, ScalarTC->getType()},
835 {VIVElem0, ScalarTC}, nullptr, Name);
836 }
838 Value *Op = State.get(getOperand(0));
839 auto *VecTy = cast<VectorType>(Op->getType());
840 assert(VecTy->getScalarSizeInBits() == 1 &&
841 "NumActiveLanes only implemented for i1 vectors");
842
843 Type *Ty = getScalarType();
844 Value *ZExt = Builder.CreateCast(
845 Instruction::ZExt, Op, VectorType::get(Ty, VecTy->getElementCount()));
846 Value *NumActive =
847 Builder.CreateUnaryIntrinsic(Intrinsic::vector_reduce_add, ZExt);
848 return NumActive;
849 }
851 // Generate code to combine the previous and current values in vector v3.
852 //
853 // vector.ph:
854 // v_init = vector(..., ..., ..., a[-1])
855 // br vector.body
856 //
857 // vector.body
858 // i = phi [0, vector.ph], [i+4, vector.body]
859 // v1 = phi [v_init, vector.ph], [v2, vector.body]
860 // v2 = a[i, i+1, i+2, i+3];
861 // v3 = vector(v1(3), v2(0, 1, 2))
862
863 auto *V1 = State.get(getOperand(0));
864 if (!V1->getType()->isVectorTy())
865 return V1;
866 Value *V2 = State.get(getOperand(1));
867 return Builder.CreateVectorSpliceRight(V1, V2, 1, Name);
868 }
870 // TODO: Restructure this code with an explicit remainder loop, vsetvli can
871 // be outside of the main loop.
872 Value *AVL = State.get(getOperand(0), /*IsScalar*/ true);
873 // Compute EVL
874 assert(AVL->getType()->isIntegerTy() &&
875 "Requested vector length should be an integer.");
876
877 assert(State.VF.isScalable() && "Expected scalable vector factor.");
878 Value *VFArg = Builder.getInt32(State.VF.getKnownMinValue());
879
880 Value *EVL = Builder.CreateIntrinsic(
881 Builder.getInt32Ty(), Intrinsic::experimental_get_vector_length,
882 {AVL, VFArg, Builder.getTrue()});
883 return EVL;
884 }
886 Value *Cond = State.get(getOperand(0), VPLane(0));
887 // Replace the temporary unreachable terminator with a new conditional
888 // branch, hooking it up to backward destination for latch blocks now, and
889 // to forward destination(s) later when they are created.
890 // Second successor may be backwards - iff it is already in VPBB2IRBB.
891 VPBasicBlock *SecondVPSucc =
892 cast<VPBasicBlock>(getParent()->getSuccessors()[1]);
893 BasicBlock *SecondIRSucc = State.CFG.VPBB2IRBB.lookup(SecondVPSucc);
894 BasicBlock *IRBB = State.CFG.VPBB2IRBB[getParent()];
895 auto *Br = Builder.CreateCondBr(Cond, IRBB, SecondIRSucc);
896 // First successor is always forward, reset it to nullptr.
897 Br->setSuccessor(0, nullptr);
899 applyMetadata(*Br);
900 return Br;
901 }
903 return Builder.CreateVectorSplat(
904 State.VF, State.get(getOperand(0), /*IsScalar*/ true), "broadcast");
905 }
907 // For struct types, we need to build a new 'wide' struct type, where each
908 // element is widened, i.e., we create a struct of vectors.
909 auto *StructTy = cast<StructType>(getOperand(0)->getScalarType());
910 Value *Res = PoisonValue::get(toVectorizedTy(StructTy, State.VF));
911 for (const auto &[LaneIndex, Op] : enumerate(operands())) {
912 for (unsigned FieldIndex = 0; FieldIndex != StructTy->getNumElements();
913 FieldIndex++) {
914 Value *ScalarValue =
915 Builder.CreateExtractValue(State.get(Op, true), FieldIndex);
916 Value *VectorValue = Builder.CreateExtractValue(Res, FieldIndex);
917 VectorValue =
918 Builder.CreateInsertElement(VectorValue, ScalarValue, LaneIndex);
919 Res = Builder.CreateInsertValue(Res, VectorValue, FieldIndex);
920 }
921 }
922 return Res;
923 }
925 auto *ScalarTy = getOperand(0)->getScalarType();
926 auto NumOfElements = ElementCount::getFixed(getNumOperands());
927 Value *Res = PoisonValue::get(toVectorizedTy(ScalarTy, NumOfElements));
928 for (const auto &[Idx, Op] : enumerate(operands()))
929 Res = Builder.CreateInsertElement(Res, State.get(Op, true),
930 Builder.getInt64(Idx));
931 return Res;
932 }
934 if (State.VF.isScalar())
935 return State.get(getOperand(0), true);
936 IRBuilderBase::FastMathFlagGuard FMFG(Builder);
938 // If this start vector is scaled then it should produce a vector with fewer
939 // elements than the VF.
940 ElementCount VF = State.VF.divideCoefficientBy(
941 cast<VPConstantInt>(getOperand(2))->getZExtValue());
942 auto *Iden = Builder.CreateVectorSplat(VF, State.get(getOperand(1), true));
943 return Builder.CreateInsertElement(Iden, State.get(getOperand(0), true),
944 Builder.getInt64(0));
945 }
947 RecurKind RK = getRecurKind();
948 bool IsOrdered = isReductionOrdered();
949 bool IsInLoop = isReductionInLoop();
951 "FindIV should use min/max reduction kinds");
952
953 // The recipe may have multiple operands to be reduced together.
954 unsigned NumOperandsToReduce = getNumOperands();
955 SmallVector<Value *, 2> RdxParts(NumOperandsToReduce);
956 for (unsigned Part = 0; Part < NumOperandsToReduce; ++Part)
957 RdxParts[Part] = State.get(getOperand(Part), IsInLoop);
958
959 IRBuilderBase::FastMathFlagGuard FMFG(Builder);
961
962 // Reduce multiple operands into one.
963 Value *ReducedPartRdx = RdxParts[0];
964 if (IsOrdered) {
965 ReducedPartRdx = RdxParts[NumOperandsToReduce - 1];
966 } else {
967 // Floating-point operations should have some FMF to enable the reduction.
968 for (unsigned Part = 1; Part < NumOperandsToReduce; ++Part) {
969 Value *RdxPart = RdxParts[Part];
971 ReducedPartRdx = createMinMaxOp(Builder, RK, ReducedPartRdx, RdxPart);
972 else {
973 // For sub-recurrences, each part's reduction variable is already
974 // negative, we need to do: reduce.add(-acc_uf0 + -acc_uf1)
978 : (Instruction::BinaryOps)RecurrenceDescriptor::getOpcode(RK);
979 ReducedPartRdx =
980 Builder.CreateBinOp(Opcode, RdxPart, ReducedPartRdx, "bin.rdx");
981 }
982 }
983 }
984
985 // Create the reduction after the loop. Note that inloop reductions create
986 // the target reduction in the loop using a Reduction recipe.
987 if (State.VF.isVector() && !IsInLoop) {
988 // TODO: Support in-order reductions based on the recurrence descriptor.
989 // All ops in the reduction inherit fast-math-flags from the recurrence
990 // descriptor.
991 ReducedPartRdx = createSimpleReduction(Builder, ReducedPartRdx, RK);
992 }
993
994 return ReducedPartRdx;
995 }
998 unsigned Offset =
1000 Value *Res;
1001 if (State.VF.isVector()) {
1002 assert(Offset <= State.VF.getKnownMinValue() &&
1003 "invalid offset to extract from");
1004 // Extract lane VF - Offset from the operand.
1005 Res = State.get(getOperand(0), VPLane::getLaneFromEnd(State.VF, Offset));
1006 } else {
1007 // TODO: Remove ExtractLastLane for scalar VFs.
1008 assert(Offset <= 1 && "invalid offset to extract from");
1009 Res = State.get(getOperand(0));
1010 }
1011 if (isa<ExtractElementInst>(Res))
1012 Res->setName(Name);
1013 return Res;
1014 }
1016 Value *A = State.get(getOperand(0));
1017 Value *B = State.get(getOperand(1));
1018 return Builder.CreateLogicalAnd(A, B, Name);
1019 }
1021 Value *A = State.get(getOperand(0));
1022 Value *B = State.get(getOperand(1));
1023 return Builder.CreateLogicalOr(A, B, Name);
1024 }
1025 case VPInstruction::PtrAdd: {
1026 assert((State.VF.isScalar() || vputils::onlyFirstLaneUsed(this)) &&
1027 "can only generate first lane for PtrAdd");
1028 Value *Ptr = State.get(getOperand(0), VPLane(0));
1029 Value *Addend = State.get(getOperand(1), VPLane(0));
1030 return Builder.CreatePtrAdd(Ptr, Addend, Name, getGEPNoWrapFlags());
1031 }
1033 Value *Ptr =
1035 Value *Addend = State.get(getOperand(1));
1036 return Builder.CreatePtrAdd(Ptr, Addend, Name, getGEPNoWrapFlags());
1037 }
1038 case VPInstruction::AnyOf: {
1039 Value *Res = Builder.CreateFreeze(State.get(getOperand(0)));
1040 for (VPValue *Op : drop_begin(operands()))
1041 Res = Builder.CreateOr(Res, Builder.CreateFreeze(State.get(Op)));
1042 return State.VF.isScalar() ? Res : Builder.CreateOrReduce(Res);
1043 }
1045 assert(getNumOperands() != 2 && "ExtractLane from single source should be "
1046 "simplified to ExtractElement.");
1047 Value *LaneToExtract = State.get(getOperand(0), true);
1048 Type *IdxTy = getOperand(0)->getScalarType();
1049 Value *Res = nullptr;
1050 Value *RuntimeVF = getRuntimeVF(Builder, IdxTy, State.VF);
1051
1052 for (unsigned Idx = 1; Idx != getNumOperands(); ++Idx) {
1053 Value *VectorStart =
1054 Builder.CreateMul(RuntimeVF, ConstantInt::get(IdxTy, Idx - 1));
1055 Value *VectorIdx = Idx == 1
1056 ? LaneToExtract
1057 : Builder.CreateSub(LaneToExtract, VectorStart);
1058 Value *Ext = State.VF.isScalar()
1059 ? State.get(getOperand(Idx))
1060 : Builder.CreateExtractElement(
1061 State.get(getOperand(Idx)), VectorIdx);
1062 if (Res) {
1063 Value *Cmp = Builder.CreateICmpUGE(LaneToExtract, VectorStart);
1064 Res = Builder.CreateSelect(Cmp, Ext, Res);
1065 } else {
1066 Res = Ext;
1067 }
1068 }
1069 return Res;
1070 }
1072 Type *Ty = this->getScalarType();
1073 if (getNumOperands() == 1) {
1074 Value *Mask = State.get(getOperand(0));
1075 return Builder.CreateCountTrailingZeroElems(Ty, Mask,
1076 /*ZeroIsPoison=*/false, Name);
1077 }
1078 // If there are multiple operands, create a chain of selects to pick the
1079 // first operand with an active lane and add the number of lanes of the
1080 // preceding operands.
1081 Value *RuntimeVF = getRuntimeVF(Builder, Ty, State.VF);
1082 unsigned LastOpIdx = getNumOperands() - 1;
1083 Value *Res = nullptr;
1084 for (int Idx = LastOpIdx; Idx >= 0; --Idx) {
1085 Value *TrailingZeros =
1086 State.VF.isScalar()
1087 ? Builder.CreateZExt(
1088 Builder.CreateICmpEQ(State.get(getOperand(Idx)),
1089 Builder.getFalse()),
1090 Ty)
1092 Ty, State.get(getOperand(Idx)),
1093 /*ZeroIsPoison=*/false, Name);
1094 Value *Current = Builder.CreateAdd(
1095 Builder.CreateMul(RuntimeVF, ConstantInt::get(Ty, Idx)),
1096 TrailingZeros);
1097 if (Res) {
1098 Value *Cmp = Builder.CreateICmpNE(TrailingZeros, RuntimeVF);
1099 Res = Builder.CreateSelect(Cmp, Current, Res);
1100 } else {
1101 Res = Current;
1102 }
1103 }
1104
1105 return Res;
1106 }
1108 return State.get(getOperand(0), true);
1110 return Builder.CreateVectorReverse(State.get(getOperand(0)), "reverse");
1112 Value *Result = State.get(getOperand(0), /*IsScalar=*/true);
1113 for (unsigned Idx = 1; Idx < getNumOperands(); Idx += 2) {
1114 Value *Data = State.get(getOperand(Idx));
1115 Value *Mask = State.get(getOperand(Idx + 1));
1116 Type *VTy = Data->getType();
1117
1118 if (State.VF.isScalar())
1119 Result = Builder.CreateSelect(Mask, Data, Result);
1120 else
1121 Result = Builder.CreateIntrinsic(
1122 Intrinsic::experimental_vector_extract_last_active, {VTy},
1123 {Data, Mask, Result});
1124 }
1125
1126 return Result;
1127 }
1129 Value *Src = State.get(getOperand(0));
1130 Type *DstTy = VectorType::get(getScalarType(), State.VF);
1131 uint64_t Part = cast<VPConstantInt>(getOperand(1))->getZExtValue();
1132
1133 if (Src->getType() == DstTy)
1134 return Src;
1135
1136 return Builder.CreateExtractVector(
1137 DstTy, Src, Builder.getInt64(State.VF.getKnownMinValue() * Part), Name);
1138 }
1140 return State.Builder.CreateStepVector(
1141 VectorType::get(getScalarType(), State.VF));
1143 SmallVector<Value *, 2> Args;
1144 for (VPValue *Op : drop_end(operands()))
1145 Args.push_back(State.get(Op, /*IsSingleScalar=*/true));
1146 return State.Builder.CreateIntrinsic(getScalarType(),
1147 vputils::getIntrinsicID(this), Args,
1148 /*FMFSource=*/nullptr, getName());
1149 }
1150 default:
1151 llvm_unreachable("Unsupported opcode for instruction");
1152 }
1153}
1154
1156 unsigned Opcode, ElementCount VF, VPCostContext &Ctx) const {
1157 Type *ScalarTy = this->getScalarType();
1158 Type *ResultTy = VF.isVector() ? toVectorTy(ScalarTy, VF) : ScalarTy;
1159 switch (Opcode) {
1160 case Instruction::FNeg:
1161 return Ctx.TTI.getArithmeticInstrCost(Opcode, ResultTy, Ctx.CostKind);
1162 case Instruction::UDiv:
1163 case Instruction::SDiv:
1164 case Instruction::SRem:
1165 case Instruction::URem:
1166 case Instruction::Add:
1167 case Instruction::FAdd:
1168 case Instruction::Sub:
1169 case Instruction::FSub:
1170 case Instruction::Mul:
1171 case Instruction::FMul:
1172 case Instruction::FDiv:
1173 case Instruction::FRem:
1174 case Instruction::Shl:
1175 case Instruction::LShr:
1176 case Instruction::AShr:
1177 case Instruction::And:
1178 case Instruction::Or:
1179 case Instruction::Xor: {
1180 // Certain instructions can be cheaper if they have a constant second
1181 // operand. One example of this are shifts on x86.
1182 VPValue *RHS = getOperand(1);
1183 TargetTransformInfo::OperandValueInfo RHSInfo = Ctx.getOperandInfo(RHS);
1184
1185 if (RHSInfo.Kind == TargetTransformInfo::OK_AnyValue &&
1188
1191 if (CtxI)
1192 Operands.append(CtxI->value_op_begin(), CtxI->value_op_end());
1193 return Ctx.TTI.getArithmeticInstrCost(
1194 Opcode, ResultTy, Ctx.CostKind,
1195 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
1196 RHSInfo, Operands, CtxI, &Ctx.TLI);
1197 }
1198 case Instruction::Freeze:
1199 // NOTE: The only way to ask for the cost is via getInstructionCost, which
1200 // requires the actual vector instruction. Instead, both here and in the
1201 // LoopVectorizationCostModel::getInstructionCost the costs mirror the
1202 // current behaviour in llvm/Analysis/TargetTransformInfoImpl.h to keep
1203 // them in sync.
1204 return TTI::TCC_Free;
1205 case Instruction::ExtractValue:
1206 return Ctx.TTI.getInsertExtractValueCost(Instruction::ExtractValue,
1207 Ctx.CostKind);
1208 case Instruction::ICmp:
1209 case Instruction::FCmp: {
1210 Type *ScalarOpTy = getOperand(0)->getScalarType();
1211 Type *OpTy = VF.isVector() ? toVectorTy(ScalarOpTy, VF) : ScalarOpTy;
1213 return Ctx.TTI.getCmpSelInstrCost(
1215 Ctx.CostKind, {TTI::OK_AnyValue, TTI::OP_None},
1216 {TTI::OK_AnyValue, TTI::OP_None}, CtxI);
1217 }
1218 case Instruction::BitCast: {
1219 Type *ScalarTy = this->getScalarType();
1220 if (ScalarTy->isPointerTy())
1221 return 0;
1222 [[fallthrough]];
1223 }
1224 case Instruction::SExt:
1225 case Instruction::ZExt:
1226 case Instruction::FPToUI:
1227 case Instruction::FPToSI:
1228 case Instruction::FPExt:
1229 case Instruction::PtrToInt:
1230 case Instruction::PtrToAddr:
1231 case Instruction::IntToPtr:
1232 case Instruction::SIToFP:
1233 case Instruction::UIToFP:
1234 case Instruction::Trunc:
1235 case Instruction::FPTrunc:
1236 case Instruction::AddrSpaceCast: {
1237 // Computes the CastContextHint from a recipe that may access memory.
1238 auto ComputeCCH = [&](const VPRecipeBase *R) -> TTI::CastContextHint {
1239 if (isa<VPInterleaveBase>(R))
1241 if (const auto *ReplicateRecipe = dyn_cast<VPReplicateRecipe>(R)) {
1242 // Only compute CCH for memory operations, matching the legacy model
1243 // which only considers loads/stores for cast context hints.
1244 auto *UI = cast<Instruction>(ReplicateRecipe->getUnderlyingValue());
1245 if (!isa<LoadInst, StoreInst>(UI))
1247 return ReplicateRecipe->isPredicated() ? TTI::CastContextHint::Masked
1249 }
1250 const auto *WidenMemoryRecipe = dyn_cast<VPWidenMemoryRecipe>(R);
1251 if (WidenMemoryRecipe == nullptr)
1253 if (VF.isScalar())
1255 if (!WidenMemoryRecipe->isConsecutive())
1257 if (WidenMemoryRecipe->isMasked())
1260 };
1261
1262 VPValue *Operand = getOperand(0);
1264 bool IsReverse = false;
1265 // For Trunc/FPTrunc, get the context from the only user.
1266 if (Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) {
1267 if (auto *Recipe = cast_or_null<VPRecipeBase>(getSingleUser())) {
1268 if (match(Recipe,
1272 IsReverse = true;
1274 Recipe->getVPSingleValue()->getSingleUser());
1275 }
1276 if (Recipe)
1277 CCH = ComputeCCH(Recipe);
1278 }
1279 }
1280 // For Z/Sext, get the context from the operand.
1281 else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt ||
1282 Opcode == Instruction::FPExt) {
1283 if (auto *Recipe = Operand->getDefiningRecipe()) {
1284 VPValue *ReverseOp;
1285 if (match(Recipe,
1286 m_CombineOr(m_Reverse(m_VPValue(ReverseOp)),
1288 m_VPValue(ReverseOp))))) {
1289 Recipe = ReverseOp->getDefiningRecipe();
1290 IsReverse = true;
1291 }
1292 if (Recipe)
1293 CCH = ComputeCCH(Recipe);
1294 }
1295 }
1296 if (IsReverse && CCH != TTI::CastContextHint::None)
1298
1299 auto *ScalarSrcTy = Operand->getScalarType();
1300 Type *SrcTy = VF.isVector() ? toVectorTy(ScalarSrcTy, VF) : ScalarSrcTy;
1301 // Arm TTI will use the underlying instruction to determine the cost.
1302 return Ctx.TTI.getCastInstrCost(
1303 Opcode, ResultTy, SrcTy, CCH, Ctx.CostKind,
1305 }
1306 case Instruction::Select: {
1308 bool IsScalarCond = getOperand(0)->isDefinedOutsideLoopRegions();
1309 Type *ScalarTy = this->getScalarType();
1310
1311 VPValue *Op0, *Op1;
1312 bool IsLogicalAnd =
1313 match(this, m_c_LogicalAnd(m_VPValue(Op0), m_VPValue(Op1)));
1314 bool IsLogicalOr =
1315 match(this, m_c_LogicalOr(m_VPValue(Op0), m_VPValue(Op1)));
1316 // Also match the inverted forms:
1317 // select x, false, y --> !x & y (still AND)
1318 // select x, y, true --> !x | y (still OR)
1319 IsLogicalAnd |=
1320 match(this, m_Select(m_VPValue(Op0), m_False(), m_VPValue(Op1)));
1321 IsLogicalOr |=
1322 match(this, m_Select(m_VPValue(Op0), m_VPValue(Op1), m_True()));
1323
1324 if (!IsScalarCond && ScalarTy->getScalarSizeInBits() == 1 &&
1325 (IsLogicalAnd || IsLogicalOr)) {
1326 // select x, y, false --> x & y
1327 // select x, true, y --> x | y
1328 const auto [Op1VK, Op1VP] = Ctx.getOperandInfo(Op0);
1329 const auto [Op2VK, Op2VP] = Ctx.getOperandInfo(Op1);
1330
1332 if (SI && all_of(operands(),
1333 [](VPValue *Op) { return Op->getUnderlyingValue(); }))
1334 append_range(Operands, SI->operands());
1335 return Ctx.TTI.getArithmeticInstrCost(
1336 IsLogicalOr ? Instruction::Or : Instruction::And, ResultTy,
1337 Ctx.CostKind, {Op1VK, Op1VP}, {Op2VK, Op2VP}, Operands, SI);
1338 }
1339
1340 Type *CondTy = getOperand(0)->getScalarType();
1341 if (!IsScalarCond && VF.isVector())
1342 CondTy = VectorType::get(CondTy, VF);
1343
1344 llvm::CmpPredicate Pred;
1345 if (!match(getOperand(0), m_Cmp(Pred, m_VPValue(), m_VPValue())))
1346 if (auto *CondIRV = dyn_cast<VPIRValue>(getOperand(0)))
1347 if (auto *Cmp = dyn_cast<CmpInst>(CondIRV->getValue()))
1348 Pred = Cmp->getPredicate();
1349 Type *VectorTy = toVectorTy(this->getScalarType(), VF);
1350 return Ctx.TTI.getCmpSelInstrCost(
1351 Instruction::Select, VectorTy, CondTy, Pred, Ctx.CostKind,
1352 {TTI::OK_AnyValue, TTI::OP_None}, {TTI::OK_AnyValue, TTI::OP_None}, SI);
1353 }
1354 }
1355 llvm_unreachable("called for unsupported opcode");
1356}
1357
1359 VPCostContext &Ctx) const {
1360 // NOTE: At the moment it seems only possible to expose this path for
1361 // the trunc, zext and sext opcodes.
1362 // TODO: Update VF arg to use onlyFirstLaneUsed once WidenCast is unified.
1365 Ctx);
1366
1368 if (!getUnderlyingValue() && getOpcode() != Instruction::FMul) {
1369 // TODO: Compute cost for VPInstructions without underlying values once
1370 // the legacy cost model has been retired.
1371 return 0;
1372 }
1373
1375 "Should only generate a vector value or single scalar, not scalars "
1376 "for all lanes.");
1378 getOpcode(),
1380 }
1381
1382 switch (getOpcode()) {
1383 case Instruction::Select: {
1385 match(getOperand(0), m_Cmp(Pred, m_VPValue(), m_VPValue()));
1386 auto *CondTy = getOperand(0)->getScalarType();
1387 auto *VecTy = getOperand(1)->getScalarType();
1388 if (!vputils::onlyFirstLaneUsed(this)) {
1389 CondTy = toVectorTy(CondTy, VF);
1390 VecTy = toVectorTy(VecTy, VF);
1391 }
1392 return Ctx.TTI.getCmpSelInstrCost(Instruction::Select, VecTy, CondTy, Pred,
1393 Ctx.CostKind);
1394 }
1395 case Instruction::ExtractElement:
1397 if (VF.isScalar()) {
1398 // ExtractLane with VF=1 takes care of handling extracting across multiple
1399 // parts.
1400 return 0;
1401 }
1402
1403 // Add on the cost of extracting the element.
1404 auto *VecTy = toVectorTy(getOperand(0)->getScalarType(), VF);
1405 return Ctx.TTI.getVectorInstrCost(Instruction::ExtractElement, VecTy,
1406 Ctx.CostKind);
1407 }
1408 case VPInstruction::AnyOf: {
1409 auto *VecTy = toVectorTy(this->getScalarType(), VF);
1410 return Ctx.TTI.getArithmeticReductionCost(
1411 Instruction::Or, cast<VectorType>(VecTy), std::nullopt, Ctx.CostKind);
1412 }
1414 Type *Ty = this->getScalarType();
1415 Type *ScalarTy = getOperand(0)->getScalarType();
1416 if (VF.isScalar())
1417 return Ctx.TTI.getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
1419 CmpInst::ICMP_EQ, Ctx.CostKind);
1420 // Calculate the cost of determining the lane index.
1421 auto *PredTy = toVectorTy(ScalarTy, VF);
1422 IntrinsicCostAttributes Attrs(Intrinsic::experimental_cttz_elts, Ty,
1423 {PredTy, Type::getInt1Ty(Ctx.LLVMCtx)});
1424 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1425 }
1427 Type *Ty = this->getScalarType();
1428 Type *ScalarTy = getOperand(0)->getScalarType();
1429 if (VF.isScalar())
1430 return Ctx.TTI.getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
1432 CmpInst::ICMP_EQ, Ctx.CostKind);
1433 // Calculate the cost of determining the lane index: NOT + cttz_elts + SUB.
1434 auto *PredTy = toVectorTy(ScalarTy, VF);
1435 IntrinsicCostAttributes Attrs(Intrinsic::experimental_cttz_elts, Ty,
1436 {PredTy, Type::getInt1Ty(Ctx.LLVMCtx)});
1437 InstructionCost Cost = Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1438 // Add cost of NOT operation on the predicate.
1439 Cost += Ctx.TTI.getArithmeticInstrCost(
1440 Instruction::Xor, PredTy, Ctx.CostKind,
1441 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
1442 {TargetTransformInfo::OK_UniformConstantValue,
1443 TargetTransformInfo::OP_None});
1444 // Add cost of SUB operation on the index.
1445 Cost += Ctx.TTI.getArithmeticInstrCost(Instruction::Sub, Ty, Ctx.CostKind);
1446 return Cost;
1447 }
1449 Type *ScalarTy = this->getScalarType();
1450 Type *VecTy = toVectorTy(ScalarTy, VF);
1451 Type *MaskTy = toVectorTy(Type::getInt1Ty(Ctx.LLVMCtx), VF);
1453 Intrinsic::experimental_vector_extract_last_active, ScalarTy,
1454 {VecTy, MaskTy, ScalarTy});
1455 return Ctx.TTI.getIntrinsicInstrCost(ICA, Ctx.CostKind);
1456 }
1458 assert(VF.isVector() && "Scalar FirstOrderRecurrenceSplice?");
1459 Type *VectorTy = toVectorTy(this->getScalarType(), VF);
1460 return Ctx.TTI.getShuffleCost(
1462 cast<VectorType>(VectorTy), Ctx.CostKind, {}, -1);
1463 }
1466 Type *ArgTy = getOperand(0)->getScalarType();
1467 uint64_t Multiplier =
1469 ? cast<VPConstantInt>(getOperand(2))->getZExtValue()
1470 : 1;
1471 Type *RetTy = toVectorTy(Type::getInt1Ty(Ctx.LLVMCtx), VF * Multiplier);
1472 IntrinsicCostAttributes Attrs(Intrinsic::get_active_lane_mask, RetTy,
1473 {ArgTy, ArgTy});
1474 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1475 }
1477 Type *Arg0Ty = getOperand(0)->getScalarType();
1478 Type *I32Ty = Type::getInt32Ty(Ctx.LLVMCtx);
1479 Type *I1Ty = Type::getInt1Ty(Ctx.LLVMCtx);
1480 IntrinsicCostAttributes Attrs(Intrinsic::experimental_get_vector_length,
1481 I32Ty, {Arg0Ty, I32Ty, I1Ty});
1482 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1483 }
1485 assert(VF.isVector() && "Reverse operation must be vector type");
1486 Type *EltTy = this->getScalarType();
1487 // Skip the reverse operation cost for the mask.
1488 // FIXME: Remove this once redundant mask reverse operations can be
1489 // eliminated by VPlanTransforms::cse before cost computation.
1490 if (EltTy->isIntegerTy(1))
1491 return 0;
1492 auto *VectorTy = cast<VectorType>(toVectorTy(EltTy, VF));
1493 return Ctx.TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy,
1494 VectorTy, Ctx.CostKind, /*Mask=*/{},
1495 /*Index=*/0);
1496 }
1498 // Add on the cost of extracting the element.
1499 auto *VecTy = toVectorTy(getOperand(0)->getScalarType(), VF);
1500 return Ctx.TTI.getIndexedVectorInstrCostFromEnd(Instruction::ExtractElement,
1501 VecTy, Ctx.CostKind, 0);
1502 }
1503 case VPInstruction::Not: {
1504 Type *ValTy = this->getScalarType();
1505 // InstCombine will fold `xor` to the conditional branch.
1506 if (auto *U = const_cast<VPUser *>(getSingleUser()))
1507 if (match(U, m_BranchOnCond(m_VPValue())))
1508 return 0;
1509 if (!vputils::onlyFirstLaneUsed(this))
1510 ValTy = toVectorTy(ValTy, VF);
1511 return Ctx.TTI.getArithmeticInstrCost(Instruction::Xor, ValTy,
1512 Ctx.CostKind);
1513 }
1515 // If TC <= VF then this is just a branch.
1516 // FIXME: Removing the branch happens in simplifyBranchConditionForVFAndUF
1517 // where it checks TC <= VF * UF, but we don't know UF yet. This means in
1518 // some cases we get a cost that's too high due to counting a cmp that
1519 // later gets removed.
1520 // FIXME: The compare could also be removed if TC = M * vscale,
1521 // VF = N * vscale, and M <= N. Detecting that would require having the
1522 // trip count as a SCEV though.
1523 if (VPCostContext::executesAtMostOnce(*getParent()->getPlan(), VF))
1524 return 0;
1525 // Otherwise BranchOnCount generates ICmpEQ followed by a branch.
1526 Type *ValTy = getOperand(0)->getScalarType();
1527 return Ctx.TTI.getCmpSelInstrCost(Instruction::ICmp, ValTy,
1529 CmpInst::ICMP_EQ, Ctx.CostKind);
1530 }
1532 Type *Ty = getScalarType();
1534 for (const VPValue *Op : drop_end(operands()))
1535 ArgTys.push_back(Op->getScalarType());
1536 IntrinsicCostAttributes Attrs(vputils::getIntrinsicID(this), Ty, ArgTys);
1537 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1538 }
1540 // TODO: This isn't quite right since even if the step-vector is hoisted
1541 // out of the loop it has a non-zero cost in the middle block, etc.
1542 // Once the stepvector is correctly hoisted out of the vector loop by the
1543 // licm transform we can add the cost here so that it doesn't incorrectly
1544 // affect the choice of VF.
1545 return 0;
1547 // It isn't currently possible to expose cases where WideIVStep's cost is
1548 // queried.
1549 llvm_unreachable("Unhandled opcode");
1550 case Instruction::FCmp:
1551 case Instruction::ICmp:
1553 getOpcode(),
1556 if (VF == ElementCount::getScalable(1))
1558 [[fallthrough]];
1559 default:
1560 // TODO: Compute cost other VPInstructions once the legacy cost model has
1561 // been retired.
1563 "unexpected VPInstruction witht underlying value");
1564 return 0;
1565 }
1566}
1567
1580
1582 switch (getOpcode()) {
1583 case Instruction::Load:
1584 case Instruction::PHI:
1588 return true;
1589 default:
1591 }
1592}
1593
1595#ifndef NDEBUG
1596 Type *Ty = Op->getScalarType();
1597 switch (getOpcode()) {
1601 assert(Ty == getOperand(0)->getScalarType() &&
1602 "types of operand 0 and new operand must match");
1603 break;
1607 assert(Ty == getOperand(0)->getScalarType() &&
1608 "appended operand must match operand 0's scalar type");
1609 break;
1611 assert(Ty == getOperand(1)->getScalarType() &&
1612 "appended operand must match operand 1's scalar type");
1613 break;
1615 // The recipe is constructed with 3 operands (result, data, mask). Extra
1616 // operands beyond that are appended in (data, mask) pairs.
1617 constexpr unsigned NumInitialOperands = 3;
1618 assert(getNumOperands() >= NumInitialOperands &&
1619 "ExtractLastActive must have at least the initial 3 operands");
1620 bool IsMaskSlot = ((getNumOperands() - NumInitialOperands) & 1u) == 1u;
1621 assert((IsMaskSlot ? Ty->isIntegerTy(1)
1622 : Ty == getOperand(1)->getScalarType()) &&
1623 "ExtractLastActive expects alternating data/mask operands "
1624 "matching operand 1's type and i1, respectively");
1625 break;
1626 }
1627 default:
1628 llvm_unreachable("opcode does not support growing the operand list "
1629 "outside of construction");
1630 }
1631#endif
1633}
1634
1636 assert(!isMasked() && "cannot execute masked VPInstruction");
1637 IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder);
1639 "Set flags not supported for the provided opcode");
1641 "Opcode requires specific flags to be set");
1642 State.Builder.setFastMathFlags(getFastMathFlagsOrNone());
1643 Value *GeneratedValue = generate(State);
1644 if (!hasResult())
1645 return;
1646 assert(GeneratedValue && "generate must produce a value");
1647 bool GeneratesPerFirstLaneOnly = canGenerateScalarForFirstLane() &&
1650 assert((((GeneratedValue->getType()->isVectorTy() ||
1651 GeneratedValue->getType()->isStructTy()) ==
1652 !GeneratesPerFirstLaneOnly) ||
1653 State.VF.isScalar()) &&
1654 "scalar value but not only first lane defined");
1655 State.set(this, GeneratedValue,
1656 /*IsScalar*/ GeneratesPerFirstLaneOnly);
1658 getOpcode() == Instruction::Freeze) {
1659 // FIXME: This is a workaround to enable reliable updates of the scalar loop
1660 // resume phis, and to let epilogue vectorization recover the frozen
1661 // reduction start from the main plan. Must be removed once epilogue
1662 // vectorization explicitly connects VPlans.
1663 setUnderlyingValue(GeneratedValue);
1664 }
1665}
1666
1670 return false;
1671 switch (getOpcode()) {
1672 case Instruction::ExtractValue:
1673 case Instruction::InsertValue:
1674 case Instruction::GetElementPtr:
1675 case Instruction::ExtractElement:
1676 case Instruction::InsertElement:
1677 case Instruction::Freeze:
1678 case Instruction::FCmp:
1679 case Instruction::ICmp:
1680 case Instruction::Select:
1681 case Instruction::PHI:
1708 case VPInstruction::Not:
1716 return false;
1719 AttributeSet Attrs =
1721 return !Attrs.getMemoryEffects().doesNotAccessMemory();
1722 }
1723 case Instruction::Call:
1725 default:
1726 return true;
1727 }
1728}
1729
1731 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
1733 return vputils::onlyFirstLaneUsed(this);
1734
1735 switch (getOpcode()) {
1736 default:
1737 return false;
1738 case Instruction::ExtractElement:
1739 return Op == getOperand(1);
1740 case Instruction::InsertElement:
1741 return Op == getOperand(1) || Op == getOperand(2);
1742 case Instruction::PHI:
1743 return true;
1744 case Instruction::FCmp:
1745 case Instruction::ICmp:
1746 case Instruction::Select:
1747 case Instruction::Or:
1748 case Instruction::Freeze:
1749 case VPInstruction::Not:
1750 // TODO: Cover additional opcodes.
1751 return vputils::onlyFirstLaneUsed(this);
1752 case Instruction::Load:
1764 return true;
1767 // Before replicating by VF, Build(Struct)Vector uses all lanes of the
1768 // operand, after replicating its operands only the first lane is used.
1769 // Before replicating, it will have only a single operand.
1770 return getNumOperands() > 1;
1772 return Op == getOperand(0) || vputils::onlyFirstLaneUsed(this);
1774 // WidePtrAdd supports scalar and vector base addresses.
1775 return false;
1778 return Op == getOperand(0);
1779 };
1780 llvm_unreachable("switch should return");
1781}
1782
1784 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
1786 return vputils::onlyFirstPartUsed(this);
1787
1788 switch (getOpcode()) {
1789 default:
1790 return false;
1791 case Instruction::FCmp:
1792 case Instruction::ICmp:
1793 case Instruction::Select:
1794 return vputils::onlyFirstPartUsed(this);
1799 return true;
1800 };
1801 llvm_unreachable("switch should return");
1802}
1803
1804#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1806 VPSlotTracker SlotTracker(getParent()->getPlan());
1808}
1809
1811 VPSlotTracker &SlotTracker) const {
1812 O << Indent << "EMIT" << (isSingleScalar() ? "-SCALAR" : "") << " ";
1813
1814 if (hasResult()) {
1816 O << " = ";
1817 }
1818
1819 switch (getOpcode()) {
1820 case VPInstruction::Not:
1821 O << "not";
1822 break;
1824 O << "active lane mask";
1825 break;
1827 O << "wide active lane mask";
1828 break;
1830 O << "incoming-alias-mask";
1831 break;
1833 O << "EXPLICIT-VECTOR-LENGTH";
1834 break;
1836 O << "first-order splice";
1837 break;
1839 O << "branch-on-cond";
1840 break;
1842 O << "branch-on-two-conds";
1843 break;
1845 O << "VF * Part +";
1846 break;
1848 O << "branch-on-count";
1849 break;
1851 O << "broadcast";
1852 break;
1854 O << "buildstructvector";
1855 break;
1857 O << "buildvector";
1858 break;
1860 O << "exiting-iv-value";
1861 break;
1863 O << "masked-cond";
1864 break;
1866 O << "extract-lane";
1867 break;
1869 O << "extract-last-lane";
1870 break;
1872 O << "extract-last-part";
1873 break;
1875 O << "extract-penultimate-element";
1876 break;
1878 O << "extract-vector-for-part";
1879 break;
1881 O << "compute-reduction-result";
1882 break;
1884 O << "logical-and";
1885 break;
1887 O << "logical-or";
1888 break;
1890 O << "ptradd";
1891 break;
1893 O << "wide-ptradd";
1894 break;
1896 O << "any-of";
1897 break;
1899 O << "first-active-lane";
1900 break;
1902 O << "last-active-lane";
1903 break;
1905 O << "reduction-start-vector";
1906 break;
1908 O << "resume-for-epilogue";
1909 break;
1911 O << "reverse";
1912 break;
1914 O << "unpack";
1915 break;
1917 O << "extract-last-active";
1918 break;
1920 O << "num-active-lanes";
1921 break;
1923 O << "wide-iv-step";
1924 break;
1926 O << "step-vector " << *getScalarType();
1927 break;
1929 O << "call " << *getScalarType() << " @"
1932 Op->printAsOperand(O, SlotTracker);
1933 });
1934 O << ")";
1935 return;
1936 }
1937 case Instruction::Load:
1938 O << "load";
1939 break;
1940 default:
1942 }
1943
1944 if (!operands_empty()) {
1945 printFlags(O);
1947 }
1949 O << " to " << *getScalarType();
1950}
1951#endif
1952
1953/// Shared execute logic for VPPhi and VPWidenPHIRecipe. Creates a PHI node,
1954/// adds incoming values, and stores the result in State. For header phis, only
1955/// the preheader incoming value is added; the backedge is fixed up later by
1956/// VPlan::execute().
1958 VPTransformState &State, bool IsScalar,
1959 const Twine &Name) {
1960 unsigned NumIncoming = VPBlockUtils::isHeader(R->getParent(), State.VPDT)
1961 ? 1
1962 : Phi.getNumIncoming();
1963 Value *FirstInc = State.get(Phi.getIncomingValue(0), IsScalar);
1964 PHINode *NewPhi = State.Builder.CreatePHI(FirstInc->getType(), 2, Name);
1965 NewPhi->addIncoming(FirstInc,
1966 State.CFG.VPBB2IRBB.at(Phi.getIncomingBlock(0)));
1967 for (unsigned Idx = 1; Idx != NumIncoming; ++Idx)
1968 NewPhi->addIncoming(State.get(Phi.getIncomingValue(Idx), IsScalar),
1969 State.CFG.VPBB2IRBB.at(Phi.getIncomingBlock(Idx)));
1970 State.set(R, NewPhi, IsScalar);
1971}
1972
1974 executePhiRecipe(this, *this, State, /*IsScalar=*/true, getName());
1975}
1976
1977#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1978void VPPhi::printRecipe(raw_ostream &O, const Twine &Indent,
1979 VPSlotTracker &SlotTracker) const {
1980 O << Indent << "EMIT" << (isSingleScalar() ? "-SCALAR" : "") << " ";
1982 O << " = phi";
1983 printFlags(O);
1985}
1986#endif
1987
1988VPIRInstruction *VPIRInstruction ::create(Instruction &I) {
1989 if (auto *Phi = dyn_cast<PHINode>(&I))
1990 return new VPIRPhi(*Phi);
1991 return new VPIRInstruction(I);
1992}
1993
1995 assert(!isa<VPIRPhi>(this) && getNumOperands() == 0 &&
1996 "PHINodes must be handled by VPIRPhi");
1997 // Advance the insert point after the wrapped IR instruction. This allows
1998 // interleaving VPIRInstructions and other recipes.
1999 State.Builder.SetInsertPoint(I.getParent(), std::next(I.getIterator()));
2000}
2001
2003 VPCostContext &Ctx) const {
2004 // The recipe wraps an existing IR instruction on the border of VPlan's scope,
2005 // hence it does not contribute to the cost-modeling for the VPlan.
2006 return 0;
2007}
2008
2009#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2011 VPSlotTracker &SlotTracker) const {
2012 O << Indent << "IR " << I;
2013}
2014#endif
2015
2017 PHINode *Phi = &getIRPhi();
2018 for (const auto &[Idx, Op] : enumerate(operands())) {
2019 VPValue *ExitValue = Op;
2020 auto Lane = vputils::isSingleScalar(ExitValue)
2022 : VPLane::getLastLaneForVF(State.VF);
2023 VPBlockBase *Pred = getParent()->getPredecessors()[Idx];
2024 auto *PredVPBB = Pred->getExitingBasicBlock();
2025 BasicBlock *PredBB = State.CFG.VPBB2IRBB[PredVPBB];
2026 // Set insertion point in PredBB in case an extract needs to be generated.
2027 // TODO: Model extracts explicitly.
2028 State.Builder.SetInsertPoint(PredBB->getTerminator());
2029 Value *V = State.get(ExitValue, VPLane(Lane));
2030 // If there is no existing block for PredBB in the phi, add a new incoming
2031 // value. Otherwise update the existing incoming value for PredBB.
2032 if (Phi->getBasicBlockIndex(PredBB) == -1)
2033 Phi->addIncoming(V, PredBB);
2034 else
2035 Phi->setIncomingValueForBlock(PredBB, V);
2036 }
2037
2038 // Advance the insert point after the wrapped IR instruction. This allows
2039 // interleaving VPIRInstructions and other recipes.
2040 State.Builder.SetInsertPoint(Phi->getParent(), std::next(Phi->getIterator()));
2041}
2042
2044 VPRecipeBase *R = const_cast<VPRecipeBase *>(getAsRecipe());
2045 assert(R->getNumOperands() == R->getParent()->getNumPredecessors() &&
2046 "Number of phi operands must match number of predecessors");
2047 unsigned Position = R->getParent()->getIndexForPredecessor(IncomingBlock);
2048 R->removeOperand(Position);
2049}
2050
2051VPValue *
2053 VPRecipeBase *R = const_cast<VPRecipeBase *>(getAsRecipe());
2054 return getIncomingValue(R->getParent()->getIndexForPredecessor(VPBB));
2055}
2056
2058 VPValue *V) const {
2059 VPRecipeBase *R = const_cast<VPRecipeBase *>(getAsRecipe());
2060 R->setOperand(R->getParent()->getIndexForPredecessor(VPBB), V);
2061}
2062
2063#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2065 VPSlotTracker &SlotTracker) const {
2067 O << "[ ";
2068 std::get<0>(Op)->printAsOperand(O, SlotTracker);
2069 O << ", ";
2070 std::get<1>(Op)->printAsOperand(O);
2071 O << " ]";
2072 });
2073}
2074#endif
2075
2076#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2078 VPSlotTracker &SlotTracker) const {
2080
2081 if (getNumOperands() != 0) {
2082 O << " (extra operand" << (getNumOperands() > 1 ? "s" : "") << ": ";
2084 [&O, &SlotTracker](auto Op) {
2085 std::get<0>(Op)->printAsOperand(O, SlotTracker);
2086 O << " from ";
2087 std::get<1>(Op)->printAsOperand(O);
2088 });
2089 O << ")";
2090 }
2091}
2092#endif
2093
2095 if (Metadata.empty())
2096 return;
2097 // Frequencies and estimated branch weights are VPlan-internal and must not
2098 // reach IR.
2099 unsigned ExecFreqKind = getMDKindID(ExecutionFrequencyMDName);
2100 unsigned EstProfKind = getMDKindID(EstimatedProfileMDName);
2101 for (const auto &[Kind, Node] : Metadata)
2102 if (Kind != ExecFreqKind && Kind != EstProfKind)
2103 I.setMetadata(Kind, Node);
2104}
2105
2106/// Returns the execution frequency recorded in \p Node.
2108 assert(Node->getNumOperands() <= 2 && "unexpected frequency node shape");
2109 uint64_t Freq =
2110 mdconst::extract<ConstantInt>(Node->getOperand(0))->getZExtValue();
2112 "frequency cannot exceed the one of an always executing block");
2113 return {BlockFrequency(Freq), Node->getNumOperands() == 2};
2114}
2115
2117 std::optional<VPExecutionFrequency> Freq, LLVMContext &Ctx) {
2118 // A recipe that never or always executes needs no annotation.
2119 if (!Freq || Freq->Freq.getFrequency() == 0 ||
2120 Freq->Freq.getFrequency() == vputils::AlwaysExecutesFreq)
2121 return;
2123 ConstantInt::get(Type::getInt64Ty(Ctx), Freq->Freq.getFrequency()))};
2124 if (Freq->IsEstimated)
2126 setMetadata(Ctx.getMDKindID(ExecutionFrequencyMDName), MDNode::get(Ctx, Ops));
2127}
2128
2129std::optional<VPExecutionFrequency>
2131 if (MDNode *Node = getInternalMetadata(ExecutionFrequencyMDName))
2133 return std::nullopt;
2134}
2135
2137 if (Metadata.empty())
2138 return;
2139 unsigned ID = getMDKindID(ExecutionFrequencyMDName);
2140 erase_if(Metadata, [ID](const auto &P) { return P.first == ID; });
2141}
2142
2144 SmallVector<std::pair<unsigned, MDNode *>> MetadataIntersection;
2145 for (const auto &[KindA, MDA] : Metadata) {
2146 for (const auto &[KindB, MDB] : Other.Metadata) {
2147 if (KindA == KindB && MDA == MDB) {
2148 MetadataIntersection.emplace_back(KindA, MDA);
2149 break;
2150 }
2151 }
2152 }
2153 Metadata = std::move(MetadataIntersection);
2154}
2155
2156#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2158 const Module *M = SlotTracker.getModule();
2159 if (Metadata.empty() || !M || !VPlanPrintMetadata)
2160 return;
2161
2162 ArrayRef<StringRef> MDNames = SlotTracker.getMDNames();
2163 O << " (";
2164 interleaveComma(Metadata, O, [&](const auto &KindNodePair) {
2165 auto [Kind, Node] = KindNodePair;
2166 assert(Kind < MDNames.size() && !MDNames[Kind].empty() &&
2167 "Unexpected unnamed metadata kind");
2168 O << "!" << MDNames[Kind] << " ";
2169 // Print the values of branch weights, which are more informative than the
2170 // ID of the metadata node holding them.
2171 SmallVector<uint32_t> Weights;
2172 bool IsEstimatedProfile = MDNames[Kind] == EstimatedProfileMDName;
2173 if ((Kind == LLVMContext::MD_prof || IsEstimatedProfile) &&
2174 extractBranchWeights(Node, Weights)) {
2175 if (IsEstimatedProfile)
2176 O << "estimated ";
2177 O << "{";
2178 interleaveComma(Weights, O);
2179 O << "}";
2180 } else if (MDNames[Kind] == ExecutionFrequencyMDName) {
2181 // Print the frequency together with the probability it corresponds to.
2182 auto [Freq, IsEstimated] = getExecutionFrequencyFromMD(Node);
2183 O << Freq.getFrequency()
2184 << format(" (%.4g%%%s)",
2185 100.0 * Freq.getFrequency() / vputils::AlwaysExecutesFreq,
2186 IsEstimated ? ", estimated" : "");
2187 } else {
2188 Node->printAsOperand(O, M);
2189 }
2190 });
2191 O << ")";
2192}
2193#endif
2194
2196 assert(State.VF.isVector() && "not widening");
2197 assert(Variant != nullptr && "Can't create vector function.");
2198
2199 FunctionType *VFTy = Variant->getFunctionType();
2200 // Add return type if intrinsic is overloaded on it.
2202 for (const auto &I : enumerate(args())) {
2203 Value *Arg;
2204 // Some vectorized function variants may also take a scalar argument,
2205 // e.g. linear parameters for pointers. This needs to be the scalar value
2206 // from the start of the respective part when interleaving.
2207 if (!VFTy->getParamType(I.index())->isVectorTy())
2208 Arg = State.get(I.value(), VPLane(0));
2209 else
2210 Arg = State.get(I.value(), usesFirstLaneOnly(I.value()));
2211 Args.push_back(Arg);
2212 }
2213
2216 if (CI)
2217 CI->getOperandBundlesAsDefs(OpBundles);
2218
2219 CallInst *V = State.Builder.CreateCall(Variant, Args, OpBundles);
2220 applyFlags(*V);
2221 applyMetadata(*V);
2222 V->setCallingConv(Variant->getCallingConv());
2223
2224 if (!V->getType()->isVoidTy())
2225 State.set(this, V);
2226}
2227
2229 VPCostContext &Ctx) const {
2230 assert(getVectorizedTypeVF(Variant->getReturnType()) == VF &&
2231 "Variant return type must match VF");
2232 return computeCallCost(Variant, Ctx);
2233}
2234
2236 VPCostContext &Ctx) {
2237 return Ctx.TTI.getCallInstrCost(nullptr, Variant->getReturnType(),
2238 Variant->getFunctionType()->params(),
2239 Ctx.CostKind);
2240}
2241
2243 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
2244 assert(Variant && "Variant not set");
2245 FunctionType *VFTy = Variant->getFunctionType();
2246 return all_of(enumerate(args()), [VFTy, &Op](const auto &Arg) {
2247 auto [Idx, V] = Arg;
2248 Type *ArgTy = VFTy->getParamType(Idx);
2249 return V != Op || ArgTy->isIntegerTy() || ArgTy->isFloatingPointTy() ||
2250 ArgTy->isPointerTy() || ArgTy->isByteTy();
2251 });
2252}
2253
2254#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2256 VPSlotTracker &SlotTracker) const {
2257 O << Indent << "WIDEN-CALL ";
2258
2259 Function *CalledFn = getCalledScalarFunction();
2260 if (CalledFn->getReturnType()->isVoidTy())
2261 O << "void ";
2262 else {
2264 O << " = ";
2265 }
2266
2267 O << "call";
2268 printFlags(O);
2269 O << "@" << CalledFn->getName() << "(";
2270 interleaveComma(args(), O, [&O, &SlotTracker](VPValue *Op) {
2271 Op->printAsOperand(O, SlotTracker);
2272 });
2273 O << ")";
2274
2275 O << " (using library function";
2276 if (Variant->hasName())
2277 O << ": " << Variant->getName();
2278 O << ")";
2279}
2280#endif
2281
2283 assert(State.VF.isVector() && "not widening");
2284
2285 SmallVector<Type *, 2> TysForDecl;
2286 // Add return type if intrinsic is overloaded on it.
2287 if (isVectorIntrinsicWithOverloadTypeAtArg(VectorIntrinsicID, -1,
2288 State.TTI)) {
2289 Type *RetTy = toVectorizedTy(getScalarType(), State.VF);
2290 ArrayRef<Type *> ContainedTys = getContainedTypes(RetTy);
2291 for (auto [Idx, Ty] : enumerate(ContainedTys)) {
2293 Idx, State.TTI))
2294 TysForDecl.push_back(Ty);
2295 }
2296 }
2298 for (const auto &I : enumerate(operands())) {
2299 // Some intrinsics have a scalar argument - don't replace it with a
2300 // vector.
2301 Value *Arg;
2302 if (isVectorIntrinsicWithScalarOpAtArg(VectorIntrinsicID, I.index(),
2303 State.TTI))
2304 Arg = State.get(I.value(), VPLane(0));
2305 else
2306 Arg = State.get(I.value(), usesFirstLaneOnly(I.value()));
2307 if (isVectorIntrinsicWithOverloadTypeAtArg(VectorIntrinsicID, I.index(),
2308 State.TTI))
2309 TysForDecl.push_back(Arg->getType());
2310 Args.push_back(Arg);
2311 }
2312
2313 // Use vector version of the intrinsic.
2314 Module *M = State.Builder.GetInsertBlock()->getModule();
2315 Function *VectorF =
2316 Intrinsic::getOrInsertDeclaration(M, VectorIntrinsicID, TysForDecl);
2317 assert(VectorF &&
2318 "Can't retrieve vector intrinsic or vector-predication intrinsics.");
2319
2322 if (CI)
2323 CI->getOperandBundlesAsDefs(OpBundles);
2324
2325 CallInst *V = State.Builder.CreateCall(VectorF, Args, OpBundles);
2326
2327 applyFlags(*V);
2328 applyMetadata(*V);
2329
2330 return V;
2331}
2332
2334 CallInst *V = createVectorCall(State);
2335 if (!V->getType()->isVoidTy())
2336 State.set(this, V);
2337}
2338
2341 const VPRecipeWithIRFlags &R, ElementCount VF, VPCostContext &Ctx) {
2342 Type *ScalarRetTy = R.getScalarType();
2343 // Skip the reverse operation cost for the mask.
2344 // FIXME: Remove this once redundant mask reverse operations can be eliminated
2345 // by VPlanTransforms::cse before cost computation.
2346 if (ID == Intrinsic::experimental_vp_reverse && ScalarRetTy->isIntegerTy(1))
2347 return InstructionCost(0);
2348
2349 // Some backends analyze intrinsic arguments to determine cost. Use the
2350 // underlying value for the operand if it has one. Otherwise try to use the
2351 // operand of the underlying call instruction, if there is one. Otherwise
2352 // clear Arguments.
2353 // TODO: Rework TTI interface to be independent of concrete IR values.
2355 for (const auto &[Idx, Op] : enumerate(Operands)) {
2356 auto *V = Op->getUnderlyingValue();
2357 if (!V) {
2358 if (auto *UI = dyn_cast_or_null<CallBase>(R.getUnderlyingValue())) {
2359 Arguments.push_back(UI->getArgOperand(Idx));
2360 continue;
2361 }
2362 Arguments.clear();
2363 break;
2364 }
2365 Arguments.push_back(V);
2366 }
2367
2368 Type *RetTy = VF.isVector() ? toVectorizedTy(ScalarRetTy, VF) : ScalarRetTy;
2369 SmallVector<Type *> ParamTys =
2370 map_to_vector(Operands, [&](const VPValue *Op) {
2371 return toVectorTy(Op->getScalarType(), VF);
2372 });
2373
2375 for (const VPValue *Op : Operands)
2376 if (isa<VPWidenRecipe>(Op) &&
2379 break;
2380 }
2381
2382 // TODO: Rework TTI interface to avoid reliance on underlying IntrinsicInst.
2383 IntrinsicCostAttributes CostAttrs(
2384 ID, RetTy, Arguments, ParamTys, R.getFastMathFlagsOrNone(),
2385 dyn_cast_or_null<IntrinsicInst>(R.getUnderlyingValue()),
2387 return Ctx.TTI.getIntrinsicInstrCost(CostAttrs, Ctx.CostKind);
2388}
2389
2391 VPCostContext &Ctx) const {
2392 return computeCallCost(VectorIntrinsicID, operands(), *this, VF, Ctx);
2393}
2394
2396 return Intrinsic::getBaseName(VectorIntrinsicID);
2397}
2398
2400 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
2401 return all_of(enumerate(operands()), [this, &Op](const auto &X) {
2402 auto [Idx, V] = X;
2404 Idx, nullptr);
2405 });
2406}
2407
2408#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2410 VPSlotTracker &SlotTracker) const {
2411 O << Indent << "WIDEN-INTRINSIC ";
2412 if (getScalarType()->isVoidTy()) {
2413 O << "void ";
2414 } else {
2416 O << " = ";
2417 }
2418
2419 O << "call";
2420 printFlags(O);
2421 O << getIntrinsicName() << "(";
2423 O << ")";
2424}
2425#endif
2426
2428 CallInst *MemI = createVectorCall(State);
2430 assert(PtrPos && "Expected a memory intrinsic with a valid pointer position");
2431 MemI->addParamAttr(
2432 *PtrPos, Attribute::getWithAlignment(MemI->getContext(), Alignment));
2433 if (!MemI->getType()->isVoidTy())
2434 State.set(this, MemI);
2435}
2436
2438 Intrinsic::ID IID, Type *Ty, bool IsMasked, Align Alignment,
2439 VPCostContext &Ctx) {
2440 return Ctx.TTI.getMemIntrinsicInstrCost(
2441 MemIntrinsicCostAttributes(IID, Ty, /*Ptr=*/nullptr, IsMasked, Alignment),
2442 Ctx.CostKind);
2443}
2444
2447 VPCostContext &Ctx) const {
2448 Type *DataTy;
2450 DataTy = getOperand(*DataPos)->getScalarType();
2451 else
2452 DataTy = getScalarType();
2453 assert(!DataTy->isVoidTy() && "Expected a non-void data type");
2454 Type *Ty = toVectorTy(DataTy, VF);
2456 assert(MaskPos && "Expected a memory intrinsic with a valid mask position");
2458 !match(getOperand(*MaskPos), m_True()),
2459 Alignment, Ctx);
2460}
2461
2463 IRBuilderBase &Builder = State.Builder;
2464
2465 Value *Address = State.get(getOperand(0));
2466 Value *IncAmt = State.get(getOperand(1), /*IsScalar=*/true);
2467 VectorType *VTy = cast<VectorType>(Address->getType());
2468
2469 // The histogram intrinsic requires a mask even if the recipe doesn't;
2470 // if the mask operand was omitted then all lanes should be executed and
2471 // we just need to synthesize an all-true mask.
2472 Value *Mask = nullptr;
2473 if (VPValue *VPMask = getMask())
2474 Mask = State.get(VPMask);
2475 else
2476 Mask =
2477 Builder.CreateVectorSplat(VTy->getElementCount(), Builder.getInt1(1));
2478
2479 // If this is a subtract, we want to invert the increment amount. We may
2480 // add a separate intrinsic in future, but for now we'll try this.
2481 if (Opcode == Instruction::Sub)
2482 IncAmt = Builder.CreateNeg(IncAmt);
2483 else
2484 assert(Opcode == Instruction::Add && "only add or sub supported for now");
2485
2486 Instruction *HistogramInst = State.Builder.CreateIntrinsicWithoutFolding(
2487 Intrinsic::experimental_vector_histogram_add, {VTy, IncAmt->getType()},
2488 {Address, IncAmt, Mask});
2489 applyMetadata(*HistogramInst);
2490}
2491
2493 VPCostContext &Ctx) const {
2494 // FIXME: Take the gather and scatter into account as well. For now we're
2495 // generating the same cost as the fallback path, but we'll likely
2496 // need to create a new TTI method for determining the cost, including
2497 // whether we can use base + vec-of-smaller-indices or just
2498 // vec-of-pointers.
2499 assert(VF.isVector() && "Invalid VF for histogram cost");
2500 Type *AddressTy = getOperand(0)->getScalarType();
2501 VPValue *IncAmt = getOperand(1);
2502 Type *IncTy = IncAmt->getScalarType();
2503 VectorType *VTy = VectorType::get(IncTy, VF);
2504
2505 // Assume that a non-constant update value (or a constant != 1) requires
2506 // a multiply, and add that into the cost.
2507 InstructionCost MulCost =
2508 Ctx.TTI.getArithmeticInstrCost(Instruction::Mul, VTy, Ctx.CostKind);
2509 if (match(IncAmt, m_One()))
2510 MulCost = TTI::TCC_Free;
2511
2512 // Find the cost of the histogram operation itself.
2513 Type *PtrTy = VectorType::get(AddressTy, VF);
2514 Type *MaskTy = VectorType::get(Type::getInt1Ty(Ctx.LLVMCtx), VF);
2515 IntrinsicCostAttributes ICA(Intrinsic::experimental_vector_histogram_add,
2516 Type::getVoidTy(Ctx.LLVMCtx),
2517 {PtrTy, IncTy, MaskTy});
2518
2519 // Add the costs together with the add/sub operation.
2520 return Ctx.TTI.getIntrinsicInstrCost(ICA, Ctx.CostKind) + MulCost +
2521 Ctx.TTI.getArithmeticInstrCost(Opcode, VTy, Ctx.CostKind);
2522}
2523
2524#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2526 VPSlotTracker &SlotTracker) const {
2527 O << Indent << "WIDEN-HISTOGRAM buckets: ";
2529
2530 if (Opcode == Instruction::Sub)
2531 O << ", dec: ";
2532 else {
2533 assert(Opcode == Instruction::Add);
2534 O << ", inc: ";
2535 }
2537
2538 if (VPValue *Mask = getMask()) {
2539 O << ", mask: ";
2540 Mask->printAsOperand(O, SlotTracker);
2541 }
2542}
2543#endif
2544
2545VPIRFlags::FastMathFlagsTy::FastMathFlagsTy(const FastMathFlags &FMF) {
2546 AllowReassoc = FMF.allowReassoc();
2547 NoNaNs = FMF.noNaNs();
2548 NoInfs = FMF.noInfs();
2549 NoSignedZeros = FMF.noSignedZeros();
2550 AllowReciprocal = FMF.allowReciprocal();
2551 AllowContract = FMF.allowContract();
2552 ApproxFunc = FMF.approxFunc();
2553}
2554
2555VPIRFlags VPIRFlags::getDefaultFlags(unsigned Opcode, Type *ResultTy) {
2556 switch (Opcode) {
2557 case Instruction::Add:
2558 case Instruction::Sub:
2559 case Instruction::Mul:
2560 case Instruction::Shl:
2562 return WrapFlagsTy(false, false);
2563 case Instruction::Trunc:
2564 return TruncFlagsTy(false, false);
2565 case Instruction::Or:
2566 return DisjointFlagsTy(false);
2567 case Instruction::AShr:
2568 case Instruction::LShr:
2569 case Instruction::UDiv:
2570 case Instruction::SDiv:
2571 return ExactFlagsTy(false);
2572 case Instruction::GetElementPtr:
2575 return GEPNoWrapFlags::none();
2576 case Instruction::ZExt:
2577 case Instruction::UIToFP:
2578 return NonNegFlagsTy(false);
2579 case Instruction::FAdd:
2580 case Instruction::FSub:
2581 case Instruction::FMul:
2582 case Instruction::FDiv:
2583 case Instruction::FRem:
2584 case Instruction::FNeg:
2585 case Instruction::FPExt:
2586 case Instruction::FPTrunc:
2587 return FastMathFlags();
2588 case Instruction::Select:
2589 case Instruction::PHI:
2590 case Instruction::Call:
2591 // Selects, phis and calls only have fast-math flags if they have a
2592 // supported floating-point result type.
2594 return FastMathFlags();
2595 return VPIRFlags();
2596 case Instruction::ICmp:
2597 case Instruction::FCmp:
2599 llvm_unreachable("opcode requires explicit flags");
2600 default:
2601 return VPIRFlags();
2602 }
2603}
2604
2605#if !defined(NDEBUG)
2606bool VPIRFlags::flagsValidForOpcode(unsigned Opcode) const {
2607 switch (OpType) {
2608 case OperationType::OverflowingBinOp:
2609 return Opcode == Instruction::Add || Opcode == Instruction::Sub ||
2610 Opcode == Instruction::Mul || Opcode == Instruction::Shl ||
2611 Opcode == VPInstruction::VPInstruction::CanonicalIVIncrementForPart;
2612 case OperationType::Trunc:
2613 return Opcode == Instruction::Trunc;
2614 case OperationType::DisjointOp:
2615 return Opcode == Instruction::Or;
2616 case OperationType::PossiblyExactOp:
2617 return Opcode == Instruction::AShr || Opcode == Instruction::LShr ||
2618 Opcode == Instruction::UDiv || Opcode == Instruction::SDiv;
2619 case OperationType::GEPOp:
2620 return Opcode == Instruction::GetElementPtr ||
2621 Opcode == VPInstruction::PtrAdd ||
2622 Opcode == VPInstruction::WidePtrAdd;
2623 case OperationType::FPMathOp:
2624 return Opcode == Instruction::Call || Opcode == Instruction::FAdd ||
2625 Opcode == Instruction::FMul || Opcode == Instruction::FSub ||
2626 Opcode == Instruction::FNeg || Opcode == Instruction::FDiv ||
2627 Opcode == Instruction::FRem || Opcode == Instruction::FPExt ||
2628 Opcode == Instruction::FPTrunc || Opcode == Instruction::PHI ||
2629 Opcode == Instruction::Select || Opcode == Instruction::SIToFP ||
2630 Opcode == Instruction::UIToFP ||
2631 Opcode == VPInstruction::WideIVStep ||
2633 case OperationType::FCmp:
2634 return Opcode == Instruction::FCmp;
2635 case OperationType::NonNegOp:
2636 return Opcode == Instruction::ZExt || Opcode == Instruction::UIToFP;
2637 case OperationType::Cmp:
2638 return Opcode == Instruction::FCmp || Opcode == Instruction::ICmp;
2639 case OperationType::ReductionOp:
2641 case OperationType::Other:
2642 return true;
2643 }
2644 llvm_unreachable("Unknown OperationType enum");
2645}
2646
2648 Type *ResultTy) const {
2649 // Handle opcodes without default flags.
2650 if (Opcode == Instruction::ICmp)
2651 return OpType == OperationType::Cmp;
2652 if (Opcode == Instruction::FCmp)
2653 return OpType == OperationType::FCmp;
2655 return OpType == OperationType::ReductionOp;
2656
2657 OperationType Required = getDefaultFlags(Opcode, ResultTy).OpType;
2658 return Required == OperationType::Other || Required == OpType;
2659}
2660#endif
2661
2662#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2663static void printRecurrenceKind(raw_ostream &OS, const RecurKind &Kind) {
2664 switch (Kind) {
2665 case RecurKind::None:
2666 OS << "none";
2667 break;
2668 case RecurKind::Add:
2669 OS << "add";
2670 break;
2671 case RecurKind::Sub:
2672 OS << "sub";
2673 break;
2675 OS << "add-chain-with-subs";
2676 break;
2677 case RecurKind::Mul:
2678 OS << "mul";
2679 break;
2680 case RecurKind::Or:
2681 OS << "or";
2682 break;
2683 case RecurKind::And:
2684 OS << "and";
2685 break;
2686 case RecurKind::Xor:
2687 OS << "xor";
2688 break;
2689 case RecurKind::SMin:
2690 OS << "smin";
2691 break;
2692 case RecurKind::SMax:
2693 OS << "smax";
2694 break;
2695 case RecurKind::UMin:
2696 OS << "umin";
2697 break;
2698 case RecurKind::UMax:
2699 OS << "umax";
2700 break;
2701 case RecurKind::FAdd:
2702 OS << "fadd";
2703 break;
2705 OS << "fadd-chain-with-subs";
2706 break;
2707 case RecurKind::FSub:
2708 OS << "fsub";
2709 break;
2710 case RecurKind::FMul:
2711 OS << "fmul";
2712 break;
2713 case RecurKind::FMin:
2714 OS << "fmin";
2715 break;
2716 case RecurKind::FMax:
2717 OS << "fmax";
2718 break;
2719 case RecurKind::FMinNum:
2720 OS << "fminnum";
2721 break;
2722 case RecurKind::FMaxNum:
2723 OS << "fmaxnum";
2724 break;
2726 OS << "fminimum";
2727 break;
2729 OS << "fmaximum";
2730 break;
2732 OS << "fminimumnum";
2733 break;
2735 OS << "fmaximumnum";
2736 break;
2737 case RecurKind::FMulAdd:
2738 OS << "fmuladd";
2739 break;
2740 case RecurKind::AnyOf:
2741 OS << "any-of";
2742 break;
2743 case RecurKind::FindIV:
2744 OS << "find-iv";
2745 break;
2747 OS << "find-last";
2748 break;
2749 }
2750}
2751
2753 switch (OpType) {
2754 case OperationType::Cmp:
2756 break;
2757 case OperationType::FCmp:
2760 break;
2761 case OperationType::DisjointOp:
2762 if (DisjointFlags.IsDisjoint)
2763 O << " disjoint";
2764 break;
2765 case OperationType::PossiblyExactOp:
2766 if (ExactFlags.IsExact)
2767 O << " exact";
2768 break;
2769 case OperationType::OverflowingBinOp:
2770 if (WrapFlags.HasNUW)
2771 O << " nuw";
2772 if (WrapFlags.HasNSW)
2773 O << " nsw";
2774 break;
2775 case OperationType::Trunc:
2776 if (TruncFlags.HasNUW)
2777 O << " nuw";
2778 if (TruncFlags.HasNSW)
2779 O << " nsw";
2780 break;
2781 case OperationType::FPMathOp:
2783 break;
2784 case OperationType::GEPOp: {
2786 if (Flags.isInBounds())
2787 O << " inbounds";
2788 else if (Flags.hasNoUnsignedSignedWrap())
2789 O << " nusw";
2790 if (Flags.hasNoUnsignedWrap())
2791 O << " nuw";
2792 break;
2793 }
2794 case OperationType::NonNegOp:
2795 if (NonNegFlags.NonNeg)
2796 O << " nneg";
2797 break;
2798 case OperationType::ReductionOp: {
2799 O << " (";
2801 if (isReductionInLoop())
2802 O << ", in-loop";
2803 if (isReductionOrdered())
2804 O << ", ordered";
2805 O << ")";
2807 break;
2808 }
2809 case OperationType::Other:
2810 break;
2811 }
2812 O << " ";
2813}
2814#endif
2815
2817 auto &Builder = State.Builder;
2818 switch (Opcode) {
2819 case Instruction::Call:
2820 case Instruction::UncondBr:
2821 case Instruction::CondBr:
2822 case Instruction::PHI:
2823 case Instruction::GetElementPtr:
2824 llvm_unreachable("This instruction is handled by a different recipe.");
2825 case Instruction::UDiv:
2826 case Instruction::SDiv:
2827 case Instruction::SRem:
2828 case Instruction::URem:
2829 case Instruction::Add:
2830 case Instruction::FAdd:
2831 case Instruction::Sub:
2832 case Instruction::FSub:
2833 case Instruction::FNeg:
2834 case Instruction::Mul:
2835 case Instruction::FMul:
2836 case Instruction::FDiv:
2837 case Instruction::FRem:
2838 case Instruction::Shl:
2839 case Instruction::LShr:
2840 case Instruction::AShr:
2841 case Instruction::And:
2842 case Instruction::Or:
2843 case Instruction::Xor: {
2844 // Just widen unops and binops.
2846 for (VPValue *VPOp : operands())
2847 Ops.push_back(State.get(VPOp));
2848
2849 Value *V = Builder.CreateNAryOp(Opcode, Ops);
2850
2851 if (auto *VecOp = dyn_cast<Instruction>(V)) {
2852 applyFlags(*VecOp);
2853 applyMetadata(*VecOp);
2854 }
2855
2856 // Use this vector value for all users of the original instruction.
2857 State.set(this, V);
2858 break;
2859 }
2860 case Instruction::ExtractValue: {
2861 assert(getNumOperands() == 2 && "expected single level extractvalue");
2862 Value *Op = State.get(getOperand(0));
2863 Value *Extract = Builder.CreateExtractValue(
2864 Op, cast<VPConstantInt>(getOperand(1))->getZExtValue());
2865 State.set(this, Extract);
2866 break;
2867 }
2868 case Instruction::Freeze: {
2869 Value *Op = State.get(getOperand(0));
2870 Value *Freeze = Builder.CreateFreeze(Op);
2871 State.set(this, Freeze);
2872 break;
2873 }
2874 case Instruction::ICmp:
2875 case Instruction::FCmp: {
2876 // Widen compares. Generate vector compares.
2877 bool FCmp = Opcode == Instruction::FCmp;
2878 Value *A = State.get(getOperand(0));
2879 Value *B = State.get(getOperand(1));
2880 Value *C = nullptr;
2881 if (FCmp) {
2882 C = Builder.CreateFCmp(getPredicate(), A, B);
2883 } else {
2884 C = Builder.CreateICmp(getPredicate(), A, B);
2885 }
2886 if (auto *I = dyn_cast<Instruction>(C)) {
2887 applyFlags(*I);
2888 applyMetadata(*I);
2889 }
2890 State.set(this, C);
2891 break;
2892 }
2893 case Instruction::Select: {
2894 VPValue *CondOp = getOperand(0);
2895 Value *Cond = State.get(CondOp, vputils::isSingleScalar(CondOp));
2896 Value *Op0 = State.get(getOperand(1));
2897 Value *Op1 = State.get(getOperand(2));
2898 Value *Sel = State.Builder.CreateSelect(Cond, Op0, Op1);
2899 State.set(this, Sel);
2900 if (auto *I = dyn_cast<Instruction>(Sel)) {
2902 applyFlags(*I);
2903 applyMetadata(*I);
2904 }
2905 break;
2906 }
2907 default:
2908 // This instruction is not vectorized by simple widening.
2909 LLVM_DEBUG(dbgs() << "LV: Found an unhandled opcode : "
2910 << Instruction::getOpcodeName(Opcode));
2911 llvm_unreachable("Unhandled instruction!");
2912 } // end of switch.
2913
2914#if !defined(NDEBUG)
2915 // Verify that VPlan type inference results agree with the type of the
2916 // generated values.
2917 assert(VectorType::get(this->getScalarType(), State.VF) ==
2918 State.get(this)->getType() &&
2919 "inferred type and type from generated instructions do not match");
2920#endif
2921}
2922
2924 VPCostContext &Ctx) const {
2925 switch (Opcode) {
2926 case Instruction::UDiv:
2927 case Instruction::SDiv:
2928 case Instruction::SRem:
2929 case Instruction::URem:
2930 // If the div/rem operation isn't safe to speculate and requires
2931 // predication, then the only way we can even create a vplan is to insert
2932 // a select on the second input operand to ensure we use the value of 1
2933 // for the inactive lanes. The select will be costed separately.
2934 case Instruction::FNeg:
2935 case Instruction::Add:
2936 case Instruction::FAdd:
2937 case Instruction::Sub:
2938 case Instruction::FSub:
2939 case Instruction::Mul:
2940 case Instruction::FMul:
2941 case Instruction::FDiv:
2942 case Instruction::FRem:
2943 case Instruction::Shl:
2944 case Instruction::LShr:
2945 case Instruction::AShr:
2946 case Instruction::And:
2947 case Instruction::Or:
2948 case Instruction::Xor:
2949 case Instruction::Freeze:
2950 case Instruction::ExtractValue:
2951 case Instruction::ICmp:
2952 case Instruction::FCmp:
2953 case Instruction::Select:
2954 return getCostForRecipeWithOpcode(getOpcode(), VF, Ctx);
2955 default:
2956 llvm_unreachable("Unsupported opcode for instruction");
2957 }
2958}
2959
2960#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2962 VPSlotTracker &SlotTracker) const {
2963 O << Indent << "WIDEN ";
2965 O << " = " << Instruction::getOpcodeName(Opcode);
2966 printFlags(O);
2968}
2969#endif
2970
2972 auto &Builder = State.Builder;
2973 /// Vectorize casts.
2974 assert(State.VF.isVector() && "Not vectorizing?");
2975 Type *DestTy = VectorType::get(getScalarType(), State.VF);
2976 VPValue *Op = getOperand(0);
2977 Value *A = State.get(Op);
2978 Value *Cast = Builder.CreateCast(Instruction::CastOps(Opcode), A, DestTy);
2979 State.set(this, Cast);
2980 if (auto *CastOp = dyn_cast<Instruction>(Cast)) {
2981 applyFlags(*CastOp);
2982 applyMetadata(*CastOp);
2983 }
2984}
2985
2990
2991#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2993 VPSlotTracker &SlotTracker) const {
2994 O << Indent << "WIDEN-CAST ";
2996 O << " = " << Instruction::getOpcodeName(Opcode);
2997 printFlags(O);
2999 O << " to " << *getScalarType();
3000}
3001#endif
3002
3004 VPCostContext &Ctx) const {
3005 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
3006}
3007
3008#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3010 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
3011 O << Indent;
3013 O << " = WIDEN-INDUCTION";
3014 printFlags(O);
3016
3017 if (auto *TI = getTruncInst())
3018 O << " (truncated to " << *TI->getType() << ")";
3019}
3020#endif
3021
3023 // The step may be defined by a recipe in the preheader (e.g. if it requires
3024 // SCEV expansion), but for the canonical induction the step is required to be
3025 // 1, which is represented as live-in.
3026 return match(getStartValue(), m_ZeroInt()) &&
3027 match(getStepValue(), m_One()) &&
3028 getScalarType() == getRegion()->getCanonicalIVType();
3029}
3030
3033 VPCostContext &Ctx) const {
3034 // A widened induction generates a vector phi and increments it by the
3035 // splatted step each iteration.
3037 InstructionCost Cost = Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
3038 Type *StepTy = getScalarType();
3039 unsigned IncOpc = ID.getKind() == InductionDescriptor::IK_IntInduction
3040 ? Instruction::Add
3041 : ID.getInductionOpcode();
3042 assert(IncOpc != Instruction::BinaryOpsEnd &&
3043 "induction must have a valid increment opcode");
3044 return Cost + Ctx.TTI.getArithmeticInstrCost(IncOpc, toVectorTy(StepTy, VF),
3045 Ctx.CostKind);
3046}
3047
3048/// Returns the ConstantFP \p V wraps, or nullptr if it does not wrap one.
3049static const ConstantFP *getConstantFP(const VPValue *V) {
3050 auto *C = dyn_cast<VPConstant>(V);
3051 return C ? dyn_cast<ConstantFP>(C->getConstant()) : nullptr;
3052}
3053
3055 VPCostContext &Ctx) const {
3056 // The cost model for this is modelled on expandVPDerivedIV in
3057 // VPlanTransforms.cpp. In order to avoid overly pessimistic costs that can
3058 // negatively affect vectorization it takes into account any expected
3059 // simplifications that happen in simplifyRecipe.
3060 switch (getInductionKind()) {
3061 default:
3062 // TODO: Compute cost for remaining kinds.
3063 break;
3065 // There are currently no tests that expose a path where all lanes are
3066 // used, so it's better to bail out for now.
3067 if (!vputils::onlyFirstLaneUsed(this))
3068 break;
3069
3070 // Start off by assuming we need both mul and add, then refine this.
3071 bool NeedsMul = true, NeedsAdd = true, NeedsShl = false;
3072
3073 // If the start value is zero the add gets folded away.
3074 if (auto *StartC = dyn_cast<VPConstantInt>(getStartValue()))
3075 NeedsAdd = !StartC->isZero();
3076
3077 // For some values of step the arithmetic changes:
3078 // 1. A step of 1 requires no operation.
3079 // 2. A step of -1 requires a negate.
3080 // 3. A power-of-2 step will use a shl, instead of a mul.
3081 Type *StepTy = getStepValue()->getScalarType();
3083 if (auto *StepC = dyn_cast<VPConstantInt>(getStepValue())) {
3084 if (StepC->isOne())
3085 NeedsMul = false;
3086 else if (StepC->getAPInt().isAllOnes()) {
3087 // This will most likely end up as a negate in simplifyRecipe, and
3088 // the negate will be combined with the add to make a sub.
3089 // NOTE: This is perhaps an invalid assumption that the cost of an
3090 // 'add' is the same as a 'sub'.
3091 NeedsMul = false;
3092 NeedsAdd = true;
3093 } else if (StepC->getAPInt().isPowerOf2()) {
3094 // This will most likely end up as a shift-left in simplifyRecipe
3095 NeedsMul = false;
3096 NeedsShl = true;
3097 }
3098 }
3099
3100 // Add the cost of the conversion from index to step type if the index
3101 // will be used.
3102 Type *IndexTy = getIndex()->getScalarType();
3103 unsigned StepTySize = StepTy->getScalarSizeInBits();
3104 unsigned IndexTySize = IndexTy->getScalarSizeInBits();
3105 if ((NeedsAdd || NeedsMul || NeedsShl) && StepTySize != IndexTySize) {
3106 unsigned CastOpc =
3107 StepTySize < IndexTySize ? Instruction::Trunc : Instruction::ZExt;
3108 Cost += Ctx.TTI.getCastInstrCost(
3109 CastOpc, StepTy, IndexTy, TTI::CastContextHint::None, Ctx.CostKind);
3110 }
3111
3112 if (NeedsMul)
3113 Cost += Ctx.TTI.getArithmeticInstrCost(Instruction::Mul, StepTy,
3114 Ctx.CostKind);
3115 if (NeedsShl)
3116 Cost += Ctx.TTI.getArithmeticInstrCost(
3117 Instruction::Shl, StepTy, Ctx.CostKind,
3118 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
3119 {TargetTransformInfo::OK_UniformConstantValue,
3120 TargetTransformInfo::OP_None});
3121 if (NeedsAdd)
3122 Cost += Ctx.TTI.getArithmeticInstrCost(Instruction::Add, StepTy,
3123 Ctx.CostKind);
3124 return Cost;
3125 }
3127 // There are currently no tests that expose a path where all lanes are
3128 // used, so it's better to bail out for now.
3129 if (!vputils::onlyFirstLaneUsed(this))
3130 break;
3131
3132 // Unlike the integer case, converting the index to the FP step type is
3133 // unavoidable: the index is always the integer canonical IV, so this
3134 // cast is never folded away.
3135 Type *StepTy = getStepValue()->getScalarType();
3136 Type *IndexTy = getIndex()->getScalarType();
3138 Ctx.TTI.getCastInstrCost(Instruction::SIToFP, StepTy, IndexTy,
3139 TTI::CastContextHint::None, Ctx.CostKind);
3140
3141 // If the step is 1.0, the multiply is an exact identity and gets folded
3142 // away, independent of fast-math flags.
3143 const ConstantFP *StepC = getConstantFP(getStepValue());
3144 bool NeedsMul = !StepC || !StepC->isOne();
3145
3146 // "fadd -0.0, X" folds to X unconditionally, but "fadd 0.0, X" only folds
3147 // to X without nsz if X can be proven to never be -0.0, which we cannot, as
3148 // Step may be -0.0.
3149 // TODO: Consider fast-math flags when they are available in
3150 // VPDerivedIVRecipe.
3151 const ConstantFP *StartC = getConstantFP(getStartValue());
3152 bool AddFolds = getFPBinOp()->getOpcode() == Instruction::FAdd && StartC &&
3153 StartC->isZero() && (StartC->isNegZero() || !NeedsMul);
3154
3155 if (NeedsMul)
3156 Cost += Ctx.TTI.getArithmeticInstrCost(Instruction::FMul, StepTy,
3157 Ctx.CostKind);
3158 if (!AddFolds)
3159 Cost += Ctx.TTI.getArithmeticInstrCost(getFPBinOp()->getOpcode(), StepTy,
3160 Ctx.CostKind);
3161 return Cost;
3162 }
3163 }
3164
3165 return 0;
3166}
3167
3168#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3170 VPSlotTracker &SlotTracker) const {
3171 O << Indent;
3173 O << " = DERIVED-IV";
3174 printFlags(O);
3175 getStartValue()->printAsOperand(O, SlotTracker);
3176 O << " + ";
3177 getOperand(1)->printAsOperand(O, SlotTracker);
3178 O << " * ";
3179 getStepValue()->printAsOperand(O, SlotTracker);
3180}
3181#endif
3182
3186
3188 VPCostContext &Ctx) const {
3189 Type *BaseIVTy = getOperand(0)->getScalarType();
3190 assert((BaseIVTy->isIntegerTy() || BaseIVTy->isFloatingPointTy()) &&
3191 "VPScalarIVStepsRecipe is only created for integer and FP inductions");
3192
3193 // If only the first lane is used, then there won't be any code that remains
3194 // in the loop for the first unrolled part.
3196 return 0;
3197
3198 // If the vector body executes at most once, the canonical IV is a constant
3199 // and every lane's step folds away with it.
3200 if (VPCostContext::executesAtMostOnce(*getParent()->getPlan(), VF))
3201 return 0;
3202
3203 // Typically the operations are:
3204 // 1. Add the start index to each lane value.
3205 // 2. Multiply the start index by the step.
3206 // 3. Add the scaled start index to base IV.
3207 // Any code generated for 1 and 2 should be loop invariant and therefore
3208 // hoisted out of the loop. We only need to add on the cost of 3.
3210 if (BaseIVTy->isFloatingPointTy()) {
3211 // Unlike the integer case, the users of an FP induction cannot be re-based
3212 // on a common value, so each lane needs its own FAdd/FSub.
3213 assert(!VF.isScalable() &&
3214 "FP scalar steps for all lanes are only created for fixed VFs");
3215 Cost = Ctx.TTI.getArithmeticInstrCost(InductionOpcode, BaseIVTy,
3216 Ctx.CostKind) *
3217 (VF.getFixedValue() - 1);
3218 } else {
3219 // Given the users of VPScalarIVStepsRecipe tend to be scalarized GEPs, i.e.
3220 // %add1 = add i32 %iv, 0
3221 // %add2 = add i32 %iv, 1
3222 // %gep1 = getelementptr i8, ptr %p, i32 %add1
3223 // %gep2 = getelementptr i8, ptr %p, i32 %add2
3224 // it's very likely that these GEPs will all be rewritten to have a common
3225 // base such that what's left is just
3226 // %base_gep = getelementptr i8, ptr %p, i32 %iv
3227 // %gep1 = getelementptr i8, ptr %base_gep, i32 0
3228 // %gep2 = getelementptr i8, ptr %base_gep, i32 1
3229 // Therefore, in reality the cost is somewhere betwen 1*AddCost and
3230 // (NumLanes - 1) * AddCost. For now, assume the cost of a single add.
3231 Cost = Ctx.TTI.getArithmeticInstrCost(Instruction::Add, BaseIVTy,
3232 Ctx.CostKind);
3233 }
3234
3235 // If the steps are generated inside a replicate region, scale by execution
3236 // probability.
3237 const VPRegionBlock *Region = getRegion();
3238 if (Region && Region->isReplicator())
3239 Cost /= Ctx.getReplicateRegionCostDivisor(Region);
3240 return Cost;
3241}
3242
3244 // Fast-math-flags propagate from the original induction instruction.
3245 IRBuilder<>::FastMathFlagGuard FMFG(State.Builder);
3246 State.Builder.setFastMathFlags(getFastMathFlagsOrNone());
3247
3248 /// Compute scalar induction steps. \p ScalarIV is the scalar induction
3249 /// variable on which to base the steps, \p Step is the size of the step.
3250
3251 Value *BaseIV = State.get(getOperand(0), VPLane(0));
3252 Value *Step = State.get(getStepValue(), VPLane(0));
3253 IRBuilderBase &Builder = State.Builder;
3254
3255 // Ensure step has the same type as that of scalar IV.
3256 Type *BaseIVTy = BaseIV->getType()->getScalarType();
3257 assert(BaseIVTy == Step->getType() && "Types of BaseIV and Step must match!");
3258
3259 // We build scalar steps for both integer and floating-point induction
3260 // variables. Here, we determine the kind of arithmetic we will perform.
3263 if (BaseIVTy->isIntegerTy()) {
3264 AddOp = Instruction::Add;
3265 MulOp = Instruction::Mul;
3266 } else {
3267 AddOp = InductionOpcode;
3268 MulOp = Instruction::FMul;
3269 }
3270
3271 // Lanes other than the first have been materialized as separate
3272 // single-scalar recipes by replicateByVF, each with its own start index.
3273 assert((vputils::onlyFirstLaneUsed(this) || State.VF.isScalar()) &&
3274 "must have been replicated by VF");
3275 Value *StartIdx = getStartIndex() ? State.get(getStartIndex(), true)
3276 : Constant::getNullValue(BaseIVTy);
3277 auto *Mul = Builder.CreateBinOp(MulOp, StartIdx, Step);
3278 auto *Add = Builder.CreateBinOp(AddOp, BaseIV, Mul);
3279 State.set(this, Add, VPLane(0));
3280}
3281
3282#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3284 VPSlotTracker &SlotTracker) const {
3285 O << Indent;
3287 O << " = SCALAR-STEPS ";
3289}
3290#endif
3291
3293 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
3295}
3296
3298 assert(State.VF.isVector() && "not widening");
3299 auto Ops = map_to_vector(operands(), [&](VPValue *Op) {
3300 return State.get(Op, vputils::isSingleScalar(Op));
3301 });
3302 auto *GEP =
3303 State.Builder.CreateGEP(getSourceElementType(), Ops.front(),
3304 drop_begin(Ops), "wide.gep", getGEPNoWrapFlags());
3305 State.set(this, GEP, vputils::isSingleScalar(this));
3306}
3307
3308#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3310 VPSlotTracker &SlotTracker) const {
3311 O << Indent << "WIDEN-GEP ";
3313 O << " = getelementptr";
3314 printFlags(O);
3316}
3317#endif
3318
3320 assert(!getOffset() && "Unexpected offset operand");
3321 VPBuilder Builder(this);
3322 VPlan &Plan = *getParent()->getPlan();
3323 VPValue *VFVal = getVFValue();
3324 const DataLayout &DL = Plan.getDataLayout();
3325 Type *IndexTy = DL.getIndexType(this->getScalarType());
3326 VPValue *Stride =
3327 Plan.getConstantInt(IndexTy, getStride(), /*IsSigned=*/true);
3328 VPValue *VF =
3329 Builder.createScalarZExtOrTrunc(VFVal, IndexTy, DebugLoc::getUnknown());
3330
3331 // Offset for Part0 = Offset0 = Stride * (VF - 1).
3332 VPInstruction *VFMinusOne =
3333 Builder.createSub(VF, Plan.getConstantInt(IndexTy, 1u),
3334 DebugLoc::getUnknown(), "", {true, true});
3335 VPInstruction *Offset0 =
3336 Builder.createOverflowingOp(Instruction::Mul, {VFMinusOne, Stride});
3337
3338 // Offset for PartN = Offset0 + Part * Stride * VF.
3339 VPValue *PartxStride =
3340 Plan.getConstantInt(IndexTy, Part * getStride(), /*IsSigned=*/true);
3341 VPValue *Offset = Builder.createAdd(
3342 Offset0,
3343 Builder.createOverflowingOp(Instruction::Mul, {PartxStride, VF}));
3345}
3346
3348 auto &Builder = State.Builder;
3349 assert(getOffset() && "Expected prior materialization of offset");
3350 Value *Ptr = State.get(getPointer(), true);
3351 Value *Offset = State.get(getOffset(), true);
3352 Value *ResultPtr = Builder.CreateGEP(getSourceElementType(), Ptr, Offset, "",
3354 State.set(this, ResultPtr, /*IsScalar*/ true);
3355}
3356
3357#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3359 VPSlotTracker &SlotTracker) const {
3360 O << Indent;
3362 O << " = vector-end-pointer";
3363 printFlags(O);
3364 getSourceElementType()->print(O);
3365 O << ", ";
3367}
3368#endif
3369
3371 assert(getVFxPart() &&
3372 "Expected prior simplification of recipe without VFxPart");
3373
3374 auto &Builder = State.Builder;
3375 Value *Ptr = State.get(getOperand(0), VPLane(0));
3376 Value *Offset = State.get(getVFxPart(), true);
3377 // TODO: Expand to VPInstruction to support constant folding.
3378 if (!match(getStride(), m_One())) {
3379 Value *Stride = Builder.CreateZExtOrTrunc(State.get(getStride(), true),
3380 Offset->getType());
3381 Offset = Builder.CreateMul(Offset, Stride);
3382 }
3383 Value *ResultPtr = Builder.CreateGEP(getSourceElementType(), Ptr, Offset, "",
3385 State.set(this, ResultPtr, /*IsScalar*/ true);
3386}
3387
3388#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3390 VPSlotTracker &SlotTracker) const {
3391 O << Indent;
3393 O << " = vector-pointer";
3394 printFlags(O);
3395 getSourceElementType()->print(O);
3396 O << ", ";
3398}
3399#endif
3400
3402 VPCostContext &Ctx) const {
3403 // A blend will be expanded to a select VPInstruction, which will generate a
3404 // scalar select if only the first lane is used.
3406 VF = ElementCount::getFixed(1);
3407
3408 Type *ResultTy = toVectorTy(this->getScalarType(), VF);
3409 Type *CmpTy = toVectorTy(Type::getInt1Ty(Ctx.LLVMCtx), VF);
3410
3412 for (unsigned I = 1, E = getNumIncomingValues(); I != E; ++I) {
3413 CmpPredicate Pred;
3414 if (!match(getMask(I), m_Cmp(Pred, m_VPValue(), m_VPValue())))
3415 Pred = getScalarType()->isFloatingPointTy() ? CmpInst::BAD_FCMP_PREDICATE
3417 Cost += Ctx.TTI.getCmpSelInstrCost(Instruction::Select, ResultTy, CmpTy,
3418 Pred, Ctx.CostKind);
3419 }
3420 return Cost;
3421}
3422
3423#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3425 VPSlotTracker &SlotTracker) const {
3426 O << Indent << "BLEND ";
3428 O << " =";
3429 printFlags(O);
3430 if (getNumIncomingValues() == 1) {
3431 // Not a User of any mask: not really blending, this is a
3432 // single-predecessor phi.
3433 getIncomingValue(0)->printAsOperand(O, SlotTracker);
3434 } else {
3435 for (unsigned I = 0, E = getNumIncomingValues(); I < E; ++I) {
3436 if (I != 0)
3437 O << " ";
3438 getIncomingValue(I)->printAsOperand(O, SlotTracker);
3439 if (I == 0 && isNormalized())
3440 continue;
3441 O << "/";
3442 getMask(I)->printAsOperand(O, SlotTracker);
3443 }
3444 }
3445}
3446#endif
3447
3451 "In-loop AnyOf reductions aren't currently supported");
3452 // Propagate the fast-math flags carried by the underlying instruction.
3453 IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder);
3454 State.Builder.setFastMathFlags(getFastMathFlagsOrNone());
3455 Value *NewVecOp = State.get(getVecOp());
3456 if (VPValue *Cond = getCondOp()) {
3457 Value *NewCond = State.get(Cond, State.VF.isScalar());
3458 VectorType *VecTy = dyn_cast<VectorType>(NewVecOp->getType());
3459 Type *ElementTy = VecTy ? VecTy->getElementType() : NewVecOp->getType();
3460
3461 Value *Start =
3463 if (State.VF.isVector())
3464 Start = State.Builder.CreateVectorSplat(VecTy->getElementCount(), Start);
3465
3466 Value *Select = State.Builder.CreateSelect(NewCond, NewVecOp, Start);
3467 NewVecOp = Select;
3468 }
3469 Value *NewRed;
3470 Value *NextInChain;
3471 if (isOrdered()) {
3472 Value *PrevInChain = State.get(getChainOp(), /*IsScalar*/ true);
3473 if (State.VF.isVector())
3474 NewRed =
3475 createOrderedReduction(State.Builder, Kind, NewVecOp, PrevInChain);
3476 else
3477 NewRed = State.Builder.CreateBinOp(
3479 PrevInChain, NewVecOp);
3480 PrevInChain = NewRed;
3481 NextInChain = NewRed;
3482 } else if (isPartialReduction()) {
3483 assert((Kind == RecurKind::Add || Kind == RecurKind::FAdd) &&
3484 "Unexpected partial reduction kind");
3485 Value *PrevInChain = State.get(getChainOp(), /*IsScalar*/ false);
3486 NewRed = State.Builder.CreateIntrinsic(
3487 PrevInChain->getType(),
3488 Kind == RecurKind::Add ? Intrinsic::vector_partial_reduce_add
3489 : Intrinsic::vector_partial_reduce_fadd,
3490 {PrevInChain, NewVecOp}, State.Builder.getFastMathFlags(),
3491 "partial.reduce");
3492 PrevInChain = NewRed;
3493 NextInChain = NewRed;
3494 } else {
3495 assert(isInLoop() &&
3496 "The reduction must either be ordered, partial or in-loop");
3497 Value *PrevInChain = State.get(getChainOp(), /*IsScalar*/ true);
3498 NewRed = createSimpleReduction(State.Builder, NewVecOp, Kind);
3500 NextInChain = createMinMaxOp(State.Builder, Kind, NewRed, PrevInChain);
3501 else
3502 NextInChain = State.Builder.CreateBinOp(
3504 PrevInChain, NewRed);
3505 }
3506 State.set(this, NextInChain, /*IsScalar*/ !isPartialReduction());
3507}
3508
3510
3511 assert(State.VF.isVector() &&
3512 "Shouldn't generate VPReductionEVLRecipe with scalar VF");
3513 auto &Builder = State.Builder;
3514 // Propagate the fast-math flags carried by the underlying instruction.
3515 IRBuilderBase::FastMathFlagGuard FMFGuard(Builder);
3516 Builder.setFastMathFlags(getFastMathFlagsOrNone());
3517
3519 Value *Prev = State.get(getChainOp(), /*IsScalar*/ !isPartialReduction());
3520 Value *VecOp = State.get(getVecOp());
3521 Value *EVL = State.get(getEVL(), VPLane(0));
3522
3523 Value *Mask;
3524 if (VPValue *CondOp = getCondOp())
3525 Mask = State.get(CondOp);
3526 else
3527 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
3528
3529 Value *NewRed;
3530 if (isPartialReduction()) {
3531 // For partial reductions, we need to generate a predicated select
3532 // (vp.merge) since `@llvm.vector.partial.reduce()` doesn't have a vector
3533 // predicated version.
3534 VectorType *VecTy = cast<VectorType>(VecOp->getType());
3535 Value *Identity = getRecurrenceIdentity(Kind, VecTy->getElementType(),
3537 Identity =
3538 State.Builder.CreateVectorSplat(VecTy->getElementCount(), Identity);
3539
3540 // TODO: Calculate the predicate cost for the partial reduction.
3541 Value *NewVecOp = State.Builder.CreateIntrinsic(
3542 VecTy, Intrinsic::vp_merge, {Mask, VecOp, Identity, EVL});
3543 assert((Kind == RecurKind::Add || Kind == RecurKind::FAdd) &&
3544 "Unexpected partial reduction kind");
3545 NewRed = State.Builder.CreateIntrinsic(
3546 Prev->getType(),
3547 Kind == RecurKind::Add ? Intrinsic::vector_partial_reduce_add
3548 : Intrinsic::vector_partial_reduce_fadd,
3549 {Prev, NewVecOp}, State.Builder.getFastMathFlags(), "partial.reduce");
3550 } else if (isOrdered()) {
3551 NewRed = createOrderedReduction(Builder, Kind, VecOp, Prev, Mask, EVL);
3552 } else {
3553 NewRed = createSimpleReduction(Builder, VecOp, Kind, Mask, EVL);
3555 NewRed = createMinMaxOp(Builder, Kind, NewRed, Prev);
3556 else
3557 NewRed = Builder.CreateBinOp(
3559 Prev);
3560 }
3561 State.set(this, NewRed, !isPartialReduction());
3562}
3563
3565 VPCostContext &Ctx) const {
3566 RecurKind RdxKind = getRecurrenceKind();
3567 Type *ElementTy = this->getScalarType();
3568 auto *VectorTy = cast<VectorType>(toVectorTy(ElementTy, VF));
3569 unsigned Opcode = RecurrenceDescriptor::getOpcode(RdxKind);
3571 std::optional<FastMathFlags> OptionalFMF =
3572 ElementTy->isFloatingPointTy() ? std::make_optional(FMFs) : std::nullopt;
3573
3574 if (isPartialReduction()) {
3575 InstructionCost CondCost = 0;
3576 if (isConditional()) {
3578 auto *CondTy =
3580 CondCost = Ctx.TTI.getCmpSelInstrCost(Instruction::Select, VectorTy,
3581 CondTy, Pred, Ctx.CostKind);
3582 }
3583 return CondCost + Ctx.TTI.getPartialReductionCost(
3584 Opcode, ElementTy, nullptr, ElementTy, VF,
3585 TTI::PR_None, TTI::PR_None, {}, Ctx.CostKind,
3586 OptionalFMF);
3587 }
3588
3589 // TODO: Support any-of reductions.
3590 assert(
3592 ForceTargetInstructionCost.getNumOccurrences() > 0) &&
3593 "Any-of reduction not implemented in VPlan-based cost model currently.");
3594
3595 // Note that TTI should model the cost of moving result to the scalar register
3596 // and the BinOp cost in the getMinMaxReductionCost().
3599 return Ctx.TTI.getMinMaxReductionCost(Id, VectorTy, FMFs, Ctx.CostKind);
3600 }
3601
3602 // Note that TTI should model the cost of moving result to the scalar register
3603 // and the BinOp cost in the getArithmeticReductionCost().
3604 return Ctx.TTI.getArithmeticReductionCost(Opcode, VectorTy, OptionalFMF,
3605 Ctx.CostKind);
3606}
3607
3609 ExpressionTypes ExpressionType,
3610 ArrayRef<VPSingleDefRecipe *> ExpressionRecipes)
3611 : VPSingleDefRecipe(VPRecipeBase::VPExpressionSC, {},
3612 cast<VPReductionRecipe>(ExpressionRecipes.back())
3613 ->getChainOp()
3614 ->getScalarType()),
3615 ExpressionRecipes(ExpressionRecipes), ExpressionType(ExpressionType) {
3616 assert(!ExpressionRecipes.empty() && "Nothing to combine?");
3617 assert(
3618 none_of(ExpressionRecipes,
3619 [](VPSingleDefRecipe *R) { return R->mayHaveSideEffects(); }) &&
3620 "expression cannot contain recipes with side-effects");
3621
3622 // Maintain a copy of the expression recipes as a set of users.
3623 SmallPtrSet<VPUser *, 4> ExpressionRecipesAsSetOfUsers;
3624 for (auto *R : ExpressionRecipes)
3625 ExpressionRecipesAsSetOfUsers.insert(R);
3626
3627 // Recipes in the expression, except the last one, must only be used by
3628 // (other) recipes inside the expression. If there are other users, external
3629 // to the expression, use a clone of the recipe for external users.
3630 for (VPSingleDefRecipe *R : reverse(ExpressionRecipes)) {
3631 if (R != ExpressionRecipes.back() &&
3632 any_of(R->users(), [&ExpressionRecipesAsSetOfUsers](VPUser *U) {
3633 return !ExpressionRecipesAsSetOfUsers.contains(U);
3634 })) {
3635 // There are users outside of the expression. Clone the recipe and use the
3636 // clone those external users.
3637 VPSingleDefRecipe *CopyForExtUsers = R->clone();
3638 R->replaceUsesWithIf(CopyForExtUsers, [&ExpressionRecipesAsSetOfUsers](
3639 VPUser &U, unsigned) {
3640 return !ExpressionRecipesAsSetOfUsers.contains(&U);
3641 });
3642 CopyForExtUsers->insertBefore(R);
3643 }
3644 if (R->getParent())
3645 R->removeFromParent();
3646 }
3647
3648 // Internalize all external operands to the expression recipes. To do so,
3649 // create new temporary VPValues for all operands defined by a recipe outside
3650 // the expression. The original operands are added as operands of the
3651 // VPExpressionRecipe itself.
3652 for (auto *R : ExpressionRecipes) {
3653 for (const auto &[Idx, Op] : enumerate(R->operands())) {
3654 auto *Def = Op->getDefiningRecipe();
3655 if (Def && ExpressionRecipesAsSetOfUsers.contains(Def))
3656 continue;
3657 addOperand(Op);
3658 LiveInPlaceholders.push_back(new VPSymbolicValue(Op->getScalarType()));
3659 }
3660 }
3661
3662 // Replace each external operand with the first one created for it in
3663 // LiveInPlaceholders.
3664 for (auto *R : ExpressionRecipes)
3665 for (auto const &[LiveIn, Tmp] : zip(operands(), LiveInPlaceholders))
3666 R->replaceUsesOfWith(LiveIn, Tmp);
3667}
3668
3670 for (auto *R : ExpressionRecipes)
3671 // Since the list could contain duplicates, make sure the recipe hasn't
3672 // already been inserted.
3673 if (!R->getParent())
3674 R->insertBefore(this);
3675
3676 for (const auto &[Idx, Op] : enumerate(operands()))
3677 LiveInPlaceholders[Idx]->replaceAllUsesWith(Op);
3678
3679 replaceAllUsesWith(ExpressionRecipes.back());
3680 SmallVector<VPSingleDefRecipe *> DecomposedRecipes(ExpressionRecipes);
3681 ExpressionRecipes.clear();
3682 return DecomposedRecipes;
3683}
3684
3686 VPCostContext &Ctx) const {
3687 Type *RedTy = this->getScalarType();
3688 auto *SrcVecTy =
3690 unsigned Opcode = RecurrenceDescriptor::getOpcode(
3691 cast<VPReductionRecipe>(ExpressionRecipes.back())->getRecurrenceKind());
3692 switch (ExpressionType) {
3693 case ExpressionTypes::NegatedExtendedReduction:
3694 assert((Opcode == Instruction::Add || Opcode == Instruction::FAdd) &&
3695 "Unexpected opcode");
3696 Opcode = Opcode == Instruction::Add ? Instruction::Sub : Instruction::FSub;
3697 [[fallthrough]];
3698 case ExpressionTypes::ExtendedReduction: {
3699 auto *RedR = cast<VPReductionRecipe>(ExpressionRecipes.back());
3700 auto *ExtR = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3701
3702 if (RedR->isPartialReduction())
3703 return Ctx.TTI.getPartialReductionCost(
3704 Opcode, getOperand(0)->getScalarType(), nullptr, RedTy, VF,
3706 TargetTransformInfo::PR_None, std::nullopt, Ctx.CostKind,
3707 RedTy->isFloatingPointTy()
3708 ? std::optional{RedR->getFastMathFlagsOrNone()}
3709 : std::nullopt);
3710 else if (!RedTy->isFloatingPointTy())
3711 // TTI::getExtendedReductionCost only supports integer types.
3712 return Ctx.TTI.getExtendedReductionCost(
3713 Opcode, ExtR->getOpcode() == Instruction::ZExt, RedTy, SrcVecTy,
3714 std::nullopt, Ctx.CostKind);
3715 else
3717 }
3718 case ExpressionTypes::MulAccReduction:
3719 return Ctx.TTI.getMulAccReductionCost(false, Opcode, RedTy, SrcVecTy,
3720 Ctx.CostKind);
3721
3722 case ExpressionTypes::ExtNegatedMulAccReduction:
3723 switch (Opcode) {
3724 case Instruction::Add:
3725 Opcode = Instruction::Sub;
3726 break;
3727 case Instruction::FAdd:
3728 Opcode = Instruction::FSub;
3729 break;
3730 default:
3731 llvm_unreachable("Unsupported opcode for ExtNegatedMulAccReduction");
3732 }
3733 [[fallthrough]];
3734 case ExpressionTypes::ExtMulAccReduction: {
3735 auto *RedR = cast<VPReductionRecipe>(ExpressionRecipes.back());
3736 if (RedR->isPartialReduction()) {
3737 auto *Ext0R = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3738 auto *Ext1R = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
3739 auto *Mul = cast<VPWidenRecipe>(ExpressionRecipes[2]);
3740 return Ctx.TTI.getPartialReductionCost(
3741 Opcode, getOperand(0)->getScalarType(),
3742 getOperand(1)->getScalarType(), RedTy, VF,
3744 Ext0R->getOpcode()),
3746 Ext1R->getOpcode()),
3747 Mul->getOpcode(), Ctx.CostKind,
3748 RedTy->isFloatingPointTy()
3749 ? std::optional{RedR->getFastMathFlagsOrNone()}
3750 : std::nullopt);
3751 }
3752 assert(Opcode != Instruction::FSub && "Only integer types are supported");
3753 return Ctx.TTI.getMulAccReductionCost(
3754 cast<VPWidenCastRecipe>(ExpressionRecipes.front())->getOpcode() ==
3755 Instruction::ZExt,
3756 Opcode, RedTy, SrcVecTy, Ctx.CostKind);
3757 }
3758 }
3759 llvm_unreachable("Unknown VPExpressionRecipe::ExpressionTypes enum");
3760}
3761
3763 return any_of(ExpressionRecipes, [](VPSingleDefRecipe *R) {
3764 return R->mayReadFromMemory() || R->mayWriteToMemory();
3765 });
3766}
3767
3769 assert(
3770 none_of(ExpressionRecipes,
3771 [](VPSingleDefRecipe *R) { return R->mayHaveSideEffects(); }) &&
3772 "expression cannot contain recipes with side-effects");
3773 return false;
3774}
3775
3777 auto *RR = dyn_cast<VPReductionRecipe>(ExpressionRecipes.back());
3778 return RR && !RR->isPartialReduction();
3779}
3780
3781#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3782
3784 VPSlotTracker &SlotTracker) const {
3785 O << Indent << "EXPRESSION ";
3787 O << " = ";
3788 auto *Red = cast<VPReductionRecipe>(ExpressionRecipes.back());
3789 unsigned Opcode = RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind());
3790 VPValue *Mask = getOperand(getNumOperands() - 1);
3791 VPValue *EVL =
3793 ? getOperand(getNumOperands() - (Red->isConditional() ? 2 : 1))
3794 : nullptr;
3795 VPValue *RdxStart = getOperand(
3796 getNumOperands() - (Red->isConditional() ? 2 : 1) - (EVL ? 1 : 0));
3797 auto PrintEVLAndMask = [&]() {
3798 if (EVL) {
3799 O << ", ";
3800 EVL->printAsOperand(O, SlotTracker);
3801 }
3802 if (Red->isConditional()) {
3803 O << ", ";
3804 Mask->printAsOperand(O, SlotTracker);
3805 }
3806 };
3807
3808 switch (ExpressionType) {
3809 case ExpressionTypes::NegatedExtendedReduction:
3810 case ExpressionTypes::ExtendedReduction: {
3811 bool Negated = ExpressionType == ExpressionTypes::NegatedExtendedReduction;
3813 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
3814 O << Instruction::getOpcodeName(Opcode) << " (";
3815 if (Negated)
3816 O << (Opcode == Instruction::Add ? "sub (0, " : "fneg(");
3818 if (Negated)
3819 O << ")";
3820 Red->printFlags(O);
3821
3822 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3823 O << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
3824 << *Ext0->getScalarType();
3825 PrintEVLAndMask();
3826 O << ")";
3827 break;
3828 }
3829 case ExpressionTypes::ExtNegatedMulAccReduction: {
3830 RdxStart->printAsOperand(O, SlotTracker);
3831 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
3833 RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind()))
3834 << " (sub (0, mul";
3835 auto *Mul = cast<VPWidenRecipe>(ExpressionRecipes[2]);
3836 Mul->printFlags(O);
3837 O << "(";
3839 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3840 O << " " << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
3841 << *Ext0->getScalarType() << "), (";
3843 auto *Ext1 = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
3844 O << " " << Instruction::getOpcodeName(Ext1->getOpcode()) << " to "
3845 << *Ext1->getScalarType() << ")";
3846 PrintEVLAndMask();
3847 O << "))";
3848 break;
3849 }
3850 case ExpressionTypes::MulAccReduction:
3851 case ExpressionTypes::ExtMulAccReduction: {
3852 RdxStart->printAsOperand(O, SlotTracker);
3853 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
3855 RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind()))
3856 << " (";
3857 O << "mul";
3858 bool IsExtended = ExpressionType == ExpressionTypes::ExtMulAccReduction;
3859 auto *Mul = cast<VPWidenRecipe>(IsExtended ? ExpressionRecipes[2]
3860 : ExpressionRecipes[0]);
3861 Mul->printFlags(O);
3862 if (IsExtended)
3863 O << "(";
3865 if (IsExtended) {
3866 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3867 O << " " << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
3868 << *Ext0->getScalarType() << "), (";
3869 } else {
3870 O << ", ";
3871 }
3873 if (IsExtended) {
3874 auto *Ext1 = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
3875 O << " " << Instruction::getOpcodeName(Ext1->getOpcode()) << " to "
3876 << *Ext1->getScalarType() << ")";
3877 }
3878 PrintEVLAndMask();
3879 O << ")";
3880 break;
3881 }
3882 }
3883}
3884
3886 VPSlotTracker &SlotTracker) const {
3887 if (isPartialReduction())
3888 O << Indent << "PARTIAL-REDUCE ";
3889 else
3890 O << Indent << "REDUCE ";
3892 O << " = ";
3894 O << " +";
3895 printFlags(O);
3896 O << " reduce.";
3898 O << " (";
3900 if (isConditional()) {
3901 O << ", ";
3903 }
3904 O << ")";
3905}
3906
3908 VPSlotTracker &SlotTracker) const {
3909 if (isPartialReduction())
3910 O << Indent << "PARTIAL-REDUCE ";
3911 else
3912 O << Indent << "REDUCE ";
3914 O << " = ";
3916 O << " +";
3917 printFlags(O);
3918 O << " vp.reduce."
3921 << " (";
3923 O << ", ";
3925 if (isConditional()) {
3926 O << ", ";
3928 }
3929 O << ")";
3930}
3931
3932#endif
3933
3935 assert(IsSingleScalar &&
3936 "VPReplicateRecipes must be unrolled before ::execute");
3937 auto *Instr = getUnderlyingInstr();
3938 Instruction *Cloned = Instr->clone();
3939 Type *ResultTy = getScalarType();
3940 if (!ResultTy->isVoidTy()) {
3941 Cloned->setName(Instr->getName() + ".cloned");
3942 // The operands of the replicate recipe may have been narrowed, resulting in
3943 // a narrower result type. Update the type of the cloned instruction to the
3944 // correct type.
3945 if (ResultTy != Cloned->getType())
3946 Cloned->mutateType(ResultTy);
3947 }
3948
3949 applyFlags(*Cloned);
3950 applyMetadata(*Cloned);
3951
3952 if (hasPredicate())
3953 cast<CmpInst>(Cloned)->setPredicate(getPredicate());
3954
3955 // Replace the operands of the cloned instructions with their scalar
3956 // equivalents in the new loop.
3957 for (const auto &[Idx, V] : enumerate(operands()))
3958 Cloned->setOperand(Idx, State.get(V, true));
3959
3960 // Place the cloned scalar in the new loop.
3961 State.Builder.Insert(Cloned);
3962
3963 State.set(this, Cloned, true);
3964
3965 // If we just cloned a new assumption, add it the assumption cache.
3966 if (auto *II = dyn_cast<AssumeInst>(Cloned))
3967 State.AC->registerAssumption(II);
3968}
3969
3970/// Returns a SCEV expression for \p Ptr if it is a pointer computation for
3971/// which the legacy cost model computes a SCEV expression when computing the
3972/// address cost. Computing SCEVs for VPValues is incomplete and returns
3973/// SCEVCouldNotCompute in cases the legacy cost model can compute SCEVs. In
3974/// those cases we fall back to the legacy cost model. Otherwise return nullptr.
3975static const SCEV *getAddressAccessSCEV(const VPValue *Ptr,
3977 const Loop *L) {
3978 const SCEV *Addr = vputils::getSCEVExprForVPValue(Ptr, PSE, L);
3979 if (isa<SCEVCouldNotCompute>(Addr))
3980 return Addr;
3981
3982 return vputils::isAddressSCEVForCost(Addr, *PSE.getSE(), L) ? Addr : nullptr;
3983}
3984
3986 VPCostContext &Ctx) const {
3988 // VPReplicateRecipe may be cloned as part of an existing VPlan-to-VPlan
3989 // transform, avoid computing their cost multiple times for now.
3990 Ctx.SkipCostComputation.insert(UI);
3991
3992 if (VF.isScalable() && !isSingleScalar())
3994
3995 switch (UI->getOpcode()) {
3996 case Instruction::Alloca:
3997 if (VF.isScalable())
3999 return Ctx.TTI.getArithmeticInstrCost(Instruction::Mul,
4000 this->getScalarType(), Ctx.CostKind);
4001 case Instruction::GetElementPtr:
4002 // We mark this instruction as zero-cost because the cost of GEPs in
4003 // vectorized code depends on whether the corresponding memory instruction
4004 // is scalarized or not. Therefore, we handle GEPs with the memory
4005 // instruction cost.
4006 return 0;
4007 case Instruction::Call: {
4008 auto *CalledFn =
4010 Type *ResultTy = this->getScalarType();
4011 return computeCallCost(CalledFn, ResultTy, drop_end(operands()),
4012 isSingleScalar(), VF, Ctx);
4013 }
4014 case Instruction::Add:
4015 case Instruction::Sub:
4016 case Instruction::FAdd:
4017 case Instruction::FSub:
4018 case Instruction::Mul:
4019 case Instruction::FMul:
4020 case Instruction::FDiv:
4021 case Instruction::FRem:
4022 case Instruction::Shl:
4023 case Instruction::LShr:
4024 case Instruction::AShr:
4025 case Instruction::And:
4026 case Instruction::Or:
4027 case Instruction::Xor:
4028 case Instruction::ICmp:
4029 case Instruction::FCmp:
4031 Ctx) *
4032 (isSingleScalar() ? 1 : VF.getFixedValue());
4033 case Instruction::SDiv:
4034 case Instruction::UDiv:
4035 case Instruction::SRem:
4036 case Instruction::URem: {
4037 InstructionCost ScalarCost =
4039 if (isSingleScalar())
4040 return ScalarCost;
4041
4042 // If any of the operands is from a different replicate region and has its
4043 // cost skipped, it may have been forced to scalar. Fall back to legacy cost
4044 // model to avoid cost mis-match.
4045 if (any_of(operands(), [&Ctx, VF](VPValue *Op) {
4046 auto *PredR = dyn_cast<VPPredInstPHIRecipe>(Op);
4047 if (!PredR)
4048 return false;
4049 return Ctx.skipCostComputation(
4051 PredR->getOperand(0)->getUnderlyingValue()),
4052 VF.isVector());
4053 }))
4054 break;
4055
4056 ScalarCost = ScalarCost * VF.getFixedValue() +
4057 Ctx.getScalarizationOverhead(this->getScalarType(),
4058 to_vector(operands()), VF);
4059 // If the recipe is not predicated (i.e. not in a replicate region), return
4060 // the scalar cost. Otherwise handle predicated cost.
4061 if (!getRegion()->isReplicator())
4062 return ScalarCost;
4063
4064 // Account for the phi nodes that we will create.
4065 ScalarCost += VF.getFixedValue() *
4066 Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
4067 // Scale the cost by the probability of executing the predicated blocks.
4068 // This assumes the predicated block for each vector lane is equally
4069 // likely.
4070 ScalarCost /= Ctx.getReplicateRegionCostDivisor(getRegion());
4071 return ScalarCost;
4072 }
4073 case Instruction::Load:
4074 case Instruction::Store: {
4075 bool IsLoad = UI->getOpcode() == Instruction::Load;
4076 const VPValue *PtrOp = getOperand(!IsLoad);
4077 const SCEV *PtrSCEV = getAddressAccessSCEV(PtrOp, Ctx.PSE, Ctx.L);
4079 break;
4080
4081 Type *ValTy = (IsLoad ? this : getOperand(0))->getScalarType();
4082 Type *ScalarPtrTy = PtrOp->getScalarType();
4083 const Align Alignment = getLoadStoreAlignment(UI);
4084 unsigned AS = cast<PointerType>(ScalarPtrTy)->getAddressSpace();
4086 bool PreferVectorizedAddressing = Ctx.TTI.prefersVectorizedAddressing();
4087 bool UsedByLoadStoreAddress =
4088 !PreferVectorizedAddressing && vputils::isUsedByLoadStoreAddress(this);
4089 InstructionCost ScalarMemOpCost = Ctx.TTI.getMemoryOpCost(
4090 UI->getOpcode(), ValTy, Alignment, AS, Ctx.CostKind, OpInfo,
4091 UsedByLoadStoreAddress ? UI : nullptr);
4092
4093 Type *PtrTy = isSingleScalar() ? ScalarPtrTy : toVectorTy(ScalarPtrTy, VF);
4094 InstructionCost ScalarCost =
4095 ScalarMemOpCost +
4096 Ctx.TTI.getAddressComputationCost(
4097 PtrTy, UsedByLoadStoreAddress ? nullptr : Ctx.PSE.getSE(), PtrSCEV,
4098 Ctx.CostKind);
4099 if (isSingleScalar())
4100 return ScalarCost;
4101
4102 SmallVector<const VPValue *> OpsToScalarize;
4103 Type *ResultTy = Type::getVoidTy(PtrTy->getContext());
4104 // Set ResultTy and OpsToScalarize, if scalarization is needed. Currently we
4105 // don't assign scalarization overhead in general, if the target prefers
4106 // vectorized addressing or the loaded value is used as part of an address
4107 // of another load or store.
4108 if (!UsedByLoadStoreAddress) {
4109 bool EfficientVectorLoadStore =
4110 Ctx.TTI.supportsEfficientVectorElementLoadStore();
4111 if (!(IsLoad && !PreferVectorizedAddressing) &&
4112 !(!IsLoad && EfficientVectorLoadStore))
4113 append_range(OpsToScalarize, operands());
4114
4115 if (!EfficientVectorLoadStore)
4116 ResultTy = this->getScalarType();
4117 }
4118
4120 IsLoad ? TTI::VectorInstrContext::Load : TTI::VectorInstrContext::Store;
4122 (ScalarCost * VF.getFixedValue()) +
4123 Ctx.getScalarizationOverhead(ResultTy, OpsToScalarize, VF, VIC, true);
4124
4125 const VPRegionBlock *ParentRegion = getRegion();
4126 if (ParentRegion && ParentRegion->isReplicator()) {
4127 if (!PtrSCEV)
4128 break;
4129 Cost /= Ctx.getReplicateRegionCostDivisor(ParentRegion);
4130 Cost += Ctx.TTI.getCFInstrCost(Instruction::CondBr, Ctx.CostKind);
4131
4132 auto *VecI1Ty = VectorType::get(
4133 IntegerType::getInt1Ty(Ctx.L->getHeader()->getContext()), VF);
4134 Cost += Ctx.TTI.getScalarizationOverhead(
4135 VecI1Ty, APInt::getAllOnes(VF.getFixedValue()),
4136 /*Insert=*/false, /*Extract=*/true, Ctx.CostKind);
4137
4138 if (Ctx.useEmulatedMaskMemRefHack(this, VF)) {
4139 // Artificially setting to a high enough value to practically disable
4140 // vectorization with such operations.
4141 return 3000000;
4142 }
4143 }
4144 return Cost;
4145 }
4146 case Instruction::SExt:
4147 case Instruction::ZExt:
4148 case Instruction::FPToUI:
4149 case Instruction::FPToSI:
4150 case Instruction::FPExt:
4151 case Instruction::PtrToInt:
4152 case Instruction::PtrToAddr:
4153 case Instruction::IntToPtr:
4154 case Instruction::SIToFP:
4155 case Instruction::UIToFP:
4156 case Instruction::Trunc:
4157 case Instruction::FPTrunc:
4158 case Instruction::Select:
4159 case Instruction::AddrSpaceCast: {
4161 Ctx) *
4162 (isSingleScalar() ? 1 : VF.getFixedValue());
4163 }
4164 case Instruction::ExtractValue:
4165 case Instruction::InsertValue:
4166 return Ctx.TTI.getInsertExtractValueCost(getOpcode(), Ctx.CostKind);
4167 }
4168
4169 return Ctx.getLegacyCost(UI, VF);
4170}
4171
4173 Function *CalledFn, Type *ResultTy, ArrayRef<const VPValue *> ArgOps,
4174 bool IsSingleScalar, ElementCount VF, VPCostContext &Ctx) {
4176 ArgOps, [&](const VPValue *Op) { return Op->getScalarType(); });
4177
4178 Intrinsic::ID IntrinID = CalledFn->getIntrinsicID();
4179 auto GetIntrinsicCost = [&] {
4180 if (!IntrinID)
4182 return Ctx.TTI.getIntrinsicInstrCost(
4183 IntrinsicCostAttributes(IntrinID, ResultTy, Tys), Ctx.CostKind);
4184 };
4185
4186 if (IntrinID && VPCostContext::isFreeScalarIntrinsic(IntrinID)) {
4187 assert(GetIntrinsicCost() == 0 && "scalarizing intrinsic should be free");
4188 return 0;
4189 }
4190
4191 InstructionCost ScalarCallCost =
4192 Ctx.TTI.getCallInstrCost(CalledFn, ResultTy, Tys, Ctx.CostKind);
4193 if (IsSingleScalar) {
4194 ScalarCallCost = std::min(ScalarCallCost, GetIntrinsicCost());
4195 return ScalarCallCost;
4196 }
4197
4198 // Scalarization overhead is undefined for scalable VFs.
4199 if (VF.isScalable())
4201
4202 return ScalarCallCost * VF.getFixedValue() +
4203 Ctx.getScalarizationOverhead(ResultTy, ArgOps, VF);
4204}
4205
4206#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4208 VPSlotTracker &SlotTracker) const {
4209 O << Indent << (IsSingleScalar ? "CLONE " : "REPLICATE ");
4210
4211 if (!getScalarType()->isVoidTy()) {
4213 O << " = ";
4214 }
4215 if (auto *CB = dyn_cast<CallBase>(getUnderlyingInstr())) {
4216 O << "call";
4217 printFlags(O);
4218 O << "@" << CB->getCalledFunction()->getName() << "(";
4220 Op->printAsOperand(O, SlotTracker);
4221 });
4222 O << ")";
4223 } else {
4225 printFlags(O);
4227 }
4228
4229 // Find if the recipe is used by a widened recipe via an intervening
4230 // VPPredInstPHIRecipe. In this case, also pack the scalar values in a vector.
4231 if (any_of(users(), [](const VPUser *U) {
4232 if (auto *PredR = dyn_cast<VPPredInstPHIRecipe>(U))
4233 return !vputils::onlyScalarValuesUsed(PredR);
4234 return false;
4235 }))
4236 O << " (S->V)";
4237}
4238#endif
4239
4241 llvm_unreachable("recipe must be removed when dissolving replicate region");
4242}
4243
4245 VPCostContext &Ctx) const {
4246 // The legacy cost model doesn't assign costs to branches for individual
4247 // replicate regions. Match the current behavior in the VPlan cost model for
4248 // now.
4249 return 0;
4250}
4251
4253 llvm_unreachable("recipe must be removed when dissolving replicate region");
4254}
4255
4256#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4258 VPSlotTracker &SlotTracker) const {
4259 O << Indent << "PHI-PREDICATED-INSTRUCTION ";
4261 O << " = ";
4263}
4264#endif
4265
4267const VPRecipeBase *VPWidenLoadRecipe::getAsRecipe() const { return this; }
4268
4271
4273const VPRecipeBase *VPWidenStoreRecipe::getAsRecipe() const { return this; }
4274
4277
4279 VPCostContext &Ctx) const {
4280 const VPRecipeBase *R = getAsRecipe();
4282 Type *ScalarTy = IsLoad ? cast<VPSingleDefRecipe>(R)->getScalarType()
4283 : R->getOperand(1)->getScalarType();
4284 Type *Ty = toVectorTy(ScalarTy, VF);
4285 unsigned AS =
4286 cast<PointerType>(getAddr()->getScalarType())->getAddressSpace();
4287 unsigned Opcode = IsLoad ? Instruction::Load : Instruction::Store;
4288
4289 if (!Consecutive) {
4290 // TODO: Using the original IR may not be accurate.
4291 // Currently, ARM will use the underlying IR to calculate gather/scatter
4292 // instruction cost.
4293 Type *PtrTy = getAddr()->getScalarType();
4294 const Value *Ptr = getAddr()->getUnderlyingValue();
4295
4296 // If the address value is uniform across all lanes, then the address can be
4297 // calculated with scalar type and broadcast.
4299 PtrTy = toVectorTy(PtrTy, VF);
4300
4301 unsigned IID = isa<VPWidenLoadRecipe>(R) ? Intrinsic::masked_gather
4302 : isa<VPWidenStoreRecipe>(R) ? Intrinsic::masked_scatter
4303 : isa<VPWidenLoadEVLRecipe>(R) ? Intrinsic::vp_gather
4304 : Intrinsic::vp_scatter;
4305 return Ctx.TTI.getAddressComputationCost(PtrTy, nullptr, nullptr,
4306 Ctx.CostKind) +
4307 Ctx.TTI.getMemIntrinsicInstrCost(
4309 &Ingredient),
4310 Ctx.CostKind);
4311 }
4312
4314 if (IsMasked) {
4315 unsigned IID = isa<VPWidenLoadRecipe>(R) ? Intrinsic::masked_load
4316 : Intrinsic::masked_store;
4317 Cost += Ctx.TTI.getMemIntrinsicInstrCost(
4318 MemIntrinsicCostAttributes(IID, Ty, Alignment, AS), Ctx.CostKind);
4319 } else {
4320 TTI::OperandValueInfo OpInfo = Ctx.getOperandInfo(
4322 : R->getOperand(1));
4323 Cost += Ctx.TTI.getMemoryOpCost(Opcode, Ty, Alignment, AS, Ctx.CostKind,
4324 OpInfo, &Ingredient);
4325 }
4326 return Cost;
4327}
4328
4330 Type *ScalarDataTy = getScalarType();
4331 auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
4332 bool CreateGather = !isConsecutive();
4333
4334 auto &Builder = State.Builder;
4335 Value *Mask = nullptr;
4336 if (auto *VPMask = getMask())
4337 Mask = State.get(VPMask);
4338
4339 Value *Addr = State.get(getAddr(), /*IsScalar*/ !CreateGather);
4340 Value *NewLI;
4341 if (CreateGather) {
4342 NewLI = Builder.CreateMaskedGather(DataTy, Addr, Alignment, Mask, nullptr,
4343 "wide.masked.gather");
4344 } else if (Mask) {
4345 NewLI =
4346 Builder.CreateMaskedLoad(DataTy, Addr, Alignment, Mask,
4347 PoisonValue::get(DataTy), "wide.masked.load");
4348 } else {
4349 NewLI = Builder.CreateAlignedLoad(DataTy, Addr, Alignment, "wide.load");
4350 }
4352 State.set(this, NewLI);
4353}
4354
4355#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4357 VPSlotTracker &SlotTracker) const {
4358 O << Indent << "WIDEN ";
4360 O << " = load ";
4362}
4363#endif
4364
4366 Type *ScalarDataTy = getScalarType();
4367 auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
4368 bool CreateGather = !isConsecutive();
4369
4370 auto &Builder = State.Builder;
4371 CallInst *NewLI;
4372 Value *EVL = State.get(getEVL(), VPLane(0));
4373 Value *Addr = State.get(getAddr(), !CreateGather);
4374 Value *Mask = nullptr;
4375 if (VPValue *VPMask = getMask())
4376 Mask = State.get(VPMask);
4377 else
4378 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
4379
4380 if (CreateGather) {
4381 NewLI = Builder.CreateIntrinsicWithoutFolding(DataTy, Intrinsic::vp_gather,
4382 {Addr, Mask, EVL}, nullptr,
4383 "wide.masked.gather");
4384 } else {
4385 NewLI = Builder.CreateIntrinsicWithoutFolding(
4386 DataTy, Intrinsic::vp_load, {Addr, Mask, EVL}, nullptr, "vp.op.load");
4387 }
4388 NewLI->addParamAttr(
4390 applyMetadata(*NewLI);
4391 State.set(this, NewLI);
4392}
4393
4395 VPCostContext &Ctx) const {
4396 if (!Consecutive || IsMasked)
4397 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
4398
4399 // We need to use the getMemIntrinsicInstrCost() instead of getMemoryOpCost()
4400 // here because the EVL recipes using EVL to replace the tail mask. But in the
4401 // legacy model, it will always calculate the cost of mask.
4402 // TODO: Using getMemoryOpCost() instead of getMemIntrinsicInstrCost when we
4403 // don't need to compare to the legacy cost model.
4404 Type *Ty = toVectorTy(getScalarType(), VF);
4405 unsigned AS =
4406 cast<PointerType>(getAddr()->getScalarType())->getAddressSpace();
4407 return Ctx.TTI.getMemIntrinsicInstrCost(
4408 MemIntrinsicCostAttributes(Intrinsic::vp_load, Ty, Alignment, AS),
4409 Ctx.CostKind);
4410}
4411
4412#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4414 VPSlotTracker &SlotTracker) const {
4415 O << Indent << "WIDEN ";
4417 O << " = vp.load ";
4419}
4420#endif
4421
4423 VPValue *StoredVPValue = getStoredValue();
4424 bool CreateScatter = !isConsecutive();
4425
4426 auto &Builder = State.Builder;
4427
4428 Value *Mask = nullptr;
4429 if (auto *VPMask = getMask())
4430 Mask = State.get(VPMask);
4431
4432 Value *StoredVal = State.get(StoredVPValue);
4433 Value *Addr = State.get(getAddr(), /*IsScalar*/ !CreateScatter);
4434 Instruction *NewSI = nullptr;
4435 if (CreateScatter)
4436 NewSI = Builder.CreateMaskedScatter(StoredVal, Addr, Alignment, Mask);
4437 else if (Mask)
4438 NewSI = Builder.CreateMaskedStore(StoredVal, Addr, Alignment, Mask);
4439 else
4440 NewSI = Builder.CreateAlignedStore(StoredVal, Addr, Alignment);
4441 applyMetadata(*NewSI);
4442}
4443
4444#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4446 VPSlotTracker &SlotTracker) const {
4447 O << Indent << "WIDEN store ";
4449}
4450#endif
4451
4453 VPValue *StoredValue = getStoredValue();
4454 bool CreateScatter = !isConsecutive();
4455
4456 auto &Builder = State.Builder;
4457
4458 CallInst *NewSI = nullptr;
4459 Value *StoredVal = State.get(StoredValue);
4460 Value *EVL = State.get(getEVL(), VPLane(0));
4461 Value *Mask = nullptr;
4462 if (VPValue *VPMask = getMask())
4463 Mask = State.get(VPMask);
4464 else
4465 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
4466
4467 Value *Addr = State.get(getAddr(), !CreateScatter);
4468 if (CreateScatter) {
4469 NewSI = Builder.CreateIntrinsicWithoutFolding(
4470 Type::getVoidTy(EVL->getContext()), Intrinsic::vp_scatter,
4471 {StoredVal, Addr, Mask, EVL});
4472 } else {
4473 NewSI = Builder.CreateIntrinsicWithoutFolding(
4474 Type::getVoidTy(EVL->getContext()), Intrinsic::vp_store,
4475 {StoredVal, Addr, Mask, EVL});
4476 }
4477 NewSI->addParamAttr(
4479 applyMetadata(*NewSI);
4480}
4481
4483 VPCostContext &Ctx) const {
4484 if (!Consecutive || IsMasked)
4485 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
4486
4487 // We need to use the getMemIntrinsicInstrCost() instead of getMemoryOpCost()
4488 // here because the EVL recipes using EVL to replace the tail mask. But in the
4489 // legacy model, it will always calculate the cost of mask.
4490 // TODO: Using getMemoryOpCost() instead of getMemIntrinsicInstrCost when we
4491 // don't need to compare to the legacy cost model.
4492 Type *Ty = toVectorTy(getStoredValue()->getScalarType(), VF);
4493 unsigned AS =
4494 cast<PointerType>(getAddr()->getScalarType())->getAddressSpace();
4495 return Ctx.TTI.getMemIntrinsicInstrCost(
4496 MemIntrinsicCostAttributes(Intrinsic::vp_store, Ty, Alignment, AS),
4497 Ctx.CostKind);
4498}
4499
4500#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4502 VPSlotTracker &SlotTracker) const {
4503 O << Indent << "WIDEN vp.store ";
4505}
4506#endif
4507
4509 VectorType *DstVTy, const DataLayout &DL) {
4510 // Verify that V is a vector type with same number of elements as DstVTy.
4511 auto VF = DstVTy->getElementCount();
4512 auto *SrcVecTy = cast<VectorType>(V->getType());
4513 assert(VF == SrcVecTy->getElementCount() && "Vector dimensions do not match");
4514 Type *SrcElemTy = SrcVecTy->getElementType();
4515 Type *DstElemTy = DstVTy->getElementType();
4516 assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&
4517 "Vector elements must have same size");
4518
4519 // Do a direct cast if element types are castable.
4520 if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
4521 return Builder.CreateBitOrPointerCast(V, DstVTy);
4522 }
4523 // V cannot be directly casted to desired vector type.
4524 // May happen when V is a floating point vector but DstVTy is a vector of
4525 // pointers or vice-versa. Handle this using a two-step bitcast using an
4526 // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
4527 assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&
4528 "Only one type should be a pointer type");
4529 assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&
4530 "Only one type should be a floating point type");
4531 Type *IntTy =
4532 IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy));
4533 auto *VecIntTy = VectorType::get(IntTy, VF);
4534 Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
4535 return Builder.CreateBitOrPointerCast(CastVal, DstVTy);
4536}
4537
4538/// Return a vector containing interleaved elements from multiple
4539/// smaller input vectors.
4541 const Twine &Name) {
4542 unsigned Factor = Vals.size();
4543 assert(Factor > 1 && "Tried to interleave invalid number of vectors");
4544
4545 VectorType *VecTy = cast<VectorType>(Vals[0]->getType());
4546#ifndef NDEBUG
4547 for (Value *Val : Vals)
4548 assert(Val->getType() == VecTy && "Tried to interleave mismatched types");
4549#endif
4550
4551 // Scalable vectors cannot use arbitrary shufflevectors (only splats), so
4552 // must use intrinsics to interleave.
4553 if (VecTy->isScalableTy()) {
4554 assert(Factor <= 8 && "Unsupported interleave factor for scalable vectors");
4555 return Builder.CreateVectorInterleave(Vals, Name);
4556 }
4557
4558 // Fixed length. Start by concatenating all vectors into a wide vector.
4559 Value *WideVec = concatenateVectors(Builder, Vals);
4560
4561 // Interleave the elements into the wide vector.
4562 const unsigned NumElts = VecTy->getElementCount().getFixedValue();
4563 return Builder.CreateShuffleVector(
4564 WideVec, createInterleaveMask(NumElts, Factor), Name);
4565}
4566
4567// Try to vectorize the interleave group that \p Instr belongs to.
4568//
4569// E.g. Translate following interleaved load group (factor = 3):
4570// for (i = 0; i < N; i+=3) {
4571// R = Pic[i]; // Member of index 0
4572// G = Pic[i+1]; // Member of index 1
4573// B = Pic[i+2]; // Member of index 2
4574// ... // do something to R, G, B
4575// }
4576// To:
4577// %wide.vec = load <12 x i32> ; Read 4 tuples of R,G,B
4578// %R.vec = shuffle %wide.vec, poison, <0, 3, 6, 9> ; R elements
4579// %G.vec = shuffle %wide.vec, poison, <1, 4, 7, 10> ; G elements
4580// %B.vec = shuffle %wide.vec, poison, <2, 5, 8, 11> ; B elements
4581//
4582// Or translate following interleaved store group (factor = 3):
4583// for (i = 0; i < N; i+=3) {
4584// ... do something to R, G, B
4585// Pic[i] = R; // Member of index 0
4586// Pic[i+1] = G; // Member of index 1
4587// Pic[i+2] = B; // Member of index 2
4588// }
4589// To:
4590// %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
4591// %B_U.vec = shuffle %B.vec, poison, <0, 1, 2, 3, u, u, u, u>
4592// %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
4593// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> ; Interleave R,G,B elements
4594// store <12 x i32> %interleaved.vec ; Write 4 tuples of R,G,B
4596 assert((!needsMaskForGaps() || !State.VF.isScalable()) &&
4597 "Masking gaps for scalable vectors is not yet supported.");
4599 Instruction *Instr = Group->getInsertPos();
4600
4601 // Prepare for the vector type of the interleaved load/store.
4602 Type *ScalarTy = getLoadStoreType(Instr);
4603 unsigned InterleaveFactor = Group->getFactor();
4604 auto *VecTy = VectorType::get(ScalarTy, State.VF * InterleaveFactor);
4605
4606 VPValue *BlockInMask = getMask();
4607 VPValue *Addr = getAddr();
4608 Value *ResAddr = State.get(Addr, VPLane(0));
4609
4610 auto CreateGroupMask = [&BlockInMask, &State,
4611 &InterleaveFactor](Value *MaskForGaps) -> Value * {
4612 if (State.VF.isScalable()) {
4613 assert(!MaskForGaps && "Interleaved groups with gaps are not supported.");
4614 assert(InterleaveFactor <= 8 &&
4615 "Unsupported deinterleave factor for scalable vectors");
4616 auto *ResBlockInMask = State.get(BlockInMask);
4617 SmallVector<Value *> Ops(InterleaveFactor, ResBlockInMask);
4618 return interleaveVectors(State.Builder, Ops, "interleaved.mask");
4619 }
4620
4621 if (!BlockInMask)
4622 return MaskForGaps;
4623
4624 Value *ResBlockInMask = State.get(BlockInMask);
4625 Value *ShuffledMask = State.Builder.CreateShuffleVector(
4626 ResBlockInMask,
4627 createReplicatedMask(InterleaveFactor, State.VF.getFixedValue()),
4628 "interleaved.mask");
4629 return MaskForGaps ? State.Builder.CreateBinOp(Instruction::And,
4630 ShuffledMask, MaskForGaps)
4631 : ShuffledMask;
4632 };
4633
4634 const DataLayout &DL = Instr->getDataLayout();
4635 // Vectorize the interleaved load group.
4636 if (isa<LoadInst>(Instr)) {
4637 Value *MaskForGaps = nullptr;
4638 if (needsMaskForGaps()) {
4639 MaskForGaps =
4640 createBitMaskForGaps(State.Builder, State.VF.getFixedValue(), *Group);
4641 assert(MaskForGaps && "Mask for Gaps is required but it is null");
4642 }
4643
4644 Instruction *NewLoad;
4645 if (BlockInMask || MaskForGaps) {
4646 Value *GroupMask = CreateGroupMask(MaskForGaps);
4647 Value *PoisonVec = PoisonValue::get(VecTy);
4648 NewLoad = State.Builder.CreateMaskedLoad(VecTy, ResAddr,
4649 Group->getAlign(), GroupMask,
4650 PoisonVec, "wide.masked.vec");
4651 } else
4652 NewLoad = State.Builder.CreateAlignedLoad(VecTy, ResAddr,
4653 Group->getAlign(), "wide.vec");
4654 applyMetadata(*NewLoad);
4655 // TODO: Also manage existing metadata using VPIRMetadata.
4656 Group->addMetadata(NewLoad);
4657
4659 if (VecTy->isScalableTy()) {
4660 // Scalable vectors cannot use arbitrary shufflevectors (only splats),
4661 // so must use intrinsics to deinterleave.
4662 assert(InterleaveFactor <= 8 &&
4663 "Unsupported deinterleave factor for scalable vectors");
4664 NewLoad = State.Builder.CreateIntrinsicWithoutFolding(
4665 Intrinsic::getDeinterleaveIntrinsicID(InterleaveFactor),
4666 NewLoad->getType(), NewLoad,
4667 /*FMFSource=*/nullptr, "strided.vec");
4668 }
4669
4670 auto CreateStridedVector = [&InterleaveFactor, &State,
4671 &NewLoad](unsigned Index) -> Value * {
4672 assert(Index < InterleaveFactor && "Illegal group index");
4673 if (State.VF.isScalable())
4674 return State.Builder.CreateExtractValue(NewLoad, Index);
4675
4676 // For fixed length VF, use shuffle to extract the sub-vectors from the
4677 // wide load.
4678 auto StrideMask =
4679 createStrideMask(Index, InterleaveFactor, State.VF.getFixedValue());
4680 return State.Builder.CreateShuffleVector(NewLoad, StrideMask,
4681 "strided.vec");
4682 };
4683
4684 for (unsigned I = 0, J = 0; I < InterleaveFactor; ++I) {
4685 Instruction *Member = Group->getMember(I);
4686
4687 // Skip the gaps in the group.
4688 if (!Member)
4689 continue;
4690
4691 Value *StridedVec = CreateStridedVector(I);
4692
4693 // If this member has different type, cast the result type.
4694 if (Member->getType() != ScalarTy) {
4695 VectorType *OtherVTy = VectorType::get(Member->getType(), State.VF);
4696 StridedVec =
4697 createBitOrPointerCast(State.Builder, StridedVec, OtherVTy, DL);
4698 }
4699
4700 if (Group->isReverse())
4701 StridedVec = State.Builder.CreateVectorReverse(StridedVec, "reverse");
4702
4703 State.set(VPDefs[J], StridedVec);
4704 ++J;
4705 }
4706 return;
4707 }
4708
4709 // The sub vector type for current instruction.
4710 auto *SubVT = VectorType::get(ScalarTy, State.VF);
4711
4712 // Vectorize the interleaved store group.
4713 Value *MaskForGaps =
4714 createBitMaskForGaps(State.Builder, State.VF.getKnownMinValue(), *Group);
4715 assert(((MaskForGaps != nullptr) == needsMaskForGaps()) &&
4716 "Mismatch between NeedsMaskForGaps and MaskForGaps");
4717 ArrayRef<VPValue *> StoredValues = getStoredValues();
4718 // Collect the stored vector from each member.
4719 SmallVector<Value *, 4> StoredVecs;
4720 unsigned StoredIdx = 0;
4721 for (unsigned i = 0; i < InterleaveFactor; i++) {
4722 assert((Group->getMember(i) || MaskForGaps) &&
4723 "Fail to get a member from an interleaved store group");
4724 Instruction *Member = Group->getMember(i);
4725
4726 // Skip the gaps in the group.
4727 if (!Member) {
4728 Value *Undef = PoisonValue::get(SubVT);
4729 StoredVecs.push_back(Undef);
4730 continue;
4731 }
4732
4733 Value *StoredVec = State.get(StoredValues[StoredIdx]);
4734 ++StoredIdx;
4735
4736 if (Group->isReverse())
4737 StoredVec = State.Builder.CreateVectorReverse(StoredVec, "reverse");
4738
4739 // If this member has different type, cast it to a unified type.
4740
4741 if (StoredVec->getType() != SubVT)
4742 StoredVec = createBitOrPointerCast(State.Builder, StoredVec, SubVT, DL);
4743
4744 StoredVecs.push_back(StoredVec);
4745 }
4746
4747 // Interleave all the smaller vectors into one wider vector.
4748 Value *IVec = interleaveVectors(State.Builder, StoredVecs, "interleaved.vec");
4749 Instruction *NewStoreInstr;
4750 if (BlockInMask || MaskForGaps) {
4751 Value *GroupMask = CreateGroupMask(MaskForGaps);
4752 NewStoreInstr = State.Builder.CreateMaskedStore(
4753 IVec, ResAddr, Group->getAlign(), GroupMask);
4754 } else
4755 NewStoreInstr =
4756 State.Builder.CreateAlignedStore(IVec, ResAddr, Group->getAlign());
4757
4758 applyMetadata(*NewStoreInstr);
4759 // TODO: Also manage existing metadata using VPIRMetadata.
4760 Group->addMetadata(NewStoreInstr);
4761}
4762
4763#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4765 VPSlotTracker &SlotTracker) const {
4767 O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << ", ";
4769 VPValue *Mask = getMask();
4770 if (Mask) {
4771 O << ", ";
4772 Mask->printAsOperand(O, SlotTracker);
4773 }
4774
4775 unsigned OpIdx = 0;
4776 for (unsigned i = 0; i < IG->getFactor(); ++i) {
4777 if (!IG->getMember(i))
4778 continue;
4779 if (getNumStoreOperands() > 0) {
4780 O << "\n" << Indent << " store ";
4781 getOperand(1 + OpIdx)->printAsOperand(O, SlotTracker);
4782 O << " to index " << i;
4783 } else {
4784 O << "\n" << Indent << " ";
4786 O << " = load from index " << i;
4787 }
4788 ++OpIdx;
4789 }
4790}
4791#endif
4792
4794 assert(State.VF.isScalable() &&
4795 "Only support scalable VF for EVL tail-folding.");
4797 "Masking gaps for scalable vectors is not yet supported.");
4799 Instruction *Instr = Group->getInsertPos();
4800
4801 // Prepare for the vector type of the interleaved load/store.
4802 Type *ScalarTy = getLoadStoreType(Instr);
4803 unsigned InterleaveFactor = Group->getFactor();
4804 assert(InterleaveFactor <= 8 &&
4805 "Unsupported deinterleave/interleave factor for scalable vectors");
4806 ElementCount WideVF = State.VF * InterleaveFactor;
4807 auto *VecTy = VectorType::get(ScalarTy, WideVF);
4808
4809 VPValue *Addr = getAddr();
4810 Value *ResAddr = State.get(Addr, VPLane(0));
4811 Value *EVL = State.get(getEVL(), VPLane(0));
4812 Value *InterleaveEVL = State.Builder.CreateMul(
4813 EVL, ConstantInt::get(EVL->getType(), InterleaveFactor), "interleave.evl",
4814 /* NUW= */ true, /* NSW= */ true);
4815 LLVMContext &Ctx = State.Builder.getContext();
4816
4817 Value *GroupMask = nullptr;
4818 if (VPValue *BlockInMask = getMask()) {
4819 SmallVector<Value *> Ops(InterleaveFactor, State.get(BlockInMask));
4820 GroupMask = interleaveVectors(State.Builder, Ops, "interleaved.mask");
4821 } else {
4822 GroupMask =
4823 State.Builder.CreateVectorSplat(WideVF, State.Builder.getTrue());
4824 }
4825
4826 // Vectorize the interleaved load group.
4827 if (isa<LoadInst>(Instr)) {
4828 CallInst *NewLoad = State.Builder.CreateIntrinsicWithoutFolding(
4829 VecTy, Intrinsic::vp_load, {ResAddr, GroupMask, InterleaveEVL}, nullptr,
4830 "wide.vp.load");
4831 NewLoad->addParamAttr(0,
4832 Attribute::getWithAlignment(Ctx, Group->getAlign()));
4833
4834 applyMetadata(*NewLoad);
4835 // TODO: Also manage existing metadata using VPIRMetadata.
4836 Group->addMetadata(NewLoad);
4837
4838 // Scalable vectors cannot use arbitrary shufflevectors (only splats),
4839 // so must use intrinsics to deinterleave.
4840 NewLoad = State.Builder.CreateIntrinsicWithoutFolding(
4841 Intrinsic::getDeinterleaveIntrinsicID(InterleaveFactor),
4842 NewLoad->getType(), NewLoad,
4843 /*FMFSource=*/nullptr, "strided.vec");
4844
4845 const DataLayout &DL = Instr->getDataLayout();
4846 for (unsigned I = 0, J = 0; I < InterleaveFactor; ++I) {
4847 Instruction *Member = Group->getMember(I);
4848 // Skip the gaps in the group.
4849 if (!Member)
4850 continue;
4851
4852 Value *StridedVec = State.Builder.CreateExtractValue(NewLoad, I);
4853 // If this member has different type, cast the result type.
4854 if (Member->getType() != ScalarTy) {
4855 VectorType *OtherVTy = VectorType::get(Member->getType(), State.VF);
4856 StridedVec =
4857 createBitOrPointerCast(State.Builder, StridedVec, OtherVTy, DL);
4858 }
4859
4860 State.set(getVPValue(J), StridedVec);
4861 ++J;
4862 }
4863 return;
4864 } // End for interleaved load.
4865
4866 // The sub vector type for current instruction.
4867 auto *SubVT = VectorType::get(ScalarTy, State.VF);
4868 // Vectorize the interleaved store group.
4869 ArrayRef<VPValue *> StoredValues = getStoredValues();
4870 // Collect the stored vector from each member.
4871 SmallVector<Value *, 4> StoredVecs;
4872 const DataLayout &DL = Instr->getDataLayout();
4873 for (unsigned I = 0, StoredIdx = 0; I < InterleaveFactor; I++) {
4874 Instruction *Member = Group->getMember(I);
4875 // Skip the gaps in the group.
4876 if (!Member) {
4877 StoredVecs.push_back(PoisonValue::get(SubVT));
4878 continue;
4879 }
4880
4881 Value *StoredVec = State.get(StoredValues[StoredIdx]);
4882 // If this member has different type, cast it to a unified type.
4883 if (StoredVec->getType() != SubVT)
4884 StoredVec = createBitOrPointerCast(State.Builder, StoredVec, SubVT, DL);
4885
4886 StoredVecs.push_back(StoredVec);
4887 ++StoredIdx;
4888 }
4889
4890 // Interleave all the smaller vectors into one wider vector.
4891 Value *IVec = interleaveVectors(State.Builder, StoredVecs, "interleaved.vec");
4892 CallInst *NewStore = State.Builder.CreateIntrinsicWithoutFolding(
4893 Type::getVoidTy(Ctx), Intrinsic::vp_store,
4894 {IVec, ResAddr, GroupMask, InterleaveEVL});
4895
4896 NewStore->addParamAttr(1,
4897 Attribute::getWithAlignment(Ctx, Group->getAlign()));
4898
4899 applyMetadata(*NewStore);
4900 // TODO: Also manage existing metadata using VPIRMetadata.
4901 Group->addMetadata(NewStore);
4902}
4903
4904#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4906 VPSlotTracker &SlotTracker) const {
4908 O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << ", ";
4910 O << ", ";
4912 if (VPValue *Mask = getMask()) {
4913 O << ", ";
4914 Mask->printAsOperand(O, SlotTracker);
4915 }
4916
4917 unsigned OpIdx = 0;
4918 for (unsigned i = 0; i < IG->getFactor(); ++i) {
4919 if (!IG->getMember(i))
4920 continue;
4921 if (getNumStoreOperands() > 0) {
4922 O << "\n" << Indent << " vp.store ";
4923 getOperand(2 + OpIdx)->printAsOperand(O, SlotTracker);
4924 O << " to index " << i;
4925 } else {
4926 O << "\n" << Indent << " ";
4928 O << " = vp.load from index " << i;
4929 }
4930 ++OpIdx;
4931 }
4932}
4933#endif
4934
4936 VPCostContext &Ctx) const {
4937 Instruction *InsertPos = getInsertPos();
4938 // Find the VPValue index of the interleave group. We need to skip gaps.
4939 unsigned InsertPosIdx = 0;
4940 for (unsigned Idx = 0; IG->getFactor(); ++Idx)
4941 if (auto *Member = IG->getMember(Idx)) {
4942 if (Member == InsertPos)
4943 break;
4944 InsertPosIdx++;
4945 }
4946 const VPValue *ValV = getNumDefinedValues() > 0
4947 ? getVPValue(InsertPosIdx)
4948 : getStoredValues()[InsertPosIdx];
4949 Type *ValTy = ValV->getScalarType();
4950 auto *VectorTy = cast<VectorType>(toVectorTy(ValTy, VF));
4951 unsigned AS =
4952 cast<PointerType>(getAddr()->getScalarType())->getAddressSpace();
4953
4954 unsigned InterleaveFactor = IG->getFactor();
4955 auto *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
4956
4957 // Holds the indices of existing members in the interleaved group.
4959 for (unsigned IF = 0; IF < InterleaveFactor; IF++)
4960 if (IG->getMember(IF))
4961 Indices.push_back(IF);
4962
4963 // Calculate the cost of the whole interleaved group.
4964 InstructionCost Cost = Ctx.TTI.getInterleavedMemoryOpCost(
4965 InsertPos->getOpcode(), WideVecTy, IG->getFactor(), Indices,
4966 IG->getAlign(), AS, Ctx.CostKind, getMask(), NeedsMaskForGaps);
4967
4968 if (!IG->isReverse())
4969 return Cost;
4970
4971 return Cost + IG->getNumMembers() *
4972 Ctx.TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
4973 VectorTy, VectorTy, Ctx.CostKind, {},
4974 0);
4975}
4976
4979 VPCostContext &Ctx) const {
4980 // The recipe creates a scalar phi, a GEP to increment the induction and
4981 // vector add to compute the vector of pointers.
4982 // TODO: Charge costs for induction increment and vector add as well.
4983 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
4984}
4985
4987 return vputils::onlyScalarValuesUsed(this) &&
4988 (!IsScalable || vputils::onlyFirstLaneUsed(this));
4989}
4990
4991#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4993 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
4994 assert((getNumOperands() == 3 || getNumOperands() == 5) &&
4995 "unexpected number of operands");
4996 O << Indent << "EMIT ";
4998 O << " = WIDEN-POINTER-INDUCTION ";
5000 O << ", ";
5002 O << ", ";
5004 if (getNumOperands() == 5) {
5005 O << ", ";
5007 O << ", ";
5009 }
5010}
5011
5013 VPSlotTracker &SlotTracker) const {
5014 O << Indent << "EMIT ";
5016 O << " = EXPAND SCEV " << *Expr;
5017}
5018#endif
5019
5020#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5022 VPSlotTracker &SlotTracker) const {
5023 O << Indent << "EMIT ";
5025 O << " = WIDEN-CANONICAL-INDUCTION";
5026 printFlags(O);
5028}
5029#endif
5030
5032 auto &Builder = State.Builder;
5033 // Create a vector from the initial value.
5034 auto *VectorInit = getStartValue()->getLiveInIRValue();
5035
5036 Type *VecTy = State.VF.isScalar()
5037 ? VectorInit->getType()
5038 : VectorType::get(VectorInit->getType(), State.VF);
5039
5040 BasicBlock *VectorPH =
5041 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
5042 if (State.VF.isVector()) {
5043 auto *IdxTy = Builder.getInt32Ty();
5044 auto *One = ConstantInt::get(IdxTy, 1);
5045 IRBuilder<>::InsertPointGuard Guard(Builder);
5046 Builder.SetInsertPoint(VectorPH->getTerminator());
5047 auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, State.VF);
5048 auto *LastIdx = Builder.CreateSub(RuntimeVF, One);
5049 VectorInit = Builder.CreateInsertElement(
5050 PoisonValue::get(VecTy), VectorInit, LastIdx, "vector.recur.init");
5051 }
5052
5053 // Create a phi node for the new recurrence.
5054 PHINode *Phi = PHINode::Create(VecTy, 2, "vector.recur");
5055 Phi->insertBefore(State.CFG.PrevBB->getFirstInsertionPt());
5056 Phi->addIncoming(VectorInit, VectorPH);
5057 State.set(this, Phi);
5058}
5059
5062 VPCostContext &Ctx) const {
5063 if (VF.isScalar())
5064 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
5065
5066 return 0;
5067}
5068
5069#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5071 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
5072 O << Indent << "FIRST-ORDER-RECURRENCE-PHI ";
5074 O << " = phi ";
5076}
5077#endif
5078
5080 // Reductions do not have to start at zero. They can start with
5081 // any loop invariant values.
5082 VPValue *StartVPV = getStartValue();
5083
5084 // In order to support recurrences we need to be able to vectorize Phi nodes.
5085 // Phi nodes have cycles, so we need to vectorize them in two stages. This is
5086 // stage #1: We create a new vector PHI node with no incoming edges. We'll use
5087 // this value when we vectorize all of the instructions that use the PHI.
5088 BasicBlock *VectorPH =
5089 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
5090 bool ScalarPHI = State.VF.isScalar() || isInLoop();
5091 Value *StartV = State.get(StartVPV, ScalarPHI);
5092 Type *VecTy = StartV->getType();
5093
5094 BasicBlock *HeaderBB = State.CFG.PrevBB;
5095 assert(State.CurrentParentLoop->getHeader() == HeaderBB &&
5096 "recipe must be in the vector loop header");
5097 auto *Phi = PHINode::Create(VecTy, 2, "vec.phi");
5098 Phi->insertBefore(HeaderBB->getFirstInsertionPt());
5099 State.set(this, Phi, isInLoop());
5100
5101 Phi->addIncoming(StartV, VectorPH);
5102}
5103
5104#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5106 VPSlotTracker &SlotTracker) const {
5107 O << Indent << "WIDEN-REDUCTION-PHI ";
5108
5110 O << " = phi (";
5111 printRecurrenceKind(O, Kind);
5112 O << ")";
5113 printFlags(O);
5115 if (getVFScaleFactor() > 1)
5116 O << " (VF scaled by 1/" << getVFScaleFactor() << ")";
5117}
5118#endif
5119
5121 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
5122 return vputils::onlyFirstLaneUsed(this);
5123}
5124
5126 executePhiRecipe(this, *this, State, /*IsScalar=*/false, Name);
5127}
5128
5130 VPCostContext &Ctx) const {
5131 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
5132}
5133
5134#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5136 VPSlotTracker &SlotTracker) const {
5137 O << Indent << "WIDEN-PHI ";
5138
5140 O << " = phi ";
5142}
5143#endif
5144
5146 BasicBlock *VectorPH =
5147 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
5148 Value *StartMask = State.get(getOperand(0));
5149 PHINode *Phi =
5150 State.Builder.CreatePHI(StartMask->getType(), 2, "active.lane.mask");
5151 Phi->addIncoming(StartMask, VectorPH);
5152 State.set(this, Phi);
5153}
5154
5155#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5157 VPSlotTracker &SlotTracker) const {
5158 O << Indent << "ACTIVE-LANE-MASK-PHI ";
5159
5161 O << " = phi ";
5163}
5164#endif
5165
5166#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5168 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
5169 O << Indent << "CURRENT-ITERATION-PHI ";
5170
5172 O << " = phi ";
5174}
5175#endif
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
static MCDisassembler::DecodeStatus addOperand(MCInst &Inst, const MCOperand &Opnd)
AMDGPU Lower Kernel Arguments
AMDGPU Register Bank Select
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static const Function * getParent(const Value *V)
#define X(NUM, ENUM, NAME)
Definition ELF.h:857
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static void replaceAllUsesWith(Value *Old, Value *New, SmallPtrSet< BasicBlock *, 32 > &FreshBBs, bool IsHuge)
Replace all old uses with new ones, and push the updated BBs into FreshBBs.
Hexagon Common GEP
Value * getPointer(Value *Ptr)
iv users
Definition IVUsers.cpp:48
static constexpr Value * getValue(Ty &ValueOrUse)
static std::pair< Value *, APInt > getMask(Value *WideMask, unsigned Factor, ElementCount LeafValueEC)
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
This file provides a LoopVectorizationPlanner class.
static const SCEV * getAddressAccessSCEV(Value *Ptr, PredicatedScalarEvolution &PSE, const Loop *TheLoop)
Gets the address access SCEV for Ptr, if it should be used for cost modeling according to isAddressSC...
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static const Function * getCalledFunction(const Value *V)
static bool isOrdered(const Instruction *I)
uint64_t IntrinsicInst * II
#define P(N)
This file contains the declarations for profiling metadata utility functions.
const SmallVectorImpl< MachineOperand > & Cond
SI Fold Operands
static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, EVT VT, SDValue A, SDValue B, SDValue GlueChain, SDNodeFlags Flags)
This file contains some templates that are useful if you are working with the STL at all.
This file defines less commonly used SmallVector utilities.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
This file contains the declarations of different VPlan-related auxiliary helpers.
static Value * interleaveVectors(IRBuilderBase &Builder, ArrayRef< Value * > Vals, const Twine &Name)
Return a vector containing interleaved elements from multiple smaller input vectors.
static const ConstantFP * getConstantFP(const VPValue *V)
Returns the ConstantFP V wraps, or nullptr if it does not wrap one.
static void executePhiRecipe(VPSingleDefRecipe *R, VPPhiAccessors &Phi, VPTransformState &State, bool IsScalar, const Twine &Name)
Shared execute logic for VPPhi and VPWidenPHIRecipe.
static Value * createBitOrPointerCast(IRBuilderBase &Builder, Value *V, VectorType *DstVTy, const DataLayout &DL)
static Instruction::BinaryOps getSubRecurOpcode(RecurKind Kind)
static cl::opt< bool > VPlanPrintMetadata("vplan-print-metadata", cl::init(true), cl::Hidden, cl::desc("Controls the printing of recipe metadata when debugging."))
static VPExecutionFrequency getExecutionFrequencyFromMD(const MDNode *Node)
Returns the execution frequency recorded in Node.
static void printRecurrenceKind(raw_ostream &OS, const RecurKind &Kind)
static unsigned getCalledFnOperandIndex(ArrayRef< VPValue * > Operands)
For call VPInstruction operands, return the operand index of the called function.
This file contains the declarations of the Vectorization Plan base classes:
void printAsOperand(OutputBuffer &OB, Prec P=Prec::Default, bool StrictlyWorse=false) const
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:230
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
This class holds the attributes for a particular argument, parameter, function, or return value.
Definition Attributes.h:410
static LLVM_ABI Attribute getWithAlignment(LLVMContext &Context, Align Alignment)
Return a uniquified Attribute object that has the specific alignment set.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
Adds the attribute to the indicated argument.
This class represents a function call, abstracting a target machine's calling convention.
static LLVM_ABI bool isBitOrNoopPointerCastable(Type *SrcTy, Type *DestTy, const DataLayout &DL)
Check whether a bitcast, inttoptr, or ptrtoint cast between these types is valid and a no-op.
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
static LLVM_ABI StringRef getPredicateName(Predicate P)
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:548
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
bool isNegZero() const
Return true if the value is negative zero.
Definition Constants.h:473
bool isOne() const
Returns true if this value is exactly +1.0.
Definition Constants.h:485
bool isZero() const
Return true if the value is positive or negative zero.
Definition Constants.h:467
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
A debug info location.
Definition DebugLoc.h:126
static DebugLoc getUnknown()
Definition DebugLoc.h:153
constexpr bool isVector() const
One or more elements.
Definition TypeSize.h:320
static constexpr ElementCount getScalable(ScalarTy MinVal)
Definition TypeSize.h:308
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:305
constexpr bool isScalar() const
Exactly one element.
Definition TypeSize.h:316
static bool isSupportedFloatingPointType(Type *Ty)
Returns true if Ty is a supported floating-point type for phi, select, or call FPMathOperators.
Definition Operator.h:302
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
LLVM_ABI void print(raw_ostream &O) const
Print fast-math flags to O.
Definition Operator.cpp:290
void setAllowContract(bool B=true)
Definition FMF.h:90
bool noSignedZeros() const
Definition FMF.h:67
bool noInfs() const
Definition FMF.h:66
void setAllowReciprocal(bool B=true)
Definition FMF.h:87
bool allowReciprocal() const
Definition FMF.h:68
void setNoSignedZeros(bool B=true)
Definition FMF.h:84
bool allowReassoc() const
Flag queries.
Definition FMF.h:64
bool approxFunc() const
Definition FMF.h:70
void setNoNaNs(bool B=true)
Definition FMF.h:78
void setAllowReassoc(bool B=true)
Flag setters.
Definition FMF.h:75
bool noNaNs() const
Definition FMF.h:65
void setApproxFunc(bool B=true)
Definition FMF.h:93
void setNoInfs(bool B=true)
Definition FMF.h:81
bool allowContract() const
Definition FMF.h:69
Class to represent function types.
Type * getParamType(unsigned i) const
Parameter type accessors.
bool willReturn() const
Determine if the function will return.
Definition Function.h:647
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
Definition Function.h:247
bool doesNotThrow() const
Determine if the function cannot unwind.
Definition Function.h:577
bool doesNotAccessMemory() const
Determine if the function does not access memory.
Definition Function.cpp:869
Type * getReturnType() const
Returns the type of the ret val.
Definition Function.h:217
Represents flags for the getelementptr instruction/expression.
static GEPNoWrapFlags none()
Common base class shared among various IRBuilders.
Definition IRBuilder.h:114
Value * CreateInsertElement(Type *VecTy, Value *NewElt, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2677
IntegerType * getInt1Ty()
Fetch the type representing a single bit.
Definition IRBuilder.h:519
Value * CreateInsertValue(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &Name="")
Definition IRBuilder.h:2731
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2665
LLVM_ABI Value * CreateVectorSpliceRight(Value *V1, Value *V2, Value *Offset, const Twine &Name="")
Create a vector.splice.right intrinsic call, or a shufflevector that produces the same result if the ...
CondBrInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a conditional 'br Cond, TrueDest, FalseDest' instruction.
Definition IRBuilder.h:1224
LLVM_ABI Value * CreateSelectFMF(Value *C, Value *True, Value *False, FMFSource FMFSource, const Twine &Name="", Instruction *MDFrom=nullptr)
LLVM_ABI Value * CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name="")
Return a vector value that contains.
Value * CreateExtractValue(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &Name="")
Definition IRBuilder.h:2724
LLVM_ABI Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
Value * CreateFreeze(Value *V, const Twine &Name="")
Definition IRBuilder.h:2743
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
Definition IRBuilder.h:534
Value * CreateExtractVector(Type *DstType, Value *SrcVec, Value *Idx, const Twine &Name="")
Create a call to the vector.extract intrinsic.
Definition IRBuilder.h:1120
Value * CreatePtrAdd(Value *Ptr, Value *Offset, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Definition IRBuilder.h:2100
Value * CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy, const Twine &Name="", MDNode *FPMathTag=nullptr, FMFSource FMFSource={})
Definition IRBuilder.h:2292
void setFastMathFlags(FastMathFlags NewFMF)
Set the fast-math flags to be used with generated fp-math operators.
Definition IRBuilder.h:300
LLVM_ABI Value * CreateVectorReverse(Value *V, const Twine &Name="")
Return a vector value that contains the vector V reversed.
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2394
ConstantInt * getInt64(uint64_t C)
Get a constant 64-bit value.
Definition IRBuilder.h:482
Value * CreateLogicalAnd(Value *Cond1, Value *Cond2, const Twine &Name="", Instruction *MDFrom=nullptr)
Definition IRBuilder.h:1778
LLVM_ABI Value * CreateOrReduce(Value *Src)
Create a vector int OR reduction intrinsic of the source vector.
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition IRBuilder.h:477
Value * CreateCmp(CmpInst::Predicate Pred, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2524
Value * CreateNot(Value *V, const Twine &Name="")
Definition IRBuilder.h:1862
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2390
Value * CreateCountTrailingZeroElems(Type *ResTy, Value *Mask, bool ZeroIsPoison=true, const Twine &Name="")
Create a call to llvm.experimental_cttz_elts.
Definition IRBuilder.h:1162
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1447
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNeg=false)
Definition IRBuilder.h:2129
LLVM_ABI Value * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > OverloadTypes, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="", ArrayRef< OperandBundleDef > OpBundles={}, function_ref< void(CallInst *)> SetFn=[](CallInst *) {})
Variant to create a possibly constant-folded intrinsic.
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1430
ConstantInt * getFalse()
Get the constant value for i1 false.
Definition IRBuilder.h:462
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:1739
Value * CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2402
Value * CreateLogicalOr(Value *Cond1, Value *Cond2, const Twine &Name="", Instruction *MDFrom=nullptr)
Definition IRBuilder.h:1786
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
Definition IRBuilder.h:1600
LLVM_ABI Value * CreateStepVector(Type *DstType, const Twine &Name="")
Creates a vector of type DstType with the linear sequence <0, 1, ...>
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1464
LLVM_ABI Value * CreateUnaryIntrinsic(Intrinsic::ID ID, Value *Op, FMFSource FMFSource={}, const Twine &Name="")
Create a call to intrinsic ID with 1 operand which is mangled on its type.
A struct for saving information about induction variables.
@ IK_FpInduction
Floating point induction variable.
@ IK_IntInduction
Integer induction variable. Step = C.
static InstructionCost getInvalid(CostType Val=0)
bool isCast() const
bool isBinaryOp() const
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
const char * getOpcodeName() const
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
bool isUnaryOp() const
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:338
The group of interleaved loads/stores sharing the same stride and close to each other.
uint32_t getFactor() const
InstTy * getMember(uint32_t Index) const
Get the member with the given index Index.
bool isReverse() const
InstTy * getInsertPos() const
void addMetadata(InstTy *NewInst) const
Add metadata (e.g.
Align getAlign() const
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Metadata node.
Definition Metadata.h:1081
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1578
Information for memory intrinsic cost model.
Root of the metadata hierarchy.
Definition Metadata.h:64
LLVM_ABI void print(raw_ostream &OS, const Module *M=nullptr, bool IsForDebug=false) const
Print.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
An interface layer with SCEV used to manage how we see SCEV expressions for values in the context of ...
ScalarEvolution * getSE() const
Returns the ScalarEvolution analysis used.
static LLVM_ABI unsigned getOpcode(RecurKind Kind)
Returns the opcode corresponding to the RecurrenceKind.
static bool isAnyOfRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
static LLVM_ABI bool isSubRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is for a sub operation.
static bool isFindIVRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
static bool isMinMaxRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is any min/max kind.
This class represents an analyzed expression in the program.
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
This class represents the LLVM 'select' instruction.
This class provides computation of slot numbers for LLVM Assembly writing.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
reference emplace_back(ArgTypes &&... Args)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
static LLVM_ABI PartialReductionExtendKind getPartialReductionExtendKind(Instruction *I)
Get the kind of extension that an instruction represents.
static LLVM_ABI OperandValueInfo getOperandInfo(const Value *V)
Collect properties of V used in cost analysis, e.g. OP_PowerOf2.
llvm::VectorInstrContext VectorInstrContext
@ TCC_Free
Expected to fold away in lowering.
@ SK_Splice
Concatenates elements from the first input vector with elements of the second input vector.
@ SK_Reverse
Reverse the order of the vector.
CastContextHint
Represents a hint about the context in which a cast is used.
@ Reversed
The cast is used with a reversed load/store.
@ Masked
The cast is used with a masked load/store.
@ None
The cast is not used with a load/store of any kind.
@ Normal
The cast is used with a normal load/store.
@ Interleave
The cast is used with an interleaved load/store.
@ GatherScatter
The cast is used with a gather/scatter.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:300
bool isByteTy() const
True if this is an instance of ByteType.
Definition Type.h:237
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:299
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:272
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:363
bool isStructTy() const
True if this is an instance of StructType.
Definition Type.h:271
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:222
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:296
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
Definition Type.h:265
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:303
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
value_op_iterator value_op_end()
Definition User.h:288
void setOperand(unsigned i, Value *Val)
Definition User.h:212
Value * getOperand(unsigned i) const
Definition User.h:207
value_op_iterator value_op_begin()
Definition User.h:285
void execute(VPTransformState &State) override
Generate the active lane mask phi of the vector loop.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph.
Definition VPlan.h:4418
RecipeListTy & getRecipeList()
Returns a reference to the list of recipes.
Definition VPlan.h:4471
iterator end()
Definition VPlan.h:4455
void insert(VPRecipeBase *Recipe, iterator InsertPt)
Definition VPlan.h:4484
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:3004
unsigned getNumIncomingValues() const
Return the number of incoming values, taking into account when normalized the first incoming value wi...
Definition VPlan.h:2999
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
bool isNormalized() const
A normalized blend is one that has an odd number of operands, whereby the first operand does not have...
Definition VPlan.h:2995
VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
Definition VPlan.h:95
const VPBlocksTy & getPredecessors() const
Definition VPlan.h:228
static bool isHeader(const VPBlockBase *VPB, const VPDominatorTree &VPDT)
Returns true if VPB is a loop header, based on regions or VPDT in their absence.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPBranchOnMaskRecipe.
void execute(VPTransformState &State) override
Generate the extraction of the appropriate bit from the block mask and the conditional branch.
VPlan-based builder utility analogous to IRBuilder.
LLVM_ABI_FOR_TEST void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
unsigned getNumDefinedValues() const
Returns the number of values defined by the VPDef.
Definition VPlanValue.h:579
VPValue * getVPSingleValue()
Returns the only VPValue defined by the VPDef.
Definition VPlanValue.h:552
VPValue * getVPValue(unsigned I)
Returns the VPValue with index I defined by the VPDef.
Definition VPlanValue.h:564
ArrayRef< VPRecipeValue * > definedValues()
Returns an ArrayRef of the values defined by the VPDef.
Definition VPlanValue.h:574
InductionDescriptor::InductionKind getInductionKind() const
Definition VPlan.h:4236
VPValue * getIndex() const
Definition VPlan.h:4233
VPValue * getStepValue() const
Definition VPlan.h:4234
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPDerivedIVRecipe.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPValue * getStartValue() const
Definition VPlan.h:4232
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPExpandSCEVRecipe(const SCEV *Expr)
bool isVectorToScalar() const
Returns true if this VPExpressionRecipe produces a single scalar.
SmallVector< VPSingleDefRecipe * > decompose()
Return and insert the recipes of the expression back into the VPlan, directly before the current reci...
bool mayHaveSideEffects() const
Returns true if this expression contains recipes that may have side effects.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Compute the cost of this recipe either using a recipe's specialized implementation or using the legac...
bool mayReadOrWriteMemory() const
Returns true if this expression contains recipes that may read from or write to memory.
VPExpressionRecipe(ExpressionTypes ExpressionType, ArrayRef< VPSingleDefRecipe * > ExpressionRecipes)
Construct a new VPExpressionRecipe by internalizing recipes in ExpressionRecipes.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this header phi recipe.
VPValue * getStartValue()
Returns the start value of the phi, if one is set.
Definition VPlan.h:2482
void execute(VPTransformState &State) override
Produce a vectorized histogram operation.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPHistogramRecipe.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPValue * getMask() const
Return the mask operand if one was provided, or a null pointer if all lanes should be executed uncond...
Definition VPlan.h:2203
Class to record and manage LLVM IR flags.
Definition VPlan.h:704
FastMathFlagsTy FMFs
Definition VPlan.h:793
ReductionFlagsTy ReductionFlags
Definition VPlan.h:795
LLVM_ABI_FOR_TEST bool flagsValidForOpcode(unsigned Opcode) const
Returns true if the set flags are valid for Opcode.
WrapFlagsTy WrapFlags
Definition VPlan.h:787
void printFlags(raw_ostream &O) const
bool hasFastMathFlags() const
Returns true if the recipe has fast-math flags.
Definition VPlan.h:1010
static VPIRFlags getDefaultFlags(unsigned Opcode, Type *ResultTy=nullptr)
Returns default flags for Opcode and scalar ResultTy for opcodes that support it, asserts otherwise.
bool isReductionOrdered() const
Definition VPlan.h:1071
TruncFlagsTy TruncFlags
Definition VPlan.h:788
CmpInst::Predicate getPredicate() const
Definition VPlan.h:982
LLVM_ABI_FOR_TEST FastMathFlags getFastMathFlagsOrNone() const
ExactFlagsTy ExactFlags
Definition VPlan.h:790
void intersectFlags(const VPIRFlags &Other)
Only keep flags also present in Other.
uint8_t GEPFlagsStorage
Definition VPlan.h:791
GEPNoWrapFlags getGEPNoWrapFlags() const
Definition VPlan.h:1000
bool hasPredicate() const
Returns true if the recipe has a comparison predicate.
Definition VPlan.h:1005
LLVM_ABI_FOR_TEST bool hasRequiredFlagsForOpcode(unsigned Opcode, Type *ResultTy) const
Returns true if Opcode with scalar result type ResultTy has its required flags set.
DisjointFlagsTy DisjointFlags
Definition VPlan.h:789
FCmpFlagsTy FCmpFlags
Definition VPlan.h:794
NonNegFlagsTy NonNegFlags
Definition VPlan.h:792
bool isReductionInLoop() const
Definition VPlan.h:1077
void applyFlags(Instruction &I) const
Apply the IR flags to I.
Definition VPlan.h:939
uint8_t CmpPredStorage
Definition VPlan.h:786
RecurKind getRecurKind() const
Definition VPlan.h:1065
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
LLVM_ABI_FOR_TEST InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPIRInstruction.
VPIRInstruction(Instruction &I)
VPIRInstruction::create() should be used to create VPIRInstructions, as subclasses may need to be cre...
Definition VPlan.h:1733
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
std::optional< VPExecutionFrequency > getExecutionFrequency() const
Returns the frequency recorded by setExecutionFrequency, if any.
void intersect(const VPIRMetadata &MD)
Intersect this VPIRMetadata object with MD, keeping only metadata nodes that are common to both.
void clearExecutionFrequency()
Drop the frequency recorded by setExecutionFrequency, if any.
VPIRMetadata()=default
void print(raw_ostream &O, VPSlotTracker &SlotTracker) const
Print metadata with node IDs.
void applyMetadata(Instruction &I) const
Add all metadata to I.
void setMetadata(unsigned Kind, MDNode *Node)
Set metadata with kind Kind to Node.
Definition VPlan.h:1240
void setExecutionFrequency(std::optional< VPExecutionFrequency > Freq, LLVMContext &Ctx)
Record that the recipe executes with frequency Freq, relative to the entry of the loop region.
This is a concrete Recipe that models a single VPlan-level instruction.
Definition VPlan.h:1305
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPInstruction.
VPInstruction(unsigned Opcode, ArrayRef< VPValue * > Operands, const VPIRFlags &Flags={}, const VPIRMetadata &MD={}, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="", Type *ResultTy=nullptr)
bool doesGeneratePerAllLanes() const
Returns true if this recipe produces scalar values for all VF lanes.
@ ExtractLastActive
Extracts the last active lane from a set of vectors.
Definition VPlan.h:1415
@ Intrinsic
Calls a scalar intrinsic. The intrinsic ID is the last operand.
Definition VPlan.h:1427
@ ExtractLane
Extracts a single lane (first operand) from a set of vector operands.
Definition VPlan.h:1406
@ ExitingIVValue
Compute the exiting value of a wide induction after vectorization, that is the value of the last lane...
Definition VPlan.h:1419
@ WideIVStep
Scale the first operand (vector step) by the second operand (scalar-step).
Definition VPlan.h:1423
@ ResumeForEpilogue
Explicit user for the resume phi of the canonical induction in the main VPlan, used by the epilogue v...
Definition VPlan.h:1409
@ Unpack
Extracts all lanes from its (non-scalable) vector operand.
Definition VPlan.h:1356
@ ReductionStartVector
Start vector for reductions with 3 operands: the original start value, the identity value for the red...
Definition VPlan.h:1402
@ BuildVector
Creates a fixed-width vector containing all operands.
Definition VPlan.h:1351
@ BuildStructVector
Given operands of (the same) struct type, creates a struct of fixed- width vectors each containing a ...
Definition VPlan.h:1348
@ CanonicalIVIncrementForPart
Definition VPlan.h:1332
@ ComputeReductionResult
Reduce the operands to the final reduction result using the operation specified via the operation's V...
Definition VPlan.h:1359
bool hasResult() const
Definition VPlan.h:1512
bool opcodeMayReadOrWriteFromMemory() const
Returns true if the underlying opcode may read from or write to memory.
LLVM_DUMP_METHOD void dump() const
Print the VPInstruction to dbgs() (for debugging).
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the VPInstruction to O.
StringRef getName() const
Returns the symbolic name assigned to the VPInstruction.
Definition VPlan.h:1598
unsigned getOpcode() const
Definition VPlan.h:1491
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
void addOperand(VPValue *Op)
Add Op as operand of this VPInstruction.
bool isVectorToScalar() const
Returns true if this VPInstruction produces a scalar value from a vector, e.g.
bool isSingleScalar() const
Returns true if the recipe produces a single scalar value.
unsigned getNumOperandsForOpcode() const
Return the number of operands determined by the opcode of the VPInstruction, excluding mask.
bool isMasked() const
Returns true if the VPInstruction has a mask operand.
Definition VPlan.h:1537
void execute(VPTransformState &State) override
Generate the instruction.
bool usesFirstPartOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first part of operand Op.
bool needsMaskForGaps() const
Return true if the access needs a mask because of the gaps.
Definition VPlan.h:3108
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this recipe.
Instruction * getInsertPos() const
Definition VPlan.h:3112
const InterleaveGroup< Instruction > * getInterleaveGroup() const
Definition VPlan.h:3110
VPValue * getMask() const
Return the mask used by this recipe.
Definition VPlan.h:3102
ArrayRef< VPValue * > getStoredValues() const
Return the VPValues stored by this interleave group.
Definition VPlan.h:3131
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition VPlan.h:3096
VPValue * getEVL() const
The VPValue of the explicit vector length.
Definition VPlan.h:3205
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
unsigned getNumStoreOperands() const override
Returns the number of stored operands of this interleave group.
Definition VPlan.h:3218
void execute(VPTransformState &State) override
Generate the wide load or store, and shuffles.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
unsigned getNumStoreOperands() const override
Returns the number of stored operands of this interleave group.
Definition VPlan.h:3168
void execute(VPTransformState &State) override
Generate the wide load or store, and shuffles.
static LLVM_ABI std::optional< unsigned > getMaskParamPos(Intrinsic::ID IntrinsicID)
static LLVM_ABI std::optional< unsigned > getMemoryDataParamPos(Intrinsic::ID)
static LLVM_ABI std::optional< unsigned > getMemoryPointerParamPos(Intrinsic::ID)
In what follows, the term "input IR" refers to code that is fed into the vectorizer whereas the term ...
static VPLane getLastLaneForVF(const ElementCount &VF)
static VPLane getLaneFromEnd(const ElementCount &VF, unsigned Offset)
static VPLane getFirstLane()
Helper type to provide functions to access incoming values and blocks for phi-like recipes.
Definition VPlan.h:1613
virtual const VPRecipeBase * getAsRecipe() const =0
Return a VPRecipeBase* to the current object.
VPValue * getIncomingValueForBlock(const VPBasicBlock *VPBB) const
Returns the incoming value for VPBB. VPBB must be an incoming block.
void removeIncomingValueFor(VPBlockBase *IncomingBlock) const
Removes the incoming value for IncomingBlock, which must be a predecessor.
detail::zippy< llvm::detail::zip_first, VPUser::const_operand_range, const_incoming_blocks_range > incoming_values_and_blocks() const
Returns an iterator range over pairs of incoming values and corresponding incoming blocks.
Definition VPlan.h:1662
VPValue * getIncomingValue(unsigned Idx) const
Returns the incoming VPValue with index Idx.
Definition VPlan.h:1622
void printPhiOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const
Print the recipe.
void setIncomingValueForBlock(const VPBasicBlock *VPBB, VPValue *V) const
Sets the incoming value for VPBB to V.
void execute(VPTransformState &State) override
Generates phi nodes for live-outs (from a replicate region) as needed to retain SSA form.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPRecipeBase is a base class modeling a sequence of one or more output IR instructions.
Definition VPlan.h:411
bool mayReadFromMemory() const
Returns true if the recipe may read from memory.
bool mayHaveSideEffects() const
Returns true if the recipe may have side-effects.
virtual void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const =0
Each concrete VPRecipe prints itself, without printing common information, like debug info or metadat...
VPRegionBlock * getRegion()
Definition VPlan.h:4817
LLVM_ABI_FOR_TEST void dump() const
Dump the recipe to stderr (for debugging).
Definition VPlan.cpp:115
bool isPhi() const
Returns true for PHI-like recipes.
bool mayWriteToMemory() const
Returns true if the recipe may write to memory.
VPRecipeTy getVPRecipeID() const
Definition VPlan.h:529
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:483
DebugLoc getDebugLoc() const
Returns the debug location of the recipe.
Definition VPlan.h:561
void moveBefore(VPBasicBlock &BB, iplist< VPRecipeBase >::iterator I)
Unlink this recipe and insert into BB before I.
bool isSafeToSpeculativelyExecute() const
Return true if we can safely execute this recipe unconditionally even if it is masked originally.
void insertBefore(VPRecipeBase *InsertPos)
Insert an unlinked recipe into a basic block immediately before the specified recipe.
void insertAfter(VPRecipeBase *InsertPos)
Insert an unlinked Recipe into a basic block immediately after the specified Recipe.
iplist< VPRecipeBase >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
VPRecipeBase(VPRecipeTy SC, ArrayRef< VPValue * > Operands, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:473
InstructionCost cost(ElementCount VF, VPCostContext &Ctx)
Return the cost of this recipe, taking into account if the cost computation should be skipped and the...
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const
Print the recipe, delegating to printRecipe().
void removeFromParent()
This method unlinks 'this' from the containing basic block, but does not delete it.
void moveAfter(VPRecipeBase *MovePos)
Unlink this recipe from its current VPBasicBlock and insert it into the VPBasicBlock that MovePos liv...
Type * getScalarType() const
Returns the scalar type of this VPRecipeValue.
Definition VPlanValue.h:354
friend class VPValue
Definition VPlanValue.h:333
void execute(VPTransformState &State) override
Generate the reduction in the loop.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPValue * getEVL() const
The VPValue of the explicit vector length.
Definition VPlan.h:3379
unsigned getVFScaleFactor() const
Get the factor that the VF of this recipe's output should be scaled by, or 1 if it isn't scaled.
Definition VPlan.h:2908
bool isInLoop() const
Returns true if the phi is part of an in-loop reduction.
Definition VPlan.h:2927
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate the phi/select nodes.
bool isConditional() const
Return true if the in-loop reduction is conditional.
Definition VPlan.h:3318
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:3331
VPValue * getCondOp() const
The VPValue of the condition for the block.
Definition VPlan.h:3333
RecurKind getRecurrenceKind() const
Return the recurrence kind for the in-loop reduction.
Definition VPlan.h:3314
bool isPartialReduction() const
Returns true if the reduction outputs a vector with a scaled down VF.
Definition VPlan.h:3320
VPValue * getChainOp() const
The VPValue of the scalar Chain being accumulated.
Definition VPlan.h:3329
bool isInLoop() const
Returns true if the reduction is in-loop.
Definition VPlan.h:3324
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate the reduction in the loop.
VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks which form a Single-Entry-S...
Definition VPlan.h:4643
bool isReplicator() const
An indicator whether this region is to generate multiple replicated instances of output IR correspond...
Definition VPlan.h:4719
void execute(VPTransformState &State) override
Generate replicas of the desired Ingredient.
bool isSingleScalar() const
Returns true if the recipe produces a single scalar value.
Definition VPlan.h:3460
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPReplicateRecipe.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
static Type * computeScalarType(const Instruction *I, ArrayRef< VPValue * > Operands)
Compute the scalar result type for a VPReplicateRecipe wrapping I with Operands (excluding any predic...
static InstructionCost computeCallCost(Function *CalledFn, Type *ResultTy, ArrayRef< const VPValue * > ArgOps, bool IsSingleScalar, ElementCount VF, VPCostContext &Ctx)
Return the cost of scalarizing a call to CalledFn with argument operands ArgOps for a given VF.
unsigned getOpcode() const
Definition VPlan.h:3498
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPScalarIVStepsRecipe.
bool doesGeneratePerAllLanes() const
Returns true if this recipe produces scalar values for all VF lanes.
VPValue * getStepValue() const
Definition VPlan.h:4291
VPValue * getStartIndex() const
Return the StartIndex, or null if known to be zero, valid only after unrolling.
Definition VPlan.h:4299
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate the scalarized versions of the phi node as needed by their users.
VPSingleDefRecipe is a base class for recipes that model a sequence of one or more output IR that def...
Definition VPlan.h:619
Instruction * getUnderlyingInstr()
Returns the underlying instruction.
Definition VPlan.h:689
LLVM_ABI_FOR_TEST LLVM_DUMP_METHOD void dump() const
Print this VPSingleDefRecipe to dbgs() (for debugging).
VPSingleDefRecipe(VPRecipeTy SC, ArrayRef< VPValue * > Operands, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:621
This class can be used to assign names to VPValues.
A symbolic live-in VPValue, used for values like vector trip count, VF, and VFxUF.
Definition VPlanValue.h:217
This class augments VPValue with operands which provide the inverse def-use edges from VPValue's user...
Definition VPlanValue.h:401
void printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const
Print the operands to O.
Definition VPlan.cpp:1496
operand_range operands()
Definition VPlanValue.h:474
unsigned getNumOperands() const
Definition VPlanValue.h:441
VPValue * getOperand(unsigned N) const
Definition VPlanValue.h:442
bool operands_empty() const
Definition VPlanValue.h:478
void addOperand(VPValue *Operand)
Definition VPlanValue.h:427
This is the base class of the VPlan Def/Use graph, used for modeling the data flow into,...
Definition VPlanValue.h:50
Type * getScalarType() const
Returns the scalar type of this VPValue, dispatching based on the concrete subclass.
Definition VPlan.cpp:147
Value * getLiveInIRValue() const
Return the underlying IR value for a VPIRValue.
Definition VPlan.cpp:141
bool isDefinedOutsideLoopRegions() const
Returns true if the VPValue is defined outside any loop.
Definition VPlan.cpp:1447
VPRecipeBase * getDefiningRecipe()
Returns the recipe defining this VPValue or nullptr if it is not defined by a recipe,...
Definition VPlan.cpp:128
void printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const
Definition VPlan.cpp:1492
Value * getUnderlyingValue() const
Return the underlying Value attached to this VPValue.
Definition VPlanValue.h:75
void setUnderlyingValue(Value *Val)
Definition VPlanValue.h:209
VPUser * getSingleUser()
Return the single user of this value, or nullptr if there is not exactly one user.
Definition VPlanValue.h:179
VPValue * getVFValue() const
Definition VPlan.h:2297
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
Type * getSourceElementType() const
Definition VPlan.h:2294
int64_t getStride() const
Definition VPlan.h:2295
void materializeOffset(unsigned Part=0)
Adds the offset operand to the recipe.
VPValue * getStride() const
Definition VPlan.h:2371
Type * getSourceElementType() const
Definition VPlan.h:2386
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
VPValue * getVFxPart() const
Definition VPlan.h:2373
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
operand_range args()
Definition VPlan.h:2154
Function * getCalledScalarFunction() const
Definition VPlan.h:2150
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenCallRecipe.
void execute(VPTransformState &State) override
Produce a widened version of the call instruction.
static InstructionCost computeCallCost(Function *Variant, VPCostContext &Ctx)
Return the cost of widening a call using the vector function Variant.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
Instruction::CastOps getOpcode() const
Definition VPlan.h:1925
LLVM_ABI_FOR_TEST void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
LLVM_ABI_FOR_TEST void execute(VPTransformState &State) override
Produce widened copies of the cast.
LLVM_ABI_FOR_TEST InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenCastRecipe.
void execute(VPTransformState &State) override
Generate the gep nodes.
Type * getSourceElementType() const
Definition VPlan.h:2251
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
VPValue * getStepValue()
Returns the step value of the induction.
Definition VPlan.h:2566
const InductionDescriptor & getInductionDescriptor() const
Returns the induction descriptor for the recipe.
Definition VPlan.h:2586
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenIntOrFpInductionRecipe.
TruncInst * getTruncInst()
Returns the first defined value as TruncInst, if it is one or nullptr otherwise.
Definition VPlan.h:2674
bool isCanonical() const
Returns true if the induction is canonical, i.e.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
CallInst * createVectorCall(VPTransformState &State)
Helper function to produce the widened intrinsic call.
Intrinsic::ID getVectorIntrinsicID() const
Return the ID of the intrinsic.
Definition VPlan.h:2039
LLVM_ABI_FOR_TEST void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
StringRef getIntrinsicName() const
Return to name of the intrinsic as string.
static InstructionCost computeCallCost(Intrinsic::ID ID, ArrayRef< const VPValue * > Operands, const VPRecipeWithIRFlags &R, ElementCount VF, VPCostContext &Ctx)
Compute the cost of a vector intrinsic with ID and Operands.
LLVM_ABI_FOR_TEST bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the VPUser only uses the first lane of operand Op.
LLVM_ABI_FOR_TEST void execute(VPTransformState &State) override
Produce a widened version of the vector intrinsic.
LLVM_ABI_FOR_TEST InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this vector intrinsic.
static InstructionCost computeMemIntrinsicCost(Intrinsic::ID IID, Type *Ty, bool IsMasked, Align Alignment, VPCostContext &Ctx)
Helper function for computing the cost of vector memory intrinsic.
void execute(VPTransformState &State) override
Produce a widened version of the vector memory intrinsic.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this vector memory intrinsic.
bool IsMasked
Whether the memory access is masked.
Definition VPlan.h:3765
bool isConsecutive() const
Return whether the loaded-from / stored-to addresses are consecutive.
Definition VPlan.h:3790
Instruction & Ingredient
Definition VPlan.h:3756
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const
Return the cost of this VPWidenMemoryRecipe.
bool Consecutive
Whether the accessed addresses are consecutive.
Definition VPlan.h:3762
VPValue * getMask() const
Return the mask used by this recipe.
Definition VPlan.h:3800
Align Alignment
Alignment information for this memory access.
Definition VPlan.h:3759
virtual VPRecipeBase * getAsRecipe()=0
Return a VPRecipeBase* to the current object.
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition VPlan.h:3793
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenPHIRecipe.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate the phi/select nodes.
bool onlyScalarsGenerated(bool IsScalable)
Returns true if only scalar values will be generated.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenPointerInductionRecipe.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenRecipe.
void execute(VPTransformState &State) override
Produce a widened instruction using the opcode and operands of the recipe, processing State....
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
unsigned getOpcode() const
Definition VPlan.h:1868
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition VPlan.h:4830
const DataLayout & getDataLayout() const
Definition VPlan.h:5044
VPIRValue * getConstantInt(Type *Ty, uint64_t Val, bool IsSigned=false)
Return a VPIRValue wrapping a ConstantInt with the given type and value.
Definition VPlan.h:5146
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:394
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
void mutateType(Type *Ty)
Mutate the type of this Value to be of the specified type.
Definition Value.h:809
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
Base class of all SIMD vector types.
ElementCount getElementCount() const
Return an ElementCount instance to represent the (possibly scalable) number of elements in the vector...
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
Type * getElementType() const
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:165
constexpr LeafTy divideCoefficientBy(ScalarTy RHS) const
We do not provide the '/' operator here because division for polynomial types does not work in the sa...
Definition TypeSize.h:252
self_iterator getIterator()
Definition ilist_node.h:123
iterator erase(iterator where)
Definition ilist.h:204
pointer remove(iterator &IT)
Definition ilist.h:188
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
LLVM_ABI Intrinsic::ID getDeinterleaveIntrinsicID(unsigned Factor)
Returns the corresponding llvm.vector.deinterleaveN intrinsic for factor N.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
LLVM_ABI AttributeSet getFnAttributes(LLVMContext &C, ID id)
Return the function attributes for an intrinsic.
LLVM_ABI StringRef getBaseName(ID id)
Return the LLVM name for an intrinsic, without encoded types for overloading, such as "llvm....
SpecificConstantMatch m_ZeroInt()
Convenience matchers for specific integer values.
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
auto m_Cmp()
Matches any compare instruction and ignore it.
bool match(Val *V, const Pattern &P)
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
LogicalOp_match< LHS, RHS, Instruction::And, true > m_c_LogicalAnd(const LHS &L, const RHS &R)
Matches L && R with LHS and RHS in either order.
LogicalOp_match< LHS, RHS, Instruction::Or, true > m_c_LogicalOr(const LHS &L, const RHS &R)
Matches L || R with LHS and RHS in either order.
int_pred_ty< is_zero_int, 1 > m_False()
auto m_VPValue()
Match an arbitrary VPValue and ignore it.
int_pred_ty< is_one, 1 > m_True()
VPInstruction_match< VPInstruction::BranchOnCond > m_BranchOnCond()
VPInstruction_match< VPInstruction::Reverse, Op0_t > m_Reverse(const Op0_t &Op0)
initializer< Ty > init(const Ty &Val)
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:679
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
bool isSingleScalar(const VPValue *VPV)
Returns true if VPV is a single scalar, either because it produces the same value for all lanes or on...
bool isAddressSCEVForCost(const SCEV *Addr, ScalarEvolution &SE, const Loop *L)
Returns true if Addr is an address SCEV that can be passed to TTI::getAddressComputationCost,...
bool onlyFirstPartUsed(const VPValue *Def)
Returns true if only the first part of Def is used.
Intrinsic::ID getIntrinsicID(const Ty *R)
Return the intrinsic ID underlying a call.
Definition VPlanUtils.h:87
bool onlyFirstLaneUsed(const VPValue *Def)
Returns true if only the first lane of Def is used.
constexpr uint64_t AlwaysExecutesFreq
Denominator of the frequencies computed by computeExecutionFrequencies, i.e.
Definition VPlanUtils.h:238
bool onlyScalarValuesUsed(const VPValue *Def)
Returns true if only scalar values of Def are used by all users.
bool isUsedByLoadStoreAddress(const VPValue *V)
Returns true if V is used as part of the address of another load or store.
const SCEV * getSCEVExprForVPValue(const VPValue *V, PredicatedScalarEvolution &PSE, const Loop *L=nullptr)
Return the SCEV expression for V.
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
LLVM_ABI Value * createSimpleReduction(IRBuilderBase &B, Value *Src, RecurKind RdxKind)
Create a reduction of the given vector.
@ Offset
Definition DWP.cpp:577
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
Definition STLExtras.h:846
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:1755
LLVM_ABI Intrinsic::ID getMinMaxReductionIntrinsicOp(Intrinsic::ID RdxID)
Returns the min/max intrinsic used when expanding a min/max reduction.
InstructionCost Cost
@ Undef
Value of the register doesn't matter.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2570
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
VectorInstrContext
Represents a hint about the context in which a vector instruction or intrinsic is used.
@ None
The instruction is not folded.
@ BinaryOp
One of the operands is a binary op.
auto map_to_vector(ContainerTy &&C, FuncTy &&F)
Map a range to a SmallVector with element types deduced from the mapping.
Value * getRuntimeVF(IRBuilderBase &B, Type *Ty, ElementCount VF)
Return the runtime value for VF.
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
void interleaveComma(const Container &c, StreamT &os, UnaryFunctor each_fn)
Definition STLExtras.h:2329
auto cast_or_null(const Y &Val)
Definition Casting.h:714
LLVM_ABI Value * concatenateVectors(IRBuilderBase &Builder, ArrayRef< Value * > Vecs)
Concatenate a list of vectors.
Align getLoadStoreAlignment(const Value *I)
A helper function that returns the alignment of load or store instruction.
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
LLVM_ABI Value * createMinMaxOp(IRBuilderBase &Builder, RecurKind RK, Value *Left, Value *Right)
Returns a Min/Max operation corresponding to MinMaxRecurrenceKind.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
static Error getOffset(const SymbolRef &Sym, SectionRef Sec, uint64_t &Result)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
LLVM_ABI Constant * createBitMaskForGaps(IRBuilderBase &Builder, unsigned VF, const InterleaveGroup< Instruction > &Group)
Create a mask that filters the members of an interleave group where there are gaps.
LLVM_ABI llvm::SmallVector< int, 16 > createStrideMask(unsigned Start, unsigned Stride, unsigned VF)
Create a stride shuffle mask.
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
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."))
Definition VPlan.cpp:58
ElementCount getVectorizedTypeVF(Type *Ty)
Returns the number of vector elements for a vectorized type.
LLVM_ABI llvm::SmallVector< int, 16 > createReplicatedMask(unsigned ReplicationFactor, unsigned VF)
Create a mask with replicated elements.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool isPointerTy(const Type *T)
Definition SPIRVUtils.h:383
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
SmallVector< ValueTypeFromRangeType< R >, Size > to_vector(R &&Range)
Given a range of type R, iterate the entire range and return a SmallVector with elements of the vecto...
Type * toVectorizedTy(Type *Ty, ElementCount EC)
A helper for converting to vectorized types.
LLVM_ABI Type * computeScalarTypeForInstruction(unsigned Opcode, ArrayRef< VPValue * > Operands)
Compute the scalar result type for an IR Opcode given Operands.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition Format.h:102
auto drop_end(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the last N elements excluded.
Definition STLExtras.h:323
LLVM_ABI bool isVectorIntrinsicWithStructReturnOverloadAtField(Intrinsic::ID ID, int RetIdx, const TargetTransformInfo *TTI)
Identifies if the vector form of the intrinsic that returns a struct is overloaded at the struct elem...
@ Other
Any other memory.
Definition ModRef.h:68
static const MachineInstrBuilder & addOffset(const MachineInstrBuilder &MIB, int Offset)
LLVM_ABI llvm::SmallVector< int, 16 > createInterleaveMask(unsigned VF, unsigned NumVecs)
Create an interleave shuffle mask.
RecurKind
These are the kinds of recurrences that we support.
@ UMin
Unsigned integer min implemented in terms of select(cmp()).
@ FMinimumNum
FP min with llvm.minimumnum semantics.
@ FindIV
FindIV reduction with select(icmp(),x,y) where one of (x,y) is a loop induction variable (increasing ...
@ Or
Bitwise or logical OR of integers.
@ FMinimum
FP min with llvm.minimum semantics.
@ FMaxNum
FP max with llvm.maxnum semantics including NaNs.
@ Mul
Product of integers.
@ FSub
Subtraction of floats.
@ FAddChainWithSubs
A chain of fadds and fsubs.
@ None
Not a recurrence.
@ AnyOf
AnyOf reduction with select(cmp(),x,y) where one of (x,y) is loop invariant, and both x and y are int...
@ Xor
Bitwise or logical XOR of integers.
@ FindLast
FindLast reduction with select(cmp(),x,y) where x and y.
@ FMax
FP max implemented in terms of select(cmp()).
@ FMaximum
FP max with llvm.maximum semantics.
@ FMulAdd
Sum of float products with llvm.fmuladd(a * b + sum).
@ FMul
Product of floats.
@ SMax
Signed integer max implemented in terms of select(cmp()).
@ And
Bitwise or logical AND of integers.
@ SMin
Signed integer min implemented in terms of select(cmp()).
@ FMin
FP min implemented in terms of select(cmp()).
@ FMinNum
FP min with llvm.minnum semantics including NaNs.
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
@ AddChainWithSubs
A chain of adds and subs.
@ FAdd
Sum of floats.
@ FMaximumNum
FP max with llvm.maximumnum semantics.
@ UMax
Unsigned integer max implemented in terms of select(cmp()).
LLVM_ABI bool isVectorIntrinsicWithScalarOpAtArg(Intrinsic::ID ID, unsigned ScalarOpdIdx, const TargetTransformInfo *TTI)
Identifies if the vector form of the intrinsic has a scalar operand.
LLVM_ABI Value * getRecurrenceIdentity(RecurKind K, Type *Tp, FastMathFlags FMF)
Given information about an recurrence kind, return the identity for the @llvm.vector....
DWARFExpression::Operation Op
LLVM_ABI bool extractBranchWeights(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Extract branch weights from MD_prof metadata.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2208
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
Type * getLoadStoreType(const Value *I)
A helper function that returns the type of a load or store instruction.
LLVM_ABI Value * createOrderedReduction(IRBuilderBase &B, RecurKind RdxKind, Value *Src, Value *Start)
Create an ordered reduction intrinsic using the given recurrence kind RdxKind.
ArrayRef< Type * > getContainedTypes(Type *const &Ty)
Returns the types contained in Ty.
Type * toVectorTy(Type *Scalar, ElementCount EC)
A helper function for converting Scalar types to vector types.
LLVM_ABI bool isVectorIntrinsicWithOverloadTypeAtArg(Intrinsic::ID ID, int OpdIdx, const TargetTransformInfo *TTI)
Identifies if the vector form of the intrinsic is overloaded on the type of the operand at index OpdI...
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Struct to hold various analysis needed for cost computations.
static bool isFreeScalarIntrinsic(Intrinsic::ID ID)
Returns true if ID is a pseudo intrinsic that is dropped via scalarization rather than widened.
Definition VPlan.cpp:1940
static bool executesAtMostOnce(const VPlan &Plan, ElementCount VF)
Returns true if the vector loop body of Plan is known to execute at most once at VF,...
TargetTransformInfo::TargetCostKind CostKind
The frequency with which a recipe executes, relative to the entry of the loop region.
Definition VPlan.h:1182
void execute(VPTransformState &State) override
Generate the phi nodes.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this first-order recurrence phi recipe.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
An overlay for VPIRInstructions wrapping PHI nodes enabling convenient use cast/dyn_cast/isa and exec...
Definition VPlan.h:1791
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
PHINode & getIRPhi() const
Definition VPlan.h:1804
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
void execute(VPTransformState &State) override
Generate the instruction.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPRecipeWithIRFlags(VPRecipeTy SC, ArrayRef< VPValue * > Operands, const VPIRFlags &Flags, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:1127
InstructionCost getCostForRecipeWithOpcode(unsigned Opcode, ElementCount VF, VPCostContext &Ctx) const
Compute the cost for this recipe for VF, using Opcode and Ctx.
SmallDenseMap< const VPBasicBlock *, BasicBlock * > VPBB2IRBB
A mapping of each VPBasicBlock to the corresponding BasicBlock.
VPTransformState holds information passed down when "executing" a VPlan, needed for generating the ou...
struct llvm::VPTransformState::CFGState CFG
Value * get(const VPValue *Def, bool IsScalar=false)
Get the generated vector Value for a given VPValue Def if IsScalar is false, otherwise return the gen...
Definition VPlan.cpp:282
IRBuilderBase & Builder
Hold a reference to the IRBuilder used to generate output IR code.
ElementCount VF
The chosen Vectorization Factor of the loop being vectorized.
void execute(VPTransformState &State) override
Generate the wide load or gather.
VPRecipeBase * getAsRecipe() override
Return a VPRecipeBase* to the current object.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenLoadEVLRecipe.
VPValue * getEVL() const
Return the EVL operand.
Definition VPlan.h:3891
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate a wide load or gather.
VPRecipeBase * getAsRecipe() override
Return a VPRecipeBase* to the current object.
VPValue * getStoredValue() const
Return the address accessed by this recipe.
Definition VPlan.h:3993
void execute(VPTransformState &State) override
Generate the wide store or scatter.
VPRecipeBase * getAsRecipe() override
Return a VPRecipeBase* to the current object.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenStoreEVLRecipe.
VPValue * getEVL() const
Return the EVL operand.
Definition VPlan.h:3996
void execute(VPTransformState &State) override
Generate a wide store or scatter.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPRecipeBase * getAsRecipe() override
Return a VPRecipeBase* to the current object.
VPValue * getStoredValue() const
Return the value stored by this recipe.
Definition VPlan.h:3941