xref: /llvm-project/llvm/lib/Transforms/Vectorize/VPlanTransforms.cpp (revision 7ffb691595a3108f72023ae0051487df25a85fc3)
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<VPHeaderPHIRecipe>(&Phi);
596     if (!PhiR)
597       break;
598 
599     // Check if any uniform VPReplicateRecipes using the phi recipe are used by
600     // ExtractFromEnd. Those must be replaced by a regular VPReplicateRecipe to
601     // ensure the final value is available.
602     // TODO: Remove once uniformity analysis is done on VPlan.
603     for (VPUser *U : collectUsersRecursively(PhiR)) {
604       auto *ExitIRI = dyn_cast<VPIRInstruction>(U);
605       VPValue *Op;
606       if (!ExitIRI || !match(ExitIRI->getOperand(0),
607                              m_VPInstruction<VPInstruction::ExtractFromEnd>(
608                                  m_VPValue(Op), m_VPValue())))
609         continue;
610       auto *RepR = dyn_cast<VPReplicateRecipe>(Op);
611       if (!RepR || !RepR->isUniform())
612         continue;
613       assert(!RepR->isPredicated() && "RepR must not be predicated");
614       Instruction *I = RepR->getUnderlyingInstr();
615       auto *Clone =
616           new VPReplicateRecipe(I, RepR->operands(), /*IsUniform*/ false);
617       Clone->insertAfter(RepR);
618       RepR->replaceAllUsesWith(Clone);
619     }
620 
621     // Replace wide pointer inductions which have only their scalars used by
622     // PtrAdd(IndStart, ScalarIVSteps (0, Step)).
623     if (auto *PtrIV = dyn_cast<VPWidenPointerInductionRecipe>(&Phi)) {
624       if (!PtrIV->onlyScalarsGenerated(Plan.hasScalableVF()))
625         continue;
626 
627       const InductionDescriptor &ID = PtrIV->getInductionDescriptor();
628       VPValue *StartV =
629           Plan.getOrAddLiveIn(ConstantInt::get(ID.getStep()->getType(), 0));
630       VPValue *StepV = PtrIV->getOperand(1);
631       VPScalarIVStepsRecipe *Steps = createScalarIVSteps(
632           Plan, InductionDescriptor::IK_IntInduction, Instruction::Add, nullptr,
633           nullptr, StartV, StepV, PtrIV->getDebugLoc(), Builder);
634 
635       VPValue *PtrAdd = Builder.createPtrAdd(PtrIV->getStartValue(), Steps,
636                                              PtrIV->getDebugLoc(), "next.gep");
637 
638       PtrIV->replaceAllUsesWith(PtrAdd);
639       continue;
640     }
641 
642     // Replace widened induction with scalar steps for users that only use
643     // scalars.
644     auto *WideIV = dyn_cast<VPWidenIntOrFpInductionRecipe>(&Phi);
645     if (!WideIV)
646       continue;
647     if (HasOnlyVectorVFs && none_of(WideIV->users(), [WideIV](VPUser *U) {
648           return U->usesScalars(WideIV);
649         }))
650       continue;
651 
652     const InductionDescriptor &ID = WideIV->getInductionDescriptor();
653     VPScalarIVStepsRecipe *Steps = createScalarIVSteps(
654         Plan, ID.getKind(), ID.getInductionOpcode(),
655         dyn_cast_or_null<FPMathOperator>(ID.getInductionBinOp()),
656         WideIV->getTruncInst(), WideIV->getStartValue(), WideIV->getStepValue(),
657         WideIV->getDebugLoc(), Builder);
658 
659     // Update scalar users of IV to use Step instead.
660     if (!HasOnlyVectorVFs)
661       WideIV->replaceAllUsesWith(Steps);
662     else
663       WideIV->replaceUsesWithIf(Steps, [WideIV](VPUser &U, unsigned) {
664         return U.usesScalars(WideIV);
665       });
666   }
667 }
668 
669 /// Remove redundant EpxandSCEVRecipes in \p Plan's entry block by replacing
670 /// them with already existing recipes expanding the same SCEV expression.
671 static void removeRedundantExpandSCEVRecipes(VPlan &Plan) {
672   DenseMap<const SCEV *, VPValue *> SCEV2VPV;
673 
674   for (VPRecipeBase &R :
675        make_early_inc_range(*Plan.getEntry()->getEntryBasicBlock())) {
676     auto *ExpR = dyn_cast<VPExpandSCEVRecipe>(&R);
677     if (!ExpR)
678       continue;
679 
680     auto I = SCEV2VPV.insert({ExpR->getSCEV(), ExpR});
681     if (I.second)
682       continue;
683     ExpR->replaceAllUsesWith(I.first->second);
684     ExpR->eraseFromParent();
685   }
686 }
687 
688 static void recursivelyDeleteDeadRecipes(VPValue *V) {
689   SmallVector<VPValue *> WorkList;
690   SmallPtrSet<VPValue *, 8> Seen;
691   WorkList.push_back(V);
692 
693   while (!WorkList.empty()) {
694     VPValue *Cur = WorkList.pop_back_val();
695     if (!Seen.insert(Cur).second)
696       continue;
697     VPRecipeBase *R = Cur->getDefiningRecipe();
698     if (!R)
699       continue;
700     if (!isDeadRecipe(*R))
701       continue;
702     WorkList.append(R->op_begin(), R->op_end());
703     R->eraseFromParent();
704   }
705 }
706 
707 /// Try to simplify recipe \p R.
708 static void simplifyRecipe(VPRecipeBase &R, VPTypeAnalysis &TypeInfo) {
709   using namespace llvm::VPlanPatternMatch;
710 
711   if (auto *Blend = dyn_cast<VPBlendRecipe>(&R)) {
712     // Try to remove redundant blend recipes.
713     SmallPtrSet<VPValue *, 4> UniqueValues;
714     if (Blend->isNormalized() || !match(Blend->getMask(0), m_False()))
715       UniqueValues.insert(Blend->getIncomingValue(0));
716     for (unsigned I = 1; I != Blend->getNumIncomingValues(); ++I)
717       if (!match(Blend->getMask(I), m_False()))
718         UniqueValues.insert(Blend->getIncomingValue(I));
719 
720     if (UniqueValues.size() == 1) {
721       Blend->replaceAllUsesWith(*UniqueValues.begin());
722       Blend->eraseFromParent();
723       return;
724     }
725 
726     if (Blend->isNormalized())
727       return;
728 
729     // Normalize the blend so its first incoming value is used as the initial
730     // value with the others blended into it.
731 
732     unsigned StartIndex = 0;
733     for (unsigned I = 0; I != Blend->getNumIncomingValues(); ++I) {
734       // If a value's mask is used only by the blend then is can be deadcoded.
735       // TODO: Find the most expensive mask that can be deadcoded, or a mask
736       // that's used by multiple blends where it can be removed from them all.
737       VPValue *Mask = Blend->getMask(I);
738       if (Mask->getNumUsers() == 1 && !match(Mask, m_False())) {
739         StartIndex = I;
740         break;
741       }
742     }
743 
744     SmallVector<VPValue *, 4> OperandsWithMask;
745     OperandsWithMask.push_back(Blend->getIncomingValue(StartIndex));
746 
747     for (unsigned I = 0; I != Blend->getNumIncomingValues(); ++I) {
748       if (I == StartIndex)
749         continue;
750       OperandsWithMask.push_back(Blend->getIncomingValue(I));
751       OperandsWithMask.push_back(Blend->getMask(I));
752     }
753 
754     auto *NewBlend = new VPBlendRecipe(
755         cast<PHINode>(Blend->getUnderlyingValue()), OperandsWithMask);
756     NewBlend->insertBefore(&R);
757 
758     VPValue *DeadMask = Blend->getMask(StartIndex);
759     Blend->replaceAllUsesWith(NewBlend);
760     Blend->eraseFromParent();
761     recursivelyDeleteDeadRecipes(DeadMask);
762     return;
763   }
764 
765   VPValue *A;
766   if (match(&R, m_Trunc(m_ZExtOrSExt(m_VPValue(A))))) {
767     VPValue *Trunc = R.getVPSingleValue();
768     Type *TruncTy = TypeInfo.inferScalarType(Trunc);
769     Type *ATy = TypeInfo.inferScalarType(A);
770     if (TruncTy == ATy) {
771       Trunc->replaceAllUsesWith(A);
772     } else {
773       // Don't replace a scalarizing recipe with a widened cast.
774       if (isa<VPReplicateRecipe>(&R))
775         return;
776       if (ATy->getScalarSizeInBits() < TruncTy->getScalarSizeInBits()) {
777 
778         unsigned ExtOpcode = match(R.getOperand(0), m_SExt(m_VPValue()))
779                                  ? Instruction::SExt
780                                  : Instruction::ZExt;
781         auto *VPC =
782             new VPWidenCastRecipe(Instruction::CastOps(ExtOpcode), A, TruncTy);
783         if (auto *UnderlyingExt = R.getOperand(0)->getUnderlyingValue()) {
784           // UnderlyingExt has distinct return type, used to retain legacy cost.
785           VPC->setUnderlyingValue(UnderlyingExt);
786         }
787         VPC->insertBefore(&R);
788         Trunc->replaceAllUsesWith(VPC);
789       } else if (ATy->getScalarSizeInBits() > TruncTy->getScalarSizeInBits()) {
790         auto *VPC = new VPWidenCastRecipe(Instruction::Trunc, A, TruncTy);
791         VPC->insertBefore(&R);
792         Trunc->replaceAllUsesWith(VPC);
793       }
794     }
795 #ifndef NDEBUG
796     // Verify that the cached type info is for both A and its users is still
797     // accurate by comparing it to freshly computed types.
798     VPTypeAnalysis TypeInfo2(
799         R.getParent()->getPlan()->getCanonicalIV()->getScalarType());
800     assert(TypeInfo.inferScalarType(A) == TypeInfo2.inferScalarType(A));
801     for (VPUser *U : A->users()) {
802       auto *R = cast<VPRecipeBase>(U);
803       for (VPValue *VPV : R->definedValues())
804         assert(TypeInfo.inferScalarType(VPV) == TypeInfo2.inferScalarType(VPV));
805     }
806 #endif
807   }
808 
809   // Simplify (X && Y) || (X && !Y) -> X.
810   // TODO: Split up into simpler, modular combines: (X && Y) || (X && Z) into X
811   // && (Y || Z) and (X || !X) into true. This requires queuing newly created
812   // recipes to be visited during simplification.
813   VPValue *X, *Y, *X1, *Y1;
814   if (match(&R,
815             m_c_BinaryOr(m_LogicalAnd(m_VPValue(X), m_VPValue(Y)),
816                          m_LogicalAnd(m_VPValue(X1), m_Not(m_VPValue(Y1))))) &&
817       X == X1 && Y == Y1) {
818     R.getVPSingleValue()->replaceAllUsesWith(X);
819     R.eraseFromParent();
820     return;
821   }
822 
823   if (match(&R, m_c_Mul(m_VPValue(A), m_SpecificInt(1))))
824     return R.getVPSingleValue()->replaceAllUsesWith(A);
825 
826   if (match(&R, m_Not(m_Not(m_VPValue(A)))))
827     return R.getVPSingleValue()->replaceAllUsesWith(A);
828 
829   // Remove redundant DerviedIVs, that is 0 + A * 1 -> A and 0 + 0 * x -> 0.
830   if ((match(&R,
831              m_DerivedIV(m_SpecificInt(0), m_VPValue(A), m_SpecificInt(1))) ||
832        match(&R,
833              m_DerivedIV(m_SpecificInt(0), m_SpecificInt(0), m_VPValue()))) &&
834       TypeInfo.inferScalarType(R.getOperand(1)) ==
835           TypeInfo.inferScalarType(R.getVPSingleValue()))
836     return R.getVPSingleValue()->replaceAllUsesWith(R.getOperand(1));
837 }
838 
839 /// Try to simplify the recipes in \p Plan. Use \p CanonicalIVTy as type for all
840 /// un-typed live-ins in VPTypeAnalysis.
841 static void simplifyRecipes(VPlan &Plan, Type *CanonicalIVTy) {
842   ReversePostOrderTraversal<VPBlockDeepTraversalWrapper<VPBlockBase *>> RPOT(
843       Plan.getEntry());
844   VPTypeAnalysis TypeInfo(CanonicalIVTy);
845   for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(RPOT)) {
846     for (VPRecipeBase &R : make_early_inc_range(*VPBB)) {
847       simplifyRecipe(R, TypeInfo);
848     }
849   }
850 }
851 
852 void VPlanTransforms::optimizeForVFAndUF(VPlan &Plan, ElementCount BestVF,
853                                          unsigned BestUF,
854                                          PredicatedScalarEvolution &PSE) {
855   assert(Plan.hasVF(BestVF) && "BestVF is not available in Plan");
856   assert(Plan.hasUF(BestUF) && "BestUF is not available in Plan");
857   VPRegionBlock *VectorRegion = Plan.getVectorLoopRegion();
858   VPBasicBlock *ExitingVPBB = VectorRegion->getExitingBasicBlock();
859   auto *Term = &ExitingVPBB->back();
860   // Try to simplify the branch condition if TC <= VF * UF when preparing to
861   // execute the plan for the main vector loop. We only do this if the
862   // terminator is:
863   //  1. BranchOnCount, or
864   //  2. BranchOnCond where the input is Not(ActiveLaneMask).
865   using namespace llvm::VPlanPatternMatch;
866   if (!match(Term, m_BranchOnCount(m_VPValue(), m_VPValue())) &&
867       !match(Term,
868              m_BranchOnCond(m_Not(m_ActiveLaneMask(m_VPValue(), m_VPValue())))))
869     return;
870 
871   ScalarEvolution &SE = *PSE.getSE();
872   const SCEV *TripCount =
873       vputils::getSCEVExprForVPValue(Plan.getTripCount(), SE);
874   assert(!isa<SCEVCouldNotCompute>(TripCount) &&
875          "Trip count SCEV must be computable");
876   ElementCount NumElements = BestVF.multiplyCoefficientBy(BestUF);
877   const SCEV *C = SE.getElementCount(TripCount->getType(), NumElements);
878   if (TripCount->isZero() ||
879       !SE.isKnownPredicate(CmpInst::ICMP_ULE, TripCount, C))
880     return;
881 
882   // The vector loop region only executes once. If possible, completely remove
883   // the region, otherwise replace the terminator controlling the latch with
884   // (BranchOnCond true).
885   auto *Header = cast<VPBasicBlock>(VectorRegion->getEntry());
886   auto *CanIVTy = Plan.getCanonicalIV()->getScalarType();
887   if (all_of(
888           Header->phis(),
889           IsaPred<VPCanonicalIVPHIRecipe, VPFirstOrderRecurrencePHIRecipe>)) {
890     for (VPRecipeBase &HeaderR : make_early_inc_range(Header->phis())) {
891       auto *HeaderPhiR = cast<VPHeaderPHIRecipe>(&HeaderR);
892       HeaderPhiR->replaceAllUsesWith(HeaderPhiR->getStartValue());
893       HeaderPhiR->eraseFromParent();
894     }
895 
896     VPBlockBase *Preheader = VectorRegion->getSinglePredecessor();
897     VPBlockBase *Exit = VectorRegion->getSingleSuccessor();
898     VPBlockUtils::disconnectBlocks(Preheader, VectorRegion);
899     VPBlockUtils::disconnectBlocks(VectorRegion, Exit);
900 
901     for (VPBlockBase *B : vp_depth_first_shallow(VectorRegion->getEntry()))
902       B->setParent(nullptr);
903 
904     VPBlockUtils::connectBlocks(Preheader, Header);
905     VPBlockUtils::connectBlocks(ExitingVPBB, Exit);
906     simplifyRecipes(Plan, CanIVTy);
907   } else {
908     // The vector region contains header phis for which we cannot remove the
909     // loop region yet.
910     LLVMContext &Ctx = SE.getContext();
911     auto *BOC = new VPInstruction(
912         VPInstruction::BranchOnCond,
913         {Plan.getOrAddLiveIn(ConstantInt::getTrue(Ctx))}, Term->getDebugLoc());
914     ExitingVPBB->appendRecipe(BOC);
915   }
916 
917   Term->eraseFromParent();
918   VPlanTransforms::removeDeadRecipes(Plan);
919 
920   Plan.setVF(BestVF);
921   Plan.setUF(BestUF);
922   // TODO: Further simplifications are possible
923   //      1. Replace inductions with constants.
924   //      2. Replace vector loop region with VPBasicBlock.
925 }
926 
927 /// Sink users of \p FOR after the recipe defining the previous value \p
928 /// Previous of the recurrence. \returns true if all users of \p FOR could be
929 /// re-arranged as needed or false if it is not possible.
930 static bool
931 sinkRecurrenceUsersAfterPrevious(VPFirstOrderRecurrencePHIRecipe *FOR,
932                                  VPRecipeBase *Previous,
933                                  VPDominatorTree &VPDT) {
934   // Collect recipes that need sinking.
935   SmallVector<VPRecipeBase *> WorkList;
936   SmallPtrSet<VPRecipeBase *, 8> Seen;
937   Seen.insert(Previous);
938   auto TryToPushSinkCandidate = [&](VPRecipeBase *SinkCandidate) {
939     // The previous value must not depend on the users of the recurrence phi. In
940     // that case, FOR is not a fixed order recurrence.
941     if (SinkCandidate == Previous)
942       return false;
943 
944     if (isa<VPHeaderPHIRecipe>(SinkCandidate) ||
945         !Seen.insert(SinkCandidate).second ||
946         VPDT.properlyDominates(Previous, SinkCandidate))
947       return true;
948 
949     if (SinkCandidate->mayHaveSideEffects())
950       return false;
951 
952     WorkList.push_back(SinkCandidate);
953     return true;
954   };
955 
956   // Recursively sink users of FOR after Previous.
957   WorkList.push_back(FOR);
958   for (unsigned I = 0; I != WorkList.size(); ++I) {
959     VPRecipeBase *Current = WorkList[I];
960     assert(Current->getNumDefinedValues() == 1 &&
961            "only recipes with a single defined value expected");
962 
963     for (VPUser *User : Current->getVPSingleValue()->users()) {
964       if (!TryToPushSinkCandidate(cast<VPRecipeBase>(User)))
965         return false;
966     }
967   }
968 
969   // Keep recipes to sink ordered by dominance so earlier instructions are
970   // processed first.
971   sort(WorkList, [&VPDT](const VPRecipeBase *A, const VPRecipeBase *B) {
972     return VPDT.properlyDominates(A, B);
973   });
974 
975   for (VPRecipeBase *SinkCandidate : WorkList) {
976     if (SinkCandidate == FOR)
977       continue;
978 
979     SinkCandidate->moveAfter(Previous);
980     Previous = SinkCandidate;
981   }
982   return true;
983 }
984 
985 /// Try to hoist \p Previous and its operands before all users of \p FOR.
986 static bool hoistPreviousBeforeFORUsers(VPFirstOrderRecurrencePHIRecipe *FOR,
987                                         VPRecipeBase *Previous,
988                                         VPDominatorTree &VPDT) {
989   if (Previous->mayHaveSideEffects() || Previous->mayReadFromMemory())
990     return false;
991 
992   // Collect recipes that need hoisting.
993   SmallVector<VPRecipeBase *> HoistCandidates;
994   SmallPtrSet<VPRecipeBase *, 8> Visited;
995   VPRecipeBase *HoistPoint = nullptr;
996   // Find the closest hoist point by looking at all users of FOR and selecting
997   // the recipe dominating all other users.
998   for (VPUser *U : FOR->users()) {
999     auto *R = cast<VPRecipeBase>(U);
1000     if (!HoistPoint || VPDT.properlyDominates(R, HoistPoint))
1001       HoistPoint = R;
1002   }
1003   assert(all_of(FOR->users(),
1004                 [&VPDT, HoistPoint](VPUser *U) {
1005                   auto *R = cast<VPRecipeBase>(U);
1006                   return HoistPoint == R ||
1007                          VPDT.properlyDominates(HoistPoint, R);
1008                 }) &&
1009          "HoistPoint must dominate all users of FOR");
1010 
1011   auto NeedsHoisting = [HoistPoint, &VPDT,
1012                         &Visited](VPValue *HoistCandidateV) -> VPRecipeBase * {
1013     VPRecipeBase *HoistCandidate = HoistCandidateV->getDefiningRecipe();
1014     if (!HoistCandidate)
1015       return nullptr;
1016     VPRegionBlock *EnclosingLoopRegion =
1017         HoistCandidate->getParent()->getEnclosingLoopRegion();
1018     assert((!HoistCandidate->getParent()->getParent() ||
1019             HoistCandidate->getParent()->getParent() == EnclosingLoopRegion) &&
1020            "CFG in VPlan should still be flat, without replicate regions");
1021     // Hoist candidate was already visited, no need to hoist.
1022     if (!Visited.insert(HoistCandidate).second)
1023       return nullptr;
1024 
1025     // Candidate is outside loop region or a header phi, dominates FOR users w/o
1026     // hoisting.
1027     if (!EnclosingLoopRegion || isa<VPHeaderPHIRecipe>(HoistCandidate))
1028       return nullptr;
1029 
1030     // If we reached a recipe that dominates HoistPoint, we don't need to
1031     // hoist the recipe.
1032     if (VPDT.properlyDominates(HoistCandidate, HoistPoint))
1033       return nullptr;
1034     return HoistCandidate;
1035   };
1036   auto CanHoist = [&](VPRecipeBase *HoistCandidate) {
1037     // Avoid hoisting candidates with side-effects, as we do not yet analyze
1038     // associated dependencies.
1039     return !HoistCandidate->mayHaveSideEffects();
1040   };
1041 
1042   if (!NeedsHoisting(Previous->getVPSingleValue()))
1043     return true;
1044 
1045   // Recursively try to hoist Previous and its operands before all users of FOR.
1046   HoistCandidates.push_back(Previous);
1047 
1048   for (unsigned I = 0; I != HoistCandidates.size(); ++I) {
1049     VPRecipeBase *Current = HoistCandidates[I];
1050     assert(Current->getNumDefinedValues() == 1 &&
1051            "only recipes with a single defined value expected");
1052     if (!CanHoist(Current))
1053       return false;
1054 
1055     for (VPValue *Op : Current->operands()) {
1056       // If we reach FOR, it means the original Previous depends on some other
1057       // recurrence that in turn depends on FOR. If that is the case, we would
1058       // also need to hoist recipes involving the other FOR, which may break
1059       // dependencies.
1060       if (Op == FOR)
1061         return false;
1062 
1063       if (auto *R = NeedsHoisting(Op))
1064         HoistCandidates.push_back(R);
1065     }
1066   }
1067 
1068   // Order recipes to hoist by dominance so earlier instructions are processed
1069   // first.
1070   sort(HoistCandidates, [&VPDT](const VPRecipeBase *A, const VPRecipeBase *B) {
1071     return VPDT.properlyDominates(A, B);
1072   });
1073 
1074   for (VPRecipeBase *HoistCandidate : HoistCandidates) {
1075     HoistCandidate->moveBefore(*HoistPoint->getParent(),
1076                                HoistPoint->getIterator());
1077   }
1078 
1079   return true;
1080 }
1081 
1082 bool VPlanTransforms::adjustFixedOrderRecurrences(VPlan &Plan,
1083                                                   VPBuilder &LoopBuilder) {
1084   VPDominatorTree VPDT;
1085   VPDT.recalculate(Plan);
1086 
1087   SmallVector<VPFirstOrderRecurrencePHIRecipe *> RecurrencePhis;
1088   for (VPRecipeBase &R :
1089        Plan.getVectorLoopRegion()->getEntry()->getEntryBasicBlock()->phis())
1090     if (auto *FOR = dyn_cast<VPFirstOrderRecurrencePHIRecipe>(&R))
1091       RecurrencePhis.push_back(FOR);
1092 
1093   for (VPFirstOrderRecurrencePHIRecipe *FOR : RecurrencePhis) {
1094     SmallPtrSet<VPFirstOrderRecurrencePHIRecipe *, 4> SeenPhis;
1095     VPRecipeBase *Previous = FOR->getBackedgeValue()->getDefiningRecipe();
1096     // Fixed-order recurrences do not contain cycles, so this loop is guaranteed
1097     // to terminate.
1098     while (auto *PrevPhi =
1099                dyn_cast_or_null<VPFirstOrderRecurrencePHIRecipe>(Previous)) {
1100       assert(PrevPhi->getParent() == FOR->getParent());
1101       assert(SeenPhis.insert(PrevPhi).second);
1102       Previous = PrevPhi->getBackedgeValue()->getDefiningRecipe();
1103     }
1104 
1105     if (!sinkRecurrenceUsersAfterPrevious(FOR, Previous, VPDT) &&
1106         !hoistPreviousBeforeFORUsers(FOR, Previous, VPDT))
1107       return false;
1108 
1109     // Introduce a recipe to combine the incoming and previous values of a
1110     // fixed-order recurrence.
1111     VPBasicBlock *InsertBlock = Previous->getParent();
1112     if (isa<VPHeaderPHIRecipe>(Previous))
1113       LoopBuilder.setInsertPoint(InsertBlock, InsertBlock->getFirstNonPhi());
1114     else
1115       LoopBuilder.setInsertPoint(InsertBlock,
1116                                  std::next(Previous->getIterator()));
1117 
1118     auto *RecurSplice = cast<VPInstruction>(
1119         LoopBuilder.createNaryOp(VPInstruction::FirstOrderRecurrenceSplice,
1120                                  {FOR, FOR->getBackedgeValue()}));
1121 
1122     FOR->replaceAllUsesWith(RecurSplice);
1123     // Set the first operand of RecurSplice to FOR again, after replacing
1124     // all users.
1125     RecurSplice->setOperand(0, FOR);
1126   }
1127   return true;
1128 }
1129 
1130 void VPlanTransforms::clearReductionWrapFlags(VPlan &Plan) {
1131   for (VPRecipeBase &R :
1132        Plan.getVectorLoopRegion()->getEntryBasicBlock()->phis()) {
1133     auto *PhiR = dyn_cast<VPReductionPHIRecipe>(&R);
1134     if (!PhiR)
1135       continue;
1136     const RecurrenceDescriptor &RdxDesc = PhiR->getRecurrenceDescriptor();
1137     RecurKind RK = RdxDesc.getRecurrenceKind();
1138     if (RK != RecurKind::Add && RK != RecurKind::Mul)
1139       continue;
1140 
1141     for (VPUser *U : collectUsersRecursively(PhiR))
1142       if (auto *RecWithFlags = dyn_cast<VPRecipeWithIRFlags>(U)) {
1143         RecWithFlags->dropPoisonGeneratingFlags();
1144       }
1145   }
1146 }
1147 
1148 /// Move loop-invariant recipes out of the vector loop region in \p Plan.
1149 static void licm(VPlan &Plan) {
1150   VPBasicBlock *Preheader = Plan.getVectorPreheader();
1151 
1152   // Return true if we do not know how to (mechanically) hoist a given recipe
1153   // out of a loop region. Does not address legality concerns such as aliasing
1154   // or speculation safety.
1155   auto CannotHoistRecipe = [](VPRecipeBase &R) {
1156     // Allocas cannot be hoisted.
1157     auto *RepR = dyn_cast<VPReplicateRecipe>(&R);
1158     return RepR && RepR->getOpcode() == Instruction::Alloca;
1159   };
1160 
1161   // Hoist any loop invariant recipes from the vector loop region to the
1162   // preheader. Preform a shallow traversal of the vector loop region, to
1163   // exclude recipes in replicate regions.
1164   VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
1165   for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(
1166            vp_depth_first_shallow(LoopRegion->getEntry()))) {
1167     for (VPRecipeBase &R : make_early_inc_range(*VPBB)) {
1168       if (CannotHoistRecipe(R))
1169         continue;
1170       // TODO: Relax checks in the future, e.g. we could also hoist reads, if
1171       // their memory location is not modified in the vector loop.
1172       if (R.mayHaveSideEffects() || R.mayReadFromMemory() || R.isPhi() ||
1173           any_of(R.operands(), [](VPValue *Op) {
1174             return !Op->isDefinedOutsideLoopRegions();
1175           }))
1176         continue;
1177       R.moveBefore(*Preheader, Preheader->end());
1178     }
1179   }
1180 }
1181 
1182 void VPlanTransforms::truncateToMinimalBitwidths(
1183     VPlan &Plan, const MapVector<Instruction *, uint64_t> &MinBWs) {
1184 #ifndef NDEBUG
1185   // Count the processed recipes and cross check the count later with MinBWs
1186   // size, to make sure all entries in MinBWs have been handled.
1187   unsigned NumProcessedRecipes = 0;
1188 #endif
1189   // Keep track of created truncates, so they can be re-used. Note that we
1190   // cannot use RAUW after creating a new truncate, as this would could make
1191   // other uses have different types for their operands, making them invalidly
1192   // typed.
1193   DenseMap<VPValue *, VPWidenCastRecipe *> ProcessedTruncs;
1194   Type *CanonicalIVType = Plan.getCanonicalIV()->getScalarType();
1195   VPTypeAnalysis TypeInfo(CanonicalIVType);
1196   VPBasicBlock *PH = Plan.getVectorPreheader();
1197   for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(
1198            vp_depth_first_deep(Plan.getVectorLoopRegion()))) {
1199     for (VPRecipeBase &R : make_early_inc_range(*VPBB)) {
1200       if (!isa<VPWidenRecipe, VPWidenCastRecipe, VPReplicateRecipe,
1201                VPWidenSelectRecipe, VPWidenLoadRecipe>(&R))
1202         continue;
1203 
1204       VPValue *ResultVPV = R.getVPSingleValue();
1205       auto *UI = cast_or_null<Instruction>(ResultVPV->getUnderlyingValue());
1206       unsigned NewResSizeInBits = MinBWs.lookup(UI);
1207       if (!NewResSizeInBits)
1208         continue;
1209 
1210 #ifndef NDEBUG
1211       NumProcessedRecipes++;
1212 #endif
1213       // If the value wasn't vectorized, we must maintain the original scalar
1214       // type. Skip those here, after incrementing NumProcessedRecipes. Also
1215       // skip casts which do not need to be handled explicitly here, as
1216       // redundant casts will be removed during recipe simplification.
1217       if (isa<VPReplicateRecipe, VPWidenCastRecipe>(&R)) {
1218 #ifndef NDEBUG
1219         // If any of the operands is a live-in and not used by VPWidenRecipe or
1220         // VPWidenSelectRecipe, but in MinBWs, make sure it is counted as
1221         // processed as well. When MinBWs is currently constructed, there is no
1222         // information about whether recipes are widened or replicated and in
1223         // case they are reciplicated the operands are not truncated. Counting
1224         // them them here ensures we do not miss any recipes in MinBWs.
1225         // TODO: Remove once the analysis is done on VPlan.
1226         for (VPValue *Op : R.operands()) {
1227           if (!Op->isLiveIn())
1228             continue;
1229           auto *UV = dyn_cast_or_null<Instruction>(Op->getUnderlyingValue());
1230           if (UV && MinBWs.contains(UV) && !ProcessedTruncs.contains(Op) &&
1231               none_of(Op->users(),
1232                       IsaPred<VPWidenRecipe, VPWidenSelectRecipe>)) {
1233             // Add an entry to ProcessedTruncs to avoid counting the same
1234             // operand multiple times.
1235             ProcessedTruncs[Op] = nullptr;
1236             NumProcessedRecipes += 1;
1237           }
1238         }
1239 #endif
1240         continue;
1241       }
1242 
1243       Type *OldResTy = TypeInfo.inferScalarType(ResultVPV);
1244       unsigned OldResSizeInBits = OldResTy->getScalarSizeInBits();
1245       assert(OldResTy->isIntegerTy() && "only integer types supported");
1246       (void)OldResSizeInBits;
1247 
1248       LLVMContext &Ctx = CanonicalIVType->getContext();
1249       auto *NewResTy = IntegerType::get(Ctx, NewResSizeInBits);
1250 
1251       // Any wrapping introduced by shrinking this operation shouldn't be
1252       // considered undefined behavior. So, we can't unconditionally copy
1253       // arithmetic wrapping flags to VPW.
1254       if (auto *VPW = dyn_cast<VPRecipeWithIRFlags>(&R))
1255         VPW->dropPoisonGeneratingFlags();
1256 
1257       using namespace llvm::VPlanPatternMatch;
1258       if (OldResSizeInBits != NewResSizeInBits &&
1259           !match(&R, m_Binary<Instruction::ICmp>(m_VPValue(), m_VPValue()))) {
1260         // Extend result to original width.
1261         auto *Ext =
1262             new VPWidenCastRecipe(Instruction::ZExt, ResultVPV, OldResTy);
1263         Ext->insertAfter(&R);
1264         ResultVPV->replaceAllUsesWith(Ext);
1265         Ext->setOperand(0, ResultVPV);
1266         assert(OldResSizeInBits > NewResSizeInBits && "Nothing to shrink?");
1267       } else {
1268         assert(
1269             match(&R, m_Binary<Instruction::ICmp>(m_VPValue(), m_VPValue())) &&
1270             "Only ICmps should not need extending the result.");
1271       }
1272 
1273       assert(!isa<VPWidenStoreRecipe>(&R) && "stores cannot be narrowed");
1274       if (isa<VPWidenLoadRecipe>(&R))
1275         continue;
1276 
1277       // Shrink operands by introducing truncates as needed.
1278       unsigned StartIdx = isa<VPWidenSelectRecipe>(&R) ? 1 : 0;
1279       for (unsigned Idx = StartIdx; Idx != R.getNumOperands(); ++Idx) {
1280         auto *Op = R.getOperand(Idx);
1281         unsigned OpSizeInBits =
1282             TypeInfo.inferScalarType(Op)->getScalarSizeInBits();
1283         if (OpSizeInBits == NewResSizeInBits)
1284           continue;
1285         assert(OpSizeInBits > NewResSizeInBits && "nothing to truncate");
1286         auto [ProcessedIter, IterIsEmpty] =
1287             ProcessedTruncs.insert({Op, nullptr});
1288         VPWidenCastRecipe *NewOp =
1289             IterIsEmpty
1290                 ? new VPWidenCastRecipe(Instruction::Trunc, Op, NewResTy)
1291                 : ProcessedIter->second;
1292         R.setOperand(Idx, NewOp);
1293         if (!IterIsEmpty)
1294           continue;
1295         ProcessedIter->second = NewOp;
1296         if (!Op->isLiveIn()) {
1297           NewOp->insertBefore(&R);
1298         } else {
1299           PH->appendRecipe(NewOp);
1300 #ifndef NDEBUG
1301           auto *OpInst = dyn_cast<Instruction>(Op->getLiveInIRValue());
1302           bool IsContained = MinBWs.contains(OpInst);
1303           NumProcessedRecipes += IsContained;
1304 #endif
1305         }
1306       }
1307 
1308     }
1309   }
1310 
1311   assert(MinBWs.size() == NumProcessedRecipes &&
1312          "some entries in MinBWs haven't been processed");
1313 }
1314 
1315 void VPlanTransforms::optimize(VPlan &Plan) {
1316   removeRedundantCanonicalIVs(Plan);
1317   removeRedundantInductionCasts(Plan);
1318 
1319   simplifyRecipes(Plan, Plan.getCanonicalIV()->getScalarType());
1320   legalizeAndOptimizeInductions(Plan);
1321   removeRedundantExpandSCEVRecipes(Plan);
1322   simplifyRecipes(Plan, Plan.getCanonicalIV()->getScalarType());
1323   removeDeadRecipes(Plan);
1324 
1325   createAndOptimizeReplicateRegions(Plan);
1326   mergeBlocksIntoPredecessors(Plan);
1327   licm(Plan);
1328 }
1329 
1330 // Add a VPActiveLaneMaskPHIRecipe and related recipes to \p Plan and replace
1331 // the loop terminator with a branch-on-cond recipe with the negated
1332 // active-lane-mask as operand. Note that this turns the loop into an
1333 // uncountable one. Only the existing terminator is replaced, all other existing
1334 // recipes/users remain unchanged, except for poison-generating flags being
1335 // dropped from the canonical IV increment. Return the created
1336 // VPActiveLaneMaskPHIRecipe.
1337 //
1338 // The function uses the following definitions:
1339 //
1340 //  %TripCount = DataWithControlFlowWithoutRuntimeCheck ?
1341 //    calculate-trip-count-minus-VF (original TC) : original TC
1342 //  %IncrementValue = DataWithControlFlowWithoutRuntimeCheck ?
1343 //     CanonicalIVPhi : CanonicalIVIncrement
1344 //  %StartV is the canonical induction start value.
1345 //
1346 // The function adds the following recipes:
1347 //
1348 // vector.ph:
1349 //   %TripCount = calculate-trip-count-minus-VF (original TC)
1350 //       [if DataWithControlFlowWithoutRuntimeCheck]
1351 //   %EntryInc = canonical-iv-increment-for-part %StartV
1352 //   %EntryALM = active-lane-mask %EntryInc, %TripCount
1353 //
1354 // vector.body:
1355 //   ...
1356 //   %P = active-lane-mask-phi [ %EntryALM, %vector.ph ], [ %ALM, %vector.body ]
1357 //   ...
1358 //   %InLoopInc = canonical-iv-increment-for-part %IncrementValue
1359 //   %ALM = active-lane-mask %InLoopInc, TripCount
1360 //   %Negated = Not %ALM
1361 //   branch-on-cond %Negated
1362 //
1363 static VPActiveLaneMaskPHIRecipe *addVPLaneMaskPhiAndUpdateExitBranch(
1364     VPlan &Plan, bool DataAndControlFlowWithoutRuntimeCheck) {
1365   VPRegionBlock *TopRegion = Plan.getVectorLoopRegion();
1366   VPBasicBlock *EB = TopRegion->getExitingBasicBlock();
1367   auto *CanonicalIVPHI = Plan.getCanonicalIV();
1368   VPValue *StartV = CanonicalIVPHI->getStartValue();
1369 
1370   auto *CanonicalIVIncrement =
1371       cast<VPInstruction>(CanonicalIVPHI->getBackedgeValue());
1372   // TODO: Check if dropping the flags is needed if
1373   // !DataAndControlFlowWithoutRuntimeCheck.
1374   CanonicalIVIncrement->dropPoisonGeneratingFlags();
1375   DebugLoc DL = CanonicalIVIncrement->getDebugLoc();
1376   // We can't use StartV directly in the ActiveLaneMask VPInstruction, since
1377   // we have to take unrolling into account. Each part needs to start at
1378   //   Part * VF
1379   auto *VecPreheader = Plan.getVectorPreheader();
1380   VPBuilder Builder(VecPreheader);
1381 
1382   // Create the ActiveLaneMask instruction using the correct start values.
1383   VPValue *TC = Plan.getTripCount();
1384 
1385   VPValue *TripCount, *IncrementValue;
1386   if (!DataAndControlFlowWithoutRuntimeCheck) {
1387     // When the loop is guarded by a runtime overflow check for the loop
1388     // induction variable increment by VF, we can increment the value before
1389     // the get.active.lane mask and use the unmodified tripcount.
1390     IncrementValue = CanonicalIVIncrement;
1391     TripCount = TC;
1392   } else {
1393     // When avoiding a runtime check, the active.lane.mask inside the loop
1394     // uses a modified trip count and the induction variable increment is
1395     // done after the active.lane.mask intrinsic is called.
1396     IncrementValue = CanonicalIVPHI;
1397     TripCount = Builder.createNaryOp(VPInstruction::CalculateTripCountMinusVF,
1398                                      {TC}, DL);
1399   }
1400   auto *EntryIncrement = Builder.createOverflowingOp(
1401       VPInstruction::CanonicalIVIncrementForPart, {StartV}, {false, false}, DL,
1402       "index.part.next");
1403 
1404   // Create the active lane mask instruction in the VPlan preheader.
1405   auto *EntryALM =
1406       Builder.createNaryOp(VPInstruction::ActiveLaneMask, {EntryIncrement, TC},
1407                            DL, "active.lane.mask.entry");
1408 
1409   // Now create the ActiveLaneMaskPhi recipe in the main loop using the
1410   // preheader ActiveLaneMask instruction.
1411   auto *LaneMaskPhi = new VPActiveLaneMaskPHIRecipe(EntryALM, DebugLoc());
1412   LaneMaskPhi->insertAfter(CanonicalIVPHI);
1413 
1414   // Create the active lane mask for the next iteration of the loop before the
1415   // original terminator.
1416   VPRecipeBase *OriginalTerminator = EB->getTerminator();
1417   Builder.setInsertPoint(OriginalTerminator);
1418   auto *InLoopIncrement =
1419       Builder.createOverflowingOp(VPInstruction::CanonicalIVIncrementForPart,
1420                                   {IncrementValue}, {false, false}, DL);
1421   auto *ALM = Builder.createNaryOp(VPInstruction::ActiveLaneMask,
1422                                    {InLoopIncrement, TripCount}, DL,
1423                                    "active.lane.mask.next");
1424   LaneMaskPhi->addOperand(ALM);
1425 
1426   // Replace the original terminator with BranchOnCond. We have to invert the
1427   // mask here because a true condition means jumping to the exit block.
1428   auto *NotMask = Builder.createNot(ALM, DL);
1429   Builder.createNaryOp(VPInstruction::BranchOnCond, {NotMask}, DL);
1430   OriginalTerminator->eraseFromParent();
1431   return LaneMaskPhi;
1432 }
1433 
1434 /// Collect all VPValues representing a header mask through the (ICMP_ULE,
1435 /// WideCanonicalIV, backedge-taken-count) pattern.
1436 /// TODO: Introduce explicit recipe for header-mask instead of searching
1437 /// for the header-mask pattern manually.
1438 static SmallVector<VPValue *> collectAllHeaderMasks(VPlan &Plan) {
1439   SmallVector<VPValue *> WideCanonicalIVs;
1440   auto *FoundWidenCanonicalIVUser =
1441       find_if(Plan.getCanonicalIV()->users(),
1442               [](VPUser *U) { return isa<VPWidenCanonicalIVRecipe>(U); });
1443   assert(count_if(Plan.getCanonicalIV()->users(),
1444                   [](VPUser *U) { return isa<VPWidenCanonicalIVRecipe>(U); }) <=
1445              1 &&
1446          "Must have at most one VPWideCanonicalIVRecipe");
1447   if (FoundWidenCanonicalIVUser != Plan.getCanonicalIV()->users().end()) {
1448     auto *WideCanonicalIV =
1449         cast<VPWidenCanonicalIVRecipe>(*FoundWidenCanonicalIVUser);
1450     WideCanonicalIVs.push_back(WideCanonicalIV);
1451   }
1452 
1453   // Also include VPWidenIntOrFpInductionRecipes that represent a widened
1454   // version of the canonical induction.
1455   VPBasicBlock *HeaderVPBB = Plan.getVectorLoopRegion()->getEntryBasicBlock();
1456   for (VPRecipeBase &Phi : HeaderVPBB->phis()) {
1457     auto *WidenOriginalIV = dyn_cast<VPWidenIntOrFpInductionRecipe>(&Phi);
1458     if (WidenOriginalIV && WidenOriginalIV->isCanonical())
1459       WideCanonicalIVs.push_back(WidenOriginalIV);
1460   }
1461 
1462   // Walk users of wide canonical IVs and collect to all compares of the form
1463   // (ICMP_ULE, WideCanonicalIV, backedge-taken-count).
1464   SmallVector<VPValue *> HeaderMasks;
1465   for (auto *Wide : WideCanonicalIVs) {
1466     for (VPUser *U : SmallVector<VPUser *>(Wide->users())) {
1467       auto *HeaderMask = dyn_cast<VPInstruction>(U);
1468       if (!HeaderMask || !vputils::isHeaderMask(HeaderMask, Plan))
1469         continue;
1470 
1471       assert(HeaderMask->getOperand(0) == Wide &&
1472              "WidenCanonicalIV must be the first operand of the compare");
1473       HeaderMasks.push_back(HeaderMask);
1474     }
1475   }
1476   return HeaderMasks;
1477 }
1478 
1479 void VPlanTransforms::addActiveLaneMask(
1480     VPlan &Plan, bool UseActiveLaneMaskForControlFlow,
1481     bool DataAndControlFlowWithoutRuntimeCheck) {
1482   assert((!DataAndControlFlowWithoutRuntimeCheck ||
1483           UseActiveLaneMaskForControlFlow) &&
1484          "DataAndControlFlowWithoutRuntimeCheck implies "
1485          "UseActiveLaneMaskForControlFlow");
1486 
1487   auto *FoundWidenCanonicalIVUser =
1488       find_if(Plan.getCanonicalIV()->users(),
1489               [](VPUser *U) { return isa<VPWidenCanonicalIVRecipe>(U); });
1490   assert(FoundWidenCanonicalIVUser &&
1491          "Must have widened canonical IV when tail folding!");
1492   auto *WideCanonicalIV =
1493       cast<VPWidenCanonicalIVRecipe>(*FoundWidenCanonicalIVUser);
1494   VPSingleDefRecipe *LaneMask;
1495   if (UseActiveLaneMaskForControlFlow) {
1496     LaneMask = addVPLaneMaskPhiAndUpdateExitBranch(
1497         Plan, DataAndControlFlowWithoutRuntimeCheck);
1498   } else {
1499     VPBuilder B = VPBuilder::getToInsertAfter(WideCanonicalIV);
1500     LaneMask = B.createNaryOp(VPInstruction::ActiveLaneMask,
1501                               {WideCanonicalIV, Plan.getTripCount()}, nullptr,
1502                               "active.lane.mask");
1503   }
1504 
1505   // Walk users of WideCanonicalIV and replace all compares of the form
1506   // (ICMP_ULE, WideCanonicalIV, backedge-taken-count) with an
1507   // active-lane-mask.
1508   for (VPValue *HeaderMask : collectAllHeaderMasks(Plan))
1509     HeaderMask->replaceAllUsesWith(LaneMask);
1510 }
1511 
1512 /// Try to convert \p CurRecipe to a corresponding EVL-based recipe. Returns
1513 /// nullptr if no EVL-based recipe could be created.
1514 /// \p HeaderMask  Header Mask.
1515 /// \p CurRecipe   Recipe to be transform.
1516 /// \p TypeInfo    VPlan-based type analysis.
1517 /// \p AllOneMask  The vector mask parameter of vector-predication intrinsics.
1518 /// \p EVL         The explicit vector length parameter of vector-predication
1519 /// intrinsics.
1520 static VPRecipeBase *createEVLRecipe(VPValue *HeaderMask,
1521                                      VPRecipeBase &CurRecipe,
1522                                      VPTypeAnalysis &TypeInfo,
1523                                      VPValue &AllOneMask, VPValue &EVL) {
1524   using namespace llvm::VPlanPatternMatch;
1525   auto GetNewMask = [&](VPValue *OrigMask) -> VPValue * {
1526     assert(OrigMask && "Unmasked recipe when folding tail");
1527     return HeaderMask == OrigMask ? nullptr : OrigMask;
1528   };
1529 
1530   return TypeSwitch<VPRecipeBase *, VPRecipeBase *>(&CurRecipe)
1531       .Case<VPWidenLoadRecipe>([&](VPWidenLoadRecipe *L) {
1532         VPValue *NewMask = GetNewMask(L->getMask());
1533         return new VPWidenLoadEVLRecipe(*L, EVL, NewMask);
1534       })
1535       .Case<VPWidenStoreRecipe>([&](VPWidenStoreRecipe *S) {
1536         VPValue *NewMask = GetNewMask(S->getMask());
1537         return new VPWidenStoreEVLRecipe(*S, EVL, NewMask);
1538       })
1539       .Case<VPWidenRecipe>([&](VPWidenRecipe *W) -> VPRecipeBase * {
1540         unsigned Opcode = W->getOpcode();
1541         if (!Instruction::isBinaryOp(Opcode) && !Instruction::isUnaryOp(Opcode))
1542           return nullptr;
1543         return new VPWidenEVLRecipe(*W, EVL);
1544       })
1545       .Case<VPReductionRecipe>([&](VPReductionRecipe *Red) {
1546         VPValue *NewMask = GetNewMask(Red->getCondOp());
1547         return new VPReductionEVLRecipe(*Red, EVL, NewMask);
1548       })
1549       .Case<VPWidenIntrinsicRecipe, VPWidenCastRecipe>(
1550           [&](auto *CR) -> VPRecipeBase * {
1551             Intrinsic::ID VPID;
1552             if (auto *CallR = dyn_cast<VPWidenIntrinsicRecipe>(CR)) {
1553               VPID =
1554                   VPIntrinsic::getForIntrinsic(CallR->getVectorIntrinsicID());
1555             } else {
1556               auto *CastR = cast<VPWidenCastRecipe>(CR);
1557               VPID = VPIntrinsic::getForOpcode(CastR->getOpcode());
1558             }
1559 
1560             // Not all intrinsics have a corresponding VP intrinsic.
1561             if (VPID == Intrinsic::not_intrinsic)
1562               return nullptr;
1563             assert(VPIntrinsic::getMaskParamPos(VPID) &&
1564                    VPIntrinsic::getVectorLengthParamPos(VPID) &&
1565                    "Expected VP intrinsic to have mask and EVL");
1566 
1567             SmallVector<VPValue *> Ops(CR->operands());
1568             Ops.push_back(&AllOneMask);
1569             Ops.push_back(&EVL);
1570             return new VPWidenIntrinsicRecipe(
1571                 VPID, Ops, TypeInfo.inferScalarType(CR), CR->getDebugLoc());
1572           })
1573       .Case<VPWidenSelectRecipe>([&](VPWidenSelectRecipe *Sel) {
1574         SmallVector<VPValue *> Ops(Sel->operands());
1575         Ops.push_back(&EVL);
1576         return new VPWidenIntrinsicRecipe(Intrinsic::vp_select, Ops,
1577                                           TypeInfo.inferScalarType(Sel),
1578                                           Sel->getDebugLoc());
1579       })
1580       .Case<VPInstruction>([&](VPInstruction *VPI) -> VPRecipeBase * {
1581         VPValue *LHS, *RHS;
1582         // Transform select with a header mask condition
1583         //   select(header_mask, LHS, RHS)
1584         // into vector predication merge.
1585         //   vp.merge(all-true, LHS, RHS, EVL)
1586         if (!match(VPI, m_Select(m_Specific(HeaderMask), m_VPValue(LHS),
1587                                  m_VPValue(RHS))))
1588           return nullptr;
1589         // Use all true as the condition because this transformation is
1590         // limited to selects whose condition is a header mask.
1591         return new VPWidenIntrinsicRecipe(
1592             Intrinsic::vp_merge, {&AllOneMask, LHS, RHS, &EVL},
1593             TypeInfo.inferScalarType(LHS), VPI->getDebugLoc());
1594       })
1595       .Default([&](VPRecipeBase *R) { return nullptr; });
1596 }
1597 
1598 /// Replace recipes with their EVL variants.
1599 static void transformRecipestoEVLRecipes(VPlan &Plan, VPValue &EVL) {
1600   Type *CanonicalIVType = Plan.getCanonicalIV()->getScalarType();
1601   VPTypeAnalysis TypeInfo(CanonicalIVType);
1602   LLVMContext &Ctx = CanonicalIVType->getContext();
1603   VPValue *AllOneMask = Plan.getOrAddLiveIn(ConstantInt::getTrue(Ctx));
1604 
1605   for (VPUser *U : Plan.getVF().users()) {
1606     if (auto *R = dyn_cast<VPReverseVectorPointerRecipe>(U))
1607       R->setOperand(1, &EVL);
1608   }
1609 
1610   SmallVector<VPRecipeBase *> ToErase;
1611 
1612   for (VPValue *HeaderMask : collectAllHeaderMasks(Plan)) {
1613     for (VPUser *U : collectUsersRecursively(HeaderMask)) {
1614       auto *CurRecipe = cast<VPRecipeBase>(U);
1615       VPRecipeBase *EVLRecipe =
1616           createEVLRecipe(HeaderMask, *CurRecipe, TypeInfo, *AllOneMask, EVL);
1617       if (!EVLRecipe)
1618         continue;
1619 
1620       [[maybe_unused]] unsigned NumDefVal = EVLRecipe->getNumDefinedValues();
1621       assert(NumDefVal == CurRecipe->getNumDefinedValues() &&
1622              "New recipe must define the same number of values as the "
1623              "original.");
1624       assert(
1625           NumDefVal <= 1 &&
1626           "Only supports recipes with a single definition or without users.");
1627       EVLRecipe->insertBefore(CurRecipe);
1628       if (isa<VPSingleDefRecipe, VPWidenLoadEVLRecipe>(EVLRecipe)) {
1629         VPValue *CurVPV = CurRecipe->getVPSingleValue();
1630         CurVPV->replaceAllUsesWith(EVLRecipe->getVPSingleValue());
1631       }
1632       // Defer erasing recipes till the end so that we don't invalidate the
1633       // VPTypeAnalysis cache.
1634       ToErase.push_back(CurRecipe);
1635     }
1636   }
1637 
1638   for (VPRecipeBase *R : reverse(ToErase)) {
1639     SmallVector<VPValue *> PossiblyDead(R->operands());
1640     R->eraseFromParent();
1641     for (VPValue *Op : PossiblyDead)
1642       recursivelyDeleteDeadRecipes(Op);
1643   }
1644 }
1645 
1646 /// Add a VPEVLBasedIVPHIRecipe and related recipes to \p Plan and
1647 /// replaces all uses except the canonical IV increment of
1648 /// VPCanonicalIVPHIRecipe with a VPEVLBasedIVPHIRecipe. VPCanonicalIVPHIRecipe
1649 /// is used only for loop iterations counting after this transformation.
1650 ///
1651 /// The function uses the following definitions:
1652 ///  %StartV is the canonical induction start value.
1653 ///
1654 /// The function adds the following recipes:
1655 ///
1656 /// vector.ph:
1657 /// ...
1658 ///
1659 /// vector.body:
1660 /// ...
1661 /// %EVLPhi = EXPLICIT-VECTOR-LENGTH-BASED-IV-PHI [ %StartV, %vector.ph ],
1662 ///                                               [ %NextEVLIV, %vector.body ]
1663 /// %AVL = sub original TC, %EVLPhi
1664 /// %VPEVL = EXPLICIT-VECTOR-LENGTH %AVL
1665 /// ...
1666 /// %NextEVLIV = add IVSize (cast i32 %VPEVVL to IVSize), %EVLPhi
1667 /// ...
1668 ///
1669 /// If MaxSafeElements is provided, the function adds the following recipes:
1670 /// vector.ph:
1671 /// ...
1672 ///
1673 /// vector.body:
1674 /// ...
1675 /// %EVLPhi = EXPLICIT-VECTOR-LENGTH-BASED-IV-PHI [ %StartV, %vector.ph ],
1676 ///                                               [ %NextEVLIV, %vector.body ]
1677 /// %AVL = sub original TC, %EVLPhi
1678 /// %cmp = cmp ult %AVL, MaxSafeElements
1679 /// %SAFE_AVL = select %cmp, %AVL, MaxSafeElements
1680 /// %VPEVL = EXPLICIT-VECTOR-LENGTH %SAFE_AVL
1681 /// ...
1682 /// %NextEVLIV = add IVSize (cast i32 %VPEVL to IVSize), %EVLPhi
1683 /// ...
1684 ///
1685 bool VPlanTransforms::tryAddExplicitVectorLength(
1686     VPlan &Plan, const std::optional<unsigned> &MaxSafeElements) {
1687   VPBasicBlock *Header = Plan.getVectorLoopRegion()->getEntryBasicBlock();
1688   // The transform updates all users of inductions to work based on EVL, instead
1689   // of the VF directly. At the moment, widened inductions cannot be updated, so
1690   // bail out if the plan contains any.
1691   bool ContainsWidenInductions = any_of(
1692       Header->phis(),
1693       IsaPred<VPWidenIntOrFpInductionRecipe, VPWidenPointerInductionRecipe>);
1694   if (ContainsWidenInductions)
1695     return false;
1696 
1697   auto *CanonicalIVPHI = Plan.getCanonicalIV();
1698   VPValue *StartV = CanonicalIVPHI->getStartValue();
1699 
1700   // Create the ExplicitVectorLengthPhi recipe in the main loop.
1701   auto *EVLPhi = new VPEVLBasedIVPHIRecipe(StartV, DebugLoc());
1702   EVLPhi->insertAfter(CanonicalIVPHI);
1703   VPBuilder Builder(Header, Header->getFirstNonPhi());
1704   // Compute original TC - IV as the AVL (application vector length).
1705   VPValue *AVL = Builder.createNaryOp(
1706       Instruction::Sub, {Plan.getTripCount(), EVLPhi}, DebugLoc(), "avl");
1707   if (MaxSafeElements) {
1708     // Support for MaxSafeDist for correct loop emission.
1709     VPValue *AVLSafe = Plan.getOrAddLiveIn(
1710         ConstantInt::get(CanonicalIVPHI->getScalarType(), *MaxSafeElements));
1711     VPValue *Cmp = Builder.createICmp(ICmpInst::ICMP_ULT, AVL, AVLSafe);
1712     AVL = Builder.createSelect(Cmp, AVL, AVLSafe, DebugLoc(), "safe_avl");
1713   }
1714   auto *VPEVL = Builder.createNaryOp(VPInstruction::ExplicitVectorLength, AVL,
1715                                      DebugLoc());
1716 
1717   auto *CanonicalIVIncrement =
1718       cast<VPInstruction>(CanonicalIVPHI->getBackedgeValue());
1719   VPSingleDefRecipe *OpVPEVL = VPEVL;
1720   if (unsigned IVSize = CanonicalIVPHI->getScalarType()->getScalarSizeInBits();
1721       IVSize != 32) {
1722     OpVPEVL = new VPScalarCastRecipe(
1723         IVSize < 32 ? Instruction::Trunc : Instruction::ZExt, OpVPEVL,
1724         CanonicalIVPHI->getScalarType(), CanonicalIVIncrement->getDebugLoc());
1725     OpVPEVL->insertBefore(CanonicalIVIncrement);
1726   }
1727   auto *NextEVLIV =
1728       new VPInstruction(Instruction::Add, {OpVPEVL, EVLPhi},
1729                         {CanonicalIVIncrement->hasNoUnsignedWrap(),
1730                          CanonicalIVIncrement->hasNoSignedWrap()},
1731                         CanonicalIVIncrement->getDebugLoc(), "index.evl.next");
1732   NextEVLIV->insertBefore(CanonicalIVIncrement);
1733   EVLPhi->addOperand(NextEVLIV);
1734 
1735   transformRecipestoEVLRecipes(Plan, *VPEVL);
1736 
1737   // Replace all uses of VPCanonicalIVPHIRecipe by
1738   // VPEVLBasedIVPHIRecipe except for the canonical IV increment.
1739   CanonicalIVPHI->replaceAllUsesWith(EVLPhi);
1740   CanonicalIVIncrement->setOperand(0, CanonicalIVPHI);
1741   // TODO: support unroll factor > 1.
1742   Plan.setUF(1);
1743   return true;
1744 }
1745 
1746 void VPlanTransforms::dropPoisonGeneratingRecipes(
1747     VPlan &Plan, function_ref<bool(BasicBlock *)> BlockNeedsPredication) {
1748   // Collect recipes in the backward slice of `Root` that may generate a poison
1749   // value that is used after vectorization.
1750   SmallPtrSet<VPRecipeBase *, 16> Visited;
1751   auto CollectPoisonGeneratingInstrsInBackwardSlice([&](VPRecipeBase *Root) {
1752     SmallVector<VPRecipeBase *, 16> Worklist;
1753     Worklist.push_back(Root);
1754 
1755     // Traverse the backward slice of Root through its use-def chain.
1756     while (!Worklist.empty()) {
1757       VPRecipeBase *CurRec = Worklist.pop_back_val();
1758 
1759       if (!Visited.insert(CurRec).second)
1760         continue;
1761 
1762       // Prune search if we find another recipe generating a widen memory
1763       // instruction. Widen memory instructions involved in address computation
1764       // will lead to gather/scatter instructions, which don't need to be
1765       // handled.
1766       if (isa<VPWidenMemoryRecipe, VPInterleaveRecipe, VPScalarIVStepsRecipe,
1767               VPHeaderPHIRecipe>(CurRec))
1768         continue;
1769 
1770       // This recipe contributes to the address computation of a widen
1771       // load/store. If the underlying instruction has poison-generating flags,
1772       // drop them directly.
1773       if (auto *RecWithFlags = dyn_cast<VPRecipeWithIRFlags>(CurRec)) {
1774         VPValue *A, *B;
1775         using namespace llvm::VPlanPatternMatch;
1776         // Dropping disjoint from an OR may yield incorrect results, as some
1777         // analysis may have converted it to an Add implicitly (e.g. SCEV used
1778         // for dependence analysis). Instead, replace it with an equivalent Add.
1779         // This is possible as all users of the disjoint OR only access lanes
1780         // where the operands are disjoint or poison otherwise.
1781         if (match(RecWithFlags, m_BinaryOr(m_VPValue(A), m_VPValue(B))) &&
1782             RecWithFlags->isDisjoint()) {
1783           VPBuilder Builder(RecWithFlags);
1784           VPInstruction *New = Builder.createOverflowingOp(
1785               Instruction::Add, {A, B}, {false, false},
1786               RecWithFlags->getDebugLoc());
1787           New->setUnderlyingValue(RecWithFlags->getUnderlyingValue());
1788           RecWithFlags->replaceAllUsesWith(New);
1789           RecWithFlags->eraseFromParent();
1790           CurRec = New;
1791         } else
1792           RecWithFlags->dropPoisonGeneratingFlags();
1793       } else {
1794         Instruction *Instr = dyn_cast_or_null<Instruction>(
1795             CurRec->getVPSingleValue()->getUnderlyingValue());
1796         (void)Instr;
1797         assert((!Instr || !Instr->hasPoisonGeneratingFlags()) &&
1798                "found instruction with poison generating flags not covered by "
1799                "VPRecipeWithIRFlags");
1800       }
1801 
1802       // Add new definitions to the worklist.
1803       for (VPValue *Operand : CurRec->operands())
1804         if (VPRecipeBase *OpDef = Operand->getDefiningRecipe())
1805           Worklist.push_back(OpDef);
1806     }
1807   });
1808 
1809   // Traverse all the recipes in the VPlan and collect the poison-generating
1810   // recipes in the backward slice starting at the address of a VPWidenRecipe or
1811   // VPInterleaveRecipe.
1812   auto Iter = vp_depth_first_deep(Plan.getEntry());
1813   for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(Iter)) {
1814     for (VPRecipeBase &Recipe : *VPBB) {
1815       if (auto *WidenRec = dyn_cast<VPWidenMemoryRecipe>(&Recipe)) {
1816         Instruction &UnderlyingInstr = WidenRec->getIngredient();
1817         VPRecipeBase *AddrDef = WidenRec->getAddr()->getDefiningRecipe();
1818         if (AddrDef && WidenRec->isConsecutive() &&
1819             BlockNeedsPredication(UnderlyingInstr.getParent()))
1820           CollectPoisonGeneratingInstrsInBackwardSlice(AddrDef);
1821       } else if (auto *InterleaveRec = dyn_cast<VPInterleaveRecipe>(&Recipe)) {
1822         VPRecipeBase *AddrDef = InterleaveRec->getAddr()->getDefiningRecipe();
1823         if (AddrDef) {
1824           // Check if any member of the interleave group needs predication.
1825           const InterleaveGroup<Instruction> *InterGroup =
1826               InterleaveRec->getInterleaveGroup();
1827           bool NeedPredication = false;
1828           for (int I = 0, NumMembers = InterGroup->getNumMembers();
1829                I < NumMembers; ++I) {
1830             Instruction *Member = InterGroup->getMember(I);
1831             if (Member)
1832               NeedPredication |= BlockNeedsPredication(Member->getParent());
1833           }
1834 
1835           if (NeedPredication)
1836             CollectPoisonGeneratingInstrsInBackwardSlice(AddrDef);
1837         }
1838       }
1839     }
1840   }
1841 }
1842 
1843 void VPlanTransforms::createInterleaveGroups(
1844     VPlan &Plan,
1845     const SmallPtrSetImpl<const InterleaveGroup<Instruction> *>
1846         &InterleaveGroups,
1847     VPRecipeBuilder &RecipeBuilder, bool ScalarEpilogueAllowed) {
1848   if (InterleaveGroups.empty())
1849     return;
1850 
1851   // Interleave memory: for each Interleave Group we marked earlier as relevant
1852   // for this VPlan, replace the Recipes widening its memory instructions with a
1853   // single VPInterleaveRecipe at its insertion point.
1854   VPDominatorTree VPDT;
1855   VPDT.recalculate(Plan);
1856   for (const auto *IG : InterleaveGroups) {
1857     SmallVector<VPValue *, 4> StoredValues;
1858     for (unsigned i = 0; i < IG->getFactor(); ++i)
1859       if (auto *SI = dyn_cast_or_null<StoreInst>(IG->getMember(i))) {
1860         auto *StoreR = cast<VPWidenStoreRecipe>(RecipeBuilder.getRecipe(SI));
1861         StoredValues.push_back(StoreR->getStoredValue());
1862       }
1863 
1864     bool NeedsMaskForGaps =
1865         IG->requiresScalarEpilogue() && !ScalarEpilogueAllowed;
1866 
1867     Instruction *IRInsertPos = IG->getInsertPos();
1868     auto *InsertPos =
1869         cast<VPWidenMemoryRecipe>(RecipeBuilder.getRecipe(IRInsertPos));
1870 
1871     // Get or create the start address for the interleave group.
1872     auto *Start =
1873         cast<VPWidenMemoryRecipe>(RecipeBuilder.getRecipe(IG->getMember(0)));
1874     VPValue *Addr = Start->getAddr();
1875     VPRecipeBase *AddrDef = Addr->getDefiningRecipe();
1876     if (AddrDef && !VPDT.properlyDominates(AddrDef, InsertPos)) {
1877       // TODO: Hoist Addr's defining recipe (and any operands as needed) to
1878       // InsertPos or sink loads above zero members to join it.
1879       bool InBounds = false;
1880       if (auto *Gep = dyn_cast<GetElementPtrInst>(
1881               getLoadStorePointerOperand(IRInsertPos)->stripPointerCasts()))
1882         InBounds = Gep->isInBounds();
1883 
1884       // We cannot re-use the address of member zero because it does not
1885       // dominate the insert position. Instead, use the address of the insert
1886       // position and create a PtrAdd adjusting it to the address of member
1887       // zero.
1888       assert(IG->getIndex(IRInsertPos) != 0 &&
1889              "index of insert position shouldn't be zero");
1890       auto &DL = IRInsertPos->getDataLayout();
1891       APInt Offset(32,
1892                    DL.getTypeAllocSize(getLoadStoreType(IRInsertPos)) *
1893                        IG->getIndex(IRInsertPos),
1894                    /*IsSigned=*/true);
1895       VPValue *OffsetVPV = Plan.getOrAddLiveIn(
1896           ConstantInt::get(IRInsertPos->getParent()->getContext(), -Offset));
1897       VPBuilder B(InsertPos);
1898       Addr = InBounds ? B.createInBoundsPtrAdd(InsertPos->getAddr(), OffsetVPV)
1899                       : B.createPtrAdd(InsertPos->getAddr(), OffsetVPV);
1900     }
1901     auto *VPIG = new VPInterleaveRecipe(IG, Addr, StoredValues,
1902                                         InsertPos->getMask(), NeedsMaskForGaps);
1903     VPIG->insertBefore(InsertPos);
1904 
1905     unsigned J = 0;
1906     for (unsigned i = 0; i < IG->getFactor(); ++i)
1907       if (Instruction *Member = IG->getMember(i)) {
1908         VPRecipeBase *MemberR = RecipeBuilder.getRecipe(Member);
1909         if (!Member->getType()->isVoidTy()) {
1910           VPValue *OriginalV = MemberR->getVPSingleValue();
1911           OriginalV->replaceAllUsesWith(VPIG->getVPValue(J));
1912           J++;
1913         }
1914         MemberR->eraseFromParent();
1915       }
1916   }
1917 }
1918 
1919 void VPlanTransforms::convertToConcreteRecipes(VPlan &Plan) {
1920   for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(
1921            vp_depth_first_deep(Plan.getEntry()))) {
1922     for (VPRecipeBase &R : make_early_inc_range(VPBB->phis())) {
1923       if (!isa<VPCanonicalIVPHIRecipe, VPEVLBasedIVPHIRecipe>(&R))
1924         continue;
1925       auto *PhiR = cast<VPHeaderPHIRecipe>(&R);
1926       StringRef Name =
1927           isa<VPCanonicalIVPHIRecipe>(PhiR) ? "index" : "evl.based.iv";
1928       auto *ScalarR =
1929           new VPScalarPHIRecipe(PhiR->getStartValue(), PhiR->getBackedgeValue(),
1930                                 PhiR->getDebugLoc(), Name);
1931       ScalarR->insertBefore(PhiR);
1932       PhiR->replaceAllUsesWith(ScalarR);
1933       PhiR->eraseFromParent();
1934     }
1935   }
1936 }
1937 
1938 void VPlanTransforms::handleUncountableEarlyExit(
1939     VPlan &Plan, ScalarEvolution &SE, Loop *OrigLoop,
1940     BasicBlock *UncountableExitingBlock, VPRecipeBuilder &RecipeBuilder) {
1941   VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
1942   auto *LatchVPBB = cast<VPBasicBlock>(LoopRegion->getExiting());
1943   VPBuilder Builder(LatchVPBB->getTerminator());
1944   auto *MiddleVPBB = Plan.getMiddleBlock();
1945   VPValue *IsEarlyExitTaken = nullptr;
1946 
1947   // Process the uncountable exiting block. Update IsEarlyExitTaken, which
1948   // tracks if the uncountable early exit has been taken. Also split the middle
1949   // block and have it conditionally branch to the early exit block if
1950   // EarlyExitTaken.
1951   auto *EarlyExitingBranch =
1952       cast<BranchInst>(UncountableExitingBlock->getTerminator());
1953   BasicBlock *TrueSucc = EarlyExitingBranch->getSuccessor(0);
1954   BasicBlock *FalseSucc = EarlyExitingBranch->getSuccessor(1);
1955 
1956   // The early exit block may or may not be the same as the "countable" exit
1957   // block. Creates a new VPIRBB for the early exit block in case it is distinct
1958   // from the countable exit block.
1959   // TODO: Introduce both exit blocks during VPlan skeleton construction.
1960   VPIRBasicBlock *VPEarlyExitBlock;
1961   if (OrigLoop->getUniqueExitBlock()) {
1962     VPEarlyExitBlock = cast<VPIRBasicBlock>(MiddleVPBB->getSuccessors()[0]);
1963   } else {
1964     VPEarlyExitBlock = Plan.createVPIRBasicBlock(
1965         !OrigLoop->contains(TrueSucc) ? TrueSucc : FalseSucc);
1966   }
1967 
1968   VPValue *EarlyExitNotTakenCond = RecipeBuilder.getBlockInMask(
1969       OrigLoop->contains(TrueSucc) ? TrueSucc : FalseSucc);
1970   auto *EarlyExitTakenCond = Builder.createNot(EarlyExitNotTakenCond);
1971   IsEarlyExitTaken =
1972       Builder.createNaryOp(VPInstruction::AnyOf, {EarlyExitTakenCond});
1973 
1974   VPBasicBlock *NewMiddle = Plan.createVPBasicBlock("middle.split");
1975   VPBlockUtils::insertOnEdge(LoopRegion, MiddleVPBB, NewMiddle);
1976   VPBlockUtils::connectBlocks(NewMiddle, VPEarlyExitBlock);
1977   NewMiddle->swapSuccessors();
1978 
1979   VPBuilder MiddleBuilder(NewMiddle);
1980   MiddleBuilder.createNaryOp(VPInstruction::BranchOnCond, {IsEarlyExitTaken});
1981 
1982   // Replace the condition controlling the non-early exit from the vector loop
1983   // with one exiting if either the original condition of the vector latch is
1984   // true or the early exit has been taken.
1985   auto *LatchExitingBranch = cast<VPInstruction>(LatchVPBB->getTerminator());
1986   assert(LatchExitingBranch->getOpcode() == VPInstruction::BranchOnCount &&
1987          "Unexpected terminator");
1988   auto *IsLatchExitTaken =
1989       Builder.createICmp(CmpInst::ICMP_EQ, LatchExitingBranch->getOperand(0),
1990                          LatchExitingBranch->getOperand(1));
1991   auto *AnyExitTaken = Builder.createNaryOp(
1992       Instruction::Or, {IsEarlyExitTaken, IsLatchExitTaken});
1993   Builder.createNaryOp(VPInstruction::BranchOnCond, AnyExitTaken);
1994   LatchExitingBranch->eraseFromParent();
1995 }
1996