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