LLVM 24.0.0git
VPlanLowering.cpp
Go to the documentation of this file.
1//===- VPlanLowering.cpp - VPlan-to-VPlan lowering transforms -------------===//
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 implements VPlan-to-VPlan lowering transformations, which
11/// prepare an optimized VPlan for execution.
12///
13//===----------------------------------------------------------------------===//
14
16#include "VPlan.h"
17#include "VPlanAnalysis.h"
18#include "VPlanCFG.h"
19#include "VPlanDominatorTree.h"
20#include "VPlanHelpers.h"
21#include "VPlanPatternMatch.h"
22#include "VPlanTransforms.h"
23#include "VPlanUtils.h"
24#include "llvm/ADT/APInt.h"
25#include "llvm/ADT/STLExtras.h"
29#include "llvm/IR/Intrinsics.h"
30#include "llvm/IR/MDBuilder.h"
31#include "llvm/IR/Metadata.h"
35
36using namespace llvm;
37using namespace VPlanPatternMatch;
38using namespace SCEVPatternMatch;
39
43 unsigned UF) {
44 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
45 if (!LoopRegion)
46 return;
47
48 auto *WideCanIV =
50 if (!WideCanIV)
51 return;
52
53 Type *CanIVTy = LoopRegion->getCanonicalIVType();
54
55 // Replace the wide canonical IV with a scalar-iv-steps over the canonical
56 // IV.
57 if (Plan.hasScalarVFOnly() || vputils::onlyFirstLaneUsed(WideCanIV)) {
58 VPBuilder Builder(WideCanIV);
59 WideCanIV->replaceAllUsesWith(vputils::createScalarIVSteps(
60 Plan, InductionDescriptor::IK_IntInduction, Instruction::Add, nullptr,
61 CanIVTy, Plan.getZero(CanIVTy), Plan.getConstantInt(CanIVTy, 1),
62 WideCanIV->getDebugLoc(), Builder,
63 WideCanIV->getNoWrapFlags().withoutNoSignedWrap()));
64 WideCanIV->eraseFromParent();
65 return;
66 }
67
68 if (vputils::onlyScalarValuesUsed(WideCanIV))
69 return;
70
71 // If a canonical VPWidenIntOrFpInductionRecipe already produces vector lanes
72 // in the header, reuse it instead of introducing another wide induction phi.
73 VPBasicBlock *Header = LoopRegion->getEntryBasicBlock();
74 for (VPRecipeBase &Phi : Header->phis()) {
76 if (!match(&Phi, m_CanonicalWidenIV(WidenIV)))
77 continue;
78 // The reused wide IV feeds the header mask, whose lanes may extend past
79 // the trip count; drop flags that only hold inside the scalar loop.
81 WideCanIV->replaceAllUsesWith(WidenIV);
82 WideCanIV->eraseFromParent();
83 return;
84 }
85
86 // Introduce a new VPWidenIntOrFpInductionRecipe if profitable.
87 auto *VecTy = VectorType::get(CanIVTy, VF);
88 InstructionCost BroadcastCost = TTI.getShuffleCost(
89 TargetTransformInfo::SK_Broadcast, VecTy, VecTy, CostKind);
90 InstructionCost PHICost = TTI.getCFInstrCost(Instruction::PHI, CostKind);
91 if (PHICost > BroadcastCost)
92 return;
93
94 // Bail out if the additional wide induction phi increase the expected spill
95 // cost.
96 VPRegisterUsage UnrolledBase =
98 for (unsigned &NumUsers : make_second_range(UnrolledBase.MaxLocalUsers))
99 NumUsers *= UF;
100 unsigned RegClass = TTI.getRegisterClassForType(/*Vector=*/true, VecTy);
101 VPRegisterUsage Projected = UnrolledBase;
102 Projected.MaxLocalUsers[RegClass] += TTI.getRegUsageForType(VecTy);
103 if (Projected.spillCost(TTI, CostKind) >
104 UnrolledBase.spillCost(TTI, CostKind))
105 return;
106
109 VPValue *StepV = Plan.getConstantInt(CanIVTy, 1);
110 auto *NewWideIV = new VPWidenIntOrFpInductionRecipe(
111 /*IV=*/nullptr, Plan.getZero(CanIVTy), StepV, &Plan.getVF(), ID,
112 WideCanIV->getNoWrapFlags(), WideCanIV->getDebugLoc());
113 NewWideIV->insertBefore(&*Header->getFirstNonPhi());
114 WideCanIV->replaceAllUsesWith(NewWideIV);
115 WideCanIV->eraseFromParent();
116}
117
118// Add a VPActiveLaneMaskPHIRecipe and related recipes to \p Plan and replace
119// the loop terminator with a branch-on-cond recipe with the negated
120// wide-active-lane-mask as operand. Note that this turns the loop into an
121// uncountable one. Only the existing terminator is replaced, all other existing
122// recipes/users remain unchanged. Return the created VPActiveLaneMaskPHIRecipe.
123//
124// The function adds the following recipes:
125//
126// vector.ph:
127// %EntryInc = canonical-iv-increment-for-part CanonicalIVStart
128// %EntryALM = wide-active-lane-mask %EntryInc, TC
129// %EntryALMPart = extract-vector-for-part %EntryALM, ir<0>
130//
131// vector.body:
132// ...
133// %P = active-lane-mask-phi [ %EntryALMPart, %vector.ph ],
134// [ %ALMPart, %vector.body ]
135// ...
136// %InLoopInc = canonical-iv-increment-for-part CanonicalIVIncrement
137// %ALM = wide-active-lane-mask %InLoopInc, TC
138// %ALMPart = extract-vector-for-part %ALM, ir<0>
139// %Negated = Not %ALMPart
140// branch-on-cond %Negated
141//
144 VPRegionBlock *TopRegion = Plan.getVectorLoopRegion();
145 VPBasicBlock *EB = TopRegion->getExitingBasicBlock();
146 VPValue *StartV = Plan.getZero(TopRegion->getCanonicalIVType());
147 auto *CanonicalIVIncrement = TopRegion->getOrCreateCanonicalIVIncrement();
148 DebugLoc DL = CanonicalIVIncrement->getDebugLoc();
149 auto *VecPreheader = Plan.getVectorPreheader();
150 VPBuilder Builder(VecPreheader);
151 VPValue *TC = Plan.getTripCount();
152
153 // Create the wide active lane mask instruction in the VPlan preheader.
154 VPValue *ALMMultiplier =
155 Plan.getConstantInt(TopRegion->getCanonicalIVType(), 1);
156 auto *EntryALM = Builder.createNaryOp(VPInstruction::WideActiveLaneMask,
157 {StartV, TC, ALMMultiplier}, DL,
158 "active.lane.mask.entry");
159 EntryALM = Builder.createNaryOp(VPInstruction::ExtractVectorForPart,
160 {EntryALM, Plan.getConstantInt(64, 0)}, DL,
161 "extract.entry.alm.part");
162
163 // Now create the ActiveLaneMaskPhi recipe in the main loop using the
164 // preheader WideActiveLaneMask instruction.
165 auto *LaneMaskPhi =
167 auto *HeaderVPBB = TopRegion->getEntryBasicBlock();
168 LaneMaskPhi->insertBefore(HeaderVPBB->begin());
169
170 // If the canonical IV increment could overflow, adjust the trip count (TC)
171 // to TC - VF * UF.
172 VPValue *IncrementValue = CanonicalIVIncrement;
173 if (!TopRegion->hasCanonicalIVNUW() &&
175 IncrementValue = TopRegion->getCanonicalIV();
176 VPValue &VFxUF = Plan.getVFxUF();
177 TC = Builder.createScalarIntrinsic(Intrinsic::usub_sat, {TC, &VFxUF},
178 TC->getScalarType(), DL,
179 "trip.count.minus.vf");
180 }
181
182 // Create the active lane mask for the next iteration of the loop before the
183 // original terminator.
184 VPRecipeBase *OriginalTerminator = EB->getTerminator();
185 Builder.setInsertPoint(OriginalTerminator);
186 auto *ALM = Builder.createNaryOp(VPInstruction::WideActiveLaneMask,
187 {IncrementValue, TC, ALMMultiplier}, DL,
188 "active.lane.mask.next");
189 ALM = Builder.createNaryOp(VPInstruction::ExtractVectorForPart,
190 {ALM, Plan.getConstantInt(64, 0)}, DL,
191 "extract.next.alm.part");
192 LaneMaskPhi->addBackedgeValue(ALM);
193
194 // Replace the original terminator with BranchOnCond. We have to invert the
195 // mask here because a true condition means jumping to the exit block.
196 auto *NotMask = Builder.createNot(ALM, DL);
197 Builder.createNaryOp(VPInstruction::BranchOnCond, {NotMask}, DL);
198 OriginalTerminator->eraseFromParent();
199 return LaneMaskPhi;
200}
201
203 VPlan &Plan, bool UseActiveLaneMask, bool UseActiveLaneMaskForControlFlow) {
204 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
205 VPValue *HeaderMask = LoopRegion->getUsedHeaderMask();
206 if (!HeaderMask)
207 return;
208
209 if (UseActiveLaneMaskForControlFlow) {
211 return;
212 }
213
214 VPBasicBlock *Header = LoopRegion->getEntryBasicBlock();
215 VPBuilder Builder(Header->getFirstNonPhi());
216 auto *WideCanonicalIV = Builder.insert(new VPWidenCanonicalIVRecipe(
217 LoopRegion->getCanonicalIV(),
218 VPIRFlags::WrapFlagsTy(/*HasNUW=*/true, /*HasNSW=*/false)));
219 VPValue *Mask;
220 if (UseActiveLaneMask) {
221 Mask = Builder.createNaryOp(VPInstruction::ActiveLaneMask,
222 {WideCanonicalIV, Plan.getTripCount()}, nullptr,
223 "active.lane.mask");
224 } else {
225 // Compare against the backedge-taken count, TC - 1, computed in the vector
226 // preheader.
227 VPBasicBlock *VectorPH = Plan.getVectorPreheader();
228 VPValue *TC = Plan.getTripCount();
229 VPValue *BTC =
230 VPBuilder(VectorPH->getFirstNonPhi())
231 .createSub(TC, Plan.getConstantInt(TC->getScalarType(), 1),
232 DebugLoc::getCompilerGenerated(), "trip.count.minus.1");
233 if (!Plan.hasScalarVFOnly())
234 BTC = VPBuilder(VectorPH).createNaryOp(VPInstruction::Broadcast, BTC);
235 Mask = Builder.createICmp(CmpInst::ICMP_ULE, WideCanonicalIV, BTC);
236 }
237 HeaderMask->replaceAllUsesWith(Mask);
238}
239
240/// Expand a VPWidenIntOrFpInduction into executable recipes, for the initial
241/// value, phi and backedge value. In the following example:
242///
243/// vector.ph:
244/// Successor(s): vector loop
245///
246/// <x1> vector loop: {
247/// vector.body:
248/// WIDEN-INDUCTION %i = phi %start, %step, %vf
249/// ...
250/// EMIT branch-on-count ...
251/// No successors
252/// }
253///
254/// WIDEN-INDUCTION will get expanded to:
255///
256/// vector.ph:
257/// ...
258/// vp<%induction.start> = ...
259/// vp<%induction.increment> = ...
260///
261/// Successor(s): vector loop
262///
263/// <x1> vector loop: {
264/// vector.body:
265/// ir<%i> = WIDEN-PHI vp<%induction.start>, vp<%vec.ind.next>
266/// ...
267/// vp<%vec.ind.next> = add ir<%i>, vp<%induction.increment>
268/// EMIT branch-on-count ...
269/// No successors
270/// }
271static void
273 VPlan *Plan = WidenIVR->getParent()->getPlan();
274 VPValue *Start = WidenIVR->getStartValue();
275 VPValue *Step = WidenIVR->getStepValue();
276 VPValue *VF = WidenIVR->getVFValue();
277 DebugLoc DL = WidenIVR->getDebugLoc();
278
279 // The value from the original loop to which we are mapping the new induction
280 // variable.
281 Type *Ty = WidenIVR->getScalarType();
282
283 const InductionDescriptor &ID = WidenIVR->getInductionDescriptor();
286 VPIRFlags Flags = *WidenIVR;
287 if (ID.getKind() == InductionDescriptor::IK_IntInduction) {
288 AddOp = Instruction::Add;
289 MulOp = Instruction::Mul;
290 } else {
291 AddOp = ID.getInductionOpcode();
292 MulOp = Instruction::FMul;
293 }
294
295 // If the phi is truncated, truncate the start and step values.
296 VPBuilder Builder(Plan->getVectorPreheader());
297 Type *StepTy = Step->getScalarType();
298 if (Ty->getScalarSizeInBits() < StepTy->getScalarSizeInBits()) {
299 assert(StepTy->isIntegerTy() && "Truncation requires an integer type");
300 Step = Builder.createScalarCast(Instruction::Trunc, Step, Ty, DL);
301 Start = Builder.createScalarCast(Instruction::Trunc, Start, Ty, DL);
302 StepTy = Ty;
303 }
304
305 // Construct the initial value of the vector IV in the vector loop preheader.
306 Type *IVIntTy =
308 VPValue *Init = Builder.createNaryOp(VPInstruction::StepVector, {}, IVIntTy);
309 if (StepTy->isFloatingPointTy())
310 Init = Builder.createWidenCast(Instruction::UIToFP, Init, StepTy);
311
312 VPValue *SplatStart = Builder.createNaryOp(VPInstruction::Broadcast, Start);
313 VPValue *SplatStep = Builder.createNaryOp(VPInstruction::Broadcast, Step);
314
315 Init = Builder.createNaryOp(MulOp, {Init, SplatStep}, Flags);
316 Init = Builder.createNaryOp(AddOp, {SplatStart, Init}, Flags,
317 DebugLoc::getUnknown(), "induction");
318
319 // Create the widened phi of the vector IV.
320 auto *WidePHI = VPBuilder(WidenIVR).createWidenPhi(
321 Init, WidenIVR->getDebugLoc(), "vec.ind");
322
323 // Create the backedge value for the vector IV.
324 VPValue *Inc;
325 VPValue *Prev;
326 // If unrolled, use the increment and prev value from the operands.
327 if (auto *SplatVF = WidenIVR->getSplatVFValue()) {
328 Inc = SplatVF;
329 Prev = WidenIVR->getLastUnrolledPartOperand();
330 } else {
331 // Move the insertion point after the VF definition when the VF is defined
332 // inside a loop, such as for EVL tail-folding.
333 if (VPRecipeBase *R = VF->getDefiningRecipe())
334 if (R->getParent()->getEnclosingLoopRegion())
335 Builder.setInsertPoint(std::next(R->getIterator()));
336
337 // Multiply the vectorization factor by the step using integer or
338 // floating-point arithmetic as appropriate.
339 if (StepTy->isFloatingPointTy())
340 VF = Builder.createScalarCast(Instruction::CastOps::UIToFP, VF, StepTy,
341 DL);
342 else
343 VF = Builder.createScalarZExtOrTrunc(VF, StepTy, DL);
344
345 Inc = Builder.createNaryOp(MulOp, {Step, VF}, Flags);
346 Inc = Builder.createNaryOp(VPInstruction::Broadcast, Inc);
347 Prev = WidePHI;
348 }
349
351 Builder.setInsertPoint(ExitingBB->getTerminator());
352 auto *Next = Builder.createNaryOp(AddOp, {Prev, Inc}, Flags,
353 WidenIVR->getDebugLoc(), "vec.ind.next");
354
355 WidePHI->addIncoming(Next);
356
357 WidenIVR->replaceAllUsesWith(WidePHI);
358}
359
360/// Expand a VPWidenPointerInductionRecipe into executable recipes, for the
361/// initial value, phi and backedge value. In the following example:
362///
363/// <x1> vector loop: {
364/// vector.body:
365/// EMIT ir<%ptr.iv> = WIDEN-POINTER-INDUCTION %start, %step, %vf
366/// ...
367/// EMIT branch-on-count ...
368/// }
369///
370/// WIDEN-POINTER-INDUCTION will get expanded to:
371///
372/// <x1> vector loop: {
373/// vector.body:
374/// EMIT-SCALAR %pointer.phi = phi %start, %ptr.ind
375/// EMIT %mul = mul %stepvector, %step
376/// EMIT %vector.gep = wide-ptradd %pointer.phi, %mul
377/// ...
378/// EMIT %ptr.ind = ptradd %pointer.phi, %vf
379/// EMIT branch-on-count ...
380/// }
382 VPlan *Plan = R->getParent()->getPlan();
383 VPValue *Start = R->getStartValue();
384 VPValue *Step = R->getStepValue();
385 VPValue *VF = R->getVFValue();
386
387 assert(R->getInductionDescriptor().getKind() ==
389 "Not a pointer induction according to InductionDescriptor!");
390 assert(R->getScalarType()->isPointerTy() && "Unexpected type.");
391 assert(!R->onlyScalarsGenerated(Plan->hasScalableVF()) &&
392 "Recipe should have been replaced");
393
394 VPBuilder Builder(R);
395 DebugLoc DL = R->getDebugLoc();
396
397 // Build a scalar pointer phi.
398 VPPhi *ScalarPtrPhi = Builder.createScalarPhi(Start, DL, "pointer.phi");
399
400 // Create actual address geps that use the pointer phi as base and a
401 // vectorized version of the step value (<step*0, ..., step*N>) as offset.
402 Builder.setInsertPoint(R->getParent()->getFirstNonPhi());
403 Type *StepTy = Step->getScalarType();
404 VPValue *Offset = Builder.createNaryOp(VPInstruction::StepVector, {}, StepTy);
405 Offset = Builder.createOverflowingOp(Instruction::Mul, {Offset, Step});
406 VPValue *PtrAdd =
407 Builder.createWidePtrAdd(ScalarPtrPhi, Offset, DL, "vector.gep");
408 R->replaceAllUsesWith(PtrAdd);
409
410 // Create the backedge value for the scalar pointer phi.
412 Builder.setInsertPoint(ExitingBB->getTerminator());
413 VF = Builder.createScalarZExtOrTrunc(VF, StepTy, DL);
414 VPValue *Inc = Builder.createOverflowingOp(Instruction::Mul, {Step, VF});
415
416 VPValue *InductionGEP =
417 Builder.createPtrAdd(ScalarPtrPhi, Inc, DL, "ptr.ind");
418 ScalarPtrPhi->addIncoming(InductionGEP);
419}
420
421/// Expand a VPDerivedIVRecipe into executable recipes.
423 VPBuilder Builder(R);
424 VPValue *Start = R->getStartValue();
425 VPValue *Step = R->getStepValue();
426 VPValue *Index = R->getIndex();
427 Type *StepTy = Step->getScalarType();
428 Index = StepTy->isIntegerTy()
429 ? Builder.createScalarZExtOrTrunc(
430 Index, StepTy, DebugLoc::getCompilerGenerated())
431 : Builder.createScalarCast(Instruction::SIToFP, Index, StepTy,
433 VPIRFlags::WrapFlagsTy Flags = R->getNoWrapFlags();
434 switch (R->getInductionKind()) {
436 assert(Index->getScalarType() == Start->getScalarType() &&
437 "Index type does not match StartValue type");
438 return R->replaceAllUsesWith(Builder.createAdd(
439 Start,
440 Builder.createOverflowingOp(Instruction::Mul, {Index, Step}, Flags),
441 DebugLoc::getUnknown(), "", Flags));
442 }
444 return R->replaceAllUsesWith(Builder.createPtrAdd(
445 Start,
446 Builder.createOverflowingOp(Instruction::Mul, {Index, Step}, Flags)));
448 assert(StepTy->isFloatingPointTy() && "Expected FP Step value");
449 const FPMathOperator *FPBinOp = R->getFPBinOp();
450 assert(FPBinOp &&
451 (FPBinOp->getOpcode() == Instruction::FAdd ||
452 FPBinOp->getOpcode() == Instruction::FSub) &&
453 "Original BinOp should be defined for FP induction");
454 FastMathFlags FMF = FPBinOp->getFastMathFlags();
455 VPValue *FMul = Builder.createNaryOp(Instruction::FMul, {Step, Index}, FMF);
456 return R->replaceAllUsesWith(
457 Builder.createNaryOp(FPBinOp->getOpcode(), {Start, FMul}, FMF));
458 }
460 return;
461 }
462 llvm_unreachable("Unhandled induction kind");
463}
464
466 // Replace loop regions with explicity CFG.
469 vp_depth_first_deep(Plan.getEntry()))) {
470 if (!R->isReplicator())
471 LoopRegions.push_back(R);
472 }
473 for (VPRegionBlock *R : LoopRegions)
474 R->dissolveToCFGLoop();
475}
476
479 // The transform runs after dissolving loop regions, so all VPBasicBlocks
480 // terminated with BranchOnTwoConds are reached via a shallow traversal.
483 if (!VPBB->empty() && match(&VPBB->back(), m_BranchOnTwoConds()))
484 WorkList.push_back(cast<VPInstruction>(&VPBB->back()));
485 }
486
487 // Expand BranchOnTwoConds instructions into explicit CFG with two new
488 // single-condition branches:
489 // 1. A branch that replaces BranchOnTwoConds, jumps to the first successor if
490 // the first condition is true, and otherwise jumps to a new interim block.
491 // 2. A branch that ends the interim block, jumps to the second successor if
492 // the second condition is true, and otherwise jumps to the third
493 // successor.
494 for (VPInstruction *Br : WorkList) {
495 assert(Br->getNumOperands() == 2 &&
496 "BranchOnTwoConds must have exactly 2 conditions");
497 DebugLoc DL = Br->getDebugLoc();
498 VPBasicBlock *BrOnTwoCondsBB = Br->getParent();
499 const auto Successors = to_vector(BrOnTwoCondsBB->getSuccessors());
500 assert(Successors.size() == 3 &&
501 "BranchOnTwoConds must have exactly 3 successors");
502
503 for (VPBlockBase *Succ : Successors)
504 VPBlockUtils::disconnectBlocks(BrOnTwoCondsBB, Succ);
505
506 VPValue *Cond0 = Br->getOperand(0);
507 VPValue *Cond1 = Br->getOperand(1);
508 VPBlockBase *Succ0 = Successors[0];
509 VPBlockBase *Succ1 = Successors[1];
510 VPBlockBase *Succ2 = Successors[2];
511
512 // If the successor block for both conditions is the same, then combine the
513 // two conditions and plant a single conditional branch.
514 if (Succ0 == Succ1) {
515 VPBuilder Builder(Br);
516 VPValue *Combined = Builder.createOr(Cond0, Cond1, DL);
517 Builder.createNaryOp(VPInstruction::BranchOnCond, {Combined}, DL);
518 VPBlockUtils::connectBlocks(BrOnTwoCondsBB, Succ0);
519 VPBlockUtils::connectBlocks(BrOnTwoCondsBB, Succ2);
520 Br->eraseFromParent();
521 continue;
522 }
523
524 assert(!Succ0->getParent() && !Succ1->getParent() && !Succ2->getParent() &&
525 !BrOnTwoCondsBB->getParent() && "regions must already be dissolved");
526
527 VPBasicBlock *InterimBB =
528 Plan.createVPBasicBlock(BrOnTwoCondsBB->getName() + ".interim");
529
530 VPBuilder(BrOnTwoCondsBB)
532 VPBlockUtils::connectBlocks(BrOnTwoCondsBB, Succ0);
533 VPBlockUtils::connectBlocks(BrOnTwoCondsBB, InterimBB);
534
536 VPBlockUtils::connectBlocks(InterimBB, Succ1);
537 VPBlockUtils::connectBlocks(InterimBB, Succ2);
538 Br->eraseFromParent();
539 }
540}
541
544 vp_depth_first_deep(Plan.getEntry()))) {
545 for (VPRecipeBase &R : make_early_inc_range(*VPBB)) {
546 VPBuilder Builder(&R);
547 // !prof is only supported on scalar selects.
548 if (auto *Widen = dyn_cast<VPWidenRecipe>(&R)) {
549 if (Widen->getOpcode() == Instruction::Select &&
550 !vputils::isSingleScalar(Widen->getOperand(0)))
551 Widen->eraseMetadata(LLVMContext::MD_prof);
552 }
553
554 if (auto *WidenIVR = dyn_cast<VPWidenIntOrFpInductionRecipe>(&R)) {
556 WidenIVR->eraseFromParent();
557 continue;
558 }
559
560 if (auto *WidenIVR = dyn_cast<VPWidenPointerInductionRecipe>(&R)) {
561 // If the recipe only generates scalars, scalarize it instead of
562 // expanding it.
563 if (WidenIVR->onlyScalarsGenerated(Plan.hasScalableVF())) {
565 WidenIVR, Plan, Builder);
566 WidenIVR->replaceAllUsesWith(PtrAdd);
567 WidenIVR->eraseFromParent();
568 continue;
569 }
571 WidenIVR->eraseFromParent();
572 continue;
573 }
574
575 if (auto *CondIV = dyn_cast<VPConditionalInductionPHIRecipe>(&R)) {
576 VPPhi *CondIVPhi = Builder.createScalarPhi(
577 CondIV->getStartValue(), CondIV->getDebugLoc(), "conditional.iv");
578 CondIVPhi->addIncoming(CondIV->getBackedgeValue());
579 CondIV->replaceAllUsesWith(CondIVPhi);
580 CondIV->eraseFromParent();
581 continue;
582 }
583
584 if (auto *DerivedIVR = dyn_cast<VPDerivedIVRecipe>(&R)) {
585 expandVPDerivedIV(DerivedIVR);
586 DerivedIVR->eraseFromParent();
587 continue;
588 }
589
590 if (auto *WideCanIV = dyn_cast<VPWidenCanonicalIVRecipe>(&R)) {
591 VPValue *CanIV = WideCanIV->getCanonicalIV();
592 Type *CanIVTy = CanIV->getScalarType();
593 VPValue *Step = WideCanIV->getStepValue();
594 if (!Step) {
595 assert(Plan.getConcreteUF() == 1 &&
596 "Expected unroller to have materialized step for UF != 1");
597 Step = Plan.getZero(CanIVTy);
598 }
599 CanIV = Builder.createNaryOp(VPInstruction::Broadcast, CanIV);
600 Step = Builder.createNaryOp(VPInstruction::Broadcast, Step);
601 Step = Builder.createAdd(
602 Step, Builder.createNaryOp(VPInstruction::StepVector, {}, CanIVTy));
603 VPValue *CanVecIV =
604 Builder.createAdd(CanIV, Step, WideCanIV->getDebugLoc(), "vec.iv",
605 WideCanIV->getNoWrapFlags());
606 WideCanIV->replaceAllUsesWith(CanVecIV);
607 WideCanIV->eraseFromParent();
608 continue;
609 }
610
611 // Expand VPBlendRecipe into VPInstruction::Select.
612 if (auto *Blend = dyn_cast<VPBlendRecipe>(&R)) {
613 VPValue *Select = Blend->getIncomingValue(0);
614 for (unsigned I = 1; I != Blend->getNumIncomingValues(); ++I)
615 Select = Builder.createSelect(Blend->getMask(I),
616 Blend->getIncomingValue(I), Select,
617 R.getDebugLoc(), "predphi", *Blend);
618 Blend->replaceAllUsesWith(Select);
619 Blend->eraseFromParent();
620 continue;
621 }
622
623 if (auto *VEPR = dyn_cast<VPVectorEndPointerRecipe>(&R)) {
624 if (!VEPR->getOffset()) {
625 assert(Plan.getConcreteUF() == 1 &&
626 "Expected unroller to have materialized offset for UF != 1");
627 VEPR->materializeOffset();
628 }
629 continue;
630 }
631
632 if (auto *Expr = dyn_cast<VPExpressionRecipe>(&R)) {
633 Expr->decompose();
634 Expr->eraseFromParent();
635 continue;
636 }
637
638 // Expand LastActiveLane into Not + FirstActiveLane + Sub.
639 auto *LastActiveL = dyn_cast<VPInstruction>(&R);
640 if (LastActiveL &&
641 LastActiveL->getOpcode() == VPInstruction::LastActiveLane) {
642 // Create Not(Mask) for all operands.
644 for (VPValue *Op : LastActiveL->operands()) {
645 VPValue *NotMask = Builder.createNot(Op, LastActiveL->getDebugLoc());
646 NotMasks.push_back(NotMask);
647 }
648
649 // Create FirstActiveLane on the inverted masks.
650 VPValue *FirstInactiveLane = Builder.createFirstActiveLane(
651 NotMasks, LastActiveL->getDebugLoc(), "first.inactive.lane");
652
653 // Subtract 1 to get the last active lane.
654 VPValue *One =
655 Plan.getConstantInt(FirstInactiveLane->getScalarType(), 1);
656 VPValue *LastLane =
657 Builder.createSub(FirstInactiveLane, One,
658 LastActiveL->getDebugLoc(), "last.active.lane");
659
660 LastActiveL->replaceAllUsesWith(LastLane);
661 LastActiveL->eraseFromParent();
662 continue;
663 }
664
665 // Lower MaskedCond with block mask to LogicalAnd.
667 auto *VPI = cast<VPInstruction>(&R);
668 assert(VPI->isMasked() &&
669 "Unmasked MaskedCond should be simplified earlier");
670 VPI->replaceAllUsesWith(Builder.createNaryOp(
671 VPInstruction::LogicalAnd, {VPI->getMask(), VPI->getOperand(0)}));
672 VPI->eraseFromParent();
673 continue;
674 }
675
676 // Lower CanonicalIVIncrementForPart to plain Add.
677 if (match(
678 &R,
680 auto *VPI = cast<VPInstruction>(&R);
681 VPValue *Add = Builder.createOverflowingOp(
682 Instruction::Add, VPI->operands(), VPI->getNoWrapFlags(),
683 VPI->getDebugLoc());
684 VPI->replaceAllUsesWith(Add);
685 VPI->eraseFromParent();
686 continue;
687 }
688
689 // Lower BranchOnCount to ICmp + BranchOnCond.
690 VPValue *IV, *TC;
691 if (match(&R, m_BranchOnCount(m_VPValue(IV), m_VPValue(TC)))) {
692 auto *BranchOnCountInst = cast<VPInstruction>(&R);
693 DebugLoc DL = BranchOnCountInst->getDebugLoc();
694 VPValue *Cond = Builder.createICmp(CmpInst::ICMP_EQ, IV, TC, DL);
695 Builder.createNaryOp(VPInstruction::BranchOnCond, Cond, DL);
696 BranchOnCountInst->eraseFromParent();
697 continue;
698 }
699
700 VPValue *VectorStep;
701 VPValue *ScalarStep;
703 m_VPValue(VectorStep), m_VPValue(ScalarStep))))
704 continue;
705
706 // Expand WideIVStep.
707 auto *VPI = cast<VPInstruction>(&R);
708 Type *IVTy = VPI->getScalarType();
709 if (VectorStep->getScalarType() != IVTy) {
711 ? Instruction::UIToFP
712 : Instruction::Trunc;
713 VectorStep = Builder.createWidenCast(CastOp, VectorStep, IVTy);
714 }
715
716 assert(!match(ScalarStep, m_One()) && "Expected non-unit scalar-step");
717 if (ScalarStep->getScalarType() != IVTy) {
718 ScalarStep =
719 Builder.createWidenCast(Instruction::Trunc, ScalarStep, IVTy);
720 }
721
722 VPIRFlags Flags;
723 unsigned MulOpc;
724 if (IVTy->isFloatingPointTy()) {
725 MulOpc = Instruction::FMul;
726 Flags = VPI->getFastMathFlagsOrNone();
727 } else {
728 MulOpc = Instruction::Mul;
729 Flags = VPIRFlags::getDefaultFlags(MulOpc);
730 }
731
732 VPInstruction *Mul = Builder.createNaryOp(
733 MulOpc, {VectorStep, ScalarStep}, Flags, R.getDebugLoc());
734 VectorStep = Mul;
735 VPI->replaceAllUsesWith(VectorStep);
736 VPI->eraseFromParent();
737 }
738 }
739}
740
742 if (Plan.hasScalarVFOnly())
743 return;
744
745#ifndef NDEBUG
746 VPDominatorTree VPDT(Plan);
747#endif
748
749 SmallVector<VPValue *> VPValues;
750 append_range(VPValues, Plan.getLiveIns());
751 for (VPRecipeBase &R : *Plan.getEntry())
752 append_range(VPValues, R.definedValues());
753
754 auto *VectorPreheader = Plan.getVectorPreheader();
755 for (VPValue *VPV : VPValues) {
757 continue;
758
759 // Add explicit broadcast at the insert point that dominates all users.
760 VPBasicBlock::iterator HoistPoint = VectorPreheader->end();
761 for (VPUser *User : VPV->users()) {
762 if (User->usesScalars(VPV))
763 continue;
764 if (cast<VPRecipeBase>(User)->getParent() == VectorPreheader)
765 HoistPoint = VectorPreheader->getFirstNonPhi();
766 else
767 assert(VPDT.dominates(VectorPreheader,
768 cast<VPRecipeBase>(User)->getParent()) &&
769 "All users must be in the vector preheader or dominated by it");
770 }
771
772 VPBuilder Builder(HoistPoint);
773 auto *Broadcast = Builder.createNaryOp(VPInstruction::Broadcast, {VPV});
774 VPV->replaceUsesWithIf(Broadcast, [VPV, Broadcast](VPUser *U) {
775 return Broadcast != U && !U->usesScalars(VPV);
776 });
777 }
778}
779
781 VPlan &Plan, ElementCount BestVF, unsigned BestUF,
783 assert(Plan.hasVF(BestVF) && "BestVF is not available in Plan");
784 assert(Plan.hasUF(BestUF) && "BestUF is not available in Plan");
785
786 VPValue *TC = Plan.getTripCount();
787 if (TC->user_empty())
788 return;
789
790 // Skip cases for which the trip count may be non-trivial to materialize.
791 // I.e., when a scalar tail is absent - due to tail folding, or when a scalar
792 // tail is required.
793 if (Plan.hasTailFolded() || !Plan.hasScalarTail() ||
795 Plan.getScalarPreheader() ||
796 !isa<VPIRValue>(TC))
797 return;
798
799 // Materialize vector trip counts for constants early if it can simply
800 // be computed as (Original TC / VF * UF) * VF * UF.
801 // TODO: Compute vector trip counts for loops requiring a scalar epilogue and
802 // tail-folded loops.
803 ScalarEvolution &SE = *PSE.getSE();
804 auto *TCScev = SE.getSCEV(TC->getLiveInIRValue());
805 if (!isa<SCEVConstant>(TCScev))
806 return;
807 const SCEV *VFxUF = SE.getElementCount(TCScev->getType(), BestVF * BestUF);
808 const SCEV *VecTCScev = SE.getMulExpr(SE.getUDivExpr(TCScev, VFxUF), VFxUF);
809 if (auto *ConstVecTC = dyn_cast<SCEVConstant>(VecTCScev))
810 Plan.getVectorTripCount().setUnderlyingValue(ConstVecTC->getValue());
811}
812
814 if (Plan.hasScalarVFOnly())
815 return;
816
817 auto VPBBsInsideLoopRegion = VPBlockUtils::blocksOnly<VPBasicBlock>(
819 // Create explicit VPInstructions to convert vectors to scalars. The current
820 // implementation is conservative - it may miss some cases that may or may not
821 // be vector values. TODO: introduce Unpacks speculatively - remove them later
822 // if they are known to operate on scalar values.
823 for (VPBasicBlock *VPBB : VPBBsInsideLoopRegion) {
824 for (VPRecipeBase &R : make_early_inc_range(*VPBB)) {
827 continue;
828 for (VPValue *Def : R.definedValues()) {
829 // Skip recipes that are single-scalar.
830 // TODO: The Defs skipped here may or may not be vector values.
831 // Introduce Unpacks, and remove them later, if they are guaranteed to
832 // produce scalar values.
834 continue;
835
836 // Only introduce an Unpack if some, but not all, users use the first
837 // lane only.
838 unsigned NumFirstLaneUsers = count_if(Def->users(), [&Def](VPUser *U) {
839 return U->usesFirstLaneOnly(Def);
840 });
841 if (!NumFirstLaneUsers || NumFirstLaneUsers == Def->getNumUsers())
842 continue;
843
844 auto *Unpack = new VPInstruction(VPInstruction::Unpack, {Def});
845 if (R.isPhi())
846 Unpack->insertBefore(VPBB->getFirstNonPhi());
847 else
848 Unpack->insertAfter(&R);
849 Def->replaceUsesWithIf(
850 Unpack, [&Def](VPUser *U) { return U->usesFirstLaneOnly(Def); });
851 }
852 }
853 }
854}
855
857 VPlan &Plan, VPBasicBlock *VectorPHVPBB, bool TailByMasking,
858 bool RequiresScalarEpilogue, VPValue *Step,
859 std::optional<uint64_t> MaxRuntimeStep) {
860 VPSymbolicValue &VectorTC = Plan.getVectorTripCount();
861 // There's nothing to do if there are no users of the vector trip count or its
862 // IR value has already been set.
863 if (VectorTC.user_empty() || VectorTC.getUnderlyingValue())
864 return;
865
866 VPValue *TC = Plan.getTripCount();
867 Type *TCTy = TC->getScalarType();
868 VPBasicBlock::iterator InsertPt = VectorPHVPBB->getFirstNonPhi();
869 if (auto *StepR = Step->getDefiningRecipe()) {
870 assert(VPDominatorTree(Plan).dominates(StepR->getParent(), VectorPHVPBB) &&
871 "Step VPBB must dominate VectorPHVPBB");
872 // Insert after Step's definition to maintain valid def-use ordering.
873 InsertPt = std::next(StepR->getIterator());
874 }
875 VPBuilder Builder(InsertPt);
876
877 // For scalable steps, if TC is a constant and is divisible by the maximum
878 // possible runtime step, then TC % Step == 0 for all valid vscale values
879 // and the vector trip count equals TC directly.
880 const APInt *TCVal;
881 if (!RequiresScalarEpilogue && match(TC, m_APInt(TCVal)) && MaxRuntimeStep &&
882 TCVal->urem(*MaxRuntimeStep) == 0) {
883 VectorTC.replaceAllUsesWith(TC);
884 return;
885 }
886
887 // If the tail is to be folded by masking, round the number of iterations N
888 // up to a multiple of Step instead of rounding down. This is done by first
889 // adding Step-1 and then rounding down. Note that it's ok if this addition
890 // overflows: the vector induction variable will eventually wrap to zero given
891 // that it starts at zero and its Step is a power of two; the loop will then
892 // exit, with the last early-exit vector comparison also producing all-true.
893 if (TailByMasking) {
894 TC = Builder.createAdd(
895 TC, Builder.createSub(Step, Plan.getConstantInt(TCTy, 1)),
896 DebugLoc::getCompilerGenerated(), "n.rnd.up");
897 }
898
899 // Now we need to generate the expression for the part of the loop that the
900 // vectorized body will execute. This is equal to N - (N % Step) if scalar
901 // iterations are not required for correctness, or N - Step, otherwise. Step
902 // is equal to the vectorization factor (number of SIMD elements) times the
903 // unroll factor (number of SIMD instructions).
904 VPValue *R =
905 Builder.createNaryOp(Instruction::URem, {TC, Step},
906 DebugLoc::getCompilerGenerated(), "n.mod.vf");
907
908 // There are cases where we *must* run at least one iteration in the remainder
909 // loop. See the cost model for when this can happen. If the step evenly
910 // divides the trip count, we set the remainder to be equal to the step. If
911 // the step does not evenly divide the trip count, no adjustment is necessary
912 // since there will already be scalar iterations. Note that the minimum
913 // iterations check ensures that N >= Step.
914 if (RequiresScalarEpilogue) {
915 assert(!TailByMasking &&
916 "requiring scalar epilogue is not supported with fail folding");
917 VPValue *IsZero =
918 Builder.createICmp(CmpInst::ICMP_EQ, R, Plan.getZero(TCTy));
919 R = Builder.createSelect(IsZero, Step, R);
920 }
921
922 VPValue *Res =
923 Builder.createSub(TC, R, DebugLoc::getCompilerGenerated(), "n.vec");
924 VectorTC.replaceAllUsesWith(Res);
925}
926
928 ElementCount VFEC) {
929 // If VF and VFxUF have already been materialized (no remaining users),
930 // there's nothing more to do.
931 if (Plan.getVF().isMaterialized()) {
932 assert(Plan.getVFxUF().isMaterialized() &&
933 "VF and VFxUF must be materialized together");
934 return;
935 }
936
937 VPBuilder Builder(VectorPH->getFirstNonPhi());
938 Type *TCTy = Plan.getTripCount()->getScalarType();
939 VPValue &VF = Plan.getVF();
940 VPValue &VFxUF = Plan.getVFxUF();
941 // If there are no users of the runtime VF, compute VFxUF by constant folding
942 // the multiplication of VF and UF.
943 if (VF.user_empty()) {
944 VPValue *RuntimeVFxUF =
945 Builder.createElementCount(TCTy, VFEC * Plan.getConcreteUF());
946 VFxUF.replaceAllUsesWith(RuntimeVFxUF);
947 return;
948 }
949
950 // For users of the runtime VF, compute it as VF * vscale, and VFxUF as (VF *
951 // vscale) * UF.
952 VPValue *RuntimeVF = Builder.createElementCount(TCTy, VFEC);
954 VPValue *BC = Builder.createNaryOp(VPInstruction::Broadcast, RuntimeVF);
955 VF.replaceUsesWithIf(BC, [&VF](VPUser *U) { return !U->usesScalars(&VF); });
956 }
957 VF.replaceAllUsesWith(RuntimeVF);
958
959 VPValue *MulByUF =
960 Builder.createElementCount(TCTy, VFEC * Plan.getConcreteUF());
961 VFxUF.replaceAllUsesWith(MulByUF);
962}
963
964VPValue *
966 ArrayRef<PointerDiffInfo> DiffChecks) {
967 VPBuilder Builder(AliasCheckVPBB);
968 Type *I1Ty = IntegerType::getInt1Ty(Plan.getContext());
969
970 VPValue *IncomingAliasMask = vputils::findIncomingAliasMask(Plan);
971 assert(IncomingAliasMask && "Expected an alias mask!");
972
973 VPValue *AliasMask = nullptr;
974 for (const PointerDiffInfo &Check : DiffChecks) {
976 VPValue *Sink =
978 Type *AddrType = Src->getScalarType();
979
980 // TODO: Only freeze the required pointer (not both src and sink).
981 if (Check.NeedsFreeze) {
982 Src = Builder.createFreeze(Src);
983 Sink = Builder.createFreeze(Sink);
984 }
985
986 // TODO: Generate loop_dependence_raw_mask when there's a read-after-write
987 // dependency between the source and the sink. This is not necessary for
988 // correctness of the mask, but using the "raw" variant prevents loads
989 // depending on the completion of stores.
990 VPWidenIntrinsicRecipe *WARMask = Builder.insert(new VPWidenIntrinsicRecipe(
991 Intrinsic::loop_dependence_war_mask,
992 {Src, Sink, Plan.getConstantInt(AddrType, Check.AccessSize)}, I1Ty));
993
994 if (AliasMask)
995 AliasMask = Builder.createAnd(AliasMask, WARMask);
996 else
997 AliasMask = WARMask;
998 }
999
1001 Type *IndexTy = Plan.getDataLayout().getIndexType(Plan.getContext(), 0);
1002 VPValue *NumActive = Builder.createNaryOp(
1003 VPInstruction::NumActiveLanes, {AliasMask}, nullptr, {}, {},
1004 DebugLoc::getUnknown(), "num.active.lanes", IndexTy);
1005 VPValue *ClampedVF = Builder.createScalarZExtOrTrunc(
1006 NumActive, IVTy, DebugLoc::getCompilerGenerated());
1007
1008 IncomingAliasMask->replaceAllUsesWith(AliasMask);
1009
1010 return ClampedVF;
1011}
1012
1014 VPlan &Plan, ArrayRef<PointerDiffInfo> DiffChecks, bool HasBranchWeights) {
1015 VPBasicBlock *ClampedVFCheck =
1016 Plan.createVPBasicBlock("vector.clamped.vf.check");
1017
1018 VPValue *ClampedVF = materializeAliasMask(Plan, ClampedVFCheck, DiffChecks);
1019 VPBuilder Builder(ClampedVFCheck);
1021 Type *TCTy = Plan.getTripCount()->getScalarType();
1022
1023 // Check the "ClampedVF" from the alias mask is larger than one.
1024 VPValue *IsScalar =
1025 Builder.createICmp(CmpInst::ICMP_ULE, ClampedVF,
1026 Plan.getConstantInt(TCTy, 1), DL, "vf.is.scalar");
1027
1028 VPValue *TripCount = Plan.getTripCount();
1029 VPValue *MaxUIntTripCount =
1031 VPValue *DistanceToMax = Builder.createSub(MaxUIntTripCount, TripCount);
1032
1033 // For tail-folding: Don't execute the vector loop if (UMax - n) < ClampedVF.
1034 // Note: The ClampedVF may not be a power-of-two. This means the loop exit
1035 // condition (index.next == n.vec) may not be correct in the case of an
1036 // overflow. The issue is `n.vec` could be zero due to an overflow, but
1037 // index.next is not guaranteed to overflow to zero as the ClampedVF is not a
1038 // power-of-two).
1039 VPValue *TripCountCheck = Builder.createICmp(
1040 ICmpInst::ICMP_ULT, DistanceToMax, ClampedVF, DL, "vf.step.overflow");
1041
1042 VPValue *Cond = Builder.createOr(IsScalar, TripCountCheck, DL);
1043 attachVPCheckBlock(Plan, Cond, ClampedVFCheck, HasBranchWeights);
1044
1045 // Materialize the trip count early as this will add a use of (VFxUF) that
1046 // needs to be replaced with the ClampedVF.
1048 /*TailByMasking=*/true,
1049 /*RequiresScalarEpilogue=*/false,
1050 &Plan.getVFxUF());
1051
1052 assert(Plan.getConcreteUF() == 1 &&
1053 "Clamped VF not supported with interleaving");
1054 Plan.getVF().replaceAllUsesWith(ClampedVF);
1055 Plan.getVFxUF().replaceAllUsesWith(ClampedVF);
1056}
1057
1059 ScalarEvolution &SE) {
1060 auto *Entry = Plan.getEntry();
1061 VPBuilder Builder(Entry->begin());
1063 ->getIRBasicBlock()
1064 ->getTerminator()
1065 ->getDebugLoc();
1066 VPSCEVExpander Expander(Builder, SE, DL);
1067
1068 // Expand VPExpandSCEVRecipes to VPInstructions using VPSCEVExpander.
1069 for (VPExpandSCEVRecipe &ExpSCEV :
1071 if (ExpSCEV.user_empty())
1072 continue;
1073 Builder.setInsertPoint(&ExpSCEV);
1074 VPValue *Expanded = Expander.expand(ExpSCEV);
1075 if (Expanded == &ExpSCEV)
1076 continue;
1077 ExpSCEV.replaceAllUsesWith(Expanded);
1078 // TripCount should not be used after expansion to VPInstructions. Reset to
1079 // poison to avoid dangling references.
1080 if (Plan.getTripCount() == &ExpSCEV)
1081 Plan.resetTripCount(Plan.getPoison(ExpSCEV.getScalarType()));
1082 ExpSCEV.eraseFromParent();
1083 }
1084}
1085
1088 SCEVExpander Expander(SE, "induction", /*PreserveLCSSA=*/false);
1089
1090 auto *Entry = cast<VPIRBasicBlock>(Plan.getEntry());
1091 BasicBlock *EntryBB = Entry->getIRBasicBlock();
1092 DenseMap<const SCEV *, Value *> ExpandedSCEVs;
1093 // Expand remaining VPExpandSCEVRecipes to IR instructions using SCEVExpander.
1094 for (VPExpandSCEVRecipe &ExpSCEV :
1096 const SCEV *Expr = ExpSCEV.getSCEV();
1097 Value *Res =
1098 Expander.expandCodeFor(Expr, Expr->getType(), EntryBB->getTerminator());
1099 ExpandedSCEVs[Expr] = Res;
1100 VPValue *Exp = Plan.getOrAddLiveIn(Res);
1101 ExpSCEV.replaceAllUsesWith(Exp);
1102 if (Plan.getTripCount() == &ExpSCEV)
1103 Plan.resetTripCount(Exp);
1104 ExpSCEV.eraseFromParent();
1105 }
1107 "all VPExpandSCEVRecipes must have been expanded");
1108 // Add IR instructions in the entry basic block but not in the VPIRBasicBlock
1109 // to the VPIRBasicBlock.
1110 auto EI = Entry->begin();
1111 for (Instruction &I : drop_end(*EntryBB)) {
1112 if (EI != Entry->end() && isa<VPIRInstruction>(*EI) &&
1113 &cast<VPIRInstruction>(&*EI)->getInstruction() == &I) {
1114 EI++;
1115 continue;
1116 }
1118 }
1119
1120 return ExpandedSCEVs;
1121}
1122
1123/// Add branch weight metadata, if the \p Plan's middle block is terminated by a
1124/// BranchOnCond recipe.
1126 VPlan &Plan, ElementCount VF, std::optional<unsigned> VScaleForTuning) {
1127 VPBasicBlock *MiddleVPBB = Plan.getMiddleBlock();
1128 auto *MiddleTerm =
1130 // Only add branch metadata if there is a (conditional) terminator.
1131 if (!MiddleTerm)
1132 return;
1133
1134 assert(MiddleTerm->getOpcode() == VPInstruction::BranchOnCond &&
1135 "must have a BranchOnCond");
1136 // Assume that `TripCount % VectorStep ` is equally distributed.
1137 unsigned VectorStep = Plan.getConcreteUF() * VF.getKnownMinValue();
1138 if (VF.isScalable() && VScaleForTuning.has_value())
1139 VectorStep *= *VScaleForTuning;
1140 assert(VectorStep > 0 && "trip count should not be zero");
1141 MDBuilder MDB(Plan.getContext());
1142 MDNode *BranchWeights =
1143 MDB.createBranchWeights({1, VectorStep - 1}, /*IsExpected=*/false);
1144 MiddleTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
1145}
static SDValue Widen(SelectionDAG *CurDAG, SDValue N)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
AMDGPU Register Bank Select
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static const Function * getParent(const Value *V)
static std::pair< Value *, APInt > getMask(Value *WideMask, unsigned Factor, ElementCount LeafValueEC)
This file provides a LoopVectorizationPlanner class.
#define I(x, y, z)
Definition MD5.cpp:57
This file contains the declarations for metadata subclasses.
SmallVector< MachineOperand, 4 > Cond
static bool dominates(InstrPosIndexes &PosIndexes, const MachineInstr &A, const MachineInstr &B)
This file contains some templates that are useful if you are working with the STL at all.
This file implements dominator tree analysis for a single level of a VPlan's H-CFG.
This file contains the declarations of different VPlan-related auxiliary helpers.
static VPActiveLaneMaskPHIRecipe * addVPLaneMaskPhiAndUpdateExitBranch(VPlan &Plan)
static void expandVPDerivedIV(VPDerivedIVRecipe *R)
Expand a VPDerivedIVRecipe into executable recipes.
static void expandVPWidenIntOrFpInduction(VPWidenIntOrFpInductionRecipe *WidenIVR)
Expand a VPWidenIntOrFpInduction into executable recipes, for the initial value, phi and backedge val...
static void expandVPWidenPointerInduction(VPWidenPointerInductionRecipe *R)
Expand a VPWidenPointerInductionRecipe into executable recipes, for the initial value,...
This file provides utility VPlan to VPlan transformations.
This file contains the declarations of the Vectorization Plan base classes:
static const uint32_t IV[8]
Definition blake3_impl.h:83
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition APInt.cpp:1695
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
LLVM Basic Block Representation.
Definition BasicBlock.h:62
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
LLVM_ABI IntegerType * getIndexType(LLVMContext &C, unsigned AddressSpace) const
Returns the type of a GEP index in AddressSpace.
A debug info location.
Definition DebugLoc.h:126
static DebugLoc getCompilerGenerated()
Definition DebugLoc.h:154
static DebugLoc getUnknown()
Definition DebugLoc.h:153
bool dominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
dominates - Returns true iff A dominates B.
Utility class for floating point operations which can have information about relaxed accuracy require...
Definition Operator.h:202
FastMathFlags getFastMathFlags() const
Convenience function for getting all the fast-math flags.
Definition Operator.h:291
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
A struct for saving information about induction variables.
static LLVM_ABI InductionDescriptor getCanonicalIntInduction(Type *Ty, ScalarEvolution &SE)
Returns the canonical integer induction for type Ty with start = 0 and step = 1.
@ IK_NoInduction
Not an induction variable.
@ IK_FpInduction
Floating point induction variable.
@ IK_PtrInduction
Pointer induction var. Step = C.
@ IK_IntInduction
Integer induction variable. Step = C.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:338
LLVM_ABI MDNode * createBranchWeights(uint32_t TrueWeight, uint32_t FalseWeight, bool IsExpected=false)
Return metadata containing two branch weights.
Definition MDBuilder.cpp:38
Metadata node.
Definition Metadata.h:1081
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
Definition Operator.h:43
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.
This class uses information about analyze scalars to rewrite expressions in canonical form.
LLVM_ABI Value * expandCodeFor(SCEVUse SH, Type *Ty, BasicBlock::iterator I)
Insert code to directly compute the specified SCEV expression into the program.
This class represents an analyzed expression in the program.
Type * getType() const
Return the LLVM type of this SCEV expression.
The main scalar evolution driver.
LLVM_ABI const SCEV * getUDivExpr(SCEVUse LHS, SCEVUse RHS)
Get a canonical unsigned division expression, or something simpler if possible.
LLVM_ABI const SCEV * getElementCount(Type *Ty, ElementCount EC, SCEVFlags Flags=SCEV::FlagNone)
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
LLVM_ABI SCEVUse getMulExpr(SmallVectorImpl< SCEVUse > &Ops, SCEVFlagsPair Flags={}, unsigned Depth=0)
Get a canonical multiply expression, or something simpler if possible.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
TargetCostKind
The kind of cost model.
@ SK_Broadcast
Broadcast element 0 to all other elements.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:363
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:222
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:296
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
A recipe for generating the active lane mask for the vector loop that is used to predicate the vector...
Definition VPlan.h:4160
VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph.
Definition VPlan.h:4523
RecipeListTy::iterator iterator
Instruction iterators...
Definition VPlan.h:4554
iterator getFirstNonPhi()
Return the position of the first non-phi node recipe in the block.
Definition VPlan.cpp:228
VPRecipeBase * getTerminator()
If the block has multiple successors, return the branch recipe terminating the block.
Definition VPlan.cpp:608
VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
Definition VPlan.h:96
VPRegionBlock * getParent()
Definition VPlan.h:194
const VPBasicBlock * getExitingBasicBlock() const
Definition VPlan.cpp:198
const std::string & getName() const
Definition VPlan.h:185
const VPBasicBlock * getEntryBasicBlock() const
Definition VPlan.cpp:183
VPBlockBase * getSingleSuccessor() const
Definition VPlan.h:234
const VPBlocksTy & getSuccessors() const
Definition VPlan.h:218
static auto blocksAs(T &&Range)
Return an iterator range over Range with each block cast to BlockTy.
Definition VPlanUtils.h:453
static void connectBlocks(VPBlockBase *From, VPBlockBase *To, unsigned PredIdx=-1u, unsigned SuccIdx=-1u)
Connect VPBlockBases From and To bi-directionally.
Definition VPlanUtils.h:380
static void disconnectBlocks(VPBlockBase *From, VPBlockBase *To)
Disconnect VPBlockBases From and To bi-directionally.
Definition VPlanUtils.h:398
static auto blocksOnly(T &&Range)
Return an iterator range over Range which only includes BlockTy blocks.
Definition VPlanUtils.h:446
VPInstruction * createNaryOp(unsigned Opcode, ArrayRef< VPValue * > Operands, Instruction *Inst=nullptr, const VPIRFlags &Flags={}, const VPIRMetadata &MD={}, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="", Type *ResultTy=nullptr, const VPIRAttributes &Attrs={})
Create an N-ary operation with Opcode, Operands and set Inst as its underlying Instruction.
VPInstruction * createSub(VPValue *LHS, VPValue *RHS, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="", VPRecipeWithIRFlags::WrapFlagsTy WrapFlags={false, false})
VPWidenPHIRecipe * createWidenPhi(ArrayRef< VPValue * > IncomingValues, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
A recipe for converting Current into Start + Current * Step.
Definition VPlan.h:4293
Template specialization of the standard LLVM dominator tree utility for VPBlockBases.
Recipe to expand a SCEV expression.
Definition VPlan.h:4117
VPValue * getStartValue()
Returns the start value of the phi, if one is set.
Definition VPlan.h:2509
Class to record and manage LLVM IR flags.
Definition VPlan.h:684
static LLVM_ABI_FOR_TEST VPIRFlags getDefaultFlags(unsigned Opcode, Type *ResultTy=nullptr)
Returns default flags for Opcode and scalar ResultTy for opcodes that support it, asserts otherwise.
void dropPoisonGeneratingFlags()
Drop all poison-generating flags.
Definition VPlan.h:879
static LLVM_ABI_FOR_TEST VPIRInstruction * create(Instruction &I)
Create a new VPIRPhi for \I , if it is a PHINode, otherwise create a VPIRInstruction.
This is a concrete Recipe that models a single VPlan-level instruction.
Definition VPlan.h:1323
@ Unpack
Extracts all lanes from its (non-scalable) vector operand.
Definition VPlan.h:1379
void addIncoming(VPValue *IncomingV)
Append IncomingV as an incoming value to the phi-like recipe.
Definition VPlan.h:1670
VPRecipeBase is a base class modeling a sequence of one or more output IR instructions.
Definition VPlan.h:403
RecipeListTy::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
DebugLoc getDebugLoc() const
Returns the debug location of the recipe.
Definition VPlan.h:548
void insertBefore(VPRecipeBase *InsertPos)
Insert an unlinked recipe into a basic block immediately before the specified recipe.
Type * getScalarType() const
Returns the scalar type of this VPRecipeValue.
Definition VPlanValue.h:349
VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks which form a Single-Entry-S...
Definition VPlan.h:4754
const VPBlockBase * getEntry() const
Definition VPlan.h:4798
VPRegionValue * getUsedHeaderMask() const
Return the header mask if it exists and is used, or null otherwise.
Definition VPlan.h:4894
VPInstruction * getOrCreateCanonicalIVIncrement()
Get the canonical IV increment instruction if it exists.
Definition VPlan.cpp:885
Type * getCanonicalIVType() const
Return the type of the canonical IV for loop regions.
Definition VPlan.h:4882
bool hasCanonicalIVNUW() const
Indicates if NUW is set for the canonical IV increment, for loop regions.
Definition VPlan.h:4918
VPRegionValue * getCanonicalIV()
Return the canonical induction variable of the region, null for replicating regions.
Definition VPlan.h:4874
VPReplicateRecipe replicates a given instruction producing multiple scalar copies of the original sca...
Definition VPlan.h:3485
Lightweight SCEV-to-VPlan expander.
Definition VPlanUtils.h:281
VPValue * expand(const SCEV *S)
Expand S into recipes and live-ins using the builder.
A recipe for handling phi nodes of integer and floating-point inductions, producing their scalar valu...
Definition VPlan.h:4354
A symbolic live-in VPValue, used for values like vector trip count, VF, and VFxUF.
Definition VPlanValue.h:212
bool isMaterialized() const
Returns true if this value has been materialized.
Definition VPlanValue.h:230
This class augments VPValue with operands which provide the inverse def-use edges from VPValue's user...
Definition VPlanValue.h:396
This is the base class of the VPlan Def/Use graph, used for modeling the data flow into,...
Definition VPlanValue.h:50
Type * getScalarType() const
Returns the scalar type of this VPValue, dispatching based on the concrete subclass.
Definition VPlan.cpp:142
Value * getLiveInIRValue() const
Return the underlying IR value for a VPIRValue.
Definition VPlan.cpp:136
VPRecipeBase * getDefiningRecipe()
Returns the recipe defining this VPValue or nullptr if it is not defined by a recipe,...
Definition VPlan.cpp:123
Value * getUnderlyingValue() const
Return the underlying Value attached to this VPValue.
Definition VPlanValue.h:75
void replaceUsesWithIf(VPValue *New, llvm::function_ref< bool(VPUser *U)> ShouldReplace)
Go through the uses list for this VPValue and make each use point to New if the callback ShouldReplac...
Definition VPlan.cpp:1482
bool user_empty() const
Definition VPlanValue.h:161
void setUnderlyingValue(Value *Val)
Definition VPlanValue.h:204
void replaceAllUsesWith(VPValue *New)
Definition VPlan.cpp:1476
A Recipe for widening the canonical induction variable of the vector loop.
Definition VPlan.h:4236
VPValue * getStepValue()
Returns the step value of the induction.
Definition VPlan.h:2587
const InductionDescriptor & getInductionDescriptor() const
Returns the induction descriptor for the recipe.
Definition VPlan.h:2604
A recipe for handling phi nodes of integer and floating-point inductions, producing their vector valu...
Definition VPlan.h:2633
VPValue * getSplatVFValue() const
If the recipe has been unrolled, return the VPValue for the induction increment, otherwise return nul...
Definition VPlan.h:2675
VPValue * getLastUnrolledPartOperand()
Returns the VPValue representing the value of this induction at the last unrolled part,...
Definition VPlan.h:2704
A recipe for widening vector intrinsics.
Definition VPlan.h:1937
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition VPlan.h:4941
bool hasVF(ElementCount VF) const
Definition VPlan.h:5164
const DataLayout & getDataLayout() const
Definition VPlan.h:5142
LLVMContext & getContext() const
Definition VPlan.h:5138
VPBasicBlock * getEntry()
Definition VPlan.h:5033
bool hasScalableVF() const
Definition VPlan.h:5165
VPValue * getTripCount() const
The trip count of the original loop.
Definition VPlan.h:5105
VPSymbolicValue & getVFxUF()
Returns VF * UF of the vector loop region.
Definition VPlan.h:5136
auto getLiveIns() const
Return the list of live-in VPValues available in the VPlan.
Definition VPlan.h:5274
bool hasUF(unsigned UF) const
Definition VPlan.h:5189
VPIRValue * getPoison(Type *Ty)
Return a VPIRValue wrapping a poison value of type Ty.
Definition VPlan.h:5265
VPSymbolicValue & getVectorTripCount()
The vector trip count.
Definition VPlan.h:5126
VPIRValue * getOrAddLiveIn(Value *V)
Gets the live-in VPIRValue for V or adds a new live-in (if none exists yet) for V.
Definition VPlan.h:5214
VPIRValue * getZero(Type *Ty)
Return a VPIRValue wrapping the null value of type Ty.
Definition VPlan.h:5240
LLVM_ABI_FOR_TEST VPRegionBlock * getVectorLoopRegion()
Returns the VPRegionBlock of the vector loop.
Definition VPlan.cpp:1066
unsigned getConcreteUF() const
Returns the concrete UF of the plan, after unrolling.
Definition VPlan.h:5192
void resetTripCount(VPValue *NewTripCount)
Resets the trip count for the VPlan.
Definition VPlan.h:5119
VPBasicBlock * getMiddleBlock()
Returns the 'middle' block of the plan, that is the block that selects whether to execute the scalar ...
Definition VPlan.h:5075
VPBasicBlock * createVPBasicBlock(const Twine &Name, VPRecipeBase *Recipe=nullptr)
Create a new VPBasicBlock with Name and containing Recipe if present.
Definition VPlan.h:5297
VPBasicBlock * getVectorPreheader() const
Returns the preheader of the vector loop region, if one exists, or null otherwise.
Definition VPlan.h:5038
bool hasScalarVFOnly() const
Definition VPlan.h:5182
VPBasicBlock * getScalarPreheader() const
Return the VPBasicBlock for the preheader of the scalar loop.
Definition VPlan.h:5089
bool hasTailFolded() const
Returns true if the vector loop region is tail-folded.
Definition VPlan.h:5054
VPSymbolicValue & getVF()
Returns the VF of the vector loop region.
Definition VPlan.h:5129
bool hasScalarTail() const
Returns true if the scalar tail may execute after the vector loop, i.e.
Definition VPlan.h:5370
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:5248
LLVM Value Representation.
Definition Value.h:75
iterator_range< user_iterator > users()
Definition Value.h:428
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:166
const ParentTy * getParent() const
Definition ilist_node.h:34
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
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.
RecipeTy * findSingleUser(VPValue *V, const MatchT &P)
Return the sole user of V matching pattern P, casting it to RecipeTy, or nullptr.
VPInstruction_match< VPInstruction::BranchOnTwoConds > m_BranchOnTwoConds()
canonical_widen_iv_match m_CanonicalWidenIV()
VPInstruction_match< VPInstruction::BranchOnCount > m_BranchOnCount()
auto m_VPValue()
Match an arbitrary VPValue and ignore it.
match_bind< VPInstruction > m_VPInstruction(VPInstruction *&V)
Match a VPInstruction, capturing if we match.
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 onlyFirstLaneUsed(const VPValue *Def)
Returns true if only the first lane of Def is used by all users.
VPValue * findIncomingAliasMask(const VPlan &Plan)
Finds the incoming alias-mask within the vector preheader.
VPScalarIVStepsRecipe * createScalarIVSteps(VPlan &Plan, InductionDescriptor::InductionKind Kind, Instruction::BinaryOps InductionOpcode, FPMathOperator *FPBinOp, Type *ResultTy, VPValue *StartV, VPValue *Step, DebugLoc DL, VPBuilder &Builder, const VPIRFlags::WrapFlagsTy &Flags={})
Create a scalar-iv-steps recipe over Plan's canonical IV for an induction of Kind with InductionOpcod...
bool onlyScalarValuesUsed(const VPValue *Def)
Returns true if only scalar values of Def are used by all users.
VPValue * getOrCreateVPValueForSCEVExpr(VPlan &Plan, const SCEV *Expr, bool ExpandInIR=false)
Get or create a VPValue that corresponds to the expansion of Expr.
VPValue * scalarizeVPWidenPointerInduction(VPWidenPointerInductionRecipe *PtrIV, VPlan &Plan, VPBuilder &Builder)
Scalarize a VPWidenPointerInductionRecipe by replacing it with a PtrAdd (IndStart,...
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
VPBuilderBase<> VPBuilder
Definition VPlan.h:67
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
iterator_range< df_iterator< VPBlockShallowTraversalWrapper< VPBlockBase * > > > vp_depth_first_shallow(VPBlockBase *G)
Returns an iterator range to traverse the graph starting at G in depth-first order.
Definition VPlanCFG.h:250
iterator_range< df_iterator< VPBlockDeepTraversalWrapper< VPBlockBase * > > > vp_depth_first_deep(VPBlockBase *G)
Returns an iterator range to traverse the graph starting at G in depth-first order while traversing t...
Definition VPlanCFG.h:285
auto make_isa_range(RangeT &&Range)
Return a range over Range containing only elements for which isa<T> holds, casting each of them to T.
Definition STLExtras.h:567
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
SmallVector< VPRegisterUsage, 8 > calculateRegisterUsageForPlan(VPlan &Plan, ArrayRef< ElementCount > VFs, const TargetTransformInfo &TTI)
Estimate the register usage for Plan and vectorization factors in VFs by calculating the highest numb...
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...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
auto drop_end(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the last N elements excluded.
Definition STLExtras.h:323
TargetTransformInfo TTI
@ Mul
Product of integers.
@ FMul
Product of floats.
@ Add
Sum of integers.
DWARFExpression::Operation Op
auto make_second_range(ContainerTy &&c)
Given a container of pairs, return a range over the second elements.
Definition STLExtras.h:1425
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2035
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
Definition Casting.h:866
A struct that represents some properties of the register usage of a loop.
SmallMapVector< unsigned, unsigned, 4 > MaxLocalUsers
Holds the maximum number of concurrent live intervals in the loop.
InstructionCost spillCost(const TargetTransformInfo &TTI, TargetTransformInfo::TargetCostKind CostKind, unsigned OverrideMaxNumRegs=0) const
Calculate the estimated cost of any spills due to using more registers than the number available for ...
static VPValue * materializeAliasMask(VPlan &Plan, VPBasicBlock *AliasCheckVPBB, ArrayRef< PointerDiffInfo > DiffChecks)
Materializes within the AliasCheckVPBB block.
static void expandSCEVsToVPInstructions(VPlan &Plan, ScalarEvolution &SE)
Expand VPExpandSCEVRecipes in Plan's entry block to VPInstructions.
static void materializeBroadcasts(VPlan &Plan)
Add explicit broadcasts for live-ins and VPValues defined in Plan's entry block if they are used as v...
static void materializeFactors(VPlan &Plan, VPBasicBlock *VectorPH, ElementCount VF)
Materialize UF, VF and VFxUF to be computed explicitly using VPInstructions.
static void materializeHeaderMask(VPlan &Plan, bool UseActiveLaneMask, bool UseActiveLaneMaskForControlFlow)
Materialize the abstract header mask of the loop region into concrete recipes: an active-lane-mask if...
static void addBranchWeightToMiddleTerminator(VPlan &Plan, ElementCount VF, std::optional< unsigned > VScaleForTuning)
Add branch weight metadata, if the Plan's middle block is terminated by a BranchOnCond recipe.
static void materializeAliasMaskCheckBlock(VPlan &Plan, ArrayRef< PointerDiffInfo > DiffChecks, bool HasBranchWeights)
Materializes the alias mask within a check block before the loop.
static DenseMap< const SCEV *, Value * > expandSCEVs(VPlan &Plan, ScalarEvolution &SE)
Expand remaining VPExpandSCEVRecipes in Plan's entry block using SCEVExpander.
static void convertToConcreteRecipes(VPlan &Plan)
Lower abstract recipes to concrete ones, that can be codegen'd.
static void expandBranchOnTwoConds(VPlan &Plan)
Expand BranchOnTwoConds instructions into explicit CFG with BranchOnCond instructions.
static void materializeVectorTripCount(VPlan &Plan, VPBasicBlock *VectorPHVPBB, bool TailByMasking, bool RequiresScalarEpilogue, VPValue *Step, std::optional< uint64_t > MaxRuntimeStep=std::nullopt)
Materialize vector trip count computations to a set of VPInstructions.
static void materializeConstantVectorTripCount(VPlan &Plan, ElementCount BestVF, unsigned BestUF, PredicatedScalarEvolution &PSE)
static void replaceWideCanonicalIVWithWideIV(VPlan &Plan, ScalarEvolution &SE, const TargetTransformInfo &TTI, TargetTransformInfo::TargetCostKind CostKind, ElementCount VF, unsigned UF)
Replace a VPWidenCanonicalIVRecipe if it is present in Plan, with a VPWidenIntOrFpInductionRecipe,...
static void materializeUnpacks(VPlan &Plan)
Add explicit Unpack recipes to extract scalars from vectors as needed.
static void attachVPCheckBlock(VPlan &Plan, VPValue *Cond, VPBasicBlock *CheckBlock, bool AddBranchWeights)
Connect CheckBlock to Plan, branching on Cond.
static void dissolveLoopRegions(VPlan &Plan)
Replace loop regions with explicit CFG.