xref: /llvm-project/llvm/lib/Transforms/Vectorize/VPlanTransforms.cpp (revision 8df64ed77727ab9b7540819f2fe64379e88a50be)
1 //===-- VPlanTransforms.cpp - Utility VPlan to VPlan 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 a set of utility VPlan to VPlan transformations.
11 ///
12 //===----------------------------------------------------------------------===//
13 
14 #include "VPlanTransforms.h"
15 #include "VPRecipeBuilder.h"
16 #include "VPlan.h"
17 #include "VPlanAnalysis.h"
18 #include "VPlanCFG.h"
19 #include "VPlanDominatorTree.h"
20 #include "VPlanPatternMatch.h"
21 #include "VPlanUtils.h"
22 #include "llvm/ADT/PostOrderIterator.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/SetVector.h"
25 #include "llvm/ADT/TypeSwitch.h"
26 #include "llvm/Analysis/IVDescriptors.h"
27 #include "llvm/Analysis/VectorUtils.h"
28 #include "llvm/IR/Intrinsics.h"
29 #include "llvm/IR/PatternMatch.h"
30 
31 using namespace llvm;
32 
33 void VPlanTransforms::VPInstructionsToVPRecipes(
34     VPlanPtr &Plan,
35     function_ref<const InductionDescriptor *(PHINode *)>
36         GetIntOrFpInductionDescriptor,
37     ScalarEvolution &SE, const TargetLibraryInfo &TLI) {
38 
39   ReversePostOrderTraversal<VPBlockDeepTraversalWrapper<VPBlockBase *>> RPOT(
40       Plan->getVectorLoopRegion());
41   for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(RPOT)) {
42     // Skip blocks outside region
43     if (!VPBB->getParent())
44       break;
45     VPRecipeBase *Term = VPBB->getTerminator();
46     auto EndIter = Term ? Term->getIterator() : VPBB->end();
47     // Introduce each ingredient into VPlan.
48     for (VPRecipeBase &Ingredient :
49          make_early_inc_range(make_range(VPBB->begin(), EndIter))) {
50 
51       VPValue *VPV = Ingredient.getVPSingleValue();
52       Instruction *Inst = cast<Instruction>(VPV->getUnderlyingValue());
53 
54       VPRecipeBase *NewRecipe = nullptr;
55       if (auto *VPPhi = dyn_cast<VPWidenPHIRecipe>(&Ingredient)) {
56         auto *Phi = cast<PHINode>(VPPhi->getUnderlyingValue());
57         const auto *II = GetIntOrFpInductionDescriptor(Phi);
58         if (!II)
59           continue;
60 
61         VPValue *Start = Plan->getOrAddLiveIn(II->getStartValue());
62         VPValue *Step =
63             vputils::getOrCreateVPValueForSCEVExpr(*Plan, II->getStep(), SE);
64         NewRecipe = new VPWidenIntOrFpInductionRecipe(
65             Phi, Start, Step, &Plan->getVF(), *II, Ingredient.getDebugLoc());
66       } else {
67         assert(isa<VPInstruction>(&Ingredient) &&
68                "only VPInstructions expected here");
69         assert(!isa<PHINode>(Inst) && "phis should be handled above");
70         // Create VPWidenMemoryRecipe for loads and stores.
71         if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
72           NewRecipe = new VPWidenLoadRecipe(
73               *Load, Ingredient.getOperand(0), nullptr /*Mask*/,
74               false /*Consecutive*/, false /*Reverse*/,
75               Ingredient.getDebugLoc());
76         } else if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) {
77           NewRecipe = new VPWidenStoreRecipe(
78               *Store, Ingredient.getOperand(1), Ingredient.getOperand(0),
79               nullptr /*Mask*/, false /*Consecutive*/, false /*Reverse*/,
80               Ingredient.getDebugLoc());
81         } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Inst)) {
82           NewRecipe = new VPWidenGEPRecipe(GEP, Ingredient.operands());
83         } else if (CallInst *CI = dyn_cast<CallInst>(Inst)) {
84           NewRecipe = new VPWidenIntrinsicRecipe(
85               *CI, getVectorIntrinsicIDForCall(CI, &TLI),
86               {Ingredient.op_begin(), Ingredient.op_end() - 1}, CI->getType(),
87               CI->getDebugLoc());
88         } else if (SelectInst *SI = dyn_cast<SelectInst>(Inst)) {
89           NewRecipe = new VPWidenSelectRecipe(*SI, Ingredient.operands());
90         } else if (auto *CI = dyn_cast<CastInst>(Inst)) {
91           NewRecipe = new VPWidenCastRecipe(
92               CI->getOpcode(), Ingredient.getOperand(0), CI->getType(), *CI);
93         } else {
94           NewRecipe = new VPWidenRecipe(*Inst, Ingredient.operands());
95         }
96       }
97 
98       NewRecipe->insertBefore(&Ingredient);
99       if (NewRecipe->getNumDefinedValues() == 1)
100         VPV->replaceAllUsesWith(NewRecipe->getVPSingleValue());
101       else
102         assert(NewRecipe->getNumDefinedValues() == 0 &&
103                "Only recpies with zero or one defined values expected");
104       Ingredient.eraseFromParent();
105     }
106   }
107 }
108 
109 static bool sinkScalarOperands(VPlan &Plan) {
110   auto Iter = vp_depth_first_deep(Plan.getEntry());
111   bool Changed = false;
112   // First, collect the operands of all recipes in replicate blocks as seeds for
113   // sinking.
114   SetVector<std::pair<VPBasicBlock *, VPSingleDefRecipe *>> WorkList;
115   for (VPRegionBlock *VPR : VPBlockUtils::blocksOnly<VPRegionBlock>(Iter)) {
116     VPBasicBlock *EntryVPBB = VPR->getEntryBasicBlock();
117     if (!VPR->isReplicator() || EntryVPBB->getSuccessors().size() != 2)
118       continue;
119     VPBasicBlock *VPBB = dyn_cast<VPBasicBlock>(EntryVPBB->getSuccessors()[0]);
120     if (!VPBB || VPBB->getSingleSuccessor() != VPR->getExitingBasicBlock())
121       continue;
122     for (auto &Recipe : *VPBB) {
123       for (VPValue *Op : Recipe.operands())
124         if (auto *Def =
125                 dyn_cast_or_null<VPSingleDefRecipe>(Op->getDefiningRecipe()))
126           WorkList.insert(std::make_pair(VPBB, Def));
127     }
128   }
129 
130   bool ScalarVFOnly = Plan.hasScalarVFOnly();
131   // Try to sink each replicate or scalar IV steps recipe in the worklist.
132   for (unsigned I = 0; I != WorkList.size(); ++I) {
133     VPBasicBlock *SinkTo;
134     VPSingleDefRecipe *SinkCandidate;
135     std::tie(SinkTo, SinkCandidate) = WorkList[I];
136     if (SinkCandidate->getParent() == SinkTo ||
137         SinkCandidate->mayHaveSideEffects() ||
138         SinkCandidate->mayReadOrWriteMemory())
139       continue;
140     if (auto *RepR = dyn_cast<VPReplicateRecipe>(SinkCandidate)) {
141       if (!ScalarVFOnly && RepR->isUniform())
142         continue;
143     } else if (!isa<VPScalarIVStepsRecipe>(SinkCandidate))
144       continue;
145 
146     bool NeedsDuplicating = false;
147     // All recipe users of the sink candidate must be in the same block SinkTo
148     // or all users outside of SinkTo must be uniform-after-vectorization (
149     // i.e., only first lane is used) . In the latter case, we need to duplicate
150     // SinkCandidate.
151     auto CanSinkWithUser = [SinkTo, &NeedsDuplicating,
152                             SinkCandidate](VPUser *U) {
153       auto *UI = cast<VPRecipeBase>(U);
154       if (UI->getParent() == SinkTo)
155         return true;
156       NeedsDuplicating = UI->onlyFirstLaneUsed(SinkCandidate);
157       // We only know how to duplicate VPRecipeRecipes for now.
158       return NeedsDuplicating && isa<VPReplicateRecipe>(SinkCandidate);
159     };
160     if (!all_of(SinkCandidate->users(), CanSinkWithUser))
161       continue;
162 
163     if (NeedsDuplicating) {
164       if (ScalarVFOnly)
165         continue;
166       Instruction *I = SinkCandidate->getUnderlyingInstr();
167       auto *Clone = new VPReplicateRecipe(I, SinkCandidate->operands(), true);
168       // TODO: add ".cloned" suffix to name of Clone's VPValue.
169 
170       Clone->insertBefore(SinkCandidate);
171       SinkCandidate->replaceUsesWithIf(Clone, [SinkTo](VPUser &U, unsigned) {
172         return cast<VPRecipeBase>(&U)->getParent() != SinkTo;
173       });
174     }
175     SinkCandidate->moveBefore(*SinkTo, SinkTo->getFirstNonPhi());
176     for (VPValue *Op : SinkCandidate->operands())
177       if (auto *Def =
178               dyn_cast_or_null<VPSingleDefRecipe>(Op->getDefiningRecipe()))
179         WorkList.insert(std::make_pair(SinkTo, Def));
180     Changed = true;
181   }
182   return Changed;
183 }
184 
185 /// If \p R is a region with a VPBranchOnMaskRecipe in the entry block, return
186 /// the mask.
187 VPValue *getPredicatedMask(VPRegionBlock *R) {
188   auto *EntryBB = dyn_cast<VPBasicBlock>(R->getEntry());
189   if (!EntryBB || EntryBB->size() != 1 ||
190       !isa<VPBranchOnMaskRecipe>(EntryBB->begin()))
191     return nullptr;
192 
193   return cast<VPBranchOnMaskRecipe>(&*EntryBB->begin())->getOperand(0);
194 }
195 
196 /// If \p R is a triangle region, return the 'then' block of the triangle.
197 static VPBasicBlock *getPredicatedThenBlock(VPRegionBlock *R) {
198   auto *EntryBB = cast<VPBasicBlock>(R->getEntry());
199   if (EntryBB->getNumSuccessors() != 2)
200     return nullptr;
201 
202   auto *Succ0 = dyn_cast<VPBasicBlock>(EntryBB->getSuccessors()[0]);
203   auto *Succ1 = dyn_cast<VPBasicBlock>(EntryBB->getSuccessors()[1]);
204   if (!Succ0 || !Succ1)
205     return nullptr;
206 
207   if (Succ0->getNumSuccessors() + Succ1->getNumSuccessors() != 1)
208     return nullptr;
209   if (Succ0->getSingleSuccessor() == Succ1)
210     return Succ0;
211   if (Succ1->getSingleSuccessor() == Succ0)
212     return Succ1;
213   return nullptr;
214 }
215 
216 // Merge replicate regions in their successor region, if a replicate region
217 // is connected to a successor replicate region with the same predicate by a
218 // single, empty VPBasicBlock.
219 static bool mergeReplicateRegionsIntoSuccessors(VPlan &Plan) {
220   SmallPtrSet<VPRegionBlock *, 4> TransformedRegions;
221 
222   // Collect replicate regions followed by an empty block, followed by another
223   // replicate region with matching masks to process front. This is to avoid
224   // iterator invalidation issues while merging regions.
225   SmallVector<VPRegionBlock *, 8> WorkList;
226   for (VPRegionBlock *Region1 : VPBlockUtils::blocksOnly<VPRegionBlock>(
227            vp_depth_first_deep(Plan.getEntry()))) {
228     if (!Region1->isReplicator())
229       continue;
230     auto *MiddleBasicBlock =
231         dyn_cast_or_null<VPBasicBlock>(Region1->getSingleSuccessor());
232     if (!MiddleBasicBlock || !MiddleBasicBlock->empty())
233       continue;
234 
235     auto *Region2 =
236         dyn_cast_or_null<VPRegionBlock>(MiddleBasicBlock->getSingleSuccessor());
237     if (!Region2 || !Region2->isReplicator())
238       continue;
239 
240     VPValue *Mask1 = getPredicatedMask(Region1);
241     VPValue *Mask2 = getPredicatedMask(Region2);
242     if (!Mask1 || Mask1 != Mask2)
243       continue;
244 
245     assert(Mask1 && Mask2 && "both region must have conditions");
246     WorkList.push_back(Region1);
247   }
248 
249   // Move recipes from Region1 to its successor region, if both are triangles.
250   for (VPRegionBlock *Region1 : WorkList) {
251     if (TransformedRegions.contains(Region1))
252       continue;
253     auto *MiddleBasicBlock = cast<VPBasicBlock>(Region1->getSingleSuccessor());
254     auto *Region2 = cast<VPRegionBlock>(MiddleBasicBlock->getSingleSuccessor());
255 
256     VPBasicBlock *Then1 = getPredicatedThenBlock(Region1);
257     VPBasicBlock *Then2 = getPredicatedThenBlock(Region2);
258     if (!Then1 || !Then2)
259       continue;
260 
261     // Note: No fusion-preventing memory dependencies are expected in either
262     // region. Such dependencies should be rejected during earlier dependence
263     // checks, which guarantee accesses can be re-ordered for vectorization.
264     //
265     // Move recipes to the successor region.
266     for (VPRecipeBase &ToMove : make_early_inc_range(reverse(*Then1)))
267       ToMove.moveBefore(*Then2, Then2->getFirstNonPhi());
268 
269     auto *Merge1 = cast<VPBasicBlock>(Then1->getSingleSuccessor());
270     auto *Merge2 = cast<VPBasicBlock>(Then2->getSingleSuccessor());
271 
272     // Move VPPredInstPHIRecipes from the merge block to the successor region's
273     // merge block. Update all users inside the successor region to use the
274     // original values.
275     for (VPRecipeBase &Phi1ToMove : make_early_inc_range(reverse(*Merge1))) {
276       VPValue *PredInst1 =
277           cast<VPPredInstPHIRecipe>(&Phi1ToMove)->getOperand(0);
278       VPValue *Phi1ToMoveV = Phi1ToMove.getVPSingleValue();
279       Phi1ToMoveV->replaceUsesWithIf(PredInst1, [Then2](VPUser &U, unsigned) {
280         return cast<VPRecipeBase>(&U)->getParent() == Then2;
281       });
282 
283       // Remove phi recipes that are unused after merging the regions.
284       if (Phi1ToMove.getVPSingleValue()->getNumUsers() == 0) {
285         Phi1ToMove.eraseFromParent();
286         continue;
287       }
288       Phi1ToMove.moveBefore(*Merge2, Merge2->begin());
289     }
290 
291     // Finally, remove the first region.
292     for (VPBlockBase *Pred : make_early_inc_range(Region1->getPredecessors())) {
293       VPBlockUtils::disconnectBlocks(Pred, Region1);
294       VPBlockUtils::connectBlocks(Pred, MiddleBasicBlock);
295     }
296     VPBlockUtils::disconnectBlocks(Region1, MiddleBasicBlock);
297     TransformedRegions.insert(Region1);
298   }
299 
300   return !TransformedRegions.empty();
301 }
302 
303 static VPRegionBlock *createReplicateRegion(VPReplicateRecipe *PredRecipe,
304                                             VPlan &Plan) {
305   Instruction *Instr = PredRecipe->getUnderlyingInstr();
306   // Build the triangular if-then region.
307   std::string RegionName = (Twine("pred.") + Instr->getOpcodeName()).str();
308   assert(Instr->getParent() && "Predicated instruction not in any basic block");
309   auto *BlockInMask = PredRecipe->getMask();
310   auto *BOMRecipe = new VPBranchOnMaskRecipe(BlockInMask);
311   auto *Entry =
312       Plan.createVPBasicBlock(Twine(RegionName) + ".entry", BOMRecipe);
313 
314   // Replace predicated replicate recipe with a replicate recipe without a
315   // mask but in the replicate region.
316   auto *RecipeWithoutMask = new VPReplicateRecipe(
317       PredRecipe->getUnderlyingInstr(),
318       make_range(PredRecipe->op_begin(), std::prev(PredRecipe->op_end())),
319       PredRecipe->isUniform());
320   auto *Pred =
321       Plan.createVPBasicBlock(Twine(RegionName) + ".if", RecipeWithoutMask);
322 
323   VPPredInstPHIRecipe *PHIRecipe = nullptr;
324   if (PredRecipe->getNumUsers() != 0) {
325     PHIRecipe = new VPPredInstPHIRecipe(RecipeWithoutMask,
326                                         RecipeWithoutMask->getDebugLoc());
327     PredRecipe->replaceAllUsesWith(PHIRecipe);
328     PHIRecipe->setOperand(0, RecipeWithoutMask);
329   }
330   PredRecipe->eraseFromParent();
331   auto *Exiting =
332       Plan.createVPBasicBlock(Twine(RegionName) + ".continue", PHIRecipe);
333   VPRegionBlock *Region =
334       Plan.createVPRegionBlock(Entry, Exiting, RegionName, true);
335 
336   // Note: first set Entry as region entry and then connect successors starting
337   // from it in order, to propagate the "parent" of each VPBasicBlock.
338   VPBlockUtils::insertTwoBlocksAfter(Pred, Exiting, Entry);
339   VPBlockUtils::connectBlocks(Pred, Exiting);
340 
341   return Region;
342 }
343 
344 static void addReplicateRegions(VPlan &Plan) {
345   SmallVector<VPReplicateRecipe *> WorkList;
346   for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(
347            vp_depth_first_deep(Plan.getEntry()))) {
348     for (VPRecipeBase &R : *VPBB)
349       if (auto *RepR = dyn_cast<VPReplicateRecipe>(&R)) {
350         if (RepR->isPredicated())
351           WorkList.push_back(RepR);
352       }
353   }
354 
355   unsigned BBNum = 0;
356   for (VPReplicateRecipe *RepR : WorkList) {
357     VPBasicBlock *CurrentBlock = RepR->getParent();
358     VPBasicBlock *SplitBlock = CurrentBlock->splitAt(RepR->getIterator());
359 
360     BasicBlock *OrigBB = RepR->getUnderlyingInstr()->getParent();
361     SplitBlock->setName(
362         OrigBB->hasName() ? OrigBB->getName() + "." + Twine(BBNum++) : "");
363     // Record predicated instructions for above packing optimizations.
364     VPBlockBase *Region = createReplicateRegion(RepR, Plan);
365     Region->setParent(CurrentBlock->getParent());
366     VPBlockUtils::insertOnEdge(CurrentBlock, SplitBlock, Region);
367   }
368 }
369 
370 /// Remove redundant VPBasicBlocks by merging them into their predecessor if
371 /// the predecessor has a single successor.
372 static bool mergeBlocksIntoPredecessors(VPlan &Plan) {
373   SmallVector<VPBasicBlock *> WorkList;
374   for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(
375            vp_depth_first_deep(Plan.getEntry()))) {
376     // Don't fold the blocks in the skeleton of the Plan into their single
377     // predecessors for now.
378     // TODO: Remove restriction once more of the skeleton is modeled in VPlan.
379     if (!VPBB->getParent())
380       continue;
381     auto *PredVPBB =
382         dyn_cast_or_null<VPBasicBlock>(VPBB->getSinglePredecessor());
383     if (!PredVPBB || PredVPBB->getNumSuccessors() != 1 ||
384         isa<VPIRBasicBlock>(PredVPBB))
385       continue;
386     WorkList.push_back(VPBB);
387   }
388 
389   for (VPBasicBlock *VPBB : WorkList) {
390     VPBasicBlock *PredVPBB = cast<VPBasicBlock>(VPBB->getSinglePredecessor());
391     for (VPRecipeBase &R : make_early_inc_range(*VPBB))
392       R.moveBefore(*PredVPBB, PredVPBB->end());
393     VPBlockUtils::disconnectBlocks(PredVPBB, VPBB);
394     auto *ParentRegion = cast_or_null<VPRegionBlock>(VPBB->getParent());
395     if (ParentRegion && ParentRegion->getExiting() == VPBB)
396       ParentRegion->setExiting(PredVPBB);
397     for (auto *Succ : to_vector(VPBB->successors())) {
398       VPBlockUtils::disconnectBlocks(VPBB, Succ);
399       VPBlockUtils::connectBlocks(PredVPBB, Succ);
400     }
401     // VPBB is now dead and will be cleaned up when the plan gets destroyed.
402   }
403   return !WorkList.empty();
404 }
405 
406 void VPlanTransforms::createAndOptimizeReplicateRegions(VPlan &Plan) {
407   // Convert masked VPReplicateRecipes to if-then region blocks.
408   addReplicateRegions(Plan);
409 
410   bool ShouldSimplify = true;
411   while (ShouldSimplify) {
412     ShouldSimplify = sinkScalarOperands(Plan);
413     ShouldSimplify |= mergeReplicateRegionsIntoSuccessors(Plan);
414     ShouldSimplify |= mergeBlocksIntoPredecessors(Plan);
415   }
416 }
417 
418 /// Remove redundant casts of inductions.
419 ///
420 /// Such redundant casts are casts of induction variables that can be ignored,
421 /// because we already proved that the casted phi is equal to the uncasted phi
422 /// in the vectorized loop. There is no need to vectorize the cast - the same
423 /// value can be used for both the phi and casts in the vector loop.
424 static void removeRedundantInductionCasts(VPlan &Plan) {
425   for (auto &Phi : Plan.getVectorLoopRegion()->getEntryBasicBlock()->phis()) {
426     auto *IV = dyn_cast<VPWidenIntOrFpInductionRecipe>(&Phi);
427     if (!IV || IV->getTruncInst())
428       continue;
429 
430     // A sequence of IR Casts has potentially been recorded for IV, which
431     // *must be bypassed* when the IV is vectorized, because the vectorized IV
432     // will produce the desired casted value. This sequence forms a def-use
433     // chain and is provided in reverse order, ending with the cast that uses
434     // the IV phi. Search for the recipe of the last cast in the chain and
435     // replace it with the original IV. Note that only the final cast is
436     // expected to have users outside the cast-chain and the dead casts left
437     // over will be cleaned up later.
438     auto &Casts = IV->getInductionDescriptor().getCastInsts();
439     VPValue *FindMyCast = IV;
440     for (Instruction *IRCast : reverse(Casts)) {
441       VPSingleDefRecipe *FoundUserCast = nullptr;
442       for (auto *U : FindMyCast->users()) {
443         auto *UserCast = dyn_cast<VPSingleDefRecipe>(U);
444         if (UserCast && UserCast->getUnderlyingValue() == IRCast) {
445           FoundUserCast = UserCast;
446           break;
447         }
448       }
449       FindMyCast = FoundUserCast;
450     }
451     FindMyCast->replaceAllUsesWith(IV);
452   }
453 }
454 
455 /// Try to replace VPWidenCanonicalIVRecipes with a widened canonical IV
456 /// recipe, if it exists.
457 static void removeRedundantCanonicalIVs(VPlan &Plan) {
458   VPCanonicalIVPHIRecipe *CanonicalIV = Plan.getCanonicalIV();
459   VPWidenCanonicalIVRecipe *WidenNewIV = nullptr;
460   for (VPUser *U : CanonicalIV->users()) {
461     WidenNewIV = dyn_cast<VPWidenCanonicalIVRecipe>(U);
462     if (WidenNewIV)
463       break;
464   }
465 
466   if (!WidenNewIV)
467     return;
468 
469   VPBasicBlock *HeaderVPBB = Plan.getVectorLoopRegion()->getEntryBasicBlock();
470   for (VPRecipeBase &Phi : HeaderVPBB->phis()) {
471     auto *WidenOriginalIV = dyn_cast<VPWidenIntOrFpInductionRecipe>(&Phi);
472 
473     if (!WidenOriginalIV || !WidenOriginalIV->isCanonical())
474       continue;
475 
476     // Replace WidenNewIV with WidenOriginalIV if WidenOriginalIV provides
477     // everything WidenNewIV's users need. That is, WidenOriginalIV will
478     // generate a vector phi or all users of WidenNewIV demand the first lane
479     // only.
480     if (any_of(WidenOriginalIV->users(),
481                [WidenOriginalIV](VPUser *U) {
482                  return !U->usesScalars(WidenOriginalIV);
483                }) ||
484         vputils::onlyFirstLaneUsed(WidenNewIV)) {
485       WidenNewIV->replaceAllUsesWith(WidenOriginalIV);
486       WidenNewIV->eraseFromParent();
487       return;
488     }
489   }
490 }
491 
492 /// Returns true if \p R is dead and can be removed.
493 static bool isDeadRecipe(VPRecipeBase &R) {
494   using namespace llvm::PatternMatch;
495   // Do remove conditional assume instructions as their conditions may be
496   // flattened.
497   auto *RepR = dyn_cast<VPReplicateRecipe>(&R);
498   bool IsConditionalAssume =
499       RepR && RepR->isPredicated() &&
500       match(RepR->getUnderlyingInstr(), m_Intrinsic<Intrinsic::assume>());
501   if (IsConditionalAssume)
502     return true;
503 
504   if (R.mayHaveSideEffects())
505     return false;
506 
507   // Recipe is dead if no user keeps the recipe alive.
508   return all_of(R.definedValues(),
509                 [](VPValue *V) { return V->getNumUsers() == 0; });
510 }
511 
512 void VPlanTransforms::removeDeadRecipes(VPlan &Plan) {
513   ReversePostOrderTraversal<VPBlockDeepTraversalWrapper<VPBlockBase *>> RPOT(
514       Plan.getEntry());
515 
516   for (VPBasicBlock *VPBB : reverse(VPBlockUtils::blocksOnly<VPBasicBlock>(RPOT))) {
517     // The recipes in the block are processed in reverse order, to catch chains
518     // of dead recipes.
519     for (VPRecipeBase &R : make_early_inc_range(reverse(*VPBB))) {
520       if (isDeadRecipe(R))
521         R.eraseFromParent();
522     }
523   }
524 }
525 
526 static VPScalarIVStepsRecipe *
527 createScalarIVSteps(VPlan &Plan, InductionDescriptor::InductionKind Kind,
528                     Instruction::BinaryOps InductionOpcode,
529                     FPMathOperator *FPBinOp, Instruction *TruncI,
530                     VPValue *StartV, VPValue *Step, DebugLoc DL,
531                     VPBuilder &Builder) {
532   VPBasicBlock *HeaderVPBB = Plan.getVectorLoopRegion()->getEntryBasicBlock();
533   VPCanonicalIVPHIRecipe *CanonicalIV = Plan.getCanonicalIV();
534   VPSingleDefRecipe *BaseIV = Builder.createDerivedIV(
535       Kind, FPBinOp, StartV, CanonicalIV, Step, "offset.idx");
536 
537   // Truncate base induction if needed.
538   Type *CanonicalIVType = CanonicalIV->getScalarType();
539   VPTypeAnalysis TypeInfo(CanonicalIVType);
540   Type *ResultTy = TypeInfo.inferScalarType(BaseIV);
541   if (TruncI) {
542     Type *TruncTy = TruncI->getType();
543     assert(ResultTy->getScalarSizeInBits() > TruncTy->getScalarSizeInBits() &&
544            "Not truncating.");
545     assert(ResultTy->isIntegerTy() && "Truncation requires an integer type");
546     BaseIV = Builder.createScalarCast(Instruction::Trunc, BaseIV, TruncTy, DL);
547     ResultTy = TruncTy;
548   }
549 
550   // Truncate step if needed.
551   Type *StepTy = TypeInfo.inferScalarType(Step);
552   if (ResultTy != StepTy) {
553     assert(StepTy->getScalarSizeInBits() > ResultTy->getScalarSizeInBits() &&
554            "Not truncating.");
555     assert(StepTy->isIntegerTy() && "Truncation requires an integer type");
556     auto *VecPreheader =
557         cast<VPBasicBlock>(HeaderVPBB->getSingleHierarchicalPredecessor());
558     VPBuilder::InsertPointGuard Guard(Builder);
559     Builder.setInsertPoint(VecPreheader);
560     Step = Builder.createScalarCast(Instruction::Trunc, Step, ResultTy, DL);
561   }
562   return Builder.createScalarIVSteps(InductionOpcode, FPBinOp, BaseIV, Step);
563 }
564 
565 static SmallVector<VPUser *> collectUsersRecursively(VPValue *V) {
566   SetVector<VPUser *> Users(V->user_begin(), V->user_end());
567   for (unsigned I = 0; I != Users.size(); ++I) {
568     VPRecipeBase *Cur = cast<VPRecipeBase>(Users[I]);
569     if (isa<VPHeaderPHIRecipe>(Cur))
570       continue;
571     for (VPValue *V : Cur->definedValues())
572       Users.insert(V->user_begin(), V->user_end());
573   }
574   return Users.takeVector();
575 }
576 
577 /// Legalize VPWidenPointerInductionRecipe, by replacing it with a PtrAdd
578 /// (IndStart, ScalarIVSteps (0, Step)) if only its scalar values are used, as
579 /// VPWidenPointerInductionRecipe will generate vectors only. If some users
580 /// require vectors while other require scalars, the scalar uses need to extract
581 /// the scalars from the generated vectors (Note that this is different to how
582 /// int/fp inductions are handled). Legalize extract-from-ends using uniform
583 /// VPReplicateRecipe of wide inductions to use regular VPReplicateRecipe, so
584 /// the correct end value is available. Also optimize
585 /// VPWidenIntOrFpInductionRecipe, if any of its users needs scalar values, by
586 /// providing them scalar steps built on the canonical scalar IV and update the
587 /// original IV's users. This is an optional optimization to reduce the needs of
588 /// vector extracts.
589 static void legalizeAndOptimizeInductions(VPlan &Plan) {
590   using namespace llvm::VPlanPatternMatch;
591   VPBasicBlock *HeaderVPBB = Plan.getVectorLoopRegion()->getEntryBasicBlock();
592   bool HasOnlyVectorVFs = !Plan.hasVF(ElementCount::getFixed(1));
593   VPBuilder Builder(HeaderVPBB, HeaderVPBB->getFirstNonPhi());
594   for (VPRecipeBase &Phi : HeaderVPBB->phis()) {
595     auto *PhiR = dyn_cast<VPWidenInductionRecipe>(&Phi);
596     if (!PhiR)
597       continue;
598 
599     // Try to narrow wide and replicating recipes to uniform recipes, based on
600     // VPlan analysis.
601     // TODO: Apply to all recipes in the future, to replace legacy uniformity
602     // analysis.
603     auto Users = collectUsersRecursively(PhiR);
604     for (VPUser *U : reverse(Users)) {
605       auto *Def = dyn_cast<VPSingleDefRecipe>(U);
606       auto *RepR = dyn_cast<VPReplicateRecipe>(U);
607       // Skip recipes that shouldn't be narrowed.
608       if (!Def || !isa<VPReplicateRecipe, VPWidenRecipe>(Def) ||
609           Def->getNumUsers() == 0 || !Def->getUnderlyingValue() ||
610           (RepR && (RepR->isUniform() || RepR->isPredicated())))
611         continue;
612 
613       // Skip recipes that may have other lanes than their first used.
614       if (!vputils::isUniformAfterVectorization(Def) &&
615           !vputils::onlyFirstLaneUsed(Def))
616         continue;
617 
618       auto *Clone = new VPReplicateRecipe(Def->getUnderlyingInstr(),
619                                           Def->operands(), /*IsUniform*/ true);
620       Clone->insertAfter(Def);
621       Def->replaceAllUsesWith(Clone);
622     }
623 
624     // Replace wide pointer inductions which have only their scalars used by
625     // PtrAdd(IndStart, ScalarIVSteps (0, Step)).
626     if (auto *PtrIV = dyn_cast<VPWidenPointerInductionRecipe>(&Phi)) {
627       if (!PtrIV->onlyScalarsGenerated(Plan.hasScalableVF()))
628         continue;
629 
630       const InductionDescriptor &ID = PtrIV->getInductionDescriptor();
631       VPValue *StartV =
632           Plan.getOrAddLiveIn(ConstantInt::get(ID.getStep()->getType(), 0));
633       VPValue *StepV = PtrIV->getOperand(1);
634       VPScalarIVStepsRecipe *Steps = createScalarIVSteps(
635           Plan, InductionDescriptor::IK_IntInduction, Instruction::Add, nullptr,
636           nullptr, StartV, StepV, PtrIV->getDebugLoc(), Builder);
637 
638       VPValue *PtrAdd = Builder.createPtrAdd(PtrIV->getStartValue(), Steps,
639                                              PtrIV->getDebugLoc(), "next.gep");
640 
641       PtrIV->replaceAllUsesWith(PtrAdd);
642       continue;
643     }
644 
645     // Replace widened induction with scalar steps for users that only use
646     // scalars.
647     auto *WideIV = cast<VPWidenIntOrFpInductionRecipe>(&Phi);
648     if (HasOnlyVectorVFs && none_of(WideIV->users(), [WideIV](VPUser *U) {
649           return U->usesScalars(WideIV);
650         }))
651       continue;
652 
653     const InductionDescriptor &ID = WideIV->getInductionDescriptor();
654     VPScalarIVStepsRecipe *Steps = createScalarIVSteps(
655         Plan, ID.getKind(), ID.getInductionOpcode(),
656         dyn_cast_or_null<FPMathOperator>(ID.getInductionBinOp()),
657         WideIV->getTruncInst(), WideIV->getStartValue(), WideIV->getStepValue(),
658         WideIV->getDebugLoc(), Builder);
659 
660     // Update scalar users of IV to use Step instead.
661     if (!HasOnlyVectorVFs)
662       WideIV->replaceAllUsesWith(Steps);
663     else
664       WideIV->replaceUsesWithIf(Steps, [WideIV](VPUser &U, unsigned) {
665         return U.usesScalars(WideIV);
666       });
667   }
668 }
669 
670 /// Remove redundant EpxandSCEVRecipes in \p Plan's entry block by replacing
671 /// them with already existing recipes expanding the same SCEV expression.
672 static void removeRedundantExpandSCEVRecipes(VPlan &Plan) {
673   DenseMap<const SCEV *, VPValue *> SCEV2VPV;
674 
675   for (VPRecipeBase &R :
676        make_early_inc_range(*Plan.getEntry()->getEntryBasicBlock())) {
677     auto *ExpR = dyn_cast<VPExpandSCEVRecipe>(&R);
678     if (!ExpR)
679       continue;
680 
681     auto I = SCEV2VPV.insert({ExpR->getSCEV(), ExpR});
682     if (I.second)
683       continue;
684     ExpR->replaceAllUsesWith(I.first->second);
685     ExpR->eraseFromParent();
686   }
687 }
688 
689 static void recursivelyDeleteDeadRecipes(VPValue *V) {
690   SmallVector<VPValue *> WorkList;
691   SmallPtrSet<VPValue *, 8> Seen;
692   WorkList.push_back(V);
693 
694   while (!WorkList.empty()) {
695     VPValue *Cur = WorkList.pop_back_val();
696     if (!Seen.insert(Cur).second)
697       continue;
698     VPRecipeBase *R = Cur->getDefiningRecipe();
699     if (!R)
700       continue;
701     if (!isDeadRecipe(*R))
702       continue;
703     WorkList.append(R->op_begin(), R->op_end());
704     R->eraseFromParent();
705   }
706 }
707 
708 /// Try to simplify recipe \p R.
709 static void simplifyRecipe(VPRecipeBase &R, VPTypeAnalysis &TypeInfo) {
710   using namespace llvm::VPlanPatternMatch;
711 
712   if (auto *Blend = dyn_cast<VPBlendRecipe>(&R)) {
713     // Try to remove redundant blend recipes.
714     SmallPtrSet<VPValue *, 4> UniqueValues;
715     if (Blend->isNormalized() || !match(Blend->getMask(0), m_False()))
716       UniqueValues.insert(Blend->getIncomingValue(0));
717     for (unsigned I = 1; I != Blend->getNumIncomingValues(); ++I)
718       if (!match(Blend->getMask(I), m_False()))
719         UniqueValues.insert(Blend->getIncomingValue(I));
720 
721     if (UniqueValues.size() == 1) {
722       Blend->replaceAllUsesWith(*UniqueValues.begin());
723       Blend->eraseFromParent();
724       return;
725     }
726 
727     if (Blend->isNormalized())
728       return;
729 
730     // Normalize the blend so its first incoming value is used as the initial
731     // value with the others blended into it.
732 
733     unsigned StartIndex = 0;
734     for (unsigned I = 0; I != Blend->getNumIncomingValues(); ++I) {
735       // If a value's mask is used only by the blend then is can be deadcoded.
736       // TODO: Find the most expensive mask that can be deadcoded, or a mask
737       // that's used by multiple blends where it can be removed from them all.
738       VPValue *Mask = Blend->getMask(I);
739       if (Mask->getNumUsers() == 1 && !match(Mask, m_False())) {
740         StartIndex = I;
741         break;
742       }
743     }
744 
745     SmallVector<VPValue *, 4> OperandsWithMask;
746     OperandsWithMask.push_back(Blend->getIncomingValue(StartIndex));
747 
748     for (unsigned I = 0; I != Blend->getNumIncomingValues(); ++I) {
749       if (I == StartIndex)
750         continue;
751       OperandsWithMask.push_back(Blend->getIncomingValue(I));
752       OperandsWithMask.push_back(Blend->getMask(I));
753     }
754 
755     auto *NewBlend = new VPBlendRecipe(
756         cast<PHINode>(Blend->getUnderlyingValue()), OperandsWithMask);
757     NewBlend->insertBefore(&R);
758 
759     VPValue *DeadMask = Blend->getMask(StartIndex);
760     Blend->replaceAllUsesWith(NewBlend);
761     Blend->eraseFromParent();
762     recursivelyDeleteDeadRecipes(DeadMask);
763     return;
764   }
765 
766   VPValue *A;
767   if (match(&R, m_Trunc(m_ZExtOrSExt(m_VPValue(A))))) {
768     VPValue *Trunc = R.getVPSingleValue();
769     Type *TruncTy = TypeInfo.inferScalarType(Trunc);
770     Type *ATy = TypeInfo.inferScalarType(A);
771     if (TruncTy == ATy) {
772       Trunc->replaceAllUsesWith(A);
773     } else {
774       // Don't replace a scalarizing recipe with a widened cast.
775       if (isa<VPReplicateRecipe>(&R))
776         return;
777       if (ATy->getScalarSizeInBits() < TruncTy->getScalarSizeInBits()) {
778 
779         unsigned ExtOpcode = match(R.getOperand(0), m_SExt(m_VPValue()))
780                                  ? Instruction::SExt
781                                  : Instruction::ZExt;
782         auto *VPC =
783             new VPWidenCastRecipe(Instruction::CastOps(ExtOpcode), A, TruncTy);
784         if (auto *UnderlyingExt = R.getOperand(0)->getUnderlyingValue()) {
785           // UnderlyingExt has distinct return type, used to retain legacy cost.
786           VPC->setUnderlyingValue(UnderlyingExt);
787         }
788         VPC->insertBefore(&R);
789         Trunc->replaceAllUsesWith(VPC);
790       } else if (ATy->getScalarSizeInBits() > TruncTy->getScalarSizeInBits()) {
791         auto *VPC = new VPWidenCastRecipe(Instruction::Trunc, A, TruncTy);
792         VPC->insertBefore(&R);
793         Trunc->replaceAllUsesWith(VPC);
794       }
795     }
796 #ifndef NDEBUG
797     // Verify that the cached type info is for both A and its users is still
798     // accurate by comparing it to freshly computed types.
799     VPTypeAnalysis TypeInfo2(
800         R.getParent()->getPlan()->getCanonicalIV()->getScalarType());
801     assert(TypeInfo.inferScalarType(A) == TypeInfo2.inferScalarType(A));
802     for (VPUser *U : A->users()) {
803       auto *R = cast<VPRecipeBase>(U);
804       for (VPValue *VPV : R->definedValues())
805         assert(TypeInfo.inferScalarType(VPV) == TypeInfo2.inferScalarType(VPV));
806     }
807 #endif
808   }
809 
810   // Simplify (X && Y) || (X && !Y) -> X.
811   // TODO: Split up into simpler, modular combines: (X && Y) || (X && Z) into X
812   // && (Y || Z) and (X || !X) into true. This requires queuing newly created
813   // recipes to be visited during simplification.
814   VPValue *X, *Y, *X1, *Y1;
815   if (match(&R,
816             m_c_BinaryOr(m_LogicalAnd(m_VPValue(X), m_VPValue(Y)),
817                          m_LogicalAnd(m_VPValue(X1), m_Not(m_VPValue(Y1))))) &&
818       X == X1 && Y == Y1) {
819     R.getVPSingleValue()->replaceAllUsesWith(X);
820     R.eraseFromParent();
821     return;
822   }
823 
824   if (match(&R, m_c_Mul(m_VPValue(A), m_SpecificInt(1))))
825     return R.getVPSingleValue()->replaceAllUsesWith(A);
826 
827   if (match(&R, m_Not(m_Not(m_VPValue(A)))))
828     return R.getVPSingleValue()->replaceAllUsesWith(A);
829 
830   // Remove redundant DerviedIVs, that is 0 + A * 1 -> A and 0 + 0 * x -> 0.
831   if ((match(&R,
832              m_DerivedIV(m_SpecificInt(0), m_VPValue(A), m_SpecificInt(1))) ||
833        match(&R,
834              m_DerivedIV(m_SpecificInt(0), m_SpecificInt(0), m_VPValue()))) &&
835       TypeInfo.inferScalarType(R.getOperand(1)) ==
836           TypeInfo.inferScalarType(R.getVPSingleValue()))
837     return R.getVPSingleValue()->replaceAllUsesWith(R.getOperand(1));
838 }
839 
840 /// Try to simplify the recipes in \p Plan. Use \p CanonicalIVTy as type for all
841 /// un-typed live-ins in VPTypeAnalysis.
842 static void simplifyRecipes(VPlan &Plan, Type *CanonicalIVTy) {
843   ReversePostOrderTraversal<VPBlockDeepTraversalWrapper<VPBlockBase *>> RPOT(
844       Plan.getEntry());
845   VPTypeAnalysis TypeInfo(CanonicalIVTy);
846   for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(RPOT)) {
847     for (VPRecipeBase &R : make_early_inc_range(*VPBB)) {
848       simplifyRecipe(R, TypeInfo);
849     }
850   }
851 }
852 
853 void VPlanTransforms::optimizeForVFAndUF(VPlan &Plan, ElementCount BestVF,
854                                          unsigned BestUF,
855                                          PredicatedScalarEvolution &PSE) {
856   assert(Plan.hasVF(BestVF) && "BestVF is not available in Plan");
857   assert(Plan.hasUF(BestUF) && "BestUF is not available in Plan");
858   VPRegionBlock *VectorRegion = Plan.getVectorLoopRegion();
859   VPBasicBlock *ExitingVPBB = VectorRegion->getExitingBasicBlock();
860   auto *Term = &ExitingVPBB->back();
861   // Try to simplify the branch condition if TC <= VF * UF when preparing to
862   // execute the plan for the main vector loop. We only do this if the
863   // terminator is:
864   //  1. BranchOnCount, or
865   //  2. BranchOnCond where the input is Not(ActiveLaneMask).
866   using namespace llvm::VPlanPatternMatch;
867   if (!match(Term, m_BranchOnCount(m_VPValue(), m_VPValue())) &&
868       !match(Term,
869              m_BranchOnCond(m_Not(m_ActiveLaneMask(m_VPValue(), m_VPValue())))))
870     return;
871 
872   ScalarEvolution &SE = *PSE.getSE();
873   const SCEV *TripCount =
874       vputils::getSCEVExprForVPValue(Plan.getTripCount(), SE);
875   assert(!isa<SCEVCouldNotCompute>(TripCount) &&
876          "Trip count SCEV must be computable");
877   ElementCount NumElements = BestVF.multiplyCoefficientBy(BestUF);
878   const SCEV *C = SE.getElementCount(TripCount->getType(), NumElements);
879   if (TripCount->isZero() ||
880       !SE.isKnownPredicate(CmpInst::ICMP_ULE, TripCount, C))
881     return;
882 
883   // The vector loop region only executes once. If possible, completely remove
884   // the region, otherwise replace the terminator controlling the latch with
885   // (BranchOnCond true).
886   auto *Header = cast<VPBasicBlock>(VectorRegion->getEntry());
887   auto *CanIVTy = Plan.getCanonicalIV()->getScalarType();
888   if (all_of(
889           Header->phis(),
890           IsaPred<VPCanonicalIVPHIRecipe, VPFirstOrderRecurrencePHIRecipe>)) {
891     for (VPRecipeBase &HeaderR : make_early_inc_range(Header->phis())) {
892       auto *HeaderPhiR = cast<VPHeaderPHIRecipe>(&HeaderR);
893       HeaderPhiR->replaceAllUsesWith(HeaderPhiR->getStartValue());
894       HeaderPhiR->eraseFromParent();
895     }
896 
897     VPBlockBase *Preheader = VectorRegion->getSinglePredecessor();
898     VPBlockBase *Exit = VectorRegion->getSingleSuccessor();
899     VPBlockUtils::disconnectBlocks(Preheader, VectorRegion);
900     VPBlockUtils::disconnectBlocks(VectorRegion, Exit);
901 
902     for (VPBlockBase *B : vp_depth_first_shallow(VectorRegion->getEntry()))
903       B->setParent(nullptr);
904 
905     VPBlockUtils::connectBlocks(Preheader, Header);
906     VPBlockUtils::connectBlocks(ExitingVPBB, Exit);
907     simplifyRecipes(Plan, CanIVTy);
908   } else {
909     // The vector region contains header phis for which we cannot remove the
910     // loop region yet.
911     LLVMContext &Ctx = SE.getContext();
912     auto *BOC = new VPInstruction(
913         VPInstruction::BranchOnCond,
914         {Plan.getOrAddLiveIn(ConstantInt::getTrue(Ctx))}, Term->getDebugLoc());
915     ExitingVPBB->appendRecipe(BOC);
916   }
917 
918   Term->eraseFromParent();
919   VPlanTransforms::removeDeadRecipes(Plan);
920 
921   Plan.setVF(BestVF);
922   Plan.setUF(BestUF);
923   // TODO: Further simplifications are possible
924   //      1. Replace inductions with constants.
925   //      2. Replace vector loop region with VPBasicBlock.
926 }
927 
928 /// Sink users of \p FOR after the recipe defining the previous value \p
929 /// Previous of the recurrence. \returns true if all users of \p FOR could be
930 /// re-arranged as needed or false if it is not possible.
931 static bool
932 sinkRecurrenceUsersAfterPrevious(VPFirstOrderRecurrencePHIRecipe *FOR,
933                                  VPRecipeBase *Previous,
934                                  VPDominatorTree &VPDT) {
935   // Collect recipes that need sinking.
936   SmallVector<VPRecipeBase *> WorkList;
937   SmallPtrSet<VPRecipeBase *, 8> Seen;
938   Seen.insert(Previous);
939   auto TryToPushSinkCandidate = [&](VPRecipeBase *SinkCandidate) {
940     // The previous value must not depend on the users of the recurrence phi. In
941     // that case, FOR is not a fixed order recurrence.
942     if (SinkCandidate == Previous)
943       return false;
944 
945     if (isa<VPHeaderPHIRecipe>(SinkCandidate) ||
946         !Seen.insert(SinkCandidate).second ||
947         VPDT.properlyDominates(Previous, SinkCandidate))
948       return true;
949 
950     if (SinkCandidate->mayHaveSideEffects())
951       return false;
952 
953     WorkList.push_back(SinkCandidate);
954     return true;
955   };
956 
957   // Recursively sink users of FOR after Previous.
958   WorkList.push_back(FOR);
959   for (unsigned I = 0; I != WorkList.size(); ++I) {
960     VPRecipeBase *Current = WorkList[I];
961     assert(Current->getNumDefinedValues() == 1 &&
962            "only recipes with a single defined value expected");
963 
964     for (VPUser *User : Current->getVPSingleValue()->users()) {
965       if (!TryToPushSinkCandidate(cast<VPRecipeBase>(User)))
966         return false;
967     }
968   }
969 
970   // Keep recipes to sink ordered by dominance so earlier instructions are
971   // processed first.
972   sort(WorkList, [&VPDT](const VPRecipeBase *A, const VPRecipeBase *B) {
973     return VPDT.properlyDominates(A, B);
974   });
975 
976   for (VPRecipeBase *SinkCandidate : WorkList) {
977     if (SinkCandidate == FOR)
978       continue;
979 
980     SinkCandidate->moveAfter(Previous);
981     Previous = SinkCandidate;
982   }
983   return true;
984 }
985 
986 /// Try to hoist \p Previous and its operands before all users of \p FOR.
987 static bool hoistPreviousBeforeFORUsers(VPFirstOrderRecurrencePHIRecipe *FOR,
988                                         VPRecipeBase *Previous,
989                                         VPDominatorTree &VPDT) {
990   if (Previous->mayHaveSideEffects() || Previous->mayReadFromMemory())
991     return false;
992 
993   // Collect recipes that need hoisting.
994   SmallVector<VPRecipeBase *> HoistCandidates;
995   SmallPtrSet<VPRecipeBase *, 8> Visited;
996   VPRecipeBase *HoistPoint = nullptr;
997   // Find the closest hoist point by looking at all users of FOR and selecting
998   // the recipe dominating all other users.
999   for (VPUser *U : FOR->users()) {
1000     auto *R = cast<VPRecipeBase>(U);
1001     if (!HoistPoint || VPDT.properlyDominates(R, HoistPoint))
1002       HoistPoint = R;
1003   }
1004   assert(all_of(FOR->users(),
1005                 [&VPDT, HoistPoint](VPUser *U) {
1006                   auto *R = cast<VPRecipeBase>(U);
1007                   return HoistPoint == R ||
1008                          VPDT.properlyDominates(HoistPoint, R);
1009                 }) &&
1010          "HoistPoint must dominate all users of FOR");
1011 
1012   auto NeedsHoisting = [HoistPoint, &VPDT,
1013                         &Visited](VPValue *HoistCandidateV) -> VPRecipeBase * {
1014     VPRecipeBase *HoistCandidate = HoistCandidateV->getDefiningRecipe();
1015     if (!HoistCandidate)
1016       return nullptr;
1017     VPRegionBlock *EnclosingLoopRegion =
1018         HoistCandidate->getParent()->getEnclosingLoopRegion();
1019     assert((!HoistCandidate->getParent()->getParent() ||
1020             HoistCandidate->getParent()->getParent() == EnclosingLoopRegion) &&
1021            "CFG in VPlan should still be flat, without replicate regions");
1022     // Hoist candidate was already visited, no need to hoist.
1023     if (!Visited.insert(HoistCandidate).second)
1024       return nullptr;
1025 
1026     // Candidate is outside loop region or a header phi, dominates FOR users w/o
1027     // hoisting.
1028     if (!EnclosingLoopRegion || isa<VPHeaderPHIRecipe>(HoistCandidate))
1029       return nullptr;
1030 
1031     // If we reached a recipe that dominates HoistPoint, we don't need to
1032     // hoist the recipe.
1033     if (VPDT.properlyDominates(HoistCandidate, HoistPoint))
1034       return nullptr;
1035     return HoistCandidate;
1036   };
1037   auto CanHoist = [&](VPRecipeBase *HoistCandidate) {
1038     // Avoid hoisting candidates with side-effects, as we do not yet analyze
1039     // associated dependencies.
1040     return !HoistCandidate->mayHaveSideEffects();
1041   };
1042 
1043   if (!NeedsHoisting(Previous->getVPSingleValue()))
1044     return true;
1045 
1046   // Recursively try to hoist Previous and its operands before all users of FOR.
1047   HoistCandidates.push_back(Previous);
1048 
1049   for (unsigned I = 0; I != HoistCandidates.size(); ++I) {
1050     VPRecipeBase *Current = HoistCandidates[I];
1051     assert(Current->getNumDefinedValues() == 1 &&
1052            "only recipes with a single defined value expected");
1053     if (!CanHoist(Current))
1054       return false;
1055 
1056     for (VPValue *Op : Current->operands()) {
1057       // If we reach FOR, it means the original Previous depends on some other
1058       // recurrence that in turn depends on FOR. If that is the case, we would
1059       // also need to hoist recipes involving the other FOR, which may break
1060       // dependencies.
1061       if (Op == FOR)
1062         return false;
1063 
1064       if (auto *R = NeedsHoisting(Op))
1065         HoistCandidates.push_back(R);
1066     }
1067   }
1068 
1069   // Order recipes to hoist by dominance so earlier instructions are processed
1070   // first.
1071   sort(HoistCandidates, [&VPDT](const VPRecipeBase *A, const VPRecipeBase *B) {
1072     return VPDT.properlyDominates(A, B);
1073   });
1074 
1075   for (VPRecipeBase *HoistCandidate : HoistCandidates) {
1076     HoistCandidate->moveBefore(*HoistPoint->getParent(),
1077                                HoistPoint->getIterator());
1078   }
1079 
1080   return true;
1081 }
1082 
1083 bool VPlanTransforms::adjustFixedOrderRecurrences(VPlan &Plan,
1084                                                   VPBuilder &LoopBuilder) {
1085   VPDominatorTree VPDT;
1086   VPDT.recalculate(Plan);
1087 
1088   SmallVector<VPFirstOrderRecurrencePHIRecipe *> RecurrencePhis;
1089   for (VPRecipeBase &R :
1090        Plan.getVectorLoopRegion()->getEntry()->getEntryBasicBlock()->phis())
1091     if (auto *FOR = dyn_cast<VPFirstOrderRecurrencePHIRecipe>(&R))
1092       RecurrencePhis.push_back(FOR);
1093 
1094   for (VPFirstOrderRecurrencePHIRecipe *FOR : RecurrencePhis) {
1095     SmallPtrSet<VPFirstOrderRecurrencePHIRecipe *, 4> SeenPhis;
1096     VPRecipeBase *Previous = FOR->getBackedgeValue()->getDefiningRecipe();
1097     // Fixed-order recurrences do not contain cycles, so this loop is guaranteed
1098     // to terminate.
1099     while (auto *PrevPhi =
1100                dyn_cast_or_null<VPFirstOrderRecurrencePHIRecipe>(Previous)) {
1101       assert(PrevPhi->getParent() == FOR->getParent());
1102       assert(SeenPhis.insert(PrevPhi).second);
1103       Previous = PrevPhi->getBackedgeValue()->getDefiningRecipe();
1104     }
1105 
1106     if (!sinkRecurrenceUsersAfterPrevious(FOR, Previous, VPDT) &&
1107         !hoistPreviousBeforeFORUsers(FOR, Previous, VPDT))
1108       return false;
1109 
1110     // Introduce a recipe to combine the incoming and previous values of a
1111     // fixed-order recurrence.
1112     VPBasicBlock *InsertBlock = Previous->getParent();
1113     if (isa<VPHeaderPHIRecipe>(Previous))
1114       LoopBuilder.setInsertPoint(InsertBlock, InsertBlock->getFirstNonPhi());
1115     else
1116       LoopBuilder.setInsertPoint(InsertBlock,
1117                                  std::next(Previous->getIterator()));
1118 
1119     auto *RecurSplice = cast<VPInstruction>(
1120         LoopBuilder.createNaryOp(VPInstruction::FirstOrderRecurrenceSplice,
1121                                  {FOR, FOR->getBackedgeValue()}));
1122 
1123     FOR->replaceAllUsesWith(RecurSplice);
1124     // Set the first operand of RecurSplice to FOR again, after replacing
1125     // all users.
1126     RecurSplice->setOperand(0, FOR);
1127   }
1128   return true;
1129 }
1130 
1131 void VPlanTransforms::clearReductionWrapFlags(VPlan &Plan) {
1132   for (VPRecipeBase &R :
1133        Plan.getVectorLoopRegion()->getEntryBasicBlock()->phis()) {
1134     auto *PhiR = dyn_cast<VPReductionPHIRecipe>(&R);
1135     if (!PhiR)
1136       continue;
1137     const RecurrenceDescriptor &RdxDesc = PhiR->getRecurrenceDescriptor();
1138     RecurKind RK = RdxDesc.getRecurrenceKind();
1139     if (RK != RecurKind::Add && RK != RecurKind::Mul)
1140       continue;
1141 
1142     for (VPUser *U : collectUsersRecursively(PhiR))
1143       if (auto *RecWithFlags = dyn_cast<VPRecipeWithIRFlags>(U)) {
1144         RecWithFlags->dropPoisonGeneratingFlags();
1145       }
1146   }
1147 }
1148 
1149 /// Move loop-invariant recipes out of the vector loop region in \p Plan.
1150 static void licm(VPlan &Plan) {
1151   VPBasicBlock *Preheader = Plan.getVectorPreheader();
1152 
1153   // Return true if we do not know how to (mechanically) hoist a given recipe
1154   // out of a loop region. Does not address legality concerns such as aliasing
1155   // or speculation safety.
1156   auto CannotHoistRecipe = [](VPRecipeBase &R) {
1157     // Allocas cannot be hoisted.
1158     auto *RepR = dyn_cast<VPReplicateRecipe>(&R);
1159     return RepR && RepR->getOpcode() == Instruction::Alloca;
1160   };
1161 
1162   // Hoist any loop invariant recipes from the vector loop region to the
1163   // preheader. Preform a shallow traversal of the vector loop region, to
1164   // exclude recipes in replicate regions.
1165   VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
1166   for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(
1167            vp_depth_first_shallow(LoopRegion->getEntry()))) {
1168     for (VPRecipeBase &R : make_early_inc_range(*VPBB)) {
1169       if (CannotHoistRecipe(R))
1170         continue;
1171       // TODO: Relax checks in the future, e.g. we could also hoist reads, if
1172       // their memory location is not modified in the vector loop.
1173       if (R.mayHaveSideEffects() || R.mayReadFromMemory() || R.isPhi() ||
1174           any_of(R.operands(), [](VPValue *Op) {
1175             return !Op->isDefinedOutsideLoopRegions();
1176           }))
1177         continue;
1178       R.moveBefore(*Preheader, Preheader->end());
1179     }
1180   }
1181 }
1182 
1183 void VPlanTransforms::truncateToMinimalBitwidths(
1184     VPlan &Plan, const MapVector<Instruction *, uint64_t> &MinBWs) {
1185 #ifndef NDEBUG
1186   // Count the processed recipes and cross check the count later with MinBWs
1187   // size, to make sure all entries in MinBWs have been handled.
1188   unsigned NumProcessedRecipes = 0;
1189 #endif
1190   // Keep track of created truncates, so they can be re-used. Note that we
1191   // cannot use RAUW after creating a new truncate, as this would could make
1192   // other uses have different types for their operands, making them invalidly
1193   // typed.
1194   DenseMap<VPValue *, VPWidenCastRecipe *> ProcessedTruncs;
1195   Type *CanonicalIVType = Plan.getCanonicalIV()->getScalarType();
1196   VPTypeAnalysis TypeInfo(CanonicalIVType);
1197   VPBasicBlock *PH = Plan.getVectorPreheader();
1198   for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(
1199            vp_depth_first_deep(Plan.getVectorLoopRegion()))) {
1200     for (VPRecipeBase &R : make_early_inc_range(*VPBB)) {
1201       if (!isa<VPWidenRecipe, VPWidenCastRecipe, VPReplicateRecipe,
1202                VPWidenSelectRecipe, VPWidenLoadRecipe>(&R))
1203         continue;
1204 
1205       VPValue *ResultVPV = R.getVPSingleValue();
1206       auto *UI = cast_or_null<Instruction>(ResultVPV->getUnderlyingValue());
1207       unsigned NewResSizeInBits = MinBWs.lookup(UI);
1208       if (!NewResSizeInBits)
1209         continue;
1210 
1211 #ifndef NDEBUG
1212       NumProcessedRecipes++;
1213 #endif
1214       // If the value wasn't vectorized, we must maintain the original scalar
1215       // type. Skip those here, after incrementing NumProcessedRecipes. Also
1216       // skip casts which do not need to be handled explicitly here, as
1217       // redundant casts will be removed during recipe simplification.
1218       if (isa<VPReplicateRecipe, VPWidenCastRecipe>(&R)) {
1219 #ifndef NDEBUG
1220         // If any of the operands is a live-in and not used by VPWidenRecipe or
1221         // VPWidenSelectRecipe, but in MinBWs, make sure it is counted as
1222         // processed as well. When MinBWs is currently constructed, there is no
1223         // information about whether recipes are widened or replicated and in
1224         // case they are reciplicated the operands are not truncated. Counting
1225         // them them here ensures we do not miss any recipes in MinBWs.
1226         // TODO: Remove once the analysis is done on VPlan.
1227         for (VPValue *Op : R.operands()) {
1228           if (!Op->isLiveIn())
1229             continue;
1230           auto *UV = dyn_cast_or_null<Instruction>(Op->getUnderlyingValue());
1231           if (UV && MinBWs.contains(UV) && !ProcessedTruncs.contains(Op) &&
1232               none_of(Op->users(),
1233                       IsaPred<VPWidenRecipe, VPWidenSelectRecipe>)) {
1234             // Add an entry to ProcessedTruncs to avoid counting the same
1235             // operand multiple times.
1236             ProcessedTruncs[Op] = nullptr;
1237             NumProcessedRecipes += 1;
1238           }
1239         }
1240 #endif
1241         continue;
1242       }
1243 
1244       Type *OldResTy = TypeInfo.inferScalarType(ResultVPV);
1245       unsigned OldResSizeInBits = OldResTy->getScalarSizeInBits();
1246       assert(OldResTy->isIntegerTy() && "only integer types supported");
1247       (void)OldResSizeInBits;
1248 
1249       LLVMContext &Ctx = CanonicalIVType->getContext();
1250       auto *NewResTy = IntegerType::get(Ctx, NewResSizeInBits);
1251 
1252       // Any wrapping introduced by shrinking this operation shouldn't be
1253       // considered undefined behavior. So, we can't unconditionally copy
1254       // arithmetic wrapping flags to VPW.
1255       if (auto *VPW = dyn_cast<VPRecipeWithIRFlags>(&R))
1256         VPW->dropPoisonGeneratingFlags();
1257 
1258       using namespace llvm::VPlanPatternMatch;
1259       if (OldResSizeInBits != NewResSizeInBits &&
1260           !match(&R, m_Binary<Instruction::ICmp>(m_VPValue(), m_VPValue()))) {
1261         // Extend result to original width.
1262         auto *Ext =
1263             new VPWidenCastRecipe(Instruction::ZExt, ResultVPV, OldResTy);
1264         Ext->insertAfter(&R);
1265         ResultVPV->replaceAllUsesWith(Ext);
1266         Ext->setOperand(0, ResultVPV);
1267         assert(OldResSizeInBits > NewResSizeInBits && "Nothing to shrink?");
1268       } else {
1269         assert(
1270             match(&R, m_Binary<Instruction::ICmp>(m_VPValue(), m_VPValue())) &&
1271             "Only ICmps should not need extending the result.");
1272       }
1273 
1274       assert(!isa<VPWidenStoreRecipe>(&R) && "stores cannot be narrowed");
1275       if (isa<VPWidenLoadRecipe>(&R))
1276         continue;
1277 
1278       // Shrink operands by introducing truncates as needed.
1279       unsigned StartIdx = isa<VPWidenSelectRecipe>(&R) ? 1 : 0;
1280       for (unsigned Idx = StartIdx; Idx != R.getNumOperands(); ++Idx) {
1281         auto *Op = R.getOperand(Idx);
1282         unsigned OpSizeInBits =
1283             TypeInfo.inferScalarType(Op)->getScalarSizeInBits();
1284         if (OpSizeInBits == NewResSizeInBits)
1285           continue;
1286         assert(OpSizeInBits > NewResSizeInBits && "nothing to truncate");
1287         auto [ProcessedIter, IterIsEmpty] =
1288             ProcessedTruncs.insert({Op, nullptr});
1289         VPWidenCastRecipe *NewOp =
1290             IterIsEmpty
1291                 ? new VPWidenCastRecipe(Instruction::Trunc, Op, NewResTy)
1292                 : ProcessedIter->second;
1293         R.setOperand(Idx, NewOp);
1294         if (!IterIsEmpty)
1295           continue;
1296         ProcessedIter->second = NewOp;
1297         if (!Op->isLiveIn()) {
1298           NewOp->insertBefore(&R);
1299         } else {
1300           PH->appendRecipe(NewOp);
1301 #ifndef NDEBUG
1302           auto *OpInst = dyn_cast<Instruction>(Op->getLiveInIRValue());
1303           bool IsContained = MinBWs.contains(OpInst);
1304           NumProcessedRecipes += IsContained;
1305 #endif
1306         }
1307       }
1308 
1309     }
1310   }
1311 
1312   assert(MinBWs.size() == NumProcessedRecipes &&
1313          "some entries in MinBWs haven't been processed");
1314 }
1315 
1316 void VPlanTransforms::optimize(VPlan &Plan) {
1317   removeRedundantCanonicalIVs(Plan);
1318   removeRedundantInductionCasts(Plan);
1319 
1320   simplifyRecipes(Plan, Plan.getCanonicalIV()->getScalarType());
1321   legalizeAndOptimizeInductions(Plan);
1322   removeRedundantExpandSCEVRecipes(Plan);
1323   simplifyRecipes(Plan, Plan.getCanonicalIV()->getScalarType());
1324   removeDeadRecipes(Plan);
1325 
1326   createAndOptimizeReplicateRegions(Plan);
1327   mergeBlocksIntoPredecessors(Plan);
1328   licm(Plan);
1329 }
1330 
1331 // Add a VPActiveLaneMaskPHIRecipe and related recipes to \p Plan and replace
1332 // the loop terminator with a branch-on-cond recipe with the negated
1333 // active-lane-mask as operand. Note that this turns the loop into an
1334 // uncountable one. Only the existing terminator is replaced, all other existing
1335 // recipes/users remain unchanged, except for poison-generating flags being
1336 // dropped from the canonical IV increment. Return the created
1337 // VPActiveLaneMaskPHIRecipe.
1338 //
1339 // The function uses the following definitions:
1340 //
1341 //  %TripCount = DataWithControlFlowWithoutRuntimeCheck ?
1342 //    calculate-trip-count-minus-VF (original TC) : original TC
1343 //  %IncrementValue = DataWithControlFlowWithoutRuntimeCheck ?
1344 //     CanonicalIVPhi : CanonicalIVIncrement
1345 //  %StartV is the canonical induction start value.
1346 //
1347 // The function adds the following recipes:
1348 //
1349 // vector.ph:
1350 //   %TripCount = calculate-trip-count-minus-VF (original TC)
1351 //       [if DataWithControlFlowWithoutRuntimeCheck]
1352 //   %EntryInc = canonical-iv-increment-for-part %StartV
1353 //   %EntryALM = active-lane-mask %EntryInc, %TripCount
1354 //
1355 // vector.body:
1356 //   ...
1357 //   %P = active-lane-mask-phi [ %EntryALM, %vector.ph ], [ %ALM, %vector.body ]
1358 //   ...
1359 //   %InLoopInc = canonical-iv-increment-for-part %IncrementValue
1360 //   %ALM = active-lane-mask %InLoopInc, TripCount
1361 //   %Negated = Not %ALM
1362 //   branch-on-cond %Negated
1363 //
1364 static VPActiveLaneMaskPHIRecipe *addVPLaneMaskPhiAndUpdateExitBranch(
1365     VPlan &Plan, bool DataAndControlFlowWithoutRuntimeCheck) {
1366   VPRegionBlock *TopRegion = Plan.getVectorLoopRegion();
1367   VPBasicBlock *EB = TopRegion->getExitingBasicBlock();
1368   auto *CanonicalIVPHI = Plan.getCanonicalIV();
1369   VPValue *StartV = CanonicalIVPHI->getStartValue();
1370 
1371   auto *CanonicalIVIncrement =
1372       cast<VPInstruction>(CanonicalIVPHI->getBackedgeValue());
1373   // TODO: Check if dropping the flags is needed if
1374   // !DataAndControlFlowWithoutRuntimeCheck.
1375   CanonicalIVIncrement->dropPoisonGeneratingFlags();
1376   DebugLoc DL = CanonicalIVIncrement->getDebugLoc();
1377   // We can't use StartV directly in the ActiveLaneMask VPInstruction, since
1378   // we have to take unrolling into account. Each part needs to start at
1379   //   Part * VF
1380   auto *VecPreheader = Plan.getVectorPreheader();
1381   VPBuilder Builder(VecPreheader);
1382 
1383   // Create the ActiveLaneMask instruction using the correct start values.
1384   VPValue *TC = Plan.getTripCount();
1385 
1386   VPValue *TripCount, *IncrementValue;
1387   if (!DataAndControlFlowWithoutRuntimeCheck) {
1388     // When the loop is guarded by a runtime overflow check for the loop
1389     // induction variable increment by VF, we can increment the value before
1390     // the get.active.lane mask and use the unmodified tripcount.
1391     IncrementValue = CanonicalIVIncrement;
1392     TripCount = TC;
1393   } else {
1394     // When avoiding a runtime check, the active.lane.mask inside the loop
1395     // uses a modified trip count and the induction variable increment is
1396     // done after the active.lane.mask intrinsic is called.
1397     IncrementValue = CanonicalIVPHI;
1398     TripCount = Builder.createNaryOp(VPInstruction::CalculateTripCountMinusVF,
1399                                      {TC}, DL);
1400   }
1401   auto *EntryIncrement = Builder.createOverflowingOp(
1402       VPInstruction::CanonicalIVIncrementForPart, {StartV}, {false, false}, DL,
1403       "index.part.next");
1404 
1405   // Create the active lane mask instruction in the VPlan preheader.
1406   auto *EntryALM =
1407       Builder.createNaryOp(VPInstruction::ActiveLaneMask, {EntryIncrement, TC},
1408                            DL, "active.lane.mask.entry");
1409 
1410   // Now create the ActiveLaneMaskPhi recipe in the main loop using the
1411   // preheader ActiveLaneMask instruction.
1412   auto *LaneMaskPhi = new VPActiveLaneMaskPHIRecipe(EntryALM, DebugLoc());
1413   LaneMaskPhi->insertAfter(CanonicalIVPHI);
1414 
1415   // Create the active lane mask for the next iteration of the loop before the
1416   // original terminator.
1417   VPRecipeBase *OriginalTerminator = EB->getTerminator();
1418   Builder.setInsertPoint(OriginalTerminator);
1419   auto *InLoopIncrement =
1420       Builder.createOverflowingOp(VPInstruction::CanonicalIVIncrementForPart,
1421                                   {IncrementValue}, {false, false}, DL);
1422   auto *ALM = Builder.createNaryOp(VPInstruction::ActiveLaneMask,
1423                                    {InLoopIncrement, TripCount}, DL,
1424                                    "active.lane.mask.next");
1425   LaneMaskPhi->addOperand(ALM);
1426 
1427   // Replace the original terminator with BranchOnCond. We have to invert the
1428   // mask here because a true condition means jumping to the exit block.
1429   auto *NotMask = Builder.createNot(ALM, DL);
1430   Builder.createNaryOp(VPInstruction::BranchOnCond, {NotMask}, DL);
1431   OriginalTerminator->eraseFromParent();
1432   return LaneMaskPhi;
1433 }
1434 
1435 /// Collect all VPValues representing a header mask through the (ICMP_ULE,
1436 /// WideCanonicalIV, backedge-taken-count) pattern.
1437 /// TODO: Introduce explicit recipe for header-mask instead of searching
1438 /// for the header-mask pattern manually.
1439 static SmallVector<VPValue *> collectAllHeaderMasks(VPlan &Plan) {
1440   SmallVector<VPValue *> WideCanonicalIVs;
1441   auto *FoundWidenCanonicalIVUser =
1442       find_if(Plan.getCanonicalIV()->users(),
1443               [](VPUser *U) { return isa<VPWidenCanonicalIVRecipe>(U); });
1444   assert(count_if(Plan.getCanonicalIV()->users(),
1445                   [](VPUser *U) { return isa<VPWidenCanonicalIVRecipe>(U); }) <=
1446              1 &&
1447          "Must have at most one VPWideCanonicalIVRecipe");
1448   if (FoundWidenCanonicalIVUser != Plan.getCanonicalIV()->users().end()) {
1449     auto *WideCanonicalIV =
1450         cast<VPWidenCanonicalIVRecipe>(*FoundWidenCanonicalIVUser);
1451     WideCanonicalIVs.push_back(WideCanonicalIV);
1452   }
1453 
1454   // Also include VPWidenIntOrFpInductionRecipes that represent a widened
1455   // version of the canonical induction.
1456   VPBasicBlock *HeaderVPBB = Plan.getVectorLoopRegion()->getEntryBasicBlock();
1457   for (VPRecipeBase &Phi : HeaderVPBB->phis()) {
1458     auto *WidenOriginalIV = dyn_cast<VPWidenIntOrFpInductionRecipe>(&Phi);
1459     if (WidenOriginalIV && WidenOriginalIV->isCanonical())
1460       WideCanonicalIVs.push_back(WidenOriginalIV);
1461   }
1462 
1463   // Walk users of wide canonical IVs and collect to all compares of the form
1464   // (ICMP_ULE, WideCanonicalIV, backedge-taken-count).
1465   SmallVector<VPValue *> HeaderMasks;
1466   for (auto *Wide : WideCanonicalIVs) {
1467     for (VPUser *U : SmallVector<VPUser *>(Wide->users())) {
1468       auto *HeaderMask = dyn_cast<VPInstruction>(U);
1469       if (!HeaderMask || !vputils::isHeaderMask(HeaderMask, Plan))
1470         continue;
1471 
1472       assert(HeaderMask->getOperand(0) == Wide &&
1473              "WidenCanonicalIV must be the first operand of the compare");
1474       HeaderMasks.push_back(HeaderMask);
1475     }
1476   }
1477   return HeaderMasks;
1478 }
1479 
1480 void VPlanTransforms::addActiveLaneMask(
1481     VPlan &Plan, bool UseActiveLaneMaskForControlFlow,
1482     bool DataAndControlFlowWithoutRuntimeCheck) {
1483   assert((!DataAndControlFlowWithoutRuntimeCheck ||
1484           UseActiveLaneMaskForControlFlow) &&
1485          "DataAndControlFlowWithoutRuntimeCheck implies "
1486          "UseActiveLaneMaskForControlFlow");
1487 
1488   auto *FoundWidenCanonicalIVUser =
1489       find_if(Plan.getCanonicalIV()->users(),
1490               [](VPUser *U) { return isa<VPWidenCanonicalIVRecipe>(U); });
1491   assert(FoundWidenCanonicalIVUser &&
1492          "Must have widened canonical IV when tail folding!");
1493   auto *WideCanonicalIV =
1494       cast<VPWidenCanonicalIVRecipe>(*FoundWidenCanonicalIVUser);
1495   VPSingleDefRecipe *LaneMask;
1496   if (UseActiveLaneMaskForControlFlow) {
1497     LaneMask = addVPLaneMaskPhiAndUpdateExitBranch(
1498         Plan, DataAndControlFlowWithoutRuntimeCheck);
1499   } else {
1500     VPBuilder B = VPBuilder::getToInsertAfter(WideCanonicalIV);
1501     LaneMask = B.createNaryOp(VPInstruction::ActiveLaneMask,
1502                               {WideCanonicalIV, Plan.getTripCount()}, nullptr,
1503                               "active.lane.mask");
1504   }
1505 
1506   // Walk users of WideCanonicalIV and replace all compares of the form
1507   // (ICMP_ULE, WideCanonicalIV, backedge-taken-count) with an
1508   // active-lane-mask.
1509   for (VPValue *HeaderMask : collectAllHeaderMasks(Plan))
1510     HeaderMask->replaceAllUsesWith(LaneMask);
1511 }
1512 
1513 /// Try to convert \p CurRecipe to a corresponding EVL-based recipe. Returns
1514 /// nullptr if no EVL-based recipe could be created.
1515 /// \p HeaderMask  Header Mask.
1516 /// \p CurRecipe   Recipe to be transform.
1517 /// \p TypeInfo    VPlan-based type analysis.
1518 /// \p AllOneMask  The vector mask parameter of vector-predication intrinsics.
1519 /// \p EVL         The explicit vector length parameter of vector-predication
1520 /// intrinsics.
1521 static VPRecipeBase *createEVLRecipe(VPValue *HeaderMask,
1522                                      VPRecipeBase &CurRecipe,
1523                                      VPTypeAnalysis &TypeInfo,
1524                                      VPValue &AllOneMask, VPValue &EVL) {
1525   using namespace llvm::VPlanPatternMatch;
1526   auto GetNewMask = [&](VPValue *OrigMask) -> VPValue * {
1527     assert(OrigMask && "Unmasked recipe when folding tail");
1528     return HeaderMask == OrigMask ? nullptr : OrigMask;
1529   };
1530 
1531   return TypeSwitch<VPRecipeBase *, VPRecipeBase *>(&CurRecipe)
1532       .Case<VPWidenLoadRecipe>([&](VPWidenLoadRecipe *L) {
1533         VPValue *NewMask = GetNewMask(L->getMask());
1534         return new VPWidenLoadEVLRecipe(*L, EVL, NewMask);
1535       })
1536       .Case<VPWidenStoreRecipe>([&](VPWidenStoreRecipe *S) {
1537         VPValue *NewMask = GetNewMask(S->getMask());
1538         return new VPWidenStoreEVLRecipe(*S, EVL, NewMask);
1539       })
1540       .Case<VPWidenRecipe>([&](VPWidenRecipe *W) -> VPRecipeBase * {
1541         unsigned Opcode = W->getOpcode();
1542         if (!Instruction::isBinaryOp(Opcode) && !Instruction::isUnaryOp(Opcode))
1543           return nullptr;
1544         return new VPWidenEVLRecipe(*W, EVL);
1545       })
1546       .Case<VPReductionRecipe>([&](VPReductionRecipe *Red) {
1547         VPValue *NewMask = GetNewMask(Red->getCondOp());
1548         return new VPReductionEVLRecipe(*Red, EVL, NewMask);
1549       })
1550       .Case<VPWidenIntrinsicRecipe, VPWidenCastRecipe>(
1551           [&](auto *CR) -> VPRecipeBase * {
1552             Intrinsic::ID VPID;
1553             if (auto *CallR = dyn_cast<VPWidenIntrinsicRecipe>(CR)) {
1554               VPID =
1555                   VPIntrinsic::getForIntrinsic(CallR->getVectorIntrinsicID());
1556             } else {
1557               auto *CastR = cast<VPWidenCastRecipe>(CR);
1558               VPID = VPIntrinsic::getForOpcode(CastR->getOpcode());
1559             }
1560 
1561             // Not all intrinsics have a corresponding VP intrinsic.
1562             if (VPID == Intrinsic::not_intrinsic)
1563               return nullptr;
1564             assert(VPIntrinsic::getMaskParamPos(VPID) &&
1565                    VPIntrinsic::getVectorLengthParamPos(VPID) &&
1566                    "Expected VP intrinsic to have mask and EVL");
1567 
1568             SmallVector<VPValue *> Ops(CR->operands());
1569             Ops.push_back(&AllOneMask);
1570             Ops.push_back(&EVL);
1571             return new VPWidenIntrinsicRecipe(
1572                 VPID, Ops, TypeInfo.inferScalarType(CR), CR->getDebugLoc());
1573           })
1574       .Case<VPWidenSelectRecipe>([&](VPWidenSelectRecipe *Sel) {
1575         SmallVector<VPValue *> Ops(Sel->operands());
1576         Ops.push_back(&EVL);
1577         return new VPWidenIntrinsicRecipe(Intrinsic::vp_select, Ops,
1578                                           TypeInfo.inferScalarType(Sel),
1579                                           Sel->getDebugLoc());
1580       })
1581       .Case<VPInstruction>([&](VPInstruction *VPI) -> VPRecipeBase * {
1582         VPValue *LHS, *RHS;
1583         // Transform select with a header mask condition
1584         //   select(header_mask, LHS, RHS)
1585         // into vector predication merge.
1586         //   vp.merge(all-true, LHS, RHS, EVL)
1587         if (!match(VPI, m_Select(m_Specific(HeaderMask), m_VPValue(LHS),
1588                                  m_VPValue(RHS))))
1589           return nullptr;
1590         // Use all true as the condition because this transformation is
1591         // limited to selects whose condition is a header mask.
1592         return new VPWidenIntrinsicRecipe(
1593             Intrinsic::vp_merge, {&AllOneMask, LHS, RHS, &EVL},
1594             TypeInfo.inferScalarType(LHS), VPI->getDebugLoc());
1595       })
1596       .Default([&](VPRecipeBase *R) { return nullptr; });
1597 }
1598 
1599 /// Replace recipes with their EVL variants.
1600 static void transformRecipestoEVLRecipes(VPlan &Plan, VPValue &EVL) {
1601   Type *CanonicalIVType = Plan.getCanonicalIV()->getScalarType();
1602   VPTypeAnalysis TypeInfo(CanonicalIVType);
1603   LLVMContext &Ctx = CanonicalIVType->getContext();
1604   VPValue *AllOneMask = Plan.getOrAddLiveIn(ConstantInt::getTrue(Ctx));
1605 
1606   for (VPUser *U : Plan.getVF().users()) {
1607     if (auto *R = dyn_cast<VPReverseVectorPointerRecipe>(U))
1608       R->setOperand(1, &EVL);
1609   }
1610 
1611   SmallVector<VPRecipeBase *> ToErase;
1612 
1613   for (VPValue *HeaderMask : collectAllHeaderMasks(Plan)) {
1614     for (VPUser *U : collectUsersRecursively(HeaderMask)) {
1615       auto *CurRecipe = cast<VPRecipeBase>(U);
1616       VPRecipeBase *EVLRecipe =
1617           createEVLRecipe(HeaderMask, *CurRecipe, TypeInfo, *AllOneMask, EVL);
1618       if (!EVLRecipe)
1619         continue;
1620 
1621       [[maybe_unused]] unsigned NumDefVal = EVLRecipe->getNumDefinedValues();
1622       assert(NumDefVal == CurRecipe->getNumDefinedValues() &&
1623              "New recipe must define the same number of values as the "
1624              "original.");
1625       assert(
1626           NumDefVal <= 1 &&
1627           "Only supports recipes with a single definition or without users.");
1628       EVLRecipe->insertBefore(CurRecipe);
1629       if (isa<VPSingleDefRecipe, VPWidenLoadEVLRecipe>(EVLRecipe)) {
1630         VPValue *CurVPV = CurRecipe->getVPSingleValue();
1631         CurVPV->replaceAllUsesWith(EVLRecipe->getVPSingleValue());
1632       }
1633       // Defer erasing recipes till the end so that we don't invalidate the
1634       // VPTypeAnalysis cache.
1635       ToErase.push_back(CurRecipe);
1636     }
1637   }
1638 
1639   for (VPRecipeBase *R : reverse(ToErase)) {
1640     SmallVector<VPValue *> PossiblyDead(R->operands());
1641     R->eraseFromParent();
1642     for (VPValue *Op : PossiblyDead)
1643       recursivelyDeleteDeadRecipes(Op);
1644   }
1645 }
1646 
1647 /// Add a VPEVLBasedIVPHIRecipe and related recipes to \p Plan and
1648 /// replaces all uses except the canonical IV increment of
1649 /// VPCanonicalIVPHIRecipe with a VPEVLBasedIVPHIRecipe. VPCanonicalIVPHIRecipe
1650 /// is used only for loop iterations counting after this transformation.
1651 ///
1652 /// The function uses the following definitions:
1653 ///  %StartV is the canonical induction start value.
1654 ///
1655 /// The function adds the following recipes:
1656 ///
1657 /// vector.ph:
1658 /// ...
1659 ///
1660 /// vector.body:
1661 /// ...
1662 /// %EVLPhi = EXPLICIT-VECTOR-LENGTH-BASED-IV-PHI [ %StartV, %vector.ph ],
1663 ///                                               [ %NextEVLIV, %vector.body ]
1664 /// %AVL = sub original TC, %EVLPhi
1665 /// %VPEVL = EXPLICIT-VECTOR-LENGTH %AVL
1666 /// ...
1667 /// %NextEVLIV = add IVSize (cast i32 %VPEVVL to IVSize), %EVLPhi
1668 /// ...
1669 ///
1670 /// If MaxSafeElements is provided, the function adds the following recipes:
1671 /// vector.ph:
1672 /// ...
1673 ///
1674 /// vector.body:
1675 /// ...
1676 /// %EVLPhi = EXPLICIT-VECTOR-LENGTH-BASED-IV-PHI [ %StartV, %vector.ph ],
1677 ///                                               [ %NextEVLIV, %vector.body ]
1678 /// %AVL = sub original TC, %EVLPhi
1679 /// %cmp = cmp ult %AVL, MaxSafeElements
1680 /// %SAFE_AVL = select %cmp, %AVL, MaxSafeElements
1681 /// %VPEVL = EXPLICIT-VECTOR-LENGTH %SAFE_AVL
1682 /// ...
1683 /// %NextEVLIV = add IVSize (cast i32 %VPEVL to IVSize), %EVLPhi
1684 /// ...
1685 ///
1686 bool VPlanTransforms::tryAddExplicitVectorLength(
1687     VPlan &Plan, const std::optional<unsigned> &MaxSafeElements) {
1688   VPBasicBlock *Header = Plan.getVectorLoopRegion()->getEntryBasicBlock();
1689   // The transform updates all users of inductions to work based on EVL, instead
1690   // of the VF directly. At the moment, widened inductions cannot be updated, so
1691   // bail out if the plan contains any.
1692   bool ContainsWidenInductions = any_of(
1693       Header->phis(),
1694       IsaPred<VPWidenIntOrFpInductionRecipe, VPWidenPointerInductionRecipe>);
1695   if (ContainsWidenInductions)
1696     return false;
1697 
1698   auto *CanonicalIVPHI = Plan.getCanonicalIV();
1699   VPValue *StartV = CanonicalIVPHI->getStartValue();
1700 
1701   // Create the ExplicitVectorLengthPhi recipe in the main loop.
1702   auto *EVLPhi = new VPEVLBasedIVPHIRecipe(StartV, DebugLoc());
1703   EVLPhi->insertAfter(CanonicalIVPHI);
1704   VPBuilder Builder(Header, Header->getFirstNonPhi());
1705   // Compute original TC - IV as the AVL (application vector length).
1706   VPValue *AVL = Builder.createNaryOp(
1707       Instruction::Sub, {Plan.getTripCount(), EVLPhi}, DebugLoc(), "avl");
1708   if (MaxSafeElements) {
1709     // Support for MaxSafeDist for correct loop emission.
1710     VPValue *AVLSafe = Plan.getOrAddLiveIn(
1711         ConstantInt::get(CanonicalIVPHI->getScalarType(), *MaxSafeElements));
1712     VPValue *Cmp = Builder.createICmp(ICmpInst::ICMP_ULT, AVL, AVLSafe);
1713     AVL = Builder.createSelect(Cmp, AVL, AVLSafe, DebugLoc(), "safe_avl");
1714   }
1715   auto *VPEVL = Builder.createNaryOp(VPInstruction::ExplicitVectorLength, AVL,
1716                                      DebugLoc());
1717 
1718   auto *CanonicalIVIncrement =
1719       cast<VPInstruction>(CanonicalIVPHI->getBackedgeValue());
1720   VPSingleDefRecipe *OpVPEVL = VPEVL;
1721   if (unsigned IVSize = CanonicalIVPHI->getScalarType()->getScalarSizeInBits();
1722       IVSize != 32) {
1723     OpVPEVL = new VPScalarCastRecipe(
1724         IVSize < 32 ? Instruction::Trunc : Instruction::ZExt, OpVPEVL,
1725         CanonicalIVPHI->getScalarType(), CanonicalIVIncrement->getDebugLoc());
1726     OpVPEVL->insertBefore(CanonicalIVIncrement);
1727   }
1728   auto *NextEVLIV =
1729       new VPInstruction(Instruction::Add, {OpVPEVL, EVLPhi},
1730                         {CanonicalIVIncrement->hasNoUnsignedWrap(),
1731                          CanonicalIVIncrement->hasNoSignedWrap()},
1732                         CanonicalIVIncrement->getDebugLoc(), "index.evl.next");
1733   NextEVLIV->insertBefore(CanonicalIVIncrement);
1734   EVLPhi->addOperand(NextEVLIV);
1735 
1736   transformRecipestoEVLRecipes(Plan, *VPEVL);
1737 
1738   // Replace all uses of VPCanonicalIVPHIRecipe by
1739   // VPEVLBasedIVPHIRecipe except for the canonical IV increment.
1740   CanonicalIVPHI->replaceAllUsesWith(EVLPhi);
1741   CanonicalIVIncrement->setOperand(0, CanonicalIVPHI);
1742   // TODO: support unroll factor > 1.
1743   Plan.setUF(1);
1744   return true;
1745 }
1746 
1747 void VPlanTransforms::dropPoisonGeneratingRecipes(
1748     VPlan &Plan, function_ref<bool(BasicBlock *)> BlockNeedsPredication) {
1749   // Collect recipes in the backward slice of `Root` that may generate a poison
1750   // value that is used after vectorization.
1751   SmallPtrSet<VPRecipeBase *, 16> Visited;
1752   auto CollectPoisonGeneratingInstrsInBackwardSlice([&](VPRecipeBase *Root) {
1753     SmallVector<VPRecipeBase *, 16> Worklist;
1754     Worklist.push_back(Root);
1755 
1756     // Traverse the backward slice of Root through its use-def chain.
1757     while (!Worklist.empty()) {
1758       VPRecipeBase *CurRec = Worklist.pop_back_val();
1759 
1760       if (!Visited.insert(CurRec).second)
1761         continue;
1762 
1763       // Prune search if we find another recipe generating a widen memory
1764       // instruction. Widen memory instructions involved in address computation
1765       // will lead to gather/scatter instructions, which don't need to be
1766       // handled.
1767       if (isa<VPWidenMemoryRecipe, VPInterleaveRecipe, VPScalarIVStepsRecipe,
1768               VPHeaderPHIRecipe>(CurRec))
1769         continue;
1770 
1771       // This recipe contributes to the address computation of a widen
1772       // load/store. If the underlying instruction has poison-generating flags,
1773       // drop them directly.
1774       if (auto *RecWithFlags = dyn_cast<VPRecipeWithIRFlags>(CurRec)) {
1775         VPValue *A, *B;
1776         using namespace llvm::VPlanPatternMatch;
1777         // Dropping disjoint from an OR may yield incorrect results, as some
1778         // analysis may have converted it to an Add implicitly (e.g. SCEV used
1779         // for dependence analysis). Instead, replace it with an equivalent Add.
1780         // This is possible as all users of the disjoint OR only access lanes
1781         // where the operands are disjoint or poison otherwise.
1782         if (match(RecWithFlags, m_BinaryOr(m_VPValue(A), m_VPValue(B))) &&
1783             RecWithFlags->isDisjoint()) {
1784           VPBuilder Builder(RecWithFlags);
1785           VPInstruction *New = Builder.createOverflowingOp(
1786               Instruction::Add, {A, B}, {false, false},
1787               RecWithFlags->getDebugLoc());
1788           New->setUnderlyingValue(RecWithFlags->getUnderlyingValue());
1789           RecWithFlags->replaceAllUsesWith(New);
1790           RecWithFlags->eraseFromParent();
1791           CurRec = New;
1792         } else
1793           RecWithFlags->dropPoisonGeneratingFlags();
1794       } else {
1795         Instruction *Instr = dyn_cast_or_null<Instruction>(
1796             CurRec->getVPSingleValue()->getUnderlyingValue());
1797         (void)Instr;
1798         assert((!Instr || !Instr->hasPoisonGeneratingFlags()) &&
1799                "found instruction with poison generating flags not covered by "
1800                "VPRecipeWithIRFlags");
1801       }
1802 
1803       // Add new definitions to the worklist.
1804       for (VPValue *Operand : CurRec->operands())
1805         if (VPRecipeBase *OpDef = Operand->getDefiningRecipe())
1806           Worklist.push_back(OpDef);
1807     }
1808   });
1809 
1810   // Traverse all the recipes in the VPlan and collect the poison-generating
1811   // recipes in the backward slice starting at the address of a VPWidenRecipe or
1812   // VPInterleaveRecipe.
1813   auto Iter = vp_depth_first_deep(Plan.getEntry());
1814   for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(Iter)) {
1815     for (VPRecipeBase &Recipe : *VPBB) {
1816       if (auto *WidenRec = dyn_cast<VPWidenMemoryRecipe>(&Recipe)) {
1817         Instruction &UnderlyingInstr = WidenRec->getIngredient();
1818         VPRecipeBase *AddrDef = WidenRec->getAddr()->getDefiningRecipe();
1819         if (AddrDef && WidenRec->isConsecutive() &&
1820             BlockNeedsPredication(UnderlyingInstr.getParent()))
1821           CollectPoisonGeneratingInstrsInBackwardSlice(AddrDef);
1822       } else if (auto *InterleaveRec = dyn_cast<VPInterleaveRecipe>(&Recipe)) {
1823         VPRecipeBase *AddrDef = InterleaveRec->getAddr()->getDefiningRecipe();
1824         if (AddrDef) {
1825           // Check if any member of the interleave group needs predication.
1826           const InterleaveGroup<Instruction> *InterGroup =
1827               InterleaveRec->getInterleaveGroup();
1828           bool NeedPredication = false;
1829           for (int I = 0, NumMembers = InterGroup->getNumMembers();
1830                I < NumMembers; ++I) {
1831             Instruction *Member = InterGroup->getMember(I);
1832             if (Member)
1833               NeedPredication |= BlockNeedsPredication(Member->getParent());
1834           }
1835 
1836           if (NeedPredication)
1837             CollectPoisonGeneratingInstrsInBackwardSlice(AddrDef);
1838         }
1839       }
1840     }
1841   }
1842 }
1843 
1844 void VPlanTransforms::createInterleaveGroups(
1845     VPlan &Plan,
1846     const SmallPtrSetImpl<const InterleaveGroup<Instruction> *>
1847         &InterleaveGroups,
1848     VPRecipeBuilder &RecipeBuilder, bool ScalarEpilogueAllowed) {
1849   if (InterleaveGroups.empty())
1850     return;
1851 
1852   // Interleave memory: for each Interleave Group we marked earlier as relevant
1853   // for this VPlan, replace the Recipes widening its memory instructions with a
1854   // single VPInterleaveRecipe at its insertion point.
1855   VPDominatorTree VPDT;
1856   VPDT.recalculate(Plan);
1857   for (const auto *IG : InterleaveGroups) {
1858     SmallVector<VPValue *, 4> StoredValues;
1859     for (unsigned i = 0; i < IG->getFactor(); ++i)
1860       if (auto *SI = dyn_cast_or_null<StoreInst>(IG->getMember(i))) {
1861         auto *StoreR = cast<VPWidenStoreRecipe>(RecipeBuilder.getRecipe(SI));
1862         StoredValues.push_back(StoreR->getStoredValue());
1863       }
1864 
1865     bool NeedsMaskForGaps =
1866         IG->requiresScalarEpilogue() && !ScalarEpilogueAllowed;
1867 
1868     Instruction *IRInsertPos = IG->getInsertPos();
1869     auto *InsertPos =
1870         cast<VPWidenMemoryRecipe>(RecipeBuilder.getRecipe(IRInsertPos));
1871 
1872     // Get or create the start address for the interleave group.
1873     auto *Start =
1874         cast<VPWidenMemoryRecipe>(RecipeBuilder.getRecipe(IG->getMember(0)));
1875     VPValue *Addr = Start->getAddr();
1876     VPRecipeBase *AddrDef = Addr->getDefiningRecipe();
1877     if (AddrDef && !VPDT.properlyDominates(AddrDef, InsertPos)) {
1878       // TODO: Hoist Addr's defining recipe (and any operands as needed) to
1879       // InsertPos or sink loads above zero members to join it.
1880       bool InBounds = false;
1881       if (auto *Gep = dyn_cast<GetElementPtrInst>(
1882               getLoadStorePointerOperand(IRInsertPos)->stripPointerCasts()))
1883         InBounds = Gep->isInBounds();
1884 
1885       // We cannot re-use the address of member zero because it does not
1886       // dominate the insert position. Instead, use the address of the insert
1887       // position and create a PtrAdd adjusting it to the address of member
1888       // zero.
1889       assert(IG->getIndex(IRInsertPos) != 0 &&
1890              "index of insert position shouldn't be zero");
1891       auto &DL = IRInsertPos->getDataLayout();
1892       APInt Offset(32,
1893                    DL.getTypeAllocSize(getLoadStoreType(IRInsertPos)) *
1894                        IG->getIndex(IRInsertPos),
1895                    /*IsSigned=*/true);
1896       VPValue *OffsetVPV = Plan.getOrAddLiveIn(
1897           ConstantInt::get(IRInsertPos->getParent()->getContext(), -Offset));
1898       VPBuilder B(InsertPos);
1899       Addr = InBounds ? B.createInBoundsPtrAdd(InsertPos->getAddr(), OffsetVPV)
1900                       : B.createPtrAdd(InsertPos->getAddr(), OffsetVPV);
1901     }
1902     auto *VPIG = new VPInterleaveRecipe(IG, Addr, StoredValues,
1903                                         InsertPos->getMask(), NeedsMaskForGaps);
1904     VPIG->insertBefore(InsertPos);
1905 
1906     unsigned J = 0;
1907     for (unsigned i = 0; i < IG->getFactor(); ++i)
1908       if (Instruction *Member = IG->getMember(i)) {
1909         VPRecipeBase *MemberR = RecipeBuilder.getRecipe(Member);
1910         if (!Member->getType()->isVoidTy()) {
1911           VPValue *OriginalV = MemberR->getVPSingleValue();
1912           OriginalV->replaceAllUsesWith(VPIG->getVPValue(J));
1913           J++;
1914         }
1915         MemberR->eraseFromParent();
1916       }
1917   }
1918 }
1919 
1920 void VPlanTransforms::convertToConcreteRecipes(VPlan &Plan) {
1921   for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(
1922            vp_depth_first_deep(Plan.getEntry()))) {
1923     for (VPRecipeBase &R : make_early_inc_range(VPBB->phis())) {
1924       if (!isa<VPCanonicalIVPHIRecipe, VPEVLBasedIVPHIRecipe>(&R))
1925         continue;
1926       auto *PhiR = cast<VPHeaderPHIRecipe>(&R);
1927       StringRef Name =
1928           isa<VPCanonicalIVPHIRecipe>(PhiR) ? "index" : "evl.based.iv";
1929       auto *ScalarR =
1930           new VPScalarPHIRecipe(PhiR->getStartValue(), PhiR->getBackedgeValue(),
1931                                 PhiR->getDebugLoc(), Name);
1932       ScalarR->insertBefore(PhiR);
1933       PhiR->replaceAllUsesWith(ScalarR);
1934       PhiR->eraseFromParent();
1935     }
1936   }
1937 }
1938 
1939 void VPlanTransforms::handleUncountableEarlyExit(
1940     VPlan &Plan, ScalarEvolution &SE, Loop *OrigLoop,
1941     BasicBlock *UncountableExitingBlock, VPRecipeBuilder &RecipeBuilder) {
1942   VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
1943   auto *LatchVPBB = cast<VPBasicBlock>(LoopRegion->getExiting());
1944   VPBuilder Builder(LatchVPBB->getTerminator());
1945   auto *MiddleVPBB = Plan.getMiddleBlock();
1946   VPValue *IsEarlyExitTaken = nullptr;
1947 
1948   // Process the uncountable exiting block. Update IsEarlyExitTaken, which
1949   // tracks if the uncountable early exit has been taken. Also split the middle
1950   // block and have it conditionally branch to the early exit block if
1951   // EarlyExitTaken.
1952   auto *EarlyExitingBranch =
1953       cast<BranchInst>(UncountableExitingBlock->getTerminator());
1954   BasicBlock *TrueSucc = EarlyExitingBranch->getSuccessor(0);
1955   BasicBlock *FalseSucc = EarlyExitingBranch->getSuccessor(1);
1956 
1957   // The early exit block may or may not be the same as the "countable" exit
1958   // block. Creates a new VPIRBB for the early exit block in case it is distinct
1959   // from the countable exit block.
1960   // TODO: Introduce both exit blocks during VPlan skeleton construction.
1961   VPIRBasicBlock *VPEarlyExitBlock;
1962   if (OrigLoop->getUniqueExitBlock()) {
1963     VPEarlyExitBlock = cast<VPIRBasicBlock>(MiddleVPBB->getSuccessors()[0]);
1964   } else {
1965     VPEarlyExitBlock = Plan.createVPIRBasicBlock(
1966         !OrigLoop->contains(TrueSucc) ? TrueSucc : FalseSucc);
1967   }
1968 
1969   VPValue *EarlyExitNotTakenCond = RecipeBuilder.getBlockInMask(
1970       OrigLoop->contains(TrueSucc) ? TrueSucc : FalseSucc);
1971   auto *EarlyExitTakenCond = Builder.createNot(EarlyExitNotTakenCond);
1972   IsEarlyExitTaken =
1973       Builder.createNaryOp(VPInstruction::AnyOf, {EarlyExitTakenCond});
1974 
1975   VPBasicBlock *NewMiddle = Plan.createVPBasicBlock("middle.split");
1976   VPBlockUtils::insertOnEdge(LoopRegion, MiddleVPBB, NewMiddle);
1977   VPBlockUtils::connectBlocks(NewMiddle, VPEarlyExitBlock);
1978   NewMiddle->swapSuccessors();
1979 
1980   VPBuilder MiddleBuilder(NewMiddle);
1981   MiddleBuilder.createNaryOp(VPInstruction::BranchOnCond, {IsEarlyExitTaken});
1982 
1983   // Replace the condition controlling the non-early exit from the vector loop
1984   // with one exiting if either the original condition of the vector latch is
1985   // true or the early exit has been taken.
1986   auto *LatchExitingBranch = cast<VPInstruction>(LatchVPBB->getTerminator());
1987   assert(LatchExitingBranch->getOpcode() == VPInstruction::BranchOnCount &&
1988          "Unexpected terminator");
1989   auto *IsLatchExitTaken =
1990       Builder.createICmp(CmpInst::ICMP_EQ, LatchExitingBranch->getOperand(0),
1991                          LatchExitingBranch->getOperand(1));
1992   auto *AnyExitTaken = Builder.createNaryOp(
1993       Instruction::Or, {IsEarlyExitTaken, IsLatchExitTaken});
1994   Builder.createNaryOp(VPInstruction::BranchOnCond, AnyExitTaken);
1995   LatchExitingBranch->eraseFromParent();
1996 }
1997