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