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