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