LLVM 24.0.0git
VPlanRecipes.cpp
Go to the documentation of this file.
1//===- VPlanRecipes.cpp - Implementations for VPlan recipes ---------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// This file contains implementations for different VPlan recipes.
11///
12//===----------------------------------------------------------------------===//
13
15#include "VPlan.h"
16#include "VPlanHelpers.h"
17#include "VPlanPatternMatch.h"
18#include "VPlanUtils.h"
19#include "llvm/ADT/APFloat.h"
20#include "llvm/ADT/STLExtras.h"
23#include "llvm/ADT/Twine.h"
29#include "llvm/IR/BasicBlock.h"
30#include "llvm/IR/IRBuilder.h"
31#include "llvm/IR/Instruction.h"
33#include "llvm/IR/Intrinsics.h"
35#include "llvm/IR/Type.h"
36#include "llvm/IR/Value.h"
39#include "llvm/Support/Debug.h"
43#include <cassert>
44
45using namespace llvm;
46using namespace llvm::VPlanPatternMatch;
47
48#define LV_NAME "loop-vectorize"
49#define DEBUG_TYPE LV_NAME
50
51namespace llvm {
53} // namespace llvm
54
56 switch (getVPRecipeID()) {
57 case VPExpressionSC:
58 return cast<VPExpressionRecipe>(this)->mayReadOrWriteMemory();
59 case VPInstructionSC: {
60 auto *VPI = cast<VPInstruction>(this);
61 // Loads read from memory but don't write to memory.
62 if (VPI->getOpcode() == Instruction::Load ||
63 VPI->getOpcode() == VPInstruction::WideVectorLoad)
64 return false;
65 return VPI->opcodeMayReadOrWriteFromMemory();
66 }
67 case VPInterleaveEVLSC:
68 case VPInterleaveSC:
69 return cast<VPInterleaveBase>(this)->getNumStoreOperands() > 0;
70 case VPWidenStoreEVLSC:
71 case VPWidenStoreSC:
72 return true;
73 case VPReplicateSC:
74 return cast<Instruction>(getVPSingleValue()->getUnderlyingValue())
75 ->mayWriteToMemory();
76 case VPWidenCallSC:
77 return !cast<VPWidenCallRecipe>(this)
78 ->getCalledScalarFunction()
79 ->onlyReadsMemory();
80 case VPWidenMemIntrinsicSC:
81 case VPWidenIntrinsicSC:
82 return cast<VPWidenIntrinsicRecipe>(this)->mayWriteToMemory();
83 case VPActiveLaneMaskPHISC:
84 case VPCurrentIterationPHISC:
85 case VPBranchOnMaskSC:
86 case VPDerivedIVSC:
87 case VPFirstOrderRecurrencePHISC:
88 case VPReductionPHISC:
89 case VPScalarIVStepsSC:
90 case VPPredInstPHISC:
91 case VPExpandSCEVSC:
92 return false;
93 case VPBlendSC:
94 case VPReductionEVLSC:
95 case VPReductionSC:
96 case VPVectorPointerSC:
97 case VPWidenCanonicalIVSC:
98 case VPWidenCastSC:
99 case VPWidenGEPSC:
100 case VPWidenIntOrFpInductionSC:
101 case VPWidenLoadEVLSC:
102 case VPWidenLoadSC:
103 case VPWidenPHISC:
104 case VPWidenPointerInductionSC:
105 case VPWidenSC: {
106 const Instruction *I =
107 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
108 (void)I;
109 assert((!I || !I->mayWriteToMemory()) &&
110 "underlying instruction may write to memory");
111 return false;
112 }
113 default:
114 return true;
115 }
116}
117
119 switch (getVPRecipeID()) {
120 case VPExpressionSC:
121 return cast<VPExpressionRecipe>(this)->mayReadOrWriteMemory();
122 case VPInstructionSC: {
123 auto *VPI = cast<VPInstruction>(this);
124 // Stores write to memory but don't read from memory.
125 if (VPI->getOpcode() == VPInstruction::WideVectorStore)
126 return false;
127 return VPI->opcodeMayReadOrWriteFromMemory();
128 }
129 case VPWidenLoadEVLSC:
130 case VPWidenLoadSC:
131 return true;
132 case VPReplicateSC:
133 return cast<Instruction>(getVPSingleValue()->getUnderlyingValue())
134 ->mayReadFromMemory();
135 case VPWidenCallSC:
136 return !cast<VPWidenCallRecipe>(this)
137 ->getCalledScalarFunction()
138 ->onlyWritesMemory();
139 case VPWidenMemIntrinsicSC:
140 case VPWidenIntrinsicSC:
141 return cast<VPWidenIntrinsicRecipe>(this)->mayReadFromMemory();
142 case VPBranchOnMaskSC:
143 case VPDerivedIVSC:
144 case VPCurrentIterationPHISC:
145 case VPFirstOrderRecurrencePHISC:
146 case VPReductionPHISC:
147 case VPPredInstPHISC:
148 case VPScalarIVStepsSC:
149 case VPWidenStoreEVLSC:
150 case VPWidenStoreSC:
151 case VPExpandSCEVSC:
152 return false;
153 case VPBlendSC:
154 case VPReductionEVLSC:
155 case VPReductionSC:
156 case VPVectorPointerSC:
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 (ForceTargetInstructionCost.getNumOccurrences() > 0 &&
329 RecipeCost.isValid()) {
330 // VPDerivedIVRecipe and VPScalarIVStepsRecipe never have underlying
331 // instructions.
334 else
335 RecipeCost = InstructionCost(0);
336 }
337 }
338
339 LLVM_DEBUG({
340 dbgs() << "Cost of " << RecipeCost << " for VF " << VF << ": ";
341 if (VPSlotTracker *SlotTracker = Ctx.getSlotTracker()) {
342 print(dbgs(), "", *SlotTracker);
343 dbgs() << "\n";
344 } else {
345 dump();
346 }
347 });
348 return RecipeCost;
349}
350
352 VPCostContext &Ctx) const {
353 llvm_unreachable("subclasses should implement computeCost");
354}
355
357 return (getVPRecipeID() >= VPFirstPHISC && getVPRecipeID() <= VPLastPHISC) ||
359}
360
362 assert(OpType == Other.OpType && "OpType must match");
363 switch (OpType) {
364 case OperationType::OverflowingBinOp:
365 WrapFlags.HasNUW &= Other.WrapFlags.HasNUW;
366 WrapFlags.HasNSW &= Other.WrapFlags.HasNSW;
367 break;
368 case OperationType::Trunc:
369 TruncFlags.HasNUW &= Other.TruncFlags.HasNUW;
370 TruncFlags.HasNSW &= Other.TruncFlags.HasNSW;
371 break;
372 case OperationType::DisjointOp:
373 DisjointFlags.IsDisjoint &= Other.DisjointFlags.IsDisjoint;
374 break;
375 case OperationType::PossiblyExactOp:
376 ExactFlags.IsExact &= Other.ExactFlags.IsExact;
377 break;
378 case OperationType::GEPOp:
379 GEPFlagsStorage &= Other.GEPFlagsStorage;
380 break;
381 case OperationType::FPMathOp:
382 case OperationType::FCmp:
383 assert((OpType != OperationType::FCmp ||
384 FCmpFlags.CmpPredStorage == Other.FCmpFlags.CmpPredStorage) &&
385 "Cannot drop CmpPredicate");
386 getFMFsRef() = getFastMathFlagsOrNone() & Other.getFastMathFlagsOrNone();
387 break;
388 case OperationType::NonNegOp:
389 NonNegFlags.NonNeg &= Other.NonNegFlags.NonNeg;
390 break;
391 case OperationType::Cmp:
392 assert(CmpPredStorage == Other.CmpPredStorage &&
393 "Cannot drop CmpPredicate");
394 break;
395 case OperationType::ReductionOp:
396 assert(ReductionFlags.Kind == Other.ReductionFlags.Kind &&
397 "Cannot change RecurKind");
398 assert(ReductionFlags.IsOrdered == Other.ReductionFlags.IsOrdered &&
399 "Cannot change IsOrdered");
400 assert(ReductionFlags.IsInLoop == Other.ReductionFlags.IsInLoop &&
401 "Cannot change IsInLoop");
402 getFMFsRef() = getFastMathFlagsOrNone() & Other.getFastMathFlagsOrNone();
403 break;
404 case OperationType::Other:
405 break;
406 }
407}
408
410 if (!hasFastMathFlags())
411 return {};
412 const FastMathFlagsTy &F = getFMFsRef();
413 FastMathFlags Res;
414 Res.setAllowReassoc(F.AllowReassoc);
415 Res.setNoNaNs(F.NoNaNs);
416 Res.setNoInfs(F.NoInfs);
417 Res.setNoSignedZeros(F.NoSignedZeros);
418 Res.setAllowReciprocal(F.AllowReciprocal);
419 Res.setAllowContract(F.AllowContract);
420 Res.setApproxFunc(F.ApproxFunc);
421 return Res;
422}
423
424#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
426
427void VPRecipeBase::print(raw_ostream &O, const Twine &Indent,
428 VPSlotTracker &SlotTracker) const {
429 printRecipe(O, Indent, SlotTracker);
430 if (auto DL = getDebugLoc()) {
431 O << ", !dbg ";
432 DL.print(O);
433 }
434
435 if (auto *Metadata = dyn_cast<VPIRMetadata>(this))
437}
438#endif
439
441 : VPSingleDefRecipe(VPRecipeBase::VPExpandSCEVSC, {}, Expr->getType()),
442 Expr(Expr) {}
443
444/// For call VPInstruction operands, return the operand index of the called
445/// function. The function is either the last operand (for unmasked calls) or
446/// the second-to-last operand (for masked calls).
448 unsigned NumOps = Operands.size();
449 auto *LastOp = dyn_cast<VPIRValue>(Operands[NumOps - 1]);
450 if (LastOp && isa<Function>(LastOp->getValue()))
451 return NumOps - 1;
453 "expected function operand");
454 return NumOps - 2;
455}
456
457/// For call VPInstruction operands, return the called function.
462
468
471 assert(!Operands.empty() &&
472 "zero-operand VPInstruction opcodes must pass explicit ResultTy");
473 // Assert operand \p Idx (if present and typed) has type \p ExpectedTy.
474 [[maybe_unused]] auto AssertOperandType = [&Operands](unsigned Idx,
475 Type *ExpectedTy) {
476 if (!ExpectedTy || Operands.size() <= Idx)
477 return;
478 [[maybe_unused]] Type *OpTy = Operands[Idx]->getScalarType();
479 assert((!OpTy || OpTy == ExpectedTy) &&
480 "different types inferred for different operands");
481 };
482
483 Type *Op0Ty = Operands[0]->getScalarType();
484 LLVMContext &Ctx = Op0Ty->getContext();
485 switch (Opcode) {
487 assert(Op0Ty->isIntegerTy(1) && "expected bool condition");
488 return Type::getVoidTy(Ctx);
490 assert(Op0Ty->isIntegerTy(1) && "expected bool condition");
491 AssertOperandType(1, IntegerType::get(Ctx, 1));
492 return Type::getVoidTy(Ctx);
494 assert(Op0Ty->isIntegerTy() && "expected integer operand");
495 AssertOperandType(1, Op0Ty);
496 return Type::getVoidTy(Ctx);
498 assert(Op0Ty->isIntegerTy() && "expected integer operand");
499 for (unsigned Idx = 1; Idx != Operands.size(); ++Idx)
500 AssertOperandType(Idx, Op0Ty);
501 return Op0Ty;
502 case Instruction::Switch:
503 for (unsigned Idx = 1; Idx != Operands.size(); ++Idx)
504 AssertOperandType(Idx, Op0Ty);
505 return Type::getVoidTy(Ctx);
507 case Instruction::Store:
508 return Type::getVoidTy(Ctx);
509 case Instruction::ICmp:
510 assert(Op0Ty->isIntOrPtrTy() && "expected integer or pointer operand");
511 AssertOperandType(1, Op0Ty);
512 return IntegerType::get(Ctx, 1);
513 case Instruction::FCmp:
514 assert(Op0Ty->isFloatingPointTy() && "expected floating-point operand");
515 AssertOperandType(1, Op0Ty);
516 return IntegerType::get(Ctx, 1);
519 assert(Op0Ty->isIntegerTy() && "expected integer operand");
520 AssertOperandType(1, Op0Ty);
521 return IntegerType::get(Ctx, 1);
523 assert(Op0Ty->isIntegerTy(1) && "expected bool operand");
524 return IntegerType::get(Ctx, 1);
527 assert(Op0Ty->isIntegerTy(1) && "expected bool operand");
528 AssertOperandType(1, Op0Ty);
529 return IntegerType::get(Ctx, 1);
531 assert(Op0Ty->isIntegerTy(1) && "expected bool operand");
532 for (unsigned Idx = 1; Idx != Operands.size(); ++Idx)
533 AssertOperandType(Idx, Op0Ty);
534 return IntegerType::get(Ctx, 1);
536 assert(Op0Ty->isIntegerTy() && "expected integer operand");
537 return IntegerType::get(Ctx, 32);
538 case Instruction::Select: {
539 assert((!Op0Ty || Op0Ty->isIntegerTy(1)) &&
540 "select condition must be bool");
541 Type *Op1Ty = Operands[1]->getScalarType();
542 AssertOperandType(2, Op1Ty);
543 return Op1Ty;
544 }
545 case Instruction::InsertElement:
546 // The inserted scalar (operand 1) must match the vector element type;
547 // operand 2 must be an integer.
548 AssertOperandType(1, Op0Ty);
549 assert(Operands[2]->getScalarType()->isIntegerTy() &&
550 "expected integer operand");
551 return Op0Ty;
553 // The start value and the identity value (operands 0 and 1) fill the same
554 // vector and must match in type; operand 2 is the scaling factor.
555 AssertOperandType(1, Op0Ty);
556 return Op0Ty;
558 assert(Operands.size() >= 2 && "ExtractLane requires a lane operand and "
559 "at least one source vector operand");
560 // Operand 0 is the lane index, used for integer arithmetic.
561 assert(Op0Ty->isIntegerTy() && "expected integer operand");
562 Type *Op1Ty = Operands[1]->getScalarType();
563 for (unsigned Idx = 2; Idx != Operands.size(); ++Idx)
564 AssertOperandType(Idx, Op1Ty);
565 return Op1Ty;
566 }
569 assert(Operands[0]->getScalarType()->isPointerTy() &&
570 "expected pointer operand");
571 assert(Operands[1]->getScalarType()->isIntegerTy() &&
572 "expected integer operand");
573 return Op0Ty;
574 case Instruction::ExtractValue:
582 case Instruction::Load:
583 case Instruction::Alloca:
584 llvm_unreachable("type must be passed explicitly");
585 case Instruction::Call:
587 default:
588 if (Instruction::isCast(Opcode))
589 llvm_unreachable("type must be passed explicitly");
590 break;
591 }
592
593 // Opcodes that require all operands to share the same scalar type as the
594 // result.
595 bool AllOperandsSameType =
596 Instruction::isBinaryOp(Opcode) ||
601 Opcode);
602 if (AllOperandsSameType)
603 for (unsigned Idx = 1; Idx != Operands.size(); ++Idx)
604 AssertOperandType(Idx, Op0Ty);
605
606 return Op0Ty;
607}
608
611 unsigned Opcode = I->getOpcode();
612 if (Instruction::isCast(Opcode) ||
613 is_contained(ArrayRef<unsigned>({Instruction::Load, Instruction::Alloca}),
614 Opcode))
615 return I->getType();
617}
618
620 const VPIRFlags &Flags, const VPIRMetadata &MD,
621 DebugLoc DL, const Twine &Name, Type *ResultTy)
623 VPRecipeBase::VPInstructionSC, Operands,
624 ResultTy ? ResultTy
626 Flags, DL),
627 VPIRMetadata(MD), Opcode(Opcode), Name(Name.str()) {
629 "Set flags not supported for the provided opcode");
631 "Opcode requires specific flags to be set");
635 "number of operands does not match opcode");
636}
637
639 if (Instruction::isUnaryOp(Opcode) || Instruction::isCast(Opcode))
640 return 1;
641
642 if (Instruction::isBinaryOp(Opcode))
643 return 2;
644
645 switch (Opcode) {
648 return 0;
649 case Instruction::Alloca:
650 case Instruction::Freeze:
651 case Instruction::Load:
664 return 1;
665 case Instruction::ICmp:
666 case Instruction::FCmp:
667 case Instruction::ExtractElement:
668 case Instruction::Store:
680 return 2;
681 case Instruction::InsertElement:
682 case Instruction::Select:
686 return 3;
688 return 4;
689 case Instruction::Call:
690 return getCalledFnOperandIndex(operands()) + 1;
691 case Instruction::GetElementPtr:
692 case Instruction::PHI:
693 case Instruction::Switch:
694 case Instruction::AtomicRMW:
695 case Instruction::AtomicCmpXchg:
696 case Instruction::ExtractValue:
697 case Instruction::Fence:
709 // Cannot determine the number of operands from the opcode.
710 return -1u;
711 }
712 llvm_unreachable("all cases should be handled above");
713}
714
716 return Opcode == VPInstruction::Unpack ||
718}
719
720bool VPInstruction::doesGenerateSingleScalar() const {
722 return true;
723 switch (Opcode) {
724 case Instruction::Freeze:
725 case Instruction::ICmp:
726 case Instruction::PHI:
727 case Instruction::Select:
736 return vputils::onlyFirstLaneUsed(this);
737 default:
739 }
740}
741
743 if (Kind == RecurKind::Sub)
744 return Instruction::Add;
745 if (Kind == RecurKind::FSub)
746 return Instruction::FAdd;
747 llvm_unreachable("RecurKind should be Sub/FSub.");
748}
749
750Value *VPInstruction::generate(VPTransformState &State,
751 bool GenerateSingleScalar) {
752 IRBuilderBase &Builder = State.Builder;
753
755 Value *A = State.get(getOperand(0), GenerateSingleScalar);
756 Value *B = State.get(getOperand(1), GenerateSingleScalar);
757 auto *Res =
758 Builder.CreateBinOp((Instruction::BinaryOps)getOpcode(), A, B, Name);
759 if (auto *I = dyn_cast<Instruction>(Res))
760 applyFlags(*I);
761 return Res;
762 }
764 Value *Op = State.get(getOperand(0), VPLane(0));
766 getScalarType());
767 if (auto *CastOp = dyn_cast<Instruction>(Res)) {
768 applyFlags(*CastOp);
769 applyMetadata(*CastOp);
770 }
771 return Res;
772 }
773
774 switch (getOpcode()) {
775 case VPInstruction::Not: {
776 Value *A = State.get(getOperand(0), GenerateSingleScalar);
777 return Builder.CreateNot(A, Name);
778 }
780 // TODO: Use IsSingleScalar to produce a scalar value.
781 Value *A = State.get(getOperand(0));
782 Value *B = State.get(getOperand(1));
783 return Builder.CreateLogicalAnd(A, B, Name);
784 }
786 // TODO: Use IsSingleScalar to produce a scalar value.
787 Value *A = State.get(getOperand(0));
788 Value *B = State.get(getOperand(1));
789 return Builder.CreateLogicalOr(A, B, Name);
790 }
791 case Instruction::ExtractElement: {
792 assert(GenerateSingleScalar &&
793 "Can only generate first lane for ExtractElement");
794 assert(State.VF.isVector() && "Only extract elements from vectors");
795 if (auto *Idx = dyn_cast<VPConstantInt>(getOperand(1)))
796 return State.get(getOperand(0), VPLane(Idx->getZExtValue()));
797 Value *Vec = State.get(getOperand(0));
798 Value *Idx = State.get(getOperand(1), /*NeedsSingleScalar=*/true);
799 return Builder.CreateExtractElement(Vec, Idx, Name);
800 }
801 case Instruction::InsertElement: {
802 assert(!GenerateSingleScalar &&
803 "Cannot generate scalar value for InsertElement");
804 assert(State.VF.isVector() && "Can only insert elements into vectors");
805 Value *Vec = State.get(getOperand(0), /*NeedsSingleScalar=*/false);
806 Value *Elt = State.get(getOperand(1), /*NeedsSingleScalar=*/true);
807 Value *Idx = State.get(getOperand(2), /*NeedsSingleScalar=*/true);
808 return Builder.CreateInsertElement(Vec, Elt, Idx, Name);
809 }
810 case Instruction::Freeze: {
811 Value *Op = State.get(getOperand(0), GenerateSingleScalar);
812 return Builder.CreateFreeze(Op, Name);
813 }
814 case Instruction::FCmp:
815 case Instruction::ICmp: {
816 Value *A = State.get(getOperand(0), GenerateSingleScalar);
817 Value *B = State.get(getOperand(1), GenerateSingleScalar);
818 return Builder.CreateCmp(getPredicate(), A, B, Name);
819 }
820 case Instruction::PHI: {
821 llvm_unreachable("should be handled by VPPhi::execute");
822 }
823 case Instruction::Select: {
824 Value *Cond =
825 State.get(getOperand(0), GenerateSingleScalar ||
827 Value *Op1 = State.get(getOperand(1), GenerateSingleScalar);
828 Value *Op2 = State.get(getOperand(2), GenerateSingleScalar);
829 Value *Sel =
830 Builder.CreateSelectFMF(Cond, Op1, Op2, getFastMathFlagsOrNone(), Name);
831 if (auto *I = dyn_cast<Instruction>(Sel))
833 return Sel;
834 }
837 // Can produce either a scalar value as a icmp of a phi, or a vector value,
838 // as a get.active.lane.mask intrinsic.
839 // Get first lane of vector induction variable.
840 Value *VIVElem0 = State.get(getOperand(0), VPLane(0));
841 // Get the original loop tripcount.
842 Value *ScalarTC = State.get(getOperand(1), VPLane(0));
843
844 uint64_t Multiplier =
846 ? cast<VPConstantInt>(getOperand(2))->getZExtValue()
847 : 1;
848
849 // If this part of the active lane mask is scalar, generate the CMP directly
850 // to avoid unnecessary extracts.
851 if (State.VF.isScalar() && Multiplier == 1)
852 return Builder.CreateCmp(CmpInst::Predicate::ICMP_ULT, VIVElem0, ScalarTC,
853 Name);
854
855 auto *PredTy = VectorType::get(Builder.getInt1Ty(), State.VF * Multiplier);
856 return Builder.CreateIntrinsic(Intrinsic::get_active_lane_mask,
857 {PredTy, ScalarTC->getType()},
858 {VIVElem0, ScalarTC}, nullptr, Name);
859 }
861 assert(GenerateSingleScalar &&
862 "Can only generate first lane for NumActiveLanes");
863 Value *Op = State.get(getOperand(0));
864 auto *VecTy = cast<VectorType>(Op->getType());
865 assert(VecTy->getScalarSizeInBits() == 1 &&
866 "NumActiveLanes only implemented for i1 vectors");
867
868 Type *Ty = getScalarType();
869 Value *ZExt = Builder.CreateCast(
870 Instruction::ZExt, Op, VectorType::get(Ty, VecTy->getElementCount()));
871 Value *NumActive =
872 Builder.CreateUnaryIntrinsic(Intrinsic::vector_reduce_add, ZExt);
873 return NumActive;
874 }
876 // Generate code to combine the previous and current values in vector v3.
877 //
878 // vector.ph:
879 // v_init = vector(..., ..., ..., a[-1])
880 // br vector.body
881 //
882 // vector.body
883 // i = phi [0, vector.ph], [i+4, vector.body]
884 // v1 = phi [v_init, vector.ph], [v2, vector.body]
885 // v2 = a[i, i+1, i+2, i+3];
886 // v3 = vector(v1(3), v2(0, 1, 2))
887
888 auto *V1 = State.get(getOperand(0));
889 if (!V1->getType()->isVectorTy())
890 return V1;
891 Value *V2 = State.get(getOperand(1));
892 return Builder.CreateVectorSpliceRight(V1, V2, 1, Name);
893 }
895 // TODO: Restructure this code with an explicit remainder loop, vsetvli can
896 // be outside of the main loop.
897 assert(GenerateSingleScalar &&
898 "Can only generate first lane for ExplicitVectorLength");
899 Value *AVL = State.get(getOperand(0), /*NeedsSingleScalar=*/true);
900 // Compute EVL
901 assert(AVL->getType()->isIntegerTy() &&
902 "Requested vector length should be an integer.");
903
904 assert(State.VF.isScalable() && "Expected scalable vector factor.");
905 Value *VFArg = Builder.getInt32(State.VF.getKnownMinValue());
906
907 Value *EVL = Builder.CreateIntrinsic(
908 Builder.getInt32Ty(), Intrinsic::experimental_get_vector_length,
909 {AVL, VFArg, Builder.getTrue()});
910 return EVL;
911 }
913 assert(GenerateSingleScalar &&
914 "Can only generate first lane for BranchOnCond");
915 Value *Cond = State.get(getOperand(0), VPLane(0));
916 // Replace the temporary unreachable terminator with a new conditional
917 // branch, hooking it up to backward destination for latch blocks now, and
918 // to forward destination(s) later when they are created.
919 // Second successor may be backwards - iff it is already in VPBB2IRBB.
920 VPBasicBlock *SecondVPSucc =
921 cast<VPBasicBlock>(getParent()->getSuccessors()[1]);
922 BasicBlock *SecondIRSucc = State.CFG.VPBB2IRBB.lookup(SecondVPSucc);
923 BasicBlock *IRBB = State.CFG.VPBB2IRBB[getParent()];
924 auto *Br = Builder.CreateCondBr(Cond, IRBB, SecondIRSucc);
925 // First successor is always forward, reset it to nullptr.
926 Br->setSuccessor(0, nullptr);
928 applyMetadata(*Br);
929 return Br;
930 }
932 assert(!GenerateSingleScalar &&
933 "Cannot generate scalar value for Broadcast");
934 return Builder.CreateVectorSplat(
935 State.VF, State.get(getOperand(0), /*NeedsSingleScalar=*/true),
936 "broadcast");
937 }
939 assert(!GenerateSingleScalar &&
940 "Cannot generate scalar value for BuildStructVector");
941 // For struct types, we need to build a new 'wide' struct type, where each
942 // element is widened, i.e., we create a struct of vectors.
943 auto *StructTy = cast<StructType>(getOperand(0)->getScalarType());
944 Value *Res = PoisonValue::get(toVectorizedTy(StructTy, State.VF));
945 for (const auto &[LaneIndex, Op] : enumerate(operands())) {
946 for (unsigned FieldIndex = 0; FieldIndex != StructTy->getNumElements();
947 FieldIndex++) {
948 Value *ScalarValue =
949 Builder.CreateExtractValue(State.get(Op, true), FieldIndex);
950 Value *VectorValue = Builder.CreateExtractValue(Res, FieldIndex);
951 VectorValue =
952 Builder.CreateInsertElement(VectorValue, ScalarValue, LaneIndex);
953 Res = Builder.CreateInsertValue(Res, VectorValue, FieldIndex);
954 }
955 }
956 return Res;
957 }
959 assert(!GenerateSingleScalar &&
960 "Cannot generate scalar value for BuildVector");
961 auto *ScalarTy = getOperand(0)->getScalarType();
962 auto NumOfElements = ElementCount::getFixed(getNumOperands());
963 Value *Res = PoisonValue::get(toVectorizedTy(ScalarTy, NumOfElements));
964 for (const auto &[Idx, Op] : enumerate(operands()))
965 Res = Builder.CreateInsertElement(Res, State.get(Op, true),
966 Builder.getInt64(Idx));
967 return Res;
968 }
970 Type *ScalarTy = getScalarType();
971 auto *WideTy = VectorType::get(ScalarTy, State.VF * getNumOperands());
972 Value *Res = PoisonValue::get(WideTy);
973 for (const auto &[Idx, Op] : enumerate(operands()))
974 Res = Builder.CreateInsertVector(WideTy, Res, State.get(Op),
975 Idx * State.VF.getKnownMinValue());
976 return Res;
977 }
979 if (State.VF.isScalar())
980 return State.get(getOperand(0), true);
981 IRBuilderBase::FastMathFlagGuard FMFG(Builder);
983 // If this start vector is scaled then it should produce a vector with fewer
984 // elements than the VF.
985 ElementCount VF = State.VF.divideCoefficientBy(
986 cast<VPConstantInt>(getOperand(2))->getZExtValue());
987 auto *Iden = Builder.CreateVectorSplat(VF, State.get(getOperand(1), true));
988 return Builder.CreateInsertElement(Iden, State.get(getOperand(0), true),
989 Builder.getInt64(0));
990 }
992 assert(GenerateSingleScalar &&
993 "Can only generate first lane for ComputeReductionResult");
994 RecurKind RK = getRecurKind();
995 bool IsOrdered = isReductionOrdered();
996 bool IsInLoop = isReductionInLoop();
998 "FindIV should use min/max reduction kinds");
999
1000 // The recipe may have multiple operands to be reduced together.
1001 unsigned NumOperandsToReduce = getNumOperands();
1002 SmallVector<Value *, 2> RdxParts(NumOperandsToReduce);
1003 for (unsigned Part = 0; Part < NumOperandsToReduce; ++Part)
1004 RdxParts[Part] = State.get(getOperand(Part), IsInLoop);
1005
1006 IRBuilderBase::FastMathFlagGuard FMFG(Builder);
1008
1009 // Reduce multiple operands into one.
1010 Value *ReducedPartRdx = RdxParts[0];
1011 if (IsOrdered) {
1012 ReducedPartRdx = RdxParts[NumOperandsToReduce - 1];
1013 } else {
1014 // Floating-point operations should have some FMF to enable the reduction.
1015 for (unsigned Part = 1; Part < NumOperandsToReduce; ++Part) {
1016 Value *RdxPart = RdxParts[Part];
1018 ReducedPartRdx = createMinMaxOp(Builder, RK, ReducedPartRdx, RdxPart);
1019 else {
1020 // For sub-recurrences, each part's reduction variable is already
1021 // negative, we need to do: reduce.add(-acc_uf0 + -acc_uf1)
1022 Instruction::BinaryOps Opcode =
1024 ? getSubRecurOpcode(RK)
1025 : (Instruction::BinaryOps)RecurrenceDescriptor::getOpcode(RK);
1026 ReducedPartRdx =
1027 Builder.CreateBinOp(Opcode, RdxPart, ReducedPartRdx, "bin.rdx");
1028 }
1029 }
1030 }
1031
1032 // Create the reduction after the loop. Note that inloop reductions create
1033 // the target reduction in the loop using a Reduction recipe.
1034 if (State.VF.isVector() && !IsInLoop) {
1035 // TODO: Support in-order reductions based on the recurrence descriptor.
1036 // All ops in the reduction inherit fast-math-flags from the recurrence
1037 // descriptor.
1038 ReducedPartRdx = createSimpleReduction(Builder, ReducedPartRdx, RK);
1039 }
1040
1041 return ReducedPartRdx;
1042 }
1045 assert(GenerateSingleScalar &&
1046 "Can only generate first lane for ExtractLane and "
1047 "ExtractPenultimateElement");
1048 unsigned Offset =
1050 Value *Res;
1051 if (State.VF.isVector()) {
1052 assert(Offset <= State.VF.getKnownMinValue() &&
1053 "invalid offset to extract from");
1054 // Extract lane VF - Offset from the operand.
1055 Res = State.get(getOperand(0), VPLane::getLaneFromEnd(State.VF, Offset));
1056 } else {
1057 // TODO: Remove ExtractLastLane for scalar VFs.
1058 assert(Offset <= 1 && "invalid offset to extract from");
1059 Res = State.get(getOperand(0));
1060 }
1061 if (isa<ExtractElementInst>(Res))
1062 Res->setName(Name);
1063 return Res;
1064 }
1065 case VPInstruction::PtrAdd: {
1066 assert(GenerateSingleScalar && "Can only generate first lane for PtrAdd");
1067 Value *Ptr = State.get(getOperand(0), VPLane(0));
1068 Value *Addend = State.get(getOperand(1), VPLane(0));
1069 return Builder.CreatePtrAdd(Ptr, Addend, Name, getGEPNoWrapFlags());
1070 }
1072 assert(!GenerateSingleScalar &&
1073 "Cannot generate scalar value for WidePtrAdd");
1074 Value *Ptr =
1076 Value *Addend = State.get(getOperand(1));
1077 return Builder.CreatePtrAdd(Ptr, Addend, Name, getGEPNoWrapFlags());
1078 }
1079 case VPInstruction::AnyOf: {
1080 assert(GenerateSingleScalar && "Can only generate first lane for AnyOf");
1081 Value *Res = State.get(getOperand(0));
1082 for (VPValue *Op : drop_begin(operands()))
1083 Res = Builder.CreateOr(Res, State.get(Op));
1084 return State.VF.isScalar() ? Res : Builder.CreateOrReduce(Res);
1085 }
1087 assert(GenerateSingleScalar &&
1088 "Can only generate first lane for ExtractLane");
1089 assert(getNumOperands() != 2 && "ExtractLane from single source should be "
1090 "simplified to ExtractElement.");
1091 Value *LaneToExtract = State.get(getOperand(0), true);
1092 Type *IdxTy = getOperand(0)->getScalarType();
1093 Value *Res = nullptr;
1094 Value *RuntimeVF = getRuntimeVF(Builder, IdxTy, State.VF);
1095
1096 for (unsigned Idx = 1; Idx != getNumOperands(); ++Idx) {
1097 Value *VectorStart =
1098 Builder.CreateMul(RuntimeVF, ConstantInt::get(IdxTy, Idx - 1));
1099 Value *VectorIdx = Idx == 1
1100 ? LaneToExtract
1101 : Builder.CreateSub(LaneToExtract, VectorStart);
1102 Value *Ext = State.VF.isScalar()
1103 ? State.get(getOperand(Idx))
1104 : Builder.CreateExtractElement(
1105 State.get(getOperand(Idx)), VectorIdx);
1106 if (Res) {
1107 Value *Cmp = Builder.CreateICmpUGE(LaneToExtract, VectorStart);
1108 Res = Builder.CreateSelect(Cmp, Ext, Res);
1109 } else {
1110 Res = Ext;
1111 }
1112 }
1113 return Res;
1114 }
1116 assert(GenerateSingleScalar &&
1117 "Can only generate first lane for FirstActiveLane");
1118 Type *Ty = this->getScalarType();
1119 if (getNumOperands() == 1) {
1120 Value *Mask = State.get(getOperand(0));
1121 return Builder.CreateCountTrailingZeroElems(Ty, Mask,
1122 /*ZeroIsPoison=*/false, Name);
1123 }
1124 // If there are multiple operands, create a chain of selects to pick the
1125 // first operand with an active lane and add the number of lanes of the
1126 // preceding operands.
1127 Value *RuntimeVF = getRuntimeVF(Builder, Ty, State.VF);
1128 unsigned LastOpIdx = getNumOperands() - 1;
1129 Value *Res = nullptr;
1130 for (int Idx = LastOpIdx; Idx >= 0; --Idx) {
1131 Value *TrailingZeros =
1132 State.VF.isScalar()
1133 ? Builder.CreateZExt(
1134 Builder.CreateICmpEQ(State.get(getOperand(Idx)),
1135 Builder.getFalse()),
1136 Ty)
1138 Ty, State.get(getOperand(Idx)),
1139 /*ZeroIsPoison=*/false, Name);
1140 Value *Current = Builder.CreateAdd(
1141 Builder.CreateMul(RuntimeVF, ConstantInt::get(Ty, Idx)),
1142 TrailingZeros);
1143 if (Res) {
1144 Value *Cmp = Builder.CreateICmpNE(TrailingZeros, RuntimeVF);
1145 Res = Builder.CreateSelect(Cmp, Current, Res);
1146 } else {
1147 Res = Current;
1148 }
1149 }
1150
1151 return Res;
1152 }
1154 assert(GenerateSingleScalar &&
1155 "Can only generate first lane for ResumeForEpilogue");
1156 return State.get(getOperand(0), true);
1158 assert(!GenerateSingleScalar && "Cannot generate scalar value for Reverse");
1159 return Builder.CreateVectorReverse(State.get(getOperand(0)), "reverse");
1161 assert(GenerateSingleScalar &&
1162 "Can only generate first lane for ExtractLastActive");
1163 Value *Result = State.get(getOperand(0), /*NeedsSingleScalar=*/true);
1164 for (unsigned Idx = 1; Idx < getNumOperands(); Idx += 2) {
1165 Value *Data = State.get(getOperand(Idx));
1166 Value *Mask = State.get(getOperand(Idx + 1));
1167 Type *VTy = Data->getType();
1168
1169 if (State.VF.isScalar())
1170 Result = Builder.CreateSelect(Mask, Data, Result);
1171 else
1172 Result = Builder.CreateIntrinsic(
1173 Intrinsic::experimental_vector_extract_last_active, {VTy},
1174 {Data, Mask, Result});
1175 }
1176
1177 return Result;
1178 }
1180 assert(!GenerateSingleScalar &&
1181 "Cannot generate scalar value for ExtractVectorForPart");
1182 Value *Src = State.get(getOperand(0));
1183 Type *DstTy = VectorType::get(getScalarType(), State.VF);
1184 uint64_t Part = cast<VPConstantInt>(getOperand(1))->getZExtValue();
1185
1186 if (Src->getType() == DstTy)
1187 return Src;
1188
1189 return Builder.CreateExtractVector(
1190 DstTy, Src, Builder.getInt64(State.VF.getKnownMinValue() * Part), Name);
1191 }
1193 assert(!GenerateSingleScalar &&
1194 "Cannot generate scalar value for StepVector");
1195 return State.Builder.CreateStepVector(
1196 VectorType::get(getScalarType(), State.VF));
1198 assert(GenerateSingleScalar &&
1199 "Can only generate first lane for Intrinsic");
1200 SmallVector<Value *, 2> Args;
1201 for (VPValue *Op : drop_end(operands()))
1202 Args.push_back(State.get(Op, /*NeedsSingleScalar=*/true));
1203 return State.Builder.CreateIntrinsic(getScalarType(),
1204 vputils::getIntrinsicID(this), Args,
1205 /*FMFSource=*/nullptr, getName());
1206 }
1208 unsigned Multiplier = cast<VPConstantInt>(getOperand(0))->getZExtValue();
1209 auto *WideDataTy = VectorType::get(getScalarType(), State.VF * Multiplier);
1210
1211 Value *Addr = State.get(getOperand(1), /*IsScalar=*/true);
1212 Align Alignment = Align(cast<VPConstantInt>(getOperand(2))->getZExtValue());
1213 LoadInst *WideLI = Builder.CreateAlignedLoad(WideDataTy, Addr, Alignment);
1214 applyMetadata(*WideLI);
1215 return WideLI;
1216 }
1218 unsigned Multiplier = cast<VPConstantInt>(getOperand(0))->getZExtValue();
1219 Value *WideData = State.get(getOperand(3));
1220 assert(cast<VectorType>(WideData->getType())->getElementCount() ==
1221 State.VF * Multiplier &&
1222 "stored value does not match wide element count");
1223 (void)Multiplier;
1224
1225 Value *Addr = State.get(getOperand(1), /*IsScalar=*/true);
1226 Align Alignment = Align(cast<VPConstantInt>(getOperand(2))->getZExtValue());
1227 StoreInst *WideSI = Builder.CreateAlignedStore(WideData, Addr, Alignment);
1228 applyMetadata(*WideSI);
1229 return WideSI;
1230 }
1231 default:
1232 llvm_unreachable("Unsupported opcode for instruction");
1233 }
1234}
1235
1237 unsigned Opcode, ElementCount VF, VPCostContext &Ctx) const {
1238 Type *ScalarTy = this->getScalarType();
1239 Type *ResultTy = VF.isVector() ? toVectorTy(ScalarTy, VF) : ScalarTy;
1240 switch (Opcode) {
1241 case Instruction::FNeg:
1242 return Ctx.TTI.getArithmeticInstrCost(Opcode, ResultTy, Ctx.CostKind);
1243 case Instruction::UDiv:
1244 case Instruction::SDiv:
1245 case Instruction::SRem:
1246 case Instruction::URem:
1247 case Instruction::Add:
1248 case Instruction::FAdd:
1249 case Instruction::Sub:
1250 case Instruction::FSub:
1251 case Instruction::Mul:
1252 case Instruction::FMul:
1253 case Instruction::FDiv:
1254 case Instruction::FRem:
1255 case Instruction::Shl:
1256 case Instruction::LShr:
1257 case Instruction::AShr:
1258 case Instruction::And:
1259 case Instruction::Or:
1260 case Instruction::Xor: {
1261 // Certain instructions can be cheaper if they have a constant second
1262 // operand. One example of this are shifts on x86.
1263 VPValue *RHS = getOperand(1);
1264 TargetTransformInfo::OperandValueInfo RHSInfo = Ctx.getOperandInfo(RHS);
1265
1266 if (RHSInfo.Kind == TargetTransformInfo::OK_AnyValue &&
1269
1272 if (CtxI)
1273 Operands.append(CtxI->value_op_begin(), CtxI->value_op_end());
1274 return Ctx.TTI.getArithmeticInstrCost(
1275 Opcode, ResultTy, Ctx.CostKind,
1276 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
1277 RHSInfo, Operands, CtxI, &Ctx.TLI);
1278 }
1279 case Instruction::Freeze:
1280 // NOTE: The only way to ask for the cost is via getInstructionCost, which
1281 // requires the actual vector instruction. Instead, both here and in the
1282 // LoopVectorizationCostModel::getInstructionCost the costs mirror the
1283 // current behaviour in llvm/Analysis/TargetTransformInfoImpl.h to keep
1284 // them in sync.
1285 return TTI::TCC_Free;
1286 case Instruction::ExtractValue:
1287 return Ctx.TTI.getInsertExtractValueCost(Instruction::ExtractValue,
1288 Ctx.CostKind);
1289 case Instruction::ICmp:
1290 case Instruction::FCmp: {
1291 Type *ScalarOpTy = getOperand(0)->getScalarType();
1292 Type *OpTy = VF.isVector() ? toVectorTy(ScalarOpTy, VF) : ScalarOpTy;
1294 return Ctx.TTI.getCmpSelInstrCost(
1296 Ctx.CostKind, {TTI::OK_AnyValue, TTI::OP_None},
1297 {TTI::OK_AnyValue, TTI::OP_None}, CtxI);
1298 }
1299 case Instruction::BitCast: {
1300 Type *ScalarTy = this->getScalarType();
1301 if (ScalarTy->isPointerTy())
1302 return 0;
1303 [[fallthrough]];
1304 }
1305 case Instruction::SExt:
1306 case Instruction::ZExt:
1307 case Instruction::FPToUI:
1308 case Instruction::FPToSI:
1309 case Instruction::FPExt:
1310 case Instruction::PtrToInt:
1311 case Instruction::PtrToAddr:
1312 case Instruction::IntToPtr:
1313 case Instruction::SIToFP:
1314 case Instruction::UIToFP:
1315 case Instruction::Trunc:
1316 case Instruction::FPTrunc:
1317 case Instruction::AddrSpaceCast: {
1318 // Computes the CastContextHint from a recipe that may access memory.
1319 auto ComputeCCH = [&](const VPRecipeBase *R) -> TTI::CastContextHint {
1320 if (isa<VPInterleaveBase>(R))
1322 if (const auto *ReplicateRecipe = dyn_cast<VPReplicateRecipe>(R)) {
1323 // Only compute CCH for memory operations, matching the legacy model
1324 // which only considers loads/stores for cast context hints.
1325 auto *UI = cast<Instruction>(ReplicateRecipe->getUnderlyingValue());
1326 if (!isa<LoadInst, StoreInst>(UI))
1328 return ReplicateRecipe->isPredicated() ? TTI::CastContextHint::Masked
1330 }
1331 const auto *WidenMemoryRecipe = dyn_cast<VPWidenMemoryRecipe>(R);
1332 if (WidenMemoryRecipe == nullptr)
1334 if (VF.isScalar())
1336 if (!WidenMemoryRecipe->isConsecutive())
1338 if (WidenMemoryRecipe->isMasked())
1341 };
1342
1343 VPValue *Operand = getOperand(0);
1345 bool IsReverse = false;
1346 // For Trunc/FPTrunc, get the context from the only user.
1347 if (Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) {
1348 if (auto *Recipe = cast_or_null<VPRecipeBase>(getSingleUser())) {
1349 if (match(Recipe,
1353 IsReverse = true;
1355 Recipe->getVPSingleValue()->getSingleUser());
1356 }
1357 if (Recipe)
1358 CCH = ComputeCCH(Recipe);
1359 }
1360 }
1361 // For Z/Sext, get the context from the operand.
1362 else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt ||
1363 Opcode == Instruction::FPExt) {
1364 if (auto *Recipe = Operand->getDefiningRecipe()) {
1365 VPValue *ReverseOp;
1366 if (match(Recipe,
1367 m_CombineOr(m_Reverse(m_VPValue(ReverseOp)),
1369 m_VPValue(ReverseOp))))) {
1370 Recipe = ReverseOp->getDefiningRecipe();
1371 IsReverse = true;
1372 }
1373 if (Recipe)
1374 CCH = ComputeCCH(Recipe);
1375 }
1376 }
1377 if (IsReverse && CCH != TTI::CastContextHint::None)
1379
1380 auto *ScalarSrcTy = Operand->getScalarType();
1381 Type *SrcTy = VF.isVector() ? toVectorTy(ScalarSrcTy, VF) : ScalarSrcTy;
1382 // Arm TTI will use the underlying instruction to determine the cost.
1383 return Ctx.TTI.getCastInstrCost(
1384 Opcode, ResultTy, SrcTy, CCH, Ctx.CostKind,
1386 }
1387 case Instruction::Select: {
1389 bool IsScalarCond = getOperand(0)->isDefinedOutsideLoopRegions();
1390 Type *ScalarTy = this->getScalarType();
1391
1392 VPValue *Op0, *Op1;
1393 bool IsLogicalAnd =
1394 match(this, m_c_LogicalAnd(m_VPValue(Op0), m_VPValue(Op1)));
1395 bool IsLogicalOr =
1396 match(this, m_c_LogicalOr(m_VPValue(Op0), m_VPValue(Op1)));
1397 // Also match the inverted forms:
1398 // select x, false, y --> !x & y (still AND)
1399 // select x, y, true --> !x | y (still OR)
1400 IsLogicalAnd |=
1401 match(this, m_Select(m_VPValue(Op0), m_False(), m_VPValue(Op1)));
1402 IsLogicalOr |=
1403 match(this, m_Select(m_VPValue(Op0), m_VPValue(Op1), m_True()));
1404
1405 if (!IsScalarCond && ScalarTy->getScalarSizeInBits() == 1 &&
1406 (IsLogicalAnd || IsLogicalOr)) {
1407 // select x, y, false --> x & y
1408 // select x, true, y --> x | y
1409 const auto [Op1VK, Op1VP] = Ctx.getOperandInfo(Op0);
1410 const auto [Op2VK, Op2VP] = Ctx.getOperandInfo(Op1);
1411
1413 if (SI && all_of(operands(),
1414 [](VPValue *Op) { return Op->getUnderlyingValue(); }))
1415 append_range(Operands, SI->operands());
1416 return Ctx.TTI.getArithmeticInstrCost(
1417 IsLogicalOr ? Instruction::Or : Instruction::And, ResultTy,
1418 Ctx.CostKind, {Op1VK, Op1VP}, {Op2VK, Op2VP}, Operands, SI);
1419 }
1420
1421 Type *CondTy = getOperand(0)->getScalarType();
1422 if (!IsScalarCond && VF.isVector())
1423 CondTy = VectorType::get(CondTy, VF);
1424
1425 llvm::CmpPredicate Pred;
1426 if (!match(getOperand(0), m_Cmp(Pred, m_VPValue(), m_VPValue())))
1427 if (auto *CondIRV = dyn_cast<VPIRValue>(getOperand(0)))
1428 if (auto *Cmp = dyn_cast<CmpInst>(CondIRV->getValue()))
1429 Pred = Cmp->getPredicate();
1430 Type *VectorTy = toVectorTy(this->getScalarType(), VF);
1431 return Ctx.TTI.getCmpSelInstrCost(
1432 Instruction::Select, VectorTy, CondTy, Pred, Ctx.CostKind,
1433 {TTI::OK_AnyValue, TTI::OP_None}, {TTI::OK_AnyValue, TTI::OP_None}, SI);
1434 }
1435 }
1436 llvm_unreachable("called for unsupported opcode");
1437}
1438
1440 VPCostContext &Ctx) const {
1441 // NOTE: At the moment it seems only possible to expose this path for
1442 // the trunc, zext and sext opcodes.
1443 // TODO: Update VF arg to use onlyFirstLaneUsed once WidenCast is unified.
1445 // A scalar zext/trunc that only adjusts the width of an
1446 // ExplicitVectorLength to the canonical IV type is free: it feeds only
1447 // the IV increment and AVL decrement, which are modeled as free below.
1448 if (match(this, m_ZExtOrTrunc(m_EVL(m_VPValue()))))
1449 return 0;
1451 Ctx);
1452 }
1453
1455 if (!getUnderlyingValue() && getOpcode() != Instruction::FMul) {
1456 // TODO: Compute cost for VPInstructions without underlying values once
1457 // the legacy cost model has been retired.
1458 return 0;
1459 }
1460
1462 "Should only generate a vector value or single scalar, not scalars "
1463 "for all lanes.");
1465 getOpcode(),
1467 }
1468
1469 switch (getOpcode()) {
1470 case Instruction::Select: {
1472 match(getOperand(0), m_Cmp(Pred, m_VPValue(), m_VPValue()));
1473 auto *CondTy = getOperand(0)->getScalarType();
1474 auto *VecTy = getOperand(1)->getScalarType();
1475 if (!vputils::onlyFirstLaneUsed(this)) {
1476 CondTy = toVectorTy(CondTy, VF);
1477 VecTy = toVectorTy(VecTy, VF);
1478 }
1479 return Ctx.TTI.getCmpSelInstrCost(Instruction::Select, VecTy, CondTy, Pred,
1480 Ctx.CostKind);
1481 }
1482 case Instruction::ExtractElement:
1484 if (VF.isScalar()) {
1485 // ExtractLane with VF=1 takes care of handling extracting across multiple
1486 // parts.
1487 return 0;
1488 }
1489
1490 // Add on the cost of extracting the element.
1491 auto *VecTy = toVectorTy(getOperand(0)->getScalarType(), VF);
1492 return Ctx.TTI.getVectorInstrCost(Instruction::ExtractElement, VecTy,
1493 Ctx.CostKind);
1494 }
1495 case VPInstruction::AnyOf: {
1496 auto *VecTy = toVectorTy(this->getScalarType(), VF);
1497 return Ctx.TTI.getArithmeticReductionCost(
1498 Instruction::Or, cast<VectorType>(VecTy), std::nullopt, Ctx.CostKind);
1499 }
1501 Type *Ty = this->getScalarType();
1502 Type *ScalarTy = getOperand(0)->getScalarType();
1503 if (VF.isScalar())
1504 return Ctx.TTI.getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
1506 CmpInst::ICMP_EQ, Ctx.CostKind);
1507 // Calculate the cost of determining the lane index.
1508 auto *PredTy = toVectorTy(ScalarTy, VF);
1509 IntrinsicCostAttributes Attrs(Intrinsic::experimental_cttz_elts, Ty,
1510 {PredTy, Type::getInt1Ty(Ctx.LLVMCtx)});
1511 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1512 }
1514 Type *Ty = this->getScalarType();
1515 Type *ScalarTy = getOperand(0)->getScalarType();
1516 if (VF.isScalar())
1517 return Ctx.TTI.getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
1519 CmpInst::ICMP_EQ, Ctx.CostKind);
1520 // Calculate the cost of determining the lane index: NOT + cttz_elts + SUB.
1521 auto *PredTy = toVectorTy(ScalarTy, VF);
1522 IntrinsicCostAttributes Attrs(Intrinsic::experimental_cttz_elts, Ty,
1523 {PredTy, Type::getInt1Ty(Ctx.LLVMCtx)});
1524 InstructionCost Cost = Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1525 // Add cost of NOT operation on the predicate.
1526 Cost += Ctx.TTI.getArithmeticInstrCost(
1527 Instruction::Xor, PredTy, Ctx.CostKind,
1528 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
1529 {TargetTransformInfo::OK_UniformConstantValue,
1530 TargetTransformInfo::OP_None});
1531 // Add cost of SUB operation on the index.
1532 Cost += Ctx.TTI.getArithmeticInstrCost(Instruction::Sub, Ty, Ctx.CostKind);
1533 return Cost;
1534 }
1536 Type *ScalarTy = this->getScalarType();
1537 Type *VecTy = toVectorTy(ScalarTy, VF);
1538 Type *MaskTy = toVectorTy(Type::getInt1Ty(Ctx.LLVMCtx), VF);
1540 Intrinsic::experimental_vector_extract_last_active, ScalarTy,
1541 {VecTy, MaskTy, ScalarTy});
1542 return Ctx.TTI.getIntrinsicInstrCost(ICA, Ctx.CostKind);
1543 }
1545 assert(VF.isVector() && "Scalar FirstOrderRecurrenceSplice?");
1546 Type *VectorTy = toVectorTy(this->getScalarType(), VF);
1547 return Ctx.TTI.getShuffleCost(
1549 cast<VectorType>(VectorTy), Ctx.CostKind, {}, -1);
1550 }
1553 Type *ArgTy = getOperand(0)->getScalarType();
1554 uint64_t Multiplier =
1556 ? cast<VPConstantInt>(getOperand(2))->getZExtValue()
1557 : 1;
1558 Type *RetTy = toVectorTy(Type::getInt1Ty(Ctx.LLVMCtx), VF * Multiplier);
1559 IntrinsicCostAttributes Attrs(Intrinsic::get_active_lane_mask, RetTy,
1560 {ArgTy, ArgTy});
1561 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1562 }
1564 Type *Arg0Ty = getOperand(0)->getScalarType();
1565 Type *I32Ty = Type::getInt32Ty(Ctx.LLVMCtx);
1566 Type *I1Ty = Type::getInt1Ty(Ctx.LLVMCtx);
1567 IntrinsicCostAttributes Attrs(Intrinsic::experimental_get_vector_length,
1568 I32Ty, {Arg0Ty, I32Ty, I1Ty});
1569 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1570 }
1572 assert(VF.isVector() && "Reverse operation must be vector type");
1573 Type *EltTy = this->getScalarType();
1574 // Skip the reverse operation cost for the mask.
1575 // FIXME: Remove this once redundant mask reverse operations can be
1576 // eliminated by VPlanTransforms::cse before cost computation.
1577 if (EltTy->isIntegerTy(1))
1578 return 0;
1579 auto *VectorTy = cast<VectorType>(toVectorTy(EltTy, VF));
1580 return Ctx.TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy,
1581 VectorTy, Ctx.CostKind, /*Mask=*/{},
1582 /*Index=*/0);
1583 }
1585 // Add on the cost of extracting the element.
1586 auto *VecTy = toVectorTy(getOperand(0)->getScalarType(), VF);
1587 return Ctx.TTI.getIndexedVectorInstrCostFromEnd(Instruction::ExtractElement,
1588 VecTy, Ctx.CostKind, 0);
1589 }
1590 case VPInstruction::Not: {
1591 Type *ValTy = this->getScalarType();
1592 // InstCombine will fold `xor` to the conditional branch.
1593 if (auto *U = const_cast<VPUser *>(getSingleUser()))
1594 if (match(U, m_BranchOnCond(m_VPValue())))
1595 return 0;
1596 if (!vputils::onlyFirstLaneUsed(this))
1597 ValTy = toVectorTy(ValTy, VF);
1598 return Ctx.TTI.getArithmeticInstrCost(Instruction::Xor, ValTy,
1599 Ctx.CostKind);
1600 }
1602 // If TC <= VF then this is just a branch.
1603 // FIXME: Removing the branch happens in simplifyBranchConditionForVFAndUF
1604 // where it checks TC <= VF * UF, but we don't know UF yet. This means in
1605 // some cases we get a cost that's too high due to counting a cmp that
1606 // later gets removed.
1607 // FIXME: The compare could also be removed if TC = M * vscale,
1608 // VF = N * vscale, and M <= N. Detecting that would require having the
1609 // trip count as a SCEV though.
1610 if (VPCostContext::executesAtMostOnce(*getParent()->getPlan(), VF))
1611 return 0;
1612 // Otherwise BranchOnCount generates ICmpEQ followed by a branch.
1613 Type *ValTy = getOperand(0)->getScalarType();
1614 return Ctx.TTI.getCmpSelInstrCost(Instruction::ICmp, ValTy,
1616 CmpInst::ICMP_EQ, Ctx.CostKind);
1617 }
1619 Type *Ty = getScalarType();
1621 for (const VPValue *Op : drop_end(operands()))
1622 ArgTys.push_back(Op->getScalarType());
1623 IntrinsicCostAttributes Attrs(vputils::getIntrinsicID(this), Ty, ArgTys);
1624 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1625 }
1627 // TODO: This isn't quite right since even if the step-vector is hoisted
1628 // out of the loop it has a non-zero cost in the middle block, etc.
1629 // Once the stepvector is correctly hoisted out of the vector loop by the
1630 // licm transform we can add the cost here so that it doesn't incorrectly
1631 // affect the choice of VF.
1632 return 0;
1634 // It isn't currently possible to expose cases where WideIVStep's cost is
1635 // queried.
1636 llvm_unreachable("Unhandled opcode");
1637 case Instruction::FCmp:
1638 case Instruction::ICmp:
1640 getOpcode(),
1643 if (VF == ElementCount::getScalable(1))
1645 [[fallthrough]];
1646 default:
1647 // TODO: Compute cost other VPInstructions once the legacy cost model has
1648 // been retired.
1650 "unexpected VPInstruction witht underlying value");
1651 return 0;
1652 }
1653}
1654
1667
1669 switch (getOpcode()) {
1670 case Instruction::Load:
1671 case Instruction::PHI:
1675 return true;
1676 default:
1678 }
1679}
1680
1682#ifndef NDEBUG
1683 Type *Ty = Op->getScalarType();
1684 switch (getOpcode()) {
1688 assert(Ty == getOperand(0)->getScalarType() &&
1689 "types of operand 0 and new operand must match");
1690 break;
1695 assert(Ty == getOperand(0)->getScalarType() &&
1696 "appended operand must match operand 0's scalar type");
1697 break;
1699 assert(Ty == getOperand(1)->getScalarType() &&
1700 "appended operand must match operand 1's scalar type");
1701 break;
1703 // The recipe is constructed with 3 operands (result, data, mask). Extra
1704 // operands beyond that are appended in (data, mask) pairs.
1705 constexpr unsigned NumInitialOperands = 3;
1706 assert(getNumOperands() >= NumInitialOperands &&
1707 "ExtractLastActive must have at least the initial 3 operands");
1708 bool IsMaskSlot = ((getNumOperands() - NumInitialOperands) & 1u) == 1u;
1709 assert((IsMaskSlot ? Ty->isIntegerTy(1)
1710 : Ty == getOperand(1)->getScalarType()) &&
1711 "ExtractLastActive expects alternating data/mask operands "
1712 "matching operand 1's type and i1, respectively");
1713 break;
1714 }
1715 default:
1716 llvm_unreachable("opcode does not support growing the operand list "
1717 "outside of construction");
1718 }
1719#endif
1721}
1722
1724 assert(!isMasked() && "cannot execute masked VPInstruction");
1725 IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder);
1727 "Set flags not supported for the provided opcode");
1729 "Opcode requires specific flags to be set");
1730 State.Builder.setFastMathFlags(getFastMathFlagsOrNone());
1731 bool GenerateSingleScalar = State.VF.isScalar() || doesGenerateSingleScalar();
1732 Value *GeneratedValue = generate(State, GenerateSingleScalar);
1733 if (!hasResult())
1734 return;
1735 assert(GeneratedValue && "generate must produce a value");
1736 assert(((GeneratedValue->getType()->isVectorTy() ||
1737 GeneratedValue->getType()->isStructTy()) == !GenerateSingleScalar) &&
1738 "scalar value but not only first lane defined");
1739 State.set(this, GeneratedValue, GenerateSingleScalar);
1741 getOpcode() == Instruction::Freeze) {
1742 // FIXME: This is a workaround to enable reliable updates of the scalar loop
1743 // resume phis, and to let epilogue vectorization recover the frozen
1744 // reduction start from the main plan. Must be removed once epilogue
1745 // vectorization explicitly connects VPlans.
1746 setUnderlyingValue(GeneratedValue);
1747 }
1748}
1749
1753 return false;
1754 switch (getOpcode()) {
1755 case Instruction::ExtractValue:
1756 case Instruction::InsertValue:
1757 case Instruction::GetElementPtr:
1758 case Instruction::ExtractElement:
1759 case Instruction::InsertElement:
1760 case Instruction::Freeze:
1761 case Instruction::FCmp:
1762 case Instruction::ICmp:
1763 case Instruction::Select:
1764 case Instruction::PHI:
1792 case VPInstruction::Not:
1800 return false;
1803 AttributeSet Attrs =
1805 return !Attrs.getMemoryEffects().doesNotAccessMemory();
1806 }
1807 case Instruction::Call:
1809 default:
1810 return true;
1811 }
1812}
1813
1815 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
1817 return vputils::onlyFirstLaneUsed(this);
1818
1819 switch (getOpcode()) {
1820 default:
1821 return false;
1822 case Instruction::ExtractElement:
1823 return Op == getOperand(1);
1824 case Instruction::InsertElement:
1825 return Op == getOperand(1) || Op == getOperand(2);
1827 return Op == getOperand(0);
1828 case Instruction::PHI:
1829 return true;
1830 case Instruction::FCmp:
1831 case Instruction::ICmp:
1832 case Instruction::Select:
1833 case Instruction::Or:
1834 case Instruction::Freeze:
1835 case VPInstruction::Not:
1836 // TODO: Cover additional opcodes.
1837 return vputils::onlyFirstLaneUsed(this);
1838 case Instruction::Load:
1853 return true;
1855 return Op == getOperand(0) || vputils::onlyFirstLaneUsed(this);
1857 // WidePtrAdd supports scalar and vector base addresses.
1858 return false;
1860 return Op == getOperand(0) || Op == getOperand(1) || Op == getOperand(2);
1863 return Op == getOperand(0);
1864 };
1865 llvm_unreachable("switch should return");
1866}
1867
1869 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
1871 return vputils::onlyFirstPartUsed(this);
1872
1873 switch (getOpcode()) {
1874 default:
1875 return false;
1876 case Instruction::FCmp:
1877 case Instruction::ICmp:
1878 case Instruction::Select:
1879 return vputils::onlyFirstPartUsed(this);
1884 return true;
1885 };
1886 llvm_unreachable("switch should return");
1887}
1888
1889#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1891 VPSlotTracker SlotTracker(getParent()->getPlan());
1893}
1894
1896 VPSlotTracker &SlotTracker) const {
1897 O << Indent << "EMIT" << (isSingleScalar() ? "-SCALAR" : "") << " ";
1898
1899 if (hasResult()) {
1901 O << " = ";
1902 }
1903
1904 switch (getOpcode()) {
1905 case VPInstruction::Not:
1906 O << "not";
1907 break;
1909 O << "active lane mask";
1910 break;
1912 O << "wide active lane mask";
1913 break;
1915 O << "wide vector load";
1916 break;
1918 O << "wide vector store";
1919 break;
1921 O << "concat-vectors";
1922 break;
1924 O << "incoming-alias-mask";
1925 break;
1927 O << "EXPLICIT-VECTOR-LENGTH";
1928 break;
1930 O << "first-order splice";
1931 break;
1933 O << "branch-on-cond";
1934 break;
1936 O << "branch-on-two-conds";
1937 break;
1939 O << "VF * Part +";
1940 break;
1942 O << "branch-on-count";
1943 break;
1945 O << "broadcast";
1946 break;
1948 O << "buildstructvector";
1949 break;
1951 O << "buildvector";
1952 break;
1954 O << "exiting-iv-value";
1955 break;
1957 O << "masked-cond";
1958 break;
1960 O << "extract-lane";
1961 break;
1963 O << "extract-last-lane";
1964 break;
1966 O << "extract-last-part";
1967 break;
1969 O << "extract-penultimate-element";
1970 break;
1972 O << "extract-vector-for-part";
1973 break;
1975 O << "compute-reduction-result";
1976 break;
1978 O << "logical-and";
1979 break;
1981 O << "logical-or";
1982 break;
1984 O << "ptradd";
1985 break;
1987 O << "wide-ptradd";
1988 break;
1990 O << "any-of";
1991 break;
1993 O << "first-active-lane";
1994 break;
1996 O << "last-active-lane";
1997 break;
1999 O << "reduction-start-vector";
2000 break;
2002 O << "resume-for-epilogue";
2003 break;
2005 O << "reverse";
2006 break;
2008 O << "unpack";
2009 break;
2011 O << "extract-last-active";
2012 break;
2014 O << "num-active-lanes";
2015 break;
2017 O << "wide-iv-step";
2018 break;
2020 O << "step-vector " << *getScalarType();
2021 break;
2023 O << "call " << *getScalarType() << " @"
2026 Op->printAsOperand(O, SlotTracker);
2027 });
2028 O << ")";
2029 return;
2030 }
2031 case Instruction::Load:
2032 O << "load";
2033 break;
2034 default:
2036 }
2037
2038 if (!operands_empty()) {
2039 printFlags(O);
2041 }
2043 O << " to " << *getScalarType();
2044}
2045#endif
2046
2047/// Shared execute logic for VPPhi and VPWidenPHIRecipe. Creates a PHI node,
2048/// adds incoming values, and stores the result in State. For header phis, only
2049/// the preheader incoming value is added; the backedge is fixed up later by
2050/// VPlan::execute().
2052 VPTransformState &State, bool IsScalar,
2053 const Twine &Name) {
2054 unsigned NumIncoming = VPBlockUtils::isHeader(R->getParent(), State.VPDT)
2055 ? 1
2056 : Phi.getNumIncoming();
2057 Value *FirstInc = State.get(Phi.getIncomingValue(0), IsScalar);
2058 PHINode *NewPhi = State.Builder.CreatePHI(FirstInc->getType(), 2, Name);
2059 NewPhi->addIncoming(FirstInc,
2060 State.CFG.VPBB2IRBB.at(Phi.getIncomingBlock(0)));
2061 for (unsigned Idx = 1; Idx != NumIncoming; ++Idx)
2062 NewPhi->addIncoming(State.get(Phi.getIncomingValue(Idx), IsScalar),
2063 State.CFG.VPBB2IRBB.at(Phi.getIncomingBlock(Idx)));
2064 State.set(R, NewPhi, IsScalar);
2065}
2066
2068 executePhiRecipe(this, *this, State, /*IsScalar=*/true, getName());
2069}
2070
2071#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2072void VPPhi::printRecipe(raw_ostream &O, const Twine &Indent,
2073 VPSlotTracker &SlotTracker) const {
2074 O << Indent << "EMIT" << (isSingleScalar() ? "-SCALAR" : "") << " ";
2076 O << " = phi";
2077 printFlags(O);
2079}
2080#endif
2081
2082VPIRInstruction *VPIRInstruction ::create(Instruction &I) {
2083 if (auto *Phi = dyn_cast<PHINode>(&I))
2084 return new VPIRPhi(*Phi);
2085 return new VPIRInstruction(I);
2086}
2087
2089 assert(!isa<VPIRPhi>(this) && getNumOperands() == 0 &&
2090 "PHINodes must be handled by VPIRPhi");
2091 // Advance the insert point after the wrapped IR instruction. This allows
2092 // interleaving VPIRInstructions and other recipes.
2093 State.Builder.SetInsertPoint(std::next(I.getIterator()));
2094}
2095
2097 VPCostContext &Ctx) const {
2098 // The recipe wraps an existing IR instruction on the border of VPlan's scope,
2099 // hence it does not contribute to the cost-modeling for the VPlan.
2100 return 0;
2101}
2102
2103#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2105 VPSlotTracker &SlotTracker) const {
2106 O << Indent << "IR " << I;
2107}
2108#endif
2109
2111 PHINode *Phi = &getIRPhi();
2112 for (const auto &[Idx, Op] : enumerate(operands())) {
2113 VPValue *ExitValue = Op;
2114 auto Lane = vputils::isSingleScalar(ExitValue)
2116 : VPLane::getLastLaneForVF(State.VF);
2117 VPBlockBase *Pred = getParent()->getPredecessors()[Idx];
2118 auto *PredVPBB = Pred->getExitingBasicBlock();
2119 BasicBlock *PredBB = State.CFG.VPBB2IRBB[PredVPBB];
2120 // Set insertion point in PredBB in case an extract needs to be generated.
2121 // TODO: Model extracts explicitly.
2122 State.Builder.SetInsertPoint(PredBB->getTerminator());
2123 Value *V = State.get(ExitValue, VPLane(Lane));
2124 // If there is no existing block for PredBB in the phi, add a new incoming
2125 // value. Otherwise update the existing incoming value for PredBB.
2126 if (Phi->getBasicBlockIndex(PredBB) == -1)
2127 Phi->addIncoming(V, PredBB);
2128 else
2129 Phi->setIncomingValueForBlock(PredBB, V);
2130 }
2131
2132 // Advance the insert point after the wrapped IR instruction. This allows
2133 // interleaving VPIRInstructions and other recipes.
2134 State.Builder.SetInsertPoint(std::next(Phi->getIterator()));
2135}
2136
2138 VPRecipeBase *R = const_cast<VPRecipeBase *>(getAsRecipe());
2139 assert(R->getNumOperands() == R->getParent()->getNumPredecessors() &&
2140 "Number of phi operands must match number of predecessors");
2141 unsigned Position = R->getParent()->getIndexForPredecessor(IncomingBlock);
2142 R->removeOperand(Position);
2143}
2144
2145VPValue *
2147 VPRecipeBase *R = const_cast<VPRecipeBase *>(getAsRecipe());
2148 return getIncomingValue(R->getParent()->getIndexForPredecessor(VPBB));
2149}
2150
2152 VPValue *V) const {
2153 VPRecipeBase *R = const_cast<VPRecipeBase *>(getAsRecipe());
2154 R->setOperand(R->getParent()->getIndexForPredecessor(VPBB), V);
2155}
2156
2157#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2159 VPSlotTracker &SlotTracker) const {
2161 O << "[ ";
2162 std::get<0>(Op)->printAsOperand(O, SlotTracker);
2163 O << ", ";
2164 std::get<1>(Op)->printAsOperand(O);
2165 O << " ]";
2166 });
2167}
2168#endif
2169
2170#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2172 VPSlotTracker &SlotTracker) const {
2174
2175 if (getNumOperands() != 0) {
2176 O << " (extra operand" << (getNumOperands() > 1 ? "s" : "") << ": ";
2178 [&O, &SlotTracker](auto Op) {
2179 std::get<0>(Op)->printAsOperand(O, SlotTracker);
2180 O << " from ";
2181 std::get<1>(Op)->printAsOperand(O);
2182 });
2183 O << ")";
2184 }
2185}
2186#endif
2187
2189 if (Metadata.empty())
2190 return;
2191 // Frequencies and estimated branch weights are VPlan-internal and must not
2192 // reach IR.
2193 unsigned ExecFreqKind = getMDKindID(ExecutionFrequencyMDName);
2194 unsigned EstProfKind = getMDKindID(EstimatedProfileMDName);
2195 for (const auto &[Kind, Node] : Metadata)
2196 if (Kind != ExecFreqKind && Kind != EstProfKind)
2197 I.setMetadata(Kind, Node);
2198}
2199
2200/// Returns the execution frequency recorded in \p Node.
2202 assert(Node->getNumOperands() <= 2 && "unexpected frequency node shape");
2203 uint64_t Freq =
2204 mdconst::extract<ConstantInt>(Node->getOperand(0))->getZExtValue();
2206 "frequency cannot exceed the one of an always executing block");
2207 return {BlockFrequency(Freq), Node->getNumOperands() == 2};
2208}
2209
2211 std::optional<VPExecutionFrequency> Freq, LLVMContext &Ctx) {
2212 // A recipe that always executes needs no annotation.
2213 if (!Freq || vputils::getExecutionProbability(Freq->Freq).isOne())
2214 return;
2216 ConstantInt::get(Type::getInt64Ty(Ctx), Freq->Freq.getFrequency()))};
2217 if (Freq->IsEstimated)
2219 setMetadata(Ctx.getMDKindID(ExecutionFrequencyMDName), MDNode::get(Ctx, Ops));
2220}
2221
2222std::optional<VPExecutionFrequency>
2224 if (MDNode *Node = getInternalMetadata(ExecutionFrequencyMDName))
2226 return std::nullopt;
2227}
2228
2230 if (Metadata.empty())
2231 return;
2232 unsigned ID = getMDKindID(ExecutionFrequencyMDName);
2233 erase_if(Metadata, [ID](const auto &P) { return P.first == ID; });
2234}
2235
2237 erase_if(Metadata,
2238 [&](const auto &MD) { return !is_contained(Other.Metadata, MD); });
2239}
2240
2241#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2243 const Module *M = SlotTracker.getModule();
2244 if (Metadata.empty() || !M)
2245 return;
2246
2247 ArrayRef<StringRef> MDNames = SlotTracker.getMDNames();
2248 O << " (";
2249 interleaveComma(Metadata, O, [&](const auto &KindNodePair) {
2250 auto [Kind, Node] = KindNodePair;
2251 assert(Kind < MDNames.size() && !MDNames[Kind].empty() &&
2252 "Unexpected unnamed metadata kind");
2253 O << "!" << MDNames[Kind] << " ";
2254 // Print the values of branch weights, which are more informative than the
2255 // ID of the metadata node holding them.
2256 SmallVector<uint32_t> Weights;
2257 bool IsEstimatedProfile = MDNames[Kind] == EstimatedProfileMDName;
2258 if ((Kind == LLVMContext::MD_prof || IsEstimatedProfile) &&
2259 extractBranchWeights(Node, Weights)) {
2260 if (IsEstimatedProfile)
2261 O << "estimated ";
2262 O << "{";
2263 interleaveComma(Weights, O);
2264 O << "}";
2265 } else if (MDNames[Kind] == ExecutionFrequencyMDName) {
2266 // Print the frequency together with the probability it corresponds to.
2267 auto [Freq, IsEstimated] = getExecutionFrequencyFromMD(Node);
2268 const fltSemantics &Sem = APFloat::IEEEdouble();
2269 uint64_t Full =
2271 APFloat Percent = APFloat(Sem, Freq.getFrequency()) * APFloat(Sem, 100) /
2272 APFloat(Sem, Full);
2273 SmallString<16> PercentStr;
2274 Percent.toString(PercentStr, /*FormatPrecision=*/4);
2275 O << Freq.getFrequency() << " (" << PercentStr << "%"
2276 << (IsEstimated ? ", estimated" : "") << ")";
2277 } else {
2278 SlotTracker.printMetadataAsOperand(O, Node);
2279 }
2280 });
2281 O << ")";
2282}
2283#endif
2284
2286 assert(State.VF.isVector() && "not widening");
2287 assert(Variant != nullptr && "Can't create vector function.");
2288
2289 FunctionType *VFTy = Variant->getFunctionType();
2290 // Add return type if intrinsic is overloaded on it.
2292 for (const auto &I : enumerate(args())) {
2293 Value *Arg;
2294 // Some vectorized function variants may also take a scalar argument,
2295 // e.g. linear parameters for pointers. This needs to be the scalar value
2296 // from the start of the respective part when interleaving.
2297 if (!VFTy->getParamType(I.index())->isVectorTy())
2298 Arg = State.get(I.value(), VPLane(0));
2299 else
2300 Arg = State.get(I.value(), usesFirstLaneOnly(I.value()));
2301 Args.push_back(Arg);
2302 }
2303
2306 if (CI)
2307 CI->getOperandBundlesAsDefs(OpBundles);
2308
2309 CallInst *V = State.Builder.CreateCall(Variant, Args, OpBundles);
2310 applyFlags(*V);
2311 applyMetadata(*V);
2312 V->setCallingConv(Variant->getCallingConv());
2313
2314 if (!V->getType()->isVoidTy())
2315 State.set(this, V);
2316}
2317
2319 VPCostContext &Ctx) const {
2320 assert(getVectorizedTypeVF(Variant->getReturnType()) == VF &&
2321 "Variant return type must match VF");
2322 return computeCallCost(Variant, Ctx);
2323}
2324
2326 VPCostContext &Ctx) {
2327 return Ctx.TTI.getCallInstrCost(nullptr, Variant->getReturnType(),
2328 Variant->getFunctionType()->params(),
2329 Ctx.CostKind);
2330}
2331
2333 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
2334 assert(Variant && "Variant not set");
2335 FunctionType *VFTy = Variant->getFunctionType();
2336 return all_of(enumerate(args()), [VFTy, &Op](const auto &Arg) {
2337 auto [Idx, V] = Arg;
2338 Type *ArgTy = VFTy->getParamType(Idx);
2339 return V != Op || ArgTy->isIntegerTy() || ArgTy->isFloatingPointTy() ||
2340 ArgTy->isPointerTy() || ArgTy->isByteTy();
2341 });
2342}
2343
2344#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2346 VPSlotTracker &SlotTracker) const {
2347 O << Indent << "WIDEN-CALL ";
2348
2349 Function *CalledFn = getCalledScalarFunction();
2350 if (CalledFn->getReturnType()->isVoidTy())
2351 O << "void ";
2352 else {
2354 O << " = ";
2355 }
2356
2357 O << "call";
2358 printFlags(O);
2359 O << "@" << CalledFn->getName() << "(";
2360 interleaveComma(args(), O, [&O, &SlotTracker](VPValue *Op) {
2361 Op->printAsOperand(O, SlotTracker);
2362 });
2363 O << ")";
2364
2365 O << " (using library function";
2366 if (Variant->hasName())
2367 O << ": " << Variant->getName();
2368 O << ")";
2369}
2370#endif
2371
2373 assert(State.VF.isVector() && "not widening");
2374
2375 SmallVector<Type *, 2> TysForDecl;
2376 // Add return type if intrinsic is overloaded on it.
2377 if (isVectorIntrinsicWithOverloadTypeAtArg(VectorIntrinsicID, -1,
2378 State.TTI)) {
2379 Type *RetTy = toVectorizedTy(getScalarType(), State.VF);
2380 ArrayRef<Type *> ContainedTys = getContainedTypes(RetTy);
2381 for (auto [Idx, Ty] : enumerate(ContainedTys)) {
2383 Idx, State.TTI))
2384 TysForDecl.push_back(Ty);
2385 }
2386 }
2388 for (const auto &I : enumerate(operands())) {
2389 // Some intrinsics have a scalar argument - don't replace it with a
2390 // vector.
2391 Value *Arg;
2392 if (isVectorIntrinsicWithScalarOpAtArg(VectorIntrinsicID, I.index(),
2393 State.TTI))
2394 Arg = State.get(I.value(), VPLane(0));
2395 else
2396 Arg = State.get(I.value(), usesFirstLaneOnly(I.value()));
2397 if (isVectorIntrinsicWithOverloadTypeAtArg(VectorIntrinsicID, I.index(),
2398 State.TTI))
2399 TysForDecl.push_back(Arg->getType());
2400 Args.push_back(Arg);
2401 }
2402
2403 // Use vector version of the intrinsic.
2404 Module *M = State.Builder.getModule();
2405 Function *VectorF =
2406 Intrinsic::getOrInsertDeclaration(M, VectorIntrinsicID, TysForDecl);
2407 assert(VectorF &&
2408 "Can't retrieve vector intrinsic or vector-predication intrinsics.");
2409
2412 if (CI)
2413 CI->getOperandBundlesAsDefs(OpBundles);
2414
2415 CallInst *V = State.Builder.CreateCall(VectorF, Args, OpBundles);
2416
2417 applyFlags(*V);
2418 applyMetadata(*V);
2419
2420 return V;
2421}
2422
2424 CallInst *V = createVectorCall(State);
2425 if (!V->getType()->isVoidTy())
2426 State.set(this, V);
2427}
2428
2431 const VPRecipeWithIRFlags &R, ElementCount VF, VPCostContext &Ctx) {
2432 Type *ScalarRetTy = R.getScalarType();
2433 // Skip the reverse operation cost for the mask.
2434 // FIXME: Remove this once redundant mask reverse operations can be eliminated
2435 // by VPlanTransforms::cse before cost computation.
2436 if (ID == Intrinsic::experimental_vp_reverse && ScalarRetTy->isIntegerTy(1))
2437 return InstructionCost(0);
2438
2439 // Some backends analyze intrinsic arguments to determine cost. Use the
2440 // underlying value for the operand if it has one. Otherwise try to use the
2441 // operand of the underlying call instruction, if there is one. Otherwise
2442 // clear Arguments.
2443 // TODO: Rework TTI interface to be independent of concrete IR values.
2445 for (const auto &[Idx, Op] : enumerate(Operands)) {
2446 auto *V = Op->getUnderlyingValue();
2447 if (!V) {
2448 if (auto *UI = dyn_cast_or_null<CallBase>(R.getUnderlyingValue())) {
2449 Arguments.push_back(UI->getArgOperand(Idx));
2450 continue;
2451 }
2452 Arguments.clear();
2453 break;
2454 }
2455 Arguments.push_back(V);
2456 }
2457
2458 Type *RetTy = VF.isVector() ? toVectorizedTy(ScalarRetTy, VF) : ScalarRetTy;
2459 SmallVector<Type *> ParamTys =
2460 map_to_vector(Operands, [&](const VPValue *Op) {
2461 return toVectorTy(Op->getScalarType(), VF);
2462 });
2463
2465 for (const VPValue *Op : Operands)
2466 if (isa<VPWidenRecipe>(Op) &&
2469 break;
2470 }
2471
2472 // TODO: Rework TTI interface to avoid reliance on underlying IntrinsicInst.
2473 IntrinsicCostAttributes CostAttrs(
2474 ID, RetTy, Arguments, ParamTys, R.getFastMathFlagsOrNone(),
2475 dyn_cast_or_null<IntrinsicInst>(R.getUnderlyingValue()),
2477 return Ctx.TTI.getIntrinsicInstrCost(CostAttrs, Ctx.CostKind);
2478}
2479
2481 VPCostContext &Ctx) const {
2482 return computeCallCost(VectorIntrinsicID, operands(), *this, VF, Ctx);
2483}
2484
2486 return Intrinsic::getBaseName(VectorIntrinsicID);
2487}
2488
2490 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
2491 return all_of(enumerate(operands()), [this, &Op](const auto &X) {
2492 auto [Idx, V] = X;
2494 Idx, nullptr);
2495 });
2496}
2497
2498#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2500 VPSlotTracker &SlotTracker) const {
2501 O << Indent << "WIDEN-INTRINSIC ";
2502 if (getScalarType()->isVoidTy()) {
2503 O << "void ";
2504 } else {
2506 O << " = ";
2507 }
2508
2509 O << "call";
2510 printFlags(O);
2511 O << getIntrinsicName() << "(";
2513 O << ")";
2514}
2515#endif
2516
2518 CallInst *MemI = createVectorCall(State);
2520 MemI->getContext(), Alignment));
2521 if (!MemI->getType()->isVoidTy())
2522 State.set(this, MemI);
2523}
2524
2527 assert(MaskPos && "Expected a memory intrinsic with a valid mask position");
2528 return getOperand(*MaskPos);
2529}
2530
2533 assert(PtrPos && "Expected a memory intrinsic with a valid pointer position");
2534 return *PtrPos;
2535}
2536
2538 Type *DataTy;
2540 DataTy = getOperand(*DataPos)->getScalarType();
2541 else
2542 DataTy = getScalarType();
2543 assert(!DataTy->isVoidTy() && "Expected a non-void data type");
2544 return toVectorTy(DataTy, VF);
2545}
2546
2548 Intrinsic::ID IID, Type *Ty, bool IsMasked, Align Alignment,
2549 VPCostContext &Ctx) {
2550 return Ctx.TTI.getMemIntrinsicInstrCost(
2551 MemIntrinsicCostAttributes(IID, Ty, /*Ptr=*/nullptr, IsMasked, Alignment),
2552 Ctx.CostKind);
2553}
2554
2561
2563 IRBuilderBase &Builder = State.Builder;
2564
2565 Value *Address = State.get(getOperand(0));
2566 Value *IncAmt = State.get(getOperand(1), /*NeedsSingleScalar=*/true);
2567 VectorType *VTy = cast<VectorType>(Address->getType());
2568
2569 // The histogram intrinsic requires a mask even if the recipe doesn't;
2570 // if the mask operand was omitted then all lanes should be executed and
2571 // we just need to synthesize an all-true mask.
2572 Value *Mask = nullptr;
2573 if (VPValue *VPMask = getMask())
2574 Mask = State.get(VPMask);
2575 else
2576 Mask =
2577 Builder.CreateVectorSplat(VTy->getElementCount(), Builder.getInt1(1));
2578
2579 // If this is a subtract, we want to invert the increment amount and use
2580 // the histogram_add intrinsic.
2581 if (mustNegateIncrement())
2582 IncAmt = Builder.CreateNeg(IncAmt);
2583
2584 Instruction *HistogramInst = State.Builder.CreateIntrinsicWithoutFolding(
2585 getHistogramIntrinsicID(), {VTy, IncAmt->getType()},
2586 {Address, IncAmt, Mask});
2587 applyMetadata(*HistogramInst);
2588}
2589
2590Intrinsic::ID VPHistogramRecipe::getHistogramIntrinsicID() const {
2591 switch (UpdateKind) {
2594 return Intrinsic::experimental_vector_histogram_add;
2596 return Intrinsic::experimental_vector_histogram_uadd_sat;
2598 return Intrinsic::experimental_vector_histogram_umax;
2600 return Intrinsic::experimental_vector_histogram_umin;
2601 }
2602 llvm_unreachable("Unknown HistogramUpdateKind");
2603}
2604
2606 VPCostContext &Ctx) const {
2607 // FIXME: Take the gather and scatter into account as well. For now we're
2608 // generating the same cost as the fallback path, but we'll likely
2609 // need to create a new TTI method for determining the cost, including
2610 // whether we can use base + vec-of-smaller-indices or just
2611 // vec-of-pointers.
2612 assert(VF.isVector() && "Invalid VF for histogram cost");
2613 Type *AddressTy = getOperand(0)->getScalarType();
2614 VPValue *IncAmt = getOperand(1);
2615 Type *IncTy = IncAmt->getScalarType();
2616 VectorType *VTy = VectorType::get(IncTy, VF);
2617
2618 // For umin/umax, there's no multiplication — the increment value is compared
2619 // directly. For add/sub/uadd.sat, assume that a non-constant update value
2620 // (or a constant != 1) requires a multiply.
2622 if (!match(IncAmt, m_One()) && UpdateKind != HistogramUpdateKind::UMax &&
2623 UpdateKind != HistogramUpdateKind::UMin)
2624 MulCost =
2625 Ctx.TTI.getArithmeticInstrCost(Instruction::Mul, VTy, Ctx.CostKind);
2626
2627 // Find the cost of the histogram operation itself.
2628 Type *PtrTy = VectorType::get(AddressTy, VF);
2629 Type *MaskTy = VectorType::get(Type::getInt1Ty(Ctx.LLVMCtx), VF);
2630 IntrinsicCostAttributes ICA(getHistogramIntrinsicID(),
2631 Type::getVoidTy(Ctx.LLVMCtx),
2632 {PtrTy, IncTy, MaskTy});
2633
2634 // The histogram intrinsic's TTI cost already includes the update operation
2635 // (load + update + store), so no separate UpdateCost is needed.
2636 return Ctx.TTI.getIntrinsicInstrCost(ICA, Ctx.CostKind) + MulCost;
2637}
2638
2639#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2641 VPSlotTracker &SlotTracker) const {
2642 O << Indent << "WIDEN-HISTOGRAM buckets: ";
2644
2645 switch (UpdateKind) {
2647 O << ", inc: ";
2648 break;
2650 O << ", dec: ";
2651 break;
2653 O << ", saturated inc: ";
2654 break;
2656 O << ", max: ";
2657 break;
2659 O << ", min: ";
2660 break;
2661 }
2663
2664 if (VPValue *Mask = getMask()) {
2665 O << ", mask: ";
2666 Mask->printAsOperand(O, SlotTracker);
2667 }
2668}
2669#endif
2670
2671VPIRFlags::FastMathFlagsTy::FastMathFlagsTy(const FastMathFlags &FMF) {
2672 AllowReassoc = FMF.allowReassoc();
2673 NoNaNs = FMF.noNaNs();
2674 NoInfs = FMF.noInfs();
2675 NoSignedZeros = FMF.noSignedZeros();
2676 AllowReciprocal = FMF.allowReciprocal();
2677 AllowContract = FMF.allowContract();
2678 ApproxFunc = FMF.approxFunc();
2679}
2680
2681VPIRFlags VPIRFlags::getDefaultFlags(unsigned Opcode, Type *ResultTy) {
2682 switch (Opcode) {
2683 case Instruction::Add:
2684 case Instruction::Sub:
2685 case Instruction::Mul:
2686 case Instruction::Shl:
2688 return WrapFlagsTy(false, false);
2689 case Instruction::Trunc:
2690 return TruncFlagsTy(false, false);
2691 case Instruction::Or:
2692 return DisjointFlagsTy(false);
2693 case Instruction::AShr:
2694 case Instruction::LShr:
2695 case Instruction::UDiv:
2696 case Instruction::SDiv:
2697 return ExactFlagsTy(false);
2698 case Instruction::GetElementPtr:
2701 return GEPNoWrapFlags::none();
2702 case Instruction::ZExt:
2703 case Instruction::UIToFP:
2704 return NonNegFlagsTy(false);
2705 case Instruction::FAdd:
2706 case Instruction::FSub:
2707 case Instruction::FMul:
2708 case Instruction::FDiv:
2709 case Instruction::FRem:
2710 case Instruction::FNeg:
2711 case Instruction::FPExt:
2712 case Instruction::FPTrunc:
2713 return FastMathFlags();
2714 case Instruction::Select:
2715 case Instruction::PHI:
2716 case Instruction::Call:
2717 // Selects, phis and calls only have fast-math flags if they have a
2718 // supported floating-point result type.
2720 return FastMathFlags();
2721 return VPIRFlags();
2722 case Instruction::ICmp:
2723 case Instruction::FCmp:
2725 llvm_unreachable("opcode requires explicit flags");
2726 default:
2727 return VPIRFlags();
2728 }
2729}
2730
2731#if !defined(NDEBUG)
2732bool VPIRFlags::flagsValidForOpcode(unsigned Opcode) const {
2733 switch (OpType) {
2734 case OperationType::OverflowingBinOp:
2735 return Opcode == Instruction::Add || Opcode == Instruction::Sub ||
2736 Opcode == Instruction::Mul || Opcode == Instruction::Shl ||
2737 Opcode == VPInstruction::VPInstruction::CanonicalIVIncrementForPart;
2738 case OperationType::Trunc:
2739 return Opcode == Instruction::Trunc;
2740 case OperationType::DisjointOp:
2741 return Opcode == Instruction::Or;
2742 case OperationType::PossiblyExactOp:
2743 return Opcode == Instruction::AShr || Opcode == Instruction::LShr ||
2744 Opcode == Instruction::UDiv || Opcode == Instruction::SDiv;
2745 case OperationType::GEPOp:
2746 return Opcode == Instruction::GetElementPtr ||
2747 Opcode == VPInstruction::PtrAdd ||
2748 Opcode == VPInstruction::WidePtrAdd;
2749 case OperationType::FPMathOp:
2750 return Opcode == Instruction::Call || Opcode == Instruction::FAdd ||
2751 Opcode == Instruction::FMul || Opcode == Instruction::FSub ||
2752 Opcode == Instruction::FNeg || Opcode == Instruction::FDiv ||
2753 Opcode == Instruction::FRem || Opcode == Instruction::FPExt ||
2754 Opcode == Instruction::FPTrunc || Opcode == Instruction::PHI ||
2755 Opcode == Instruction::Select || Opcode == Instruction::SIToFP ||
2756 Opcode == Instruction::UIToFP ||
2757 Opcode == VPInstruction::WideIVStep ||
2759 case OperationType::FCmp:
2760 return Opcode == Instruction::FCmp;
2761 case OperationType::NonNegOp:
2762 return Opcode == Instruction::ZExt || Opcode == Instruction::UIToFP;
2763 case OperationType::Cmp:
2764 return Opcode == Instruction::FCmp || Opcode == Instruction::ICmp;
2765 case OperationType::ReductionOp:
2767 case OperationType::Other:
2768 return true;
2769 }
2770 llvm_unreachable("Unknown OperationType enum");
2771}
2772
2774 Type *ResultTy) const {
2775 // Handle opcodes without default flags.
2776 if (Opcode == Instruction::ICmp)
2777 return OpType == OperationType::Cmp;
2778 if (Opcode == Instruction::FCmp)
2779 return OpType == OperationType::FCmp;
2781 return OpType == OperationType::ReductionOp;
2782
2783 OperationType Required = getDefaultFlags(Opcode, ResultTy).OpType;
2784 return Required == OperationType::Other || Required == OpType;
2785}
2786#endif
2787
2788#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2789static void printRecurrenceKind(raw_ostream &OS, const RecurKind &Kind) {
2790 switch (Kind) {
2791 case RecurKind::None:
2792 OS << "none";
2793 break;
2794 case RecurKind::Add:
2795 OS << "add";
2796 break;
2797 case RecurKind::Sub:
2798 OS << "sub";
2799 break;
2801 OS << "add-chain-with-subs";
2802 break;
2803 case RecurKind::Mul:
2804 OS << "mul";
2805 break;
2806 case RecurKind::Or:
2807 OS << "or";
2808 break;
2809 case RecurKind::And:
2810 OS << "and";
2811 break;
2812 case RecurKind::Xor:
2813 OS << "xor";
2814 break;
2815 case RecurKind::SMin:
2816 OS << "smin";
2817 break;
2818 case RecurKind::SMax:
2819 OS << "smax";
2820 break;
2821 case RecurKind::UMin:
2822 OS << "umin";
2823 break;
2824 case RecurKind::UMax:
2825 OS << "umax";
2826 break;
2827 case RecurKind::FAdd:
2828 OS << "fadd";
2829 break;
2831 OS << "fadd-chain-with-subs";
2832 break;
2833 case RecurKind::FSub:
2834 OS << "fsub";
2835 break;
2836 case RecurKind::FMul:
2837 OS << "fmul";
2838 break;
2839 case RecurKind::FMin:
2840 OS << "fmin";
2841 break;
2842 case RecurKind::FMax:
2843 OS << "fmax";
2844 break;
2845 case RecurKind::FMinNum:
2846 OS << "fminnum";
2847 break;
2848 case RecurKind::FMaxNum:
2849 OS << "fmaxnum";
2850 break;
2852 OS << "fminimum";
2853 break;
2855 OS << "fmaximum";
2856 break;
2858 OS << "fminimumnum";
2859 break;
2861 OS << "fmaximumnum";
2862 break;
2863 case RecurKind::FMulAdd:
2864 OS << "fmuladd";
2865 break;
2866 case RecurKind::AnyOf:
2867 OS << "any-of";
2868 break;
2869 case RecurKind::FindIV:
2870 OS << "find-iv";
2871 break;
2873 OS << "find-last";
2874 break;
2875 }
2876}
2877
2879 switch (OpType) {
2880 case OperationType::Cmp:
2882 break;
2883 case OperationType::FCmp:
2886 break;
2887 case OperationType::DisjointOp:
2888 if (DisjointFlags.IsDisjoint)
2889 O << " disjoint";
2890 break;
2891 case OperationType::PossiblyExactOp:
2892 if (ExactFlags.IsExact)
2893 O << " exact";
2894 break;
2895 case OperationType::OverflowingBinOp:
2896 if (WrapFlags.HasNUW)
2897 O << " nuw";
2898 if (WrapFlags.HasNSW)
2899 O << " nsw";
2900 break;
2901 case OperationType::Trunc:
2902 if (TruncFlags.HasNUW)
2903 O << " nuw";
2904 if (TruncFlags.HasNSW)
2905 O << " nsw";
2906 break;
2907 case OperationType::FPMathOp:
2909 break;
2910 case OperationType::GEPOp: {
2912 if (Flags.isInBounds())
2913 O << " inbounds";
2914 else if (Flags.hasNoUnsignedSignedWrap())
2915 O << " nusw";
2916 if (Flags.hasNoUnsignedWrap())
2917 O << " nuw";
2918 break;
2919 }
2920 case OperationType::NonNegOp:
2921 if (NonNegFlags.NonNeg)
2922 O << " nneg";
2923 break;
2924 case OperationType::ReductionOp: {
2925 O << " (";
2927 if (isReductionInLoop())
2928 O << ", in-loop";
2929 if (isReductionOrdered())
2930 O << ", ordered";
2931 O << ")";
2933 break;
2934 }
2935 case OperationType::Other:
2936 break;
2937 }
2938 O << " ";
2939}
2940#endif
2941
2943 auto &Builder = State.Builder;
2944 switch (Opcode) {
2945 case Instruction::Call:
2946 case Instruction::UncondBr:
2947 case Instruction::CondBr:
2948 case Instruction::PHI:
2949 case Instruction::GetElementPtr:
2950 llvm_unreachable("This instruction is handled by a different recipe.");
2951 case Instruction::UDiv:
2952 case Instruction::SDiv:
2953 case Instruction::SRem:
2954 case Instruction::URem:
2955 case Instruction::Add:
2956 case Instruction::FAdd:
2957 case Instruction::Sub:
2958 case Instruction::FSub:
2959 case Instruction::FNeg:
2960 case Instruction::Mul:
2961 case Instruction::FMul:
2962 case Instruction::FDiv:
2963 case Instruction::FRem:
2964 case Instruction::Shl:
2965 case Instruction::LShr:
2966 case Instruction::AShr:
2967 case Instruction::And:
2968 case Instruction::Or:
2969 case Instruction::Xor: {
2970 // Just widen unops and binops.
2972 for (VPValue *VPOp : operands())
2973 Ops.push_back(State.get(VPOp));
2974
2975 Value *V = Builder.CreateNAryOp(Opcode, Ops);
2976
2977 if (auto *VecOp = dyn_cast<Instruction>(V)) {
2978 applyFlags(*VecOp);
2979 applyMetadata(*VecOp);
2980 }
2981
2982 // Use this vector value for all users of the original instruction.
2983 State.set(this, V);
2984 break;
2985 }
2986 case Instruction::ExtractValue: {
2987 Value *Op = State.get(getOperand(0));
2988 Value *Extract =
2989 Builder.CreateExtractValue(Op, getExtractValueIndices(operands()));
2990 State.set(this, Extract);
2991 break;
2992 }
2993 case Instruction::Freeze: {
2994 Value *Op = State.get(getOperand(0));
2995 Value *Freeze = Builder.CreateFreeze(Op);
2996 State.set(this, Freeze);
2997 break;
2998 }
2999 case Instruction::ICmp:
3000 case Instruction::FCmp: {
3001 // Widen compares. Generate vector compares.
3002 bool FCmp = Opcode == Instruction::FCmp;
3003 Value *A = State.get(getOperand(0));
3004 Value *B = State.get(getOperand(1));
3005 Value *C = nullptr;
3006 if (FCmp) {
3007 C = Builder.CreateFCmp(getPredicate(), A, B);
3008 } else {
3009 C = Builder.CreateICmp(getPredicate(), A, B);
3010 }
3011 if (auto *I = dyn_cast<Instruction>(C)) {
3012 applyFlags(*I);
3013 applyMetadata(*I);
3014 }
3015 State.set(this, C);
3016 break;
3017 }
3018 case Instruction::Select: {
3019 VPValue *CondOp = getOperand(0);
3020 Value *Cond = State.get(CondOp, vputils::isSingleScalar(CondOp));
3021 Value *Op0 = State.get(getOperand(1));
3022 Value *Op1 = State.get(getOperand(2));
3023 Value *Sel = State.Builder.CreateSelect(Cond, Op0, Op1);
3024 State.set(this, Sel);
3025 if (auto *I = dyn_cast<Instruction>(Sel)) {
3027 applyFlags(*I);
3028 applyMetadata(*I);
3029 }
3030 break;
3031 }
3032 default:
3033 // This instruction is not vectorized by simple widening.
3034 LLVM_DEBUG(dbgs() << "LV: Found an unhandled opcode : "
3035 << Instruction::getOpcodeName(Opcode));
3036 llvm_unreachable("Unhandled instruction!");
3037 } // end of switch.
3038
3039#if !defined(NDEBUG)
3040 // Verify that VPlan type inference results agree with the type of the
3041 // generated values.
3042 assert(VectorType::get(this->getScalarType(), State.VF) ==
3043 State.get(this)->getType() &&
3044 "inferred type and type from generated instructions do not match");
3045#endif
3046}
3047
3049 VPCostContext &Ctx) const {
3050 switch (Opcode) {
3051 case Instruction::UDiv:
3052 case Instruction::SDiv:
3053 case Instruction::SRem:
3054 case Instruction::URem:
3055 // If the div/rem operation isn't safe to speculate and requires
3056 // predication, then the only way we can even create a vplan is to insert
3057 // a select on the second input operand to ensure we use the value of 1
3058 // for the inactive lanes. The select will be costed separately.
3059 case Instruction::FNeg:
3060 case Instruction::Add:
3061 case Instruction::FAdd:
3062 case Instruction::Sub:
3063 case Instruction::FSub:
3064 case Instruction::Mul:
3065 case Instruction::FMul:
3066 case Instruction::FDiv:
3067 case Instruction::FRem:
3068 case Instruction::Shl:
3069 case Instruction::LShr:
3070 case Instruction::AShr:
3071 case Instruction::And:
3072 case Instruction::Or:
3073 case Instruction::Xor:
3074 case Instruction::Freeze:
3075 case Instruction::ExtractValue:
3076 case Instruction::ICmp:
3077 case Instruction::FCmp:
3078 case Instruction::Select:
3079 return getCostForRecipeWithOpcode(getOpcode(), VF, Ctx);
3080 default:
3081 llvm_unreachable("Unsupported opcode for instruction");
3082 }
3083}
3084
3085#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3087 VPSlotTracker &SlotTracker) const {
3088 O << Indent << "WIDEN ";
3090 O << " = " << Instruction::getOpcodeName(Opcode);
3091 printFlags(O);
3093}
3094#endif
3095
3097 auto &Builder = State.Builder;
3098 /// Vectorize casts.
3099 assert(State.VF.isVector() && "Not vectorizing?");
3100 Type *DestTy = VectorType::get(getScalarType(), State.VF);
3101 VPValue *Op = getOperand(0);
3102 Value *A = State.get(Op);
3103 Value *Cast = Builder.CreateCast(Instruction::CastOps(Opcode), A, DestTy);
3104 State.set(this, Cast);
3105 if (auto *CastOp = dyn_cast<Instruction>(Cast)) {
3106 applyFlags(*CastOp);
3107 applyMetadata(*CastOp);
3108 }
3109}
3110
3115
3116#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3118 VPSlotTracker &SlotTracker) const {
3119 O << Indent << "WIDEN-CAST ";
3121 O << " = " << Instruction::getOpcodeName(Opcode);
3122 printFlags(O);
3124 O << " to " << *getScalarType();
3125}
3126#endif
3127
3129 VPCostContext &Ctx) const {
3130 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
3131}
3132
3133#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3135 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
3136 O << Indent;
3138 O << " = WIDEN-INDUCTION";
3139 printFlags(O);
3141
3142 if (auto *TI = getTruncInst())
3143 O << " (truncated to " << *TI->getType() << ")";
3144}
3145#endif
3146
3148 // The step may be defined by a recipe in the preheader (e.g. if it requires
3149 // SCEV expansion), but for the canonical induction the step is required to be
3150 // 1, which is represented as live-in.
3151 return match(getStartValue(), m_ZeroInt()) &&
3152 match(getStepValue(), m_One()) &&
3153 getScalarType() == getRegion()->getCanonicalIVType();
3154}
3155
3158 VPCostContext &Ctx) const {
3159 // A widened induction generates a vector phi and increments it by the
3160 // splatted step each iteration.
3162 InstructionCost Cost = Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
3163 Type *StepTy = getScalarType();
3164 unsigned IncOpc = ID.getKind() == InductionDescriptor::IK_IntInduction
3165 ? Instruction::Add
3166 : ID.getInductionOpcode();
3167 assert(IncOpc != Instruction::BinaryOpsEnd &&
3168 "induction must have a valid increment opcode");
3169 return Cost + Ctx.TTI.getArithmeticInstrCost(IncOpc, toVectorTy(StepTy, VF),
3170 Ctx.CostKind);
3171}
3172
3173/// Returns the ConstantFP \p V wraps, or nullptr if it does not wrap one.
3174static const ConstantFP *getConstantFP(const VPValue *V) {
3175 auto *C = dyn_cast<VPConstant>(V);
3176 return C ? dyn_cast<ConstantFP>(C->getConstant()) : nullptr;
3177}
3178
3180 VPCostContext &Ctx) const {
3181 // The cost model for this is modelled on expandVPDerivedIV in
3182 // VPlanTransforms.cpp. In order to avoid overly pessimistic costs that can
3183 // negatively affect vectorization it takes into account any expected
3184 // simplifications that happen in simplifyRecipe.
3185 switch (getInductionKind()) {
3186 default:
3187 // TODO: Compute cost for remaining kinds.
3188 break;
3190 // There are currently no tests that expose a path where all lanes are
3191 // used, so it's better to bail out for now.
3192 if (!vputils::onlyFirstLaneUsed(this))
3193 break;
3194
3195 // Start off by assuming we need both mul and add, then refine this.
3196 bool NeedsMul = true, NeedsAdd = true, NeedsShl = false;
3197
3198 // If the start value is zero the add gets folded away.
3199 if (auto *StartC = dyn_cast<VPConstantInt>(getStartValue()))
3200 NeedsAdd = !StartC->isZero();
3201
3202 // For some values of step the arithmetic changes:
3203 // 1. A step of 1 requires no operation.
3204 // 2. A step of -1 requires a negate.
3205 // 3. A power-of-2 step will use a shl, instead of a mul.
3206 Type *StepTy = getStepValue()->getScalarType();
3208 if (auto *StepC = dyn_cast<VPConstantInt>(getStepValue())) {
3209 if (StepC->isOne())
3210 NeedsMul = false;
3211 else if (StepC->getAPInt().isAllOnes()) {
3212 // This will most likely end up as a negate in simplifyRecipe, and
3213 // the negate will be combined with the add to make a sub.
3214 // NOTE: This is perhaps an invalid assumption that the cost of an
3215 // 'add' is the same as a 'sub'.
3216 NeedsMul = false;
3217 NeedsAdd = true;
3218 } else if (StepC->getAPInt().isPowerOf2()) {
3219 // This will most likely end up as a shift-left in simplifyRecipe
3220 NeedsMul = false;
3221 NeedsShl = true;
3222 }
3223 }
3224
3225 // Add the cost of the conversion from index to step type if the index
3226 // will be used.
3227 Type *IndexTy = getIndex()->getScalarType();
3228 unsigned StepTySize = StepTy->getScalarSizeInBits();
3229 unsigned IndexTySize = IndexTy->getScalarSizeInBits();
3230 if ((NeedsAdd || NeedsMul || NeedsShl) && StepTySize != IndexTySize) {
3231 unsigned CastOpc =
3232 StepTySize < IndexTySize ? Instruction::Trunc : Instruction::ZExt;
3233 Cost += Ctx.TTI.getCastInstrCost(
3234 CastOpc, StepTy, IndexTy, TTI::CastContextHint::None, Ctx.CostKind);
3235 }
3236
3237 if (NeedsMul)
3238 Cost += Ctx.TTI.getArithmeticInstrCost(Instruction::Mul, StepTy,
3239 Ctx.CostKind);
3240 if (NeedsShl)
3241 Cost += Ctx.TTI.getArithmeticInstrCost(
3242 Instruction::Shl, StepTy, Ctx.CostKind,
3243 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
3244 {TargetTransformInfo::OK_UniformConstantValue,
3245 TargetTransformInfo::OP_None});
3246 if (NeedsAdd)
3247 Cost += Ctx.TTI.getArithmeticInstrCost(Instruction::Add, StepTy,
3248 Ctx.CostKind);
3249 return Cost;
3250 }
3252 // There are currently no tests that expose a path where all lanes are
3253 // used, so it's better to bail out for now.
3254 if (!vputils::onlyFirstLaneUsed(this))
3255 break;
3256
3257 // Unlike the integer case, converting the index to the FP step type is
3258 // unavoidable: the index is always the integer canonical IV, so this
3259 // cast is never folded away.
3260 Type *StepTy = getStepValue()->getScalarType();
3261 Type *IndexTy = getIndex()->getScalarType();
3263 Ctx.TTI.getCastInstrCost(Instruction::SIToFP, StepTy, IndexTy,
3264 TTI::CastContextHint::None, Ctx.CostKind);
3265
3266 // If the step is 1.0, the multiply is an exact identity and gets folded
3267 // away, independent of fast-math flags.
3268 const ConstantFP *StepC = getConstantFP(getStepValue());
3269 bool NeedsMul = !StepC || !StepC->isOne();
3270
3271 // "fadd -0.0, X" folds to X unconditionally, but "fadd 0.0, X" only folds
3272 // to X without nsz if X can be proven to never be -0.0, which we cannot, as
3273 // Step may be -0.0.
3274 // TODO: Consider fast-math flags when they are available in
3275 // VPDerivedIVRecipe.
3276 const ConstantFP *StartC = getConstantFP(getStartValue());
3277 bool AddFolds = getFPBinOp()->getOpcode() == Instruction::FAdd && StartC &&
3278 StartC->isZero() && (StartC->isNegZero() || !NeedsMul);
3279
3280 if (NeedsMul)
3281 Cost += Ctx.TTI.getArithmeticInstrCost(Instruction::FMul, StepTy,
3282 Ctx.CostKind);
3283 if (!AddFolds)
3284 Cost += Ctx.TTI.getArithmeticInstrCost(getFPBinOp()->getOpcode(), StepTy,
3285 Ctx.CostKind);
3286 return Cost;
3287 }
3288 }
3289
3290 return 0;
3291}
3292
3293#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3295 VPSlotTracker &SlotTracker) const {
3296 O << Indent;
3298 O << " = DERIVED-IV";
3299 printFlags(O);
3300 getStartValue()->printAsOperand(O, SlotTracker);
3301 O << " + ";
3302 getOperand(1)->printAsOperand(O, SlotTracker);
3303 O << " * ";
3304 getStepValue()->printAsOperand(O, SlotTracker);
3305}
3306#endif
3307
3311
3313 VPCostContext &Ctx) const {
3314 Type *BaseIVTy = getOperand(0)->getScalarType();
3315 assert((BaseIVTy->isIntegerTy() || BaseIVTy->isFloatingPointTy()) &&
3316 "VPScalarIVStepsRecipe is only created for integer and FP inductions");
3317
3318 // If only the first lane is used, then there won't be any code that remains
3319 // in the loop for the first unrolled part.
3321 return 0;
3322
3323 // If the vector body executes at most once, the canonical IV is a constant
3324 // and every lane's step folds away with it.
3325 if (VPCostContext::executesAtMostOnce(*getParent()->getPlan(), VF))
3326 return 0;
3327
3328 // Typically the operations are:
3329 // 1. Add the start index to each lane value.
3330 // 2. Multiply the start index by the step.
3331 // 3. Add the scaled start index to base IV.
3332 // Any code generated for 1 and 2 should be loop invariant and therefore
3333 // hoisted out of the loop. We only need to add on the cost of 3.
3335 if (BaseIVTy->isFloatingPointTy()) {
3336 // Unlike the integer case, the users of an FP induction cannot be re-based
3337 // on a common value, so each lane needs its own FAdd/FSub.
3338 assert(!VF.isScalable() &&
3339 "FP scalar steps for all lanes are only created for fixed VFs");
3340 Cost = Ctx.TTI.getArithmeticInstrCost(InductionOpcode, BaseIVTy,
3341 Ctx.CostKind) *
3342 (VF.getFixedValue() - 1);
3343 } else {
3344 // Given the users of VPScalarIVStepsRecipe tend to be scalarized GEPs, i.e.
3345 // %add1 = add i32 %iv, 0
3346 // %add2 = add i32 %iv, 1
3347 // %gep1 = getelementptr i8, ptr %p, i32 %add1
3348 // %gep2 = getelementptr i8, ptr %p, i32 %add2
3349 // it's very likely that these GEPs will all be rewritten to have a common
3350 // base such that what's left is just
3351 // %base_gep = getelementptr i8, ptr %p, i32 %iv
3352 // %gep1 = getelementptr i8, ptr %base_gep, i32 0
3353 // %gep2 = getelementptr i8, ptr %base_gep, i32 1
3354 // Therefore, in reality the cost is somewhere betwen 1*AddCost and
3355 // (NumLanes - 1) * AddCost. For now, assume the cost of a single add.
3356 Cost = Ctx.TTI.getArithmeticInstrCost(Instruction::Add, BaseIVTy,
3357 Ctx.CostKind);
3358 }
3359
3360 // If the steps are generated inside a replicate region, scale by execution
3361 // probability.
3362 const VPRegionBlock *Region = getRegion();
3363 if (Region && Region->isReplicator())
3364 Cost /= Ctx.getCostDivisor(
3365 Region->getEntryBranchOnMask()->getExecutionFrequency());
3366 return Cost;
3367}
3368
3370 // Fast-math-flags propagate from the original induction instruction.
3371 IRBuilder<>::FastMathFlagGuard FMFG(State.Builder);
3372 State.Builder.setFastMathFlags(getFastMathFlagsOrNone());
3373
3374 /// Compute scalar induction steps. \p ScalarIV is the scalar induction
3375 /// variable on which to base the steps, \p Step is the size of the step.
3376
3377 Value *BaseIV = State.get(getOperand(0), VPLane(0));
3378 Value *Step = State.get(getStepValue(), VPLane(0));
3379 IRBuilderBase &Builder = State.Builder;
3380
3381 // Ensure step has the same type as that of scalar IV.
3382 Type *BaseIVTy = BaseIV->getType()->getScalarType();
3383 assert(BaseIVTy == Step->getType() && "Types of BaseIV and Step must match!");
3384
3385 // We build scalar steps for both integer and floating-point induction
3386 // variables. Here, we determine the kind of arithmetic we will perform.
3389 if (BaseIVTy->isIntegerTy()) {
3390 AddOp = Instruction::Add;
3391 MulOp = Instruction::Mul;
3392 } else {
3393 AddOp = InductionOpcode;
3394 MulOp = Instruction::FMul;
3395 }
3396
3397 // Lanes other than the first have been materialized as separate
3398 // single-scalar recipes by replicateByVF, each with its own start index.
3399 assert((vputils::onlyFirstLaneUsed(this) || State.VF.isScalar()) &&
3400 "must have been replicated by VF");
3401 Value *StartIdx = getStartIndex() ? State.get(getStartIndex(), true)
3402 : Constant::getNullValue(BaseIVTy);
3403 auto *Mul = Builder.CreateBinOp(MulOp, StartIdx, Step);
3404 auto *Add = Builder.CreateBinOp(AddOp, BaseIV, Mul);
3405 State.set(this, Add, VPLane(0));
3406}
3407
3408#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3410 VPSlotTracker &SlotTracker) const {
3411 O << Indent;
3413 O << " = SCALAR-STEPS ";
3415}
3416#endif
3417
3419 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
3421}
3422
3424 assert(State.VF.isVector() && "not widening");
3425 auto Ops = map_to_vector(operands(), [&](VPValue *Op) {
3426 return State.get(Op, vputils::isSingleScalar(Op));
3427 });
3428 auto *GEP =
3429 State.Builder.CreateGEP(getSourceElementType(), Ops.front(),
3430 drop_begin(Ops), "wide.gep", getGEPNoWrapFlags());
3431 State.set(this, GEP, vputils::isSingleScalar(this));
3432}
3433
3434#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3436 VPSlotTracker &SlotTracker) const {
3437 O << Indent << "WIDEN-GEP ";
3439 O << " = getelementptr";
3440 printFlags(O);
3442}
3443#endif
3444
3446 assert(!getOffset() && "Unexpected offset operand");
3447 VPBuilder Builder(this);
3448 VPlan &Plan = *getParent()->getPlan();
3449 VPValue *VFVal = getVFValue();
3450 const DataLayout &DL = Plan.getDataLayout();
3451 Type *IndexTy = DL.getIndexType(this->getScalarType());
3452 VPValue *Stride =
3453 Plan.getConstantInt(IndexTy, getStride(), /*IsSigned=*/true);
3454 VPValue *VF =
3455 Builder.createScalarZExtOrTrunc(VFVal, IndexTy, DebugLoc::getUnknown());
3456
3457 // Offset for Part0 = Offset0 = Stride * (VF - 1).
3458 VPInstruction *VFMinusOne =
3459 Builder.createSub(VF, Plan.getConstantInt(IndexTy, 1u),
3460 DebugLoc::getUnknown(), "", {true, true});
3461 VPInstruction *Offset0 =
3462 Builder.createOverflowingOp(Instruction::Mul, {VFMinusOne, Stride});
3463
3464 // Offset for PartN = Offset0 + Part * Stride * VF.
3465 VPValue *PartxStride =
3466 Plan.getConstantInt(IndexTy, Part * getStride(), /*IsSigned=*/true);
3467 VPValue *Offset = Builder.createAdd(
3468 Offset0,
3469 Builder.createOverflowingOp(Instruction::Mul, {PartxStride, VF}));
3471}
3472
3474 auto &Builder = State.Builder;
3475 assert(getOffset() && "Expected prior materialization of offset");
3476 Value *Ptr = State.get(getPointer(), true);
3477 Value *Offset = State.get(getOffset(), true);
3478 Value *ResultPtr = Builder.CreateGEP(getSourceElementType(), Ptr, Offset, "",
3480 State.set(this, ResultPtr, /*IsScalar*/ true);
3481}
3482
3483#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3485 VPSlotTracker &SlotTracker) const {
3486 O << Indent;
3488 O << " = vector-end-pointer";
3489 printFlags(O);
3490 getSourceElementType()->print(O);
3491 O << ", ";
3493}
3494#endif
3495
3497 assert(getVFxPart() &&
3498 "Expected prior simplification of recipe without VFxPart");
3499
3500 auto &Builder = State.Builder;
3501 Value *Ptr = State.get(getOperand(0), VPLane(0));
3502 Value *Offset = State.get(getVFxPart(), true);
3503 // TODO: Expand to VPInstruction to support constant folding.
3504 if (!match(getStride(), m_One())) {
3505 Value *Stride = Builder.CreateZExtOrTrunc(State.get(getStride(), true),
3506 Offset->getType());
3507 Offset = Builder.CreateMul(Offset, Stride);
3508 }
3509 Value *ResultPtr = Builder.CreateGEP(getSourceElementType(), Ptr, Offset, "",
3511 State.set(this, ResultPtr, /*IsScalar*/ true);
3512}
3513
3514#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3516 VPSlotTracker &SlotTracker) const {
3517 O << Indent;
3519 O << " = vector-pointer";
3520 printFlags(O);
3521 getSourceElementType()->print(O);
3522 O << ", ";
3524}
3525#endif
3526
3528 VPCostContext &Ctx) const {
3529 // A blend will be expanded to a select VPInstruction, which will generate a
3530 // scalar select if only the first lane is used.
3532 VF = ElementCount::getFixed(1);
3533
3534 Type *ResultTy = toVectorTy(this->getScalarType(), VF);
3535 Type *CmpTy = toVectorTy(Type::getInt1Ty(Ctx.LLVMCtx), VF);
3536
3538 for (unsigned I = 1, E = getNumIncomingValues(); I != E; ++I) {
3539 CmpPredicate Pred;
3540 if (!match(getMask(I), m_Cmp(Pred, m_VPValue(), m_VPValue())))
3541 Pred = getScalarType()->isFloatingPointTy() ? CmpInst::BAD_FCMP_PREDICATE
3543 Cost += Ctx.TTI.getCmpSelInstrCost(Instruction::Select, ResultTy, CmpTy,
3544 Pred, Ctx.CostKind);
3545 }
3546 return Cost;
3547}
3548
3549#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3551 VPSlotTracker &SlotTracker) const {
3552 O << Indent << "BLEND ";
3554 O << " =";
3555 printFlags(O);
3556 if (getNumIncomingValues() == 1) {
3557 // Not a User of any mask: not really blending, this is a
3558 // single-predecessor phi.
3559 getIncomingValue(0)->printAsOperand(O, SlotTracker);
3560 } else {
3561 for (unsigned I = 0, E = getNumIncomingValues(); I < E; ++I) {
3562 if (I != 0)
3563 O << " ";
3564 getIncomingValue(I)->printAsOperand(O, SlotTracker);
3565 if (I == 0 && isNormalized())
3566 continue;
3567 O << "/";
3568 getMask(I)->printAsOperand(O, SlotTracker);
3569 }
3570 }
3571}
3572#endif
3573
3577 "In-loop AnyOf reductions aren't currently supported");
3578 // Propagate the fast-math flags carried by the underlying instruction.
3579 IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder);
3580 State.Builder.setFastMathFlags(getFastMathFlagsOrNone());
3581 Value *NewVecOp = State.get(getVecOp());
3582 if (VPValue *Cond = getCondOp()) {
3583 Value *NewCond = State.get(Cond, State.VF.isScalar());
3584 VectorType *VecTy = dyn_cast<VectorType>(NewVecOp->getType());
3585 Type *ElementTy = VecTy ? VecTy->getElementType() : NewVecOp->getType();
3586
3587 Value *Start =
3589 if (State.VF.isVector())
3590 Start = State.Builder.CreateVectorSplat(VecTy->getElementCount(), Start);
3591
3592 Value *Select = State.Builder.CreateSelect(NewCond, NewVecOp, Start);
3593 NewVecOp = Select;
3594 }
3595 Value *NewRed;
3596 Value *NextInChain;
3597 if (isOrdered()) {
3598 Value *PrevInChain = State.get(getChainOp(), /*NeedsSingleScalar=*/true);
3599 if (State.VF.isVector())
3600 NewRed =
3601 createOrderedReduction(State.Builder, Kind, NewVecOp, PrevInChain);
3602 else
3603 NewRed = State.Builder.CreateBinOp(
3605 PrevInChain, NewVecOp);
3606 PrevInChain = NewRed;
3607 NextInChain = NewRed;
3608 } else if (isPartialReduction()) {
3609 assert((Kind == RecurKind::Add || Kind == RecurKind::FAdd) &&
3610 "Unexpected partial reduction kind");
3611 Value *PrevInChain = State.get(getChainOp(), /*NeedsSingleScalar=*/false);
3612 NewRed = State.Builder.CreateIntrinsic(
3613 PrevInChain->getType(),
3614 Kind == RecurKind::Add ? Intrinsic::vector_partial_reduce_add
3615 : Intrinsic::vector_partial_reduce_fadd,
3616 {PrevInChain, NewVecOp}, State.Builder.getFastMathFlags(),
3617 "partial.reduce");
3618 PrevInChain = NewRed;
3619 NextInChain = NewRed;
3620 } else {
3621 assert(isInLoop() &&
3622 "The reduction must either be ordered, partial or in-loop");
3623 Value *PrevInChain = State.get(getChainOp(), /*NeedsSingleScalar=*/true);
3624 NewRed = createSimpleReduction(State.Builder, NewVecOp, Kind);
3626 NextInChain = createMinMaxOp(State.Builder, Kind, NewRed, PrevInChain);
3627 else
3628 NextInChain = State.Builder.CreateBinOp(
3630 PrevInChain, NewRed);
3631 }
3632 State.set(this, NextInChain, /*IsScalar*/ !isPartialReduction());
3633}
3634
3636
3637 assert(State.VF.isVector() &&
3638 "Shouldn't generate VPReductionEVLRecipe with scalar VF");
3639 auto &Builder = State.Builder;
3640 // Propagate the fast-math flags carried by the underlying instruction.
3641 IRBuilderBase::FastMathFlagGuard FMFGuard(Builder);
3642 Builder.setFastMathFlags(getFastMathFlagsOrNone());
3643
3645 Value *Prev =
3646 State.get(getChainOp(), /*NeedsSingleScalar=*/!isPartialReduction());
3647 Value *VecOp = State.get(getVecOp());
3648 Value *EVL = State.get(getEVL(), VPLane(0));
3649
3650 Value *Mask;
3651 if (VPValue *CondOp = getCondOp())
3652 Mask = State.get(CondOp);
3653 else
3654 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
3655
3656 Value *NewRed;
3657 if (isPartialReduction()) {
3658 // For partial reductions, we need to generate a predicated select
3659 // (vp.merge) since `@llvm.vector.partial.reduce()` doesn't have a vector
3660 // predicated version.
3661 VectorType *VecTy = cast<VectorType>(VecOp->getType());
3662 Value *Identity = getRecurrenceIdentity(Kind, VecTy->getElementType(),
3664 Identity =
3665 State.Builder.CreateVectorSplat(VecTy->getElementCount(), Identity);
3666
3667 // TODO: Calculate the predicate cost for the partial reduction.
3668 Value *NewVecOp = State.Builder.CreateIntrinsic(
3669 VecTy, Intrinsic::vp_merge, {Mask, VecOp, Identity, EVL});
3670 assert((Kind == RecurKind::Add || Kind == RecurKind::FAdd) &&
3671 "Unexpected partial reduction kind");
3672 NewRed = State.Builder.CreateIntrinsic(
3673 Prev->getType(),
3674 Kind == RecurKind::Add ? Intrinsic::vector_partial_reduce_add
3675 : Intrinsic::vector_partial_reduce_fadd,
3676 {Prev, NewVecOp}, State.Builder.getFastMathFlags(), "partial.reduce");
3677 } else if (isOrdered()) {
3678 NewRed = createOrderedReduction(Builder, Kind, VecOp, Prev, Mask, EVL);
3679 } else {
3680 NewRed = createSimpleReduction(Builder, VecOp, Kind, Mask, EVL);
3682 NewRed = createMinMaxOp(Builder, Kind, NewRed, Prev);
3683 else
3684 NewRed = Builder.CreateBinOp(
3686 Prev);
3687 }
3688 State.set(this, NewRed, !isPartialReduction());
3689}
3690
3692 VPCostContext &Ctx) const {
3693 RecurKind RdxKind = getRecurrenceKind();
3694 Type *ElementTy = this->getScalarType();
3695 auto *VectorTy = cast<VectorType>(toVectorTy(ElementTy, VF));
3696 unsigned Opcode = RecurrenceDescriptor::getOpcode(RdxKind);
3698 std::optional<FastMathFlags> OptionalFMF =
3699 ElementTy->isFloatingPointTy() ? std::make_optional(FMFs) : std::nullopt;
3700
3701 if (isPartialReduction()) {
3702 InstructionCost CondCost = 0;
3703 if (isConditional()) {
3705 auto *CondTy =
3707 CondCost = Ctx.TTI.getCmpSelInstrCost(Instruction::Select, VectorTy,
3708 CondTy, Pred, Ctx.CostKind);
3709 }
3710 return CondCost + Ctx.TTI.getPartialReductionCost(
3711 Opcode, ElementTy, nullptr, ElementTy, VF,
3712 TTI::PR_None, TTI::PR_None, {}, Ctx.CostKind,
3713 OptionalFMF);
3714 }
3715
3716 // TODO: Support any-of reductions.
3717 assert(
3719 ForceTargetInstructionCost.getNumOccurrences() > 0) &&
3720 "Any-of reduction not implemented in VPlan-based cost model currently.");
3721
3722 // Note that TTI should model the cost of moving result to the scalar register
3723 // and the BinOp cost in the getMinMaxReductionCost().
3726 return Ctx.TTI.getMinMaxReductionCost(Id, VectorTy, FMFs, Ctx.CostKind);
3727 }
3728
3729 // Note that TTI should model the cost of moving result to the scalar register
3730 // and the BinOp cost in the getArithmeticReductionCost().
3731 return Ctx.TTI.getArithmeticReductionCost(Opcode, VectorTy, OptionalFMF,
3732 Ctx.CostKind);
3733}
3734
3736 ExpressionTypes ExpressionType,
3737 ArrayRef<VPSingleDefRecipe *> ExpressionRecipes)
3738 : VPSingleDefRecipe(VPRecipeBase::VPExpressionSC, {},
3739 cast<VPReductionRecipe>(ExpressionRecipes.back())
3740 ->getChainOp()
3741 ->getScalarType()),
3742 ExpressionRecipes(ExpressionRecipes), ExpressionType(ExpressionType) {
3743 assert(!ExpressionRecipes.empty() && "Nothing to combine?");
3744 assert(
3745 none_of(ExpressionRecipes,
3746 [](VPSingleDefRecipe *R) { return R->mayHaveSideEffects(); }) &&
3747 "expression cannot contain recipes with side-effects");
3748
3749 // Maintain a copy of the expression recipes as a set of users.
3750 SmallPtrSet<VPUser *, 4> ExpressionRecipesAsSetOfUsers;
3751 for (auto *R : ExpressionRecipes)
3752 ExpressionRecipesAsSetOfUsers.insert(R);
3753
3754 // Recipes in the expression, except the last one, must only be used by
3755 // (other) recipes inside the expression. If there are other users, external
3756 // to the expression, use a clone of the recipe for external users.
3757 for (VPSingleDefRecipe *R : reverse(ExpressionRecipes)) {
3758 if (R != ExpressionRecipes.back() &&
3759 any_of(R->users(), [&ExpressionRecipesAsSetOfUsers](VPUser *U) {
3760 return !ExpressionRecipesAsSetOfUsers.contains(U);
3761 })) {
3762 // There are users outside of the expression. Clone the recipe and use the
3763 // clone those external users.
3764 VPSingleDefRecipe *CopyForExtUsers = R->clone();
3765 R->replaceUsesWithIf(CopyForExtUsers,
3766 [&ExpressionRecipesAsSetOfUsers](VPUser &U) {
3767 return !ExpressionRecipesAsSetOfUsers.contains(&U);
3768 });
3769 CopyForExtUsers->insertBefore(R);
3770 }
3771 if (R->getParent())
3772 R->removeFromParent();
3773 }
3774
3775 // Internalize all external operands to the expression recipes. To do so,
3776 // create new temporary VPValues for all operands defined by a recipe outside
3777 // the expression. The original operands are added as operands of the
3778 // VPExpressionRecipe itself.
3779 for (auto *R : ExpressionRecipes) {
3780 for (const auto &[Idx, Op] : enumerate(R->operands())) {
3781 auto *Def = Op->getDefiningRecipe();
3782 if (Def && ExpressionRecipesAsSetOfUsers.contains(Def))
3783 continue;
3784 addOperand(Op);
3785 LiveInPlaceholders.push_back(new VPSymbolicValue(Op->getScalarType()));
3786 }
3787 }
3788
3789 // Replace each external operand with the first one created for it in
3790 // LiveInPlaceholders.
3791 for (auto *R : ExpressionRecipes)
3792 for (auto const &[LiveIn, Tmp] : zip(operands(), LiveInPlaceholders))
3793 R->replaceUsesOfWith(LiveIn, Tmp);
3794}
3795
3797 for (auto *R : ExpressionRecipes)
3798 // Since the list could contain duplicates, make sure the recipe hasn't
3799 // already been inserted.
3800 if (!R->getParent())
3801 R->insertBefore(this);
3802
3803 for (const auto &[Idx, Op] : enumerate(operands()))
3804 LiveInPlaceholders[Idx]->replaceAllUsesWith(Op);
3805
3806 replaceAllUsesWith(ExpressionRecipes.back());
3807 SmallVector<VPSingleDefRecipe *> DecomposedRecipes(ExpressionRecipes);
3808 ExpressionRecipes.clear();
3809 return DecomposedRecipes;
3810}
3811
3813 VPCostContext &Ctx) const {
3814 Type *RedTy = this->getScalarType();
3815 auto *SrcVecTy =
3817 unsigned Opcode = RecurrenceDescriptor::getOpcode(
3818 cast<VPReductionRecipe>(ExpressionRecipes.back())->getRecurrenceKind());
3819 switch (ExpressionType) {
3820 case ExpressionTypes::NegatedExtendedReduction:
3821 assert((Opcode == Instruction::Add || Opcode == Instruction::FAdd) &&
3822 "Unexpected opcode");
3823 Opcode = Opcode == Instruction::Add ? Instruction::Sub : Instruction::FSub;
3824 [[fallthrough]];
3825 case ExpressionTypes::ExtendedReduction: {
3826 auto *RedR = cast<VPReductionRecipe>(ExpressionRecipes.back());
3827 auto *ExtR = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3828
3829 if (RedR->isPartialReduction())
3830 return Ctx.TTI.getPartialReductionCost(
3831 Opcode, getOperand(0)->getScalarType(), nullptr, RedTy, VF,
3833 TargetTransformInfo::PR_None, std::nullopt, Ctx.CostKind,
3834 RedTy->isFloatingPointTy()
3835 ? std::optional{RedR->getFastMathFlagsOrNone()}
3836 : std::nullopt);
3837 else if (!RedTy->isFloatingPointTy())
3838 // TTI::getExtendedReductionCost only supports integer types.
3839 return Ctx.TTI.getExtendedReductionCost(
3840 Opcode, ExtR->getOpcode() == Instruction::ZExt, RedTy, SrcVecTy,
3841 std::nullopt, Ctx.CostKind);
3842 else
3844 }
3845 case ExpressionTypes::MulAccReduction:
3846 return Ctx.TTI.getMulAccReductionCost(false, Opcode, RedTy, SrcVecTy,
3847 Ctx.CostKind);
3848
3849 case ExpressionTypes::ExtNegatedMulAccReduction:
3850 switch (Opcode) {
3851 case Instruction::Add:
3852 Opcode = Instruction::Sub;
3853 break;
3854 case Instruction::FAdd:
3855 Opcode = Instruction::FSub;
3856 break;
3857 default:
3858 llvm_unreachable("Unsupported opcode for ExtNegatedMulAccReduction");
3859 }
3860 [[fallthrough]];
3861 case ExpressionTypes::ExtMulAccReduction: {
3862 auto *RedR = cast<VPReductionRecipe>(ExpressionRecipes.back());
3863 if (RedR->isPartialReduction()) {
3864 auto *Ext0R = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3865 auto *Ext1R = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
3866 auto *Mul = cast<VPWidenRecipe>(ExpressionRecipes[2]);
3867 return Ctx.TTI.getPartialReductionCost(
3868 Opcode, getOperand(0)->getScalarType(),
3869 getOperand(1)->getScalarType(), RedTy, VF,
3871 Ext0R->getOpcode()),
3873 Ext1R->getOpcode()),
3874 Mul->getOpcode(), Ctx.CostKind,
3875 RedTy->isFloatingPointTy()
3876 ? std::optional{RedR->getFastMathFlagsOrNone()}
3877 : std::nullopt);
3878 }
3879 assert(Opcode != Instruction::FSub && "Only integer types are supported");
3880 return Ctx.TTI.getMulAccReductionCost(
3881 cast<VPWidenCastRecipe>(ExpressionRecipes.front())->getOpcode() ==
3882 Instruction::ZExt,
3883 Opcode, RedTy, SrcVecTy, Ctx.CostKind);
3884 }
3885 }
3886 llvm_unreachable("Unknown VPExpressionRecipe::ExpressionTypes enum");
3887}
3888
3890 return any_of(ExpressionRecipes, [](VPSingleDefRecipe *R) {
3891 return R->mayReadFromMemory() || R->mayWriteToMemory();
3892 });
3893}
3894
3896 assert(
3897 none_of(ExpressionRecipes,
3898 [](VPSingleDefRecipe *R) { return R->mayHaveSideEffects(); }) &&
3899 "expression cannot contain recipes with side-effects");
3900 return false;
3901}
3902
3904 auto *RR = dyn_cast<VPReductionRecipe>(ExpressionRecipes.back());
3905 return RR && !RR->isPartialReduction();
3906}
3907
3908#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3909
3911 VPSlotTracker &SlotTracker) const {
3912 O << Indent << "EXPRESSION ";
3914 O << " = ";
3915 auto *Red = cast<VPReductionRecipe>(ExpressionRecipes.back());
3916 unsigned Opcode = RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind());
3917 VPValue *Mask = getLastOperand();
3918 VPValue *EVL =
3920 ? getOperand(getNumOperands() - (Red->isConditional() ? 2 : 1))
3921 : nullptr;
3922 VPValue *RdxStart = getOperand(
3923 getNumOperands() - (Red->isConditional() ? 2 : 1) - (EVL ? 1 : 0));
3924 auto PrintEVLAndMask = [&]() {
3925 if (EVL) {
3926 O << ", ";
3927 EVL->printAsOperand(O, SlotTracker);
3928 }
3929 if (Red->isConditional()) {
3930 O << ", ";
3931 Mask->printAsOperand(O, SlotTracker);
3932 }
3933 };
3934
3935 switch (ExpressionType) {
3936 case ExpressionTypes::NegatedExtendedReduction:
3937 case ExpressionTypes::ExtendedReduction: {
3938 bool Negated = ExpressionType == ExpressionTypes::NegatedExtendedReduction;
3940 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
3941 O << Instruction::getOpcodeName(Opcode) << " (";
3942 if (Negated)
3943 O << (Opcode == Instruction::Add ? "sub (0, " : "fneg(");
3945 if (Negated)
3946 O << ")";
3947 Red->printFlags(O);
3948
3949 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3950 O << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
3951 << *Ext0->getScalarType();
3952 PrintEVLAndMask();
3953 O << ")";
3954 break;
3955 }
3956 case ExpressionTypes::ExtNegatedMulAccReduction: {
3957 RdxStart->printAsOperand(O, SlotTracker);
3958 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
3960 RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind()))
3961 << " (sub (0, mul";
3962 auto *Mul = cast<VPWidenRecipe>(ExpressionRecipes[2]);
3963 Mul->printFlags(O);
3964 O << "(";
3966 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3967 O << " " << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
3968 << *Ext0->getScalarType() << "), (";
3970 auto *Ext1 = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
3971 O << " " << Instruction::getOpcodeName(Ext1->getOpcode()) << " to "
3972 << *Ext1->getScalarType() << ")";
3973 PrintEVLAndMask();
3974 O << "))";
3975 break;
3976 }
3977 case ExpressionTypes::MulAccReduction:
3978 case ExpressionTypes::ExtMulAccReduction: {
3979 RdxStart->printAsOperand(O, SlotTracker);
3980 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
3982 RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind()))
3983 << " (";
3984 O << "mul";
3985 bool IsExtended = ExpressionType == ExpressionTypes::ExtMulAccReduction;
3986 auto *Mul = cast<VPWidenRecipe>(IsExtended ? ExpressionRecipes[2]
3987 : ExpressionRecipes[0]);
3988 Mul->printFlags(O);
3989 if (IsExtended)
3990 O << "(";
3992 if (IsExtended) {
3993 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3994 O << " " << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
3995 << *Ext0->getScalarType() << "), (";
3996 } else {
3997 O << ", ";
3998 }
4000 if (IsExtended) {
4001 auto *Ext1 = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
4002 O << " " << Instruction::getOpcodeName(Ext1->getOpcode()) << " to "
4003 << *Ext1->getScalarType() << ")";
4004 }
4005 PrintEVLAndMask();
4006 O << ")";
4007 break;
4008 }
4009 }
4010}
4011
4013 VPSlotTracker &SlotTracker) const {
4014 if (isPartialReduction())
4015 O << Indent << "PARTIAL-REDUCE ";
4016 else
4017 O << Indent << "REDUCE ";
4019 O << " = ";
4021 O << " +";
4022 printFlags(O);
4023 O << " reduce.";
4025 O << " (";
4027 if (isConditional()) {
4028 O << ", ";
4030 }
4031 O << ")";
4032}
4033
4035 VPSlotTracker &SlotTracker) const {
4036 if (isPartialReduction())
4037 O << Indent << "PARTIAL-REDUCE ";
4038 else
4039 O << Indent << "REDUCE ";
4041 O << " = ";
4043 O << " +";
4044 printFlags(O);
4045 O << " vp.reduce."
4048 << " (";
4050 O << ", ";
4052 if (isConditional()) {
4053 O << ", ";
4055 }
4056 O << ")";
4057}
4058
4059#endif
4060
4062 assert(IsSingleScalar &&
4063 "VPReplicateRecipes must be unrolled before ::execute");
4064 auto *Instr = getUnderlyingInstr();
4065 Instruction *Cloned = Instr->clone();
4066 Type *ResultTy = getScalarType();
4067 if (!ResultTy->isVoidTy()) {
4068 Cloned->setName(Instr->getName() + ".cloned");
4069 // The operands of the replicate recipe may have been narrowed, resulting in
4070 // a narrower result type. Update the type of the cloned instruction to the
4071 // correct type.
4072 if (ResultTy != Cloned->getType())
4073 Cloned->mutateType(ResultTy);
4074 }
4075
4076 applyFlags(*Cloned);
4077 applyMetadata(*Cloned);
4078
4079 if (hasPredicate())
4080 cast<CmpInst>(Cloned)->setPredicate(getPredicate());
4081
4082 // Replace the operands of the cloned instructions with their scalar
4083 // equivalents in the new loop.
4084 for (unsigned Idx : seq(Cloned->getNumOperands()))
4085 Cloned->setOperand(Idx, State.get(getOperand(Idx), true));
4086
4087 // Place the cloned scalar in the new loop.
4088 State.Builder.Insert(Cloned);
4089
4090 State.set(this, Cloned, true);
4091
4092 // If we just cloned a new assumption, add it the assumption cache.
4093 if (auto *II = dyn_cast<AssumeInst>(Cloned))
4094 State.AC->registerAssumption(II);
4095}
4096
4097/// Returns a SCEV expression for \p Ptr if it is a pointer computation for
4098/// which the legacy cost model computes a SCEV expression when computing the
4099/// address cost. Computing SCEVs for VPValues is incomplete and returns
4100/// SCEVCouldNotCompute in cases the legacy cost model can compute SCEVs. In
4101/// those cases we fall back to the legacy cost model. Otherwise return nullptr.
4102static const SCEV *getAddressAccessSCEV(const VPValue *Ptr,
4104 const Loop *L) {
4105 const SCEV *Addr = vputils::getSCEVExprForVPValue(Ptr, PSE, L);
4106 if (isa<SCEVCouldNotCompute>(Addr))
4107 return Addr;
4108
4109 return vputils::isAddressSCEVForCost(Addr, *PSE.getSE(), L) ? Addr : nullptr;
4110}
4111
4113 VPCostContext &Ctx) const {
4115 // VPReplicateRecipe may be cloned as part of an existing VPlan-to-VPlan
4116 // transform, avoid computing their cost multiple times for now.
4117 Ctx.SkipCostComputation.insert(UI);
4118
4119 if (VF.isScalable() && !isSingleScalar())
4121
4122 switch (UI->getOpcode()) {
4123 case Instruction::Alloca:
4124 if (VF.isScalable())
4126 return Ctx.TTI.getArithmeticInstrCost(Instruction::Mul,
4127 this->getScalarType(), Ctx.CostKind);
4128 case Instruction::GetElementPtr:
4129 // We mark this instruction as zero-cost because the cost of GEPs in
4130 // vectorized code depends on whether the corresponding memory instruction
4131 // is scalarized or not. Therefore, we handle GEPs with the memory
4132 // instruction cost.
4133 return 0;
4134 case Instruction::Call: {
4135 auto *CalledFn = cast<Function>(getLastOperand()->getLiveInIRValue());
4136 Type *ResultTy = this->getScalarType();
4137 return computeCallCost(CalledFn, ResultTy, drop_end(operands()),
4138 isSingleScalar(), VF, Ctx);
4139 }
4140 case Instruction::Add:
4141 case Instruction::Sub:
4142 case Instruction::FAdd:
4143 case Instruction::FSub:
4144 case Instruction::Mul:
4145 case Instruction::FMul:
4146 case Instruction::FDiv:
4147 case Instruction::FRem:
4148 case Instruction::Shl:
4149 case Instruction::LShr:
4150 case Instruction::AShr:
4151 case Instruction::And:
4152 case Instruction::Or:
4153 case Instruction::Xor:
4154 case Instruction::ICmp:
4155 case Instruction::FCmp:
4157 Ctx) *
4158 (isSingleScalar() ? 1 : VF.getFixedValue());
4159 case Instruction::SDiv:
4160 case Instruction::UDiv:
4161 case Instruction::SRem:
4162 case Instruction::URem: {
4163 InstructionCost ScalarCost =
4165 if (isSingleScalar())
4166 return ScalarCost;
4167
4168 // If any of the operands is from a different replicate region and has its
4169 // cost skipped, it may have been forced to scalar. Fall back to legacy cost
4170 // model to avoid cost mis-match.
4171 if (any_of(operands(), [&Ctx, VF](VPValue *Op) {
4172 auto *PredR = dyn_cast<VPPredInstPHIRecipe>(Op);
4173 if (!PredR)
4174 return false;
4175 return Ctx.skipCostComputation(
4177 PredR->getOperand(0)->getUnderlyingValue()),
4178 VF.isVector());
4179 }))
4180 break;
4181
4182 ScalarCost = ScalarCost * VF.getFixedValue() +
4183 Ctx.getScalarizationOverhead(this->getScalarType(),
4184 to_vector(operands()), VF);
4185 // If the recipe is not predicated (i.e. not in a replicate region), return
4186 // the scalar cost. Otherwise handle predicated cost.
4187 const VPRegionBlock *ParentRegion = getRegion();
4188 if (!ParentRegion || !ParentRegion->isReplicator())
4189 return ScalarCost;
4190
4191 // Account for the phi nodes that we will create.
4192 ScalarCost += VF.getFixedValue() *
4193 Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
4194 // Scale the cost by the probability of executing the predicated blocks.
4195 // This assumes the predicated block for each vector lane is equally
4196 // likely.
4197 ScalarCost /= Ctx.getCostDivisor(
4198 ParentRegion->getEntryBranchOnMask()->getExecutionFrequency());
4199 return ScalarCost;
4200 }
4201 case Instruction::Load:
4202 case Instruction::Store: {
4203 bool IsLoad = UI->getOpcode() == Instruction::Load;
4204 const VPValue *PtrOp = getOperand(!IsLoad);
4205 const SCEV *PtrSCEV = getAddressAccessSCEV(PtrOp, Ctx.PSE, Ctx.L);
4207 break;
4208
4209 Type *ValTy = (IsLoad ? this : getOperand(0))->getScalarType();
4210 Type *ScalarPtrTy = PtrOp->getScalarType();
4211 const Align Alignment = getLoadStoreAlignment(UI);
4212 unsigned AS = cast<PointerType>(ScalarPtrTy)->getAddressSpace();
4214 bool PreferVectorizedAddressing = Ctx.TTI.prefersVectorizedAddressing();
4215 bool UsedByLoadStoreAddress =
4216 !PreferVectorizedAddressing && vputils::isUsedByLoadStoreAddress(this);
4217 InstructionCost ScalarMemOpCost = Ctx.TTI.getMemoryOpCost(
4218 UI->getOpcode(), ValTy, Alignment, AS, Ctx.CostKind, OpInfo,
4219 UsedByLoadStoreAddress ? UI : nullptr);
4220
4221 Type *PtrTy = isSingleScalar() ? ScalarPtrTy : toVectorTy(ScalarPtrTy, VF);
4222 InstructionCost ScalarCost =
4223 ScalarMemOpCost +
4224 Ctx.TTI.getAddressComputationCost(
4225 PtrTy, UsedByLoadStoreAddress ? nullptr : Ctx.PSE.getSE(), PtrSCEV,
4226 Ctx.CostKind);
4227 if (isSingleScalar())
4228 return ScalarCost;
4229
4230 SmallVector<const VPValue *> OpsToScalarize;
4231 Type *ResultTy = Type::getVoidTy(PtrTy->getContext());
4232 // Set ResultTy and OpsToScalarize, if scalarization is needed. Currently we
4233 // don't assign scalarization overhead in general, if the target prefers
4234 // vectorized addressing or the loaded value is used as part of an address
4235 // of another load or store.
4236 if (!UsedByLoadStoreAddress) {
4237 bool EfficientVectorLoadStore =
4238 Ctx.TTI.supportsEfficientVectorElementLoadStore();
4239 if (!(IsLoad && !PreferVectorizedAddressing) &&
4240 !(!IsLoad && EfficientVectorLoadStore))
4241 append_range(OpsToScalarize, operands());
4242
4243 if (!EfficientVectorLoadStore)
4244 ResultTy = this->getScalarType();
4245 }
4246
4248 IsLoad ? TTI::VectorInstrContext::Load : TTI::VectorInstrContext::Store;
4250 (ScalarCost * VF.getFixedValue()) +
4251 Ctx.getScalarizationOverhead(ResultTy, OpsToScalarize, VF, VIC, true);
4252
4253 const VPRegionBlock *ParentRegion = getRegion();
4254 if (ParentRegion && ParentRegion->isReplicator()) {
4255 if (!PtrSCEV)
4256 break;
4257 Cost /= Ctx.getCostDivisor(
4258 ParentRegion->getEntryBranchOnMask()->getExecutionFrequency());
4259 Cost += Ctx.TTI.getCFInstrCost(Instruction::CondBr, Ctx.CostKind);
4260
4261 auto *VecI1Ty = VectorType::get(
4262 IntegerType::getInt1Ty(Ctx.L->getHeader()->getContext()), VF);
4263 Cost += Ctx.TTI.getScalarizationOverhead(
4264 VecI1Ty, APInt::getAllOnes(VF.getFixedValue()),
4265 /*Insert=*/false, /*Extract=*/true, Ctx.CostKind);
4266
4267 if (Ctx.useEmulatedMaskMemRefHack(this, VF)) {
4268 // Artificially setting to a high enough value to practically disable
4269 // vectorization with such operations.
4270 return 3000000;
4271 }
4272 }
4273 return Cost;
4274 }
4275 case Instruction::SExt:
4276 case Instruction::ZExt:
4277 case Instruction::FPToUI:
4278 case Instruction::FPToSI:
4279 case Instruction::FPExt:
4280 case Instruction::PtrToInt:
4281 case Instruction::PtrToAddr:
4282 case Instruction::IntToPtr:
4283 case Instruction::SIToFP:
4284 case Instruction::UIToFP:
4285 case Instruction::Trunc:
4286 case Instruction::FPTrunc:
4287 case Instruction::Select:
4288 case Instruction::AddrSpaceCast: {
4290 Ctx) *
4291 (isSingleScalar() ? 1 : VF.getFixedValue());
4292 }
4293 case Instruction::ExtractValue:
4294 case Instruction::InsertValue:
4295 return Ctx.TTI.getInsertExtractValueCost(getOpcode(), Ctx.CostKind);
4296 }
4297
4298 return Ctx.getLegacyCost(UI, VF);
4299}
4300
4302 Function *CalledFn, Type *ResultTy, ArrayRef<const VPValue *> ArgOps,
4303 bool IsSingleScalar, ElementCount VF, VPCostContext &Ctx) {
4305 ArgOps, [&](const VPValue *Op) { return Op->getScalarType(); });
4306
4307 Intrinsic::ID IntrinID = CalledFn->getIntrinsicID();
4308 auto GetIntrinsicCost = [&] {
4309 if (!IntrinID)
4311 return Ctx.TTI.getIntrinsicInstrCost(
4312 IntrinsicCostAttributes(IntrinID, ResultTy, Tys), Ctx.CostKind);
4313 };
4314
4315 if (IntrinID && VPCostContext::isFreeScalarIntrinsic(IntrinID)) {
4316 assert(GetIntrinsicCost() == 0 && "scalarizing intrinsic should be free");
4317 return 0;
4318 }
4319
4320 InstructionCost ScalarCallCost =
4321 Ctx.TTI.getCallInstrCost(CalledFn, ResultTy, Tys, Ctx.CostKind);
4322 if (IsSingleScalar) {
4323 ScalarCallCost = std::min(ScalarCallCost, GetIntrinsicCost());
4324 return ScalarCallCost;
4325 }
4326
4327 // Scalarization overhead is undefined for scalable VFs.
4328 if (VF.isScalable())
4330
4331 return ScalarCallCost * VF.getFixedValue() +
4332 Ctx.getScalarizationOverhead(ResultTy, ArgOps, VF);
4333}
4334
4335#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4337 VPSlotTracker &SlotTracker) const {
4338 O << Indent << (IsSingleScalar ? "CLONE " : "REPLICATE ");
4339
4340 if (!getScalarType()->isVoidTy()) {
4342 O << " = ";
4343 }
4344 if (auto *CB = dyn_cast<CallBase>(getUnderlyingInstr())) {
4345 O << "call";
4346 printFlags(O);
4347 O << "@" << CB->getCalledFunction()->getName() << "(";
4349 Op->printAsOperand(O, SlotTracker);
4350 });
4351 O << ")";
4352 } else {
4354 printFlags(O);
4356 }
4357
4358 // Find if the recipe is used by a widened recipe via an intervening
4359 // VPPredInstPHIRecipe. In this case, also pack the scalar values in a vector.
4360 if (any_of(users(), [](const VPUser *U) {
4361 if (auto *PredR = dyn_cast<VPPredInstPHIRecipe>(U))
4362 return !vputils::onlyScalarValuesUsed(PredR);
4363 return false;
4364 }))
4365 O << " (S->V)";
4366}
4367#endif
4368
4370 llvm_unreachable("recipe must be removed when dissolving replicate region");
4371}
4372
4374 VPCostContext &Ctx) const {
4375 // The legacy cost model doesn't assign costs to branches for individual
4376 // replicate regions. Match the current behavior in the VPlan cost model for
4377 // now.
4378 return 0;
4379}
4380
4382 llvm_unreachable("recipe must be removed when dissolving replicate region");
4383}
4384
4385#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4387 VPSlotTracker &SlotTracker) const {
4388 O << Indent << "PHI-PREDICATED-INSTRUCTION ";
4390 O << " = ";
4392}
4393#endif
4394
4396const VPRecipeBase *VPWidenLoadRecipe::getAsRecipe() const { return this; }
4397
4400
4402const VPRecipeBase *VPWidenStoreRecipe::getAsRecipe() const { return this; }
4403
4406
4408 VPCostContext &Ctx) const {
4409 const VPRecipeBase *R = getAsRecipe();
4411 Type *ScalarTy = IsLoad ? cast<VPSingleDefRecipe>(R)->getScalarType()
4412 : R->getOperand(1)->getScalarType();
4413 Type *Ty = toVectorTy(ScalarTy, VF);
4414 unsigned AS =
4415 cast<PointerType>(getAddr()->getScalarType())->getAddressSpace();
4416 unsigned Opcode = IsLoad ? Instruction::Load : Instruction::Store;
4417
4418 if (!Consecutive) {
4419 // TODO: Using the original IR may not be accurate.
4420 // Currently, ARM will use the underlying IR to calculate gather/scatter
4421 // instruction cost.
4422 Type *PtrTy = getAddr()->getScalarType();
4423 const Value *Ptr = getAddr()->getUnderlyingValue();
4424
4425 // If the address value is uniform across all lanes, then the address can be
4426 // calculated with scalar type and broadcast.
4428 PtrTy = toVectorTy(PtrTy, VF);
4429
4430 unsigned IID = isa<VPWidenLoadRecipe>(R) ? Intrinsic::masked_gather
4431 : isa<VPWidenStoreRecipe>(R) ? Intrinsic::masked_scatter
4432 : isa<VPWidenLoadEVLRecipe>(R) ? Intrinsic::vp_gather
4433 : Intrinsic::vp_scatter;
4434 return Ctx.TTI.getAddressComputationCost(PtrTy, nullptr, nullptr,
4435 Ctx.CostKind) +
4436 Ctx.TTI.getMemIntrinsicInstrCost(
4438 &Ingredient),
4439 Ctx.CostKind);
4440 }
4441
4443 if (IsMasked) {
4444 unsigned IID = isa<VPWidenLoadRecipe>(R) ? Intrinsic::masked_load
4445 : Intrinsic::masked_store;
4446 Cost += Ctx.TTI.getMemIntrinsicInstrCost(
4447 MemIntrinsicCostAttributes(IID, Ty, Alignment, AS), Ctx.CostKind);
4448 } else {
4449 TTI::OperandValueInfo OpInfo = Ctx.getOperandInfo(
4451 : R->getOperand(1));
4452 Cost += Ctx.TTI.getMemoryOpCost(Opcode, Ty, Alignment, AS, Ctx.CostKind,
4453 OpInfo, &Ingredient);
4454 }
4455 return Cost;
4456}
4457
4459 Type *ScalarDataTy = getScalarType();
4460 auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
4461 bool CreateGather = !isConsecutive();
4462
4463 auto &Builder = State.Builder;
4464 Value *Mask = nullptr;
4465 if (auto *VPMask = getMask())
4466 Mask = State.get(VPMask);
4467
4468 Value *Addr = State.get(getAddr(), /*NeedsSingleScalar=*/!CreateGather);
4469 Value *NewLI;
4470 if (CreateGather) {
4471 NewLI = Builder.CreateMaskedGather(DataTy, Addr, Alignment, Mask, nullptr,
4472 "wide.masked.gather");
4473 } else if (Mask) {
4474 NewLI =
4475 Builder.CreateMaskedLoad(DataTy, Addr, Alignment, Mask,
4476 PoisonValue::get(DataTy), "wide.masked.load");
4477 } else {
4478 NewLI = Builder.CreateAlignedLoad(DataTy, Addr, Alignment, "wide.load");
4479 }
4481 State.set(this, NewLI);
4482}
4483
4484#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4486 VPSlotTracker &SlotTracker) const {
4487 O << Indent << "WIDEN ";
4489 O << " = load ";
4491}
4492#endif
4493
4495 Type *ScalarDataTy = getScalarType();
4496 auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
4497 bool CreateGather = !isConsecutive();
4498
4499 auto &Builder = State.Builder;
4500 CallInst *NewLI;
4501 Value *EVL = State.get(getEVL(), VPLane(0));
4502 Value *Addr = State.get(getAddr(), !CreateGather);
4503 Value *Mask = nullptr;
4504 if (VPValue *VPMask = getMask())
4505 Mask = State.get(VPMask);
4506 else
4507 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
4508
4509 if (CreateGather) {
4510 NewLI = Builder.CreateIntrinsicWithoutFolding(DataTy, Intrinsic::vp_gather,
4511 {Addr, Mask, EVL}, nullptr,
4512 "wide.masked.gather");
4513 } else {
4514 NewLI = Builder.CreateIntrinsicWithoutFolding(
4515 DataTy, Intrinsic::vp_load, {Addr, Mask, EVL}, nullptr, "vp.op.load");
4516 }
4517 NewLI->addParamAttr(
4519 applyMetadata(*NewLI);
4520 State.set(this, NewLI);
4521}
4522
4524 VPCostContext &Ctx) const {
4525 if (!Consecutive || IsMasked)
4526 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
4527
4528 // We need to use the getMemIntrinsicInstrCost() instead of getMemoryOpCost()
4529 // here because the EVL recipes using EVL to replace the tail mask. But in the
4530 // legacy model, it will always calculate the cost of mask.
4531 // TODO: Using getMemoryOpCost() instead of getMemIntrinsicInstrCost when we
4532 // don't need to compare to the legacy cost model.
4533 Type *Ty = toVectorTy(getScalarType(), VF);
4534 unsigned AS =
4535 cast<PointerType>(getAddr()->getScalarType())->getAddressSpace();
4536 return Ctx.TTI.getMemIntrinsicInstrCost(
4537 MemIntrinsicCostAttributes(Intrinsic::vp_load, Ty, Alignment, AS),
4538 Ctx.CostKind);
4539}
4540
4541#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4543 VPSlotTracker &SlotTracker) const {
4544 O << Indent << "WIDEN ";
4546 O << " = vp.load ";
4548}
4549#endif
4550
4552 VPValue *StoredVPValue = getStoredValue();
4553 bool CreateScatter = !isConsecutive();
4554
4555 auto &Builder = State.Builder;
4556
4557 Value *Mask = nullptr;
4558 if (auto *VPMask = getMask())
4559 Mask = State.get(VPMask);
4560
4561 Value *StoredVal = State.get(StoredVPValue);
4562 Value *Addr = State.get(getAddr(), /*NeedsSingleScalar=*/!CreateScatter);
4563 Instruction *NewSI = nullptr;
4564 if (CreateScatter)
4565 NewSI = Builder.CreateMaskedScatter(StoredVal, Addr, Alignment, Mask);
4566 else if (Mask)
4567 NewSI = Builder.CreateMaskedStore(StoredVal, Addr, Alignment, Mask);
4568 else
4569 NewSI = Builder.CreateAlignedStore(StoredVal, Addr, Alignment);
4570 applyMetadata(*NewSI);
4571}
4572
4573#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4575 VPSlotTracker &SlotTracker) const {
4576 O << Indent << "WIDEN store ";
4578}
4579#endif
4580
4582 VPValue *StoredValue = getStoredValue();
4583 bool CreateScatter = !isConsecutive();
4584
4585 auto &Builder = State.Builder;
4586
4587 CallInst *NewSI = nullptr;
4588 Value *StoredVal = State.get(StoredValue);
4589 Value *EVL = State.get(getEVL(), VPLane(0));
4590 Value *Mask = nullptr;
4591 if (VPValue *VPMask = getMask())
4592 Mask = State.get(VPMask);
4593 else
4594 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
4595
4596 Value *Addr = State.get(getAddr(), !CreateScatter);
4597 if (CreateScatter) {
4598 NewSI = Builder.CreateIntrinsicWithoutFolding(
4599 Type::getVoidTy(EVL->getContext()), Intrinsic::vp_scatter,
4600 {StoredVal, Addr, Mask, EVL});
4601 } else {
4602 NewSI = Builder.CreateIntrinsicWithoutFolding(
4603 Type::getVoidTy(EVL->getContext()), Intrinsic::vp_store,
4604 {StoredVal, Addr, Mask, EVL});
4605 }
4606 NewSI->addParamAttr(
4608 applyMetadata(*NewSI);
4609}
4610
4612 VPCostContext &Ctx) const {
4613 if (!Consecutive || IsMasked)
4614 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
4615
4616 // We need to use the getMemIntrinsicInstrCost() instead of getMemoryOpCost()
4617 // here because the EVL recipes using EVL to replace the tail mask. But in the
4618 // legacy model, it will always calculate the cost of mask.
4619 // TODO: Using getMemoryOpCost() instead of getMemIntrinsicInstrCost when we
4620 // don't need to compare to the legacy cost model.
4621 Type *Ty = toVectorTy(getStoredValue()->getScalarType(), VF);
4622 unsigned AS =
4623 cast<PointerType>(getAddr()->getScalarType())->getAddressSpace();
4624 return Ctx.TTI.getMemIntrinsicInstrCost(
4625 MemIntrinsicCostAttributes(Intrinsic::vp_store, Ty, Alignment, AS),
4626 Ctx.CostKind);
4627}
4628
4629#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4631 VPSlotTracker &SlotTracker) const {
4632 O << Indent << "WIDEN vp.store ";
4634}
4635#endif
4636
4638 VectorType *DstVTy, const DataLayout &DL) {
4639 // Verify that V is a vector type with same number of elements as DstVTy.
4640 auto VF = DstVTy->getElementCount();
4641 auto *SrcVecTy = cast<VectorType>(V->getType());
4642 assert(VF == SrcVecTy->getElementCount() && "Vector dimensions do not match");
4643 Type *SrcElemTy = SrcVecTy->getElementType();
4644 Type *DstElemTy = DstVTy->getElementType();
4645 assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&
4646 "Vector elements must have same size");
4647
4648 // Do a direct cast if element types are castable.
4649 if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
4650 return Builder.CreateBitOrPointerCast(V, DstVTy);
4651 }
4652 // V cannot be directly casted to desired vector type.
4653 // May happen when V is a floating point vector but DstVTy is a vector of
4654 // pointers or vice-versa. Handle this using a two-step bitcast using an
4655 // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
4656 assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&
4657 "Only one type should be a pointer type");
4658 assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&
4659 "Only one type should be a floating point type");
4660 Type *IntTy =
4661 IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy));
4662 auto *VecIntTy = VectorType::get(IntTy, VF);
4663 Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
4664 return Builder.CreateBitOrPointerCast(CastVal, DstVTy);
4665}
4666
4667/// Return a vector containing interleaved elements from multiple
4668/// smaller input vectors.
4670 const Twine &Name) {
4671 unsigned Factor = Vals.size();
4672 assert(Factor > 1 && "Tried to interleave invalid number of vectors");
4673
4674 VectorType *VecTy = cast<VectorType>(Vals[0]->getType());
4675#ifndef NDEBUG
4676 for (Value *Val : Vals)
4677 assert(Val->getType() == VecTy && "Tried to interleave mismatched types");
4678#endif
4679
4680 // Scalable vectors cannot use arbitrary shufflevectors (only splats), so
4681 // must use intrinsics to interleave.
4682 if (VecTy->isScalableTy()) {
4683 assert(Factor <= 8 && "Unsupported interleave factor for scalable vectors");
4684 return Builder.CreateVectorInterleave(Vals, Name);
4685 }
4686
4687 // Fixed length. Start by concatenating all vectors into a wide vector.
4688 Value *WideVec = concatenateVectors(Builder, Vals);
4689
4690 // Interleave the elements into the wide vector.
4691 const unsigned NumElts = VecTy->getElementCount().getFixedValue();
4692 return Builder.CreateShuffleVector(
4693 WideVec, createInterleaveMask(NumElts, Factor), Name);
4694}
4695
4696// Try to vectorize the interleave group that \p Instr belongs to.
4697//
4698// E.g. Translate following interleaved load group (factor = 3):
4699// for (i = 0; i < N; i+=3) {
4700// R = Pic[i]; // Member of index 0
4701// G = Pic[i+1]; // Member of index 1
4702// B = Pic[i+2]; // Member of index 2
4703// ... // do something to R, G, B
4704// }
4705// To:
4706// %wide.vec = load <12 x i32> ; Read 4 tuples of R,G,B
4707// %R.vec = shuffle %wide.vec, poison, <0, 3, 6, 9> ; R elements
4708// %G.vec = shuffle %wide.vec, poison, <1, 4, 7, 10> ; G elements
4709// %B.vec = shuffle %wide.vec, poison, <2, 5, 8, 11> ; B elements
4710//
4711// Or translate following interleaved store group (factor = 3):
4712// for (i = 0; i < N; i+=3) {
4713// ... do something to R, G, B
4714// Pic[i] = R; // Member of index 0
4715// Pic[i+1] = G; // Member of index 1
4716// Pic[i+2] = B; // Member of index 2
4717// }
4718// To:
4719// %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
4720// %B_U.vec = shuffle %B.vec, poison, <0, 1, 2, 3, u, u, u, u>
4721// %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
4722// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> ; Interleave R,G,B elements
4723// store <12 x i32> %interleaved.vec ; Write 4 tuples of R,G,B
4725 assert((!needsMaskForGaps() || !State.VF.isScalable()) &&
4726 "Masking gaps for scalable vectors is not yet supported.");
4728 Instruction *Instr = Group->getInsertPos();
4729
4730 // Prepare for the vector type of the interleaved load/store.
4731 Type *ScalarTy = getLoadStoreType(Instr);
4732 unsigned InterleaveFactor = Group->getFactor();
4733 auto *VecTy = VectorType::get(ScalarTy, State.VF * InterleaveFactor);
4734
4735 VPValue *BlockInMask = getMask();
4736 VPValue *Addr = getAddr();
4737 Value *ResAddr = State.get(Addr, VPLane(0));
4738
4739 auto CreateGroupMask = [&BlockInMask, &State,
4740 &InterleaveFactor](Value *MaskForGaps) -> Value * {
4741 if (State.VF.isScalable()) {
4742 assert(!MaskForGaps && "Interleaved groups with gaps are not supported.");
4743 assert(InterleaveFactor <= 8 &&
4744 "Unsupported deinterleave factor for scalable vectors");
4745 auto *ResBlockInMask = State.get(BlockInMask);
4746 SmallVector<Value *> Ops(InterleaveFactor, ResBlockInMask);
4747 return interleaveVectors(State.Builder, Ops, "interleaved.mask");
4748 }
4749
4750 if (!BlockInMask)
4751 return MaskForGaps;
4752
4753 Value *ResBlockInMask = State.get(BlockInMask);
4754 Value *ShuffledMask = State.Builder.CreateShuffleVector(
4755 ResBlockInMask,
4756 createReplicatedMask(InterleaveFactor, State.VF.getFixedValue()),
4757 "interleaved.mask");
4758 return MaskForGaps ? State.Builder.CreateBinOp(Instruction::And,
4759 ShuffledMask, MaskForGaps)
4760 : ShuffledMask;
4761 };
4762
4763 const DataLayout &DL = Instr->getDataLayout();
4764 // Vectorize the interleaved load group.
4765 if (isa<LoadInst>(Instr)) {
4766 Value *MaskForGaps = nullptr;
4767 if (needsMaskForGaps()) {
4768 MaskForGaps =
4769 createBitMaskForGaps(State.Builder, State.VF.getFixedValue(), *Group);
4770 assert(MaskForGaps && "Mask for Gaps is required but it is null");
4771 }
4772
4773 Instruction *NewLoad;
4774 if (BlockInMask || MaskForGaps) {
4775 Value *GroupMask = CreateGroupMask(MaskForGaps);
4776 Value *PoisonVec = PoisonValue::get(VecTy);
4777 NewLoad = State.Builder.CreateMaskedLoad(VecTy, ResAddr,
4778 Group->getAlign(), GroupMask,
4779 PoisonVec, "wide.masked.vec");
4780 } else
4781 NewLoad = State.Builder.CreateAlignedLoad(VecTy, ResAddr,
4782 Group->getAlign(), "wide.vec");
4783 applyMetadata(*NewLoad);
4784 // TODO: Also manage existing metadata using VPIRMetadata.
4785 Group->addMetadata(NewLoad);
4786
4788 if (VecTy->isScalableTy()) {
4789 // Scalable vectors cannot use arbitrary shufflevectors (only splats),
4790 // so must use intrinsics to deinterleave.
4791 assert(InterleaveFactor <= 8 &&
4792 "Unsupported deinterleave factor for scalable vectors");
4793 NewLoad = State.Builder.CreateIntrinsicWithoutFolding(
4794 Intrinsic::getDeinterleaveIntrinsicID(InterleaveFactor),
4795 NewLoad->getType(), NewLoad,
4796 /*FMFSource=*/nullptr, "strided.vec");
4797 }
4798
4799 auto CreateStridedVector = [&InterleaveFactor, &State,
4800 &NewLoad](unsigned Index) -> Value * {
4801 assert(Index < InterleaveFactor && "Illegal group index");
4802 if (State.VF.isScalable())
4803 return State.Builder.CreateExtractValue(NewLoad, Index);
4804
4805 // For fixed length VF, use shuffle to extract the sub-vectors from the
4806 // wide load.
4807 auto StrideMask =
4808 createStrideMask(Index, InterleaveFactor, State.VF.getFixedValue());
4809 return State.Builder.CreateShuffleVector(NewLoad, StrideMask,
4810 "strided.vec");
4811 };
4812
4813 for (unsigned I = 0, J = 0; I < InterleaveFactor; ++I) {
4814 Instruction *Member = Group->getMember(I);
4815
4816 // Skip the gaps in the group.
4817 if (!Member)
4818 continue;
4819
4820 Value *StridedVec = CreateStridedVector(I);
4821
4822 // If this member has different type, cast the result type.
4823 if (Member->getType() != ScalarTy) {
4824 VectorType *OtherVTy = VectorType::get(Member->getType(), State.VF);
4825 StridedVec =
4826 createBitOrPointerCast(State.Builder, StridedVec, OtherVTy, DL);
4827 }
4828
4829 if (Group->isReverse())
4830 StridedVec = State.Builder.CreateVectorReverse(StridedVec, "reverse");
4831
4832 State.set(VPDefs[J], StridedVec);
4833 ++J;
4834 }
4835 return;
4836 }
4837
4838 // The sub vector type for current instruction.
4839 auto *SubVT = VectorType::get(ScalarTy, State.VF);
4840
4841 // Vectorize the interleaved store group.
4842 Value *MaskForGaps =
4843 createBitMaskForGaps(State.Builder, State.VF.getKnownMinValue(), *Group);
4844 assert(((MaskForGaps != nullptr) == needsMaskForGaps()) &&
4845 "Mismatch between NeedsMaskForGaps and MaskForGaps");
4846 ArrayRef<VPValue *> StoredValues = getStoredValues();
4847 // Collect the stored vector from each member.
4848 SmallVector<Value *, 4> StoredVecs;
4849 unsigned StoredIdx = 0;
4850 for (unsigned i = 0; i < InterleaveFactor; i++) {
4851 assert((Group->getMember(i) || MaskForGaps) &&
4852 "Fail to get a member from an interleaved store group");
4853 Instruction *Member = Group->getMember(i);
4854
4855 // Skip the gaps in the group.
4856 if (!Member) {
4857 Value *Undef = PoisonValue::get(SubVT);
4858 StoredVecs.push_back(Undef);
4859 continue;
4860 }
4861
4862 Value *StoredVec = State.get(StoredValues[StoredIdx]);
4863 ++StoredIdx;
4864
4865 if (Group->isReverse())
4866 StoredVec = State.Builder.CreateVectorReverse(StoredVec, "reverse");
4867
4868 // If this member has different type, cast it to a unified type.
4869
4870 if (StoredVec->getType() != SubVT)
4871 StoredVec = createBitOrPointerCast(State.Builder, StoredVec, SubVT, DL);
4872
4873 StoredVecs.push_back(StoredVec);
4874 }
4875
4876 // Interleave all the smaller vectors into one wider vector.
4877 Value *IVec = interleaveVectors(State.Builder, StoredVecs, "interleaved.vec");
4878 Instruction *NewStoreInstr;
4879 if (BlockInMask || MaskForGaps) {
4880 Value *GroupMask = CreateGroupMask(MaskForGaps);
4881 NewStoreInstr = State.Builder.CreateMaskedStore(
4882 IVec, ResAddr, Group->getAlign(), GroupMask);
4883 } else
4884 NewStoreInstr =
4885 State.Builder.CreateAlignedStore(IVec, ResAddr, Group->getAlign());
4886
4887 applyMetadata(*NewStoreInstr);
4888 // TODO: Also manage existing metadata using VPIRMetadata.
4889 Group->addMetadata(NewStoreInstr);
4890}
4891
4892#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4894 VPSlotTracker &SlotTracker) const {
4896 O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << ", ";
4898 VPValue *Mask = getMask();
4899 if (Mask) {
4900 O << ", ";
4901 Mask->printAsOperand(O, SlotTracker);
4902 }
4903
4904 unsigned OpIdx = 0;
4905 for (unsigned i = 0; i < IG->getFactor(); ++i) {
4906 if (!IG->getMember(i))
4907 continue;
4908 if (getNumStoreOperands() > 0) {
4909 O << "\n" << Indent << " store ";
4910 getOperand(1 + OpIdx)->printAsOperand(O, SlotTracker);
4911 O << " to index " << i;
4912 } else {
4913 O << "\n" << Indent << " ";
4915 O << " = load from index " << i;
4916 }
4917 ++OpIdx;
4918 }
4919}
4920#endif
4921
4923 assert(State.VF.isScalable() &&
4924 "Only support scalable VF for EVL tail-folding.");
4926 "Masking gaps for scalable vectors is not yet supported.");
4928 Instruction *Instr = Group->getInsertPos();
4929
4930 // Prepare for the vector type of the interleaved load/store.
4931 Type *ScalarTy = getLoadStoreType(Instr);
4932 unsigned InterleaveFactor = Group->getFactor();
4933 assert(InterleaveFactor <= 8 &&
4934 "Unsupported deinterleave/interleave factor for scalable vectors");
4935 ElementCount WideVF = State.VF * InterleaveFactor;
4936 auto *VecTy = VectorType::get(ScalarTy, WideVF);
4937
4938 VPValue *Addr = getAddr();
4939 Value *ResAddr = State.get(Addr, VPLane(0));
4940 Value *EVL = State.get(getEVL(), VPLane(0));
4941 Value *InterleaveEVL = State.Builder.CreateMul(
4942 EVL, ConstantInt::get(EVL->getType(), InterleaveFactor), "interleave.evl",
4943 /* NUW= */ true, /* NSW= */ true);
4944 LLVMContext &Ctx = State.Builder.getContext();
4945
4946 Value *GroupMask = nullptr;
4947 if (VPValue *BlockInMask = getMask()) {
4948 SmallVector<Value *> Ops(InterleaveFactor, State.get(BlockInMask));
4949 GroupMask = interleaveVectors(State.Builder, Ops, "interleaved.mask");
4950 } else {
4951 GroupMask =
4952 State.Builder.CreateVectorSplat(WideVF, State.Builder.getTrue());
4953 }
4954
4955 // Vectorize the interleaved load group.
4956 if (isa<LoadInst>(Instr)) {
4957 CallInst *NewLoad = State.Builder.CreateIntrinsicWithoutFolding(
4958 VecTy, Intrinsic::vp_load, {ResAddr, GroupMask, InterleaveEVL}, nullptr,
4959 "wide.vp.load");
4960 NewLoad->addParamAttr(0,
4961 Attribute::getWithAlignment(Ctx, Group->getAlign()));
4962
4963 applyMetadata(*NewLoad);
4964 // TODO: Also manage existing metadata using VPIRMetadata.
4965 Group->addMetadata(NewLoad);
4966
4967 // Scalable vectors cannot use arbitrary shufflevectors (only splats),
4968 // so must use intrinsics to deinterleave.
4969 NewLoad = State.Builder.CreateIntrinsicWithoutFolding(
4970 Intrinsic::getDeinterleaveIntrinsicID(InterleaveFactor),
4971 NewLoad->getType(), NewLoad,
4972 /*FMFSource=*/nullptr, "strided.vec");
4973
4974 const DataLayout &DL = Instr->getDataLayout();
4975 for (unsigned I = 0, J = 0; I < InterleaveFactor; ++I) {
4976 Instruction *Member = Group->getMember(I);
4977 // Skip the gaps in the group.
4978 if (!Member)
4979 continue;
4980
4981 Value *StridedVec = State.Builder.CreateExtractValue(NewLoad, I);
4982 // If this member has different type, cast the result type.
4983 if (Member->getType() != ScalarTy) {
4984 VectorType *OtherVTy = VectorType::get(Member->getType(), State.VF);
4985 StridedVec =
4986 createBitOrPointerCast(State.Builder, StridedVec, OtherVTy, DL);
4987 }
4988
4989 State.set(getVPValue(J), StridedVec);
4990 ++J;
4991 }
4992 return;
4993 } // End for interleaved load.
4994
4995 // The sub vector type for current instruction.
4996 auto *SubVT = VectorType::get(ScalarTy, State.VF);
4997 // Vectorize the interleaved store group.
4998 ArrayRef<VPValue *> StoredValues = getStoredValues();
4999 // Collect the stored vector from each member.
5000 SmallVector<Value *, 4> StoredVecs;
5001 const DataLayout &DL = Instr->getDataLayout();
5002 for (unsigned I = 0, StoredIdx = 0; I < InterleaveFactor; I++) {
5003 Instruction *Member = Group->getMember(I);
5004 // Skip the gaps in the group.
5005 if (!Member) {
5006 StoredVecs.push_back(PoisonValue::get(SubVT));
5007 continue;
5008 }
5009
5010 Value *StoredVec = State.get(StoredValues[StoredIdx]);
5011 // If this member has different type, cast it to a unified type.
5012 if (StoredVec->getType() != SubVT)
5013 StoredVec = createBitOrPointerCast(State.Builder, StoredVec, SubVT, DL);
5014
5015 StoredVecs.push_back(StoredVec);
5016 ++StoredIdx;
5017 }
5018
5019 // Interleave all the smaller vectors into one wider vector.
5020 Value *IVec = interleaveVectors(State.Builder, StoredVecs, "interleaved.vec");
5021 CallInst *NewStore = State.Builder.CreateIntrinsicWithoutFolding(
5022 Type::getVoidTy(Ctx), Intrinsic::vp_store,
5023 {IVec, ResAddr, GroupMask, InterleaveEVL});
5024
5025 NewStore->addParamAttr(1,
5026 Attribute::getWithAlignment(Ctx, Group->getAlign()));
5027
5028 applyMetadata(*NewStore);
5029 // TODO: Also manage existing metadata using VPIRMetadata.
5030 Group->addMetadata(NewStore);
5031}
5032
5033#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5035 VPSlotTracker &SlotTracker) const {
5037 O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << ", ";
5039 O << ", ";
5041 if (VPValue *Mask = getMask()) {
5042 O << ", ";
5043 Mask->printAsOperand(O, SlotTracker);
5044 }
5045
5046 unsigned OpIdx = 0;
5047 for (unsigned i = 0; i < IG->getFactor(); ++i) {
5048 if (!IG->getMember(i))
5049 continue;
5050 if (getNumStoreOperands() > 0) {
5051 O << "\n" << Indent << " vp.store ";
5052 getOperand(2 + OpIdx)->printAsOperand(O, SlotTracker);
5053 O << " to index " << i;
5054 } else {
5055 O << "\n" << Indent << " ";
5057 O << " = vp.load from index " << i;
5058 }
5059 ++OpIdx;
5060 }
5061}
5062#endif
5063
5065 VPCostContext &Ctx) const {
5066 Instruction *InsertPos = getInsertPos();
5067 // Find the VPValue index of the interleave group. We need to skip gaps.
5068 unsigned InsertPosIdx = 0;
5069 for (unsigned Idx = 0; IG->getFactor(); ++Idx)
5070 if (auto *Member = IG->getMember(Idx)) {
5071 if (Member == InsertPos)
5072 break;
5073 InsertPosIdx++;
5074 }
5075 const VPValue *ValV = getNumDefinedValues() > 0
5076 ? getVPValue(InsertPosIdx)
5077 : getStoredValues()[InsertPosIdx];
5078 Type *ValTy = ValV->getScalarType();
5079 auto *VectorTy = cast<VectorType>(toVectorTy(ValTy, VF));
5080 unsigned AS =
5081 cast<PointerType>(getAddr()->getScalarType())->getAddressSpace();
5082
5083 unsigned InterleaveFactor = IG->getFactor();
5084 auto *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
5085
5086 // Holds the indices of existing members in the interleaved group.
5088 for (unsigned IF = 0; IF < InterleaveFactor; IF++)
5089 if (IG->getMember(IF))
5090 Indices.push_back(IF);
5091
5092 // Calculate the cost of the whole interleaved group.
5093 InstructionCost Cost = Ctx.TTI.getInterleavedMemoryOpCost(
5094 InsertPos->getOpcode(), WideVecTy, IG->getFactor(), Indices,
5095 IG->getAlign(), AS, Ctx.CostKind, getMask(), NeedsMaskForGaps);
5096
5097 if (!IG->isReverse())
5098 return Cost;
5099
5100 return Cost + IG->getNumMembers() *
5101 Ctx.TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
5102 VectorTy, VectorTy, Ctx.CostKind, {},
5103 0);
5104}
5105
5108 VPCostContext &Ctx) const {
5109 // The recipe creates a scalar phi, a GEP to increment the induction and
5110 // vector add to compute the vector of pointers.
5111 // TODO: Charge costs for induction increment and vector add as well.
5112 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
5113}
5114
5116 return vputils::onlyScalarValuesUsed(this) &&
5117 (!IsScalable || vputils::onlyFirstLaneUsed(this));
5118}
5119
5120#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5122 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
5123 assert((getNumOperands() == 3 || getNumOperands() == 5) &&
5124 "unexpected number of operands");
5125 O << Indent << "EMIT ";
5127 O << " = WIDEN-POINTER-INDUCTION ";
5129 O << ", ";
5131 O << ", ";
5133 if (getNumOperands() == 5) {
5134 O << ", ";
5136 O << ", ";
5138 }
5139}
5140
5142 VPSlotTracker &SlotTracker) const {
5143 O << Indent << "EMIT ";
5145 O << " = EXPAND SCEV " << *Expr;
5146}
5147#endif
5148
5149#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5151 VPSlotTracker &SlotTracker) const {
5152 O << Indent << "EMIT ";
5154 O << " = WIDEN-CANONICAL-INDUCTION";
5155 printFlags(O);
5157}
5158#endif
5159
5161 auto &Builder = State.Builder;
5162 // Create a vector from the initial value.
5163 auto *VectorInit = getStartValue()->getLiveInIRValue();
5164
5165 Type *VecTy = State.VF.isScalar()
5166 ? VectorInit->getType()
5167 : VectorType::get(VectorInit->getType(), State.VF);
5168
5169 BasicBlock *VectorPH =
5170 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
5171 if (State.VF.isVector()) {
5172 auto *IdxTy = Builder.getInt32Ty();
5173 auto *One = ConstantInt::get(IdxTy, 1);
5174 IRBuilder<>::InsertPointGuard Guard(Builder);
5175 Builder.SetInsertPoint(VectorPH->getTerminator());
5176 auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, State.VF);
5177 auto *LastIdx = Builder.CreateSub(RuntimeVF, One);
5178 VectorInit = Builder.CreateInsertElement(
5179 PoisonValue::get(VecTy), VectorInit, LastIdx, "vector.recur.init");
5180 }
5181
5182 // Create a phi node for the new recurrence.
5183 PHINode *Phi = PHINode::Create(VecTy, 2, "vector.recur");
5184 Phi->insertBefore(State.CFG.PrevBB->getFirstInsertionPt());
5185 Phi->addIncoming(VectorInit, VectorPH);
5186 State.set(this, Phi);
5187}
5188
5191 VPCostContext &Ctx) const {
5192 if (VF.isScalar())
5193 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
5194
5195 return 0;
5196}
5197
5198#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5200 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
5201 O << Indent << "FIRST-ORDER-RECURRENCE-PHI ";
5203 O << " = phi ";
5205}
5206#endif
5207
5209 // Reductions do not have to start at zero. They can start with
5210 // any loop invariant values.
5211 VPValue *StartVPV = getStartValue();
5212
5213 // In order to support recurrences we need to be able to vectorize Phi nodes.
5214 // Phi nodes have cycles, so we need to vectorize them in two stages. This is
5215 // stage #1: We create a new vector PHI node with no incoming edges. We'll use
5216 // this value when we vectorize all of the instructions that use the PHI.
5217 BasicBlock *VectorPH =
5218 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
5219 bool ScalarPHI = State.VF.isScalar() || isInLoop();
5220 Value *StartV = State.get(StartVPV, ScalarPHI);
5221 Type *VecTy = StartV->getType();
5222
5223 BasicBlock *HeaderBB = State.CFG.PrevBB;
5224 assert(State.CurrentParentLoop->getHeader() == HeaderBB &&
5225 "recipe must be in the vector loop header");
5226 auto *Phi = PHINode::Create(VecTy, 2, "vec.phi");
5227 Phi->insertBefore(HeaderBB->getFirstInsertionPt());
5228 State.set(this, Phi, isInLoop());
5229
5230 Phi->addIncoming(StartV, VectorPH);
5231}
5232
5233#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5235 VPSlotTracker &SlotTracker) const {
5236 O << Indent << "WIDEN-REDUCTION-PHI ";
5237
5239 O << " = phi (";
5240 printRecurrenceKind(O, Kind);
5241 O << ")";
5242 printFlags(O);
5244 if (getVFScaleFactor() > 1)
5245 O << " (VF scaled by 1/" << getVFScaleFactor() << ")";
5246}
5247#endif
5248
5250 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
5251 return vputils::onlyFirstLaneUsed(this);
5252}
5253
5255 executePhiRecipe(this, *this, State, /*IsScalar=*/false, Name);
5256}
5257
5259 VPCostContext &Ctx) const {
5260 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
5261}
5262
5263#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5265 VPSlotTracker &SlotTracker) const {
5266 O << Indent << "WIDEN-PHI ";
5267
5269 O << " = phi ";
5271}
5272#endif
5273
5275 BasicBlock *VectorPH =
5276 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
5277 Value *StartMask = State.get(getOperand(0));
5278 PHINode *Phi =
5279 State.Builder.CreatePHI(StartMask->getType(), 2, "active.lane.mask");
5280 Phi->addIncoming(StartMask, VectorPH);
5281 State.set(this, Phi);
5282}
5283
5284#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5286 VPSlotTracker &SlotTracker) const {
5287 O << Indent << "ACTIVE-LANE-MASK-PHI ";
5288
5290 O << " = phi ";
5292}
5293#endif
5294
5295#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5297 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
5298 O << Indent << "CURRENT-ITERATION-PHI ";
5299
5301 O << " = phi ";
5303}
5304#endif
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
static MCDisassembler::DecodeStatus addOperand(MCInst &Inst, const MCOperand &Opnd)
AMDGPU Lower Kernel Arguments
AMDGPU Register Bank Select
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 holds the attributes for a particular argument, parameter, function, or return value.
Definition Attributes.h:410
static LLVM_ABI Attribute getWithAlignment(LLVMContext &Context, Align Alignment)
Return a uniquified Attribute object that has the specific alignment set.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
Adds the attribute to the indicated argument.
This class represents a function call, abstracting a target machine's calling convention.
static LLVM_ABI bool isBitOrNoopPointerCastable(Type *SrcTy, Type *DestTy, const DataLayout &DL)
Check whether a bitcast, inttoptr, or ptrtoint cast between these types is valid and a no-op.
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
static LLVM_ABI StringRef getPredicateName(Predicate P)
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:548
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
bool isNegZero() const
Return true if the value is negative zero.
Definition Constants.h:473
bool isOne() const
Returns true if this value is exactly +1.0.
Definition Constants.h:485
bool isZero() const
Return true if the value is positive or negative zero.
Definition Constants.h:467
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
A debug info location.
Definition DebugLoc.h:126
static DebugLoc getUnknown()
Definition DebugLoc.h:153
constexpr bool isVector() const
One or more elements.
Definition TypeSize.h:320
static constexpr ElementCount getScalable(ScalarTy MinVal)
Definition TypeSize.h:308
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:305
constexpr bool isScalar() const
Exactly one element.
Definition TypeSize.h:316
static 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
Class to represent function types.
Type * getParamType(unsigned i) const
Parameter type accessors.
bool willReturn() const
Determine if the function will return.
Definition Function.h:647
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
Definition Function.h:247
bool doesNotThrow() const
Determine if the function cannot unwind.
Definition Function.h:577
bool doesNotAccessMemory() const
Determine if the function does not access memory.
Definition Function.cpp:873
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:2678
IntegerType * getInt1Ty()
Fetch the type representing a single bit.
Definition IRBuilder.h:516
Value * CreateInsertValue(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &Name="")
Definition IRBuilder.h:2732
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2666
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:1943
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:1221
LLVM_ABI Value * CreateSelectFMF(Value *C, Value *True, Value *False, FMFSource FMFSource, const Twine &Name="", Instruction *MDFrom=nullptr)
LLVM_ABI Value * CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name="")
Return a vector value that contains.
Value * CreateExtractValue(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &Name="")
Definition IRBuilder.h:2725
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:2744
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
Definition IRBuilder.h:531
Value * CreateExtractVector(Type *DstType, Value *SrcVec, Value *Idx, const Twine &Name="")
Create a call to the vector.extract intrinsic.
Definition IRBuilder.h:1117
Value * CreatePtrAdd(Value *Ptr, Value *Offset, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Definition IRBuilder.h:2101
Value * CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy, const Twine &Name="", MDNode *FPMathTag=nullptr, FMFSource FMFSource={})
Definition IRBuilder.h:2293
void setFastMathFlags(FastMathFlags NewFMF)
Set the fast-math flags to be used with generated fp-math operators.
Definition IRBuilder.h:298
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:2395
ConstantInt * getInt64(uint64_t C)
Get a constant 64-bit value.
Definition IRBuilder.h:479
Value * CreateLogicalAnd(Value *Cond1, Value *Cond2, const Twine &Name="", Instruction *MDFrom=nullptr)
Definition IRBuilder.h:1775
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:474
Value * CreateCmp(CmpInst::Predicate Pred, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2525
Value * CreateNot(Value *V, const Twine &Name="")
Definition IRBuilder.h:1859
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2391
Value * CreateCountTrailingZeroElems(Type *ResTy, Value *Mask, bool ZeroIsPoison=true, const Twine &Name="")
Create a call to llvm.experimental_cttz_elts.
Definition IRBuilder.h:1159
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1444
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNeg=false)
Definition IRBuilder.h:2130
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:1427
ConstantInt * getFalse()
Get the constant value for i1 false.
Definition IRBuilder.h:459
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:1736
Value * CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2403
Value * CreateLogicalOr(Value *Cond1, Value *Cond2, const Twine &Name="", Instruction *MDFrom=nullptr)
Definition IRBuilder.h:1783
StoreInst * CreateAlignedStore(Value *Val, Value *Ptr, MaybeAlign Align, bool isVolatile=false)
Definition IRBuilder.h:1962
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
Definition IRBuilder.h:1597
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:1131
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1461
LLVM_ABI Value * CreateUnaryIntrinsic(Intrinsic::ID ID, Value *Op, FMFSource FMFSource={}, const Twine &Name="")
Create a call to intrinsic ID with 1 operand which is mangled on its type.
A struct for saving information about induction variables.
@ IK_FpInduction
Floating point induction variable.
@ IK_IntInduction
Integer induction variable. Step = C.
static InstructionCost getInvalid(CostType Val=0)
bool isCast() const
bool isBinaryOp() const
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
const char * getOpcodeName() const
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
bool isUnaryOp() const
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:338
The group of interleaved loads/stores sharing the same stride and close to each other.
uint32_t getFactor() const
InstTy * getMember(uint32_t Index) const
Get the member with the given index Index.
bool isReverse() const
InstTy * getInsertPos() const
void addMetadata(InstTy *NewInst) const
Add metadata (e.g.
Align getAlign() const
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Metadata node.
Definition Metadata.h:1081
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h: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
bool isStructTy() const
True if this is an instance of StructType.
Definition Type.h:271
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:222
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:296
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
Definition Type.h:265
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:303
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
value_op_iterator value_op_end()
Definition User.h:288
void setOperand(unsigned i, Value *Val)
Definition User.h:212
Value * getOperand(unsigned i) const
Definition User.h:207
value_op_iterator value_op_begin()
Definition User.h:285
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:4437
RecipeListTy & getRecipeList()
Returns a reference to the list of recipes.
Definition VPlan.h:4490
iterator end()
Definition VPlan.h:4474
void insert(VPRecipeBase *Recipe, iterator InsertPt)
Definition VPlan.h:4503
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:3023
unsigned getNumIncomingValues() const
Return the number of incoming values, taking into account when normalized the first incoming value wi...
Definition VPlan.h:3018
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:3014
VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
Definition VPlan.h:97
const VPBlocksTy & getPredecessors() const
Definition VPlan.h:230
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.
LLVM_ABI_FOR_TEST void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
unsigned getNumDefinedValues() const
Returns the number of values defined by the VPDef.
Definition VPlanValue.h:578
VPValue * getVPSingleValue()
Returns the only VPValue defined by the VPDef.
Definition VPlanValue.h:551
VPValue * getVPValue(unsigned I)
Returns the VPValue with index I defined by the VPDef.
Definition VPlanValue.h:563
ArrayRef< VPRecipeValue * > definedValues()
Returns an ArrayRef of the values defined by the VPDef.
Definition VPlanValue.h:573
InductionDescriptor::InductionKind getInductionKind() const
Definition VPlan.h:4255
VPValue * getIndex() const
Definition VPlan.h:4252
VPValue * getStepValue() const
Definition VPlan.h:4253
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:4251
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:2495
void execute(VPTransformState &State) override
Produce a vectorized histogram operation.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPHistogramRecipe.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPValue * getMask() const
Return the mask operand if one was provided, or a null pointer if all lanes should be executed uncond...
Definition VPlan.h:2203
Class to record and manage LLVM IR flags.
Definition VPlan.h:688
FastMathFlagsTy FMFs
Definition VPlan.h:780
ReductionFlagsTy ReductionFlags
Definition VPlan.h:782
LLVM_ABI_FOR_TEST bool flagsValidForOpcode(unsigned Opcode) const
Returns true if the set flags are valid for Opcode.
WrapFlagsTy WrapFlags
Definition VPlan.h:774
void printFlags(raw_ostream &O) const
bool hasFastMathFlags() const
Returns true if the recipe has fast-math flags.
Definition VPlan.h:989
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:1044
TruncFlagsTy TruncFlags
Definition VPlan.h:775
CmpInst::Predicate getPredicate() const
Definition VPlan.h:961
LLVM_ABI_FOR_TEST FastMathFlags getFastMathFlagsOrNone() const
ExactFlagsTy ExactFlags
Definition VPlan.h:777
void intersectFlags(const VPIRFlags &Other)
Only keep flags also present in Other.
uint8_t GEPFlagsStorage
Definition VPlan.h:778
GEPNoWrapFlags getGEPNoWrapFlags() const
Definition VPlan.h:979
bool hasPredicate() const
Returns true if the recipe has a comparison predicate.
Definition VPlan.h:984
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:776
FCmpFlagsTy FCmpFlags
Definition VPlan.h:781
NonNegFlagsTy NonNegFlags
Definition VPlan.h:779
bool isReductionInLoop() const
Definition VPlan.h:1050
void applyFlags(Instruction &I) const
Apply the IR flags to I.
Definition VPlan.h:926
uint8_t CmpPredStorage
Definition VPlan.h:773
RecurKind getRecurKind() const
Definition VPlan.h:1038
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:1720
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:1212
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:1282
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:1400
@ Intrinsic
Calls a scalar intrinsic. The intrinsic ID is the last operand.
Definition VPlan.h:1412
@ ExtractLane
Extracts a single lane (first operand) from a set of vector operands.
Definition VPlan.h:1391
@ ExitingIVValue
Compute the exiting value of a wide induction after vectorization, that is the value of the last lane...
Definition VPlan.h:1404
@ WideIVStep
Scale the first operand (vector step) by the second operand (scalar-step).
Definition VPlan.h:1408
@ ResumeForEpilogue
Explicit user for values in the main VPlan, used by the epilogue vector loop.
Definition VPlan.h:1394
@ Unpack
Extracts all lanes from its (non-scalable) vector operand.
Definition VPlan.h:1342
@ ReductionStartVector
Start vector for reductions with 3 operands: the original start value, the identity value for the red...
Definition VPlan.h:1387
@ BuildVector
Creates a fixed-width vector containing all operands.
Definition VPlan.h:1337
@ BuildStructVector
Given operands of (the same) struct type, creates a struct of fixed- width vectors each containing a ...
Definition VPlan.h:1334
@ CanonicalIVIncrementForPart
Definition VPlan.h:1318
@ ComputeReductionResult
Reduce the operands to the final reduction result using the operation specified via the operation's V...
Definition VPlan.h:1345
bool hasResult() const
Definition VPlan.h:1498
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:1584
unsigned getOpcode() const
Definition VPlan.h:1477
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
void addOperand(VPValue *Op)
Add Op as operand of this VPInstruction.
bool isVectorToScalar() const
Returns true if this VPInstruction produces a scalar value from a vector, e.g.
bool isSingleScalar() const
Returns true if the recipe produces a single scalar value.
unsigned getNumOperandsForOpcode() const
Return the number of operands determined by the opcode of the VPInstruction, excluding mask.
bool isMasked() const
Returns true if the VPInstruction has a mask operand.
Definition VPlan.h:1524
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:3127
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this recipe.
Instruction * getInsertPos() const
Definition VPlan.h:3131
const InterleaveGroup< Instruction > * getInterleaveGroup() const
Definition VPlan.h:3129
VPValue * getMask() const
Return the mask used by this recipe.
Definition VPlan.h:3121
ArrayRef< VPValue * > getStoredValues() const
Return the VPValues stored by this interleave group.
Definition VPlan.h:3150
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition VPlan.h:3115
VPValue * getEVL() const
The VPValue of the explicit vector length.
Definition VPlan.h:3224
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:3237
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:3187
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:1599
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:1649
VPValue * getIncomingValue(unsigned Idx) const
Returns the incoming VPValue with index Idx.
Definition VPlan.h:1608
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:403
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:4836
void dump() const
Dump the recipe to stderr (for debugging).
Definition VPlan.cpp:115
bool isPhi() const
Returns true for PHI-like recipes.
bool mayWriteToMemory() const
Returns true if the recipe may write to memory.
VPRecipeTy getVPRecipeID() const
Definition VPlan.h:521
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:475
DebugLoc getDebugLoc() const
Returns the debug location of the recipe.
Definition VPlan.h:553
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:465
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:350
friend class VPValue
Definition VPlanValue.h:329
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:3398
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:2926
bool isInLoop() const
Returns true if the phi is part of an in-loop reduction.
Definition VPlan.h:2945
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:3337
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:3350
VPValue * getCondOp() const
The VPValue of the condition for the block.
Definition VPlan.h:3352
RecurKind getRecurrenceKind() const
Return the recurrence kind for the in-loop reduction.
Definition VPlan.h:3333
bool isPartialReduction() const
Returns true if the reduction outputs a vector with a scaled down VF.
Definition VPlan.h:3339
VPValue * getChainOp() const
The VPValue of the scalar Chain being accumulated.
Definition VPlan.h:3348
bool isInLoop() const
Returns true if the reduction is in-loop.
Definition VPlan.h:3343
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:4662
bool isReplicator() const
An indicator whether this region is to generate multiple replicated instances of output IR correspond...
Definition VPlan.h:4738
const VPBranchOnMaskRecipe * getEntryBranchOnMask() const
Return the VPBranchOnMaskRecipe from the entry block of this replicating region.
Definition VPlan.cpp:711
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:3479
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:3517
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:4310
VPValue * getStartIndex() const
Return the StartIndex, or null if known to be zero, valid only after unrolling.
Definition VPlan.h:4318
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:611
Instruction * getUnderlyingInstr()
Returns the underlying instruction.
Definition VPlan.h:673
VPSingleDefRecipe(VPRecipeTy SC, ArrayRef< VPValue * > Operands, Type *ResultTy, Value *UV=nullptr, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:613
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:213
This class augments VPValue with operands which provide the inverse def-use edges from VPValue's user...
Definition VPlanValue.h:397
void printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const
Print the operands to O.
Definition VPlan.cpp:1502
operand_range operands()
Definition VPlanValue.h:473
unsigned getNumOperands() const
Definition VPlanValue.h:437
VPValue * getOperand(unsigned N) const
Definition VPlanValue.h:438
bool operands_empty() const
Definition VPlanValue.h:477
VPValue * getLastOperand() const
Returns the last operand.
Definition VPlanValue.h:444
void addOperand(VPValue *Operand)
Definition VPlanValue.h:423
This is the base class of the VPlan Def/Use graph, used for modeling the data flow into,...
Definition VPlanValue.h:50
Type * getScalarType() const
Returns the scalar type of this VPValue, dispatching based on the concrete subclass.
Definition VPlan.cpp:147
Value * getLiveInIRValue() const
Return the underlying IR value for a VPIRValue.
Definition VPlan.cpp:141
bool isDefinedOutsideLoopRegions() const
Returns true if the VPValue is defined outside any loop.
Definition VPlan.cpp:1454
VPRecipeBase * getDefiningRecipe()
Returns the recipe defining this VPValue or nullptr if it is not defined by a recipe,...
Definition VPlan.cpp:128
void printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const
Definition VPlan.cpp:1498
Value * getUnderlyingValue() const
Return the underlying Value attached to this VPValue.
Definition VPlanValue.h:75
void setUnderlyingValue(Value *Val)
Definition VPlanValue.h:205
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:2314
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:2311
int64_t getStride() const
Definition VPlan.h:2312
void materializeOffset(unsigned Part=0)
Adds the offset operand to the recipe.
VPValue * getStride() const
Definition VPlan.h:2388
Type * getSourceElementType() const
Definition VPlan.h:2403
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:2390
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:2155
Function * getCalledScalarFunction() const
Definition VPlan.h:2151
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:1913
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:2268
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:2573
const InductionDescriptor & getInductionDescriptor() const
Returns the induction descriptor for the recipe.
Definition VPlan.h:2590
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenIntOrFpInductionRecipe.
TruncInst * getTruncInst()
Returns the first defined value as TruncInst, if it is one or nullptr otherwise.
Definition VPlan.h:2679
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:2028
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:3784
bool isConsecutive() const
Return whether the loaded-from / stored-to addresses are consecutive.
Definition VPlan.h:3809
Instruction & Ingredient
Definition VPlan.h:3775
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const
Return the cost of this VPWidenMemoryRecipe.
bool Consecutive
Whether the accessed addresses are consecutive.
Definition VPlan.h:3781
VPValue * getMask() const
Return the mask used by this recipe.
Definition VPlan.h:3819
Align Alignment
Alignment information for this memory access.
Definition VPlan.h:3778
virtual VPRecipeBase * getAsRecipe()=0
Return a VPRecipeBase* to the current object.
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition VPlan.h:3812
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:1855
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition VPlan.h:4849
const DataLayout & getDataLayout() const
Definition VPlan.h:5063
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:5169
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:394
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
void mutateType(Type *Ty)
Mutate the type of this Value to be of the specified type.
Definition Value.h:809
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
Base class of all SIMD vector types.
ElementCount getElementCount() const
Return an ElementCount instance to represent the (possibly scalable) number of elements in the vector...
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
Type * getElementType() const
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:165
constexpr LeafTy divideCoefficientBy(ScalarTy RHS) const
We do not provide the '/' operator here because division for polynomial types does not work in the sa...
Definition TypeSize.h:252
self_iterator getIterator()
Definition ilist_node.h:123
iterator erase(iterator where)
Definition ilist.h:204
pointer remove(iterator &IT)
Definition ilist.h:188
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char 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:93
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:67
auto map_to_vector(ContainerTy &&C, FuncTy &&F)
Map a range to a SmallVector with element types deduced from the mapping.
Value * getRuntimeVF(IRBuilderBase &B, Type *Ty, ElementCount VF)
Return the runtime value for VF.
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
void interleaveComma(const Container &c, StreamT &os, UnaryFunctor each_fn)
Definition STLExtras.h:2329
auto cast_or_null(const Y &Val)
Definition Casting.h:714
LLVM_ABI Value * concatenateVectors(IRBuilderBase &Builder, ArrayRef< Value * > Vecs)
Concatenate a list of vectors.
Align getLoadStoreAlignment(const Value *I)
A helper function that returns the alignment of load or store instruction.
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
LLVM_ABI Value * createMinMaxOp(IRBuilderBase &Builder, RecurKind RK, Value *Left, Value *Right)
Returns a Min/Max operation corresponding to MinMaxRecurrenceKind.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
static Error getOffset(const SymbolRef &Sym, SectionRef Sec, uint64_t &Result)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
LLVM_ABI Constant * createBitMaskForGaps(IRBuilderBase &Builder, unsigned VF, const InterleaveGroup< Instruction > &Group)
Create a mask that filters the members of an interleave group where there are gaps.
LLVM_ABI llvm::SmallVector< int, 16 > createStrideMask(unsigned Start, unsigned Stride, unsigned VF)
Create a stride shuffle mask.
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
cl::opt< unsigned > ForceTargetInstructionCost("force-target-instruction-cost", cl::init(0), cl::Hidden, cl::desc("A flag that overrides the target's expected cost for " "an instruction to a single constant value. Mostly " "useful for getting consistent testing."))
Definition VPlan.cpp:58
ElementCount getVectorizedTypeVF(Type *Ty)
Returns the number of vector elements for a vectorized type.
LLVM_ABI llvm::SmallVector< int, 16 > createReplicatedMask(unsigned ReplicationFactor, unsigned VF)
Create a mask with replicated elements.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool isPointerTy(const Type *T)
Definition SPIRVUtils.h: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:1916
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:1151
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:1778
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
PHINode & getIRPhi() const
Definition VPlan.h:1791
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:1101
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:275
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:3910
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:4012
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:4015
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:3960