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 "VectorizeOptions.h"
20#include "llvm/ADT/APFloat.h"
21#include "llvm/ADT/STLExtras.h"
24#include "llvm/ADT/Twine.h"
31#include "llvm/IR/BasicBlock.h"
32#include "llvm/IR/IRBuilder.h"
33#include "llvm/IR/Instruction.h"
35#include "llvm/IR/Intrinsics.h"
37#include "llvm/IR/Type.h"
38#include "llvm/IR/Value.h"
40#include "llvm/Support/Debug.h"
44#include <cassert>
45
46using namespace llvm;
47using namespace llvm::VPlanPatternMatch;
48
49#define LV_NAME "loop-vectorize"
50#define DEBUG_TYPE LV_NAME
51
52/// For call VPInstruction operands, return the operand index of the called
53/// function. The function is either the last operand (for unmasked calls) or
54/// the second-to-last operand (for masked calls).
56 unsigned NumOps = Operands.size();
57 auto *LastOp = dyn_cast<VPIRValue>(Operands[NumOps - 1]);
58 if (LastOp && isa<Function>(LastOp->getValue()))
59 return NumOps - 1;
61 "expected function operand");
62 return NumOps - 2;
63}
64
65/// For call VPInstruction operands, return the called function.
70
71/// Return the function attributes of the callee of \p VPI, which must be a
72/// call or intrinsic VPInstruction.
79
81 switch (getVPRecipeID()) {
82 case VPExpressionSC:
83 return cast<VPExpressionRecipe>(this)->mayReadOrWriteMemory();
84 case VPInstructionSC: {
85 auto *VPI = cast<VPInstruction>(this);
86 // Loads read from memory but don't write to memory.
87 if (VPI->getOpcode() == Instruction::Load ||
88 VPI->getOpcode() == VPInstruction::WideVectorLoad)
89 return false;
90 return VPI->opcodeMayReadOrWriteFromMemory();
91 }
92 case VPInterleaveEVLSC:
93 case VPInterleaveSC:
94 return cast<VPInterleaveBase>(this)->getNumStoreOperands() > 0;
95 case VPWidenStoreEVLSC:
96 case VPWidenStoreSC:
97 return true;
98 case VPReplicateSC:
99 return cast<Instruction>(getVPSingleValue()->getUnderlyingValue())
100 ->mayWriteToMemory();
101 case VPWidenCallSC:
102 return !cast<VPWidenCallRecipe>(this)
103 ->getCalledScalarFunction()
104 ->onlyReadsMemory();
105 case VPWidenMemIntrinsicSC:
106 case VPWidenIntrinsicSC:
107 return cast<VPWidenIntrinsicRecipe>(this)->mayWriteToMemory();
108 case VPActiveLaneMaskPHISC:
109 case VPCurrentIterationPHISC:
110 case VPBranchOnMaskSC:
111 case VPDerivedIVSC:
112 case VPFirstOrderRecurrencePHISC:
113 case VPReductionPHISC:
114 case VPScalarIVStepsSC:
115 case VPPredInstPHISC:
116 case VPExpandSCEVSC:
117 case VPConditionalInductionPHISC:
118 return false;
119 case VPBlendSC:
120 case VPReductionEVLSC:
121 case VPReductionSC:
122 case VPVectorPointerSC:
123 case VPVectorEndPointerSC:
124 case VPWidenCanonicalIVSC:
125 case VPWidenCastSC:
126 case VPWidenGEPSC:
127 case VPWidenIntOrFpInductionSC:
128 case VPWidenLoadEVLSC:
129 case VPWidenLoadSC:
130 case VPWidenPHISC:
131 case VPWidenPointerInductionSC:
132 case VPWidenSC: {
133 const Instruction *I =
134 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
135 (void)I;
136 assert((!I || !I->mayWriteToMemory()) &&
137 "underlying instruction may write to memory");
138 return false;
139 }
140 default:
141 return true;
142 }
143}
144
146 switch (getVPRecipeID()) {
147 case VPExpressionSC:
148 return cast<VPExpressionRecipe>(this)->mayReadOrWriteMemory();
149 case VPInstructionSC: {
150 auto *VPI = cast<VPInstruction>(this);
151 // Stores write to memory but don't read from memory.
152 if (VPI->getOpcode() == VPInstruction::WideVectorStore)
153 return false;
154 return VPI->opcodeMayReadOrWriteFromMemory();
155 }
156 case VPWidenLoadEVLSC:
157 case VPWidenLoadSC:
158 return true;
159 case VPReplicateSC:
160 return cast<Instruction>(getVPSingleValue()->getUnderlyingValue())
161 ->mayReadFromMemory();
162 case VPWidenCallSC:
163 return !cast<VPWidenCallRecipe>(this)
164 ->getCalledScalarFunction()
165 ->onlyWritesMemory();
166 case VPWidenMemIntrinsicSC:
167 case VPWidenIntrinsicSC:
168 return cast<VPWidenIntrinsicRecipe>(this)->mayReadFromMemory();
169 case VPActiveLaneMaskPHISC:
170 case VPBranchOnMaskSC:
171 case VPDerivedIVSC:
172 case VPCurrentIterationPHISC:
173 case VPFirstOrderRecurrencePHISC:
174 case VPReductionPHISC:
175 case VPPredInstPHISC:
176 case VPScalarIVStepsSC:
177 case VPWidenStoreEVLSC:
178 case VPWidenStoreSC:
179 case VPExpandSCEVSC:
180 case VPConditionalInductionPHISC:
181 return false;
182 case VPBlendSC:
183 case VPReductionEVLSC:
184 case VPReductionSC:
185 case VPVectorPointerSC:
186 case VPVectorEndPointerSC:
187 case VPWidenCanonicalIVSC:
188 case VPWidenCastSC:
189 case VPWidenGEPSC:
190 case VPWidenIntOrFpInductionSC:
191 case VPWidenPHISC:
192 case VPWidenPointerInductionSC:
193 case VPWidenSC: {
194 const Instruction *I =
195 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
196 (void)I;
197 assert((!I || !I->mayReadFromMemory()) &&
198 "underlying instruction may read from memory");
199 return false;
200 }
201 default:
202 // FIXME: Return false if the recipe represents an interleaved store.
203 return true;
204 }
205}
206
208 switch (getVPRecipeID()) {
209 case VPExpressionSC:
210 return cast<VPExpressionRecipe>(this)->mayHaveSideEffects();
211 case VPActiveLaneMaskPHISC:
212 case VPDerivedIVSC:
213 case VPCurrentIterationPHISC:
214 case VPFirstOrderRecurrencePHISC:
215 case VPReductionPHISC:
216 case VPPredInstPHISC:
217 case VPVectorEndPointerSC:
218 case VPExpandSCEVSC:
219 case VPConditionalInductionPHISC:
220 return false;
221 case VPInstructionSC: {
222 auto *VPI = cast<VPInstruction>(this);
223 if (VPI->getOpcode() == Instruction::Call ||
224 VPI->getOpcode() == VPInstruction::Intrinsic) {
225 AttributeSet CalleeFnAttrs = getCalleeFnAttrs(*VPI);
226 return mayWriteToMemory() ||
227 !VPI->hasFnAttr(Attribute::NoUnwind, CalleeFnAttrs) ||
228 !VPI->hasFnAttr(Attribute::WillReturn, CalleeFnAttrs);
229 }
230 return mayWriteToMemory() ||
231 VPI->getOpcode() == VPInstruction::BranchOnCount ||
232 VPI->getOpcode() == VPInstruction::BranchOnCond ||
233 VPI->getOpcode() == VPInstruction::BranchOnTwoConds;
234 }
235 case VPWidenCallSC: {
236 Function *Fn = cast<VPWidenCallRecipe>(this)->getCalledScalarFunction();
237 return mayWriteToMemory() || !Fn->doesNotThrow() || !Fn->willReturn();
238 }
239 case VPWidenMemIntrinsicSC:
240 case VPWidenIntrinsicSC:
241 return cast<VPWidenIntrinsicRecipe>(this)->mayHaveSideEffects();
242 case VPBlendSC:
243 case VPReductionEVLSC:
244 case VPReductionSC:
245 case VPScalarIVStepsSC:
246 case VPVectorPointerSC:
247 case VPWidenCanonicalIVSC:
248 case VPWidenCastSC:
249 case VPWidenGEPSC:
250 case VPWidenIntOrFpInductionSC:
251 case VPWidenPHISC:
252 case VPWidenPointerInductionSC:
253 case VPWidenSC: {
254 const Instruction *I =
255 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
256 (void)I;
257 assert((!I || !I->mayHaveSideEffects()) &&
258 "underlying instruction has side-effects");
259 return false;
260 }
261 case VPInterleaveEVLSC:
262 case VPInterleaveSC:
263 return mayWriteToMemory();
264 case VPWidenLoadEVLSC:
265 case VPWidenLoadSC:
266 case VPWidenStoreEVLSC:
267 case VPWidenStoreSC:
268 assert(
269 cast<VPWidenMemoryRecipe>(this)->getIngredient().mayHaveSideEffects() ==
271 "mayHaveSideffects result for ingredient differs from this "
272 "implementation");
273 return mayWriteToMemory();
274 case VPReplicateSC: {
275 auto *R = cast<VPReplicateRecipe>(this);
276 return R->getUnderlyingInstr()->mayHaveSideEffects();
277 }
278 default:
279 return true;
280 }
281}
282
284 switch (getVPRecipeID()) {
285 default:
286 return false;
287 case VPInstructionSC: {
288 unsigned Opcode = cast<VPInstruction>(this)->getOpcode();
289 if (Instruction::isCast(Opcode))
290 return true;
291
292 switch (Opcode) {
293 default:
294 return false;
295 case Instruction::Add:
296 case Instruction::Sub:
297 case Instruction::Mul:
298 case Instruction::GetElementPtr:
299 return true;
300 case Instruction::Call:
303 .hasAttribute(Attribute::Speculatable);
304 }
305 }
306 }
307}
308
310 insertBefore(InsertPos->getIterator());
311}
312
314 assert(!getParent() && "Recipe already in some VPBasicBlock");
315 assert(I.getNodeParent() && "Insertion position not in any VPBasicBlock");
316 I.getNodeParent()->insert(this, I);
317}
318
320 assert(InsertPos->getParent() &&
321 "Insertion position not in any VPBasicBlock");
322 insertBefore(std::next(InsertPos->getIterator()));
323}
324
326 assert(getParent() && "Recipe not in any VPBasicBlock");
327 getParent()->getRecipeList().remove(getIterator());
328 setParent(nullptr);
329}
330
332 assert(getParent() && "Recipe not in any VPBasicBlock");
333 return getParent()->getRecipeList().erase(getIterator());
334}
335
338 insertAfter(InsertPos);
339}
340
345
347 // Get the underlying instruction for the recipe, if there is one. It is used
348 // to
349 // * decide if cost computation should be skipped for this recipe,
350 // * apply forced target instruction cost.
351 Instruction *UI = nullptr;
352 if (auto *S = dyn_cast<VPSingleDefRecipe>(this))
353 UI = dyn_cast_or_null<Instruction>(S->getUnderlyingValue());
354 else if (auto *IG = dyn_cast<VPInterleaveBase>(this))
355 UI = IG->getInsertPos();
356 else if (auto *WidenMem = dyn_cast<VPWidenMemoryRecipe>(this))
357 UI = &WidenMem->getIngredient();
358
359 InstructionCost RecipeCost;
360 if (UI && Ctx.skipCostComputation(UI, VF.isVector())) {
361 RecipeCost = 0;
362 } else {
363 RecipeCost = computeCost(VF, Ctx);
364 if (Ctx.Opts.force_target_instruction_cost && RecipeCost.isValid()) {
365 // VPDerivedIVRecipe, VPScalarIVStepsRecipe and VPBranchOnMaskRecipe never
366 // have underlying instructions.
367 if (UI ||
369 this))
370 RecipeCost = InstructionCost(*Ctx.Opts.force_target_instruction_cost);
371 else
372 RecipeCost = InstructionCost(0);
373 }
374 }
375
376 LLVM_DEBUG({
377 dbgs() << "Cost of " << RecipeCost << " for VF " << VF << ": ";
378 if (VPSlotTracker *SlotTracker = Ctx.getSlotTracker()) {
379 print(dbgs(), "", *SlotTracker);
380 dbgs() << "\n";
381 } else {
382 dump();
383 }
384 });
385 return RecipeCost;
386}
387
389 VPCostContext &Ctx) const {
390 llvm_unreachable("subclasses should implement computeCost");
391}
392
394 return (getVPRecipeID() >= VPFirstPHISC && getVPRecipeID() <= VPLastPHISC) ||
396}
397
399 assert(OpType == Other.OpType && "OpType must match");
400 switch (OpType) {
401 case OperationType::OverflowingBinOp:
402 WrapFlags.HasNUW &= Other.WrapFlags.HasNUW;
403 WrapFlags.HasNSW &= Other.WrapFlags.HasNSW;
404 break;
405 case OperationType::Trunc:
406 TruncFlags.HasNUW &= Other.TruncFlags.HasNUW;
407 TruncFlags.HasNSW &= Other.TruncFlags.HasNSW;
408 break;
409 case OperationType::DisjointOp:
410 DisjointFlags.IsDisjoint &= Other.DisjointFlags.IsDisjoint;
411 break;
412 case OperationType::PossiblyExactOp:
413 ExactFlags.IsExact &= Other.ExactFlags.IsExact;
414 break;
415 case OperationType::GEPOp:
416 GEPFlagsStorage &= Other.GEPFlagsStorage;
417 break;
418 case OperationType::FPMathOp:
419 case OperationType::FCmp:
420 assert((OpType != OperationType::FCmp ||
421 FCmpFlags.CmpPredStorage == Other.FCmpFlags.CmpPredStorage) &&
422 "Cannot drop CmpPredicate");
423 getFMFsRef() = getFastMathFlagsOrNone() & Other.getFastMathFlagsOrNone();
424 break;
425 case OperationType::NonNegOp:
426 NonNegFlags.NonNeg &= Other.NonNegFlags.NonNeg;
427 break;
428 case OperationType::Cmp:
429 assert(CmpPredStorage == Other.CmpPredStorage &&
430 "Cannot drop CmpPredicate");
431 break;
432 case OperationType::ReductionOp:
433 assert(ReductionFlags.Kind == Other.ReductionFlags.Kind &&
434 "Cannot change RecurKind");
435 assert(ReductionFlags.IsOrdered == Other.ReductionFlags.IsOrdered &&
436 "Cannot change IsOrdered");
437 assert(ReductionFlags.IsInLoop == Other.ReductionFlags.IsInLoop &&
438 "Cannot change IsInLoop");
439 getFMFsRef() = getFastMathFlagsOrNone() & Other.getFastMathFlagsOrNone();
440 break;
441 case OperationType::Other:
442 break;
443 }
444}
445
447 if (!hasFastMathFlags())
448 return {};
449 const FastMathFlagsTy &F = getFMFsRef();
450 FastMathFlags Res;
451 Res.setAllowReassoc(F.AllowReassoc);
452 Res.setNoNaNs(F.NoNaNs);
453 Res.setNoInfs(F.NoInfs);
454 Res.setNoSignedZeros(F.NoSignedZeros);
455 Res.setAllowReciprocal(F.AllowReciprocal);
456 Res.setAllowContract(F.AllowContract);
457 Res.setApproxFunc(F.ApproxFunc);
458 return Res;
459}
460
461#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
463
464void VPRecipeBase::print(raw_ostream &O, const Twine &Indent,
465 VPSlotTracker &SlotTracker) const {
466 printRecipe(O, Indent, SlotTracker);
467 if (auto DL = getDebugLoc()) {
468 O << ", !dbg ";
469 DL.print(O);
470 }
471
472 if (auto *Metadata = dyn_cast<VPIRMetadata>(this))
474}
475#endif
476
477VPExpandSCEVRecipe::VPExpandSCEVRecipe(const SCEV *Expr, bool ExpandInIR)
478 : VPSingleDefRecipe(VPRecipeBase::VPExpandSCEVSC, {}, Expr->getType()),
479 Expr(Expr), ExpandInIR(ExpandInIR) {}
480
486
489 assert(!Operands.empty() &&
490 "zero-operand VPInstruction opcodes must pass explicit ResultTy");
491 // Assert operand \p Idx (if present and typed) has type \p ExpectedTy.
492 [[maybe_unused]] auto AssertOperandType = [&Operands](unsigned Idx,
493 Type *ExpectedTy) {
494 if (!ExpectedTy || Operands.size() <= Idx)
495 return;
496 [[maybe_unused]] Type *OpTy = Operands[Idx]->getScalarType();
497 assert((!OpTy || OpTy == ExpectedTy) &&
498 "different types inferred for different operands");
499 };
500
501 Type *Op0Ty = Operands[0]->getScalarType();
502 LLVMContext &Ctx = Op0Ty->getContext();
503 switch (Opcode) {
505 assert(Op0Ty->isIntegerTy(1) && "expected bool condition");
506 return Type::getVoidTy(Ctx);
508 assert(Op0Ty->isIntegerTy(1) && "expected bool condition");
509 AssertOperandType(1, IntegerType::get(Ctx, 1));
510 return Type::getVoidTy(Ctx);
512 assert(Op0Ty->isIntegerTy() && "expected integer operand");
513 AssertOperandType(1, Op0Ty);
514 return Type::getVoidTy(Ctx);
516 assert(Op0Ty->isIntegerTy() && "expected integer operand");
517 for (unsigned Idx = 1; Idx != Operands.size(); ++Idx)
518 AssertOperandType(Idx, Op0Ty);
519 return Op0Ty;
520 case Instruction::Switch:
521 for (unsigned Idx = 1; Idx != Operands.size(); ++Idx)
522 AssertOperandType(Idx, Op0Ty);
523 return Type::getVoidTy(Ctx);
525 case Instruction::Store:
526 return Type::getVoidTy(Ctx);
527 case Instruction::ICmp:
528 assert(Op0Ty->isIntOrPtrTy() && "expected integer or pointer operand");
529 AssertOperandType(1, Op0Ty);
530 return IntegerType::get(Ctx, 1);
531 case Instruction::FCmp:
532 assert(Op0Ty->isFloatingPointTy() && "expected floating-point operand");
533 AssertOperandType(1, Op0Ty);
534 return IntegerType::get(Ctx, 1);
537 assert(Op0Ty->isIntegerTy() && "expected integer operand");
538 AssertOperandType(1, Op0Ty);
539 return IntegerType::get(Ctx, 1);
541 assert(Op0Ty->isIntegerTy(1) && "expected bool operand");
542 return IntegerType::get(Ctx, 1);
545 assert(Op0Ty->isIntegerTy(1) && "expected bool operand");
546 AssertOperandType(1, Op0Ty);
547 return IntegerType::get(Ctx, 1);
549 assert(Op0Ty->isIntegerTy(1) && "expected bool operand");
550 for (unsigned Idx = 1; Idx != Operands.size(); ++Idx)
551 AssertOperandType(Idx, Op0Ty);
552 return IntegerType::get(Ctx, 1);
554 assert(Op0Ty->isIntegerTy() && "expected integer operand");
555 return IntegerType::get(Ctx, 32);
556 case Instruction::Select: {
557 assert((!Op0Ty || Op0Ty->isIntegerTy(1)) &&
558 "select condition must be bool");
559 Type *Op1Ty = Operands[1]->getScalarType();
560 AssertOperandType(2, Op1Ty);
561 return Op1Ty;
562 }
563 case Instruction::InsertElement:
564 // The inserted scalar (operand 1) must match the vector element type;
565 // operand 2 must be an integer.
566 AssertOperandType(1, Op0Ty);
567 assert(Operands[2]->getScalarType()->isIntegerTy() &&
568 "expected integer operand");
569 return Op0Ty;
571 // The start value and the identity value (operands 0 and 1) fill the same
572 // vector and must match in type; operand 2 is the scaling factor.
573 AssertOperandType(1, Op0Ty);
574 return Op0Ty;
576 assert(Operands.size() >= 2 && "ExtractLane requires a lane operand and "
577 "at least one source vector operand");
578 // Operand 0 is the lane index, used for integer arithmetic.
579 assert(Op0Ty->isIntegerTy() && "expected integer operand");
580 Type *Op1Ty = Operands[1]->getScalarType();
581 for (unsigned Idx = 2; Idx != Operands.size(); ++Idx)
582 AssertOperandType(Idx, Op1Ty);
583 return Op1Ty;
584 }
587 assert(Operands[0]->getScalarType()->isPointerTy() &&
588 "expected pointer operand");
589 assert(Operands[1]->getScalarType()->isIntegerTy() &&
590 "expected integer operand");
591 return Op0Ty;
592 case Instruction::ExtractValue:
600 case Instruction::Load:
601 case Instruction::Alloca:
602 llvm_unreachable("type must be passed explicitly");
603 case Instruction::Call:
607 "BuildVector operands must be valid vector elements");
608 break;
609 default:
610 if (Instruction::isCast(Opcode))
611 llvm_unreachable("type must be passed explicitly");
612 break;
613 }
614
615 // Opcodes that require all operands to share the same scalar type as the
616 // result.
617 bool AllOperandsSameType =
618 Instruction::isBinaryOp(Opcode) ||
622 Opcode);
623 if (AllOperandsSameType)
624 for (unsigned Idx = 1; Idx != Operands.size(); ++Idx)
625 AssertOperandType(Idx, Op0Ty);
626
627 return Op0Ty;
628}
629
632 unsigned Opcode = I->getOpcode();
633 if (Instruction::isCast(Opcode) ||
634 is_contained(ArrayRef<unsigned>({Instruction::Load, Instruction::Alloca}),
635 Opcode))
636 return I->getType();
638}
639
641 const VPIRFlags &Flags, const VPIRMetadata &MD,
642 DebugLoc DL, const Twine &Name, Type *ResultTy,
643 const VPIRAttributes &Attrs)
645 VPRecipeBase::VPInstructionSC, Operands,
646 ResultTy ? ResultTy
648 Flags, DL),
649 VPIRMetadata(MD), VPIRAttributes(Attrs), Opcode(Opcode),
650 Name(Name.str()) {
652 "Set flags not supported for the provided opcode");
654 "Opcode requires specific flags to be set");
658 "number of operands does not match opcode");
659}
660
662 if (Instruction::isUnaryOp(Opcode) || Instruction::isCast(Opcode))
663 return 1;
664
665 if (Instruction::isBinaryOp(Opcode))
666 return 2;
667
668 switch (Opcode) {
671 return 0;
672 case Instruction::Alloca:
673 case Instruction::Freeze:
674 case Instruction::Load:
687 return 1;
688 case Instruction::ICmp:
689 case Instruction::FCmp:
690 case Instruction::ExtractElement:
691 case Instruction::Store:
703 return 2;
704 case Instruction::InsertElement:
705 case Instruction::Select:
709 return 3;
711 return 4;
712 case Instruction::Call:
713 return getCalledFnOperandIndex(operands()) + 1;
714 case Instruction::GetElementPtr:
715 case Instruction::PHI:
716 case Instruction::Switch:
717 case Instruction::AtomicRMW:
718 case Instruction::AtomicCmpXchg:
719 case Instruction::ExtractValue:
720 case Instruction::Fence:
731 // Cannot determine the number of operands from the opcode.
732 return -1u;
733 }
734 llvm_unreachable("all cases should be handled above");
735}
736
738 return Opcode == VPInstruction::Unpack ||
740}
741
742bool VPInstruction::doesGenerateSingleScalar() const {
744 return true;
745 switch (Opcode) {
746 case Instruction::Freeze:
747 case Instruction::ICmp:
748 case Instruction::PHI:
749 case Instruction::Select:
758 return vputils::onlyFirstLaneUsed(this);
759 default:
761 }
762}
763
765 if (Kind == RecurKind::Sub)
766 return Instruction::Add;
767 if (Kind == RecurKind::FSub)
768 return Instruction::FAdd;
769 llvm_unreachable("RecurKind should be Sub/FSub.");
770}
771
772Value *VPInstruction::generate(VPTransformState &State,
773 bool GenerateSingleScalar) {
774 IRBuilderBase &Builder = State.Builder;
775
777 Value *A = State.get(getOperand(0), GenerateSingleScalar);
778 Value *B = State.get(getOperand(1), GenerateSingleScalar);
779 auto *Res =
780 Builder.CreateBinOp((Instruction::BinaryOps)getOpcode(), A, B, Name);
781 if (auto *I = dyn_cast<Instruction>(Res))
782 applyFlags(*I);
783 return Res;
784 }
786 Value *Op = State.get(getOperand(0), VPLane(0));
788 getScalarType());
789 if (auto *CastOp = dyn_cast<Instruction>(Res)) {
790 applyFlags(*CastOp);
791 applyMetadata(*CastOp);
792 }
793 return Res;
794 }
795
796 switch (getOpcode()) {
797 case VPInstruction::Not: {
798 Value *A = State.get(getOperand(0), GenerateSingleScalar);
799 return Builder.CreateNot(A, Name);
800 }
802 // TODO: Use IsSingleScalar to produce a scalar value.
803 Value *A = State.get(getOperand(0));
804 Value *B = State.get(getOperand(1));
805 return Builder.CreateLogicalAnd(A, B, Name);
806 }
808 // TODO: Use IsSingleScalar to produce a scalar value.
809 Value *A = State.get(getOperand(0));
810 Value *B = State.get(getOperand(1));
811 return Builder.CreateLogicalOr(A, B, Name);
812 }
813 case Instruction::ExtractElement: {
814 assert(GenerateSingleScalar &&
815 "Can only generate first lane for ExtractElement");
816 assert(State.VF.isVector() && "Only extract elements from vectors");
817 if (auto *Idx = dyn_cast<VPConstantInt>(getOperand(1)))
818 return State.get(getOperand(0), VPLane(Idx->getZExtValue()));
819 Value *Vec = State.get(getOperand(0));
820 Value *Idx = State.get(getOperand(1), /*NeedsSingleScalar=*/true);
821 return Builder.CreateExtractElement(Vec, Idx, Name);
822 }
823 case Instruction::InsertElement: {
824 assert(!GenerateSingleScalar &&
825 "Cannot generate scalar value for InsertElement");
826 assert(State.VF.isVector() && "Can only insert elements into vectors");
827 Value *Vec = State.get(getOperand(0), /*NeedsSingleScalar=*/false);
828 Value *Elt = State.get(getOperand(1), /*NeedsSingleScalar=*/true);
829 Value *Idx = State.get(getOperand(2), /*NeedsSingleScalar=*/true);
830 return Builder.CreateInsertElement(Vec, Elt, Idx, Name);
831 }
832 case Instruction::Freeze: {
833 Value *Op = State.get(getOperand(0), GenerateSingleScalar);
834 return Builder.CreateFreeze(Op, Name);
835 }
836 case Instruction::FCmp:
837 case Instruction::ICmp: {
838 Value *A = State.get(getOperand(0), GenerateSingleScalar);
839 Value *B = State.get(getOperand(1), GenerateSingleScalar);
840 return Builder.CreateCmp(getPredicate(), A, B, Name);
841 }
842 case Instruction::PHI: {
843 llvm_unreachable("should be handled by VPPhi::execute");
844 }
845 case Instruction::Select: {
846 Value *Cond =
847 State.get(getOperand(0), GenerateSingleScalar ||
849 Value *Op1 = State.get(getOperand(1), GenerateSingleScalar);
850 Value *Op2 = State.get(getOperand(2), GenerateSingleScalar);
851 Value *Sel =
852 Builder.CreateSelectFMF(Cond, Op1, Op2, getFastMathFlagsOrNone(), Name);
853 if (auto *I = dyn_cast<Instruction>(Sel))
855 return Sel;
856 }
859 // Can produce either a scalar value as a icmp of a phi, or a vector value,
860 // as a get.active.lane.mask intrinsic.
861 // Get first lane of vector induction variable.
862 Value *VIVElem0 = State.get(getOperand(0), VPLane(0));
863 // Get the original loop tripcount.
864 Value *ScalarTC = State.get(getOperand(1), VPLane(0));
865
866 uint64_t Multiplier =
868 ? cast<VPConstantInt>(getOperand(2))->getZExtValue()
869 : 1;
870
871 // If this part of the active lane mask is scalar, generate the CMP directly
872 // to avoid unnecessary extracts.
873 if (State.VF.isScalar() && Multiplier == 1)
874 return Builder.CreateCmp(CmpInst::Predicate::ICMP_ULT, VIVElem0, ScalarTC,
875 Name);
876
877 auto *PredTy = VectorType::get(Builder.getInt1Ty(), State.VF * Multiplier);
878 return Builder.CreateIntrinsic(Intrinsic::get_active_lane_mask,
879 {PredTy, ScalarTC->getType()},
880 {VIVElem0, ScalarTC}, nullptr, Name);
881 }
883 assert(GenerateSingleScalar &&
884 "Can only generate first lane for NumActiveLanes");
885 Value *Op = State.get(getOperand(0));
886 auto *VecTy = cast<VectorType>(Op->getType());
887 assert(VecTy->getScalarSizeInBits() == 1 &&
888 "NumActiveLanes only implemented for i1 vectors");
889
890 Type *Ty = getScalarType();
891 Value *ZExt = Builder.CreateCast(
892 Instruction::ZExt, Op, VectorType::get(Ty, VecTy->getElementCount()));
893 Value *NumActive =
894 Builder.CreateUnaryIntrinsic(Intrinsic::vector_reduce_add, ZExt);
895 return NumActive;
896 }
898 // Generate code to combine the previous and current values in vector v3.
899 //
900 // vector.ph:
901 // v_init = vector(..., ..., ..., a[-1])
902 // br vector.body
903 //
904 // vector.body
905 // i = phi [0, vector.ph], [i+4, vector.body]
906 // v1 = phi [v_init, vector.ph], [v2, vector.body]
907 // v2 = a[i, i+1, i+2, i+3];
908 // v3 = vector(v1(3), v2(0, 1, 2))
909
910 auto *V1 = State.get(getOperand(0));
911 if (!V1->getType()->isVectorTy())
912 return V1;
913 Value *V2 = State.get(getOperand(1));
914 return Builder.CreateVectorSpliceRight(V1, V2, 1, Name);
915 }
917 // TODO: Restructure this code with an explicit remainder loop, vsetvli can
918 // be outside of the main loop.
919 assert(GenerateSingleScalar &&
920 "Can only generate first lane for ExplicitVectorLength");
921 Value *AVL = State.get(getOperand(0), /*NeedsSingleScalar=*/true);
922 // Compute EVL
923 assert(AVL->getType()->isIntegerTy() &&
924 "Requested vector length should be an integer.");
925
926 assert(State.VF.isScalable() && "Expected scalable vector factor.");
927 Value *VFArg = Builder.getInt32(State.VF.getKnownMinValue());
928
929 Value *EVL = Builder.CreateIntrinsic(
930 Builder.getInt32Ty(), Intrinsic::experimental_get_vector_length,
931 {AVL, VFArg, Builder.getTrue()});
932 return EVL;
933 }
935 assert(GenerateSingleScalar &&
936 "Can only generate first lane for BranchOnCond");
937 Value *Cond = State.get(getOperand(0), VPLane(0));
938 // Replace the temporary unreachable terminator with a new conditional
939 // branch, hooking it up to backward destination for latch blocks now, and
940 // to forward destination(s) later when they are created.
941 // Second successor may be backwards - iff it is already in VPBB2IRBB.
942 VPBasicBlock *SecondVPSucc =
943 cast<VPBasicBlock>(getParent()->getSuccessors()[1]);
944 BasicBlock *SecondIRSucc = State.CFG.VPBB2IRBB.lookup(SecondVPSucc);
945 BasicBlock *IRBB = State.CFG.VPBB2IRBB[getParent()];
946 auto *Br = Builder.CreateCondBr(Cond, IRBB, SecondIRSucc);
947 // First successor is always forward, reset it to nullptr.
948 Br->setSuccessor(0, nullptr);
950 applyMetadata(*Br);
951 return Br;
952 }
954 assert(!GenerateSingleScalar &&
955 "Cannot generate scalar value for Broadcast");
956 return Builder.CreateVectorSplat(
957 State.VF, State.get(getOperand(0), /*NeedsSingleScalar=*/true),
958 "broadcast");
959 }
961 assert(!GenerateSingleScalar &&
962 "Cannot generate scalar value for BuildVector");
963 Value *Res = PoisonValue::get(
965 for (const auto &[Idx, Op] : enumerate(operands()))
966 Res = Builder.CreateInsertElement(Res, State.get(Op, true),
967 Builder.getInt64(Idx));
968 return Res;
969 }
971 Type *ScalarTy = getScalarType();
972 auto *WideTy = VectorType::get(ScalarTy, State.VF * getNumOperands());
973 Value *Res = PoisonValue::get(WideTy);
974 for (const auto &[Idx, Op] : enumerate(operands()))
975 Res = Builder.CreateInsertVector(WideTy, Res, State.get(Op),
976 Idx * State.VF.getKnownMinValue());
977 return Res;
978 }
980 if (State.VF.isScalar())
981 return State.get(getOperand(0), true);
982 IRBuilderBase::FastMathFlagGuard FMFG(Builder);
984 // If this start vector is scaled then it should produce a vector with fewer
985 // elements than the VF.
986 ElementCount VF = State.VF.divideCoefficientBy(
987 cast<VPConstantInt>(getOperand(2))->getZExtValue());
988 auto *Iden = Builder.CreateVectorSplat(VF, State.get(getOperand(1), true));
989 return Builder.CreateInsertElement(Iden, State.get(getOperand(0), true),
990 Builder.getInt64(0));
991 }
993 assert(GenerateSingleScalar &&
994 "Can only generate first lane for ComputeReductionResult");
995 RecurKind RK = getRecurKind();
996 bool IsOrdered = isReductionOrdered();
997 bool IsInLoop = isReductionInLoop();
999 "FindIV should use min/max reduction kinds");
1000
1001 // The recipe may have multiple operands to be reduced together.
1002 unsigned NumOperandsToReduce = getNumOperands();
1003 SmallVector<Value *, 2> RdxParts(NumOperandsToReduce);
1004 for (unsigned Part = 0; Part < NumOperandsToReduce; ++Part)
1005 RdxParts[Part] = State.get(getOperand(Part), IsInLoop);
1006
1007 IRBuilderBase::FastMathFlagGuard FMFG(Builder);
1009
1010 // Reduce multiple operands into one.
1011 Value *ReducedPartRdx = RdxParts[0];
1012 if (IsOrdered) {
1013 ReducedPartRdx = RdxParts[NumOperandsToReduce - 1];
1014 } else {
1015 // Floating-point operations should have some FMF to enable the reduction.
1016 for (unsigned Part = 1; Part < NumOperandsToReduce; ++Part) {
1017 Value *RdxPart = RdxParts[Part];
1019 ReducedPartRdx = createMinMaxOp(Builder, RK, ReducedPartRdx, RdxPart);
1020 else {
1021 // For sub-recurrences, each part's reduction variable is already
1022 // negative, we need to do: reduce.add(-acc_uf0 + -acc_uf1)
1023 Instruction::BinaryOps Opcode =
1025 ? getSubRecurOpcode(RK)
1026 : (Instruction::BinaryOps)RecurrenceDescriptor::getOpcode(RK);
1027 ReducedPartRdx =
1028 Builder.CreateBinOp(Opcode, RdxPart, ReducedPartRdx, "bin.rdx");
1029 }
1030 }
1031 }
1032
1033 // Create the reduction after the loop. Note that inloop reductions create
1034 // the target reduction in the loop using a Reduction recipe.
1035 if (State.VF.isVector() && !IsInLoop) {
1036 // TODO: Support in-order reductions based on the recurrence descriptor.
1037 // All ops in the reduction inherit fast-math-flags from the recurrence
1038 // descriptor.
1039 ReducedPartRdx = createSimpleReduction(Builder, ReducedPartRdx, RK);
1040 }
1041
1042 return ReducedPartRdx;
1043 }
1046 assert(GenerateSingleScalar &&
1047 "Can only generate first lane for ExtractLane and "
1048 "ExtractPenultimateElement");
1049 unsigned Offset =
1051 Value *Res;
1052 if (State.VF.isVector()) {
1053 assert(Offset <= State.VF.getKnownMinValue() &&
1054 "invalid offset to extract from");
1055 // Extract lane VF - Offset from the operand.
1056 Res = State.get(getOperand(0), VPLane::getLaneFromEnd(State.VF, Offset));
1057 } else {
1058 // TODO: Remove ExtractLastLane for scalar VFs.
1059 assert(Offset <= 1 && "invalid offset to extract from");
1060 Res = State.get(getOperand(0));
1061 }
1062 if (isa<ExtractElementInst>(Res))
1063 Res->setName(Name);
1064 return Res;
1065 }
1066 case VPInstruction::PtrAdd: {
1067 assert(GenerateSingleScalar && "Can only generate first lane for PtrAdd");
1068 Value *Ptr = State.get(getOperand(0), VPLane(0));
1069 Value *Addend = State.get(getOperand(1), VPLane(0));
1070 // TODO: Require that offset matches index type in VPlan.
1071 Addend = Builder.CreateSExtOrTrunc(
1072 Addend, Builder.getDataLayout().getIndexType(Ptr->getType()));
1073 return Builder.CreatePtrAdd(Ptr, Addend, Name, getGEPNoWrapFlags());
1074 }
1076 assert(!GenerateSingleScalar &&
1077 "Cannot generate scalar value for WidePtrAdd");
1078 Value *Ptr =
1080 Value *Addend = State.get(getOperand(1));
1081 return Builder.CreatePtrAdd(Ptr, Addend, Name, getGEPNoWrapFlags());
1082 }
1083 case VPInstruction::AnyOf: {
1084 assert(GenerateSingleScalar && "Can only generate first lane for AnyOf");
1085 Value *Res = State.get(getOperand(0));
1086 for (VPValue *Op : drop_begin(operands()))
1087 Res = Builder.CreateOr(Res, State.get(Op));
1088 return State.VF.isScalar() ? Res : Builder.CreateOrReduce(Res);
1089 }
1091 assert(GenerateSingleScalar &&
1092 "Can only generate first lane for ExtractLane");
1093 assert(getNumOperands() != 2 && "ExtractLane from single source should be "
1094 "simplified to ExtractElement.");
1095 Value *LaneToExtract = State.get(getOperand(0), true);
1096 Type *IdxTy = getOperand(0)->getScalarType();
1097 Value *Res = nullptr;
1098 Value *RuntimeVF = getRuntimeVF(Builder, IdxTy, State.VF);
1099
1100 for (unsigned Idx = 1; Idx != getNumOperands(); ++Idx) {
1101 Value *VectorStart =
1102 Builder.CreateMul(RuntimeVF, ConstantInt::get(IdxTy, Idx - 1));
1103 Value *VectorIdx = Idx == 1
1104 ? LaneToExtract
1105 : Builder.CreateSub(LaneToExtract, VectorStart);
1106 Value *Ext = State.VF.isScalar()
1107 ? State.get(getOperand(Idx))
1108 : Builder.CreateExtractElement(
1109 State.get(getOperand(Idx)), VectorIdx);
1110 if (Res) {
1111 Value *Cmp = Builder.CreateICmpUGE(LaneToExtract, VectorStart);
1112 Res = Builder.CreateSelect(Cmp, Ext, Res);
1113 } else {
1114 Res = Ext;
1115 }
1116 }
1117 return Res;
1118 }
1120 assert(GenerateSingleScalar &&
1121 "Can only generate first lane for FirstActiveLane");
1122 Type *Ty = this->getScalarType();
1123 if (getNumOperands() == 1) {
1124 Value *Mask = State.get(getOperand(0));
1125 return Builder.CreateCountTrailingZeroElems(Ty, Mask,
1126 /*ZeroIsPoison=*/false, Name);
1127 }
1128 // If there are multiple operands, create a chain of selects to pick the
1129 // first operand with an active lane and add the number of lanes of the
1130 // preceding operands.
1131 Value *RuntimeVF = getRuntimeVF(Builder, Ty, State.VF);
1132 unsigned LastOpIdx = getNumOperands() - 1;
1133 Value *Res = nullptr;
1134 for (int Idx = LastOpIdx; Idx >= 0; --Idx) {
1135 Value *TrailingZeros =
1136 State.VF.isScalar()
1137 ? Builder.CreateZExt(
1138 Builder.CreateICmpEQ(State.get(getOperand(Idx)),
1139 Builder.getFalse()),
1140 Ty)
1142 Ty, State.get(getOperand(Idx)),
1143 /*ZeroIsPoison=*/false, Name);
1144 Value *Current = Builder.CreateAdd(
1145 Builder.CreateMul(RuntimeVF, ConstantInt::get(Ty, Idx)),
1146 TrailingZeros);
1147 if (Res) {
1148 Value *Cmp = Builder.CreateICmpNE(TrailingZeros, RuntimeVF);
1149 Res = Builder.CreateSelect(Cmp, Current, Res);
1150 } else {
1151 Res = Current;
1152 }
1153 }
1154
1155 return Res;
1156 }
1158 assert(GenerateSingleScalar &&
1159 "Can only generate first lane for ResumeForEpilogue");
1160 return State.get(getOperand(0), true);
1162 assert(!GenerateSingleScalar && "Cannot generate scalar value for Reverse");
1163 return Builder.CreateVectorReverse(State.get(getOperand(0)), "reverse");
1165 assert(GenerateSingleScalar &&
1166 "Can only generate first lane for ExtractLastActive");
1167 Value *Result = State.get(getOperand(0), /*NeedsSingleScalar=*/true);
1168 for (unsigned Idx = 1; Idx < getNumOperands(); Idx += 2) {
1169 Value *Data = State.get(getOperand(Idx));
1170 Value *Mask = State.get(getOperand(Idx + 1));
1171 Type *VTy = Data->getType();
1172
1173 if (State.VF.isScalar())
1174 Result = Builder.CreateSelect(Mask, Data, Result);
1175 else
1176 Result = Builder.CreateIntrinsic(
1177 Intrinsic::experimental_vector_extract_last_active, {VTy},
1178 {Data, Mask, Result});
1179 }
1180
1181 return Result;
1182 }
1184 assert(!GenerateSingleScalar &&
1185 "Cannot generate scalar value for ExtractVectorForPart");
1186 Value *Src = State.get(getOperand(0));
1187 Type *DstTy = VectorType::get(getScalarType(), State.VF);
1188 uint64_t Part = cast<VPConstantInt>(getOperand(1))->getZExtValue();
1189
1190 if (Src->getType() == DstTy)
1191 return Src;
1192
1193 return Builder.CreateExtractVector(
1194 DstTy, Src, Builder.getInt64(State.VF.getKnownMinValue() * Part), Name);
1195 }
1197 assert(!GenerateSingleScalar &&
1198 "Cannot generate scalar value for StepVector");
1199 return State.Builder.CreateStepVector(
1200 VectorType::get(getScalarType(), State.VF));
1202 assert(GenerateSingleScalar &&
1203 "Can only generate first lane for Intrinsic");
1204 SmallVector<Value *, 2> Args;
1205 for (VPValue *Op : drop_end(operands()))
1206 Args.push_back(State.get(Op, /*NeedsSingleScalar=*/true));
1207 return State.Builder.CreateIntrinsic(getScalarType(),
1208 vputils::getIntrinsicID(this), Args,
1209 /*FMFSource=*/nullptr, getName());
1210 }
1212 unsigned Multiplier = cast<VPConstantInt>(getOperand(0))->getZExtValue();
1213 auto *WideDataTy = VectorType::get(getScalarType(), State.VF * Multiplier);
1214
1215 Value *Addr = State.get(getOperand(1), /*IsScalar=*/true);
1216 Align Alignment = Align(cast<VPConstantInt>(getOperand(2))->getZExtValue());
1217 Instruction *WideLI;
1218 if (isMasked()) {
1219 Value *Mask = State.get(getMask());
1220 WideLI = Builder.CreateMaskedLoad(WideDataTy, Addr, Alignment, Mask);
1221 } else {
1222 WideLI = Builder.CreateAlignedLoad(WideDataTy, Addr, Alignment);
1223 }
1224 applyMetadata(*WideLI);
1225 return WideLI;
1226 }
1228 unsigned Multiplier = cast<VPConstantInt>(getOperand(0))->getZExtValue();
1229 Value *WideData = State.get(getOperand(3));
1230 assert(cast<VectorType>(WideData->getType())->getElementCount() ==
1231 State.VF * Multiplier &&
1232 "stored value does not match wide element count");
1233 (void)Multiplier;
1234
1235 Value *Addr = State.get(getOperand(1), /*IsScalar=*/true);
1236 Align Alignment = Align(cast<VPConstantInt>(getOperand(2))->getZExtValue());
1237 Instruction *WideSI;
1238 if (isMasked()) {
1239 Value *Mask = State.get(getMask());
1240 WideSI = Builder.CreateMaskedStore(WideData, Addr, Alignment, Mask);
1241 } else {
1242 WideSI = Builder.CreateAlignedStore(WideData, Addr, Alignment);
1243 }
1244 applyMetadata(*WideSI);
1245 return WideSI;
1246 }
1248 llvm_unreachable("Should have been lowered in VPlanPredicator");
1249 default:
1250 llvm_unreachable("Unsupported opcode for instruction");
1251 }
1252}
1253
1255 unsigned Opcode, ElementCount VF, VPCostContext &Ctx) const {
1256 Type *ScalarTy = this->getScalarType();
1257 Type *ResultTy = VF.isVector() ? toVectorTy(ScalarTy, VF) : ScalarTy;
1258 switch (Opcode) {
1259 case Instruction::FNeg:
1260 return Ctx.TTI.getArithmeticInstrCost(Opcode, ResultTy, Ctx.CostKind);
1261 case Instruction::UDiv:
1262 case Instruction::SDiv:
1263 case Instruction::SRem:
1264 case Instruction::URem:
1265 case Instruction::Add:
1266 case Instruction::FAdd:
1267 case Instruction::Sub:
1268 case Instruction::FSub:
1269 case Instruction::Mul:
1270 case Instruction::FMul:
1271 case Instruction::FDiv:
1272 case Instruction::FRem:
1273 case Instruction::Shl:
1274 case Instruction::LShr:
1275 case Instruction::AShr:
1276 case Instruction::And:
1277 case Instruction::Or:
1278 case Instruction::Xor: {
1279 // Certain instructions can be cheaper if they have a constant second
1280 // operand. One example of this are shifts on x86.
1281 VPValue *RHS = getOperand(1);
1282 TargetTransformInfo::OperandValueInfo RHSInfo = Ctx.getOperandInfo(RHS);
1283
1284 if (RHSInfo.Kind == TargetTransformInfo::OK_AnyValue &&
1287
1290 if (CtxI)
1291 Operands.append(CtxI->value_op_begin(), CtxI->value_op_end());
1292 return Ctx.TTI.getArithmeticInstrCost(
1293 Opcode, ResultTy, Ctx.CostKind,
1294 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
1295 RHSInfo, Operands, CtxI, &Ctx.TLI);
1296 }
1297 case Instruction::Freeze:
1298 // NOTE: The only way to ask for the cost is via getInstructionCost, which
1299 // requires the actual vector instruction. Instead, both here and in the
1300 // LoopVectorizationCostModel::getInstructionCost the costs mirror the
1301 // current behaviour in llvm/Analysis/TargetTransformInfoImpl.h to keep
1302 // them in sync.
1303 return TTI::TCC_Free;
1304 case Instruction::ExtractValue:
1305 return Ctx.TTI.getInsertExtractValueCost(Instruction::ExtractValue,
1306 Ctx.CostKind);
1307 case Instruction::ICmp:
1308 case Instruction::FCmp: {
1309 Type *ScalarOpTy = getOperand(0)->getScalarType();
1310 Type *OpTy = VF.isVector() ? toVectorTy(ScalarOpTy, VF) : ScalarOpTy;
1312 return Ctx.TTI.getCmpSelInstrCost(
1314 Ctx.CostKind, {TTI::OK_AnyValue, TTI::OP_None},
1315 {TTI::OK_AnyValue, TTI::OP_None}, CtxI);
1316 }
1317 case Instruction::BitCast: {
1318 Type *ScalarTy = this->getScalarType();
1319 if (ScalarTy->isPointerTy())
1320 return 0;
1321 [[fallthrough]];
1322 }
1323 case Instruction::SExt:
1324 case Instruction::ZExt:
1325 case Instruction::FPToUI:
1326 case Instruction::FPToSI:
1327 case Instruction::FPExt:
1328 case Instruction::PtrToInt:
1329 case Instruction::PtrToAddr:
1330 case Instruction::IntToPtr:
1331 case Instruction::SIToFP:
1332 case Instruction::UIToFP:
1333 case Instruction::Trunc:
1334 case Instruction::FPTrunc:
1335 case Instruction::AddrSpaceCast: {
1336 // Computes the CastContextHint from a recipe that may access memory.
1337 auto ComputeCCH = [&](const VPRecipeBase *R) -> TTI::CastContextHint {
1338 if (isa<VPInterleaveBase>(R))
1340 if (const auto *ReplicateRecipe = dyn_cast<VPReplicateRecipe>(R)) {
1341 // Only compute CCH for memory operations, matching the legacy model
1342 // which only considers loads/stores for cast context hints.
1343 auto *UI = cast<Instruction>(ReplicateRecipe->getUnderlyingValue());
1344 if (!isa<LoadInst, StoreInst>(UI))
1346 return ReplicateRecipe->isPredicated() ? TTI::CastContextHint::Masked
1348 }
1349 const auto *WidenMemoryRecipe = dyn_cast<VPWidenMemoryRecipe>(R);
1350 if (WidenMemoryRecipe == nullptr)
1352 if (VF.isScalar())
1354 if (!WidenMemoryRecipe->isConsecutive())
1356 if (WidenMemoryRecipe->isMasked())
1359 };
1360
1361 VPValue *Operand = getOperand(0);
1363 bool IsReverse = false;
1364 // For Trunc/FPTrunc, get the context from the only user.
1365 if (Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) {
1366 if (auto *Recipe = cast_or_null<VPRecipeBase>(getSingleUser())) {
1367 if (match(Recipe,
1371 IsReverse = true;
1373 Recipe->getVPSingleValue()->getSingleUser());
1374 }
1375 if (Recipe)
1376 CCH = ComputeCCH(Recipe);
1377 }
1378 }
1379 // For Z/Sext, get the context from the operand.
1380 else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt ||
1381 Opcode == Instruction::FPExt) {
1382 if (auto *Recipe = Operand->getDefiningRecipe()) {
1383 VPValue *ReverseOp;
1384 if (match(Recipe,
1385 m_CombineOr(m_Reverse(m_VPValue(ReverseOp)),
1387 m_VPValue(ReverseOp))))) {
1388 Recipe = ReverseOp->getDefiningRecipe();
1389 IsReverse = true;
1390 }
1391 if (Recipe)
1392 CCH = ComputeCCH(Recipe);
1393 }
1394 }
1395 if (IsReverse && CCH != TTI::CastContextHint::None)
1397
1398 auto *ScalarSrcTy = Operand->getScalarType();
1399 Type *SrcTy = VF.isVector() ? toVectorTy(ScalarSrcTy, VF) : ScalarSrcTy;
1400 // Arm TTI will use the underlying instruction to determine the cost.
1401 return Ctx.TTI.getCastInstrCost(
1402 Opcode, ResultTy, SrcTy, CCH, Ctx.CostKind,
1404 }
1405 case Instruction::Select: {
1407 bool IsScalarCond = getOperand(0)->isDefinedOutsideLoopRegions();
1408 Type *ScalarTy = this->getScalarType();
1409
1410 VPValue *Op0, *Op1;
1411 bool IsLogicalAnd =
1412 match(this, m_c_LogicalAnd(m_VPValue(Op0), m_VPValue(Op1)));
1413 bool IsLogicalOr =
1414 match(this, m_c_LogicalOr(m_VPValue(Op0), m_VPValue(Op1)));
1415 // Also match the inverted forms:
1416 // select x, false, y --> !x & y (still AND)
1417 // select x, y, true --> !x | y (still OR)
1418 IsLogicalAnd |=
1419 match(this, m_Select(m_VPValue(Op0), m_False(), m_VPValue(Op1)));
1420 IsLogicalOr |=
1421 match(this, m_Select(m_VPValue(Op0), m_VPValue(Op1), m_True()));
1422
1423 if (!IsScalarCond && ScalarTy->getScalarSizeInBits() == 1 &&
1424 (IsLogicalAnd || IsLogicalOr)) {
1425 // select x, y, false --> x & y
1426 // select x, true, y --> x | y
1427 const auto [Op1VK, Op1VP] = Ctx.getOperandInfo(Op0);
1428 const auto [Op2VK, Op2VP] = Ctx.getOperandInfo(Op1);
1429
1431 if (SI && all_of(operands(),
1432 [](VPValue *Op) { return Op->getUnderlyingValue(); }))
1433 append_range(Operands, SI->operands());
1434 return Ctx.TTI.getArithmeticInstrCost(
1435 IsLogicalOr ? Instruction::Or : Instruction::And, ResultTy,
1436 Ctx.CostKind, {Op1VK, Op1VP}, {Op2VK, Op2VP}, Operands, SI);
1437 }
1438
1439 Type *CondTy = getOperand(0)->getScalarType();
1440 if (!IsScalarCond && VF.isVector())
1441 CondTy = VectorType::get(CondTy, VF);
1442
1443 llvm::CmpPredicate Pred;
1444 if (!match(getOperand(0), m_Cmp(Pred, m_VPValue(), m_VPValue())))
1445 if (auto *CondIRV = dyn_cast<VPIRValue>(getOperand(0)))
1446 if (auto *Cmp = dyn_cast<CmpInst>(CondIRV->getValue()))
1447 Pred = Cmp->getPredicate();
1448 Type *VectorTy = toVectorTy(this->getScalarType(), VF);
1449 return Ctx.TTI.getCmpSelInstrCost(
1450 Instruction::Select, VectorTy, CondTy, Pred, Ctx.CostKind,
1451 {TTI::OK_AnyValue, TTI::OP_None}, {TTI::OK_AnyValue, TTI::OP_None}, SI);
1452 }
1453 }
1454 llvm_unreachable("called for unsupported opcode");
1455}
1456
1458 VPCostContext &Ctx) const {
1459 // NOTE: At the moment it seems only possible to expose this path for
1460 // the trunc, zext and sext opcodes.
1461 // TODO: Update VF arg to use onlyFirstLaneUsed once WidenCast is unified.
1463 // A scalar zext/trunc that only adjusts the width of an
1464 // ExplicitVectorLength to the canonical IV type is free: it feeds only
1465 // the IV increment and AVL decrement, which are modeled as free below.
1466 if (match(this, m_ZExtOrTrunc(m_EVL(m_VPValue()))))
1467 return 0;
1469 Ctx);
1470 }
1471
1473 if (!getUnderlyingValue() && getOpcode() != Instruction::FMul) {
1474 // TODO: Compute cost for VPInstructions without underlying values once
1475 // the legacy cost model has been retired.
1476 return 0;
1477 }
1478
1480 "Should only generate a vector value or single scalar, not scalars "
1481 "for all lanes.");
1483 getOpcode(),
1485 }
1486
1487 switch (getOpcode()) {
1488 case Instruction::Select: {
1490 match(getOperand(0), m_Cmp(Pred, m_VPValue(), m_VPValue()));
1491 auto *CondTy = getOperand(0)->getScalarType();
1492 auto *VecTy = getOperand(1)->getScalarType();
1493 if (!vputils::onlyFirstLaneUsed(this)) {
1494 CondTy = toVectorTy(CondTy, VF);
1495 VecTy = toVectorTy(VecTy, VF);
1496 }
1497 return Ctx.TTI.getCmpSelInstrCost(Instruction::Select, VecTy, CondTy, Pred,
1498 Ctx.CostKind);
1499 }
1500 case Instruction::ExtractElement:
1502 if (VF.isScalar()) {
1503 // ExtractLane with VF=1 takes care of handling extracting across multiple
1504 // parts.
1505 return 0;
1506 }
1507
1508 // Add on the cost of extracting the element.
1509 auto *VecTy = toVectorTy(getOperand(0)->getScalarType(), VF);
1510 return Ctx.TTI.getVectorInstrCost(Instruction::ExtractElement, VecTy,
1511 Ctx.CostKind);
1512 }
1513 case VPInstruction::AnyOf: {
1514 auto *VecTy = toVectorTy(this->getScalarType(), VF);
1515 return Ctx.TTI.getArithmeticReductionCost(
1516 Instruction::Or, cast<VectorType>(VecTy), std::nullopt, Ctx.CostKind);
1517 }
1519 Type *Ty = this->getScalarType();
1520 Type *ScalarTy = getOperand(0)->getScalarType();
1521 if (VF.isScalar())
1522 return Ctx.TTI.getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
1524 CmpInst::ICMP_EQ, Ctx.CostKind);
1525 // Calculate the cost of determining the lane index.
1526 auto *PredTy = toVectorTy(ScalarTy, VF);
1527 IntrinsicCostAttributes Attrs(Intrinsic::experimental_cttz_elts, Ty,
1528 {PredTy, Type::getInt1Ty(Ctx.LLVMCtx)});
1529 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1530 }
1532 Type *Ty = this->getScalarType();
1533 Type *ScalarTy = getOperand(0)->getScalarType();
1534 if (VF.isScalar())
1535 return Ctx.TTI.getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
1537 CmpInst::ICMP_EQ, Ctx.CostKind);
1538 // Calculate the cost of determining the lane index: NOT + cttz_elts + SUB.
1539 auto *PredTy = toVectorTy(ScalarTy, VF);
1540 IntrinsicCostAttributes Attrs(Intrinsic::experimental_cttz_elts, Ty,
1541 {PredTy, Type::getInt1Ty(Ctx.LLVMCtx)});
1542 InstructionCost Cost = Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1543 // Add cost of NOT operation on the predicate.
1544 Cost += Ctx.TTI.getArithmeticInstrCost(
1545 Instruction::Xor, PredTy, Ctx.CostKind,
1546 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
1547 {TargetTransformInfo::OK_UniformConstantValue,
1548 TargetTransformInfo::OP_None});
1549 // Add cost of SUB operation on the index.
1550 Cost += Ctx.TTI.getArithmeticInstrCost(Instruction::Sub, Ty, Ctx.CostKind);
1551 return Cost;
1552 }
1554 Type *ScalarTy = this->getScalarType();
1555 Type *VecTy = toVectorTy(ScalarTy, VF);
1556 Type *MaskTy = toVectorTy(Type::getInt1Ty(Ctx.LLVMCtx), VF);
1558 Intrinsic::experimental_vector_extract_last_active, ScalarTy,
1559 {VecTy, MaskTy, ScalarTy});
1560 return Ctx.TTI.getIntrinsicInstrCost(ICA, Ctx.CostKind);
1561 }
1563 assert(VF.isVector() && "Scalar FirstOrderRecurrenceSplice?");
1564 Type *VectorTy = toVectorTy(this->getScalarType(), VF);
1565 return Ctx.TTI.getShuffleCost(
1567 cast<VectorType>(VectorTy), Ctx.CostKind, {}, -1);
1568 }
1571 Type *ArgTy = getOperand(0)->getScalarType();
1572 uint64_t Multiplier =
1574 ? cast<VPConstantInt>(getOperand(2))->getZExtValue()
1575 : 1;
1576 Type *RetTy = toVectorTy(Type::getInt1Ty(Ctx.LLVMCtx), VF * Multiplier);
1577 IntrinsicCostAttributes Attrs(Intrinsic::get_active_lane_mask, RetTy,
1578 {ArgTy, ArgTy});
1579 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1580 }
1582 Type *Arg0Ty = getOperand(0)->getScalarType();
1583 Type *I32Ty = Type::getInt32Ty(Ctx.LLVMCtx);
1584 Type *I1Ty = Type::getInt1Ty(Ctx.LLVMCtx);
1585 IntrinsicCostAttributes Attrs(Intrinsic::experimental_get_vector_length,
1586 I32Ty, {Arg0Ty, I32Ty, I1Ty});
1587 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1588 }
1590 assert(VF.isVector() && "Reverse operation must be vector type");
1591 Type *EltTy = this->getScalarType();
1592 // Skip the reverse operation cost for the mask.
1593 // FIXME: Remove this once redundant mask reverse operations can be
1594 // eliminated by VPlanTransforms::cse before cost computation.
1595 if (EltTy->isIntegerTy(1))
1596 return 0;
1597 auto *VectorTy = cast<VectorType>(toVectorTy(EltTy, VF));
1598 return Ctx.TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy,
1599 VectorTy, Ctx.CostKind, /*Mask=*/{},
1600 /*Index=*/0);
1601 }
1603 // Add on the cost of extracting the element.
1604 auto *VecTy = toVectorTy(getOperand(0)->getScalarType(), VF);
1605 return Ctx.TTI.getIndexedVectorInstrCostFromEnd(Instruction::ExtractElement,
1606 VecTy, Ctx.CostKind, 0);
1607 }
1608 case VPInstruction::Not: {
1609 Type *ValTy = this->getScalarType();
1610 // InstCombine will fold `xor` to the conditional branch.
1611 if (auto *U = const_cast<VPUser *>(getSingleUser()))
1612 if (match(U, m_BranchOnCond(m_VPValue())))
1613 return 0;
1614 if (!vputils::onlyFirstLaneUsed(this))
1615 ValTy = toVectorTy(ValTy, VF);
1616 return Ctx.TTI.getArithmeticInstrCost(Instruction::Xor, ValTy,
1617 Ctx.CostKind);
1618 }
1620 Type *ElementTy = getOperand(0)->getScalarType();
1621 auto *MaskTy = cast<VectorType>(toVectorTy(ElementTy, VF));
1622 return Ctx.TTI.getExtendedReductionCost(
1623 Instruction::Add, /*IsUnsigned=*/true, getScalarType(), MaskTy,
1624 /*FMF=*/{}, Ctx.CostKind);
1625 }
1627 // If TC <= VF then this is just a branch.
1628 // FIXME: Removing the branch happens in simplifyBranchConditionForVFAndUF
1629 // where it checks TC <= VF * UF, but we don't know UF yet. This means in
1630 // some cases we get a cost that's too high due to counting a cmp that
1631 // later gets removed.
1632 // FIXME: The compare could also be removed if TC = M * vscale,
1633 // VF = N * vscale, and M <= N. Detecting that would require having the
1634 // trip count as a SCEV though.
1635 if (VPCostContext::executesAtMostOnce(*getParent()->getPlan(), VF))
1636 return 0;
1637 // Otherwise BranchOnCount generates ICmpEQ followed by a branch.
1638 Type *ValTy = getOperand(0)->getScalarType();
1639 return Ctx.TTI.getCmpSelInstrCost(Instruction::ICmp, ValTy,
1641 CmpInst::ICMP_EQ, Ctx.CostKind);
1642 }
1644 Type *Ty = getScalarType();
1646 for (const VPValue *Op : drop_end(operands()))
1647 ArgTys.push_back(Op->getScalarType());
1648 IntrinsicCostAttributes Attrs(vputils::getIntrinsicID(this), Ty, ArgTys);
1649 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1650 }
1652 // TODO: This isn't quite right since even if the step-vector is hoisted
1653 // out of the loop it has a non-zero cost in the middle block, etc.
1654 // Once the stepvector is correctly hoisted out of the vector loop by the
1655 // licm transform we can add the cost here so that it doesn't incorrectly
1656 // affect the choice of VF.
1657 return 0;
1659 // It isn't currently possible to expose cases where WideIVStep's cost is
1660 // queried.
1661 llvm_unreachable("Unhandled opcode");
1662 case Instruction::FCmp:
1663 case Instruction::ICmp:
1665 getOpcode(),
1668 if (VF == ElementCount::getScalable(1))
1670 [[fallthrough]];
1671 default:
1672 // TODO: Compute cost other VPInstructions once the legacy cost model has
1673 // been retired.
1675 "unexpected VPInstruction witht underlying value");
1676 return 0;
1677 }
1678}
1679
1692
1694 switch (getOpcode()) {
1695 case Instruction::Load:
1696 case Instruction::PHI:
1700 return true;
1701 default:
1703 }
1704}
1705
1707#ifndef NDEBUG
1708 Type *Ty = Op->getScalarType();
1709 switch (getOpcode()) {
1713 assert(Ty == getOperand(0)->getScalarType() &&
1714 "types of operand 0 and new operand must match");
1715 break;
1719 assert(Ty == getOperand(0)->getScalarType() &&
1720 "appended operand must match operand 0's scalar type");
1721 break;
1723 assert(Ty == getOperand(1)->getScalarType() &&
1724 "appended operand must match operand 1's scalar type");
1725 break;
1727 // The recipe is constructed with 3 operands (result, data, mask). Extra
1728 // operands beyond that are appended in (data, mask) pairs.
1729 constexpr unsigned NumInitialOperands = 3;
1730 assert(getNumOperands() >= NumInitialOperands &&
1731 "ExtractLastActive must have at least the initial 3 operands");
1732 bool IsMaskSlot = ((getNumOperands() - NumInitialOperands) & 1u) == 1u;
1733 assert((IsMaskSlot ? Ty->isIntegerTy(1)
1734 : Ty == getOperand(1)->getScalarType()) &&
1735 "ExtractLastActive expects alternating data/mask operands "
1736 "matching operand 1's type and i1, respectively");
1737 break;
1738 }
1739 default:
1740 llvm_unreachable("opcode does not support growing the operand list "
1741 "outside of construction");
1742 }
1743#endif
1745}
1746
1748 assert(!isAbstract() && "cannot execute this VPInstruction");
1749 IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder);
1751 "Set flags not supported for the provided opcode");
1753 "Opcode requires specific flags to be set");
1754 State.Builder.setFastMathFlags(getFastMathFlagsOrNone());
1755 bool GenerateSingleScalar = State.VF.isScalar() || doesGenerateSingleScalar();
1756 Value *GeneratedValue = generate(State, GenerateSingleScalar);
1757 if (!hasResult())
1758 return;
1759 assert(GeneratedValue && "generate must produce a value");
1760 assert(GeneratedValue->getType()->isVectorTy() == !GenerateSingleScalar &&
1761 "scalar value but not only first lane defined");
1762 State.set(this, GeneratedValue, GenerateSingleScalar);
1764 getOpcode() == Instruction::Freeze) {
1765 // FIXME: This is a workaround to enable reliable updates of the scalar loop
1766 // resume phis, and to let epilogue vectorization recover the frozen
1767 // reduction start from the main plan. Must be removed once epilogue
1768 // vectorization explicitly connects VPlans.
1769 setUnderlyingValue(GeneratedValue);
1770 }
1771}
1772
1776 return false;
1777 switch (getOpcode()) {
1778 case Instruction::ExtractValue:
1779 case Instruction::GetElementPtr:
1780 case Instruction::ExtractElement:
1781 case Instruction::InsertElement:
1782 case Instruction::Freeze:
1783 case Instruction::FCmp:
1784 case Instruction::ICmp:
1785 case Instruction::Select:
1786 case Instruction::PHI:
1813 case VPInstruction::Not:
1822 return false;
1824 case Instruction::Call:
1826 default:
1827 return true;
1828 }
1829}
1830
1832 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
1834 return vputils::onlyFirstLaneUsed(this);
1835
1836 switch (getOpcode()) {
1837 default:
1838 return false;
1839 case Instruction::ExtractElement:
1840 return Op == getOperand(1);
1841 case Instruction::InsertElement:
1842 return Op == getOperand(1) || Op == getOperand(2);
1844 return Op == getOperand(0);
1845 case Instruction::PHI:
1846 case Instruction::Load:
1859 return true;
1862 return Op == getOperand(0) || Op == getOperand(1) || Op == getOperand(2);
1866 return Op == getOperand(0);
1867 }
1868}
1869
1871 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
1873 return vputils::onlyFirstPartUsed(this);
1874
1875 switch (getOpcode()) {
1876 default:
1877 return false;
1878 case Instruction::FCmp:
1879 case Instruction::ICmp:
1880 case Instruction::Select:
1881 return vputils::onlyFirstPartUsed(this);
1886 return true;
1887 };
1888 llvm_unreachable("switch should return");
1889}
1890
1891#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1893 VPSlotTracker SlotTracker(getParent()->getPlan());
1895}
1896
1898 VPSlotTracker &SlotTracker) const {
1899 O << Indent << "EMIT" << (isSingleScalar() ? "-SCALAR" : "") << " ";
1900
1901 if (hasResult()) {
1903 O << " = ";
1904 }
1905
1906 switch (getOpcode()) {
1907 case VPInstruction::Not:
1908 O << "not";
1909 break;
1911 O << "active lane mask";
1912 break;
1914 O << "wide active lane mask";
1915 break;
1917 O << "wide vector load";
1918 break;
1920 O << "wide vector store";
1921 break;
1923 O << "concat-vectors";
1924 break;
1926 O << "incoming-alias-mask";
1927 break;
1929 O << "EXPLICIT-VECTOR-LENGTH";
1930 break;
1932 O << "first-order splice";
1933 break;
1935 O << "branch-on-cond";
1936 break;
1938 O << "branch-on-two-conds";
1939 break;
1941 O << "VF * Part +";
1942 break;
1944 O << "branch-on-count";
1945 break;
1947 O << "broadcast";
1948 break;
1950 O << "buildvector";
1951 break;
1953 O << "exiting-iv-value";
1954 break;
1956 O << "masked-cond";
1957 break;
1959 O << "extract-lane";
1960 break;
1962 O << "extract-last-lane";
1963 break;
1965 O << "extract-last-part";
1966 break;
1968 O << "extract-penultimate-element";
1969 break;
1971 O << "extract-vector-for-part";
1972 break;
1974 O << "compute-reduction-result";
1975 break;
1977 O << "logical-and";
1978 break;
1980 O << "logical-or";
1981 break;
1983 O << "ptradd";
1984 break;
1986 O << "wide-ptradd";
1987 break;
1989 O << "any-of";
1990 break;
1992 O << "first-active-lane";
1993 break;
1995 O << "last-active-lane";
1996 break;
1998 O << "reduction-start-vector";
1999 break;
2001 O << "resume-for-epilogue";
2002 break;
2004 O << "reverse";
2005 break;
2007 O << "unpack";
2008 break;
2010 O << "extract-last-active";
2011 break;
2013 O << "num-active-lanes";
2014 break;
2016 O << "wide-iv-step";
2017 break;
2019 O << "step-vector " << *getScalarType();
2020 break;
2022 case Instruction::Call: {
2023 O << "call";
2024 printFlags(O);
2025 printRetAttrs(O);
2026 O << *getScalarType() << " ";
2027 unsigned NumArgs;
2030 NumArgs = getNumOperands() - 1;
2031 } else {
2032 getCalledFunction(operands())->printAsOperand(O, /*PrintType=*/false);
2033 NumArgs = getCalledFnOperandIndex(operands());
2034 }
2035 O << "(";
2037 O, [&O, &SlotTracker, this](const auto &IndexedOp) {
2038 auto [Idx, Op] = IndexedOp;
2039 printParamAttrs(O, Idx);
2040 Op->printAsOperand(O, SlotTracker);
2041 });
2042 O << ")";
2043 printFnAttrs(O);
2044 if (VPValue *Mask = getMask()) {
2045 O << ", ";
2046 Mask->printAsOperand(O, SlotTracker);
2047 }
2048 return;
2049 }
2050 case Instruction::Load:
2051 O << "load";
2052 break;
2053 default:
2055 }
2056
2057 if (!operands_empty()) {
2058 printFlags(O);
2060 }
2062 O << " to " << *getScalarType();
2063}
2064#endif
2065
2066/// Shared execute logic for VPPhi and VPWidenPHIRecipe. Creates a PHI node,
2067/// adds incoming values, and stores the result in State. For header phis, only
2068/// the preheader incoming value is added; the backedge is fixed up later by
2069/// VPlan::execute().
2071 VPTransformState &State, bool IsScalar,
2072 const Twine &Name) {
2073 unsigned NumIncoming = VPBlockUtils::isHeader(R->getParent(), State.VPDT)
2074 ? 1
2075 : Phi.getNumIncoming();
2076 Value *FirstInc = State.get(Phi.getIncomingValue(0), IsScalar);
2077 PHINode *NewPhi = State.Builder.CreatePHI(FirstInc->getType(), 2, Name);
2078 NewPhi->addIncoming(FirstInc,
2079 State.CFG.VPBB2IRBB.at(Phi.getIncomingBlock(0)));
2080 for (unsigned Idx = 1; Idx != NumIncoming; ++Idx)
2081 NewPhi->addIncoming(State.get(Phi.getIncomingValue(Idx), IsScalar),
2082 State.CFG.VPBB2IRBB.at(Phi.getIncomingBlock(Idx)));
2083 State.set(R, NewPhi, IsScalar);
2084}
2085
2087 executePhiRecipe(this, *this, State, /*IsScalar=*/true, getName());
2088}
2089
2090#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2091void VPPhi::printRecipe(raw_ostream &O, const Twine &Indent,
2092 VPSlotTracker &SlotTracker) const {
2093 O << Indent << "EMIT" << (isSingleScalar() ? "-SCALAR" : "") << " ";
2095 O << " = phi";
2096 printFlags(O);
2098}
2099#endif
2100
2101VPIRInstruction *VPIRInstruction ::create(Instruction &I) {
2102 if (auto *Phi = dyn_cast<PHINode>(&I))
2103 return new VPIRPhi(*Phi);
2104 return new VPIRInstruction(I);
2105}
2106
2108 assert(!isa<VPIRPhi>(this) && getNumOperands() == 0 &&
2109 "PHINodes must be handled by VPIRPhi");
2110 // Advance the insert point after the wrapped IR instruction. This allows
2111 // interleaving VPIRInstructions and other recipes.
2112 State.Builder.SetInsertPoint(std::next(I.getIterator()));
2113}
2114
2116 VPCostContext &Ctx) const {
2117 // The recipe wraps an existing IR instruction on the border of VPlan's scope,
2118 // hence it does not contribute to the cost-modeling for the VPlan.
2119 return 0;
2120}
2121
2122#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2124 VPSlotTracker &SlotTracker) const {
2125 O << Indent << "IR " << I;
2126}
2127#endif
2128
2130 PHINode *Phi = &getIRPhi();
2131 for (const auto &[Idx, Op] : enumerate(operands())) {
2132 VPValue *ExitValue = Op;
2133 auto Lane = vputils::isSingleScalar(ExitValue)
2135 : VPLane::getLastLaneForVF(State.VF);
2136 VPBlockBase *Pred = getParent()->getPredecessors()[Idx];
2137 auto *PredVPBB = Pred->getExitingBasicBlock();
2138 BasicBlock *PredBB = State.CFG.VPBB2IRBB[PredVPBB];
2139 // Set insertion point in PredBB in case an extract needs to be generated.
2140 // TODO: Model extracts explicitly.
2141 State.Builder.SetInsertPoint(PredBB->getTerminator());
2142 Value *V = State.get(ExitValue, VPLane(Lane));
2143 // If there is no existing block for PredBB in the phi, add a new incoming
2144 // value. Otherwise update the existing incoming value for PredBB.
2145 if (Phi->getBasicBlockIndex(PredBB) == -1)
2146 Phi->addIncoming(V, PredBB);
2147 else
2148 Phi->setIncomingValueForBlock(PredBB, V);
2149 }
2150
2151 // Advance the insert point after the wrapped IR instruction. This allows
2152 // interleaving VPIRInstructions and other recipes.
2153 State.Builder.SetInsertPoint(std::next(Phi->getIterator()));
2154}
2155
2157 VPRecipeBase *R = const_cast<VPRecipeBase *>(getAsRecipe());
2158 assert(R->getNumOperands() == R->getParent()->getNumPredecessors() &&
2159 "Number of phi operands must match number of predecessors");
2160 unsigned Position = R->getParent()->getIndexForPredecessor(IncomingBlock);
2161 R->removeOperand(Position);
2162}
2163
2164VPValue *
2166 VPRecipeBase *R = const_cast<VPRecipeBase *>(getAsRecipe());
2167 return getIncomingValue(R->getParent()->getIndexForPredecessor(VPBB));
2168}
2169
2171 VPValue *V) const {
2172 VPRecipeBase *R = const_cast<VPRecipeBase *>(getAsRecipe());
2173 R->setOperand(R->getParent()->getIndexForPredecessor(VPBB), V);
2174}
2175
2176#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2178 VPSlotTracker &SlotTracker) const {
2180 O << "[ ";
2181 std::get<0>(Op)->printAsOperand(O, SlotTracker);
2182 O << ", ";
2183 std::get<1>(Op)->printAsOperand(O);
2184 O << " ]";
2185 });
2186}
2187#endif
2188
2189#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2191 VPSlotTracker &SlotTracker) const {
2193
2194 if (getNumOperands() != 0) {
2195 O << " (extra operand" << (getNumOperands() > 1 ? "s" : "") << ": ";
2197 [&O, &SlotTracker](auto Op) {
2198 std::get<0>(Op)->printAsOperand(O, SlotTracker);
2199 O << " from ";
2200 std::get<1>(Op)->printAsOperand(O);
2201 });
2202 O << ")";
2203 }
2204}
2205#endif
2206
2208 if (Metadata.empty())
2209 return;
2210 // Frequencies and estimated branch weights are VPlan-internal and must not
2211 // reach IR.
2212 unsigned ExecFreqKind = getMDKindID(ExecutionFrequencyMDName);
2213 unsigned EstProfKind = getMDKindID(EstimatedProfileMDName);
2214 for (const auto &[Kind, Node] : Metadata)
2215 if (Kind != ExecFreqKind && Kind != EstProfKind)
2216 I.setMetadata(Kind, Node);
2217}
2218
2219/// Returns the execution frequency recorded in \p Node.
2221 assert(Node->getNumOperands() <= 2 && "unexpected frequency node shape");
2222 uint64_t Freq =
2223 mdconst::extract<ConstantInt>(Node->getOperand(0))->getZExtValue();
2225 "frequency cannot exceed the one of an always executing block");
2226 return {BlockFrequency(Freq), Node->getNumOperands() == 2};
2227}
2228
2230 std::optional<VPExecutionFrequency> Freq, LLVMContext &Ctx) {
2231 // A recipe that always executes needs no annotation.
2232 if (!Freq || vputils::getExecutionProbability(Freq->Freq).isOne())
2233 return;
2235 ConstantInt::get(Type::getInt64Ty(Ctx), Freq->Freq.getFrequency()))};
2236 if (Freq->IsEstimated)
2238 setMetadata(Ctx.getMDKindID(ExecutionFrequencyMDName), MDNode::get(Ctx, Ops));
2239}
2240
2241std::optional<VPExecutionFrequency>
2243 if (MDNode *Node = getInternalMetadata(ExecutionFrequencyMDName))
2245 return std::nullopt;
2246}
2247
2249 if (Metadata.empty())
2250 return;
2251 unsigned ID = getMDKindID(ExecutionFrequencyMDName);
2252 erase_if(Metadata, [ID](const auto &P) { return P.first == ID; });
2253}
2254
2256 erase_if(Metadata,
2257 [&](const auto &MD) { return !is_contained(Other.Metadata, MD); });
2258}
2259
2260#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2262 const Module *M = SlotTracker.getModule();
2263 if (Metadata.empty() || !M)
2264 return;
2265
2266 ArrayRef<StringRef> MDNames = SlotTracker.getMDNames();
2267 O << " (";
2268 interleaveComma(Metadata, O, [&](const auto &KindNodePair) {
2269 auto [Kind, Node] = KindNodePair;
2270 assert(Kind < MDNames.size() && !MDNames[Kind].empty() &&
2271 "Unexpected unnamed metadata kind");
2272 O << "!" << MDNames[Kind] << " ";
2273 // Print the values of branch weights, which are more informative than the
2274 // ID of the metadata node holding them.
2275 SmallVector<uint32_t> Weights;
2276 bool IsEstimatedProfile = MDNames[Kind] == EstimatedProfileMDName;
2277 if ((Kind == LLVMContext::MD_prof || IsEstimatedProfile) &&
2278 extractBranchWeights(Node, Weights)) {
2279 if (IsEstimatedProfile)
2280 O << "estimated ";
2281 O << "{";
2282 interleaveComma(Weights, O);
2283 O << "}";
2284 } else if (MDNames[Kind] == ExecutionFrequencyMDName) {
2285 // Print the frequency together with the probability it corresponds to.
2286 auto [Freq, IsEstimated] = getExecutionFrequencyFromMD(Node);
2287 const fltSemantics &Sem = APFloat::IEEEdouble();
2288 uint64_t Full =
2290 APFloat Percent = APFloat(Sem, Freq.getFrequency()) * APFloat(Sem, 100) /
2291 APFloat(Sem, Full);
2292 SmallString<16> PercentStr;
2293 Percent.toString(PercentStr, /*FormatPrecision=*/4);
2294 O << Freq.getFrequency() << " (" << PercentStr << "%"
2295 << (IsEstimated ? ", estimated" : "") << ")";
2296 } else {
2297 SlotTracker.printMetadataAsOperand(O, Node);
2298 }
2299 });
2300 O << ")";
2301}
2302#endif
2303
2305 FunctionType *WideTy) {
2306 assert(Call.getOpcode() == Instruction::Call && "expected call");
2307 unsigned NumArgs = getCalledFnOperandIndex(Call.operands());
2308 assert(NumArgs <= WideTy->getNumParams() &&
2309 "widened call must take all scalar arguments");
2310 LLVMContext &Ctx = WideTy->getContext();
2311 AttributeList ScalarAttrs = Call.CallAttrs;
2312
2313 // Limit initial supported set of attributes to subset of poison-generating
2314 // ones that can be transferred to the widened return value and arguments.
2315 // TODO: Support additional attributes.
2316 static constexpr Attribute::AttrKind PropagatableAttrKinds[] = {
2317 Attribute::Alignment, Attribute::NonNull, Attribute::NoFPClass,
2318 Attribute::Range};
2319
2320 // Only keep allowed attributes (which do not trigger UB) and ones that are
2321 // compatible with the widened type Ty.
2322 auto Filter = [&](Type *Ty, AttributeSet AS) {
2323 AttributeMask Incompatible = AttributeFuncs::typeIncompatible(Ty, AS);
2324 AttrBuilder AB(Ctx);
2325 for (Attribute::AttrKind K : PropagatableAttrKinds)
2326 if (AS.hasAttribute(K) && !Incompatible.contains(K))
2327 AB.addAttribute(AS.getAttribute(K));
2328 return AttributeSet::get(Ctx, AB);
2329 };
2330
2331 AttributeSet RetAttrs =
2332 Filter(WideTy->getReturnType(), ScalarAttrs.getRetAttrs());
2333
2334 // For masked calls, the widened call also executes for lanes the scalar call
2335 // did not execute for. Masked variants ignore the inactive lanes of widened
2336 // arguments, but scalar (uniform or linear) arguments are shared by all
2337 // lanes, e.g. linear arguments pass the value of the first lane, which may
2338 // be inactive. Unmasked variants process all lanes.
2339 bool IsMaskedVariant = WideTy->getNumParams() > NumArgs;
2340 SmallVector<AttributeSet> ArgAttrs(WideTy->getNumParams());
2341 for (unsigned I = 0; I != NumArgs; ++I) {
2342 Type *WideArgTy = WideTy->getParamType(I);
2343 bool IsWidenedArg = WideArgTy != Call.getOperand(I)->getScalarType();
2344 if (Call.isMasked() && (!IsMaskedVariant || !IsWidenedArg))
2345 continue;
2346 ArgAttrs[I] = Filter(WideArgTy, ScalarAttrs.getParamAttrs(I));
2347 }
2348
2349 CallAttrs = AttributeList::get(Ctx, AttributeSet(), RetAttrs, ArgAttrs);
2350}
2351
2353 LLVMContext &Ctx) {
2354 CallAttrs =
2355 CallAttrs.intersectWith(Ctx, Other.CallAttrs).value_or(AttributeList());
2356}
2357
2358#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2360 AttributeSet RetAttrs = CallAttrs.getRetAttrs();
2361 if (RetAttrs.hasAttributes())
2362 O << RetAttrs.getAsString() << " ";
2363}
2364
2365void VPIRAttributes::printParamAttrs(raw_ostream &O, unsigned ArgIdx) const {
2366 AttributeSet PA = CallAttrs.getParamAttrs(ArgIdx);
2367 if (PA.hasAttributes())
2368 O << PA.getAsString() << " ";
2369}
2370
2372 AttributeSet FnAttrs = CallAttrs.getFnAttrs();
2373 if (FnAttrs.hasAttributes())
2374 O << " " << FnAttrs.getAsString();
2375}
2376#endif
2377
2379 assert(State.VF.isVector() && "not widening");
2380 assert(Variant != nullptr && "Can't create vector function.");
2381
2382 FunctionType *VFTy = Variant->getFunctionType();
2383 // Add return type if intrinsic is overloaded on it.
2385 for (const auto &I : enumerate(args())) {
2386 Value *Arg;
2387 // Some vectorized function variants may also take a scalar argument,
2388 // e.g. linear parameters for pointers. This needs to be the scalar value
2389 // from the start of the respective part when interleaving.
2390 if (!VFTy->getParamType(I.index())->isVectorTy())
2391 Arg = State.get(I.value(), VPLane(0));
2392 else
2393 Arg = State.get(I.value(), usesFirstLaneOnly(I.value()));
2394 Args.push_back(Arg);
2395 }
2396
2397 CallInst *V = State.Builder.CreateCall(Variant, Args);
2398 applyFlags(*V);
2399 applyMetadata(*V);
2400 applyAttrs(*V);
2401 V->setCallingConv(Variant->getCallingConv());
2402
2403 if (!V->getType()->isVoidTy())
2404 State.set(this, V);
2405}
2406
2408 VPCostContext &Ctx) const {
2409 assert(getVectorizedTypeVF(Variant->getReturnType()) == VF &&
2410 "Variant return type must match VF");
2411 return computeCallCost(Variant, Ctx);
2412}
2413
2415 VPCostContext &Ctx) {
2416 return Ctx.TTI.getCallInstrCost(nullptr, Variant->getReturnType(),
2417 Variant->getFunctionType()->params(),
2418 Ctx.CostKind);
2419}
2420
2422 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
2423 assert(Variant && "Variant not set");
2424 FunctionType *VFTy = Variant->getFunctionType();
2425 return all_of(enumerate(args()), [VFTy, &Op](const auto &Arg) {
2426 auto [Idx, V] = Arg;
2427 Type *ArgTy = VFTy->getParamType(Idx);
2428 return V != Op || ArgTy->isIntegerTy() || ArgTy->isFloatingPointTy() ||
2429 ArgTy->isPointerTy() || ArgTy->isByteTy();
2430 });
2431}
2432
2433#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2435 VPSlotTracker &SlotTracker) const {
2436 O << Indent << "WIDEN-CALL ";
2437
2438 Function *CalledFn = getCalledScalarFunction();
2439 if (CalledFn->getReturnType()->isVoidTy())
2440 O << "void ";
2441 else {
2443 O << " = ";
2444 }
2445
2446 O << "call";
2447 printFlags(O);
2448 printRetAttrs(O);
2449 O << "@" << CalledFn->getName() << "(";
2451 [&O, &SlotTracker, this](const auto &IndexedOp) {
2452 auto [Idx, Op] = IndexedOp;
2453 printParamAttrs(O, Idx);
2454 Op->printAsOperand(O, SlotTracker);
2455 });
2456 O << ")";
2457
2458 O << " (using library function";
2459 if (Variant->hasName())
2460 O << ": " << Variant->getName();
2461 O << ")";
2462}
2463#endif
2464
2466 assert(State.VF.isVector() && "not widening");
2467
2468 SmallVector<Type *, 2> TysForDecl;
2469 // Add return type if intrinsic is overloaded on it.
2470 if (isVectorIntrinsicWithOverloadTypeAtArg(VectorIntrinsicID, -1,
2471 State.TTI)) {
2472 Type *RetTy = toVectorizedTy(getScalarType(), State.VF);
2473 ArrayRef<Type *> ContainedTys = getContainedTypes(RetTy);
2474 for (auto [Idx, Ty] : enumerate(ContainedTys)) {
2476 Idx, State.TTI))
2477 TysForDecl.push_back(Ty);
2478 }
2479 }
2481 for (const auto &I : enumerate(operands())) {
2482 // Some intrinsics have a scalar argument - don't replace it with a
2483 // vector.
2484 Value *Arg;
2485 if (isVectorIntrinsicWithScalarOpAtArg(VectorIntrinsicID, I.index(),
2486 State.TTI))
2487 Arg = State.get(I.value(), VPLane(0));
2488 else
2489 Arg = State.get(I.value(), usesFirstLaneOnly(I.value()));
2490 if (isVectorIntrinsicWithOverloadTypeAtArg(VectorIntrinsicID, I.index(),
2491 State.TTI))
2492 TysForDecl.push_back(Arg->getType());
2493 Args.push_back(Arg);
2494 }
2495
2496 // Use vector version of the intrinsic.
2497 Module *M = State.Builder.getModule();
2498 Function *VectorF =
2499 Intrinsic::getOrInsertDeclaration(M, VectorIntrinsicID, TysForDecl);
2500 assert(VectorF &&
2501 "Can't retrieve vector intrinsic or vector-predication intrinsics.");
2502
2503 CallInst *V = State.Builder.CreateCall(VectorF, Args);
2504
2505 applyFlags(*V);
2506 applyMetadata(*V);
2507
2508 return V;
2509}
2510
2512 CallInst *V = createVectorCall(State);
2513 if (!V->getType()->isVoidTy())
2514 State.set(this, V);
2515}
2516
2519 const VPRecipeWithIRFlags &R, ElementCount VF, VPCostContext &Ctx) {
2520 Type *ScalarRetTy = R.getScalarType();
2521 // Skip the reverse operation cost for the mask.
2522 // FIXME: Remove this once redundant mask reverse operations can be eliminated
2523 // by VPlanTransforms::cse before cost computation.
2524 if (ID == Intrinsic::experimental_vp_reverse && ScalarRetTy->isIntegerTy(1))
2525 return InstructionCost(0);
2526
2527 // Some backends analyze intrinsic arguments to determine cost. Use the
2528 // underlying value for the operand if it has one. Otherwise try to use the
2529 // operand of the underlying call instruction, if there is one. Otherwise
2530 // clear Arguments.
2531 // TODO: Rework TTI interface to be independent of concrete IR values.
2533 for (const auto &[Idx, Op] : enumerate(Operands)) {
2534 auto *V = Op->getUnderlyingValue();
2535 if (!V) {
2536 if (auto *UI = dyn_cast_or_null<CallBase>(R.getUnderlyingValue())) {
2537 Arguments.push_back(UI->getArgOperand(Idx));
2538 continue;
2539 }
2540 Arguments.clear();
2541 break;
2542 }
2543 Arguments.push_back(V);
2544 }
2545
2546 Type *RetTy = VF.isVector() ? toVectorizedTy(ScalarRetTy, VF) : ScalarRetTy;
2547 SmallVector<Type *> ParamTys =
2548 map_to_vector(Operands, [&](const VPValue *Op) {
2549 return toVectorTy(Op->getScalarType(), VF);
2550 });
2551
2553 for (const VPValue *Op : Operands)
2554 if (isa<VPWidenRecipe>(Op) &&
2557 break;
2558 }
2559
2560 // TODO: Rework TTI interface to avoid reliance on underlying IntrinsicInst.
2561 IntrinsicCostAttributes CostAttrs(
2562 ID, RetTy, Arguments, ParamTys, R.getFastMathFlagsOrNone(),
2563 dyn_cast_or_null<IntrinsicInst>(R.getUnderlyingValue()),
2565 return Ctx.TTI.getIntrinsicInstrCost(CostAttrs, Ctx.CostKind);
2566}
2567
2569 VPCostContext &Ctx) const {
2570 return computeCallCost(VectorIntrinsicID, operands(), *this, VF, Ctx);
2571}
2572
2574 return Intrinsic::getBaseName(VectorIntrinsicID);
2575}
2576
2578 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
2579 return all_of(enumerate(operands()), [this, &Op](const auto &X) {
2580 auto [Idx, V] = X;
2582 Idx, nullptr);
2583 });
2584}
2585
2586#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2588 VPSlotTracker &SlotTracker) const {
2589 O << Indent << "WIDEN-INTRINSIC ";
2590 if (getScalarType()->isVoidTy()) {
2591 O << "void ";
2592 } else {
2594 O << " = ";
2595 }
2596
2597 O << "call";
2598 printFlags(O);
2599 O << getIntrinsicName() << "(";
2601 O << ")";
2602}
2603#endif
2604
2606 CallInst *MemI = createVectorCall(State);
2608 MemI->getContext(), Alignment));
2609 if (!MemI->getType()->isVoidTy())
2610 State.set(this, MemI);
2611}
2612
2615 assert(MaskPos && "Expected a memory intrinsic with a valid mask position");
2616 return getOperand(*MaskPos);
2617}
2618
2621 assert(PtrPos && "Expected a memory intrinsic with a valid pointer position");
2622 return *PtrPos;
2623}
2624
2626 Type *DataTy;
2628 DataTy = getOperand(*DataPos)->getScalarType();
2629 else
2630 DataTy = getScalarType();
2631 assert(!DataTy->isVoidTy() && "Expected a non-void data type");
2632 return toVectorTy(DataTy, VF);
2633}
2634
2636 Intrinsic::ID IID, Type *Ty, bool IsMasked, Align Alignment,
2637 VPCostContext &Ctx) {
2638 return Ctx.TTI.getMemIntrinsicInstrCost(
2639 MemIntrinsicCostAttributes(IID, Ty, /*Ptr=*/nullptr, IsMasked, Alignment),
2640 Ctx.CostKind);
2641}
2642
2649
2651 IRBuilderBase &Builder = State.Builder;
2652
2653 Value *Address = State.get(getOperand(0));
2654 Value *IncAmt = State.get(getOperand(1), /*NeedsSingleScalar=*/true);
2655 VectorType *VTy = cast<VectorType>(Address->getType());
2656
2657 // The histogram intrinsic requires a mask even if the recipe doesn't;
2658 // if the mask operand was omitted then all lanes should be executed and
2659 // we just need to synthesize an all-true mask.
2660 Value *Mask = nullptr;
2661 if (VPValue *VPMask = getMask())
2662 Mask = State.get(VPMask);
2663 else
2664 Mask =
2665 Builder.CreateVectorSplat(VTy->getElementCount(), Builder.getInt1(1));
2666
2667 // If this is a subtract, we want to invert the increment amount and use
2668 // the histogram_add intrinsic.
2669 if (mustNegateIncrement())
2670 IncAmt = Builder.CreateNeg(IncAmt);
2671
2672 Instruction *HistogramInst = State.Builder.CreateIntrinsicWithoutFolding(
2673 getHistogramIntrinsicID(), {VTy, IncAmt->getType()},
2674 {Address, IncAmt, Mask});
2675 applyMetadata(*HistogramInst);
2676}
2677
2678Intrinsic::ID VPHistogramRecipe::getHistogramIntrinsicID() const {
2679 switch (UpdateKind) {
2682 return Intrinsic::experimental_vector_histogram_add;
2684 return Intrinsic::experimental_vector_histogram_uadd_sat;
2686 return Intrinsic::experimental_vector_histogram_umax;
2688 return Intrinsic::experimental_vector_histogram_umin;
2689 }
2690 llvm_unreachable("Unknown HistogramUpdateKind");
2691}
2692
2694 VPCostContext &Ctx) const {
2695 // FIXME: Take the gather and scatter into account as well. For now we're
2696 // generating the same cost as the fallback path, but we'll likely
2697 // need to create a new TTI method for determining the cost, including
2698 // whether we can use base + vec-of-smaller-indices or just
2699 // vec-of-pointers.
2700 assert(VF.isVector() && "Invalid VF for histogram cost");
2701 Type *AddressTy = getOperand(0)->getScalarType();
2702 VPValue *IncAmt = getOperand(1);
2703 Type *IncTy = IncAmt->getScalarType();
2704 VectorType *VTy = VectorType::get(IncTy, VF);
2705
2706 // For umin/umax, there's no multiplication — the increment value is compared
2707 // directly. For add/sub/uadd.sat, assume that a non-constant update value
2708 // (or a constant != 1) requires a multiply.
2710 if (!match(IncAmt, m_One()) && UpdateKind != HistogramUpdateKind::UMax &&
2711 UpdateKind != HistogramUpdateKind::UMin)
2712 MulCost =
2713 Ctx.TTI.getArithmeticInstrCost(Instruction::Mul, VTy, Ctx.CostKind);
2714
2715 // Find the cost of the histogram operation itself.
2716 Type *PtrTy = VectorType::get(AddressTy, VF);
2717 Type *MaskTy = VectorType::get(Type::getInt1Ty(Ctx.LLVMCtx), VF);
2718 IntrinsicCostAttributes ICA(getHistogramIntrinsicID(),
2719 Type::getVoidTy(Ctx.LLVMCtx),
2720 {PtrTy, IncTy, MaskTy});
2721
2722 // The histogram intrinsic's TTI cost already includes the update operation
2723 // (load + update + store), so no separate UpdateCost is needed.
2724 return Ctx.TTI.getIntrinsicInstrCost(ICA, Ctx.CostKind) + MulCost;
2725}
2726
2727#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2729 VPSlotTracker &SlotTracker) const {
2730 O << Indent << "WIDEN-HISTOGRAM buckets: ";
2732
2733 switch (UpdateKind) {
2735 O << ", inc: ";
2736 break;
2738 O << ", dec: ";
2739 break;
2741 O << ", saturated inc: ";
2742 break;
2744 O << ", max: ";
2745 break;
2747 O << ", min: ";
2748 break;
2749 }
2751
2752 if (VPValue *Mask = getMask()) {
2753 O << ", mask: ";
2754 Mask->printAsOperand(O, SlotTracker);
2755 }
2756}
2757#endif
2758
2759VPIRFlags::FastMathFlagsTy::FastMathFlagsTy(const FastMathFlags &FMF) {
2760 AllowReassoc = FMF.allowReassoc();
2761 NoNaNs = FMF.noNaNs();
2762 NoInfs = FMF.noInfs();
2763 NoSignedZeros = FMF.noSignedZeros();
2764 AllowReciprocal = FMF.allowReciprocal();
2765 AllowContract = FMF.allowContract();
2766 ApproxFunc = FMF.approxFunc();
2767}
2768
2769VPIRFlags VPIRFlags::getDefaultFlags(unsigned Opcode, Type *ResultTy) {
2770 switch (Opcode) {
2771 case Instruction::Add:
2772 case Instruction::Sub:
2773 case Instruction::Mul:
2774 case Instruction::Shl:
2776 return WrapFlagsTy(false, false);
2777 case Instruction::Trunc:
2778 return TruncFlagsTy(false, false);
2779 case Instruction::Or:
2780 return DisjointFlagsTy(false);
2781 case Instruction::AShr:
2782 case Instruction::LShr:
2783 case Instruction::UDiv:
2784 case Instruction::SDiv:
2785 return ExactFlagsTy(false);
2786 case Instruction::GetElementPtr:
2789 return GEPNoWrapFlags::none();
2790 case Instruction::ZExt:
2791 case Instruction::UIToFP:
2792 return NonNegFlagsTy(false);
2793 case Instruction::FAdd:
2794 case Instruction::FSub:
2795 case Instruction::FMul:
2796 case Instruction::FDiv:
2797 case Instruction::FRem:
2798 case Instruction::FNeg:
2799 case Instruction::FPExt:
2800 case Instruction::FPTrunc:
2801 return FastMathFlags();
2802 case Instruction::Select:
2803 case Instruction::PHI:
2804 case Instruction::Call:
2805 // Selects, phis and calls only have fast-math flags if they have a
2806 // supported floating-point result type.
2808 return FastMathFlags();
2809 return VPIRFlags();
2810 case Instruction::ICmp:
2811 case Instruction::FCmp:
2813 llvm_unreachable("opcode requires explicit flags");
2814 default:
2815 return VPIRFlags();
2816 }
2817}
2818
2819#if !defined(NDEBUG)
2820bool VPIRFlags::flagsValidForOpcode(unsigned Opcode) const {
2821 switch (OpType) {
2822 case OperationType::OverflowingBinOp:
2823 return Opcode == Instruction::Add || Opcode == Instruction::Sub ||
2824 Opcode == Instruction::Mul || Opcode == Instruction::Shl ||
2825 Opcode == VPInstruction::VPInstruction::CanonicalIVIncrementForPart;
2826 case OperationType::Trunc:
2827 return Opcode == Instruction::Trunc;
2828 case OperationType::DisjointOp:
2829 return Opcode == Instruction::Or;
2830 case OperationType::PossiblyExactOp:
2831 return Opcode == Instruction::AShr || Opcode == Instruction::LShr ||
2832 Opcode == Instruction::UDiv || Opcode == Instruction::SDiv;
2833 case OperationType::GEPOp:
2834 return Opcode == Instruction::GetElementPtr ||
2835 Opcode == VPInstruction::PtrAdd ||
2836 Opcode == VPInstruction::WidePtrAdd;
2837 case OperationType::FPMathOp:
2838 return Opcode == Instruction::Call || Opcode == Instruction::FAdd ||
2839 Opcode == Instruction::FMul || Opcode == Instruction::FSub ||
2840 Opcode == Instruction::FNeg || Opcode == Instruction::FDiv ||
2841 Opcode == Instruction::FRem || Opcode == Instruction::FPExt ||
2842 Opcode == Instruction::FPTrunc || Opcode == Instruction::PHI ||
2843 Opcode == Instruction::Select || Opcode == Instruction::SIToFP ||
2844 Opcode == Instruction::UIToFP ||
2845 Opcode == VPInstruction::WideIVStep ||
2847 case OperationType::FCmp:
2848 return Opcode == Instruction::FCmp;
2849 case OperationType::NonNegOp:
2850 return Opcode == Instruction::ZExt || Opcode == Instruction::UIToFP;
2851 case OperationType::Cmp:
2852 return Opcode == Instruction::FCmp || Opcode == Instruction::ICmp;
2853 case OperationType::ReductionOp:
2855 case OperationType::Other:
2856 return true;
2857 }
2858 llvm_unreachable("Unknown OperationType enum");
2859}
2860
2862 Type *ResultTy) const {
2863 // Handle opcodes without default flags.
2864 if (Opcode == Instruction::ICmp)
2865 return OpType == OperationType::Cmp;
2866 if (Opcode == Instruction::FCmp)
2867 return OpType == OperationType::FCmp;
2869 return OpType == OperationType::ReductionOp;
2870
2871 OperationType Required = getDefaultFlags(Opcode, ResultTy).OpType;
2872 return Required == OperationType::Other || Required == OpType;
2873}
2874#endif
2875
2876#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2877static void printRecurrenceKind(raw_ostream &OS, const RecurKind &Kind) {
2878 switch (Kind) {
2879 case RecurKind::None:
2880 OS << "none";
2881 break;
2882 case RecurKind::Add:
2883 OS << "add";
2884 break;
2885 case RecurKind::Sub:
2886 OS << "sub";
2887 break;
2889 OS << "add-chain-with-subs";
2890 break;
2891 case RecurKind::Mul:
2892 OS << "mul";
2893 break;
2894 case RecurKind::Or:
2895 OS << "or";
2896 break;
2897 case RecurKind::And:
2898 OS << "and";
2899 break;
2900 case RecurKind::Xor:
2901 OS << "xor";
2902 break;
2903 case RecurKind::SMin:
2904 OS << "smin";
2905 break;
2906 case RecurKind::SMax:
2907 OS << "smax";
2908 break;
2909 case RecurKind::UMin:
2910 OS << "umin";
2911 break;
2912 case RecurKind::UMax:
2913 OS << "umax";
2914 break;
2915 case RecurKind::FAdd:
2916 OS << "fadd";
2917 break;
2919 OS << "fadd-chain-with-subs";
2920 break;
2921 case RecurKind::FSub:
2922 OS << "fsub";
2923 break;
2924 case RecurKind::FMul:
2925 OS << "fmul";
2926 break;
2927 case RecurKind::FMin:
2928 OS << "fmin";
2929 break;
2930 case RecurKind::FMax:
2931 OS << "fmax";
2932 break;
2933 case RecurKind::FMinNum:
2934 OS << "fminnum";
2935 break;
2936 case RecurKind::FMaxNum:
2937 OS << "fmaxnum";
2938 break;
2940 OS << "fminimum";
2941 break;
2943 OS << "fmaximum";
2944 break;
2946 OS << "fminimumnum";
2947 break;
2949 OS << "fmaximumnum";
2950 break;
2951 case RecurKind::FMulAdd:
2952 OS << "fmuladd";
2953 break;
2954 case RecurKind::AnyOf:
2955 OS << "any-of";
2956 break;
2957 case RecurKind::FindIV:
2958 OS << "find-iv";
2959 break;
2961 OS << "find-last";
2962 break;
2963 }
2964}
2965
2967 switch (OpType) {
2968 case OperationType::Cmp:
2970 break;
2971 case OperationType::FCmp:
2974 break;
2975 case OperationType::DisjointOp:
2976 if (DisjointFlags.IsDisjoint)
2977 O << " disjoint";
2978 break;
2979 case OperationType::PossiblyExactOp:
2980 if (ExactFlags.IsExact)
2981 O << " exact";
2982 break;
2983 case OperationType::OverflowingBinOp:
2984 if (WrapFlags.HasNUW)
2985 O << " nuw";
2986 if (WrapFlags.HasNSW)
2987 O << " nsw";
2988 break;
2989 case OperationType::Trunc:
2990 if (TruncFlags.HasNUW)
2991 O << " nuw";
2992 if (TruncFlags.HasNSW)
2993 O << " nsw";
2994 break;
2995 case OperationType::FPMathOp:
2997 break;
2998 case OperationType::GEPOp: {
3000 if (Flags.isInBounds())
3001 O << " inbounds";
3002 else if (Flags.hasNoUnsignedSignedWrap())
3003 O << " nusw";
3004 if (Flags.hasNoUnsignedWrap())
3005 O << " nuw";
3006 break;
3007 }
3008 case OperationType::NonNegOp:
3009 if (NonNegFlags.NonNeg)
3010 O << " nneg";
3011 break;
3012 case OperationType::ReductionOp: {
3013 O << " (";
3015 if (isReductionInLoop())
3016 O << ", in-loop";
3017 if (isReductionOrdered())
3018 O << ", ordered";
3019 O << ")";
3021 break;
3022 }
3023 case OperationType::Other:
3024 break;
3025 }
3026 O << " ";
3027}
3028#endif
3029
3031 auto &Builder = State.Builder;
3032 switch (Opcode) {
3033 case Instruction::Call:
3034 case Instruction::UncondBr:
3035 case Instruction::CondBr:
3036 case Instruction::PHI:
3037 case Instruction::GetElementPtr:
3038 llvm_unreachable("This instruction is handled by a different recipe.");
3039 case Instruction::UDiv:
3040 case Instruction::SDiv:
3041 case Instruction::SRem:
3042 case Instruction::URem:
3043 case Instruction::Add:
3044 case Instruction::FAdd:
3045 case Instruction::Sub:
3046 case Instruction::FSub:
3047 case Instruction::FNeg:
3048 case Instruction::Mul:
3049 case Instruction::FMul:
3050 case Instruction::FDiv:
3051 case Instruction::FRem:
3052 case Instruction::Shl:
3053 case Instruction::LShr:
3054 case Instruction::AShr:
3055 case Instruction::And:
3056 case Instruction::Or:
3057 case Instruction::Xor: {
3058 // Just widen unops and binops.
3060 for (VPValue *VPOp : operands())
3061 Ops.push_back(State.get(VPOp));
3062
3063 Value *V = Builder.CreateNAryOp(Opcode, Ops);
3064
3065 if (auto *VecOp = dyn_cast<Instruction>(V)) {
3066 applyFlags(*VecOp);
3067 applyMetadata(*VecOp);
3068 }
3069
3070 // Use this vector value for all users of the original instruction.
3071 State.set(this, V);
3072 break;
3073 }
3074 case Instruction::ExtractValue: {
3075 Value *Op = State.get(getOperand(0));
3076 Value *Extract =
3077 Builder.CreateExtractValue(Op, getExtractValueIndices(operands()));
3078 State.set(this, Extract);
3079 break;
3080 }
3081 case Instruction::Freeze: {
3082 Value *Op = State.get(getOperand(0));
3083 Value *Freeze = Builder.CreateFreeze(Op);
3084 State.set(this, Freeze);
3085 break;
3086 }
3087 case Instruction::ICmp:
3088 case Instruction::FCmp: {
3089 // Widen compares. Generate vector compares.
3090 bool FCmp = Opcode == Instruction::FCmp;
3091 Value *A = State.get(getOperand(0));
3092 Value *B = State.get(getOperand(1));
3093 Value *C = nullptr;
3094 if (FCmp) {
3095 C = Builder.CreateFCmp(getPredicate(), A, B);
3096 } else {
3097 C = Builder.CreateICmp(getPredicate(), A, B);
3098 }
3099 if (auto *I = dyn_cast<Instruction>(C)) {
3100 applyFlags(*I);
3101 applyMetadata(*I);
3102 }
3103 State.set(this, C);
3104 break;
3105 }
3106 case Instruction::Select: {
3107 VPValue *CondOp = getOperand(0);
3108 Value *Cond = State.get(CondOp, vputils::isSingleScalar(CondOp));
3109 Value *Op0 = State.get(getOperand(1));
3110 Value *Op1 = State.get(getOperand(2));
3111 Value *Sel = State.Builder.CreateSelect(Cond, Op0, Op1);
3112 State.set(this, Sel);
3113 if (auto *I = dyn_cast<Instruction>(Sel)) {
3115 applyFlags(*I);
3116 applyMetadata(*I);
3117 }
3118 break;
3119 }
3120 default:
3121 // This instruction is not vectorized by simple widening.
3122 LLVM_DEBUG(dbgs() << "LV: Found an unhandled opcode : "
3123 << Instruction::getOpcodeName(Opcode));
3124 llvm_unreachable("Unhandled instruction!");
3125 } // end of switch.
3126
3127#if !defined(NDEBUG)
3128 // Verify that VPlan type inference results agree with the type of the
3129 // generated values.
3130 assert(VectorType::get(this->getScalarType(), State.VF) ==
3131 State.get(this)->getType() &&
3132 "inferred type and type from generated instructions do not match");
3133#endif
3134}
3135
3137 VPCostContext &Ctx) const {
3138 switch (Opcode) {
3139 case Instruction::UDiv:
3140 case Instruction::SDiv:
3141 case Instruction::SRem:
3142 case Instruction::URem:
3143 // If the div/rem operation isn't safe to speculate and requires
3144 // predication, then the only way we can even create a vplan is to insert
3145 // a select on the second input operand to ensure we use the value of 1
3146 // for the inactive lanes. The select will be costed separately.
3147 case Instruction::FNeg:
3148 case Instruction::Add:
3149 case Instruction::FAdd:
3150 case Instruction::Sub:
3151 case Instruction::FSub:
3152 case Instruction::Mul:
3153 case Instruction::FMul:
3154 case Instruction::FDiv:
3155 case Instruction::FRem:
3156 case Instruction::Shl:
3157 case Instruction::LShr:
3158 case Instruction::AShr:
3159 case Instruction::And:
3160 case Instruction::Or:
3161 case Instruction::Xor:
3162 case Instruction::Freeze:
3163 case Instruction::ExtractValue:
3164 case Instruction::ICmp:
3165 case Instruction::FCmp:
3166 case Instruction::Select:
3167 return getCostForRecipeWithOpcode(getOpcode(), VF, Ctx);
3168 default:
3169 llvm_unreachable("Unsupported opcode for instruction");
3170 }
3171}
3172
3173#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3175 VPSlotTracker &SlotTracker) const {
3176 O << Indent << "WIDEN ";
3178 O << " = " << Instruction::getOpcodeName(Opcode);
3179 printFlags(O);
3181}
3182#endif
3183
3185 auto &Builder = State.Builder;
3186 /// Vectorize casts.
3187 assert(State.VF.isVector() && "Not vectorizing?");
3188 Type *DestTy = VectorType::get(getScalarType(), State.VF);
3189 VPValue *Op = getOperand(0);
3190 Value *A = State.get(Op);
3191 Value *Cast = Builder.CreateCast(Instruction::CastOps(Opcode), A, DestTy);
3192 State.set(this, Cast);
3193 if (auto *CastOp = dyn_cast<Instruction>(Cast)) {
3194 applyFlags(*CastOp);
3195 applyMetadata(*CastOp);
3196 }
3197}
3198
3203
3204#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3206 VPSlotTracker &SlotTracker) const {
3207 O << Indent << "WIDEN-CAST ";
3209 O << " = " << Instruction::getOpcodeName(Opcode);
3210 printFlags(O);
3212 O << " to " << *getScalarType();
3213}
3214#endif
3215
3217 VPCostContext &Ctx) const {
3218 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
3219}
3220
3221#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3223 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
3224 O << Indent;
3226 O << " = WIDEN-INDUCTION";
3227 printFlags(O);
3229
3230 if (isTruncated())
3231 O << " (truncated to " << *getScalarType() << ")";
3232}
3233#endif
3234
3236 // The step may be defined by a recipe in the preheader (e.g. if it requires
3237 // SCEV expansion), but for the canonical induction the step is required to be
3238 // 1, which is represented as live-in.
3239 return match(getStartValue(), m_ZeroInt()) &&
3240 match(getStepValue(), m_One()) &&
3241 getScalarType() == getRegion()->getCanonicalIVType();
3242}
3243
3246 VPCostContext &Ctx) const {
3247 // A widened induction generates a vector phi and increments it by the
3248 // splatted step each iteration.
3250 InstructionCost Cost = Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
3251 Type *StepTy = getScalarType();
3252 unsigned IncOpc = ID.getKind() == InductionDescriptor::IK_IntInduction
3253 ? Instruction::Add
3254 : ID.getInductionOpcode();
3255 assert(IncOpc != Instruction::BinaryOpsEnd &&
3256 "induction must have a valid increment opcode");
3257 return Cost + Ctx.TTI.getArithmeticInstrCost(IncOpc, toVectorTy(StepTy, VF),
3258 Ctx.CostKind);
3259}
3260
3261/// Returns the ConstantFP \p V wraps, or nullptr if it does not wrap one.
3262static const ConstantFP *getConstantFP(const VPValue *V) {
3263 auto *C = dyn_cast<VPConstant>(V);
3264 return C ? dyn_cast<ConstantFP>(C->getConstant()) : nullptr;
3265}
3266
3268 VPCostContext &Ctx) const {
3269 // The cost model for this is modelled on expandVPDerivedIV in
3270 // VPlanTransforms.cpp. In order to avoid overly pessimistic costs that can
3271 // negatively affect vectorization it takes into account any expected
3272 // simplifications that happen in simplifyRecipe.
3273 switch (getInductionKind()) {
3274 default:
3275 // TODO: Compute cost for remaining kinds.
3276 break;
3278 // There are currently no tests that expose a path where all lanes are
3279 // used, so it's better to bail out for now.
3280 if (!vputils::onlyFirstLaneUsed(this))
3281 break;
3282
3283 // Start off by assuming we need both mul and add, then refine this.
3284 bool NeedsMul = true, NeedsAdd = true, NeedsShl = false;
3285
3286 // If the start value is zero the add gets folded away.
3287 if (auto *StartC = dyn_cast<VPConstantInt>(getStartValue()))
3288 NeedsAdd = !StartC->isZero();
3289
3290 // For some values of step the arithmetic changes:
3291 // 1. A step of 1 requires no operation.
3292 // 2. A step of -1 requires a negate.
3293 // 3. A power-of-2 step will use a shl, instead of a mul.
3294 Type *StepTy = getStepValue()->getScalarType();
3296 if (auto *StepC = dyn_cast<VPConstantInt>(getStepValue())) {
3297 if (StepC->isOne())
3298 NeedsMul = false;
3299 else if (StepC->getAPInt().isAllOnes()) {
3300 // This will most likely end up as a negate in simplifyRecipe, and
3301 // the negate will be combined with the add to make a sub.
3302 // NOTE: This is perhaps an invalid assumption that the cost of an
3303 // 'add' is the same as a 'sub'.
3304 NeedsMul = false;
3305 NeedsAdd = true;
3306 } else if (StepC->getAPInt().isPowerOf2()) {
3307 // This will most likely end up as a shift-left in simplifyRecipe
3308 NeedsMul = false;
3309 NeedsShl = true;
3310 }
3311 }
3312
3313 // Add the cost of the conversion from index to step type if the index
3314 // will be used.
3315 Type *IndexTy = getIndex()->getScalarType();
3316 unsigned StepTySize = StepTy->getScalarSizeInBits();
3317 unsigned IndexTySize = IndexTy->getScalarSizeInBits();
3318 if ((NeedsAdd || NeedsMul || NeedsShl) && StepTySize != IndexTySize) {
3319 unsigned CastOpc =
3320 StepTySize < IndexTySize ? Instruction::Trunc : Instruction::ZExt;
3321 Cost += Ctx.TTI.getCastInstrCost(
3322 CastOpc, StepTy, IndexTy, TTI::CastContextHint::None, Ctx.CostKind);
3323 }
3324
3325 if (NeedsMul)
3326 Cost += Ctx.TTI.getArithmeticInstrCost(Instruction::Mul, StepTy,
3327 Ctx.CostKind);
3328 if (NeedsShl)
3329 Cost += Ctx.TTI.getArithmeticInstrCost(
3330 Instruction::Shl, StepTy, Ctx.CostKind,
3331 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
3332 {TargetTransformInfo::OK_UniformConstantValue,
3333 TargetTransformInfo::OP_None});
3334 if (NeedsAdd)
3335 Cost += Ctx.TTI.getArithmeticInstrCost(Instruction::Add, StepTy,
3336 Ctx.CostKind);
3337 return Cost;
3338 }
3340 // There are currently no tests that expose a path where all lanes are
3341 // used, so it's better to bail out for now.
3342 if (!vputils::onlyFirstLaneUsed(this))
3343 break;
3344
3345 // Unlike the integer case, converting the index to the FP step type is
3346 // unavoidable: the index is always the integer canonical IV, so this
3347 // cast is never folded away.
3348 Type *StepTy = getStepValue()->getScalarType();
3349 Type *IndexTy = getIndex()->getScalarType();
3351 Ctx.TTI.getCastInstrCost(Instruction::SIToFP, StepTy, IndexTy,
3352 TTI::CastContextHint::None, Ctx.CostKind);
3353
3354 // If the step is 1.0, the multiply is an exact identity and gets folded
3355 // away, independent of fast-math flags.
3356 const ConstantFP *StepC = getConstantFP(getStepValue());
3357 bool NeedsMul = !StepC || !StepC->isOne();
3358
3359 // "fadd -0.0, X" folds to X unconditionally, but "fadd 0.0, X" only folds
3360 // to X without nsz if X can be proven to never be -0.0, which we cannot, as
3361 // Step may be -0.0.
3362 // TODO: Consider fast-math flags when they are available in
3363 // VPDerivedIVRecipe.
3364 const ConstantFP *StartC = getConstantFP(getStartValue());
3365 bool AddFolds = getFPBinOp()->getOpcode() == Instruction::FAdd && StartC &&
3366 StartC->isZero() && (StartC->isNegZero() || !NeedsMul);
3367
3368 if (NeedsMul)
3369 Cost += Ctx.TTI.getArithmeticInstrCost(Instruction::FMul, StepTy,
3370 Ctx.CostKind);
3371 if (!AddFolds)
3372 Cost += Ctx.TTI.getArithmeticInstrCost(getFPBinOp()->getOpcode(), StepTy,
3373 Ctx.CostKind);
3374 return Cost;
3375 }
3376 }
3377
3378 return 0;
3379}
3380
3381#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3383 VPSlotTracker &SlotTracker) const {
3384 O << Indent;
3386 O << " = DERIVED-IV";
3387 printFlags(O);
3388 getStartValue()->printAsOperand(O, SlotTracker);
3389 O << " + ";
3390 getOperand(1)->printAsOperand(O, SlotTracker);
3391 O << " * ";
3392 getStepValue()->printAsOperand(O, SlotTracker);
3393}
3394#endif
3395
3399
3401 VPCostContext &Ctx) const {
3402 Type *BaseIVTy = getOperand(0)->getScalarType();
3403 assert((BaseIVTy->isIntegerTy() || BaseIVTy->isFloatingPointTy()) &&
3404 "VPScalarIVStepsRecipe is only created for integer and FP inductions");
3405
3406 // If only the first lane is used, then there won't be any code that remains
3407 // in the loop for the first unrolled part.
3409 return 0;
3410
3411 // If the vector body executes at most once, the canonical IV is a constant
3412 // and every lane's step folds away with it.
3413 if (VPCostContext::executesAtMostOnce(*getParent()->getPlan(), VF))
3414 return 0;
3415
3416 // Typically the operations are:
3417 // 1. Add the start index to each lane value.
3418 // 2. Multiply the start index by the step.
3419 // 3. Add the scaled start index to base IV.
3420 // Any code generated for 1 and 2 should be loop invariant and therefore
3421 // hoisted out of the loop. We only need to add on the cost of 3.
3423 if (BaseIVTy->isFloatingPointTy()) {
3424 // Unlike the integer case, the users of an FP induction cannot be re-based
3425 // on a common value, so each lane needs its own FAdd/FSub.
3426 assert(!VF.isScalable() &&
3427 "FP scalar steps for all lanes are only created for fixed VFs");
3428 Cost = Ctx.TTI.getArithmeticInstrCost(InductionOpcode, BaseIVTy,
3429 Ctx.CostKind) *
3430 (VF.getFixedValue() - 1);
3431 } else {
3432 // Given the users of VPScalarIVStepsRecipe tend to be scalarized GEPs, i.e.
3433 // %add1 = add i32 %iv, 0
3434 // %add2 = add i32 %iv, 1
3435 // %gep1 = getelementptr i8, ptr %p, i32 %add1
3436 // %gep2 = getelementptr i8, ptr %p, i32 %add2
3437 // it's very likely that these GEPs will all be rewritten to have a common
3438 // base such that what's left is just
3439 // %base_gep = getelementptr i8, ptr %p, i32 %iv
3440 // %gep1 = getelementptr i8, ptr %base_gep, i32 0
3441 // %gep2 = getelementptr i8, ptr %base_gep, i32 1
3442 // Therefore, in reality the cost is somewhere betwen 1*AddCost and
3443 // (NumLanes - 1) * AddCost. For now, assume the cost of a single add.
3444 Cost = Ctx.TTI.getArithmeticInstrCost(Instruction::Add, BaseIVTy,
3445 Ctx.CostKind);
3446 }
3447
3448 // If the steps are generated inside a replicate region, scale by execution
3449 // probability.
3450 const VPRegionBlock *Region = getRegion();
3451 if (Region && Region->isReplicator())
3452 Cost /= Ctx.getCostDivisor(
3453 Region->getEntryBranchOnMask()->getExecutionFrequency());
3454 return Cost;
3455}
3456
3458 // Fast-math-flags propagate from the original induction instruction.
3459 IRBuilder<>::FastMathFlagGuard FMFG(State.Builder);
3460 State.Builder.setFastMathFlags(getFastMathFlagsOrNone());
3461
3462 /// Compute scalar induction steps. \p ScalarIV is the scalar induction
3463 /// variable on which to base the steps, \p Step is the size of the step.
3464
3465 Value *BaseIV = State.get(getOperand(0), VPLane(0));
3466 Value *Step = State.get(getStepValue(), VPLane(0));
3467 IRBuilderBase &Builder = State.Builder;
3468
3469 // Ensure step has the same type as that of scalar IV.
3470 Type *BaseIVTy = BaseIV->getType()->getScalarType();
3471 assert(BaseIVTy == Step->getType() && "Types of BaseIV and Step must match!");
3472
3473 // We build scalar steps for both integer and floating-point induction
3474 // variables. Here, we determine the kind of arithmetic we will perform.
3477 if (BaseIVTy->isIntegerTy()) {
3478 AddOp = Instruction::Add;
3479 MulOp = Instruction::Mul;
3480 } else {
3481 AddOp = InductionOpcode;
3482 MulOp = Instruction::FMul;
3483 }
3484
3485 // Lanes other than the first have been materialized as separate
3486 // single-scalar recipes by replicateByVF, each with its own start index.
3487 assert((vputils::onlyFirstLaneUsed(this) || State.VF.isScalar()) &&
3488 "must have been replicated by VF");
3489 Value *StartIdx = getStartIndex() ? State.get(getStartIndex(), true)
3490 : Constant::getNullValue(BaseIVTy);
3491 auto *Mul = Builder.CreateBinOp(MulOp, StartIdx, Step);
3492 auto *Add = Builder.CreateBinOp(AddOp, BaseIV, Mul);
3493 State.set(this, Add, VPLane(0));
3494}
3495
3496#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3498 VPSlotTracker &SlotTracker) const {
3499 O << Indent;
3501 O << " = SCALAR-STEPS ";
3503}
3504#endif
3505
3507 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
3509}
3510
3512 assert(State.VF.isVector() && "not widening");
3513 auto Ops = map_to_vector(operands(), [&](VPValue *Op) {
3514 return State.get(Op, vputils::isSingleScalar(Op));
3515 });
3516 auto *GEP =
3517 State.Builder.CreateGEP(getSourceElementType(), Ops.front(),
3518 drop_begin(Ops), "wide.gep", getGEPNoWrapFlags());
3519 State.set(this, GEP, vputils::isSingleScalar(this));
3520}
3521
3522#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3524 VPSlotTracker &SlotTracker) const {
3525 O << Indent << "WIDEN-GEP ";
3527 O << " = getelementptr";
3528 printFlags(O);
3530}
3531#endif
3532
3534 assert(!getOffset() && "Unexpected offset operand");
3535 VPBuilder Builder(this);
3536 VPlan &Plan = *getParent()->getPlan();
3537 VPValue *VFVal = getVFValue();
3538 const DataLayout &DL = Plan.getDataLayout();
3539 Type *IndexTy = DL.getIndexType(this->getScalarType());
3540 VPValue *Stride =
3541 Plan.getConstantInt(IndexTy, getStride(), /*IsSigned=*/true);
3542 VPValue *VF =
3543 Builder.createScalarZExtOrTrunc(VFVal, IndexTy, DebugLoc::getUnknown());
3544
3545 // Offset for Part0 = Offset0 = Stride * (VF - 1).
3546 VPInstruction *VFMinusOne =
3547 Builder.createSub(VF, Plan.getConstantInt(IndexTy, 1u),
3548 DebugLoc::getUnknown(), "", {true, true});
3549 VPInstruction *Offset0 =
3550 Builder.createOverflowingOp(Instruction::Mul, {VFMinusOne, Stride});
3551
3552 // Offset for PartN = Offset0 + Part * Stride * VF.
3553 VPValue *PartxStride =
3554 Plan.getConstantInt(IndexTy, Part * getStride(), /*IsSigned=*/true);
3555 VPValue *Offset = Builder.createAdd(
3556 Offset0,
3557 Builder.createOverflowingOp(Instruction::Mul, {PartxStride, VF}));
3559}
3560
3562 auto &Builder = State.Builder;
3563 assert(getOffset() && "Expected prior materialization of offset");
3564 Value *Ptr = State.get(getPointer(), true);
3565 Value *Offset = State.get(getOffset(), true);
3566 Value *ResultPtr = Builder.CreateGEP(getSourceElementType(), Ptr, Offset, "",
3568 State.set(this, ResultPtr, /*IsScalar*/ true);
3569}
3570
3571#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3573 VPSlotTracker &SlotTracker) const {
3574 O << Indent;
3576 O << " = vector-end-pointer";
3577 printFlags(O);
3578 getSourceElementType()->print(O);
3579 O << ", ";
3581}
3582#endif
3583
3585 assert(getVFxPart() &&
3586 "Expected prior simplification of recipe without VFxPart");
3587
3588 auto &Builder = State.Builder;
3589 Value *Ptr = State.get(getOperand(0), VPLane(0));
3590 Value *Offset = State.get(getVFxPart(), true);
3591 // TODO: Expand to VPInstruction to support constant folding.
3592 if (!match(getStride(), m_One())) {
3593 Value *Stride = Builder.CreateZExtOrTrunc(State.get(getStride(), true),
3594 Offset->getType());
3595 Offset = Builder.CreateMul(Offset, Stride);
3596 }
3597 Value *ResultPtr = Builder.CreateGEP(getSourceElementType(), Ptr, Offset, "",
3599 State.set(this, ResultPtr, /*IsScalar*/ true);
3600}
3601
3602#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3604 VPSlotTracker &SlotTracker) const {
3605 O << Indent;
3607 O << " = vector-pointer";
3608 printFlags(O);
3609 getSourceElementType()->print(O);
3610 O << ", ";
3612}
3613#endif
3614
3616 VPCostContext &Ctx) const {
3617 // A blend will be expanded to a select VPInstruction, which will generate a
3618 // scalar select if only the first lane is used.
3620 VF = ElementCount::getFixed(1);
3621
3622 Type *ResultTy = toVectorTy(this->getScalarType(), VF);
3623 Type *CmpTy = toVectorTy(Type::getInt1Ty(Ctx.LLVMCtx), VF);
3624
3626 for (unsigned I = 1, E = getNumIncomingValues(); I != E; ++I) {
3627 CmpPredicate Pred;
3628 if (!match(getMask(I), m_Cmp(Pred, m_VPValue(), m_VPValue())))
3629 Pred = getScalarType()->isFloatingPointTy() ? CmpInst::BAD_FCMP_PREDICATE
3631 Cost += Ctx.TTI.getCmpSelInstrCost(Instruction::Select, ResultTy, CmpTy,
3632 Pred, Ctx.CostKind);
3633 }
3634 return Cost;
3635}
3636
3637#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3639 VPSlotTracker &SlotTracker) const {
3640 O << Indent << "BLEND ";
3642 O << " =";
3643 printFlags(O);
3644 if (getNumIncomingValues() == 1) {
3645 // Not a User of any mask: not really blending, this is a
3646 // single-predecessor phi.
3647 getIncomingValue(0)->printAsOperand(O, SlotTracker);
3648 } else {
3649 for (unsigned I = 0, E = getNumIncomingValues(); I < E; ++I) {
3650 if (I != 0)
3651 O << " ";
3652 getIncomingValue(I)->printAsOperand(O, SlotTracker);
3653 if (I == 0 && isNormalized())
3654 continue;
3655 O << "/";
3656 getMask(I)->printAsOperand(O, SlotTracker);
3657 }
3658 }
3659}
3660#endif
3661
3665 "In-loop AnyOf reductions aren't currently supported");
3666 // Propagate the fast-math flags carried by the underlying instruction.
3667 IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder);
3668 State.Builder.setFastMathFlags(getFastMathFlagsOrNone());
3669 Value *NewVecOp = State.get(getVecOp());
3670 if (VPValue *Cond = getCondOp()) {
3671 Value *NewCond = State.get(Cond, State.VF.isScalar());
3672 VectorType *VecTy = dyn_cast<VectorType>(NewVecOp->getType());
3673 Type *ElementTy = VecTy ? VecTy->getElementType() : NewVecOp->getType();
3674
3675 Value *Start =
3677 if (State.VF.isVector())
3678 Start = State.Builder.CreateVectorSplat(VecTy->getElementCount(), Start);
3679
3680 Value *Select = State.Builder.CreateSelect(NewCond, NewVecOp, Start);
3681 NewVecOp = Select;
3682 }
3683 Value *NewRed;
3684 Value *NextInChain;
3685 if (isOrdered()) {
3686 Value *PrevInChain = State.get(getChainOp(), /*NeedsSingleScalar=*/true);
3687 if (State.VF.isVector())
3688 NewRed =
3689 createOrderedReduction(State.Builder, Kind, NewVecOp, PrevInChain);
3690 else
3691 NewRed = State.Builder.CreateBinOp(
3693 PrevInChain, NewVecOp);
3694 PrevInChain = NewRed;
3695 NextInChain = NewRed;
3696 } else if (isPartialReduction()) {
3697 assert((Kind == RecurKind::Add || Kind == RecurKind::FAdd) &&
3698 "Unexpected partial reduction kind");
3699 Value *PrevInChain = State.get(getChainOp(), /*NeedsSingleScalar=*/false);
3700 NewRed = State.Builder.CreateIntrinsic(
3701 PrevInChain->getType(),
3702 Kind == RecurKind::Add ? Intrinsic::vector_partial_reduce_add
3703 : Intrinsic::vector_partial_reduce_fadd,
3704 {PrevInChain, NewVecOp}, State.Builder.getFastMathFlags(),
3705 "partial.reduce");
3706 PrevInChain = NewRed;
3707 NextInChain = NewRed;
3708 } else {
3709 assert(isInLoop() &&
3710 "The reduction must either be ordered, partial or in-loop");
3711 Value *PrevInChain = State.get(getChainOp(), /*NeedsSingleScalar=*/true);
3712 NewRed = createSimpleReduction(State.Builder, NewVecOp, Kind);
3714 NextInChain = createMinMaxOp(State.Builder, Kind, NewRed, PrevInChain);
3715 else
3716 NextInChain = State.Builder.CreateBinOp(
3718 PrevInChain, NewRed);
3719 }
3720 State.set(this, NextInChain, /*IsScalar*/ !isPartialReduction());
3721}
3722
3724
3725 assert(State.VF.isVector() &&
3726 "Shouldn't generate VPReductionEVLRecipe with scalar VF");
3727 auto &Builder = State.Builder;
3728 // Propagate the fast-math flags carried by the underlying instruction.
3729 IRBuilderBase::FastMathFlagGuard FMFGuard(Builder);
3730 Builder.setFastMathFlags(getFastMathFlagsOrNone());
3731
3733 Value *Prev =
3734 State.get(getChainOp(), /*NeedsSingleScalar=*/!isPartialReduction());
3735 Value *VecOp = State.get(getVecOp());
3736 Value *EVL = State.get(getEVL(), VPLane(0));
3737
3738 Value *Mask;
3739 if (VPValue *CondOp = getCondOp())
3740 Mask = State.get(CondOp);
3741 else
3742 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
3743
3744 Value *NewRed;
3745 if (isPartialReduction()) {
3746 // For partial reductions, we need to generate a predicated select
3747 // (vp.merge) since `@llvm.vector.partial.reduce()` doesn't have a vector
3748 // predicated version.
3749 VectorType *VecTy = cast<VectorType>(VecOp->getType());
3750 Value *Identity = getRecurrenceIdentity(Kind, VecTy->getElementType(),
3752 Identity =
3753 State.Builder.CreateVectorSplat(VecTy->getElementCount(), Identity);
3754
3755 // TODO: Calculate the predicate cost for the partial reduction.
3756 Value *NewVecOp = State.Builder.CreateIntrinsic(
3757 VecTy, Intrinsic::vp_merge, {Mask, VecOp, Identity, EVL});
3758 assert((Kind == RecurKind::Add || Kind == RecurKind::FAdd) &&
3759 "Unexpected partial reduction kind");
3760 NewRed = State.Builder.CreateIntrinsic(
3761 Prev->getType(),
3762 Kind == RecurKind::Add ? Intrinsic::vector_partial_reduce_add
3763 : Intrinsic::vector_partial_reduce_fadd,
3764 {Prev, NewVecOp}, State.Builder.getFastMathFlags(), "partial.reduce");
3765 } else if (isOrdered()) {
3766 NewRed = createOrderedReduction(Builder, Kind, VecOp, Prev, Mask, EVL);
3767 } else {
3768 NewRed = createSimpleReduction(Builder, VecOp, Kind, Mask, EVL);
3770 NewRed = createMinMaxOp(Builder, Kind, NewRed, Prev);
3771 else
3772 NewRed = Builder.CreateBinOp(
3774 Prev);
3775 }
3776 State.set(this, NewRed, !isPartialReduction());
3777}
3778
3780 VPCostContext &Ctx) const {
3781 RecurKind RdxKind = getRecurrenceKind();
3782 Type *ElementTy = this->getScalarType();
3783 auto *VectorTy = cast<VectorType>(toVectorTy(ElementTy, VF));
3784 unsigned Opcode = RecurrenceDescriptor::getOpcode(RdxKind);
3786 std::optional<FastMathFlags> OptionalFMF =
3787 ElementTy->isFloatingPointTy() ? std::make_optional(FMFs) : std::nullopt;
3788
3789 if (isPartialReduction()) {
3790 InstructionCost CondCost = 0;
3791 if (isConditional()) {
3793 auto *CondTy =
3795 CondCost = Ctx.TTI.getCmpSelInstrCost(Instruction::Select, VectorTy,
3796 CondTy, Pred, Ctx.CostKind);
3797 }
3798 return CondCost + Ctx.TTI.getPartialReductionCost(
3799 Opcode, ElementTy, nullptr, ElementTy, VF,
3800 TTI::PR_None, TTI::PR_None, {}, Ctx.CostKind,
3801 OptionalFMF);
3802 }
3803
3804 // TODO: Support any-of reductions.
3805 assert(
3807 Ctx.Opts.force_target_instruction_cost) &&
3808 "Any-of reduction not implemented in VPlan-based cost model currently.");
3809
3810 // Note that TTI should model the cost of moving result to the scalar register
3811 // and the BinOp cost in the getMinMaxReductionCost().
3814 return Ctx.TTI.getMinMaxReductionCost(Id, VectorTy, FMFs, Ctx.CostKind);
3815 }
3816
3817 // Note that TTI should model the cost of moving result to the scalar register
3818 // and the BinOp cost in the getArithmeticReductionCost().
3819 return Ctx.TTI.getArithmeticReductionCost(Opcode, VectorTy, OptionalFMF,
3820 Ctx.CostKind);
3821}
3822
3824 ExpressionTypes ExpressionType,
3825 ArrayRef<VPSingleDefRecipe *> ExpressionRecipes)
3826 : VPSingleDefRecipe(VPRecipeBase::VPExpressionSC, {},
3827 cast<VPReductionRecipe>(ExpressionRecipes.back())
3828 ->getChainOp()
3829 ->getScalarType()),
3830 ExpressionRecipes(ExpressionRecipes), ExpressionType(ExpressionType) {
3831 assert(!ExpressionRecipes.empty() && "Nothing to combine?");
3832 assert(
3833 none_of(ExpressionRecipes,
3834 [](VPSingleDefRecipe *R) { return R->mayHaveSideEffects(); }) &&
3835 "expression cannot contain recipes with side-effects");
3836
3837 // Maintain a copy of the expression recipes as a set of users.
3838 SmallPtrSet<VPUser *, 4> ExpressionRecipesAsSetOfUsers;
3839 for (auto *R : ExpressionRecipes)
3840 ExpressionRecipesAsSetOfUsers.insert(R);
3841
3842 // Recipes in the expression, except the last one, must only be used by
3843 // (other) recipes inside the expression. If there are other users, external
3844 // to the expression, use a clone of the recipe for external users.
3845 for (VPSingleDefRecipe *R : reverse(ExpressionRecipes)) {
3846 if (R != ExpressionRecipes.back() &&
3847 any_of(R->users(), [&ExpressionRecipesAsSetOfUsers](VPUser *U) {
3848 return !ExpressionRecipesAsSetOfUsers.contains(U);
3849 })) {
3850 // There are users outside of the expression. Clone the recipe and use the
3851 // clone those external users.
3852 VPSingleDefRecipe *CopyForExtUsers = R->clone();
3853 R->replaceUsesWithIf(CopyForExtUsers,
3854 [&ExpressionRecipesAsSetOfUsers](VPUser *U) {
3855 return !ExpressionRecipesAsSetOfUsers.contains(U);
3856 });
3857 CopyForExtUsers->insertBefore(R);
3858 }
3859 if (R->getParent())
3860 R->removeFromParent();
3861 }
3862
3863 // Internalize all external operands to the expression recipes. To do so,
3864 // create new temporary VPValues for all operands defined by a recipe outside
3865 // the expression. The original operands are added as operands of the
3866 // VPExpressionRecipe itself.
3867 for (auto *R : ExpressionRecipes) {
3868 for (const auto &[Idx, Op] : enumerate(R->operands())) {
3869 auto *Def = Op->getDefiningRecipe();
3870 if (Def && ExpressionRecipesAsSetOfUsers.contains(Def))
3871 continue;
3872 addOperand(Op);
3873 LiveInPlaceholders.push_back(new VPSymbolicValue(Op->getScalarType()));
3874 }
3875 }
3876
3877 // Replace each external operand with the first one created for it in
3878 // LiveInPlaceholders.
3879 for (auto *R : ExpressionRecipes)
3880 for (auto const &[LiveIn, Tmp] : zip(operands(), LiveInPlaceholders))
3881 R->replaceUsesOfWith(LiveIn, Tmp);
3882}
3883
3885 for (auto *R : ExpressionRecipes)
3886 // Since the list could contain duplicates, make sure the recipe hasn't
3887 // already been inserted.
3888 if (!R->getParent())
3889 R->insertBefore(this);
3890
3891 for (const auto &[Idx, Op] : enumerate(operands()))
3892 LiveInPlaceholders[Idx]->replaceAllUsesWith(Op);
3893
3894 replaceAllUsesWith(ExpressionRecipes.back());
3895 SmallVector<VPSingleDefRecipe *> DecomposedRecipes(ExpressionRecipes);
3896 ExpressionRecipes.clear();
3897 return DecomposedRecipes;
3898}
3899
3901 VPCostContext &Ctx) const {
3902 Type *RedTy = this->getScalarType();
3903 auto *SrcVecTy =
3905 unsigned Opcode = RecurrenceDescriptor::getOpcode(
3906 cast<VPReductionRecipe>(ExpressionRecipes.back())->getRecurrenceKind());
3907 switch (ExpressionType) {
3908 case ExpressionTypes::NegatedExtendedReduction:
3909 assert((Opcode == Instruction::Add || Opcode == Instruction::FAdd) &&
3910 "Unexpected opcode");
3911 Opcode = Opcode == Instruction::Add ? Instruction::Sub : Instruction::FSub;
3912 [[fallthrough]];
3913 case ExpressionTypes::ExtendedReduction: {
3914 auto *RedR = cast<VPReductionRecipe>(ExpressionRecipes.back());
3915 auto *ExtR = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3916
3917 if (RedR->isPartialReduction())
3918 return Ctx.TTI.getPartialReductionCost(
3919 Opcode, getOperand(0)->getScalarType(), nullptr, RedTy, VF,
3921 TargetTransformInfo::PR_None, std::nullopt, Ctx.CostKind,
3922 RedTy->isFloatingPointTy()
3923 ? std::optional{RedR->getFastMathFlagsOrNone()}
3924 : std::nullopt);
3925 else if (!RedTy->isFloatingPointTy())
3926 // TTI::getExtendedReductionCost only supports integer types.
3927 return Ctx.TTI.getExtendedReductionCost(
3928 Opcode, ExtR->getOpcode() == Instruction::ZExt, RedTy, SrcVecTy,
3929 std::nullopt, Ctx.CostKind);
3930 else
3932 }
3933 case ExpressionTypes::MulAccReduction:
3934 return Ctx.TTI.getMulAccReductionCost(false, Opcode, RedTy, SrcVecTy,
3935 Ctx.CostKind);
3936
3937 case ExpressionTypes::ExtNegatedMulAccReduction:
3938 switch (Opcode) {
3939 case Instruction::Add:
3940 Opcode = Instruction::Sub;
3941 break;
3942 case Instruction::FAdd:
3943 Opcode = Instruction::FSub;
3944 break;
3945 default:
3946 llvm_unreachable("Unsupported opcode for ExtNegatedMulAccReduction");
3947 }
3948 [[fallthrough]];
3949 case ExpressionTypes::ExtMulAccReduction: {
3950 auto *RedR = cast<VPReductionRecipe>(ExpressionRecipes.back());
3951 if (RedR->isPartialReduction()) {
3952 auto *Ext0R = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3953 auto *Ext1R = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
3954 auto *Mul = cast<VPWidenRecipe>(ExpressionRecipes[2]);
3955 return Ctx.TTI.getPartialReductionCost(
3956 Opcode, getOperand(0)->getScalarType(),
3957 getOperand(1)->getScalarType(), RedTy, VF,
3959 Ext0R->getOpcode()),
3961 Ext1R->getOpcode()),
3962 Mul->getOpcode(), Ctx.CostKind,
3963 RedTy->isFloatingPointTy()
3964 ? std::optional{RedR->getFastMathFlagsOrNone()}
3965 : std::nullopt);
3966 }
3967 assert(Opcode != Instruction::FSub && "Only integer types are supported");
3968 return Ctx.TTI.getMulAccReductionCost(
3969 cast<VPWidenCastRecipe>(ExpressionRecipes.front())->getOpcode() ==
3970 Instruction::ZExt,
3971 Opcode, RedTy, SrcVecTy, Ctx.CostKind);
3972 }
3973 }
3974 llvm_unreachable("Unknown VPExpressionRecipe::ExpressionTypes enum");
3975}
3976
3978 return any_of(ExpressionRecipes, [](VPSingleDefRecipe *R) {
3979 return R->mayReadFromMemory() || R->mayWriteToMemory();
3980 });
3981}
3982
3984 assert(
3985 none_of(ExpressionRecipes,
3986 [](VPSingleDefRecipe *R) { return R->mayHaveSideEffects(); }) &&
3987 "expression cannot contain recipes with side-effects");
3988 return false;
3989}
3990
3992 auto *RR = dyn_cast<VPReductionRecipe>(ExpressionRecipes.back());
3993 return RR && !RR->isPartialReduction();
3994}
3995
3996#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3997
3999 VPSlotTracker &SlotTracker) const {
4000 O << Indent << "EXPRESSION ";
4002 O << " = ";
4003 auto *Red = cast<VPReductionRecipe>(ExpressionRecipes.back());
4004 unsigned Opcode = RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind());
4005 VPValue *Mask = getLastOperand();
4006 VPValue *EVL =
4008 ? getOperand(getNumOperands() - (Red->isConditional() ? 2 : 1))
4009 : nullptr;
4010 VPValue *RdxStart = getOperand(
4011 getNumOperands() - (Red->isConditional() ? 2 : 1) - (EVL ? 1 : 0));
4012 auto PrintEVLAndMask = [&]() {
4013 if (EVL) {
4014 O << ", ";
4015 EVL->printAsOperand(O, SlotTracker);
4016 }
4017 if (Red->isConditional()) {
4018 O << ", ";
4019 Mask->printAsOperand(O, SlotTracker);
4020 }
4021 };
4022
4023 switch (ExpressionType) {
4024 case ExpressionTypes::NegatedExtendedReduction:
4025 case ExpressionTypes::ExtendedReduction: {
4026 bool Negated = ExpressionType == ExpressionTypes::NegatedExtendedReduction;
4028 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
4029 O << Instruction::getOpcodeName(Opcode) << " (";
4030 if (Negated)
4031 O << (Opcode == Instruction::Add ? "sub (0, " : "fneg(");
4033 if (Negated)
4034 O << ")";
4035 Red->printFlags(O);
4036
4037 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
4038 O << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
4039 << *Ext0->getScalarType();
4040 PrintEVLAndMask();
4041 O << ")";
4042 break;
4043 }
4044 case ExpressionTypes::ExtNegatedMulAccReduction: {
4045 RdxStart->printAsOperand(O, SlotTracker);
4046 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
4048 RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind()))
4049 << " (sub (0, mul";
4050 auto *Mul = cast<VPWidenRecipe>(ExpressionRecipes[2]);
4051 Mul->printFlags(O);
4052 O << "(";
4054 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
4055 O << " " << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
4056 << *Ext0->getScalarType() << "), (";
4058 auto *Ext1 = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
4059 O << " " << Instruction::getOpcodeName(Ext1->getOpcode()) << " to "
4060 << *Ext1->getScalarType() << ")";
4061 PrintEVLAndMask();
4062 O << "))";
4063 break;
4064 }
4065 case ExpressionTypes::MulAccReduction:
4066 case ExpressionTypes::ExtMulAccReduction: {
4067 RdxStart->printAsOperand(O, SlotTracker);
4068 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
4070 RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind()))
4071 << " (";
4072 O << "mul";
4073 bool IsExtended = ExpressionType == ExpressionTypes::ExtMulAccReduction;
4074 auto *Mul = cast<VPWidenRecipe>(IsExtended ? ExpressionRecipes[2]
4075 : ExpressionRecipes[0]);
4076 Mul->printFlags(O);
4077 if (IsExtended)
4078 O << "(";
4080 if (IsExtended) {
4081 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
4082 O << " " << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
4083 << *Ext0->getScalarType() << "), (";
4084 } else {
4085 O << ", ";
4086 }
4088 if (IsExtended) {
4089 auto *Ext1 = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
4090 O << " " << Instruction::getOpcodeName(Ext1->getOpcode()) << " to "
4091 << *Ext1->getScalarType() << ")";
4092 }
4093 PrintEVLAndMask();
4094 O << ")";
4095 break;
4096 }
4097 }
4098}
4099
4101 VPSlotTracker &SlotTracker) const {
4102 if (isPartialReduction())
4103 O << Indent << "PARTIAL-REDUCE ";
4104 else
4105 O << Indent << "REDUCE ";
4107 O << " = ";
4109 O << " +";
4110 printFlags(O);
4111 O << " reduce.";
4113 O << " (";
4115 if (isConditional()) {
4116 O << ", ";
4118 }
4119 O << ")";
4120}
4121
4123 VPSlotTracker &SlotTracker) const {
4124 if (isPartialReduction())
4125 O << Indent << "PARTIAL-REDUCE ";
4126 else
4127 O << Indent << "REDUCE ";
4129 O << " = ";
4131 O << " +";
4132 printFlags(O);
4133 O << " vp.reduce."
4136 << " (";
4138 O << ", ";
4140 if (isConditional()) {
4141 O << ", ";
4143 }
4144 O << ")";
4145}
4146
4147#endif
4148
4150 assert(IsSingleScalar &&
4151 "VPReplicateRecipes must be unrolled before ::execute");
4152 auto *Instr = getUnderlyingInstr();
4153 Instruction *Cloned = Instr->clone();
4154 Type *ResultTy = getScalarType();
4155 if (!ResultTy->isVoidTy()) {
4156 Cloned->setName(Instr->getName() + ".cloned");
4157 // The operands of the replicate recipe may have been narrowed, resulting in
4158 // a narrower result type. Update the type of the cloned instruction to the
4159 // correct type.
4160 if (ResultTy != Cloned->getType())
4161 Cloned->mutateType(ResultTy);
4162 }
4163
4166 Cloned->dropPoisonGeneratingFlags();
4167 applyFlags(*Cloned);
4168 applyMetadata(*Cloned);
4169
4170 if (hasPredicate())
4171 cast<CmpInst>(Cloned)->setPredicate(getPredicate());
4172
4173 // Replace the operands of the cloned instructions with their scalar
4174 // equivalents in the new loop.
4175 for (unsigned Idx : seq(Cloned->getNumOperands()))
4176 Cloned->setOperand(Idx, State.get(getOperand(Idx), true));
4177
4178 // Place the cloned scalar in the new loop.
4179 State.Builder.Insert(Cloned);
4180
4181 State.set(this, Cloned, true);
4182
4183 // If we just cloned a new assumption, add it the assumption cache.
4184 if (auto *II = dyn_cast<AssumeInst>(Cloned))
4185 State.AC->registerAssumption(II);
4186}
4187
4188/// Returns a SCEV expression for \p Ptr if it is a pointer computation for
4189/// which the legacy cost model computes a SCEV expression when computing the
4190/// address cost. Computing SCEVs for VPValues is incomplete and returns
4191/// SCEVCouldNotCompute in cases the legacy cost model can compute SCEVs. In
4192/// those cases we fall back to the legacy cost model. Otherwise return nullptr.
4193static const SCEV *getAddressAccessSCEV(const VPValue *Ptr,
4195 const Loop *L) {
4196 const SCEV *Addr = vputils::getSCEVExprForVPValue(Ptr, PSE, L);
4197 if (isa<SCEVCouldNotCompute>(Addr))
4198 return Addr;
4199
4200 return vputils::isAddressSCEVForCost(Addr, *PSE.getSE(), L) ? Addr : nullptr;
4201}
4202
4204 VPCostContext &Ctx) const {
4206 // VPReplicateRecipe may be cloned as part of an existing VPlan-to-VPlan
4207 // transform, avoid computing their cost multiple times for now.
4208 Ctx.SkipCostComputation.insert(UI);
4209
4210 if (VF.isScalable() && !isSingleScalar())
4212
4213 switch (UI->getOpcode()) {
4214 case Instruction::Alloca:
4215 if (VF.isScalable())
4217 return Ctx.TTI.getArithmeticInstrCost(Instruction::Mul,
4218 this->getScalarType(), Ctx.CostKind);
4219 case Instruction::GetElementPtr:
4220 // We mark this instruction as zero-cost because the cost of GEPs in
4221 // vectorized code depends on whether the corresponding memory instruction
4222 // is scalarized or not. Therefore, we handle GEPs with the memory
4223 // instruction cost.
4224 return 0;
4225 case Instruction::Call: {
4226 auto *CalledFn = cast<Function>(getLastOperand()->getLiveInIRValue());
4227 Type *ResultTy = this->getScalarType();
4228 return computeCallCost(CalledFn, ResultTy, drop_end(operands()),
4229 isSingleScalar(), VF, Ctx);
4230 }
4231 case Instruction::FNeg:
4232 case Instruction::Add:
4233 case Instruction::Sub:
4234 case Instruction::FAdd:
4235 case Instruction::FSub:
4236 case Instruction::Mul:
4237 case Instruction::FMul:
4238 case Instruction::FDiv:
4239 case Instruction::FRem:
4240 case Instruction::Shl:
4241 case Instruction::LShr:
4242 case Instruction::AShr:
4243 case Instruction::And:
4244 case Instruction::Or:
4245 case Instruction::Xor:
4246 case Instruction::ICmp:
4247 case Instruction::FCmp:
4248 case Instruction::Freeze:
4250 Ctx) *
4251 (isSingleScalar() ? 1 : VF.getFixedValue());
4252 case Instruction::SDiv:
4253 case Instruction::UDiv:
4254 case Instruction::SRem:
4255 case Instruction::URem: {
4256 InstructionCost ScalarCost =
4258 if (isSingleScalar())
4259 return ScalarCost;
4260
4261 // If any of the operands is from a different replicate region and has its
4262 // cost skipped, it may have been forced to scalar. Fall back to legacy cost
4263 // model to avoid cost mis-match.
4264 if (any_of(operands(), [&Ctx, VF](VPValue *Op) {
4265 auto *PredR = dyn_cast<VPPredInstPHIRecipe>(Op);
4266 if (!PredR)
4267 return false;
4268 return Ctx.skipCostComputation(
4270 PredR->getOperand(0)->getUnderlyingValue()),
4271 VF.isVector());
4272 }))
4273 break;
4274
4275 ScalarCost = ScalarCost * VF.getFixedValue() +
4276 Ctx.getScalarizationOverhead(this->getScalarType(),
4277 to_vector(operands()), VF);
4278 // If the recipe is not predicated (i.e. not in a replicate region), return
4279 // the scalar cost. Otherwise handle predicated cost.
4280 const VPRegionBlock *ParentRegion = getRegion();
4281 if (!ParentRegion || !ParentRegion->isReplicator())
4282 return ScalarCost;
4283
4284 // Account for the phi nodes that we will create.
4285 ScalarCost += VF.getFixedValue() *
4286 Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
4287 // Scale the cost by the probability of executing the predicated blocks.
4288 // This assumes the predicated block for each vector lane is equally
4289 // likely.
4290 ScalarCost /= Ctx.getCostDivisor(
4291 ParentRegion->getEntryBranchOnMask()->getExecutionFrequency());
4292 return ScalarCost;
4293 }
4294 case Instruction::Load:
4295 case Instruction::Store: {
4296 bool IsLoad = UI->getOpcode() == Instruction::Load;
4297 const VPValue *PtrOp = getOperand(!IsLoad);
4298 const SCEV *PtrSCEV = getAddressAccessSCEV(PtrOp, Ctx.PSE, Ctx.L);
4300 // Don't fall back to the legacy cost model for single-scalar accesses.
4301 // PtrSCEV won't be used.
4302 if (!isSingleScalar())
4303 break;
4304 PtrSCEV = nullptr;
4305 }
4306
4307 Type *ValTy = (IsLoad ? this : getOperand(0))->getScalarType();
4308 Type *ScalarPtrTy = PtrOp->getScalarType();
4309 const Align Alignment = getLoadStoreAlignment(UI);
4310 unsigned AS = cast<PointerType>(ScalarPtrTy)->getAddressSpace();
4312 bool PreferVectorizedAddressing = Ctx.TTI.prefersVectorizedAddressing();
4313 bool UsedByLoadStoreAddress =
4314 !PreferVectorizedAddressing && vputils::isUsedByLoadStoreAddress(this);
4315 InstructionCost ScalarMemOpCost = Ctx.TTI.getMemoryOpCost(
4316 UI->getOpcode(), ValTy, Alignment, AS, Ctx.CostKind, OpInfo,
4317 UsedByLoadStoreAddress ? UI : nullptr);
4318
4319 Type *PtrTy = isSingleScalar() ? ScalarPtrTy : toVectorTy(ScalarPtrTy, VF);
4320 InstructionCost ScalarCost =
4321 ScalarMemOpCost +
4322 Ctx.TTI.getAddressComputationCost(
4323 PtrTy, UsedByLoadStoreAddress ? nullptr : Ctx.PSE.getSE(), PtrSCEV,
4324 Ctx.CostKind);
4325 if (isSingleScalar())
4326 return ScalarCost;
4327
4328 SmallVector<const VPValue *> OpsToScalarize;
4329 Type *ResultTy = Type::getVoidTy(PtrTy->getContext());
4330 // Set ResultTy and OpsToScalarize, if scalarization is needed. Currently we
4331 // don't assign scalarization overhead in general, if the target prefers
4332 // vectorized addressing or the loaded value is used as part of an address
4333 // of another load or store.
4334 if (!UsedByLoadStoreAddress) {
4335 bool EfficientVectorLoadStore =
4336 Ctx.TTI.supportsEfficientVectorElementLoadStore();
4337 if (!(IsLoad && !PreferVectorizedAddressing) &&
4338 !(!IsLoad && EfficientVectorLoadStore))
4339 append_range(OpsToScalarize, operands());
4340
4341 if (!EfficientVectorLoadStore)
4342 ResultTy = this->getScalarType();
4343 }
4344
4346 IsLoad ? TTI::VectorInstrContext::Load : TTI::VectorInstrContext::Store;
4348 (ScalarCost * VF.getFixedValue()) +
4349 Ctx.getScalarizationOverhead(ResultTy, OpsToScalarize, VF, VIC, true);
4350
4351 const VPRegionBlock *ParentRegion = getRegion();
4352 if (ParentRegion && ParentRegion->isReplicator()) {
4353 // The cost of the branches is accounted for by the replicate region.
4354 Cost /= Ctx.getCostDivisor(
4355 ParentRegion->getEntryBranchOnMask()->getExecutionFrequency());
4356
4357 if (Ctx.useEmulatedMaskMemRefHack(this, VF)) {
4358 // Artificially setting to a high enough value to practically disable
4359 // vectorization with such operations.
4360 return 3000000;
4361 }
4362 }
4363 return Cost;
4364 }
4365 case Instruction::BitCast:
4366 case Instruction::SExt:
4367 case Instruction::ZExt:
4368 case Instruction::FPToUI:
4369 case Instruction::FPToSI:
4370 case Instruction::FPExt:
4371 case Instruction::PtrToInt:
4372 case Instruction::PtrToAddr:
4373 case Instruction::IntToPtr:
4374 case Instruction::SIToFP:
4375 case Instruction::UIToFP:
4376 case Instruction::Trunc:
4377 case Instruction::FPTrunc:
4378 case Instruction::Select:
4379 case Instruction::AddrSpaceCast: {
4381 Ctx) *
4382 (isSingleScalar() ? 1 : VF.getFixedValue());
4383 }
4384 case Instruction::ExtractValue:
4385 return Ctx.TTI.getInsertExtractValueCost(getOpcode(), Ctx.CostKind);
4386 }
4387
4388 return Ctx.getLegacyCost(UI, VF);
4389}
4390
4392 Function *CalledFn, Type *ResultTy, ArrayRef<const VPValue *> ArgOps,
4393 bool IsSingleScalar, ElementCount VF, VPCostContext &Ctx) {
4395 ArgOps, [&](const VPValue *Op) { return Op->getScalarType(); });
4396
4397 Intrinsic::ID IntrinID = CalledFn->getIntrinsicID();
4398 auto GetIntrinsicCost = [&] {
4399 if (!IntrinID)
4401 return Ctx.TTI.getIntrinsicInstrCost(
4402 IntrinsicCostAttributes(IntrinID, ResultTy, Tys), Ctx.CostKind);
4403 };
4404
4405 if (IntrinID && VPCostContext::isFreeScalarIntrinsic(IntrinID)) {
4406 assert(GetIntrinsicCost() == 0 && "scalarizing intrinsic should be free");
4407 return 0;
4408 }
4409
4410 InstructionCost ScalarCallCost =
4411 Ctx.TTI.getCallInstrCost(CalledFn, ResultTy, Tys, Ctx.CostKind);
4412 if (IsSingleScalar) {
4413 ScalarCallCost = std::min(ScalarCallCost, GetIntrinsicCost());
4414 return ScalarCallCost;
4415 }
4416
4417 // Scalarization overhead is undefined for scalable VFs.
4418 if (VF.isScalable())
4420
4421 return ScalarCallCost * VF.getFixedValue() +
4422 Ctx.getScalarizationOverhead(ResultTy, ArgOps, VF);
4423}
4424
4425#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4427 VPSlotTracker &SlotTracker) const {
4428 O << Indent << (IsSingleScalar ? "CLONE " : "REPLICATE ");
4429
4430 if (!getScalarType()->isVoidTy()) {
4432 O << " = ";
4433 }
4434 if (auto *CB = dyn_cast<CallBase>(getUnderlyingInstr())) {
4435 O << "call";
4436 printFlags(O);
4437 O << "@" << CB->getCalledFunction()->getName() << "(";
4439 Op->printAsOperand(O, SlotTracker);
4440 });
4441 O << ")";
4442 } else {
4444 printFlags(O);
4446 }
4447
4448 // Find if the recipe is used by a widened recipe via an intervening
4449 // VPPredInstPHIRecipe. In this case, also pack the scalar values in a vector.
4450 if (any_of(users(), [](const VPUser *U) {
4451 if (auto *PredR = dyn_cast<VPPredInstPHIRecipe>(U))
4452 return !vputils::onlyScalarValuesUsed(PredR);
4453 return false;
4454 }))
4455 O << " (S->V)";
4456}
4457#endif
4458
4460 llvm_unreachable("recipe must be removed when dissolving replicate region");
4461}
4462
4464 VPCostContext &Ctx) const {
4465 // Replicating isn't supported for scalable vectors.
4466 if (VF.isScalable())
4468 auto *VecI1Ty = VectorType::get(Type::getInt1Ty(Ctx.LLVMCtx), VF);
4469 return Ctx.TTI.getScalarizationOverhead(
4470 VecI1Ty, APInt::getAllOnes(VF.getFixedValue()),
4471 /*Insert=*/false, /*Extract=*/true, Ctx.CostKind) +
4472 VF.getFixedValue() *
4473 Ctx.TTI.getCFInstrCost(Instruction::CondBr, Ctx.CostKind);
4474}
4475
4477 llvm_unreachable("recipe must be removed when dissolving replicate region");
4478}
4479
4480#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4482 VPSlotTracker &SlotTracker) const {
4483 O << Indent << "PHI-PREDICATED-INSTRUCTION ";
4485 O << " = ";
4487}
4488#endif
4489
4491const VPRecipeBase *VPWidenLoadRecipe::getAsRecipe() const { return this; }
4492
4495
4497const VPRecipeBase *VPWidenStoreRecipe::getAsRecipe() const { return this; }
4498
4501
4503 VPCostContext &Ctx) const {
4504 const VPRecipeBase *R = getAsRecipe();
4506 Type *ScalarTy = IsLoad ? cast<VPSingleDefRecipe>(R)->getScalarType()
4507 : R->getOperand(1)->getScalarType();
4508 Type *Ty = toVectorTy(ScalarTy, VF);
4509 unsigned AS =
4510 cast<PointerType>(getAddr()->getScalarType())->getAddressSpace();
4511 unsigned Opcode = IsLoad ? Instruction::Load : Instruction::Store;
4512
4513 if (!Consecutive) {
4514 // TODO: Using the original IR may not be accurate.
4515 // Currently, ARM will use the underlying IR to calculate gather/scatter
4516 // instruction cost.
4517 Type *PtrTy = getAddr()->getScalarType();
4518 const Value *Ptr = getAddr()->getUnderlyingValue();
4519
4520 // If the address value is uniform across all lanes, then the address can be
4521 // calculated with scalar type and broadcast.
4523 PtrTy = toVectorTy(PtrTy, VF);
4524
4525 unsigned IID = isa<VPWidenLoadRecipe>(R) ? Intrinsic::masked_gather
4526 : isa<VPWidenStoreRecipe>(R) ? Intrinsic::masked_scatter
4527 : isa<VPWidenLoadEVLRecipe>(R) ? Intrinsic::vp_gather
4528 : Intrinsic::vp_scatter;
4529 return Ctx.TTI.getAddressComputationCost(PtrTy, nullptr, nullptr,
4530 Ctx.CostKind) +
4531 Ctx.TTI.getMemIntrinsicInstrCost(
4533 &Ingredient),
4534 Ctx.CostKind);
4535 }
4536
4538 if (IsMasked) {
4539 unsigned IID = isa<VPWidenLoadRecipe>(R) ? Intrinsic::masked_load
4540 : Intrinsic::masked_store;
4541 Cost += Ctx.TTI.getMemIntrinsicInstrCost(
4542 MemIntrinsicCostAttributes(IID, Ty, Alignment, AS), Ctx.CostKind);
4543 } else {
4544 TTI::OperandValueInfo OpInfo = Ctx.getOperandInfo(
4546 : R->getOperand(1));
4547 Cost += Ctx.TTI.getMemoryOpCost(Opcode, Ty, Alignment, AS, Ctx.CostKind,
4548 OpInfo, &Ingredient);
4549 }
4550 return Cost;
4551}
4552
4554 Type *ScalarDataTy = getScalarType();
4555 auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
4556 bool CreateGather = !isConsecutive();
4557
4558 auto &Builder = State.Builder;
4559 Value *Mask = nullptr;
4560 if (auto *VPMask = getMask())
4561 Mask = State.get(VPMask);
4562
4563 Value *Addr = State.get(getAddr(), /*NeedsSingleScalar=*/!CreateGather);
4564 Value *NewLI;
4565 if (CreateGather) {
4566 NewLI = Builder.CreateMaskedGather(DataTy, Addr, Alignment, Mask, nullptr,
4567 "wide.masked.gather");
4568 } else if (Mask) {
4569 NewLI =
4570 Builder.CreateMaskedLoad(DataTy, Addr, Alignment, Mask,
4571 PoisonValue::get(DataTy), "wide.masked.load");
4572 } else {
4573 NewLI = Builder.CreateAlignedLoad(DataTy, Addr, Alignment, "wide.load");
4574 }
4576 State.set(this, NewLI);
4577}
4578
4579#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4581 VPSlotTracker &SlotTracker) const {
4582 O << Indent << "WIDEN ";
4584 O << " = load ";
4586 O << ", align " << getAlign().value();
4587}
4588#endif
4589
4591 Type *ScalarDataTy = getScalarType();
4592 auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
4593 bool CreateGather = !isConsecutive();
4594
4595 auto &Builder = State.Builder;
4596 CallInst *NewLI;
4597 Value *EVL = State.get(getEVL(), VPLane(0));
4598 Value *Addr = State.get(getAddr(), !CreateGather);
4599 Value *Mask = nullptr;
4600 if (VPValue *VPMask = getMask())
4601 Mask = State.get(VPMask);
4602 else
4603 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
4604
4605 if (CreateGather) {
4606 NewLI = Builder.CreateIntrinsicWithoutFolding(DataTy, Intrinsic::vp_gather,
4607 {Addr, Mask, EVL}, nullptr,
4608 "wide.masked.gather");
4609 } else {
4610 NewLI = Builder.CreateIntrinsicWithoutFolding(
4611 DataTy, Intrinsic::vp_load, {Addr, Mask, EVL}, nullptr, "vp.op.load");
4612 }
4613 NewLI->addParamAttr(
4615 applyMetadata(*NewLI);
4616 State.set(this, NewLI);
4617}
4618
4620 VPCostContext &Ctx) const {
4621 if (!Consecutive || IsMasked)
4622 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
4623
4624 // We need to use the getMemIntrinsicInstrCost() instead of getMemoryOpCost()
4625 // here because the EVL recipes using EVL to replace the tail mask. But in the
4626 // legacy model, it will always calculate the cost of mask.
4627 // TODO: Using getMemoryOpCost() instead of getMemIntrinsicInstrCost when we
4628 // don't need to compare to the legacy cost model.
4629 Type *Ty = toVectorTy(getScalarType(), VF);
4630 unsigned AS =
4631 cast<PointerType>(getAddr()->getScalarType())->getAddressSpace();
4632 return Ctx.TTI.getMemIntrinsicInstrCost(
4633 MemIntrinsicCostAttributes(Intrinsic::vp_load, Ty, Alignment, AS),
4634 Ctx.CostKind);
4635}
4636
4637#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4639 VPSlotTracker &SlotTracker) const {
4640 O << Indent << "WIDEN ";
4642 O << " = vp.load ";
4644 O << ", align " << getAlign().value();
4645}
4646#endif
4647
4649 VPValue *StoredVPValue = getStoredValue();
4650 bool CreateScatter = !isConsecutive();
4651
4652 auto &Builder = State.Builder;
4653
4654 Value *Mask = nullptr;
4655 if (auto *VPMask = getMask())
4656 Mask = State.get(VPMask);
4657
4658 Value *StoredVal = State.get(StoredVPValue);
4659 Value *Addr = State.get(getAddr(), /*NeedsSingleScalar=*/!CreateScatter);
4660 Instruction *NewSI = nullptr;
4661 if (CreateScatter)
4662 NewSI = Builder.CreateMaskedScatter(StoredVal, Addr, Alignment, Mask);
4663 else if (Mask)
4664 NewSI = Builder.CreateMaskedStore(StoredVal, Addr, Alignment, Mask);
4665 else
4666 NewSI = Builder.CreateAlignedStore(StoredVal, Addr, Alignment);
4667 applyMetadata(*NewSI);
4668}
4669
4670#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4672 VPSlotTracker &SlotTracker) const {
4673 O << Indent << "WIDEN store ";
4675 O << ", align " << getAlign().value();
4676}
4677#endif
4678
4680 VPValue *StoredValue = getStoredValue();
4681 bool CreateScatter = !isConsecutive();
4682
4683 auto &Builder = State.Builder;
4684
4685 CallInst *NewSI = nullptr;
4686 Value *StoredVal = State.get(StoredValue);
4687 Value *EVL = State.get(getEVL(), VPLane(0));
4688 Value *Mask = nullptr;
4689 if (VPValue *VPMask = getMask())
4690 Mask = State.get(VPMask);
4691 else
4692 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
4693
4694 Value *Addr = State.get(getAddr(), !CreateScatter);
4695 if (CreateScatter) {
4696 NewSI = Builder.CreateIntrinsicWithoutFolding(
4697 Type::getVoidTy(EVL->getContext()), Intrinsic::vp_scatter,
4698 {StoredVal, Addr, Mask, EVL});
4699 } else {
4700 NewSI = Builder.CreateIntrinsicWithoutFolding(
4701 Type::getVoidTy(EVL->getContext()), Intrinsic::vp_store,
4702 {StoredVal, Addr, Mask, EVL});
4703 }
4704 NewSI->addParamAttr(
4706 applyMetadata(*NewSI);
4707}
4708
4710 VPCostContext &Ctx) const {
4711 if (!Consecutive || IsMasked)
4712 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
4713
4714 // We need to use the getMemIntrinsicInstrCost() instead of getMemoryOpCost()
4715 // here because the EVL recipes using EVL to replace the tail mask. But in the
4716 // legacy model, it will always calculate the cost of mask.
4717 // TODO: Using getMemoryOpCost() instead of getMemIntrinsicInstrCost when we
4718 // don't need to compare to the legacy cost model.
4719 Type *Ty = toVectorTy(getStoredValue()->getScalarType(), VF);
4720 unsigned AS =
4721 cast<PointerType>(getAddr()->getScalarType())->getAddressSpace();
4722 return Ctx.TTI.getMemIntrinsicInstrCost(
4723 MemIntrinsicCostAttributes(Intrinsic::vp_store, Ty, Alignment, AS),
4724 Ctx.CostKind);
4725}
4726
4727#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4729 VPSlotTracker &SlotTracker) const {
4730 O << Indent << "WIDEN vp.store ";
4732 O << ", align " << getAlign().value();
4733}
4734#endif
4735
4737 VectorType *DstVTy, const DataLayout &DL) {
4738 // Verify that V is a vector type with same number of elements as DstVTy.
4739 auto VF = DstVTy->getElementCount();
4740 auto *SrcVecTy = cast<VectorType>(V->getType());
4741 assert(VF == SrcVecTy->getElementCount() && "Vector dimensions do not match");
4742 Type *SrcElemTy = SrcVecTy->getElementType();
4743 Type *DstElemTy = DstVTy->getElementType();
4744 assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&
4745 "Vector elements must have same size");
4746
4747 // Do a direct cast if element types are castable.
4748 if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
4749 return Builder.CreateBitOrPointerCast(V, DstVTy);
4750 }
4751 // V cannot be directly casted to desired vector type.
4752 // May happen when V is a floating point vector but DstVTy is a vector of
4753 // pointers or vice-versa. Handle this using a two-step bitcast using an
4754 // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
4755 assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&
4756 "Only one type should be a pointer type");
4757 assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&
4758 "Only one type should be a floating point type");
4759 Type *IntTy =
4760 IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy));
4761 auto *VecIntTy = VectorType::get(IntTy, VF);
4762 Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
4763 return Builder.CreateBitOrPointerCast(CastVal, DstVTy);
4764}
4765
4766/// Return a vector containing interleaved elements from multiple
4767/// smaller input vectors.
4769 const Twine &Name) {
4770 unsigned Factor = Vals.size();
4771 assert(Factor > 1 && "Tried to interleave invalid number of vectors");
4772
4773 VectorType *VecTy = cast<VectorType>(Vals[0]->getType());
4774#ifndef NDEBUG
4775 for (Value *Val : Vals)
4776 assert(Val->getType() == VecTy && "Tried to interleave mismatched types");
4777#endif
4778
4779 // Scalable vectors cannot use arbitrary shufflevectors (only splats), so
4780 // must use intrinsics to interleave.
4781 if (VecTy->isScalableTy()) {
4782 assert(Factor <= 8 && "Unsupported interleave factor for scalable vectors");
4783 return Builder.CreateVectorInterleave(Vals, Name);
4784 }
4785
4786 // Fixed length. Start by concatenating all vectors into a wide vector.
4787 Value *WideVec = concatenateVectors(Builder, Vals);
4788
4789 // Interleave the elements into the wide vector.
4790 const unsigned NumElts = VecTy->getElementCount().getFixedValue();
4791 return Builder.CreateShuffleVector(
4792 WideVec, createInterleaveMask(NumElts, Factor), Name);
4793}
4794
4795// Try to vectorize the interleave group that \p Instr belongs to.
4796//
4797// E.g. Translate following interleaved load group (factor = 3):
4798// for (i = 0; i < N; i+=3) {
4799// R = Pic[i]; // Member of index 0
4800// G = Pic[i+1]; // Member of index 1
4801// B = Pic[i+2]; // Member of index 2
4802// ... // do something to R, G, B
4803// }
4804// To:
4805// %wide.vec = load <12 x i32> ; Read 4 tuples of R,G,B
4806// %R.vec = shuffle %wide.vec, poison, <0, 3, 6, 9> ; R elements
4807// %G.vec = shuffle %wide.vec, poison, <1, 4, 7, 10> ; G elements
4808// %B.vec = shuffle %wide.vec, poison, <2, 5, 8, 11> ; B elements
4809//
4810// Or translate following interleaved store group (factor = 3):
4811// for (i = 0; i < N; i+=3) {
4812// ... do something to R, G, B
4813// Pic[i] = R; // Member of index 0
4814// Pic[i+1] = G; // Member of index 1
4815// Pic[i+2] = B; // Member of index 2
4816// }
4817// To:
4818// %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
4819// %B_U.vec = shuffle %B.vec, poison, <0, 1, 2, 3, u, u, u, u>
4820// %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
4821// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> ; Interleave R,G,B elements
4822// store <12 x i32> %interleaved.vec ; Write 4 tuples of R,G,B
4824 assert((!needsMaskForGaps() || !State.VF.isScalable()) &&
4825 "Masking gaps for scalable vectors is not yet supported.");
4827 Instruction *Instr = Group->getInsertPos();
4828
4829 // Prepare for the vector type of the interleaved load/store.
4830 Type *ScalarTy = getLoadStoreType(Instr);
4831 unsigned InterleaveFactor = Group->getFactor();
4832 auto *VecTy = VectorType::get(ScalarTy, State.VF * InterleaveFactor);
4833
4834 VPValue *BlockInMask = getMask();
4835 VPValue *Addr = getAddr();
4836 Value *ResAddr = State.get(Addr, VPLane(0));
4837
4838 auto CreateGroupMask = [&BlockInMask, &State,
4839 &InterleaveFactor](Value *MaskForGaps) -> Value * {
4840 if (State.VF.isScalable()) {
4841 assert(!MaskForGaps && "Interleaved groups with gaps are not supported.");
4842 assert(InterleaveFactor <= 8 &&
4843 "Unsupported deinterleave factor for scalable vectors");
4844 auto *ResBlockInMask = State.get(BlockInMask);
4845 SmallVector<Value *> Ops(InterleaveFactor, ResBlockInMask);
4846 return interleaveVectors(State.Builder, Ops, "interleaved.mask");
4847 }
4848
4849 if (!BlockInMask)
4850 return MaskForGaps;
4851
4852 Value *ResBlockInMask = State.get(BlockInMask);
4853 Value *ShuffledMask = State.Builder.CreateShuffleVector(
4854 ResBlockInMask,
4855 createReplicatedMask(InterleaveFactor, State.VF.getFixedValue()),
4856 "interleaved.mask");
4857 return MaskForGaps ? State.Builder.CreateBinOp(Instruction::And,
4858 ShuffledMask, MaskForGaps)
4859 : ShuffledMask;
4860 };
4861
4862 const DataLayout &DL = Instr->getDataLayout();
4863 // Vectorize the interleaved load group.
4864 if (isa<LoadInst>(Instr)) {
4865 Value *MaskForGaps = nullptr;
4866 if (needsMaskForGaps()) {
4867 MaskForGaps =
4868 createBitMaskForGaps(State.Builder, State.VF.getFixedValue(), *Group);
4869 assert(MaskForGaps && "Mask for Gaps is required but it is null");
4870 }
4871
4872 Instruction *NewLoad;
4873 if (BlockInMask || MaskForGaps) {
4874 Value *GroupMask = CreateGroupMask(MaskForGaps);
4875 Value *PoisonVec = PoisonValue::get(VecTy);
4876 NewLoad = State.Builder.CreateMaskedLoad(VecTy, ResAddr,
4877 Group->getAlign(), GroupMask,
4878 PoisonVec, "wide.masked.vec");
4879 } else
4880 NewLoad = State.Builder.CreateAlignedLoad(VecTy, ResAddr,
4881 Group->getAlign(), "wide.vec");
4882 applyMetadata(*NewLoad);
4883 // TODO: Also manage existing metadata using VPIRMetadata.
4884 Group->addMetadata(NewLoad);
4885
4887 if (VecTy->isScalableTy()) {
4888 // Scalable vectors cannot use arbitrary shufflevectors (only splats),
4889 // so must use intrinsics to deinterleave.
4890 assert(InterleaveFactor <= 8 &&
4891 "Unsupported deinterleave factor for scalable vectors");
4892 NewLoad = State.Builder.CreateIntrinsicWithoutFolding(
4893 Intrinsic::getDeinterleaveIntrinsicID(InterleaveFactor),
4894 NewLoad->getType(), NewLoad,
4895 /*FMFSource=*/nullptr, "strided.vec");
4896 }
4897
4898 auto CreateStridedVector = [&InterleaveFactor, &State,
4899 &NewLoad](unsigned Index) -> Value * {
4900 assert(Index < InterleaveFactor && "Illegal group index");
4901 if (State.VF.isScalable())
4902 return State.Builder.CreateExtractValue(NewLoad, Index);
4903
4904 // For fixed length VF, use shuffle to extract the sub-vectors from the
4905 // wide load.
4906 auto StrideMask =
4907 createStrideMask(Index, InterleaveFactor, State.VF.getFixedValue());
4908 return State.Builder.CreateShuffleVector(NewLoad, StrideMask,
4909 "strided.vec");
4910 };
4911
4912 for (unsigned I = 0, J = 0; I < InterleaveFactor; ++I) {
4913 Instruction *Member = Group->getMember(I);
4914
4915 // Skip the gaps in the group.
4916 if (!Member)
4917 continue;
4918
4919 Value *StridedVec = CreateStridedVector(I);
4920
4921 // If this member has different type, cast the result type.
4922 if (Member->getType() != ScalarTy) {
4923 VectorType *OtherVTy = VectorType::get(Member->getType(), State.VF);
4924 StridedVec =
4925 createBitOrPointerCast(State.Builder, StridedVec, OtherVTy, DL);
4926 }
4927
4928 if (Group->isReverse())
4929 StridedVec = State.Builder.CreateVectorReverse(StridedVec, "reverse");
4930
4931 State.set(VPDefs[J], StridedVec);
4932 ++J;
4933 }
4934 return;
4935 }
4936
4937 // The sub vector type for current instruction.
4938 auto *SubVT = VectorType::get(ScalarTy, State.VF);
4939
4940 // Vectorize the interleaved store group.
4941 Value *MaskForGaps =
4942 createBitMaskForGaps(State.Builder, State.VF.getKnownMinValue(), *Group);
4943 assert(((MaskForGaps != nullptr) == needsMaskForGaps()) &&
4944 "Mismatch between NeedsMaskForGaps and MaskForGaps");
4945 ArrayRef<VPValue *> StoredValues = getStoredValues();
4946 // Collect the stored vector from each member.
4947 SmallVector<Value *, 4> StoredVecs;
4948 unsigned StoredIdx = 0;
4949 for (unsigned i = 0; i < InterleaveFactor; i++) {
4950 assert((Group->getMember(i) || MaskForGaps) &&
4951 "Fail to get a member from an interleaved store group");
4952 Instruction *Member = Group->getMember(i);
4953
4954 // Skip the gaps in the group.
4955 if (!Member) {
4956 Value *Undef = PoisonValue::get(SubVT);
4957 StoredVecs.push_back(Undef);
4958 continue;
4959 }
4960
4961 Value *StoredVec = State.get(StoredValues[StoredIdx]);
4962 ++StoredIdx;
4963
4964 if (Group->isReverse())
4965 StoredVec = State.Builder.CreateVectorReverse(StoredVec, "reverse");
4966
4967 // If this member has different type, cast it to a unified type.
4968
4969 if (StoredVec->getType() != SubVT)
4970 StoredVec = createBitOrPointerCast(State.Builder, StoredVec, SubVT, DL);
4971
4972 StoredVecs.push_back(StoredVec);
4973 }
4974
4975 // Interleave all the smaller vectors into one wider vector.
4976 Value *IVec = interleaveVectors(State.Builder, StoredVecs, "interleaved.vec");
4977 Instruction *NewStoreInstr;
4978 if (BlockInMask || MaskForGaps) {
4979 Value *GroupMask = CreateGroupMask(MaskForGaps);
4980 NewStoreInstr = State.Builder.CreateMaskedStore(
4981 IVec, ResAddr, Group->getAlign(), GroupMask);
4982 } else
4983 NewStoreInstr =
4984 State.Builder.CreateAlignedStore(IVec, ResAddr, Group->getAlign());
4985
4986 applyMetadata(*NewStoreInstr);
4987 // TODO: Also manage existing metadata using VPIRMetadata.
4988 Group->addMetadata(NewStoreInstr);
4989}
4990
4991#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4993 VPSlotTracker &SlotTracker) const {
4995 O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << ", ";
4997 VPValue *Mask = getMask();
4998 if (Mask) {
4999 O << ", ";
5000 Mask->printAsOperand(O, SlotTracker);
5001 }
5002
5003 unsigned OpIdx = 0;
5004 for (unsigned i = 0; i < IG->getFactor(); ++i) {
5005 if (!IG->getMember(i))
5006 continue;
5007 if (getNumStoreOperands() > 0) {
5008 O << "\n" << Indent << " store ";
5009 getOperand(1 + OpIdx)->printAsOperand(O, SlotTracker);
5010 O << " to index " << i;
5011 } else {
5012 O << "\n" << Indent << " ";
5014 O << " = load from index " << i;
5015 }
5016 ++OpIdx;
5017 }
5018}
5019#endif
5020
5022 assert(State.VF.isScalable() &&
5023 "Only support scalable VF for EVL tail-folding.");
5025 "Masking gaps for scalable vectors is not yet supported.");
5027 Instruction *Instr = Group->getInsertPos();
5028
5029 // Prepare for the vector type of the interleaved load/store.
5030 Type *ScalarTy = getLoadStoreType(Instr);
5031 unsigned InterleaveFactor = Group->getFactor();
5032 assert(InterleaveFactor <= 8 &&
5033 "Unsupported deinterleave/interleave factor for scalable vectors");
5034 ElementCount WideVF = State.VF * InterleaveFactor;
5035 auto *VecTy = VectorType::get(ScalarTy, WideVF);
5036
5037 VPValue *Addr = getAddr();
5038 Value *ResAddr = State.get(Addr, VPLane(0));
5039 Value *EVL = State.get(getEVL(), VPLane(0));
5040 Value *InterleaveEVL = State.Builder.CreateMul(
5041 EVL, ConstantInt::get(EVL->getType(), InterleaveFactor), "interleave.evl",
5042 /* NUW= */ true, /* NSW= */ true);
5043 LLVMContext &Ctx = State.Builder.getContext();
5044
5045 Value *GroupMask = nullptr;
5046 if (VPValue *BlockInMask = getMask()) {
5047 SmallVector<Value *> Ops(InterleaveFactor, State.get(BlockInMask));
5048 GroupMask = interleaveVectors(State.Builder, Ops, "interleaved.mask");
5049 } else {
5050 GroupMask =
5051 State.Builder.CreateVectorSplat(WideVF, State.Builder.getTrue());
5052 }
5053
5054 // Vectorize the interleaved load group.
5055 if (isa<LoadInst>(Instr)) {
5056 CallInst *NewLoad = State.Builder.CreateIntrinsicWithoutFolding(
5057 VecTy, Intrinsic::vp_load, {ResAddr, GroupMask, InterleaveEVL}, nullptr,
5058 "wide.vp.load");
5059 NewLoad->addParamAttr(0,
5060 Attribute::getWithAlignment(Ctx, Group->getAlign()));
5061
5062 applyMetadata(*NewLoad);
5063 // TODO: Also manage existing metadata using VPIRMetadata.
5064 Group->addMetadata(NewLoad);
5065
5066 // Scalable vectors cannot use arbitrary shufflevectors (only splats),
5067 // so must use intrinsics to deinterleave.
5068 NewLoad = State.Builder.CreateIntrinsicWithoutFolding(
5069 Intrinsic::getDeinterleaveIntrinsicID(InterleaveFactor),
5070 NewLoad->getType(), NewLoad,
5071 /*FMFSource=*/nullptr, "strided.vec");
5072
5073 const DataLayout &DL = Instr->getDataLayout();
5074 for (unsigned I = 0, J = 0; I < InterleaveFactor; ++I) {
5075 Instruction *Member = Group->getMember(I);
5076 // Skip the gaps in the group.
5077 if (!Member)
5078 continue;
5079
5080 Value *StridedVec = State.Builder.CreateExtractValue(NewLoad, I);
5081 // If this member has different type, cast the result type.
5082 if (Member->getType() != ScalarTy) {
5083 VectorType *OtherVTy = VectorType::get(Member->getType(), State.VF);
5084 StridedVec =
5085 createBitOrPointerCast(State.Builder, StridedVec, OtherVTy, DL);
5086 }
5087
5088 State.set(getVPValue(J), StridedVec);
5089 ++J;
5090 }
5091 return;
5092 } // End for interleaved load.
5093
5094 // The sub vector type for current instruction.
5095 auto *SubVT = VectorType::get(ScalarTy, State.VF);
5096 // Vectorize the interleaved store group.
5097 ArrayRef<VPValue *> StoredValues = getStoredValues();
5098 // Collect the stored vector from each member.
5099 SmallVector<Value *, 4> StoredVecs;
5100 const DataLayout &DL = Instr->getDataLayout();
5101 for (unsigned I = 0, StoredIdx = 0; I < InterleaveFactor; I++) {
5102 Instruction *Member = Group->getMember(I);
5103 // Skip the gaps in the group.
5104 if (!Member) {
5105 StoredVecs.push_back(PoisonValue::get(SubVT));
5106 continue;
5107 }
5108
5109 Value *StoredVec = State.get(StoredValues[StoredIdx]);
5110 // If this member has different type, cast it to a unified type.
5111 if (StoredVec->getType() != SubVT)
5112 StoredVec = createBitOrPointerCast(State.Builder, StoredVec, SubVT, DL);
5113
5114 StoredVecs.push_back(StoredVec);
5115 ++StoredIdx;
5116 }
5117
5118 // Interleave all the smaller vectors into one wider vector.
5119 Value *IVec = interleaveVectors(State.Builder, StoredVecs, "interleaved.vec");
5120 CallInst *NewStore = State.Builder.CreateIntrinsicWithoutFolding(
5121 Type::getVoidTy(Ctx), Intrinsic::vp_store,
5122 {IVec, ResAddr, GroupMask, InterleaveEVL});
5123
5124 NewStore->addParamAttr(1,
5125 Attribute::getWithAlignment(Ctx, Group->getAlign()));
5126
5127 applyMetadata(*NewStore);
5128 // TODO: Also manage existing metadata using VPIRMetadata.
5129 Group->addMetadata(NewStore);
5130}
5131
5132#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5134 VPSlotTracker &SlotTracker) const {
5136 O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << ", ";
5138 O << ", ";
5140 if (VPValue *Mask = getMask()) {
5141 O << ", ";
5142 Mask->printAsOperand(O, SlotTracker);
5143 }
5144
5145 unsigned OpIdx = 0;
5146 for (unsigned i = 0; i < IG->getFactor(); ++i) {
5147 if (!IG->getMember(i))
5148 continue;
5149 if (getNumStoreOperands() > 0) {
5150 O << "\n" << Indent << " vp.store ";
5151 getOperand(2 + OpIdx)->printAsOperand(O, SlotTracker);
5152 O << " to index " << i;
5153 } else {
5154 O << "\n" << Indent << " ";
5156 O << " = vp.load from index " << i;
5157 }
5158 ++OpIdx;
5159 }
5160}
5161#endif
5162
5164 VPCostContext &Ctx) const {
5165 Instruction *InsertPos = getInsertPos();
5166 // Find the VPValue index of the interleave group. We need to skip gaps.
5167 unsigned InsertPosIdx = 0;
5168 for (unsigned Idx = 0; IG->getFactor(); ++Idx)
5169 if (auto *Member = IG->getMember(Idx)) {
5170 if (Member == InsertPos)
5171 break;
5172 InsertPosIdx++;
5173 }
5174 const VPValue *ValV = getNumDefinedValues() > 0
5175 ? getVPValue(InsertPosIdx)
5176 : getStoredValues()[InsertPosIdx];
5177 Type *ValTy = ValV->getScalarType();
5178 auto *VectorTy = cast<VectorType>(toVectorTy(ValTy, VF));
5179 unsigned AS =
5180 cast<PointerType>(getAddr()->getScalarType())->getAddressSpace();
5181
5182 unsigned InterleaveFactor = IG->getFactor();
5183 auto *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
5184
5185 // Holds the indices of existing members in the interleaved group.
5187 for (unsigned IF = 0; IF < InterleaveFactor; IF++)
5188 if (IG->getMember(IF))
5189 Indices.push_back(IF);
5190
5191 // Calculate the cost of the whole interleaved group.
5192 InstructionCost Cost = Ctx.TTI.getInterleavedMemoryOpCost(
5193 InsertPos->getOpcode(), WideVecTy, IG->getFactor(), Indices,
5194 IG->getAlign(), AS, Ctx.CostKind, getMask(), NeedsMaskForGaps);
5195
5196 if (!IG->isReverse())
5197 return Cost;
5198
5199 return Cost + IG->getNumMembers() *
5200 Ctx.TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
5201 VectorTy, VectorTy, Ctx.CostKind, {},
5202 0);
5203}
5204
5207 VPCostContext &Ctx) const {
5208 // The recipe creates a scalar phi, a GEP to increment the induction and
5209 // vector add to compute the vector of pointers.
5210 // TODO: Charge costs for induction increment and vector add as well.
5211 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
5212}
5213
5218
5219#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5221 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
5222 assert((getNumOperands() == 3 || getNumOperands() == 5) &&
5223 "unexpected number of operands");
5224 O << Indent << "EMIT ";
5226 O << " = WIDEN-POINTER-INDUCTION ";
5228 O << ", ";
5230 O << ", ";
5232 if (getNumOperands() == 5) {
5233 O << ", ";
5235 O << ", ";
5237 }
5238}
5239
5241 VPSlotTracker &SlotTracker) const {
5242 O << Indent << "EMIT ";
5244 O << " = EXPAND SCEV " << *Expr;
5245 if (ExpandInIR)
5246 O << " (in IR)";
5247}
5248#endif
5249
5250#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5252 VPSlotTracker &SlotTracker) const {
5253 O << Indent << "EMIT ";
5255 O << " = WIDEN-CANONICAL-INDUCTION";
5256 printFlags(O);
5258}
5259#endif
5260
5262 auto &Builder = State.Builder;
5263 // Create a vector from the initial value.
5264 auto *VectorInit = getStartValue()->getLiveInIRValue();
5265
5266 Type *VecTy = State.VF.isScalar()
5267 ? VectorInit->getType()
5268 : VectorType::get(VectorInit->getType(), State.VF);
5269
5270 BasicBlock *VectorPH =
5271 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
5272 if (State.VF.isVector()) {
5273 auto *IdxTy = Builder.getInt32Ty();
5274 auto *One = ConstantInt::get(IdxTy, 1);
5275 IRBuilder<>::InsertPointGuard Guard(Builder);
5276 Builder.SetInsertPoint(VectorPH->getTerminator());
5277 auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, State.VF);
5278 auto *LastIdx = Builder.CreateSub(RuntimeVF, One);
5279 VectorInit = Builder.CreateInsertElement(
5280 PoisonValue::get(VecTy), VectorInit, LastIdx, "vector.recur.init");
5281 }
5282
5283 // Create a phi node for the new recurrence.
5284 PHINode *Phi = PHINode::Create(VecTy, 2, "vector.recur");
5285 Phi->insertBefore(State.CFG.PrevBB->getFirstInsertionPt());
5286 Phi->addIncoming(VectorInit, VectorPH);
5287 State.set(this, Phi);
5288}
5289
5292 VPCostContext &Ctx) const {
5293 if (VF.isScalar())
5294 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
5295
5296 return 0;
5297}
5298
5299#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5301 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
5302 O << Indent << "FIRST-ORDER-RECURRENCE-PHI ";
5304 O << " = phi ";
5306}
5307#endif
5308
5310 // Reductions do not have to start at zero. They can start with
5311 // any loop invariant values.
5312 VPValue *StartVPV = getStartValue();
5313
5314 // In order to support recurrences we need to be able to vectorize Phi nodes.
5315 // Phi nodes have cycles, so we need to vectorize them in two stages. This is
5316 // stage #1: We create a new vector PHI node with no incoming edges. We'll use
5317 // this value when we vectorize all of the instructions that use the PHI.
5318 BasicBlock *VectorPH =
5319 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
5320 bool ScalarPHI = State.VF.isScalar() || isInLoop();
5321 Value *StartV = State.get(StartVPV, ScalarPHI);
5322 Type *VecTy = StartV->getType();
5323
5324 BasicBlock *HeaderBB = State.CFG.PrevBB;
5325 assert(State.CurrentParentLoop->getHeader() == HeaderBB &&
5326 "recipe must be in the vector loop header");
5327 auto *Phi = PHINode::Create(VecTy, 2, "vec.phi");
5328 Phi->insertBefore(HeaderBB->getFirstInsertionPt());
5329 State.set(this, Phi, isInLoop());
5330
5331 Phi->addIncoming(StartV, VectorPH);
5332}
5333
5334#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5336 VPSlotTracker &SlotTracker) const {
5337 O << Indent << "WIDEN-REDUCTION-PHI ";
5338
5340 O << " = phi (";
5341 printRecurrenceKind(O, Kind);
5342 O << ")";
5343 printFlags(O);
5345 if (getVFScaleFactor() > 1)
5346 O << " (VF scaled by 1/" << getVFScaleFactor() << ")";
5347}
5348#endif
5349
5351 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
5353 "Blend should propagate first lane use");
5354 return vputils::onlyFirstLaneUsed(this);
5355}
5356
5359 VPCostContext &Ctx) const {
5360 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
5361}
5362
5363#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5365 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
5366 O << Indent << "CONDITIONAL-INDUCTION-PHI ";
5367
5369 O << " = phi ";
5371}
5372#endif
5373
5375 executePhiRecipe(this, *this, State, /*IsScalar=*/false, Name);
5376}
5377
5379 VPCostContext &Ctx) const {
5380 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
5381}
5382
5383#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5385 VPSlotTracker &SlotTracker) const {
5386 O << Indent << "WIDEN-PHI ";
5387
5389 O << " = phi ";
5391}
5392#endif
5393
5395 BasicBlock *VectorPH =
5396 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
5397 Value *StartMask = State.get(getOperand(0));
5398 PHINode *Phi =
5399 State.Builder.CreatePHI(StartMask->getType(), 2, "active.lane.mask");
5400 Phi->addIncoming(StartMask, VectorPH);
5401 State.set(this, Phi);
5402}
5403
5404#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5406 VPSlotTracker &SlotTracker) const {
5407 O << Indent << "ACTIVE-LANE-MASK-PHI ";
5408
5410 O << " = phi ";
5412}
5413#endif
5414
5415#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5417 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
5418 O << Indent << "CURRENT-ITERATION-PHI ";
5419
5421 O << " = phi ";
5423}
5424#endif
bool IsScalable
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
static MCDisassembler::DecodeStatus addOperand(MCInst &Inst, const MCOperand &Opnd)
AMDGPU Lower Kernel Arguments
AMDGPU Register Bank Select
This file declares a class to represent arbitrary precision floating point values and provide a varie...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static const Function * getParent(const Value *V)
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
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.
SmallVector< MachineOperand, 4 > 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 AttributeSet getCalleeFnAttrs(const VPInstruction &VPI)
Return the function attributes of the callee of VPI, which must be a call or intrinsic VPInstruction.
static const ConstantFP * getConstantFP(const VPValue *V)
Returns the ConstantFP V wraps, or nullptr if it does not wrap one.
static SmallVector< unsigned > getExtractValueIndices(ArrayRef< VPValue * > Ops)
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 Function * getCalledFunction(ArrayRef< VPValue * > Operands)
For call VPInstruction operands, return the called function.
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:
static const fltSemantics & IEEEdouble()
Definition APFloat.h:305
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 stores enough information to efficiently remove some attributes from an existing AttrBuild...
bool contains(Attribute::AttrKind A) const
Return true if the builder has the specified attribute.
This class holds the attributes for a particular argument, parameter, function, or return value.
Definition Attributes.h:406
bool hasAttributes() const
Return true if attributes exists in this set.
Definition Attributes.h:484
LLVM_ABI bool hasAttribute(Attribute::AttrKind Kind) const
Return true if the attribute exists in this set.
LLVM_ABI std::string getAsString(bool InAttrGrp=false) const
static LLVM_ABI AttributeSet get(LLVMContext &C, const AttrBuilder &B)
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition Attributes.h:125
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
LLVM_ABI IntegerType * getIndexType(LLVMContext &C, unsigned AddressSpace) const
Returns the type of a GEP index in AddressSpace.
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:321
static constexpr ElementCount getScalable(ScalarTy MinVal)
Definition TypeSize.h:309
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:306
constexpr bool isScalar() const
Exactly one element.
Definition TypeSize.h:317
static LLVM_ABI Type * getIndexedType(Type *Agg, ArrayRef< unsigned > Idxs)
Returns the type of the element that would be extracted with an extractvalue instruction with the spe...
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
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:843
Class to represent function types.
unsigned getNumParams() const
Return the number of fixed parameters this function type requires.
Type * getParamType(unsigned i) const
Parameter type accessors.
Type * getReturnType() const
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
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition Function.h:329
bool doesNotThrow() const
Determine if the function cannot unwind.
Definition Function.h:577
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:111
const DataLayout & getDataLayout() const
Get data layout.
Definition IRBuilder.h:182
Value * CreateInsertElement(Type *VecTy, Value *NewElt, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2745
IntegerType * getInt1Ty()
Fetch the type representing a single bit.
Definition IRBuilder.h:513
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2733
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 ...
LoadInst * CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align, const char *Name)
Definition IRBuilder.h:1940
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:1218
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.
LLVM_ABI CallInst * CreateMaskedLoad(Type *Ty, Value *Ptr, Align Alignment, Value *Mask, Value *PassThru=nullptr, const Twine &Name="")
Create a call to Masked Load intrinsic.
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:2811
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
Definition IRBuilder.h:528
Value * CreateExtractVector(Type *DstType, Value *SrcVec, Value *Idx, const Twine &Name="")
Create a call to the vector.extract intrinsic.
Definition IRBuilder.h:1114
Value * CreatePtrAdd(Value *Ptr, Value *Offset, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Definition IRBuilder.h:2094
Value * CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy, const Twine &Name="", MDNode *FPMathTag=nullptr, FMFSource FMFSource={})
Definition IRBuilder.h:2360
void setFastMathFlags(FastMathFlags NewFMF)
Set the fast-math flags to be used with generated fp-math operators.
Definition IRBuilder.h:289
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:2462
ConstantInt * getInt64(uint64_t C)
Get a constant 64-bit value.
Definition IRBuilder.h:476
Value * CreateLogicalAnd(Value *Cond1, Value *Cond2, const Twine &Name="", Instruction *MDFrom=nullptr)
Definition IRBuilder.h:1772
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:471
Value * CreateCmp(CmpInst::Predicate Pred, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2592
Value * CreateNot(Value *V, const Twine &Name="")
Definition IRBuilder.h:1856
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2458
Value * CreateCountTrailingZeroElems(Type *ResTy, Value *Mask, bool ZeroIsPoison=true, const Twine &Name="")
Create a call to llvm.experimental_cttz_elts.
Definition IRBuilder.h:1156
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1441
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNeg=false)
Definition IRBuilder.h:2197
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.
LLVM_ABI CallInst * CreateMaskedStore(Value *Val, Value *Ptr, Align Alignment, Value *Mask)
Create a call to Masked Store intrinsic.
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1424
ConstantInt * getFalse()
Get the constant value for i1 false.
Definition IRBuilder.h:456
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:1733
Value * CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2470
Value * CreateLogicalOr(Value *Cond1, Value *Cond2, const Twine &Name="", Instruction *MDFrom=nullptr)
Definition IRBuilder.h:1780
StoreInst * CreateAlignedStore(Value *Val, Value *Ptr, MaybeAlign Align, bool isVolatile=false)
Definition IRBuilder.h:1959
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
Definition IRBuilder.h:1594
LLVM_ABI Value * CreateStepVector(Type *DstType, const Twine &Name="")
Creates a vector of type DstType with the linear sequence <0, 1, ...>
Value * CreateSExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a SExt or Trunc from the integer value V to DestTy.
Definition IRBuilder.h:2230
Value * CreateInsertVector(Type *DstType, Value *SrcVec, Value *SubVec, Value *Idx, const Twine &Name="")
Create a call to the vector.insert intrinsic.
Definition IRBuilder.h:1128
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1458
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.
LLVM_ABI void dropPoisonGeneratingFlags()
Drops flags that may cause this instruction to evaluate to poison despite having non-poison inputs.
LLVM_ABI void dropPoisonGeneratingAttributes()
Drops attributes that may generate poison.
LLVM_ABI void dropUBImplyingAttrsAndUnknownMetadata(ArrayRef< unsigned > KnownIDs={})
This function drops non-debug unknown metadata (through dropUnknownNonDebugMetadata).
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:76
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:1579
Information for memory intrinsic cost model.
bool doesNotAccessMemory() const
Whether this function accesses no memory.
Definition ModRef.h:246
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.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:28
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.
@ 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
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
unsigned getNumOperands() const
Definition User.h:229
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:4533
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:3098
unsigned getNumIncomingValues() const
Return the number of incoming values, taking into account when normalized the first incoming value wi...
Definition VPlan.h:3093
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:3089
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.
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...
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.
unsigned getNumDefinedValues() const
Returns the number of values defined by the VPDef.
Definition VPlanValue.h:577
VPValue * getVPSingleValue()
Returns the only VPValue defined by the VPDef.
Definition VPlanValue.h:550
VPValue * getVPValue(unsigned I)
Returns the VPValue with index I defined by the VPDef.
Definition VPlanValue.h:562
ArrayRef< VPRecipeValue * > definedValues()
Returns an ArrayRef of the values defined by the VPDef.
Definition VPlanValue.h:572
InductionDescriptor::InductionKind getInductionKind() const
Definition VPlan.h:4340
VPValue * getIndex() const
Definition VPlan.h:4337
VPValue * getStepValue() const
Definition VPlan.h:4338
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:4336
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPExpandSCEVRecipe(const SCEV *Expr, bool ExpandInIR=false)
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:2519
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:2227
void printFnAttrs(raw_ostream &O) const
Print function attributes carried with this object.
void printRetAttrs(raw_ostream &O) const
Print return-value attributes carried with this object.
MemoryEffects getMemoryEffects(AttributeSet CalleeFnAttrs) const
Returns the memory effects of a call with these attributes to a callee with function attributes Calle...
Definition VPlan.h:1293
VPIRAttributes()=default
void intersectAttrs(const VPIRAttributes &Other, LLVMContext &Ctx)
Keep only the attributes valid for both this and Other.
void printParamAttrs(raw_ostream &O, unsigned ArgIdx) const
Print per-arg attributes for argument ArgIdx.
void applyAttrs(CallInst &WideCall) const
Apply the stored attributes to the widened call WideCall.
Definition VPlan.h:1287
Class to record and manage LLVM IR flags.
Definition VPlan.h:683
FastMathFlagsTy FMFs
Definition VPlan.h:775
ReductionFlagsTy ReductionFlags
Definition VPlan.h:777
LLVM_ABI_FOR_TEST bool flagsValidForOpcode(unsigned Opcode) const
Returns true if the set flags are valid for Opcode.
WrapFlagsTy WrapFlags
Definition VPlan.h:769
void printFlags(raw_ostream &O) const
bool hasFastMathFlags() const
Returns true if the recipe has fast-math flags.
Definition VPlan.h:978
static LLVM_ABI_FOR_TEST 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:1033
TruncFlagsTy TruncFlags
Definition VPlan.h:770
CmpInst::Predicate getPredicate() const
Definition VPlan.h:950
LLVM_ABI_FOR_TEST FastMathFlags getFastMathFlagsOrNone() const
ExactFlagsTy ExactFlags
Definition VPlan.h:772
void intersectFlags(const VPIRFlags &Other)
Only keep flags also present in Other.
uint8_t GEPFlagsStorage
Definition VPlan.h:773
GEPNoWrapFlags getGEPNoWrapFlags() const
Definition VPlan.h:968
bool hasPredicate() const
Returns true if the recipe has a comparison predicate.
Definition VPlan.h:973
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:771
FCmpFlagsTy FCmpFlags
Definition VPlan.h:776
NonNegFlagsTy NonNegFlags
Definition VPlan.h:774
bool isReductionInLoop() const
Definition VPlan.h:1039
void applyFlags(Instruction &I) const
Apply the IR flags to I.
Definition VPlan.h:915
uint8_t CmpPredStorage
Definition VPlan.h:768
RecurKind getRecurKind() const
Definition VPlan.h:1027
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:1742
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:1201
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:1322
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPInstruction.
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:1437
@ Intrinsic
Calls a scalar intrinsic. The intrinsic ID is the last operand.
Definition VPlan.h:1449
@ ExtractLane
Extracts a single lane (first operand) from a set of vector operands.
Definition VPlan.h:1427
@ ExitingIVValue
Compute the exiting value of a wide induction after vectorization, that is the value of the last lane...
Definition VPlan.h:1441
@ WideIVStep
Scale the first operand (vector step) by the second operand (scalar-step).
Definition VPlan.h:1445
@ ResumeForEpilogue
Explicit user for values in the main VPlan, used by the epilogue vector loop.
Definition VPlan.h:1431
@ Unpack
Extracts all lanes from its (non-scalable) vector operand.
Definition VPlan.h:1378
@ ReductionStartVector
Start vector for reductions with 3 operands: the original start value, the identity value for the red...
Definition VPlan.h:1423
@ BuildVector
Creates a fixed-width vector containing all operands.
Definition VPlan.h:1373
@ CanonicalIVIncrementForPart
Definition VPlan.h:1358
@ ComputeReductionResult
Reduce the operands to the final reduction result using the operation specified via the operation's V...
Definition VPlan.h:1381
bool hasResult() const
Definition VPlan.h:1543
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:1606
unsigned getOpcode() const
Definition VPlan.h:1525
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.
VPInstruction(unsigned Opcode, ArrayRef< VPValue * > Operands, const VPIRFlags &Flags={}, const VPIRMetadata &MD={}, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="", Type *ResultTy=nullptr, const VPIRAttributes &Attrs={})
bool isVectorToScalar() const
Returns true if this VPInstruction produces a scalar value from a vector, e.g.
VPValue * getMask() const
Returns the mask for the VPInstruction.
Definition VPlan.h:1572
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:1546
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
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:3202
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this recipe.
Instruction * getInsertPos() const
Definition VPlan.h:3206
const InterleaveGroup< Instruction > * getInterleaveGroup() const
Definition VPlan.h:3204
VPValue * getMask() const
Return the mask used by this recipe.
Definition VPlan.h:3196
ArrayRef< VPValue * > getStoredValues() const
Return the VPValues stored by this interleave group.
Definition VPlan.h:3225
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition VPlan.h:3190
VPValue * getEVL() const
The VPValue of the explicit vector length.
Definition VPlan.h:3299
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:3312
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:3262
void execute(VPTransformState &State) override
Generate the wide load or store, and shuffles.
In what follows, the term "input IR" refers to code that is fed into the vectorizer whereas the term ...
static VPLane getLastLaneForVF(const ElementCount &VF)
static VPLane getLaneFromEnd(const ElementCount &VF, unsigned Offset)
static VPLane getFirstLane()
Helper type to provide functions to access incoming values and blocks for phi-like recipes.
Definition VPlan.h:1621
virtual const VPRecipeBase * getAsRecipe() const =0
Return a VPRecipeBase* to the current object.
LLVM_ABI_FOR_TEST 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:1671
VPValue * getIncomingValue(unsigned Idx) const
Returns the incoming VPValue with index Idx.
Definition VPlan.h:1630
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:402
bool mayReadFromMemory() const
Returns true if the recipe may read from memory.
void moveBefore(RecipeListTy::iterator I)
Unlink this recipe and insert it before I.
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:4938
RecipeListTy::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void dump() const
Dump the recipe to stderr (for debugging).
Definition VPlan.cpp:110
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:515
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...
DebugLoc getDebugLoc() const
Returns the debug location of the recipe.
Definition VPlan.h:547
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.
VPRecipeBase(VPRecipeTy SC, ArrayRef< VPValue * > Operands, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:462
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:349
friend class VPValue
Definition VPlanValue.h:328
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:3473
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:2946
bool isInLoop() const
Returns true if the phi is part of an in-loop reduction.
Definition VPlan.h:2965
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:3412
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:3425
VPValue * getCondOp() const
The VPValue of the condition for the block.
Definition VPlan.h:3427
RecurKind getRecurrenceKind() const
Return the recurrence kind for the in-loop reduction.
Definition VPlan.h:3408
bool isPartialReduction() const
Returns true if the reduction outputs a vector with a scaled down VF.
Definition VPlan.h:3414
VPValue * getChainOp() const
The VPValue of the scalar Chain being accumulated.
Definition VPlan.h:3423
bool isInLoop() const
Returns true if the reduction is in-loop.
Definition VPlan.h:3418
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:4764
bool isReplicator() const
An indicator whether this region is to generate multiple replicated instances of output IR correspond...
Definition VPlan.h:4840
const VPBranchOnMaskRecipe * getEntryBranchOnMask() const
Return the VPBranchOnMaskRecipe from the entry block of this replicating region.
Definition VPlan.cpp:707
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:3552
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:3590
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:4395
VPValue * getStartIndex() const
Return the StartIndex, or null if known to be zero, valid only after unrolling.
Definition VPlan.h:4403
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:605
Instruction * getUnderlyingInstr()
Returns the underlying instruction.
Definition VPlan.h:668
VPSingleDefRecipe(VPRecipeTy SC, ArrayRef< VPValue * > Operands, Type *ResultTy, Value *UV=nullptr, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:607
LLVM_DUMP_METHOD void dump() const
Print this VPSingleDefRecipe to dbgs() (for debugging).
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:212
This class augments VPValue with operands which provide the inverse def-use edges from VPValue's user...
Definition VPlanValue.h:396
void printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const
Print the operands to O.
Definition VPlan.cpp:1521
operand_range operands()
Definition VPlanValue.h:472
unsigned getNumOperands() const
Definition VPlanValue.h:436
VPValue * getOperand(unsigned N) const
Definition VPlanValue.h:437
bool operands_empty() const
Definition VPlanValue.h:476
VPValue * getLastOperand() const
Returns the last operand.
Definition VPlanValue.h:443
void addOperand(VPValue *Operand)
Definition VPlanValue.h:422
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:142
Value * getLiveInIRValue() const
Return the underlying IR value for a VPIRValue.
Definition VPlan.cpp:136
bool isDefinedOutsideLoopRegions() const
Returns true if the VPValue is defined outside any loop.
Definition VPlan.cpp:1473
VPRecipeBase * getDefiningRecipe()
Returns the recipe defining this VPValue or nullptr if it is not defined by a recipe,...
Definition VPlan.cpp:123
void printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const
Definition VPlan.cpp:1517
Value * getUnderlyingValue() const
Return the underlying Value attached to this VPValue.
Definition VPlanValue.h:75
void setUnderlyingValue(Value *Val)
Definition VPlanValue.h:204
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:2338
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:2335
int64_t getStride() const
Definition VPlan.h:2336
void materializeOffset(unsigned Part=0)
Adds the offset operand to the recipe.
VPValue * getStride() const
Definition VPlan.h:2412
Type * getSourceElementType() const
Definition VPlan.h:2427
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:2414
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:2179
Function * getCalledScalarFunction() const
Definition VPlan.h:2175
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:1935
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Produce widened copies of the cast.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenCastRecipe.
void execute(VPTransformState &State) override
Generate the gep nodes.
Type * getSourceElementType() const
Definition VPlan.h:2292
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:2597
const InductionDescriptor & getInductionDescriptor() const
Returns the induction descriptor for the recipe.
Definition VPlan.h:2614
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenIntOrFpInductionRecipe.
bool isTruncated() const
Returns true if this induction is evaluated in a narrower type than the start value.
Definition VPlan.h:2696
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:2050
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.
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the VPUser only uses the first lane of operand Op.
void execute(VPTransformState &State) override
Produce a widened version of the vector intrinsic.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this vector intrinsic.
static InstructionCost computeMemIntrinsicCost(Intrinsic::ID IID, Type *Ty, bool IsMasked, Align Alignment, VPCostContext &Ctx)
Helper function for computing the cost of vector memory intrinsic.
Type * getAccessType(ElementCount VF) const
Returns the data type of the memory access at VF.
void execute(VPTransformState &State) override
Produce a widened version of the vector memory intrinsic.
unsigned getAddrOpIdx() const
Returns the address operand index of the VPWidenMemIntrinsicRecipe.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this vector memory intrinsic.
VPValue * getMask() const
Returns the mask of a predicated VPWidenMemIntrinsicRecipe.
bool IsMasked
Whether the memory access is masked.
Definition VPlan.h:3857
bool isConsecutive() const
Return whether the loaded-from / stored-to addresses are consecutive.
Definition VPlan.h:3882
Instruction & Ingredient
Definition VPlan.h:3848
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const
Return the cost of this VPWidenMemoryRecipe.
bool Consecutive
Whether the accessed addresses are consecutive.
Definition VPlan.h:3854
VPValue * getMask() const
Return the mask used by this recipe.
Definition VPlan.h:3892
Align Alignment
Alignment information for this memory access.
Definition VPlan.h:3851
virtual VPRecipeBase * getAsRecipe()=0
Return a VPRecipeBase* to the current object.
Align getAlign() const
Returns the alignment of the memory access.
Definition VPlan.h:3899
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition VPlan.h:3885
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:1877
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition VPlan.h:4951
const DataLayout & getDataLayout() const
Definition VPlan.h:5152
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:5258
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:389
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
LLVM_ABI void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
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:314
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.
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Type * getElementType() const
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:166
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:253
self_iterator getIterator()
Definition ilist_node.h:123
typename base_list_type::iterator iterator
Definition ilist.h:121
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
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:83
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.
auto m_ZExtOrTrunc(const Op0_t &Op0)
int_pred_ty< is_zero_int, 1 > m_False()
auto m_VPValue()
Match an arbitrary VPValue and ignore it.
VPInstruction_match< VPInstruction::ExplicitVectorLength, Op0_t > m_EVL(const Op0_t &Op0)
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)
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
BranchProbability getExecutionProbability(BlockFrequency Freq)
Returns Freq as a BranchProbability, relative to the full mass.
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 by all users.
Intrinsic::ID getIntrinsicID(const Ty *R)
Return the intrinsic ID underlying a call.
Definition VPlanUtils.h:98
bool onlyFirstLaneUsed(const VPValue *Def)
Returns true if only the first lane of Def is used by all users.
bool propagatesFirstLaneUse(const VPUser *U, const VPValue *Op)
Returns true if checking whether U uses the first lane of Op requires recursively checking Op's users...
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.
LLVM_ABI_FOR_TEST 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
LLVM_ABI std::optional< unsigned > getVectorStoreIntrinsicDataArgIdx(Intrinsic::ID ID)
Returns the argument index of the data value of the vector store intrinsic ID, or std::nullopt if the...
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.
VPBuilderBase<> VPBuilder
Definition VPlan.h:66
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
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:373
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
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.
LLVM_ABI std::optional< unsigned > getVectorMemoryIntrinsicPointerArgIdx(Intrinsic::ID ID)
Returns the argument index of the pointer parameter for the vector memory intrinsic ID,...
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 std::optional< unsigned > getVectorIntrinsicMaskArgIdx(Intrinsic::ID ID)
Returns the argument index of the mask for the vector intrinsic ID, or std::nullopt if the intrinsic ...
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
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
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
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:82
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:1933
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:1140
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:1800
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
PHINode & getIRPhi() const
Definition VPlan.h:1813
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
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.
InstructionCost getCostForRecipeWithOpcode(unsigned Opcode, ElementCount VF, VPCostContext &Ctx) const
Compute the cost for this recipe for VF, using Opcode and Ctx.
VPRecipeWithIRFlags(VPRecipeTy SC, ArrayRef< VPValue * > Operands, Type *ResultTy, const VPIRFlags &Flags, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:1090
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
IRBuilderBase & Builder
Hold a reference to the IRBuilder used to generate output IR code.
Value * get(const VPValue *Def, bool NeedsSingleScalar=false)
Get the generated vector Value for a given VPValue Def if NeedsSingleScalar is false,...
Definition VPlan.cpp:270
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:3986
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:4089
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:4092
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:4036