1480093f4SDimitry Andric //===-- VPlanTransforms.cpp - Utility VPlan to VPlan transforms -----------===//
2480093f4SDimitry Andric //
3480093f4SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4480093f4SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5480093f4SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6480093f4SDimitry Andric //
7480093f4SDimitry Andric //===----------------------------------------------------------------------===//
8480093f4SDimitry Andric ///
9480093f4SDimitry Andric /// \file
10480093f4SDimitry Andric /// This file implements a set of utility VPlan to VPlan transformations.
11480093f4SDimitry Andric ///
12480093f4SDimitry Andric //===----------------------------------------------------------------------===//
13480093f4SDimitry Andric 
14480093f4SDimitry Andric #include "VPlanTransforms.h"
15fe013be4SDimitry Andric #include "VPRecipeBuilder.h"
16c9157d92SDimitry Andric #include "VPlanAnalysis.h"
17bdd1243dSDimitry Andric #include "VPlanCFG.h"
18c9157d92SDimitry Andric #include "VPlanDominatorTree.h"
19480093f4SDimitry Andric #include "llvm/ADT/PostOrderIterator.h"
20c9157d92SDimitry Andric #include "llvm/ADT/STLExtras.h"
2181ad6265SDimitry Andric #include "llvm/ADT/SetVector.h"
2281ad6265SDimitry Andric #include "llvm/Analysis/IVDescriptors.h"
23bdd1243dSDimitry Andric #include "llvm/Analysis/VectorUtils.h"
24bdd1243dSDimitry Andric #include "llvm/IR/Intrinsics.h"
25c9157d92SDimitry Andric #include "llvm/IR/PatternMatch.h"
26480093f4SDimitry Andric 
27480093f4SDimitry Andric using namespace llvm;
28480093f4SDimitry Andric 
29c9157d92SDimitry Andric using namespace llvm::PatternMatch;
30c9157d92SDimitry Andric 
VPInstructionsToVPRecipes(VPlanPtr & Plan,function_ref<const InductionDescriptor * (PHINode *)> GetIntOrFpInductionDescriptor,ScalarEvolution & SE,const TargetLibraryInfo & TLI)31480093f4SDimitry Andric void VPlanTransforms::VPInstructionsToVPRecipes(
32fe013be4SDimitry Andric     VPlanPtr &Plan,
330eae32dcSDimitry Andric     function_ref<const InductionDescriptor *(PHINode *)>
340eae32dcSDimitry Andric         GetIntOrFpInductionDescriptor,
35fe013be4SDimitry Andric     ScalarEvolution &SE, const TargetLibraryInfo &TLI) {
36480093f4SDimitry Andric 
37bdd1243dSDimitry Andric   ReversePostOrderTraversal<VPBlockDeepTraversalWrapper<VPBlockBase *>> RPOT(
38bdd1243dSDimitry Andric       Plan->getEntry());
3981ad6265SDimitry Andric   for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(RPOT)) {
4081ad6265SDimitry Andric     VPRecipeBase *Term = VPBB->getTerminator();
4181ad6265SDimitry Andric     auto EndIter = Term ? Term->getIterator() : VPBB->end();
42480093f4SDimitry Andric     // Introduce each ingredient into VPlan.
4381ad6265SDimitry Andric     for (VPRecipeBase &Ingredient :
4481ad6265SDimitry Andric          make_early_inc_range(make_range(VPBB->begin(), EndIter))) {
4581ad6265SDimitry Andric 
46349cc55cSDimitry Andric       VPValue *VPV = Ingredient.getVPSingleValue();
47fe6060f1SDimitry Andric       Instruction *Inst = cast<Instruction>(VPV->getUnderlyingValue());
48480093f4SDimitry Andric 
49480093f4SDimitry Andric       VPRecipeBase *NewRecipe = nullptr;
50349cc55cSDimitry Andric       if (auto *VPPhi = dyn_cast<VPWidenPHIRecipe>(&Ingredient)) {
51fe6060f1SDimitry Andric         auto *Phi = cast<PHINode>(VPPhi->getUnderlyingValue());
520eae32dcSDimitry Andric         if (const auto *II = GetIntOrFpInductionDescriptor(Phi)) {
53fe013be4SDimitry Andric           VPValue *Start = Plan->getVPValueOrAddLiveIn(II->getStartValue());
5481ad6265SDimitry Andric           VPValue *Step =
5581ad6265SDimitry Andric               vputils::getOrCreateVPValueForSCEVExpr(*Plan, II->getStep(), SE);
56fe013be4SDimitry Andric           NewRecipe = new VPWidenIntOrFpInductionRecipe(Phi, Start, Step, *II);
57fe6060f1SDimitry Andric         } else {
58fe6060f1SDimitry Andric           Plan->addVPValue(Phi, VPPhi);
59fe6060f1SDimitry Andric           continue;
60fe6060f1SDimitry Andric         }
61fe6060f1SDimitry Andric       } else {
62349cc55cSDimitry Andric         assert(isa<VPInstruction>(&Ingredient) &&
63fe6060f1SDimitry Andric                "only VPInstructions expected here");
64fe6060f1SDimitry Andric         assert(!isa<PHINode>(Inst) && "phis should be handled above");
65fe6060f1SDimitry Andric         // Create VPWidenMemoryInstructionRecipe for loads and stores.
66fe6060f1SDimitry Andric         if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
67fe6060f1SDimitry Andric           NewRecipe = new VPWidenMemoryInstructionRecipe(
68fe013be4SDimitry Andric               *Load, Ingredient.getOperand(0), nullptr /*Mask*/,
69fe013be4SDimitry Andric               false /*Consecutive*/, false /*Reverse*/);
70fe6060f1SDimitry Andric         } else if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) {
71fe6060f1SDimitry Andric           NewRecipe = new VPWidenMemoryInstructionRecipe(
72fe013be4SDimitry Andric               *Store, Ingredient.getOperand(1), Ingredient.getOperand(0),
73fe013be4SDimitry Andric               nullptr /*Mask*/, false /*Consecutive*/, false /*Reverse*/);
74480093f4SDimitry Andric         } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Inst)) {
75fe013be4SDimitry Andric           NewRecipe = new VPWidenGEPRecipe(GEP, Ingredient.operands());
76fe6060f1SDimitry Andric         } else if (CallInst *CI = dyn_cast<CallInst>(Inst)) {
77*a58f00eaSDimitry Andric           NewRecipe = new VPWidenCallRecipe(
78*a58f00eaSDimitry Andric               *CI, drop_end(Ingredient.operands()),
79*a58f00eaSDimitry Andric               getVectorIntrinsicIDForCall(CI, &TLI), CI->getDebugLoc());
80fe6060f1SDimitry Andric         } else if (SelectInst *SI = dyn_cast<SelectInst>(Inst)) {
81fe013be4SDimitry Andric           NewRecipe = new VPWidenSelectRecipe(*SI, Ingredient.operands());
82fe013be4SDimitry Andric         } else if (auto *CI = dyn_cast<CastInst>(Inst)) {
83fe013be4SDimitry Andric           NewRecipe = new VPWidenCastRecipe(
84c9157d92SDimitry Andric               CI->getOpcode(), Ingredient.getOperand(0), CI->getType(), *CI);
85fe6060f1SDimitry Andric         } else {
86fe013be4SDimitry Andric           NewRecipe = new VPWidenRecipe(*Inst, Ingredient.operands());
87fe6060f1SDimitry Andric         }
88fe6060f1SDimitry Andric       }
89480093f4SDimitry Andric 
90349cc55cSDimitry Andric       NewRecipe->insertBefore(&Ingredient);
91e8d8bef9SDimitry Andric       if (NewRecipe->getNumDefinedValues() == 1)
92fe6060f1SDimitry Andric         VPV->replaceAllUsesWith(NewRecipe->getVPSingleValue());
93e8d8bef9SDimitry Andric       else
94e8d8bef9SDimitry Andric         assert(NewRecipe->getNumDefinedValues() == 0 &&
95e8d8bef9SDimitry Andric                "Only recpies with zero or one defined values expected");
96349cc55cSDimitry Andric       Ingredient.eraseFromParent();
97480093f4SDimitry Andric     }
98480093f4SDimitry Andric   }
99fe6060f1SDimitry Andric }
100fe6060f1SDimitry Andric 
sinkScalarOperands(VPlan & Plan)101fe013be4SDimitry Andric static bool sinkScalarOperands(VPlan &Plan) {
102bdd1243dSDimitry Andric   auto Iter = vp_depth_first_deep(Plan.getEntry());
103fe6060f1SDimitry Andric   bool Changed = false;
104bdd1243dSDimitry Andric   // First, collect the operands of all recipes in replicate blocks as seeds for
105bdd1243dSDimitry Andric   // sinking.
106*a58f00eaSDimitry Andric   SetVector<std::pair<VPBasicBlock *, VPSingleDefRecipe *>> WorkList;
107bdd1243dSDimitry Andric   for (VPRegionBlock *VPR : VPBlockUtils::blocksOnly<VPRegionBlock>(Iter)) {
108bdd1243dSDimitry Andric     VPBasicBlock *EntryVPBB = VPR->getEntryBasicBlock();
109bdd1243dSDimitry Andric     if (!VPR->isReplicator() || EntryVPBB->getSuccessors().size() != 2)
110fe6060f1SDimitry Andric       continue;
111bdd1243dSDimitry Andric     VPBasicBlock *VPBB = dyn_cast<VPBasicBlock>(EntryVPBB->getSuccessors()[0]);
112bdd1243dSDimitry Andric     if (!VPBB || VPBB->getSingleSuccessor() != VPR->getExitingBasicBlock())
113bdd1243dSDimitry Andric       continue;
114bdd1243dSDimitry Andric     for (auto &Recipe : *VPBB) {
115bdd1243dSDimitry Andric       for (VPValue *Op : Recipe.operands())
116*a58f00eaSDimitry Andric         if (auto *Def =
117*a58f00eaSDimitry Andric                 dyn_cast_or_null<VPSingleDefRecipe>(Op->getDefiningRecipe()))
118bdd1243dSDimitry Andric           WorkList.insert(std::make_pair(VPBB, Def));
119fe6060f1SDimitry Andric     }
120fe6060f1SDimitry Andric   }
121fe6060f1SDimitry Andric 
122bdd1243dSDimitry Andric   bool ScalarVFOnly = Plan.hasScalarVFOnly();
123bdd1243dSDimitry Andric   // Try to sink each replicate or scalar IV steps recipe in the worklist.
124bdd1243dSDimitry Andric   for (unsigned I = 0; I != WorkList.size(); ++I) {
125349cc55cSDimitry Andric     VPBasicBlock *SinkTo;
126*a58f00eaSDimitry Andric     VPSingleDefRecipe *SinkCandidate;
127bdd1243dSDimitry Andric     std::tie(SinkTo, SinkCandidate) = WorkList[I];
128bdd1243dSDimitry Andric     if (SinkCandidate->getParent() == SinkTo ||
129fe6060f1SDimitry Andric         SinkCandidate->mayHaveSideEffects() ||
130fe6060f1SDimitry Andric         SinkCandidate->mayReadOrWriteMemory())
131fe6060f1SDimitry Andric       continue;
132bdd1243dSDimitry Andric     if (auto *RepR = dyn_cast<VPReplicateRecipe>(SinkCandidate)) {
133bdd1243dSDimitry Andric       if (!ScalarVFOnly && RepR->isUniform())
134bdd1243dSDimitry Andric         continue;
135bdd1243dSDimitry Andric     } else if (!isa<VPScalarIVStepsRecipe>(SinkCandidate))
136bdd1243dSDimitry Andric       continue;
137fe6060f1SDimitry Andric 
138349cc55cSDimitry Andric     bool NeedsDuplicating = false;
139349cc55cSDimitry Andric     // All recipe users of the sink candidate must be in the same block SinkTo
140349cc55cSDimitry Andric     // or all users outside of SinkTo must be uniform-after-vectorization (
141349cc55cSDimitry Andric     // i.e., only first lane is used) . In the latter case, we need to duplicate
142bdd1243dSDimitry Andric     // SinkCandidate.
143349cc55cSDimitry Andric     auto CanSinkWithUser = [SinkTo, &NeedsDuplicating,
144349cc55cSDimitry Andric                             SinkCandidate](VPUser *U) {
145fe6060f1SDimitry Andric       auto *UI = dyn_cast<VPRecipeBase>(U);
146349cc55cSDimitry Andric       if (!UI)
147349cc55cSDimitry Andric         return false;
148349cc55cSDimitry Andric       if (UI->getParent() == SinkTo)
149349cc55cSDimitry Andric         return true;
150*a58f00eaSDimitry Andric       NeedsDuplicating = UI->onlyFirstLaneUsed(SinkCandidate);
151bdd1243dSDimitry Andric       // We only know how to duplicate VPRecipeRecipes for now.
152bdd1243dSDimitry Andric       return NeedsDuplicating && isa<VPReplicateRecipe>(SinkCandidate);
153349cc55cSDimitry Andric     };
154*a58f00eaSDimitry Andric     if (!all_of(SinkCandidate->users(), CanSinkWithUser))
155fe6060f1SDimitry Andric       continue;
156fe6060f1SDimitry Andric 
157349cc55cSDimitry Andric     if (NeedsDuplicating) {
158bdd1243dSDimitry Andric       if (ScalarVFOnly)
159bdd1243dSDimitry Andric         continue;
160bdd1243dSDimitry Andric       Instruction *I = cast<Instruction>(
161bdd1243dSDimitry Andric           cast<VPReplicateRecipe>(SinkCandidate)->getUnderlyingValue());
162fe013be4SDimitry Andric       auto *Clone = new VPReplicateRecipe(I, SinkCandidate->operands(), true);
163349cc55cSDimitry Andric       // TODO: add ".cloned" suffix to name of Clone's VPValue.
164349cc55cSDimitry Andric 
165349cc55cSDimitry Andric       Clone->insertBefore(SinkCandidate);
166*a58f00eaSDimitry Andric       SinkCandidate->replaceUsesWithIf(Clone, [SinkTo](VPUser &U, unsigned) {
167c9157d92SDimitry Andric         return cast<VPRecipeBase>(&U)->getParent() != SinkTo;
168c9157d92SDimitry Andric       });
169349cc55cSDimitry Andric     }
170fe6060f1SDimitry Andric     SinkCandidate->moveBefore(*SinkTo, SinkTo->getFirstNonPhi());
171349cc55cSDimitry Andric     for (VPValue *Op : SinkCandidate->operands())
172*a58f00eaSDimitry Andric       if (auto *Def =
173*a58f00eaSDimitry Andric               dyn_cast_or_null<VPSingleDefRecipe>(Op->getDefiningRecipe()))
174bdd1243dSDimitry Andric         WorkList.insert(std::make_pair(SinkTo, Def));
175fe6060f1SDimitry Andric     Changed = true;
176fe6060f1SDimitry Andric   }
177fe6060f1SDimitry Andric   return Changed;
178fe6060f1SDimitry Andric }
179fe6060f1SDimitry Andric 
180fe6060f1SDimitry Andric /// If \p R is a region with a VPBranchOnMaskRecipe in the entry block, return
181fe6060f1SDimitry Andric /// the mask.
getPredicatedMask(VPRegionBlock * R)182fe6060f1SDimitry Andric VPValue *getPredicatedMask(VPRegionBlock *R) {
183fe6060f1SDimitry Andric   auto *EntryBB = dyn_cast<VPBasicBlock>(R->getEntry());
184fe6060f1SDimitry Andric   if (!EntryBB || EntryBB->size() != 1 ||
185fe6060f1SDimitry Andric       !isa<VPBranchOnMaskRecipe>(EntryBB->begin()))
186fe6060f1SDimitry Andric     return nullptr;
187fe6060f1SDimitry Andric 
188fe6060f1SDimitry Andric   return cast<VPBranchOnMaskRecipe>(&*EntryBB->begin())->getOperand(0);
189fe6060f1SDimitry Andric }
190fe6060f1SDimitry Andric 
191fe6060f1SDimitry Andric /// If \p R is a triangle region, return the 'then' block of the triangle.
getPredicatedThenBlock(VPRegionBlock * R)192fe6060f1SDimitry Andric static VPBasicBlock *getPredicatedThenBlock(VPRegionBlock *R) {
193fe6060f1SDimitry Andric   auto *EntryBB = cast<VPBasicBlock>(R->getEntry());
194fe6060f1SDimitry Andric   if (EntryBB->getNumSuccessors() != 2)
195fe6060f1SDimitry Andric     return nullptr;
196fe6060f1SDimitry Andric 
197fe6060f1SDimitry Andric   auto *Succ0 = dyn_cast<VPBasicBlock>(EntryBB->getSuccessors()[0]);
198fe6060f1SDimitry Andric   auto *Succ1 = dyn_cast<VPBasicBlock>(EntryBB->getSuccessors()[1]);
199fe6060f1SDimitry Andric   if (!Succ0 || !Succ1)
200fe6060f1SDimitry Andric     return nullptr;
201fe6060f1SDimitry Andric 
202fe6060f1SDimitry Andric   if (Succ0->getNumSuccessors() + Succ1->getNumSuccessors() != 1)
203fe6060f1SDimitry Andric     return nullptr;
204fe6060f1SDimitry Andric   if (Succ0->getSingleSuccessor() == Succ1)
205fe6060f1SDimitry Andric     return Succ0;
206fe6060f1SDimitry Andric   if (Succ1->getSingleSuccessor() == Succ0)
207fe6060f1SDimitry Andric     return Succ1;
208fe6060f1SDimitry Andric   return nullptr;
209fe6060f1SDimitry Andric }
210fe6060f1SDimitry Andric 
211fe013be4SDimitry Andric // Merge replicate regions in their successor region, if a replicate region
212fe013be4SDimitry Andric // is connected to a successor replicate region with the same predicate by a
213fe013be4SDimitry Andric // single, empty VPBasicBlock.
mergeReplicateRegionsIntoSuccessors(VPlan & Plan)214fe013be4SDimitry Andric static bool mergeReplicateRegionsIntoSuccessors(VPlan &Plan) {
215fe6060f1SDimitry Andric   SetVector<VPRegionBlock *> DeletedRegions;
216fe6060f1SDimitry Andric 
217bdd1243dSDimitry Andric   // Collect replicate regions followed by an empty block, followed by another
218bdd1243dSDimitry Andric   // replicate region with matching masks to process front. This is to avoid
219bdd1243dSDimitry Andric   // iterator invalidation issues while merging regions.
220bdd1243dSDimitry Andric   SmallVector<VPRegionBlock *, 8> WorkList;
221bdd1243dSDimitry Andric   for (VPRegionBlock *Region1 : VPBlockUtils::blocksOnly<VPRegionBlock>(
222bdd1243dSDimitry Andric            vp_depth_first_deep(Plan.getEntry()))) {
223bdd1243dSDimitry Andric     if (!Region1->isReplicator())
224fe6060f1SDimitry Andric       continue;
225fe6060f1SDimitry Andric     auto *MiddleBasicBlock =
226fe6060f1SDimitry Andric         dyn_cast_or_null<VPBasicBlock>(Region1->getSingleSuccessor());
227fe6060f1SDimitry Andric     if (!MiddleBasicBlock || !MiddleBasicBlock->empty())
228fe6060f1SDimitry Andric       continue;
229fe6060f1SDimitry Andric 
230fe6060f1SDimitry Andric     auto *Region2 =
231fe6060f1SDimitry Andric         dyn_cast_or_null<VPRegionBlock>(MiddleBasicBlock->getSingleSuccessor());
232bdd1243dSDimitry Andric     if (!Region2 || !Region2->isReplicator())
233fe6060f1SDimitry Andric       continue;
234fe6060f1SDimitry Andric 
235fe6060f1SDimitry Andric     VPValue *Mask1 = getPredicatedMask(Region1);
236fe6060f1SDimitry Andric     VPValue *Mask2 = getPredicatedMask(Region2);
237fe6060f1SDimitry Andric     if (!Mask1 || Mask1 != Mask2)
238fe6060f1SDimitry Andric       continue;
239bdd1243dSDimitry Andric 
240bdd1243dSDimitry Andric     assert(Mask1 && Mask2 && "both region must have conditions");
241bdd1243dSDimitry Andric     WorkList.push_back(Region1);
242bdd1243dSDimitry Andric   }
243bdd1243dSDimitry Andric 
244bdd1243dSDimitry Andric   // Move recipes from Region1 to its successor region, if both are triangles.
245bdd1243dSDimitry Andric   for (VPRegionBlock *Region1 : WorkList) {
246bdd1243dSDimitry Andric     if (DeletedRegions.contains(Region1))
247bdd1243dSDimitry Andric       continue;
248bdd1243dSDimitry Andric     auto *MiddleBasicBlock = cast<VPBasicBlock>(Region1->getSingleSuccessor());
249bdd1243dSDimitry Andric     auto *Region2 = cast<VPRegionBlock>(MiddleBasicBlock->getSingleSuccessor());
250bdd1243dSDimitry Andric 
251fe6060f1SDimitry Andric     VPBasicBlock *Then1 = getPredicatedThenBlock(Region1);
252fe6060f1SDimitry Andric     VPBasicBlock *Then2 = getPredicatedThenBlock(Region2);
253fe6060f1SDimitry Andric     if (!Then1 || !Then2)
254fe6060f1SDimitry Andric       continue;
255fe6060f1SDimitry Andric 
256fe6060f1SDimitry Andric     // Note: No fusion-preventing memory dependencies are expected in either
257fe6060f1SDimitry Andric     // region. Such dependencies should be rejected during earlier dependence
258fe6060f1SDimitry Andric     // checks, which guarantee accesses can be re-ordered for vectorization.
259fe6060f1SDimitry Andric     //
260fe6060f1SDimitry Andric     // Move recipes to the successor region.
261fe6060f1SDimitry Andric     for (VPRecipeBase &ToMove : make_early_inc_range(reverse(*Then1)))
262fe6060f1SDimitry Andric       ToMove.moveBefore(*Then2, Then2->getFirstNonPhi());
263fe6060f1SDimitry Andric 
264fe6060f1SDimitry Andric     auto *Merge1 = cast<VPBasicBlock>(Then1->getSingleSuccessor());
265fe6060f1SDimitry Andric     auto *Merge2 = cast<VPBasicBlock>(Then2->getSingleSuccessor());
266fe6060f1SDimitry Andric 
267fe6060f1SDimitry Andric     // Move VPPredInstPHIRecipes from the merge block to the successor region's
268fe6060f1SDimitry Andric     // merge block. Update all users inside the successor region to use the
269fe6060f1SDimitry Andric     // original values.
270fe6060f1SDimitry Andric     for (VPRecipeBase &Phi1ToMove : make_early_inc_range(reverse(*Merge1))) {
271fe6060f1SDimitry Andric       VPValue *PredInst1 =
272fe6060f1SDimitry Andric           cast<VPPredInstPHIRecipe>(&Phi1ToMove)->getOperand(0);
2738c6f6c0cSDimitry Andric       VPValue *Phi1ToMoveV = Phi1ToMove.getVPSingleValue();
274c9157d92SDimitry Andric       Phi1ToMoveV->replaceUsesWithIf(PredInst1, [Then2](VPUser &U, unsigned) {
275c9157d92SDimitry Andric         auto *UI = dyn_cast<VPRecipeBase>(&U);
276c9157d92SDimitry Andric         return UI && UI->getParent() == Then2;
277c9157d92SDimitry Andric       });
278fe6060f1SDimitry Andric 
279fe6060f1SDimitry Andric       Phi1ToMove.moveBefore(*Merge2, Merge2->begin());
280fe6060f1SDimitry Andric     }
281fe6060f1SDimitry Andric 
282fe6060f1SDimitry Andric     // Finally, remove the first region.
283fe6060f1SDimitry Andric     for (VPBlockBase *Pred : make_early_inc_range(Region1->getPredecessors())) {
284fe6060f1SDimitry Andric       VPBlockUtils::disconnectBlocks(Pred, Region1);
285fe6060f1SDimitry Andric       VPBlockUtils::connectBlocks(Pred, MiddleBasicBlock);
286fe6060f1SDimitry Andric     }
287fe6060f1SDimitry Andric     VPBlockUtils::disconnectBlocks(Region1, MiddleBasicBlock);
288fe6060f1SDimitry Andric     DeletedRegions.insert(Region1);
289fe6060f1SDimitry Andric   }
290fe6060f1SDimitry Andric 
291fe6060f1SDimitry Andric   for (VPRegionBlock *ToDelete : DeletedRegions)
292fe6060f1SDimitry Andric     delete ToDelete;
293bdd1243dSDimitry Andric   return !DeletedRegions.empty();
294bdd1243dSDimitry Andric }
295bdd1243dSDimitry Andric 
createReplicateRegion(VPReplicateRecipe * PredRecipe,VPlan & Plan)296fe013be4SDimitry Andric static VPRegionBlock *createReplicateRegion(VPReplicateRecipe *PredRecipe,
297fe013be4SDimitry Andric                                             VPlan &Plan) {
298fe013be4SDimitry Andric   Instruction *Instr = PredRecipe->getUnderlyingInstr();
299fe013be4SDimitry Andric   // Build the triangular if-then region.
300fe013be4SDimitry Andric   std::string RegionName = (Twine("pred.") + Instr->getOpcodeName()).str();
301fe013be4SDimitry Andric   assert(Instr->getParent() && "Predicated instruction not in any basic block");
302fe013be4SDimitry Andric   auto *BlockInMask = PredRecipe->getMask();
303fe013be4SDimitry Andric   auto *BOMRecipe = new VPBranchOnMaskRecipe(BlockInMask);
304fe013be4SDimitry Andric   auto *Entry = new VPBasicBlock(Twine(RegionName) + ".entry", BOMRecipe);
305fe013be4SDimitry Andric 
306fe013be4SDimitry Andric   // Replace predicated replicate recipe with a replicate recipe without a
307fe013be4SDimitry Andric   // mask but in the replicate region.
308fe013be4SDimitry Andric   auto *RecipeWithoutMask = new VPReplicateRecipe(
309fe013be4SDimitry Andric       PredRecipe->getUnderlyingInstr(),
310fe013be4SDimitry Andric       make_range(PredRecipe->op_begin(), std::prev(PredRecipe->op_end())),
311fe013be4SDimitry Andric       PredRecipe->isUniform());
312fe013be4SDimitry Andric   auto *Pred = new VPBasicBlock(Twine(RegionName) + ".if", RecipeWithoutMask);
313fe013be4SDimitry Andric 
314fe013be4SDimitry Andric   VPPredInstPHIRecipe *PHIRecipe = nullptr;
315fe013be4SDimitry Andric   if (PredRecipe->getNumUsers() != 0) {
316fe013be4SDimitry Andric     PHIRecipe = new VPPredInstPHIRecipe(RecipeWithoutMask);
317fe013be4SDimitry Andric     PredRecipe->replaceAllUsesWith(PHIRecipe);
318fe013be4SDimitry Andric     PHIRecipe->setOperand(0, RecipeWithoutMask);
319fe013be4SDimitry Andric   }
320fe013be4SDimitry Andric   PredRecipe->eraseFromParent();
321fe013be4SDimitry Andric   auto *Exiting = new VPBasicBlock(Twine(RegionName) + ".continue", PHIRecipe);
322fe013be4SDimitry Andric   VPRegionBlock *Region = new VPRegionBlock(Entry, Exiting, RegionName, true);
323fe013be4SDimitry Andric 
324fe013be4SDimitry Andric   // Note: first set Entry as region entry and then connect successors starting
325fe013be4SDimitry Andric   // from it in order, to propagate the "parent" of each VPBasicBlock.
326fe013be4SDimitry Andric   VPBlockUtils::insertTwoBlocksAfter(Pred, Exiting, Entry);
327fe013be4SDimitry Andric   VPBlockUtils::connectBlocks(Pred, Exiting);
328fe013be4SDimitry Andric 
329fe013be4SDimitry Andric   return Region;
330fe013be4SDimitry Andric }
331fe013be4SDimitry Andric 
addReplicateRegions(VPlan & Plan)332fe013be4SDimitry Andric static void addReplicateRegions(VPlan &Plan) {
333fe013be4SDimitry Andric   SmallVector<VPReplicateRecipe *> WorkList;
334fe013be4SDimitry Andric   for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(
335fe013be4SDimitry Andric            vp_depth_first_deep(Plan.getEntry()))) {
336fe013be4SDimitry Andric     for (VPRecipeBase &R : *VPBB)
337fe013be4SDimitry Andric       if (auto *RepR = dyn_cast<VPReplicateRecipe>(&R)) {
338fe013be4SDimitry Andric         if (RepR->isPredicated())
339fe013be4SDimitry Andric           WorkList.push_back(RepR);
340fe013be4SDimitry Andric       }
341fe013be4SDimitry Andric   }
342fe013be4SDimitry Andric 
343fe013be4SDimitry Andric   unsigned BBNum = 0;
344fe013be4SDimitry Andric   for (VPReplicateRecipe *RepR : WorkList) {
345fe013be4SDimitry Andric     VPBasicBlock *CurrentBlock = RepR->getParent();
346fe013be4SDimitry Andric     VPBasicBlock *SplitBlock = CurrentBlock->splitAt(RepR->getIterator());
347fe013be4SDimitry Andric 
348fe013be4SDimitry Andric     BasicBlock *OrigBB = RepR->getUnderlyingInstr()->getParent();
349fe013be4SDimitry Andric     SplitBlock->setName(
350fe013be4SDimitry Andric         OrigBB->hasName() ? OrigBB->getName() + "." + Twine(BBNum++) : "");
351fe013be4SDimitry Andric     // Record predicated instructions for above packing optimizations.
352fe013be4SDimitry Andric     VPBlockBase *Region = createReplicateRegion(RepR, Plan);
353fe013be4SDimitry Andric     Region->setParent(CurrentBlock->getParent());
354fe013be4SDimitry Andric     VPBlockUtils::disconnectBlocks(CurrentBlock, SplitBlock);
355fe013be4SDimitry Andric     VPBlockUtils::connectBlocks(CurrentBlock, Region);
356fe013be4SDimitry Andric     VPBlockUtils::connectBlocks(Region, SplitBlock);
357fe013be4SDimitry Andric   }
358fe013be4SDimitry Andric }
359fe013be4SDimitry Andric 
createAndOptimizeReplicateRegions(VPlan & Plan)360fe013be4SDimitry Andric void VPlanTransforms::createAndOptimizeReplicateRegions(VPlan &Plan) {
361fe013be4SDimitry Andric   // Convert masked VPReplicateRecipes to if-then region blocks.
362fe013be4SDimitry Andric   addReplicateRegions(Plan);
363fe013be4SDimitry Andric 
364fe013be4SDimitry Andric   bool ShouldSimplify = true;
365fe013be4SDimitry Andric   while (ShouldSimplify) {
366fe013be4SDimitry Andric     ShouldSimplify = sinkScalarOperands(Plan);
367fe013be4SDimitry Andric     ShouldSimplify |= mergeReplicateRegionsIntoSuccessors(Plan);
368fe013be4SDimitry Andric     ShouldSimplify |= VPlanTransforms::mergeBlocksIntoPredecessors(Plan);
369fe013be4SDimitry Andric   }
370fe013be4SDimitry Andric }
mergeBlocksIntoPredecessors(VPlan & Plan)371bdd1243dSDimitry Andric bool VPlanTransforms::mergeBlocksIntoPredecessors(VPlan &Plan) {
372bdd1243dSDimitry Andric   SmallVector<VPBasicBlock *> WorkList;
373bdd1243dSDimitry Andric   for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(
374bdd1243dSDimitry Andric            vp_depth_first_deep(Plan.getEntry()))) {
375bdd1243dSDimitry Andric     auto *PredVPBB =
376bdd1243dSDimitry Andric         dyn_cast_or_null<VPBasicBlock>(VPBB->getSinglePredecessor());
377bdd1243dSDimitry Andric     if (PredVPBB && PredVPBB->getNumSuccessors() == 1)
378bdd1243dSDimitry Andric       WorkList.push_back(VPBB);
379bdd1243dSDimitry Andric   }
380bdd1243dSDimitry Andric 
381bdd1243dSDimitry Andric   for (VPBasicBlock *VPBB : WorkList) {
382bdd1243dSDimitry Andric     VPBasicBlock *PredVPBB = cast<VPBasicBlock>(VPBB->getSinglePredecessor());
383bdd1243dSDimitry Andric     for (VPRecipeBase &R : make_early_inc_range(*VPBB))
384bdd1243dSDimitry Andric       R.moveBefore(*PredVPBB, PredVPBB->end());
385bdd1243dSDimitry Andric     VPBlockUtils::disconnectBlocks(PredVPBB, VPBB);
386bdd1243dSDimitry Andric     auto *ParentRegion = cast_or_null<VPRegionBlock>(VPBB->getParent());
387bdd1243dSDimitry Andric     if (ParentRegion && ParentRegion->getExiting() == VPBB)
388bdd1243dSDimitry Andric       ParentRegion->setExiting(PredVPBB);
389bdd1243dSDimitry Andric     for (auto *Succ : to_vector(VPBB->successors())) {
390bdd1243dSDimitry Andric       VPBlockUtils::disconnectBlocks(VPBB, Succ);
391bdd1243dSDimitry Andric       VPBlockUtils::connectBlocks(PredVPBB, Succ);
392bdd1243dSDimitry Andric     }
393bdd1243dSDimitry Andric     delete VPBB;
394bdd1243dSDimitry Andric   }
395bdd1243dSDimitry Andric   return !WorkList.empty();
396fe6060f1SDimitry Andric }
3970eae32dcSDimitry Andric 
removeRedundantInductionCasts(VPlan & Plan)3980eae32dcSDimitry Andric void VPlanTransforms::removeRedundantInductionCasts(VPlan &Plan) {
39981ad6265SDimitry Andric   for (auto &Phi : Plan.getVectorLoopRegion()->getEntryBasicBlock()->phis()) {
4000eae32dcSDimitry Andric     auto *IV = dyn_cast<VPWidenIntOrFpInductionRecipe>(&Phi);
4010eae32dcSDimitry Andric     if (!IV || IV->getTruncInst())
4020eae32dcSDimitry Andric       continue;
4030eae32dcSDimitry Andric 
40481ad6265SDimitry Andric     // A sequence of IR Casts has potentially been recorded for IV, which
40581ad6265SDimitry Andric     // *must be bypassed* when the IV is vectorized, because the vectorized IV
40681ad6265SDimitry Andric     // will produce the desired casted value. This sequence forms a def-use
40781ad6265SDimitry Andric     // chain and is provided in reverse order, ending with the cast that uses
40881ad6265SDimitry Andric     // the IV phi. Search for the recipe of the last cast in the chain and
40981ad6265SDimitry Andric     // replace it with the original IV. Note that only the final cast is
41081ad6265SDimitry Andric     // expected to have users outside the cast-chain and the dead casts left
41181ad6265SDimitry Andric     // over will be cleaned up later.
4120eae32dcSDimitry Andric     auto &Casts = IV->getInductionDescriptor().getCastInsts();
4130eae32dcSDimitry Andric     VPValue *FindMyCast = IV;
4140eae32dcSDimitry Andric     for (Instruction *IRCast : reverse(Casts)) {
415*a58f00eaSDimitry Andric       VPSingleDefRecipe *FoundUserCast = nullptr;
4160eae32dcSDimitry Andric       for (auto *U : FindMyCast->users()) {
417*a58f00eaSDimitry Andric         auto *UserCast = dyn_cast<VPSingleDefRecipe>(U);
418*a58f00eaSDimitry Andric         if (UserCast && UserCast->getUnderlyingValue() == IRCast) {
4190eae32dcSDimitry Andric           FoundUserCast = UserCast;
4200eae32dcSDimitry Andric           break;
4210eae32dcSDimitry Andric         }
4220eae32dcSDimitry Andric       }
423*a58f00eaSDimitry Andric       FindMyCast = FoundUserCast;
4240eae32dcSDimitry Andric     }
42581ad6265SDimitry Andric     FindMyCast->replaceAllUsesWith(IV);
4260eae32dcSDimitry Andric   }
4270eae32dcSDimitry Andric }
42804eeddc0SDimitry Andric 
removeRedundantCanonicalIVs(VPlan & Plan)42904eeddc0SDimitry Andric void VPlanTransforms::removeRedundantCanonicalIVs(VPlan &Plan) {
43004eeddc0SDimitry Andric   VPCanonicalIVPHIRecipe *CanonicalIV = Plan.getCanonicalIV();
43104eeddc0SDimitry Andric   VPWidenCanonicalIVRecipe *WidenNewIV = nullptr;
43204eeddc0SDimitry Andric   for (VPUser *U : CanonicalIV->users()) {
43304eeddc0SDimitry Andric     WidenNewIV = dyn_cast<VPWidenCanonicalIVRecipe>(U);
43404eeddc0SDimitry Andric     if (WidenNewIV)
43504eeddc0SDimitry Andric       break;
43604eeddc0SDimitry Andric   }
43704eeddc0SDimitry Andric 
43804eeddc0SDimitry Andric   if (!WidenNewIV)
43904eeddc0SDimitry Andric     return;
44004eeddc0SDimitry Andric 
44104eeddc0SDimitry Andric   VPBasicBlock *HeaderVPBB = Plan.getVectorLoopRegion()->getEntryBasicBlock();
44204eeddc0SDimitry Andric   for (VPRecipeBase &Phi : HeaderVPBB->phis()) {
44304eeddc0SDimitry Andric     auto *WidenOriginalIV = dyn_cast<VPWidenIntOrFpInductionRecipe>(&Phi);
44404eeddc0SDimitry Andric 
4451fd87a68SDimitry Andric     if (!WidenOriginalIV || !WidenOriginalIV->isCanonical() ||
4461fd87a68SDimitry Andric         WidenOriginalIV->getScalarType() != WidenNewIV->getScalarType())
4471fd87a68SDimitry Andric       continue;
4481fd87a68SDimitry Andric 
4491fd87a68SDimitry Andric     // Replace WidenNewIV with WidenOriginalIV if WidenOriginalIV provides
4501fd87a68SDimitry Andric     // everything WidenNewIV's users need. That is, WidenOriginalIV will
4511fd87a68SDimitry Andric     // generate a vector phi or all users of WidenNewIV demand the first lane
4521fd87a68SDimitry Andric     // only.
453fe013be4SDimitry Andric     if (any_of(WidenOriginalIV->users(),
454fe013be4SDimitry Andric                [WidenOriginalIV](VPUser *U) {
455fe013be4SDimitry Andric                  return !U->usesScalars(WidenOriginalIV);
456fe013be4SDimitry Andric                }) ||
4571fd87a68SDimitry Andric         vputils::onlyFirstLaneUsed(WidenNewIV)) {
45804eeddc0SDimitry Andric       WidenNewIV->replaceAllUsesWith(WidenOriginalIV);
45904eeddc0SDimitry Andric       WidenNewIV->eraseFromParent();
46004eeddc0SDimitry Andric       return;
46104eeddc0SDimitry Andric     }
46204eeddc0SDimitry Andric   }
46304eeddc0SDimitry Andric }
46481ad6265SDimitry Andric 
removeDeadRecipes(VPlan & Plan)46581ad6265SDimitry Andric void VPlanTransforms::removeDeadRecipes(VPlan &Plan) {
466bdd1243dSDimitry Andric   ReversePostOrderTraversal<VPBlockDeepTraversalWrapper<VPBlockBase *>> RPOT(
467bdd1243dSDimitry Andric       Plan.getEntry());
46881ad6265SDimitry Andric 
46981ad6265SDimitry Andric   for (VPBasicBlock *VPBB : reverse(VPBlockUtils::blocksOnly<VPBasicBlock>(RPOT))) {
47081ad6265SDimitry Andric     // The recipes in the block are processed in reverse order, to catch chains
47181ad6265SDimitry Andric     // of dead recipes.
47281ad6265SDimitry Andric     for (VPRecipeBase &R : make_early_inc_range(reverse(*VPBB))) {
473c9157d92SDimitry Andric       // A user keeps R alive:
474c9157d92SDimitry Andric       if (any_of(R.definedValues(),
475c9157d92SDimitry Andric                  [](VPValue *V) { return V->getNumUsers(); }))
47681ad6265SDimitry Andric         continue;
477c9157d92SDimitry Andric 
478c9157d92SDimitry Andric       // Having side effects keeps R alive, but do remove conditional assume
479c9157d92SDimitry Andric       // instructions as their conditions may be flattened.
480c9157d92SDimitry Andric       auto *RepR = dyn_cast<VPReplicateRecipe>(&R);
481c9157d92SDimitry Andric       bool IsConditionalAssume =
482c9157d92SDimitry Andric           RepR && RepR->isPredicated() &&
483c9157d92SDimitry Andric           match(RepR->getUnderlyingInstr(), m_Intrinsic<Intrinsic::assume>());
484c9157d92SDimitry Andric       if (R.mayHaveSideEffects() && !IsConditionalAssume)
485c9157d92SDimitry Andric         continue;
486c9157d92SDimitry Andric 
48781ad6265SDimitry Andric       R.eraseFromParent();
48881ad6265SDimitry Andric     }
48981ad6265SDimitry Andric   }
49081ad6265SDimitry Andric }
49181ad6265SDimitry Andric 
createScalarIVSteps(VPlan & Plan,const InductionDescriptor & ID,ScalarEvolution & SE,Instruction * TruncI,Type * IVTy,VPValue * StartV,VPValue * Step)492c9157d92SDimitry Andric static VPValue *createScalarIVSteps(VPlan &Plan, const InductionDescriptor &ID,
493c9157d92SDimitry Andric                                     ScalarEvolution &SE, Instruction *TruncI,
494c9157d92SDimitry Andric                                     Type *IVTy, VPValue *StartV,
495c9157d92SDimitry Andric                                     VPValue *Step) {
496c9157d92SDimitry Andric   VPBasicBlock *HeaderVPBB = Plan.getVectorLoopRegion()->getEntryBasicBlock();
497c9157d92SDimitry Andric   auto IP = HeaderVPBB->getFirstNonPhi();
498c9157d92SDimitry Andric   VPCanonicalIVPHIRecipe *CanonicalIV = Plan.getCanonicalIV();
499c9157d92SDimitry Andric   Type *TruncTy = TruncI ? TruncI->getType() : IVTy;
500c9157d92SDimitry Andric   VPValue *BaseIV = CanonicalIV;
501c9157d92SDimitry Andric   if (!CanonicalIV->isCanonical(ID.getKind(), StartV, Step, TruncTy)) {
502c9157d92SDimitry Andric     BaseIV = new VPDerivedIVRecipe(ID, StartV, CanonicalIV, Step,
503c9157d92SDimitry Andric                                    TruncI ? TruncI->getType() : nullptr);
504c9157d92SDimitry Andric     HeaderVPBB->insert(BaseIV->getDefiningRecipe(), IP);
505c9157d92SDimitry Andric   }
506c9157d92SDimitry Andric 
507c9157d92SDimitry Andric   VPScalarIVStepsRecipe *Steps = new VPScalarIVStepsRecipe(ID, BaseIV, Step);
508c9157d92SDimitry Andric   HeaderVPBB->insert(Steps, IP);
509c9157d92SDimitry Andric   return Steps;
510c9157d92SDimitry Andric }
511c9157d92SDimitry Andric 
optimizeInductions(VPlan & Plan,ScalarEvolution & SE)51281ad6265SDimitry Andric void VPlanTransforms::optimizeInductions(VPlan &Plan, ScalarEvolution &SE) {
51381ad6265SDimitry Andric   SmallVector<VPRecipeBase *> ToRemove;
51481ad6265SDimitry Andric   VPBasicBlock *HeaderVPBB = Plan.getVectorLoopRegion()->getEntryBasicBlock();
51581ad6265SDimitry Andric   bool HasOnlyVectorVFs = !Plan.hasVF(ElementCount::getFixed(1));
51681ad6265SDimitry Andric   for (VPRecipeBase &Phi : HeaderVPBB->phis()) {
517bdd1243dSDimitry Andric     auto *WideIV = dyn_cast<VPWidenIntOrFpInductionRecipe>(&Phi);
518bdd1243dSDimitry Andric     if (!WideIV)
51981ad6265SDimitry Andric       continue;
520bdd1243dSDimitry Andric     if (HasOnlyVectorVFs && none_of(WideIV->users(), [WideIV](VPUser *U) {
521bdd1243dSDimitry Andric           return U->usesScalars(WideIV);
522bdd1243dSDimitry Andric         }))
52381ad6265SDimitry Andric       continue;
52481ad6265SDimitry Andric 
525bdd1243dSDimitry Andric     const InductionDescriptor &ID = WideIV->getInductionDescriptor();
526c9157d92SDimitry Andric     VPValue *Steps = createScalarIVSteps(
527c9157d92SDimitry Andric         Plan, ID, SE, WideIV->getTruncInst(), WideIV->getPHINode()->getType(),
528c9157d92SDimitry Andric         WideIV->getStartValue(), WideIV->getStepValue());
529bdd1243dSDimitry Andric 
530c9157d92SDimitry Andric     // Update scalar users of IV to use Step instead.
531c9157d92SDimitry Andric     if (!HasOnlyVectorVFs)
532c9157d92SDimitry Andric       WideIV->replaceAllUsesWith(Steps);
533c9157d92SDimitry Andric     else
534c9157d92SDimitry Andric       WideIV->replaceUsesWithIf(Steps, [WideIV](VPUser &U, unsigned) {
535c9157d92SDimitry Andric         return U.usesScalars(WideIV);
536c9157d92SDimitry Andric       });
53781ad6265SDimitry Andric   }
53881ad6265SDimitry Andric }
53981ad6265SDimitry Andric 
removeRedundantExpandSCEVRecipes(VPlan & Plan)54081ad6265SDimitry Andric void VPlanTransforms::removeRedundantExpandSCEVRecipes(VPlan &Plan) {
54181ad6265SDimitry Andric   DenseMap<const SCEV *, VPValue *> SCEV2VPV;
54281ad6265SDimitry Andric 
54381ad6265SDimitry Andric   for (VPRecipeBase &R :
54481ad6265SDimitry Andric        make_early_inc_range(*Plan.getEntry()->getEntryBasicBlock())) {
54581ad6265SDimitry Andric     auto *ExpR = dyn_cast<VPExpandSCEVRecipe>(&R);
54681ad6265SDimitry Andric     if (!ExpR)
54781ad6265SDimitry Andric       continue;
54881ad6265SDimitry Andric 
54981ad6265SDimitry Andric     auto I = SCEV2VPV.insert({ExpR->getSCEV(), ExpR});
55081ad6265SDimitry Andric     if (I.second)
55181ad6265SDimitry Andric       continue;
55281ad6265SDimitry Andric     ExpR->replaceAllUsesWith(I.first->second);
55381ad6265SDimitry Andric     ExpR->eraseFromParent();
55481ad6265SDimitry Andric   }
55581ad6265SDimitry Andric }
556bdd1243dSDimitry Andric 
canSimplifyBranchOnCond(VPInstruction * Term)557bdd1243dSDimitry Andric static bool canSimplifyBranchOnCond(VPInstruction *Term) {
558bdd1243dSDimitry Andric   VPInstruction *Not = dyn_cast<VPInstruction>(Term->getOperand(0));
559bdd1243dSDimitry Andric   if (!Not || Not->getOpcode() != VPInstruction::Not)
560bdd1243dSDimitry Andric     return false;
561bdd1243dSDimitry Andric 
562bdd1243dSDimitry Andric   VPInstruction *ALM = dyn_cast<VPInstruction>(Not->getOperand(0));
563bdd1243dSDimitry Andric   return ALM && ALM->getOpcode() == VPInstruction::ActiveLaneMask;
564bdd1243dSDimitry Andric }
565bdd1243dSDimitry Andric 
optimizeForVFAndUF(VPlan & Plan,ElementCount BestVF,unsigned BestUF,PredicatedScalarEvolution & PSE)566bdd1243dSDimitry Andric void VPlanTransforms::optimizeForVFAndUF(VPlan &Plan, ElementCount BestVF,
567bdd1243dSDimitry Andric                                          unsigned BestUF,
568bdd1243dSDimitry Andric                                          PredicatedScalarEvolution &PSE) {
569bdd1243dSDimitry Andric   assert(Plan.hasVF(BestVF) && "BestVF is not available in Plan");
570bdd1243dSDimitry Andric   assert(Plan.hasUF(BestUF) && "BestUF is not available in Plan");
571bdd1243dSDimitry Andric   VPBasicBlock *ExitingVPBB =
572bdd1243dSDimitry Andric       Plan.getVectorLoopRegion()->getExitingBasicBlock();
573bdd1243dSDimitry Andric   auto *Term = dyn_cast<VPInstruction>(&ExitingVPBB->back());
574bdd1243dSDimitry Andric   // Try to simplify the branch condition if TC <= VF * UF when preparing to
575bdd1243dSDimitry Andric   // execute the plan for the main vector loop. We only do this if the
576bdd1243dSDimitry Andric   // terminator is:
577bdd1243dSDimitry Andric   //  1. BranchOnCount, or
578bdd1243dSDimitry Andric   //  2. BranchOnCond where the input is Not(ActiveLaneMask).
579bdd1243dSDimitry Andric   if (!Term || (Term->getOpcode() != VPInstruction::BranchOnCount &&
580bdd1243dSDimitry Andric                 (Term->getOpcode() != VPInstruction::BranchOnCond ||
581bdd1243dSDimitry Andric                  !canSimplifyBranchOnCond(Term))))
582bdd1243dSDimitry Andric     return;
583bdd1243dSDimitry Andric 
584bdd1243dSDimitry Andric   Type *IdxTy =
585bdd1243dSDimitry Andric       Plan.getCanonicalIV()->getStartValue()->getLiveInIRValue()->getType();
586bdd1243dSDimitry Andric   const SCEV *TripCount = createTripCountSCEV(IdxTy, PSE);
587bdd1243dSDimitry Andric   ScalarEvolution &SE = *PSE.getSE();
588bdd1243dSDimitry Andric   const SCEV *C =
589bdd1243dSDimitry Andric       SE.getConstant(TripCount->getType(), BestVF.getKnownMinValue() * BestUF);
590bdd1243dSDimitry Andric   if (TripCount->isZero() ||
591bdd1243dSDimitry Andric       !SE.isKnownPredicate(CmpInst::ICMP_ULE, TripCount, C))
592bdd1243dSDimitry Andric     return;
593bdd1243dSDimitry Andric 
594bdd1243dSDimitry Andric   LLVMContext &Ctx = SE.getContext();
595fe013be4SDimitry Andric   auto *BOC = new VPInstruction(
596fe013be4SDimitry Andric       VPInstruction::BranchOnCond,
597fe013be4SDimitry Andric       {Plan.getVPValueOrAddLiveIn(ConstantInt::getTrue(Ctx))});
598bdd1243dSDimitry Andric   Term->eraseFromParent();
599bdd1243dSDimitry Andric   ExitingVPBB->appendRecipe(BOC);
600bdd1243dSDimitry Andric   Plan.setVF(BestVF);
601bdd1243dSDimitry Andric   Plan.setUF(BestUF);
602bdd1243dSDimitry Andric   // TODO: Further simplifications are possible
603bdd1243dSDimitry Andric   //      1. Replace inductions with constants.
604bdd1243dSDimitry Andric   //      2. Replace vector loop region with VPBasicBlock.
605bdd1243dSDimitry Andric }
606fe013be4SDimitry Andric 
607fe013be4SDimitry Andric #ifndef NDEBUG
GetReplicateRegion(VPRecipeBase * R)608fe013be4SDimitry Andric static VPRegionBlock *GetReplicateRegion(VPRecipeBase *R) {
609fe013be4SDimitry Andric   auto *Region = dyn_cast_or_null<VPRegionBlock>(R->getParent()->getParent());
610fe013be4SDimitry Andric   if (Region && Region->isReplicator()) {
611fe013be4SDimitry Andric     assert(Region->getNumSuccessors() == 1 &&
612fe013be4SDimitry Andric            Region->getNumPredecessors() == 1 && "Expected SESE region!");
613fe013be4SDimitry Andric     assert(R->getParent()->size() == 1 &&
614fe013be4SDimitry Andric            "A recipe in an original replicator region must be the only "
615fe013be4SDimitry Andric            "recipe in its block");
616fe013be4SDimitry Andric     return Region;
617fe013be4SDimitry Andric   }
618fe013be4SDimitry Andric   return nullptr;
619fe013be4SDimitry Andric }
620fe013be4SDimitry Andric #endif
621fe013be4SDimitry Andric 
properlyDominates(const VPRecipeBase * A,const VPRecipeBase * B,VPDominatorTree & VPDT)622fe013be4SDimitry Andric static bool properlyDominates(const VPRecipeBase *A, const VPRecipeBase *B,
623fe013be4SDimitry Andric                               VPDominatorTree &VPDT) {
624fe013be4SDimitry Andric   if (A == B)
625fe013be4SDimitry Andric     return false;
626fe013be4SDimitry Andric 
627fe013be4SDimitry Andric   auto LocalComesBefore = [](const VPRecipeBase *A, const VPRecipeBase *B) {
628fe013be4SDimitry Andric     for (auto &R : *A->getParent()) {
629fe013be4SDimitry Andric       if (&R == A)
630fe013be4SDimitry Andric         return true;
631fe013be4SDimitry Andric       if (&R == B)
632fe013be4SDimitry Andric         return false;
633fe013be4SDimitry Andric     }
634fe013be4SDimitry Andric     llvm_unreachable("recipe not found");
635fe013be4SDimitry Andric   };
636fe013be4SDimitry Andric   const VPBlockBase *ParentA = A->getParent();
637fe013be4SDimitry Andric   const VPBlockBase *ParentB = B->getParent();
638fe013be4SDimitry Andric   if (ParentA == ParentB)
639fe013be4SDimitry Andric     return LocalComesBefore(A, B);
640fe013be4SDimitry Andric 
641fe013be4SDimitry Andric   assert(!GetReplicateRegion(const_cast<VPRecipeBase *>(A)) &&
642fe013be4SDimitry Andric          "No replicate regions expected at this point");
643fe013be4SDimitry Andric   assert(!GetReplicateRegion(const_cast<VPRecipeBase *>(B)) &&
644fe013be4SDimitry Andric          "No replicate regions expected at this point");
645fe013be4SDimitry Andric   return VPDT.properlyDominates(ParentA, ParentB);
646fe013be4SDimitry Andric }
647fe013be4SDimitry Andric 
648fe013be4SDimitry Andric /// Sink users of \p FOR after the recipe defining the previous value \p
649fe013be4SDimitry Andric /// Previous of the recurrence. \returns true if all users of \p FOR could be
650fe013be4SDimitry Andric /// re-arranged as needed or false if it is not possible.
651fe013be4SDimitry Andric static bool
sinkRecurrenceUsersAfterPrevious(VPFirstOrderRecurrencePHIRecipe * FOR,VPRecipeBase * Previous,VPDominatorTree & VPDT)652fe013be4SDimitry Andric sinkRecurrenceUsersAfterPrevious(VPFirstOrderRecurrencePHIRecipe *FOR,
653fe013be4SDimitry Andric                                  VPRecipeBase *Previous,
654fe013be4SDimitry Andric                                  VPDominatorTree &VPDT) {
655fe013be4SDimitry Andric   // Collect recipes that need sinking.
656fe013be4SDimitry Andric   SmallVector<VPRecipeBase *> WorkList;
657fe013be4SDimitry Andric   SmallPtrSet<VPRecipeBase *, 8> Seen;
658fe013be4SDimitry Andric   Seen.insert(Previous);
659fe013be4SDimitry Andric   auto TryToPushSinkCandidate = [&](VPRecipeBase *SinkCandidate) {
660fe013be4SDimitry Andric     // The previous value must not depend on the users of the recurrence phi. In
661fe013be4SDimitry Andric     // that case, FOR is not a fixed order recurrence.
662fe013be4SDimitry Andric     if (SinkCandidate == Previous)
663fe013be4SDimitry Andric       return false;
664fe013be4SDimitry Andric 
665fe013be4SDimitry Andric     if (isa<VPHeaderPHIRecipe>(SinkCandidate) ||
666fe013be4SDimitry Andric         !Seen.insert(SinkCandidate).second ||
667fe013be4SDimitry Andric         properlyDominates(Previous, SinkCandidate, VPDT))
668fe013be4SDimitry Andric       return true;
669fe013be4SDimitry Andric 
670fe013be4SDimitry Andric     if (SinkCandidate->mayHaveSideEffects())
671fe013be4SDimitry Andric       return false;
672fe013be4SDimitry Andric 
673fe013be4SDimitry Andric     WorkList.push_back(SinkCandidate);
674fe013be4SDimitry Andric     return true;
675fe013be4SDimitry Andric   };
676fe013be4SDimitry Andric 
677fe013be4SDimitry Andric   // Recursively sink users of FOR after Previous.
678fe013be4SDimitry Andric   WorkList.push_back(FOR);
679fe013be4SDimitry Andric   for (unsigned I = 0; I != WorkList.size(); ++I) {
680fe013be4SDimitry Andric     VPRecipeBase *Current = WorkList[I];
681fe013be4SDimitry Andric     assert(Current->getNumDefinedValues() == 1 &&
682fe013be4SDimitry Andric            "only recipes with a single defined value expected");
683fe013be4SDimitry Andric 
684fe013be4SDimitry Andric     for (VPUser *User : Current->getVPSingleValue()->users()) {
685fe013be4SDimitry Andric       if (auto *R = dyn_cast<VPRecipeBase>(User))
686fe013be4SDimitry Andric         if (!TryToPushSinkCandidate(R))
687fe013be4SDimitry Andric           return false;
688fe013be4SDimitry Andric     }
689fe013be4SDimitry Andric   }
690fe013be4SDimitry Andric 
691fe013be4SDimitry Andric   // Keep recipes to sink ordered by dominance so earlier instructions are
692fe013be4SDimitry Andric   // processed first.
693fe013be4SDimitry Andric   sort(WorkList, [&VPDT](const VPRecipeBase *A, const VPRecipeBase *B) {
694fe013be4SDimitry Andric     return properlyDominates(A, B, VPDT);
695fe013be4SDimitry Andric   });
696fe013be4SDimitry Andric 
697fe013be4SDimitry Andric   for (VPRecipeBase *SinkCandidate : WorkList) {
698fe013be4SDimitry Andric     if (SinkCandidate == FOR)
699fe013be4SDimitry Andric       continue;
700fe013be4SDimitry Andric 
701fe013be4SDimitry Andric     SinkCandidate->moveAfter(Previous);
702fe013be4SDimitry Andric     Previous = SinkCandidate;
703fe013be4SDimitry Andric   }
704fe013be4SDimitry Andric   return true;
705fe013be4SDimitry Andric }
706fe013be4SDimitry Andric 
adjustFixedOrderRecurrences(VPlan & Plan,VPBuilder & Builder)707fe013be4SDimitry Andric bool VPlanTransforms::adjustFixedOrderRecurrences(VPlan &Plan,
708fe013be4SDimitry Andric                                                   VPBuilder &Builder) {
709fe013be4SDimitry Andric   VPDominatorTree VPDT;
710fe013be4SDimitry Andric   VPDT.recalculate(Plan);
711fe013be4SDimitry Andric 
712fe013be4SDimitry Andric   SmallVector<VPFirstOrderRecurrencePHIRecipe *> RecurrencePhis;
713fe013be4SDimitry Andric   for (VPRecipeBase &R :
714fe013be4SDimitry Andric        Plan.getVectorLoopRegion()->getEntry()->getEntryBasicBlock()->phis())
715fe013be4SDimitry Andric     if (auto *FOR = dyn_cast<VPFirstOrderRecurrencePHIRecipe>(&R))
716fe013be4SDimitry Andric       RecurrencePhis.push_back(FOR);
717fe013be4SDimitry Andric 
718fe013be4SDimitry Andric   for (VPFirstOrderRecurrencePHIRecipe *FOR : RecurrencePhis) {
719fe013be4SDimitry Andric     SmallPtrSet<VPFirstOrderRecurrencePHIRecipe *, 4> SeenPhis;
720fe013be4SDimitry Andric     VPRecipeBase *Previous = FOR->getBackedgeValue()->getDefiningRecipe();
721fe013be4SDimitry Andric     // Fixed-order recurrences do not contain cycles, so this loop is guaranteed
722fe013be4SDimitry Andric     // to terminate.
723fe013be4SDimitry Andric     while (auto *PrevPhi =
724fe013be4SDimitry Andric                dyn_cast_or_null<VPFirstOrderRecurrencePHIRecipe>(Previous)) {
725fe013be4SDimitry Andric       assert(PrevPhi->getParent() == FOR->getParent());
726fe013be4SDimitry Andric       assert(SeenPhis.insert(PrevPhi).second);
727fe013be4SDimitry Andric       Previous = PrevPhi->getBackedgeValue()->getDefiningRecipe();
728fe013be4SDimitry Andric     }
729fe013be4SDimitry Andric 
730fe013be4SDimitry Andric     if (!sinkRecurrenceUsersAfterPrevious(FOR, Previous, VPDT))
731fe013be4SDimitry Andric       return false;
732fe013be4SDimitry Andric 
733fe013be4SDimitry Andric     // Introduce a recipe to combine the incoming and previous values of a
734fe013be4SDimitry Andric     // fixed-order recurrence.
735fe013be4SDimitry Andric     VPBasicBlock *InsertBlock = Previous->getParent();
736fe013be4SDimitry Andric     if (isa<VPHeaderPHIRecipe>(Previous))
737fe013be4SDimitry Andric       Builder.setInsertPoint(InsertBlock, InsertBlock->getFirstNonPhi());
738fe013be4SDimitry Andric     else
739fe013be4SDimitry Andric       Builder.setInsertPoint(InsertBlock, std::next(Previous->getIterator()));
740fe013be4SDimitry Andric 
741fe013be4SDimitry Andric     auto *RecurSplice = cast<VPInstruction>(
742fe013be4SDimitry Andric         Builder.createNaryOp(VPInstruction::FirstOrderRecurrenceSplice,
743fe013be4SDimitry Andric                              {FOR, FOR->getBackedgeValue()}));
744fe013be4SDimitry Andric 
745fe013be4SDimitry Andric     FOR->replaceAllUsesWith(RecurSplice);
746fe013be4SDimitry Andric     // Set the first operand of RecurSplice to FOR again, after replacing
747fe013be4SDimitry Andric     // all users.
748fe013be4SDimitry Andric     RecurSplice->setOperand(0, FOR);
749fe013be4SDimitry Andric   }
750fe013be4SDimitry Andric   return true;
751fe013be4SDimitry Andric }
752fe013be4SDimitry Andric 
clearReductionWrapFlags(VPlan & Plan)753fe013be4SDimitry Andric void VPlanTransforms::clearReductionWrapFlags(VPlan &Plan) {
754fe013be4SDimitry Andric   for (VPRecipeBase &R :
755fe013be4SDimitry Andric        Plan.getVectorLoopRegion()->getEntryBasicBlock()->phis()) {
756fe013be4SDimitry Andric     auto *PhiR = dyn_cast<VPReductionPHIRecipe>(&R);
757fe013be4SDimitry Andric     if (!PhiR)
758fe013be4SDimitry Andric       continue;
759fe013be4SDimitry Andric     const RecurrenceDescriptor &RdxDesc = PhiR->getRecurrenceDescriptor();
760fe013be4SDimitry Andric     RecurKind RK = RdxDesc.getRecurrenceKind();
761fe013be4SDimitry Andric     if (RK != RecurKind::Add && RK != RecurKind::Mul)
762fe013be4SDimitry Andric       continue;
763fe013be4SDimitry Andric 
764fe013be4SDimitry Andric     SmallSetVector<VPValue *, 8> Worklist;
765fe013be4SDimitry Andric     Worklist.insert(PhiR);
766fe013be4SDimitry Andric 
767fe013be4SDimitry Andric     for (unsigned I = 0; I != Worklist.size(); ++I) {
768fe013be4SDimitry Andric       VPValue *Cur = Worklist[I];
769fe013be4SDimitry Andric       if (auto *RecWithFlags =
770fe013be4SDimitry Andric               dyn_cast<VPRecipeWithIRFlags>(Cur->getDefiningRecipe())) {
771fe013be4SDimitry Andric         RecWithFlags->dropPoisonGeneratingFlags();
772fe013be4SDimitry Andric       }
773fe013be4SDimitry Andric 
774fe013be4SDimitry Andric       for (VPUser *U : Cur->users()) {
775fe013be4SDimitry Andric         auto *UserRecipe = dyn_cast<VPRecipeBase>(U);
776fe013be4SDimitry Andric         if (!UserRecipe)
777fe013be4SDimitry Andric           continue;
778fe013be4SDimitry Andric         for (VPValue *V : UserRecipe->definedValues())
779fe013be4SDimitry Andric           Worklist.insert(V);
780fe013be4SDimitry Andric       }
781fe013be4SDimitry Andric     }
782fe013be4SDimitry Andric   }
783fe013be4SDimitry Andric }
784c9157d92SDimitry Andric 
785c9157d92SDimitry Andric /// Returns true is \p V is constant one.
isConstantOne(VPValue * V)786c9157d92SDimitry Andric static bool isConstantOne(VPValue *V) {
787c9157d92SDimitry Andric   if (!V->isLiveIn())
788c9157d92SDimitry Andric     return false;
789c9157d92SDimitry Andric   auto *C = dyn_cast<ConstantInt>(V->getLiveInIRValue());
790c9157d92SDimitry Andric   return C && C->isOne();
791c9157d92SDimitry Andric }
792c9157d92SDimitry Andric 
793c9157d92SDimitry Andric /// Returns the llvm::Instruction opcode for \p R.
getOpcodeForRecipe(VPRecipeBase & R)794c9157d92SDimitry Andric static unsigned getOpcodeForRecipe(VPRecipeBase &R) {
795c9157d92SDimitry Andric   if (auto *WidenR = dyn_cast<VPWidenRecipe>(&R))
796c9157d92SDimitry Andric     return WidenR->getUnderlyingInstr()->getOpcode();
797c9157d92SDimitry Andric   if (auto *WidenC = dyn_cast<VPWidenCastRecipe>(&R))
798c9157d92SDimitry Andric     return WidenC->getOpcode();
799c9157d92SDimitry Andric   if (auto *RepR = dyn_cast<VPReplicateRecipe>(&R))
800c9157d92SDimitry Andric     return RepR->getUnderlyingInstr()->getOpcode();
801c9157d92SDimitry Andric   if (auto *VPI = dyn_cast<VPInstruction>(&R))
802c9157d92SDimitry Andric     return VPI->getOpcode();
803c9157d92SDimitry Andric   return 0;
804c9157d92SDimitry Andric }
805c9157d92SDimitry Andric 
806c9157d92SDimitry Andric /// Try to simplify recipe \p R.
simplifyRecipe(VPRecipeBase & R,VPTypeAnalysis & TypeInfo)807c9157d92SDimitry Andric static void simplifyRecipe(VPRecipeBase &R, VPTypeAnalysis &TypeInfo) {
808c9157d92SDimitry Andric   switch (getOpcodeForRecipe(R)) {
809c9157d92SDimitry Andric   case Instruction::Mul: {
810c9157d92SDimitry Andric     VPValue *A = R.getOperand(0);
811c9157d92SDimitry Andric     VPValue *B = R.getOperand(1);
812c9157d92SDimitry Andric     if (isConstantOne(A))
813c9157d92SDimitry Andric       return R.getVPSingleValue()->replaceAllUsesWith(B);
814c9157d92SDimitry Andric     if (isConstantOne(B))
815c9157d92SDimitry Andric       return R.getVPSingleValue()->replaceAllUsesWith(A);
816c9157d92SDimitry Andric     break;
817c9157d92SDimitry Andric   }
818c9157d92SDimitry Andric   case Instruction::Trunc: {
819c9157d92SDimitry Andric     VPRecipeBase *Ext = R.getOperand(0)->getDefiningRecipe();
820c9157d92SDimitry Andric     if (!Ext)
821c9157d92SDimitry Andric       break;
822c9157d92SDimitry Andric     unsigned ExtOpcode = getOpcodeForRecipe(*Ext);
823c9157d92SDimitry Andric     if (ExtOpcode != Instruction::ZExt && ExtOpcode != Instruction::SExt)
824c9157d92SDimitry Andric       break;
825c9157d92SDimitry Andric     VPValue *A = Ext->getOperand(0);
826c9157d92SDimitry Andric     VPValue *Trunc = R.getVPSingleValue();
827c9157d92SDimitry Andric     Type *TruncTy = TypeInfo.inferScalarType(Trunc);
828c9157d92SDimitry Andric     Type *ATy = TypeInfo.inferScalarType(A);
829c9157d92SDimitry Andric     if (TruncTy == ATy) {
830c9157d92SDimitry Andric       Trunc->replaceAllUsesWith(A);
831cdc20ff6SDimitry Andric     } else {
832cdc20ff6SDimitry Andric       // Don't replace a scalarizing recipe with a widened cast.
833cdc20ff6SDimitry Andric       if (isa<VPReplicateRecipe>(&R))
834cdc20ff6SDimitry Andric         break;
835cdc20ff6SDimitry Andric       if (ATy->getScalarSizeInBits() < TruncTy->getScalarSizeInBits()) {
836c9157d92SDimitry Andric         auto *VPC =
837c9157d92SDimitry Andric             new VPWidenCastRecipe(Instruction::CastOps(ExtOpcode), A, TruncTy);
838c9157d92SDimitry Andric         VPC->insertBefore(&R);
839c9157d92SDimitry Andric         Trunc->replaceAllUsesWith(VPC);
840c9157d92SDimitry Andric       } else if (ATy->getScalarSizeInBits() > TruncTy->getScalarSizeInBits()) {
841c9157d92SDimitry Andric         auto *VPC = new VPWidenCastRecipe(Instruction::Trunc, A, TruncTy);
842c9157d92SDimitry Andric         VPC->insertBefore(&R);
843c9157d92SDimitry Andric         Trunc->replaceAllUsesWith(VPC);
844c9157d92SDimitry Andric       }
845cdc20ff6SDimitry Andric     }
846c9157d92SDimitry Andric #ifndef NDEBUG
847c9157d92SDimitry Andric     // Verify that the cached type info is for both A and its users is still
848c9157d92SDimitry Andric     // accurate by comparing it to freshly computed types.
849c9157d92SDimitry Andric     VPTypeAnalysis TypeInfo2(TypeInfo.getContext());
850c9157d92SDimitry Andric     assert(TypeInfo.inferScalarType(A) == TypeInfo2.inferScalarType(A));
851c9157d92SDimitry Andric     for (VPUser *U : A->users()) {
852c9157d92SDimitry Andric       auto *R = dyn_cast<VPRecipeBase>(U);
853c9157d92SDimitry Andric       if (!R)
854c9157d92SDimitry Andric         continue;
855c9157d92SDimitry Andric       for (VPValue *VPV : R->definedValues())
856c9157d92SDimitry Andric         assert(TypeInfo.inferScalarType(VPV) == TypeInfo2.inferScalarType(VPV));
857c9157d92SDimitry Andric     }
858c9157d92SDimitry Andric #endif
859c9157d92SDimitry Andric     break;
860c9157d92SDimitry Andric   }
861c9157d92SDimitry Andric   default:
862c9157d92SDimitry Andric     break;
863c9157d92SDimitry Andric   }
864c9157d92SDimitry Andric }
865c9157d92SDimitry Andric 
866c9157d92SDimitry Andric /// Try to simplify the recipes in \p Plan.
simplifyRecipes(VPlan & Plan,LLVMContext & Ctx)867c9157d92SDimitry Andric static void simplifyRecipes(VPlan &Plan, LLVMContext &Ctx) {
868c9157d92SDimitry Andric   ReversePostOrderTraversal<VPBlockDeepTraversalWrapper<VPBlockBase *>> RPOT(
869c9157d92SDimitry Andric       Plan.getEntry());
870c9157d92SDimitry Andric   VPTypeAnalysis TypeInfo(Ctx);
871c9157d92SDimitry Andric   for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(RPOT)) {
872c9157d92SDimitry Andric     for (VPRecipeBase &R : make_early_inc_range(*VPBB)) {
873c9157d92SDimitry Andric       simplifyRecipe(R, TypeInfo);
874c9157d92SDimitry Andric     }
875c9157d92SDimitry Andric   }
876c9157d92SDimitry Andric }
877c9157d92SDimitry Andric 
truncateToMinimalBitwidths(VPlan & Plan,const MapVector<Instruction *,uint64_t> & MinBWs,LLVMContext & Ctx)878c9157d92SDimitry Andric void VPlanTransforms::truncateToMinimalBitwidths(
879c9157d92SDimitry Andric     VPlan &Plan, const MapVector<Instruction *, uint64_t> &MinBWs,
880c9157d92SDimitry Andric     LLVMContext &Ctx) {
881c9157d92SDimitry Andric #ifndef NDEBUG
882c9157d92SDimitry Andric   // Count the processed recipes and cross check the count later with MinBWs
883c9157d92SDimitry Andric   // size, to make sure all entries in MinBWs have been handled.
884c9157d92SDimitry Andric   unsigned NumProcessedRecipes = 0;
885c9157d92SDimitry Andric #endif
886c9157d92SDimitry Andric   // Keep track of created truncates, so they can be re-used. Note that we
887c9157d92SDimitry Andric   // cannot use RAUW after creating a new truncate, as this would could make
888c9157d92SDimitry Andric   // other uses have different types for their operands, making them invalidly
889c9157d92SDimitry Andric   // typed.
890c9157d92SDimitry Andric   DenseMap<VPValue *, VPWidenCastRecipe *> ProcessedTruncs;
891c9157d92SDimitry Andric   VPTypeAnalysis TypeInfo(Ctx);
892c9157d92SDimitry Andric   VPBasicBlock *PH = Plan.getEntry();
893c9157d92SDimitry Andric   for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(
894c9157d92SDimitry Andric            vp_depth_first_deep(Plan.getVectorLoopRegion()))) {
895c9157d92SDimitry Andric     for (VPRecipeBase &R : make_early_inc_range(*VPBB)) {
896c9157d92SDimitry Andric       if (!isa<VPWidenRecipe, VPWidenCastRecipe, VPReplicateRecipe,
897*a58f00eaSDimitry Andric                VPWidenSelectRecipe, VPWidenMemoryInstructionRecipe>(&R))
898*a58f00eaSDimitry Andric         continue;
899*a58f00eaSDimitry Andric       if (isa<VPWidenMemoryInstructionRecipe>(&R) &&
900*a58f00eaSDimitry Andric           cast<VPWidenMemoryInstructionRecipe>(&R)->isStore())
901c9157d92SDimitry Andric         continue;
902c9157d92SDimitry Andric 
903c9157d92SDimitry Andric       VPValue *ResultVPV = R.getVPSingleValue();
904c9157d92SDimitry Andric       auto *UI = cast_or_null<Instruction>(ResultVPV->getUnderlyingValue());
905c9157d92SDimitry Andric       unsigned NewResSizeInBits = MinBWs.lookup(UI);
906c9157d92SDimitry Andric       if (!NewResSizeInBits)
907c9157d92SDimitry Andric         continue;
908c9157d92SDimitry Andric 
909c9157d92SDimitry Andric #ifndef NDEBUG
910c9157d92SDimitry Andric       NumProcessedRecipes++;
911c9157d92SDimitry Andric #endif
912c9157d92SDimitry Andric       // If the value wasn't vectorized, we must maintain the original scalar
913c9157d92SDimitry Andric       // type. Skip those here, after incrementing NumProcessedRecipes. Also
914c9157d92SDimitry Andric       // skip casts which do not need to be handled explicitly here, as
915c9157d92SDimitry Andric       // redundant casts will be removed during recipe simplification.
916c9157d92SDimitry Andric       if (isa<VPReplicateRecipe, VPWidenCastRecipe>(&R)) {
917c9157d92SDimitry Andric #ifndef NDEBUG
918c9157d92SDimitry Andric         // If any of the operands is a live-in and not used by VPWidenRecipe or
919c9157d92SDimitry Andric         // VPWidenSelectRecipe, but in MinBWs, make sure it is counted as
920c9157d92SDimitry Andric         // processed as well. When MinBWs is currently constructed, there is no
921c9157d92SDimitry Andric         // information about whether recipes are widened or replicated and in
922c9157d92SDimitry Andric         // case they are reciplicated the operands are not truncated. Counting
923c9157d92SDimitry Andric         // them them here ensures we do not miss any recipes in MinBWs.
924c9157d92SDimitry Andric         // TODO: Remove once the analysis is done on VPlan.
925c9157d92SDimitry Andric         for (VPValue *Op : R.operands()) {
926c9157d92SDimitry Andric           if (!Op->isLiveIn())
927c9157d92SDimitry Andric             continue;
928c9157d92SDimitry Andric           auto *UV = dyn_cast_or_null<Instruction>(Op->getUnderlyingValue());
929c9157d92SDimitry Andric           if (UV && MinBWs.contains(UV) && !ProcessedTruncs.contains(Op) &&
930c9157d92SDimitry Andric               all_of(Op->users(), [](VPUser *U) {
931c9157d92SDimitry Andric                 return !isa<VPWidenRecipe, VPWidenSelectRecipe>(U);
932c9157d92SDimitry Andric               })) {
933c9157d92SDimitry Andric             // Add an entry to ProcessedTruncs to avoid counting the same
934c9157d92SDimitry Andric             // operand multiple times.
935c9157d92SDimitry Andric             ProcessedTruncs[Op] = nullptr;
936c9157d92SDimitry Andric             NumProcessedRecipes += 1;
937c9157d92SDimitry Andric           }
938c9157d92SDimitry Andric         }
939c9157d92SDimitry Andric #endif
940c9157d92SDimitry Andric         continue;
941c9157d92SDimitry Andric       }
942c9157d92SDimitry Andric 
943c9157d92SDimitry Andric       Type *OldResTy = TypeInfo.inferScalarType(ResultVPV);
944c9157d92SDimitry Andric       unsigned OldResSizeInBits = OldResTy->getScalarSizeInBits();
945c9157d92SDimitry Andric       assert(OldResTy->isIntegerTy() && "only integer types supported");
946c9157d92SDimitry Andric       if (OldResSizeInBits == NewResSizeInBits)
947c9157d92SDimitry Andric         continue;
948c9157d92SDimitry Andric       assert(OldResSizeInBits > NewResSizeInBits && "Nothing to shrink?");
949c9157d92SDimitry Andric       (void)OldResSizeInBits;
950c9157d92SDimitry Andric 
951c9157d92SDimitry Andric       auto *NewResTy = IntegerType::get(Ctx, NewResSizeInBits);
952c9157d92SDimitry Andric 
953*a58f00eaSDimitry Andric       // Any wrapping introduced by shrinking this operation shouldn't be
954*a58f00eaSDimitry Andric       // considered undefined behavior. So, we can't unconditionally copy
955*a58f00eaSDimitry Andric       // arithmetic wrapping flags to VPW.
956*a58f00eaSDimitry Andric       if (auto *VPW = dyn_cast<VPRecipeWithIRFlags>(&R))
957*a58f00eaSDimitry Andric         VPW->dropPoisonGeneratingFlags();
958*a58f00eaSDimitry Andric 
959*a58f00eaSDimitry Andric       // Extend result to original width.
960*a58f00eaSDimitry Andric       auto *Ext = new VPWidenCastRecipe(Instruction::ZExt, ResultVPV, OldResTy);
961*a58f00eaSDimitry Andric       Ext->insertAfter(&R);
962*a58f00eaSDimitry Andric       ResultVPV->replaceAllUsesWith(Ext);
963*a58f00eaSDimitry Andric       Ext->setOperand(0, ResultVPV);
964*a58f00eaSDimitry Andric 
965*a58f00eaSDimitry Andric       if (isa<VPWidenMemoryInstructionRecipe>(&R)) {
966*a58f00eaSDimitry Andric         assert(!cast<VPWidenMemoryInstructionRecipe>(&R)->isStore() && "stores cannot be narrowed");
967*a58f00eaSDimitry Andric         continue;
968*a58f00eaSDimitry Andric       }
969*a58f00eaSDimitry Andric 
970c9157d92SDimitry Andric       // Shrink operands by introducing truncates as needed.
971c9157d92SDimitry Andric       unsigned StartIdx = isa<VPWidenSelectRecipe>(&R) ? 1 : 0;
972c9157d92SDimitry Andric       for (unsigned Idx = StartIdx; Idx != R.getNumOperands(); ++Idx) {
973c9157d92SDimitry Andric         auto *Op = R.getOperand(Idx);
974c9157d92SDimitry Andric         unsigned OpSizeInBits =
975c9157d92SDimitry Andric             TypeInfo.inferScalarType(Op)->getScalarSizeInBits();
976c9157d92SDimitry Andric         if (OpSizeInBits == NewResSizeInBits)
977c9157d92SDimitry Andric           continue;
978c9157d92SDimitry Andric         assert(OpSizeInBits > NewResSizeInBits && "nothing to truncate");
979c9157d92SDimitry Andric         auto [ProcessedIter, IterIsEmpty] =
980c9157d92SDimitry Andric             ProcessedTruncs.insert({Op, nullptr});
981c9157d92SDimitry Andric         VPWidenCastRecipe *NewOp =
982c9157d92SDimitry Andric             IterIsEmpty
983c9157d92SDimitry Andric                 ? new VPWidenCastRecipe(Instruction::Trunc, Op, NewResTy)
984c9157d92SDimitry Andric                 : ProcessedIter->second;
985c9157d92SDimitry Andric         R.setOperand(Idx, NewOp);
986c9157d92SDimitry Andric         if (!IterIsEmpty)
987c9157d92SDimitry Andric           continue;
988c9157d92SDimitry Andric         ProcessedIter->second = NewOp;
989c9157d92SDimitry Andric         if (!Op->isLiveIn()) {
990c9157d92SDimitry Andric           NewOp->insertBefore(&R);
991c9157d92SDimitry Andric         } else {
992c9157d92SDimitry Andric           PH->appendRecipe(NewOp);
993c9157d92SDimitry Andric #ifndef NDEBUG
994c9157d92SDimitry Andric           auto *OpInst = dyn_cast<Instruction>(Op->getLiveInIRValue());
995c9157d92SDimitry Andric           bool IsContained = MinBWs.contains(OpInst);
996c9157d92SDimitry Andric           NumProcessedRecipes += IsContained;
997c9157d92SDimitry Andric #endif
998c9157d92SDimitry Andric         }
999c9157d92SDimitry Andric       }
1000c9157d92SDimitry Andric 
1001c9157d92SDimitry Andric     }
1002c9157d92SDimitry Andric   }
1003c9157d92SDimitry Andric 
1004c9157d92SDimitry Andric   assert(MinBWs.size() == NumProcessedRecipes &&
1005c9157d92SDimitry Andric          "some entries in MinBWs haven't been processed");
1006c9157d92SDimitry Andric }
1007c9157d92SDimitry Andric 
optimize(VPlan & Plan,ScalarEvolution & SE)1008c9157d92SDimitry Andric void VPlanTransforms::optimize(VPlan &Plan, ScalarEvolution &SE) {
1009c9157d92SDimitry Andric   removeRedundantCanonicalIVs(Plan);
1010c9157d92SDimitry Andric   removeRedundantInductionCasts(Plan);
1011c9157d92SDimitry Andric 
1012c9157d92SDimitry Andric   optimizeInductions(Plan, SE);
1013c9157d92SDimitry Andric   simplifyRecipes(Plan, SE.getContext());
1014c9157d92SDimitry Andric   removeDeadRecipes(Plan);
1015c9157d92SDimitry Andric 
1016c9157d92SDimitry Andric   createAndOptimizeReplicateRegions(Plan);
1017c9157d92SDimitry Andric 
1018c9157d92SDimitry Andric   removeRedundantExpandSCEVRecipes(Plan);
1019c9157d92SDimitry Andric   mergeBlocksIntoPredecessors(Plan);
1020c9157d92SDimitry Andric }
1021c9157d92SDimitry Andric 
1022c9157d92SDimitry Andric // Add a VPActiveLaneMaskPHIRecipe and related recipes to \p Plan and replace
1023c9157d92SDimitry Andric // the loop terminator with a branch-on-cond recipe with the negated
1024c9157d92SDimitry Andric // active-lane-mask as operand. Note that this turns the loop into an
1025c9157d92SDimitry Andric // uncountable one. Only the existing terminator is replaced, all other existing
1026c9157d92SDimitry Andric // recipes/users remain unchanged, except for poison-generating flags being
1027c9157d92SDimitry Andric // dropped from the canonical IV increment. Return the created
1028c9157d92SDimitry Andric // VPActiveLaneMaskPHIRecipe.
1029c9157d92SDimitry Andric //
1030c9157d92SDimitry Andric // The function uses the following definitions:
1031c9157d92SDimitry Andric //
1032c9157d92SDimitry Andric //  %TripCount = DataWithControlFlowWithoutRuntimeCheck ?
1033c9157d92SDimitry Andric //    calculate-trip-count-minus-VF (original TC) : original TC
1034c9157d92SDimitry Andric //  %IncrementValue = DataWithControlFlowWithoutRuntimeCheck ?
1035c9157d92SDimitry Andric //     CanonicalIVPhi : CanonicalIVIncrement
1036c9157d92SDimitry Andric //  %StartV is the canonical induction start value.
1037c9157d92SDimitry Andric //
1038c9157d92SDimitry Andric // The function adds the following recipes:
1039c9157d92SDimitry Andric //
1040c9157d92SDimitry Andric // vector.ph:
1041c9157d92SDimitry Andric //   %TripCount = calculate-trip-count-minus-VF (original TC)
1042c9157d92SDimitry Andric //       [if DataWithControlFlowWithoutRuntimeCheck]
1043c9157d92SDimitry Andric //   %EntryInc = canonical-iv-increment-for-part %StartV
1044c9157d92SDimitry Andric //   %EntryALM = active-lane-mask %EntryInc, %TripCount
1045c9157d92SDimitry Andric //
1046c9157d92SDimitry Andric // vector.body:
1047c9157d92SDimitry Andric //   ...
1048c9157d92SDimitry Andric //   %P = active-lane-mask-phi [ %EntryALM, %vector.ph ], [ %ALM, %vector.body ]
1049c9157d92SDimitry Andric //   ...
1050c9157d92SDimitry Andric //   %InLoopInc = canonical-iv-increment-for-part %IncrementValue
1051c9157d92SDimitry Andric //   %ALM = active-lane-mask %InLoopInc, TripCount
1052c9157d92SDimitry Andric //   %Negated = Not %ALM
1053c9157d92SDimitry Andric //   branch-on-cond %Negated
1054c9157d92SDimitry Andric //
addVPLaneMaskPhiAndUpdateExitBranch(VPlan & Plan,bool DataAndControlFlowWithoutRuntimeCheck)1055c9157d92SDimitry Andric static VPActiveLaneMaskPHIRecipe *addVPLaneMaskPhiAndUpdateExitBranch(
1056c9157d92SDimitry Andric     VPlan &Plan, bool DataAndControlFlowWithoutRuntimeCheck) {
1057c9157d92SDimitry Andric   VPRegionBlock *TopRegion = Plan.getVectorLoopRegion();
1058c9157d92SDimitry Andric   VPBasicBlock *EB = TopRegion->getExitingBasicBlock();
1059c9157d92SDimitry Andric   auto *CanonicalIVPHI = Plan.getCanonicalIV();
1060c9157d92SDimitry Andric   VPValue *StartV = CanonicalIVPHI->getStartValue();
1061c9157d92SDimitry Andric 
1062c9157d92SDimitry Andric   auto *CanonicalIVIncrement =
1063c9157d92SDimitry Andric       cast<VPInstruction>(CanonicalIVPHI->getBackedgeValue());
1064c9157d92SDimitry Andric   // TODO: Check if dropping the flags is needed if
1065c9157d92SDimitry Andric   // !DataAndControlFlowWithoutRuntimeCheck.
1066c9157d92SDimitry Andric   CanonicalIVIncrement->dropPoisonGeneratingFlags();
1067c9157d92SDimitry Andric   DebugLoc DL = CanonicalIVIncrement->getDebugLoc();
1068c9157d92SDimitry Andric   // We can't use StartV directly in the ActiveLaneMask VPInstruction, since
1069c9157d92SDimitry Andric   // we have to take unrolling into account. Each part needs to start at
1070c9157d92SDimitry Andric   //   Part * VF
1071c9157d92SDimitry Andric   auto *VecPreheader = cast<VPBasicBlock>(TopRegion->getSinglePredecessor());
1072c9157d92SDimitry Andric   VPBuilder Builder(VecPreheader);
1073c9157d92SDimitry Andric 
1074c9157d92SDimitry Andric   // Create the ActiveLaneMask instruction using the correct start values.
1075c9157d92SDimitry Andric   VPValue *TC = Plan.getTripCount();
1076c9157d92SDimitry Andric 
1077c9157d92SDimitry Andric   VPValue *TripCount, *IncrementValue;
1078c9157d92SDimitry Andric   if (!DataAndControlFlowWithoutRuntimeCheck) {
1079c9157d92SDimitry Andric     // When the loop is guarded by a runtime overflow check for the loop
1080c9157d92SDimitry Andric     // induction variable increment by VF, we can increment the value before
1081c9157d92SDimitry Andric     // the get.active.lane mask and use the unmodified tripcount.
1082c9157d92SDimitry Andric     IncrementValue = CanonicalIVIncrement;
1083c9157d92SDimitry Andric     TripCount = TC;
1084c9157d92SDimitry Andric   } else {
1085c9157d92SDimitry Andric     // When avoiding a runtime check, the active.lane.mask inside the loop
1086c9157d92SDimitry Andric     // uses a modified trip count and the induction variable increment is
1087c9157d92SDimitry Andric     // done after the active.lane.mask intrinsic is called.
1088c9157d92SDimitry Andric     IncrementValue = CanonicalIVPHI;
1089c9157d92SDimitry Andric     TripCount = Builder.createNaryOp(VPInstruction::CalculateTripCountMinusVF,
1090c9157d92SDimitry Andric                                      {TC}, DL);
1091c9157d92SDimitry Andric   }
1092c9157d92SDimitry Andric   auto *EntryIncrement = Builder.createOverflowingOp(
1093c9157d92SDimitry Andric       VPInstruction::CanonicalIVIncrementForPart, {StartV}, {false, false}, DL,
1094c9157d92SDimitry Andric       "index.part.next");
1095c9157d92SDimitry Andric 
1096c9157d92SDimitry Andric   // Create the active lane mask instruction in the VPlan preheader.
1097c9157d92SDimitry Andric   auto *EntryALM =
1098c9157d92SDimitry Andric       Builder.createNaryOp(VPInstruction::ActiveLaneMask, {EntryIncrement, TC},
1099c9157d92SDimitry Andric                            DL, "active.lane.mask.entry");
1100c9157d92SDimitry Andric 
1101c9157d92SDimitry Andric   // Now create the ActiveLaneMaskPhi recipe in the main loop using the
1102c9157d92SDimitry Andric   // preheader ActiveLaneMask instruction.
1103c9157d92SDimitry Andric   auto LaneMaskPhi = new VPActiveLaneMaskPHIRecipe(EntryALM, DebugLoc());
1104c9157d92SDimitry Andric   LaneMaskPhi->insertAfter(CanonicalIVPHI);
1105c9157d92SDimitry Andric 
1106c9157d92SDimitry Andric   // Create the active lane mask for the next iteration of the loop before the
1107c9157d92SDimitry Andric   // original terminator.
1108c9157d92SDimitry Andric   VPRecipeBase *OriginalTerminator = EB->getTerminator();
1109c9157d92SDimitry Andric   Builder.setInsertPoint(OriginalTerminator);
1110c9157d92SDimitry Andric   auto *InLoopIncrement =
1111c9157d92SDimitry Andric       Builder.createOverflowingOp(VPInstruction::CanonicalIVIncrementForPart,
1112c9157d92SDimitry Andric                                   {IncrementValue}, {false, false}, DL);
1113c9157d92SDimitry Andric   auto *ALM = Builder.createNaryOp(VPInstruction::ActiveLaneMask,
1114c9157d92SDimitry Andric                                    {InLoopIncrement, TripCount}, DL,
1115c9157d92SDimitry Andric                                    "active.lane.mask.next");
1116c9157d92SDimitry Andric   LaneMaskPhi->addOperand(ALM);
1117c9157d92SDimitry Andric 
1118c9157d92SDimitry Andric   // Replace the original terminator with BranchOnCond. We have to invert the
1119c9157d92SDimitry Andric   // mask here because a true condition means jumping to the exit block.
1120c9157d92SDimitry Andric   auto *NotMask = Builder.createNot(ALM, DL);
1121c9157d92SDimitry Andric   Builder.createNaryOp(VPInstruction::BranchOnCond, {NotMask}, DL);
1122c9157d92SDimitry Andric   OriginalTerminator->eraseFromParent();
1123c9157d92SDimitry Andric   return LaneMaskPhi;
1124c9157d92SDimitry Andric }
1125c9157d92SDimitry Andric 
addActiveLaneMask(VPlan & Plan,bool UseActiveLaneMaskForControlFlow,bool DataAndControlFlowWithoutRuntimeCheck)1126c9157d92SDimitry Andric void VPlanTransforms::addActiveLaneMask(
1127c9157d92SDimitry Andric     VPlan &Plan, bool UseActiveLaneMaskForControlFlow,
1128c9157d92SDimitry Andric     bool DataAndControlFlowWithoutRuntimeCheck) {
1129c9157d92SDimitry Andric   assert((!DataAndControlFlowWithoutRuntimeCheck ||
1130c9157d92SDimitry Andric           UseActiveLaneMaskForControlFlow) &&
1131c9157d92SDimitry Andric          "DataAndControlFlowWithoutRuntimeCheck implies "
1132c9157d92SDimitry Andric          "UseActiveLaneMaskForControlFlow");
1133c9157d92SDimitry Andric 
1134c9157d92SDimitry Andric   auto FoundWidenCanonicalIVUser =
1135c9157d92SDimitry Andric       find_if(Plan.getCanonicalIV()->users(),
1136c9157d92SDimitry Andric               [](VPUser *U) { return isa<VPWidenCanonicalIVRecipe>(U); });
1137c9157d92SDimitry Andric   assert(FoundWidenCanonicalIVUser &&
1138c9157d92SDimitry Andric          "Must have widened canonical IV when tail folding!");
1139c9157d92SDimitry Andric   auto *WideCanonicalIV =
1140c9157d92SDimitry Andric       cast<VPWidenCanonicalIVRecipe>(*FoundWidenCanonicalIVUser);
1141*a58f00eaSDimitry Andric   VPSingleDefRecipe *LaneMask;
1142c9157d92SDimitry Andric   if (UseActiveLaneMaskForControlFlow) {
1143c9157d92SDimitry Andric     LaneMask = addVPLaneMaskPhiAndUpdateExitBranch(
1144c9157d92SDimitry Andric         Plan, DataAndControlFlowWithoutRuntimeCheck);
1145c9157d92SDimitry Andric   } else {
1146c9157d92SDimitry Andric     LaneMask = new VPInstruction(VPInstruction::ActiveLaneMask,
1147c9157d92SDimitry Andric                                  {WideCanonicalIV, Plan.getTripCount()},
1148c9157d92SDimitry Andric                                  nullptr, "active.lane.mask");
1149c9157d92SDimitry Andric     LaneMask->insertAfter(WideCanonicalIV);
1150c9157d92SDimitry Andric   }
1151c9157d92SDimitry Andric 
1152c9157d92SDimitry Andric   // Walk users of WideCanonicalIV and replace all compares of the form
1153c9157d92SDimitry Andric   // (ICMP_ULE, WideCanonicalIV, backedge-taken-count) with an
1154c9157d92SDimitry Andric   // active-lane-mask.
1155c9157d92SDimitry Andric   VPValue *BTC = Plan.getOrCreateBackedgeTakenCount();
1156c9157d92SDimitry Andric   for (VPUser *U : SmallVector<VPUser *>(WideCanonicalIV->users())) {
1157c9157d92SDimitry Andric     auto *CompareToReplace = dyn_cast<VPInstruction>(U);
1158c9157d92SDimitry Andric     if (!CompareToReplace ||
1159c9157d92SDimitry Andric         CompareToReplace->getOpcode() != Instruction::ICmp ||
1160c9157d92SDimitry Andric         CompareToReplace->getPredicate() != CmpInst::ICMP_ULE ||
1161c9157d92SDimitry Andric         CompareToReplace->getOperand(1) != BTC)
1162c9157d92SDimitry Andric       continue;
1163c9157d92SDimitry Andric 
1164c9157d92SDimitry Andric     assert(CompareToReplace->getOperand(0) == WideCanonicalIV &&
1165c9157d92SDimitry Andric            "WidenCanonicalIV must be the first operand of the compare");
1166*a58f00eaSDimitry Andric     CompareToReplace->replaceAllUsesWith(LaneMask);
1167c9157d92SDimitry Andric     CompareToReplace->eraseFromParent();
1168c9157d92SDimitry Andric   }
1169c9157d92SDimitry Andric }
1170