LLVM 23.0.0git
VPlanUnroll.cpp
Go to the documentation of this file.
1//===-- VPlanUnroll.cpp - VPlan unroller ----------------------------------===//
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 explicit unrolling for VPlans.
11///
12//===----------------------------------------------------------------------===//
13
14#include "VPRecipeBuilder.h"
15#include "VPlan.h"
16#include "VPlanAnalysis.h"
17#include "VPlanCFG.h"
18#include "VPlanHelpers.h"
19#include "VPlanPatternMatch.h"
20#include "VPlanTransforms.h"
21#include "VPlanUtils.h"
23#include "llvm/ADT/STLExtras.h"
24#include "llvm/ADT/ScopeExit.h"
26#include "llvm/IR/Constants.h"
27#include "llvm/IR/Intrinsics.h"
28
29using namespace llvm;
30using namespace llvm::VPlanPatternMatch;
31
32namespace {
33
34/// Helper to hold state needed for unrolling. It holds the Plan to unroll by
35/// UF. It also holds copies of VPValues across UF-1 unroll parts to facilitate
36/// the unrolling transformation, where the original VPValues are retained for
37/// part zero.
38class UnrollState {
39 /// Plan to unroll.
40 VPlan &Plan;
41 /// Unroll factor to unroll by.
42 const unsigned UF;
43
44 /// Unrolling may create recipes that should not be unrolled themselves.
45 /// Those are tracked in ToSkip.
46 SmallPtrSet<VPRecipeBase *, 8> ToSkip;
47
48 // Associate with each VPValue of part 0 its unrolled instances of parts 1,
49 // ..., UF-1.
50 DenseMap<VPValue *, SmallVector<VPValue *>> VPV2Parts;
51
52 /// Unroll replicate region \p VPR by cloning the region UF - 1 times.
53 void unrollReplicateRegionByUF(VPRegionBlock *VPR);
54
55 /// Unroll recipe \p R by cloning it UF - 1 times, unless it is uniform across
56 /// all parts.
57 void unrollRecipeByUF(VPRecipeBase &R);
58
59 /// Unroll header phi recipe \p R. How exactly the recipe gets unrolled
60 /// depends on the concrete header phi. Inserts newly created recipes at \p
61 /// InsertPtForPhi.
62 void unrollHeaderPHIByUF(VPHeaderPHIRecipe *R,
63 VPBasicBlock::iterator InsertPtForPhi);
64
65 /// Unroll a widen induction recipe \p IV. This introduces recipes to compute
66 /// the induction steps for each part.
67 void unrollWidenInductionByUF(VPWidenInductionRecipe *IV,
68 VPBasicBlock::iterator InsertPtForPhi);
69
70 VPValue *getConstantInt(unsigned Part) {
71 Type *CanIVIntTy = Plan.getVectorLoopRegion()->getCanonicalIVType();
72 return Plan.getConstantInt(CanIVIntTy, Part);
73 }
74
75public:
76 UnrollState(VPlan &Plan, unsigned UF) : Plan(Plan), UF(UF) {}
77
78 void unrollBlock(VPBlockBase *VPB);
79
80 VPValue *getValueForPart(VPValue *V, unsigned Part) {
82 return V;
83 assert((VPV2Parts.contains(V) && VPV2Parts[V].size() >= Part) &&
84 "accessed value does not exist");
85 return VPV2Parts[V][Part - 1];
86 }
87
88 /// Given a single original recipe \p OrigR (of part zero), and its copy \p
89 /// CopyR for part \p Part, map every VPValue defined by \p OrigR to its
90 /// corresponding VPValue defined by \p CopyR.
91 void addRecipeForPart(VPRecipeBase *OrigR, VPRecipeBase *CopyR,
92 unsigned Part) {
93 for (const auto &[Idx, VPV] : enumerate(OrigR->definedValues())) {
94 const auto &[V, _] = VPV2Parts.try_emplace(VPV);
95 assert(V->second.size() == Part - 1 && "earlier parts not set");
96 V->second.push_back(CopyR->getVPValue(Idx));
97 }
98 }
99
100 /// Given a uniform recipe \p R, add it for all parts.
101 void addUniformForAllParts(VPSingleDefRecipe *R) {
102 const auto &[V, Inserted] = VPV2Parts.try_emplace(R);
103 assert(Inserted && "uniform value already added");
104 for (unsigned Part = 0; Part != UF; ++Part)
105 V->second.push_back(R);
106 }
107
108 bool contains(VPValue *VPV) const { return VPV2Parts.contains(VPV); }
109
110 /// Update \p R's operand at \p OpIdx with its corresponding VPValue for part
111 /// \p P.
112 void remapOperand(VPRecipeBase *R, unsigned OpIdx, unsigned Part) {
113 auto *Op = R->getOperand(OpIdx);
114 R->setOperand(OpIdx, getValueForPart(Op, Part));
115 }
116
117 /// Update \p R's operands with their corresponding VPValues for part \p P.
118 void remapOperands(VPRecipeBase *R, unsigned Part) {
119 for (const auto &[OpIdx, Op] : enumerate(R->operands()))
120 R->setOperand(OpIdx, getValueForPart(Op, Part));
121 }
122};
123} // namespace
124
126 unsigned Part, VPlan &Plan) {
127 if (Part == 0)
128 return;
129
130 VPBuilder Builder(Steps);
131 Type *BaseIVTy = Steps->getOperand(0)->getScalarType();
132 Type *IntStepTy =
133 IntegerType::get(BaseIVTy->getContext(), BaseIVTy->getScalarSizeInBits());
134 VPValue *StartIndex = Steps->getVFValue();
135 if (Part > 1) {
136 StartIndex = Builder.createOverflowingOp(
137 Instruction::Mul,
138 {StartIndex, Plan.getConstantInt(StartIndex->getScalarType(), Part)});
139 }
140 StartIndex = Builder.createScalarSExtOrTrunc(
141 StartIndex, IntStepTy, StartIndex->getScalarType(), Steps->getDebugLoc());
142
143 if (BaseIVTy->isFloatingPointTy())
144 StartIndex = Builder.createScalarCast(Instruction::SIToFP, StartIndex,
145 BaseIVTy, Steps->getDebugLoc());
146
147 Steps->setStartIndex(StartIndex);
148}
149
150void UnrollState::unrollReplicateRegionByUF(VPRegionBlock *VPR) {
151 VPBlockBase *InsertPt = VPR->getSingleSuccessor();
152 for (unsigned Part = 1; Part != UF; ++Part) {
153 auto *Copy = VPR->clone();
154 VPBlockUtils::insertBlockBefore(Copy, InsertPt);
155
156 auto PartI = vp_depth_first_shallow(Copy->getEntry());
157 auto Part0 = vp_depth_first_shallow(VPR->getEntry());
158 for (const auto &[PartIVPBB, Part0VPBB] :
161 for (const auto &[PartIR, Part0R] : zip(*PartIVPBB, *Part0VPBB)) {
162 remapOperands(&PartIR, Part);
163 if (auto *Steps = dyn_cast<VPScalarIVStepsRecipe>(&PartIR))
164 addStartIndexForScalarSteps(Steps, Part, Plan);
165
166 addRecipeForPart(&Part0R, &PartIR, Part);
167 }
168 }
169 }
170}
171
172void UnrollState::unrollWidenInductionByUF(
173 VPWidenInductionRecipe *IV, VPBasicBlock::iterator InsertPtForPhi) {
174 VPBasicBlock *PH = cast<VPBasicBlock>(
175 IV->getParent()->getEnclosingLoopRegion()->getSinglePredecessor());
176 Type *IVTy = IV->getScalarType();
177 auto &ID = IV->getInductionDescriptor();
178 FastMathFlags FMF;
179 VPIRFlags::WrapFlagsTy WrapFlags(false, false);
180 if (auto *IntOrFPInd = dyn_cast<VPWidenIntOrFpInductionRecipe>(IV)) {
181 if (IntOrFPInd->hasFastMathFlags())
182 FMF = IntOrFPInd->getFastMathFlags();
183 if (IntOrFPInd->hasNoWrapFlags())
184 WrapFlags = IntOrFPInd->getNoWrapFlags();
185 }
186
187 VPValue *ScalarStep = IV->getStepValue();
188 VPBuilder Builder(PH);
189 Type *VectorStepTy = IVTy->isPointerTy() ? ScalarStep->getScalarType() : IVTy;
190 VPInstruction *VectorStep = Builder.createNaryOp(
191 VPInstruction::WideIVStep, {&Plan.getVF(), ScalarStep}, VectorStepTy, FMF,
192 IV->getDebugLoc());
193
194 ToSkip.insert(VectorStep);
195
196 // Now create recipes to compute the induction steps for part 1 .. UF. Part 0
197 // remains the header phi. Parts > 0 are computed by adding Step to the
198 // previous part. The header phi recipe will get 2 new operands: the step
199 // value for a single part and the last part, used to compute the backedge
200 // value during VPWidenInductionRecipe::execute.
201 // %Part.0 = VPWidenInductionRecipe %Start, %ScalarStep, %VectorStep, %Part.3
202 // %Part.1 = %Part.0 + %VectorStep
203 // %Part.2 = %Part.1 + %VectorStep
204 // %Part.3 = %Part.2 + %VectorStep
205 //
206 // The newly added recipes are added to ToSkip to avoid interleaving them
207 // again.
208 VPValue *Prev = IV;
209 Builder.setInsertPoint(IV->getParent(), InsertPtForPhi);
210 unsigned AddOpc;
211 VPIRFlags AddFlags;
212 if (IVTy->isPointerTy()) {
214 AddFlags = GEPNoWrapFlags::none();
215 } else if (IVTy->isFloatingPointTy()) {
216 AddOpc = ID.getInductionOpcode();
217 AddFlags = FMF;
218 } else {
219 AddOpc = Instruction::Add;
220 AddFlags = WrapFlags;
222 AddFlags = VPIRFlags::WrapFlagsTy(/*NUW=*/true, /*NSW=*/false);
223 }
224 for (unsigned Part = 1; Part != UF; ++Part) {
225 std::string Name =
226 Part > 1 ? "step.add." + std::to_string(Part) : "step.add";
227
228 VPInstruction *Add =
229 Builder.createNaryOp(AddOpc,
230 {
231 Prev,
232 VectorStep,
233 },
234 AddFlags, IV->getDebugLoc(), Name);
235 ToSkip.insert(Add);
236 addRecipeForPart(IV, Add, Part);
237 Prev = Add;
238 }
239 IV->addUnrolledPartOperands(VectorStep, Prev);
240}
241
242void UnrollState::unrollHeaderPHIByUF(VPHeaderPHIRecipe *R,
243 VPBasicBlock::iterator InsertPtForPhi) {
244 // First-order recurrences pass a single vector or scalar through their header
245 // phis, irrespective of interleaving.
247 return;
248
249 // Generate step vectors for each unrolled part.
250 if (auto *IV = dyn_cast<VPWidenInductionRecipe>(R)) {
251 unrollWidenInductionByUF(IV, InsertPtForPhi);
252 return;
253 }
254
255 auto *RdxPhi = dyn_cast<VPReductionPHIRecipe>(R);
256 if (RdxPhi && RdxPhi->isOrdered())
257 return;
258
259 auto InsertPt = std::next(R->getIterator());
260 for (unsigned Part = 1; Part != UF; ++Part) {
261 VPRecipeBase *Copy = R->clone();
262 Copy->insertBefore(*R->getParent(), InsertPt);
263 addRecipeForPart(R, Copy, Part);
264 if (RdxPhi) {
265 // If the start value is a ReductionStartVector, use the identity value
266 // (second operand) for unrolled parts. If the scaling factor is > 1,
267 // create a new ReductionStartVector with the scale factor and both
268 // operands set to the identity value.
269 if (auto *VPI = dyn_cast<VPInstruction>(RdxPhi->getStartValue())) {
270 assert(VPI->getOpcode() == VPInstruction::ReductionStartVector &&
271 "unexpected start VPInstruction");
272 if (Part != 1)
273 continue;
274 VPValue *StartV;
275 if (match(VPI->getOperand(2), m_One())) {
276 StartV = VPI->getOperand(1);
277 } else {
278 auto *C = VPI->clone();
279 C->setOperand(0, C->getOperand(1));
280 C->insertAfter(VPI);
281 StartV = C;
282 }
283 for (unsigned Part = 1; Part != UF; ++Part)
284 VPV2Parts[VPI][Part - 1] = StartV;
285 }
286 } else {
288 "unexpected header phi recipe not needing unrolled part");
289 }
290 }
291}
292
293/// Handle non-header-phi recipes.
294void UnrollState::unrollRecipeByUF(VPRecipeBase &R) {
296 return;
297
298 if (auto *VPI = dyn_cast<VPInstruction>(&R)) {
300 addUniformForAllParts(VPI);
301 return;
302 }
303 }
304 if (auto *RepR = dyn_cast<VPReplicateRecipe>(&R)) {
305 if (isa<StoreInst>(RepR->getUnderlyingValue()) &&
306 RepR->getOperand(1)->isDefinedOutsideLoopRegions()) {
307 // Stores to an invariant address only need to store the last part.
308 remapOperands(&R, UF - 1);
309 return;
310 }
311 if (match(RepR,
313 addUniformForAllParts(RepR);
314 return;
315 }
316 }
317
318 // Unroll non-uniform recipes.
319 auto InsertPt = std::next(R.getIterator());
320 VPBasicBlock &VPBB = *R.getParent();
321 for (unsigned Part = 1; Part != UF; ++Part) {
322 VPRecipeBase *Copy = R.clone();
323 Copy->insertBefore(VPBB, InsertPt);
324 addRecipeForPart(&R, Copy, Part);
325
326 // Phi operands are updated once all other recipes have been unrolled.
327 if (isa<VPWidenPHIRecipe>(Copy))
328 continue;
329
330 VPValue *Op;
332 m_VPValue(), m_VPValue(Op)))) {
333 Copy->setOperand(0, getValueForPart(Op, Part - 1));
334 Copy->setOperand(1, getValueForPart(Op, Part));
335 continue;
336 }
338 VPBuilder Builder(&R);
339 const DataLayout &DL = Plan.getDataLayout();
340 Type *IndexTy =
343 : DL.getIndexType(R.getVPSingleValue()->getScalarType());
344 Type *VFTy = Plan.getVF().getScalarType();
345 VPValue *VF = Builder.createScalarZExtOrTrunc(
346 &Plan.getVF(), IndexTy, VFTy, DebugLoc::getUnknown());
347 // VFxUF does not wrap, so VF * Part also cannot wrap.
348 VPValue *VFxPart = Builder.createOverflowingOp(
349 Instruction::Mul, {VF, Plan.getConstantInt(IndexTy, Part)},
350 {true, true});
351 if (auto *VecPtr = dyn_cast<VPVectorPointerRecipe>(Copy))
352 VecPtr->addPerPartOffset(VFxPart);
353 else
354 cast<VPWidenCanonicalIVRecipe>(Copy)->addPerPartStep(VFxPart);
355 continue;
356 }
357 if (auto *Red = dyn_cast<VPReductionRecipe>(&R)) {
358 auto *Phi = dyn_cast<VPReductionPHIRecipe>(R.getOperand(0));
359 if (Phi && Phi->isOrdered()) {
360 auto &Parts = VPV2Parts[Phi];
361 if (Part == 1) {
362 Parts.clear();
363 Parts.push_back(Red);
364 }
365 Parts.push_back(Copy->getVPSingleValue());
366 Phi->setOperand(1, Copy->getVPSingleValue());
367 }
368 }
369 if (auto *VEPR = dyn_cast<VPVectorEndPointerRecipe>(Copy)) {
370 // Materialize PartN offset for VectorEndPointer.
371 VEPR->setOperand(0, R.getOperand(0));
372 VEPR->setOperand(1, R.getOperand(1));
373 VEPR->materializeOffset(Part);
374 continue;
375 }
376
377 remapOperands(Copy, Part);
378
379 if (auto *ScalarIVSteps = dyn_cast<VPScalarIVStepsRecipe>(Copy))
380 addStartIndexForScalarSteps(ScalarIVSteps, Part, Plan);
381
382 if (match(Copy,
384 VPBuilder Builder(Copy);
385 VPValue *ScaledByPart = Builder.createOverflowingOp(
386 Instruction::Mul, {Copy->getOperand(1), getConstantInt(Part)});
387 Copy->setOperand(1, ScaledByPart);
388 }
389 }
390 if (auto *VEPR = dyn_cast<VPVectorEndPointerRecipe>(&R)) {
391 // Materialize Part0 offset for VectorEndPointer.
392 VEPR->materializeOffset();
393 }
394 if (auto *WideCanIV = dyn_cast<VPWidenCanonicalIVRecipe>(&R)) {
395 // Set Part0 step for WidenCanonicalIV.
396 WideCanIV->addPerPartStep(getConstantInt(0));
397 }
398}
399
400void UnrollState::unrollBlock(VPBlockBase *VPB) {
401 auto *VPR = dyn_cast<VPRegionBlock>(VPB);
402 if (VPR) {
403 if (VPR->isReplicator())
404 return unrollReplicateRegionByUF(VPR);
405
406 // Traverse blocks in region in RPO to ensure defs are visited before uses
407 // across blocks.
408 ReversePostOrderTraversal<VPBlockShallowTraversalWrapper<VPBlockBase *>>
409 RPOT(VPR->getEntry());
410 for (VPBlockBase *VPB : RPOT)
411 unrollBlock(VPB);
412 return;
413 }
414
415 // VPB is a VPBasicBlock; unroll it, i.e., unroll its recipes.
416 auto *VPBB = cast<VPBasicBlock>(VPB);
417 auto InsertPtForPhi = VPBB->getFirstNonPhi();
418 for (VPRecipeBase &R : make_early_inc_range(*VPBB)) {
419 if (ToSkip.contains(&R) || isa<VPIRInstruction>(&R))
420 continue;
421
422 // Add all VPValues for all parts to AnyOf, FirstActiveLaneMask and
423 // ComputeReductionResult which combine all parts to compute the final
424 // value.
425 VPValue *Op1;
427 match(&R, m_FirstActiveLane(m_VPValue(Op1))) ||
428 match(&R, m_LastActiveLane(m_VPValue(Op1))) ||
430 auto *VPI = cast<VPInstruction>(&R);
431 addUniformForAllParts(VPI);
432 for (unsigned Part = 1; Part != UF; ++Part)
433 VPI->addOperand(getValueForPart(Op1, Part));
434 continue;
435 }
436 VPValue *Op0;
437 if (match(&R, m_ExtractLane(m_VPValue(Op0), m_VPValue(Op1)))) {
438 auto *VPI = cast<VPInstruction>(&R);
439 addUniformForAllParts(VPI);
440 for (unsigned Part = 1; Part != UF; ++Part)
441 VPI->addOperand(getValueForPart(Op1, Part));
442 continue;
443 }
444
445 VPValue *Op2;
447 m_VPValue(Op2)))) {
448 auto *VPI = cast<VPInstruction>(&R);
449 addUniformForAllParts(VPI);
450 for (unsigned Part = 1; Part != UF; ++Part) {
451 VPI->addOperand(getValueForPart(Op1, Part));
452 VPI->addOperand(getValueForPart(Op2, Part));
453 }
454 continue;
455 }
456
457 if (Plan.hasScalarVFOnly()) {
458 if (match(&R, m_ExtractLastPart(m_VPValue(Op0))) ||
460 auto *I = cast<VPInstruction>(&R);
461 bool IsPenultimatePart =
463 unsigned PartIdx = IsPenultimatePart ? UF - 2 : UF - 1;
464 // For scalar VF, directly use the scalar part value.
465 I->replaceAllUsesWith(getValueForPart(Op0, PartIdx));
466 continue;
467 }
468 }
469 // For vector VF, the penultimate element is always extracted from the last part.
472 addUniformForAllParts(cast<VPSingleDefRecipe>(&R));
473 R.setOperand(0, getValueForPart(Op0, UF - 1));
474 continue;
475 }
476
477 auto *SingleDef = dyn_cast<VPSingleDefRecipe>(&R);
478 if (SingleDef && vputils::isUniformAcrossVFsAndUFs(SingleDef)) {
479 addUniformForAllParts(SingleDef);
480 continue;
481 }
482
483 if (auto *H = dyn_cast<VPHeaderPHIRecipe>(&R)) {
484 unrollHeaderPHIByUF(H, InsertPtForPhi);
485 continue;
486 }
487
488 unrollRecipeByUF(R);
489 }
490}
491
492void VPlanTransforms::unrollByUF(VPlan &Plan, unsigned UF) {
493 assert(UF > 0 && "Unroll factor must be positive");
494 Plan.setUF(UF);
495 llvm::scope_exit Cleanup([&Plan, UF]() {
496 auto Iter = vp_depth_first_deep(Plan.getEntry());
497 // Remove recipes that are redundant after unrolling.
499 for (VPRecipeBase &R : make_early_inc_range(*VPBB)) {
500 auto *VPI = dyn_cast<VPInstruction>(&R);
501 if (VPI &&
502 VPI->getOpcode() == VPInstruction::CanonicalIVIncrementForPart &&
503 VPI->getOperand(1) == &Plan.getVF()) {
504 VPI->replaceAllUsesWith(VPI->getOperand(0));
505 VPI->eraseFromParent();
506 }
507 }
508 }
509
510 Type *TCTy = Plan.getTripCount()->getScalarType();
511 Plan.getUF().replaceAllUsesWith(Plan.getConstantInt(TCTy, UF));
512 });
513 if (UF == 1) {
514 return;
515 }
516
517 UnrollState Unroller(Plan, UF);
518
519 // Iterate over all blocks in the plan starting from Entry, and unroll
520 // recipes inside them. This includes the vector preheader and middle blocks,
521 // which may set up or post-process per-part values.
523 Plan.getEntry());
524 for (VPBlockBase *VPB : RPOT)
525 Unroller.unrollBlock(VPB);
526
527 unsigned Part = 1;
528 // Remap operands of cloned header phis to update backedge values. The header
529 // phis cloned during unrolling are just after the header phi for part 0.
530 // Reset Part to 1 when reaching the first (part 0) recipe of a block.
531 for (VPRecipeBase &H :
533 // The second operand of Fixed Order Recurrence phi's, feeding the spliced
534 // value across the backedge, needs to remap to the last part of the spliced
535 // value.
537 Unroller.remapOperand(&H, 1, UF - 1);
538 continue;
539 }
540 if (Unroller.contains(H.getVPSingleValue())) {
541 Part = 1;
542 continue;
543 }
544 Unroller.remapOperands(&H, Part);
545 Part++;
546 }
547
549}
550
551/// Add a lane offset to the start index of \p Steps.
552static void addLaneToStartIndex(VPScalarIVStepsRecipe *Steps, unsigned Lane,
553 VPlan &Plan, VPRecipeBase *InsertPt) {
554 assert(Lane > 0 && "Zero lane adds no offset to start index");
555 Type *BaseIVTy = Steps->getOperand(0)->getScalarType();
556
557 VPValue *OldStartIndex = Steps->getStartIndex();
558 VPValue *LaneOffset;
559 unsigned AddOpcode;
560 // TODO: Retrieve the flags from Steps unconditionally.
561 VPIRFlags Flags;
562 if (BaseIVTy->isFloatingPointTy()) {
563 int SignedLane = static_cast<int>(Lane);
564 if (!OldStartIndex && Steps->getInductionOpcode() == Instruction::FSub)
565 SignedLane = -SignedLane;
566 LaneOffset = Plan.getOrAddLiveIn(ConstantFP::get(BaseIVTy, SignedLane));
567 AddOpcode = Steps->getInductionOpcode();
568 Flags = VPIRFlags(FastMathFlags());
569 } else {
570 unsigned BaseIVBits = BaseIVTy->getScalarSizeInBits();
571 LaneOffset = Plan.getConstantInt(
572 APInt(BaseIVBits, Lane, /*isSigned*/ false, /*implicitTrunc*/ true));
573 AddOpcode = Instruction::Add;
574 Flags = VPIRFlags(VPIRFlags::WrapFlagsTy(false, false));
575 }
576
577 VPValue *NewStartIndex = LaneOffset;
578 if (OldStartIndex) {
579 VPBuilder Builder(InsertPt);
580 NewStartIndex =
581 Builder.createNaryOp(AddOpcode, {OldStartIndex, LaneOffset}, Flags);
582 }
583 Steps->setStartIndex(NewStartIndex);
584}
585
586/// Create a single-scalar clone of \p DefR (must be a VPReplicateRecipe,
587/// VPInstruction or VPScalarIVStepsRecipe) for lane \p Lane. Use \p
588/// Def2LaneDefs to look up scalar definitions for operands of \DefR.
589static VPValue *
590cloneForLane(VPlan &Plan, VPBuilder &Builder, Type *IdxTy,
591 VPSingleDefRecipe *DefR, VPLane Lane,
592 const DenseMap<VPValue *, SmallVector<VPValue *>> &Def2LaneDefs) {
594 "DefR must be a VPReplicateRecipe, VPInstruction or "
595 "VPScalarIVStepsRecipe");
596 VPValue *Op;
598 auto LaneDefs = Def2LaneDefs.find(Op);
599 if (LaneDefs != Def2LaneDefs.end())
600 return LaneDefs->second[Lane.getKnownLane()];
601
602 VPValue *Idx = Plan.getConstantInt(IdxTy, Lane.getKnownLane());
603 return Builder.createNaryOp(Instruction::ExtractElement, {Op, Idx});
604 }
605
606 // Collect the operands at Lane, creating extracts as needed.
608 for (VPValue *Op : DefR->operands()) {
609 // If Op is a definition that has been unrolled, directly use the clone for
610 // the corresponding lane.
611 auto LaneDefs = Def2LaneDefs.find(Op);
612 if (LaneDefs != Def2LaneDefs.end()) {
613 NewOps.push_back(LaneDefs->second[Lane.getKnownLane()]);
614 continue;
615 }
616 if (Lane.getKind() == VPLane::Kind::ScalableLast) {
617 // Look through mandatory Unpack.
618 [[maybe_unused]] bool Matched =
620 assert(Matched && "original op must have been Unpack");
621 auto *ExtractPart =
622 Builder.createNaryOp(VPInstruction::ExtractLastPart, {Op});
623 NewOps.push_back(
624 Builder.createNaryOp(VPInstruction::ExtractLastLane, {ExtractPart}));
625 continue;
626 }
628 NewOps.push_back(Op);
629 continue;
630 }
631
632 // Look through buildvector to avoid unnecessary extracts.
633 if (match(Op, m_BuildVector())) {
634 NewOps.push_back(
635 cast<VPInstruction>(Op)->getOperand(Lane.getKnownLane()));
636 continue;
637 }
638 VPValue *Idx = Plan.getConstantInt(IdxTy, Lane.getKnownLane());
639 VPValue *Ext = Builder.createNaryOp(Instruction::ExtractElement, {Op, Idx});
640 NewOps.push_back(Ext);
641 }
642
644 if (auto *RepR = dyn_cast<VPReplicateRecipe>(DefR)) {
645 // TODO: have cloning of replicate recipes also provide the desired result
646 // coupled with setting its operands to NewOps (deriving IsSingleScalar and
647 // Mask from the operands?)
648 New = new VPReplicateRecipe(RepR->getUnderlyingInstr(), NewOps,
649 /*IsSingleScalar=*/true, /*Mask=*/nullptr,
650 *RepR, *RepR, RepR->getDebugLoc());
651 } else {
652 New = DefR->clone();
653 for (const auto &[Idx, Op] : enumerate(NewOps)) {
654 New->setOperand(Idx, Op);
655 }
656 if (auto *Steps = dyn_cast<VPScalarIVStepsRecipe>(New)) {
657 // Skip lane 0: an absent start index is implicitly zero.
658 unsigned KnownLane = Lane.getKnownLane();
659 if (KnownLane != 0)
660 addLaneToStartIndex(Steps, KnownLane, Plan, DefR);
661 }
662 }
663 New->insertBefore(DefR);
664 return New;
665}
666
667/// Convert recipes in region blocks to operate on a single lane 0.
668/// VPReplicateRecipes are converted to single-scalar ones, branch-on-mask is
669/// converted into BranchOnCond, PredInstPhi recipes are replaced by scalar phi
670/// recipes with an additional poison operand, and extracts are created as
671/// needed.
673 VPBlockBase *Entry,
674 ElementCount VF) {
675 VPValue *Idx0 = Plan.getZero(IdxTy);
676 for (VPBlockBase *VPB : vp_depth_first_shallow(Entry)) {
678 assert(
679 !isa<VPWidenPHIRecipe>(&OldR) &&
680 !match(&OldR,
684 "must not contain wide phis, inserts or extracts before conversion");
685
686 VPBuilder Builder(&OldR);
687 DebugLoc OldDL = OldR.getDebugLoc();
688 // For scalar VF, operands are already scalar; no extraction needed.
689 if (!VF.isScalar()) {
690 for (const auto &[I, Op] : enumerate(OldR.operands())) {
691 // Skip operands that don't need extraction: values defined in the
692 // same block (already scalar), or values that are already single
693 // scalars.
694 // TODO: Support isSingleScalar for VPScalarIVStepsRecipe.
695 auto *DefR = Op->getDefiningRecipe();
697 DefR->getParent() == VPB) ||
699 continue;
700
701 // Extract lane zero from values defined outside the region.
702 VPValue *Extract = Builder.createNaryOp(Instruction::ExtractElement,
703 {Op, Idx0}, OldDL);
704 OldR.setOperand(I, Extract);
705 }
706 }
707
708 if (auto *RepR = dyn_cast<VPReplicateRecipe>(&OldR)) {
709 auto *NewR = new VPReplicateRecipe(
710 RepR->getUnderlyingInstr(), RepR->operands(),
711 /* IsSingleScalar=*/true, /*Mask=*/nullptr, *RepR, *RepR, OldDL);
712 NewR->insertBefore(RepR);
713 RepR->replaceAllUsesWith(NewR);
714 RepR->eraseFromParent();
715 } else if (auto *BranchOnMask = dyn_cast<VPBranchOnMaskRecipe>(&OldR)) {
716 Builder.createNaryOp(VPInstruction::BranchOnCond,
717 {BranchOnMask->getOperand(0)}, OldDL);
718 BranchOnMask->eraseFromParent();
719 } else if (auto *PredPhi = dyn_cast<VPPredInstPHIRecipe>(&OldR)) {
720 VPValue *PredOp = PredPhi->getOperand(0);
721 Type *PredTy = PredOp->getScalarType();
723 VPPhi *NewPhi = Builder.createScalarPhi({Poison, PredOp}, OldDL);
724 PredPhi->replaceAllUsesWith(NewPhi);
725 PredPhi->eraseFromParent();
726 } else {
727 // TODO: Support isSingleScalar for VPScalarIVStepsRecipe.
729 (isa<VPInstruction>(OldR) &&
730 vputils::isSingleScalar(OldR.getVPSingleValue()))) &&
731 "unexpected unhandled recipe");
732 }
733 }
734 }
735}
736
737/// Update recipes in the cloned blocks rooted at \p NewEntry to match \p Lane,
738/// using the original blocks rooted at \p OldEntry as reference.
739static void processLaneForReplicateRegion(VPlan &Plan, Type *IdxTy,
740 unsigned Lane, VPBasicBlock *OldEntry,
741 VPBasicBlock *NewEntry) {
742 DenseMap<VPValue *, VPValue *> Old2NewVPValues;
743 VPValue *IdxLane = Plan.getConstantInt(IdxTy, Lane);
744 for (const auto &[OldBB, NewBB] :
746 vp_depth_first_shallow(NewEntry))) {
747 for (auto &&[OldR, NewR] :
749 for (const auto &[OldV, NewV] :
750 zip_equal(OldR.definedValues(), NewR.definedValues()))
751 Old2NewVPValues[OldV] = NewV;
752
753 // Remap operands to use lane-specific values.
754 for (const auto &[I, OldOp] : enumerate(NewR.operands())) {
755 // Use cloned value if operand was defined in the region.
756 if (auto *NewOp = Old2NewVPValues.lookup(OldOp))
757 NewR.setOperand(I, NewOp);
758 }
759
760 if (auto *Steps = dyn_cast<VPScalarIVStepsRecipe>(&NewR)) {
761 addLaneToStartIndex(Steps, Lane, Plan, Steps);
762 } else if (match(&NewR, m_ExtractElement(m_VPValue(), m_VPValue()))) {
763 assert(match(NewR.getOperand(1), m_ZeroInt()) &&
764 "extract indices must be zero");
765 NewR.setOperand(1, IdxLane);
766 } else if (auto *NewPhi = dyn_cast<VPPhi>(&NewR)) {
767 auto *OldPhi = cast<VPPhi>(&OldR);
769 "VPPhis expected to have only first lane used");
770 auto *BVUser = dyn_cast_or_null<VPInstruction>(OldPhi->getSingleUser());
771 if (BVUser && match(BVUser, m_CombineOr(m_BuildVector(),
773 assert(BVUser->getOperand(0) == OldPhi &&
774 "Unexpected first operand of build vector user");
775 BVUser->setOperand(Lane, NewPhi);
776 }
777 }
778 }
779 }
780}
781
782/// Dissolve a single replicate region by replicating its blocks for each lane
783/// of \p VF. The region is disconnected, its blocks are reparented, cloned for
784/// each lane, and reconnected in sequence.
786 VPlan &Plan, Type *IdxTy) {
787 auto *FirstLaneEntry = cast<VPBasicBlock>(Region->getEntry());
788 auto *FirstLaneExiting = cast<VPBasicBlock>(Region->getExiting());
789
790 // Disconnect and dissolve the region.
791 VPBlockBase *Predecessor = Region->getSinglePredecessor();
792 assert(Predecessor && "Replicate region must have a single predecessor");
793 auto *Successor = cast<VPBasicBlock>(Region->getSingleSuccessor());
796
797 VPRegionBlock *ParentRegion = Region->getParent();
798 for (VPBlockBase *VPB : vp_depth_first_shallow(FirstLaneEntry))
799 VPB->setParent(ParentRegion);
800
801 // Process the original blocks for lane 0: converting their recipes to
802 // single-scalar.
803 convertRecipesInRegionBlocksToSingleScalar(Plan, IdxTy, FirstLaneEntry, VF);
804
805 // For scalar VF, just wire the blocks and return; no cloning or packing
806 // needed.
807 if (VF.isScalar()) {
808 VPBlockUtils::connectBlocks(Predecessor, FirstLaneEntry);
809 VPBlockUtils::connectBlocks(FirstLaneExiting, Successor);
810 return;
811 }
812
813 // Create a BuildVector or BuildStructVector in successor block for every
814 // VPPhi in (first lane's) exiting block having vector uses. All their
815 // operands are initialized to poison and will be replaced when processing
816 // each clone, except for the operand of the first lane which set here.
817 // BuildVectors are recorded to be replaced later by chains of insert-element
818 // and widen phi's.
819 unsigned NumLanes = VF.getFixedValue();
820 SmallVector<VPInstruction *> BuildVectors;
821 for (auto &R : FirstLaneExiting->phis()) {
822 auto *Phi = cast<VPPhi>(&R);
824 continue;
825
826 Type *ScalarTy = Phi->getScalarType();
827 bool IsStruct = isa<StructType>(ScalarTy);
829 SmallVector<VPValue *> BVOps(NumLanes, Poison);
830 auto *BV = new VPInstruction(IsStruct ? VPInstruction::BuildStructVector
832 BVOps);
833 if (!IsStruct)
834 BuildVectors.push_back(BV);
835 Phi->replaceAllUsesWith(BV);
836 BV->setOperand(0, Phi);
837 BV->insertBefore(*Successor, Successor->getFirstNonPhi());
838 }
839
840 // Clone converted blocks for remaining lanes and process each in reverse
841 // order, connecting each lane's Exiting block to the subsequent lane's entry.
842 VPBlockBase *NextLaneEntry = Successor;
843 for (int Lane = NumLanes - 1; Lane > 0; --Lane) {
844 const auto &[CurrentLaneEntry, CurrentLaneExiting] =
845 VPBlockUtils::cloneFrom(FirstLaneEntry);
846 for (VPBlockBase *VPB : vp_depth_first_shallow(CurrentLaneEntry))
847 VPB->setParent(ParentRegion);
848 processLaneForReplicateRegion(Plan, IdxTy, Lane,
849 cast<VPBasicBlock>(FirstLaneEntry),
850 cast<VPBasicBlock>(CurrentLaneEntry));
851 VPBlockUtils::connectBlocks(CurrentLaneExiting, NextLaneEntry);
852 NextLaneEntry = CurrentLaneEntry;
853 }
854
855 // Connect Predecessor to FirstLaneEntry, and FirstLaneRegionExit to
856 // NextLaneEntry which is the second lane region entry. The latter is
857 // done last so that earlier clonings from FirstLaneEntry stop at
858 // FirstLaneExiting.
859 VPBlockUtils::connectBlocks(Predecessor, FirstLaneEntry);
860 VPBlockUtils::connectBlocks(FirstLaneExiting, NextLaneEntry);
861
862 // Fold BuildVector fed by scalar phis into VPWidenPHIRecipes with
863 // InsertElement per lane.
864 // TODO: check if this folding should be dropped.
865 for (VPInstruction *BV : BuildVectors) {
866 assert(BV->getNumOperands() == NumLanes &&
867 "BuildVector must have one operand per lane");
868 for (const auto &[Idx, Op] : enumerate(BV->operands())) {
869 auto *ScalarPhi = cast<VPPhi>(Op);
870 auto DL = ScalarPhi->getDebugLoc();
871 auto *PredOp = cast<VPSingleDefRecipe>(ScalarPhi->getOperand(1));
872 VPValue *Poison = ScalarPhi->getOperand(0);
873 VPValue *PrevVal = Idx == 0 ? Poison : BV->getOperand(Idx - 1);
874 auto Builder = VPBuilder::getToInsertAfter(PredOp->getDefiningRecipe());
875 auto *Insert = Builder.createNaryOp(
876 Instruction::InsertElement,
877 {PrevVal, PredOp, Plan.getConstantInt(64, Idx)}, DL);
878 Builder.setInsertPoint(ScalarPhi);
879 auto *NewPhi = Builder.createWidenPhi({PrevVal, Insert}, DL);
880 ScalarPhi->replaceAllUsesWith(NewPhi);
881 ScalarPhi->eraseFromParent();
882 }
883 BV->replaceAllUsesWith(BV->getOperand(NumLanes - 1));
884 BV->eraseFromParent();
885 }
886}
887
888/// Collect and dissolve all replicate regions in the vector loop, replicating
889/// their blocks and recipes for each lane of \p VF.
891 Type *IdxTy) {
892 // Collect all replicate regions before modifying the CFG.
893 SmallVector<VPRegionBlock *> ReplicateRegions;
896 if (Region->isReplicator())
897 ReplicateRegions.push_back(Region);
898 }
899
900 assert((ReplicateRegions.empty() || !VF.isScalable()) &&
901 "cannot replicate across scalable VFs");
902
903 // Dissolve replicate regions by replicating their blocks for each lane.
904 // Traversing regions in reverse ensures that the successor of every region
905 // being processed is a basic-block, rather than another region.
906 for (VPRegionBlock *Region : reverse(ReplicateRegions))
907 dissolveReplicateRegion(Region, VF, Plan, IdxTy);
908
910}
911
913 Type *IdxTy = IntegerType::get(
915
916 if (Plan.hasScalarVFOnly()) {
917 // When Plan is only unrolled by UF, replicating by VF amounts to dissolving
918 // replicate regions.
919 replicateReplicateRegionsByVF(Plan, VF, IdxTy);
920 return;
921 }
922
923 // Visit all VPBBs outside the loop region and directly inside the top-level
924 // loop region.
925 auto VPBBsOutsideLoopRegion = VPBlockUtils::blocksOnly<VPBasicBlock>(
927 auto VPBBsInsideLoopRegion = VPBlockUtils::blocksOnly<VPBasicBlock>(
929 auto VPBBsToUnroll =
930 concat<VPBasicBlock *>(VPBBsOutsideLoopRegion, VPBBsInsideLoopRegion);
931 // A mapping of current VPValue definitions to collections of new VPValues
932 // defined per lane. Serves to hook-up potential users of current VPValue
933 // definition that are replicated-per-VF later.
935 // The removal of current recipes being replaced by new ones needs to be
936 // delayed after Def2LaneDefs is no longer in use.
938 for (VPBasicBlock *VPBB : VPBBsToUnroll) {
939 for (VPRecipeBase &R : make_early_inc_range(*VPBB)) {
942 cast<VPReplicateRecipe>(&R)->isSingleScalar()) ||
943 (isa<VPInstruction>(&R) &&
944 !cast<VPInstruction>(&R)->doesGeneratePerAllLanes() &&
946 continue;
947
948 auto *DefR = cast<VPSingleDefRecipe>(&R);
949 VPBuilder Builder(DefR);
950 if (DefR->getNumUsers() == 0) {
951 // Create single-scalar version of DefR for all lanes.
952 for (unsigned I = 0; I != VF.getKnownMinValue(); ++I)
953 cloneForLane(Plan, Builder, IdxTy, DefR, VPLane(I), Def2LaneDefs);
954 DefR->eraseFromParent();
955 continue;
956 }
957 /// Create single-scalar version of DefR for all lanes.
958 SmallVector<VPValue *> LaneDefs;
959 for (unsigned I = 0; I != VF.getKnownMinValue(); ++I)
960 LaneDefs.push_back(
961 cloneForLane(Plan, Builder, IdxTy, DefR, VPLane(I), Def2LaneDefs));
962
963 Def2LaneDefs[DefR] = LaneDefs;
964 /// Users that only demand the first lane can use the definition for lane
965 /// 0.
966 DefR->replaceUsesWithIf(LaneDefs[0], [DefR](VPUser &U, unsigned) {
967 return U.usesFirstLaneOnly(DefR);
968 });
969
970 // Update each build vector user that currently has DefR as its only
971 // operand, to have all LaneDefs as its operands.
972 for (VPUser *U : to_vector(DefR->users())) {
973 auto *VPI = dyn_cast<VPInstruction>(U);
974 if (!VPI || (VPI->getOpcode() != VPInstruction::BuildVector &&
975 VPI->getOpcode() != VPInstruction::BuildStructVector))
976 continue;
977 assert(VPI->getNumOperands() == 1 &&
978 "Build(Struct)Vector must have a single operand before "
979 "replicating by VF");
980 VPI->setOperand(0, LaneDefs[0]);
981 for (VPValue *LaneDef : drop_begin(LaneDefs))
982 VPI->addOperand(LaneDef);
983 }
984 ToRemove.push_back(DefR);
985 }
986 }
987 for (auto *R : reverse(ToRemove))
988 R->eraseFromParent();
989
990 replicateReplicateRegionsByVF(Plan, VF, IdxTy);
991}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
ReachingDefInfo InstSet & ToRemove
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static bool isCanonical(const MDString *S)
ManagedStatic< HTTPClientCleanup > Cleanup
#define _
static Value * getOpcode(Value &V, Type &Ty, InstrumentationConfig &IConf, InstrumentorIRBuilderTy &IIRB)
#define I(x, y, z)
Definition MD5.cpp:57
#define H(x, y, z)
Definition MD5.cpp:56
MachineInstr unsigned OpIdx
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
This file contains some templates that are useful if you are working with the STL at all.
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:483
This file defines the make_scope_exit function, which executes user-defined cleanup logic at scope ex...
static ConstantInt * getConstantInt(Value *V, const DataLayout &DL)
Extract ConstantInt from value, looking through IntToPtr and PointerNullValue.
This file contains the declarations of different VPlan-related auxiliary helpers.
This file provides utility VPlan to VPlan transformations.
static void addLaneToStartIndex(VPScalarIVStepsRecipe *Steps, unsigned Lane, VPlan &Plan, VPRecipeBase *InsertPt)
Add a lane offset to the start index of Steps.
static void replicateReplicateRegionsByVF(VPlan &Plan, ElementCount VF, Type *IdxTy)
Collect and dissolve all replicate regions in the vector loop, replicating their blocks and recipes f...
static VPValue * cloneForLane(VPlan &Plan, VPBuilder &Builder, Type *IdxTy, VPSingleDefRecipe *DefR, VPLane Lane, const DenseMap< VPValue *, SmallVector< VPValue * > > &Def2LaneDefs)
Create a single-scalar clone of DefR (must be a VPReplicateRecipe, VPInstruction or VPScalarIVStepsRe...
static void addStartIndexForScalarSteps(VPScalarIVStepsRecipe *Steps, unsigned Part, VPlan &Plan)
static void convertRecipesInRegionBlocksToSingleScalar(VPlan &Plan, Type *IdxTy, VPBlockBase *Entry, ElementCount VF)
Convert recipes in region blocks to operate on a single lane 0.
static void dissolveReplicateRegion(VPRegionBlock *Region, ElementCount VF, VPlan &Plan, Type *IdxTy)
Dissolve a single replicate region by replicating its blocks for each lane of VF.
static void processLaneForReplicateRegion(VPlan &Plan, Type *IdxTy, unsigned Lane, VPBasicBlock *OldEntry, VPBasicBlock *NewEntry)
Update recipes in the cloned blocks rooted at NewEntry to match Lane, using the original blocks roote...
static void remapOperands(VPBlockBase *Entry, VPBlockBase *NewEntry, DenseMap< VPValue *, VPValue * > &Old2NewVPValues)
Definition VPlan.cpp:1186
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 LLVMContext & getContext() const
Get the context in which this basic block lives.
A debug info location.
Definition DebugLoc.h:124
static DebugLoc getUnknown()
Definition DebugLoc.h:151
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:252
constexpr bool isScalar() const
Exactly one element.
Definition TypeSize.h:320
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
static GEPNoWrapFlags none()
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:350
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
RegionT * getParent() const
Get the parent of the Region.
Definition RegionInfo.h:362
BlockT * getEntry() const
Get the entry BasicBlock of the Region.
Definition RegionInfo.h:320
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:282
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
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph.
Definition VPlan.h:4399
RecipeListTy::iterator iterator
Instruction iterators...
Definition VPlan.h:4426
iterator_range< iterator > phis()
Returns an iterator range over the PHI-like recipes in the block.
Definition VPlan.h:4487
iterator getFirstNonPhi()
Return the position of the first non-phi node recipe in the block.
Definition VPlan.cpp:266
VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
Definition VPlan.h:94
const VPBasicBlock * getEntryBasicBlock() const
Definition VPlan.cpp:216
void setParent(VPRegionBlock *P)
Definition VPlan.h:197
VPBlockBase * getSingleSuccessor() const
Definition VPlan.h:227
static auto blocksAs(T &&Range)
Return an iterator range over Range with each block cast to BlockTy.
Definition VPlanUtils.h:342
static void connectBlocks(VPBlockBase *From, VPBlockBase *To, unsigned PredIdx=-1u, unsigned SuccIdx=-1u)
Connect VPBlockBases From and To bi-directionally.
Definition VPlanUtils.h:269
static void disconnectBlocks(VPBlockBase *From, VPBlockBase *To)
Disconnect VPBlockBases From and To bi-directionally.
Definition VPlanUtils.h:287
static void insertBlockBefore(VPBlockBase *NewBlock, VPBlockBase *BlockPtr)
Insert disconnected block NewBlock before Blockptr.
Definition VPlanUtils.h:233
static auto blocksOnly(T &&Range)
Return an iterator range over Range which only includes BlockTy blocks.
Definition VPlanUtils.h:323
static std::pair< VPBlockBase *, VPBlockBase * > cloneFrom(VPBlockBase *Entry)
Clone the CFG for all nodes reachable from Entry, including cloning the blocks and their recipes.
Definition VPlan.cpp:688
VPlan-based builder utility analogous to IRBuilder.
static VPBuilder getToInsertAfter(VPRecipeBase *R)
Create a VPBuilder to insert after R.
VPValue * getVPValue(unsigned I)
Returns the VPValue with index I defined by the VPDef.
Definition VPlanValue.h:546
ArrayRef< VPRecipeValue * > definedValues()
Returns an ArrayRef of the values defined by the VPDef.
Definition VPlanValue.h:556
BasicBlock * getIRBasicBlock() const
Definition VPlan.h:4576
Class to record and manage LLVM IR flags.
Definition VPlan.h:694
This is a concrete Recipe that models a single VPlan-level instruction.
Definition VPlan.h:1225
@ WideIVStep
Scale the first operand (vector step) by the second operand (scalar-step).
Definition VPlan.h:1343
@ Unpack
Extracts all lanes from its (non-scalable) vector operand.
Definition VPlan.h:1268
@ ReductionStartVector
Start vector for reductions with 3 operands: the original start value, the identity value for the red...
Definition VPlan.h:1314
@ BuildVector
Creates a fixed-width vector containing all operands.
Definition VPlan.h:1263
@ BuildStructVector
Given operands of (the same) struct type, creates a struct of fixed- width vectors each containing a ...
Definition VPlan.h:1260
@ CanonicalIVIncrementForPart
Definition VPlan.h:1244
In what follows, the term "input IR" refers to code that is fed into the vectorizer whereas the term ...
Kind getKind() const
Returns the Kind of lane offset.
unsigned getKnownLane() const
Returns a compile-time known value for the lane index and asserts if the lane can only be calculated ...
@ ScalableLast
For ScalableLast, Lane is the offset from the start of the last N-element subvector in a scalable vec...
VPRecipeBase is a base class modeling a sequence of one or more output IR instructions.
Definition VPlan.h:402
DebugLoc getDebugLoc() const
Returns the debug location of the recipe.
Definition VPlan.h:555
VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks which form a Single-Entry-S...
Definition VPlan.h:4609
VPRegionBlock * clone() override
Clone all blocks in the single-entry single-exit region of the block and their recipes without updati...
Definition VPlan.cpp:738
const VPBlockBase * getEntry() const
Definition VPlan.h:4653
bool isReplicator() const
An indicator whether this region is to generate multiple replicated instances of output IR correspond...
Definition VPlan.h:4685
Type * getCanonicalIVType() const
Return the type of the canonical IV for loop regions.
Definition VPlan.h:4729
VPReplicateRecipe replicates a given instruction producing multiple scalar copies of the original sca...
Definition VPlan.h:3404
A recipe for handling phi nodes of integer and floating-point inductions, producing their scalar valu...
Definition VPlan.h:4244
Instruction::BinaryOps getInductionOpcode() const
Definition VPlan.h:4315
void setStartIndex(VPValue *StartIndex)
Set or add the StartIndex operand.
Definition VPlan.h:4301
VPValue * getStartIndex() const
Return the StartIndex, or null if known to be zero, valid only after unrolling.
Definition VPlan.h:4296
VPValue * getVFValue() const
Return the number of scalars to produce per unroll part, used to compute StartIndex during unrolling.
Definition VPlan.h:4292
VPSingleDefRecipe is a base class for recipes that model a sequence of one or more output IR that def...
Definition VPlan.h:608
VPSingleDefRecipe * clone() override=0
Clone the current recipe.
This class augments VPValue with operands which provide the inverse def-use edges from VPValue's user...
Definition VPlanValue.h:384
operand_range operands()
Definition VPlanValue.h:457
VPValue * getOperand(unsigned N) const
Definition VPlanValue.h:425
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
void replaceAllUsesWith(VPValue *New)
Definition VPlan.cpp:1481
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition VPlan.h:4757
const DataLayout & getDataLayout() const
Definition VPlan.h:4962
VPBasicBlock * getEntry()
Definition VPlan.h:4853
VPValue * getTripCount() const
The trip count of the original loop.
Definition VPlan.h:4916
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:5030
VPIRValue * getZero(Type *Ty)
Return a VPIRValue wrapping the null value of type Ty.
Definition VPlan.h:5056
LLVM_ABI_FOR_TEST VPRegionBlock * getVectorLoopRegion()
Returns the VPRegionBlock of the vector loop.
Definition VPlan.cpp:1068
VPSymbolicValue & getUF()
Returns the UF of the vector loop region.
Definition VPlan.h:4953
bool hasScalarVFOnly() const
Definition VPlan.h:4998
VPIRBasicBlock * getScalarHeader() const
Return the VPIRBasicBlock wrapping the header of the scalar loop.
Definition VPlan.h:4902
VPSymbolicValue & getVF()
Returns the VF of the vector loop region.
Definition VPlan.h:4949
void setUF(unsigned UF)
Definition VPlan.h:5013
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:5064
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:165
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
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.
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.
IntrinsicID_match m_Intrinsic()
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
VPInstruction_match< VPInstruction::ExtractLastLane, VPInstruction_match< VPInstruction::ExtractLastPart, Op0_t > > m_ExtractLastLaneOfLastPart(const Op0_t &Op0)
VPInstruction_match< VPInstruction::ComputeReductionResult, Op0_t > m_ComputeReductionResult(const Op0_t &Op0)
VPInstruction_match< Instruction::InsertElement, Op0_t, Op1_t, Op2_t > m_InsertElement(const Op0_t &Op0, const Op1_t &Op1, const Op2_t &Op2)
VPInstruction_match< VPInstruction::LastActiveLane, Op0_t > m_LastActiveLane(const Op0_t &Op0)
VPInstruction_match< VPInstruction::ExtractLastActive, Op0_t, Op1_t, Op2_t > m_ExtractLastActive(const Op0_t &Op0, const Op1_t &Op1, const Op2_t &Op2)
VPInstruction_match< Instruction::ExtractElement, Op0_t, Op1_t > m_ExtractElement(const Op0_t &Op0, const Op1_t &Op1)
VPInstruction_match< VPInstruction::BranchOnCount > m_BranchOnCount()
auto m_VPValue()
Match an arbitrary VPValue and ignore it.
VPInstruction_match< VPInstruction::ExtractLastPart, Op0_t > m_ExtractLastPart(const Op0_t &Op0)
VPInstruction_match< VPInstruction::BuildVector > m_BuildVector()
BuildVector is matches only its opcode, w/o matching its operands as the number of operands is not fi...
VPInstruction_match< VPInstruction::ExtractPenultimateElement, Op0_t > m_ExtractPenultimateElement(const Op0_t &Op0)
match_bind< VPInstruction > m_VPInstruction(VPInstruction *&V)
Match a VPInstruction, capturing if we match.
VPInstruction_match< VPInstruction::FirstActiveLane, Op0_t > m_FirstActiveLane(const Op0_t &Op0)
VPInstruction_match< VPInstruction::BranchOnCond > m_BranchOnCond()
VPInstruction_match< VPInstruction::ExtractLane, Op0_t, Op1_t > m_ExtractLane(const Op0_t &Op0, const Op1_t &Op1)
VPInstruction_match< VPInstruction::BuildStructVector > m_BuildStructVector()
BuildStructVector matches only its opcode, w/o matching its operands as the number of operands is not...
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
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 onlyFirstPartUsed(const VPValue *Def)
Returns true if only the first part of Def is used.
bool onlyFirstLaneUsed(const VPValue *Def)
Returns true if only the first lane of Def is used.
bool isUniformAcrossVFsAndUFs(const VPValue *V)
Checks if V is uniform across all VF lanes and UF parts.
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
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
detail::zippy< detail::zip_first, T, U, Args... > zip_equal(T &&t, U &&u, Args &&...args)
zip iterator that assumes that all iteratees have the same length.
Definition STLExtras.h:840
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:2553
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
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:633
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:253
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:288
detail::concat_range< ValueT, RangeTs... > concat(RangeTs &&...Ranges)
Returns a concatenated range across two or more ranges.
Definition STLExtras.h:1151
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
bool isa_and_present(const Y &Val)
isa_and_present<X> - Functionally identical to isa, except that a null value is accepted.
Definition Casting.h:669
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
@ Add
Sum of integers.
DWARFExpression::Operation Op
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
static void unrollByUF(VPlan &Plan, unsigned UF)
Explicitly unroll Plan by UF.
static bool mergeBlocksIntoPredecessors(VPlan &Plan)
Remove redundant VPBasicBlocks by merging them into their single predecessor if the latter has a sing...
static void removeDeadRecipes(VPlan &Plan)
Remove dead recipes from Plan.
static void replicateByVF(VPlan &Plan, ElementCount VF)
Replace replicating VPReplicateRecipe, VPScalarIVStepsRecipe and VPInstruction in Plan with VF single...