xref: /freebsd-src/contrib/llvm-project/llvm/lib/Transforms/Vectorize/VPlanTransforms.cpp (revision c9ccf3a32da427475985b85d7df023ccfb138c27)
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 "llvm/ADT/PostOrderIterator.h"
16 
17 using namespace llvm;
18 
19 void VPlanTransforms::VPInstructionsToVPRecipes(
20     Loop *OrigLoop, VPlanPtr &Plan,
21     function_ref<const InductionDescriptor *(PHINode *)>
22         GetIntOrFpInductionDescriptor,
23     SmallPtrSetImpl<Instruction *> &DeadInstructions, ScalarEvolution &SE) {
24 
25   auto *TopRegion = cast<VPRegionBlock>(Plan->getEntry());
26   ReversePostOrderTraversal<VPBlockBase *> RPOT(TopRegion->getEntry());
27 
28   for (VPBlockBase *Base : RPOT) {
29     // Do not widen instructions in pre-header and exit blocks.
30     if (Base->getNumPredecessors() == 0 || Base->getNumSuccessors() == 0)
31       continue;
32 
33     VPBasicBlock *VPBB = Base->getEntryBasicBlock();
34     // Introduce each ingredient into VPlan.
35     for (VPRecipeBase &Ingredient : llvm::make_early_inc_range(*VPBB)) {
36       VPValue *VPV = Ingredient.getVPSingleValue();
37       Instruction *Inst = cast<Instruction>(VPV->getUnderlyingValue());
38       if (DeadInstructions.count(Inst)) {
39         VPValue DummyValue;
40         VPV->replaceAllUsesWith(&DummyValue);
41         Ingredient.eraseFromParent();
42         continue;
43       }
44 
45       VPRecipeBase *NewRecipe = nullptr;
46       if (auto *VPPhi = dyn_cast<VPWidenPHIRecipe>(&Ingredient)) {
47         auto *Phi = cast<PHINode>(VPPhi->getUnderlyingValue());
48         if (const auto *II = GetIntOrFpInductionDescriptor(Phi)) {
49           VPValue *Start = Plan->getOrAddVPValue(II->getStartValue());
50           NewRecipe =
51               new VPWidenIntOrFpInductionRecipe(Phi, Start, *II, false, true);
52         } else {
53           Plan->addVPValue(Phi, VPPhi);
54           continue;
55         }
56       } else {
57         assert(isa<VPInstruction>(&Ingredient) &&
58                "only VPInstructions expected here");
59         assert(!isa<PHINode>(Inst) && "phis should be handled above");
60         // Create VPWidenMemoryInstructionRecipe for loads and stores.
61         if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
62           NewRecipe = new VPWidenMemoryInstructionRecipe(
63               *Load, Plan->getOrAddVPValue(getLoadStorePointerOperand(Inst)),
64               nullptr /*Mask*/, false /*Consecutive*/, false /*Reverse*/);
65         } else if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) {
66           NewRecipe = new VPWidenMemoryInstructionRecipe(
67               *Store, Plan->getOrAddVPValue(getLoadStorePointerOperand(Inst)),
68               Plan->getOrAddVPValue(Store->getValueOperand()), nullptr /*Mask*/,
69               false /*Consecutive*/, false /*Reverse*/);
70         } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Inst)) {
71           NewRecipe = new VPWidenGEPRecipe(
72               GEP, Plan->mapToVPValues(GEP->operands()), OrigLoop);
73         } else if (CallInst *CI = dyn_cast<CallInst>(Inst)) {
74           NewRecipe =
75               new VPWidenCallRecipe(*CI, Plan->mapToVPValues(CI->args()));
76         } else if (SelectInst *SI = dyn_cast<SelectInst>(Inst)) {
77           bool InvariantCond =
78               SE.isLoopInvariant(SE.getSCEV(SI->getOperand(0)), OrigLoop);
79           NewRecipe = new VPWidenSelectRecipe(
80               *SI, Plan->mapToVPValues(SI->operands()), InvariantCond);
81         } else {
82           NewRecipe =
83               new VPWidenRecipe(*Inst, Plan->mapToVPValues(Inst->operands()));
84         }
85       }
86 
87       NewRecipe->insertBefore(&Ingredient);
88       if (NewRecipe->getNumDefinedValues() == 1)
89         VPV->replaceAllUsesWith(NewRecipe->getVPSingleValue());
90       else
91         assert(NewRecipe->getNumDefinedValues() == 0 &&
92                "Only recpies with zero or one defined values expected");
93       Ingredient.eraseFromParent();
94       Plan->removeVPValueFor(Inst);
95       for (auto *Def : NewRecipe->definedValues()) {
96         Plan->addVPValue(Inst, Def);
97       }
98     }
99   }
100 }
101 
102 bool VPlanTransforms::sinkScalarOperands(VPlan &Plan) {
103   auto Iter = depth_first(
104       VPBlockRecursiveTraversalWrapper<VPBlockBase *>(Plan.getEntry()));
105   bool Changed = false;
106   // First, collect the operands of all predicated replicate recipes as seeds
107   // for sinking.
108   SetVector<std::pair<VPBasicBlock *, VPValue *>> WorkList;
109   for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(Iter)) {
110     for (auto &Recipe : *VPBB) {
111       auto *RepR = dyn_cast<VPReplicateRecipe>(&Recipe);
112       if (!RepR || !RepR->isPredicated())
113         continue;
114       for (VPValue *Op : RepR->operands())
115         WorkList.insert(std::make_pair(RepR->getParent(), Op));
116     }
117   }
118 
119   // Try to sink each replicate recipe in the worklist.
120   while (!WorkList.empty()) {
121     VPBasicBlock *SinkTo;
122     VPValue *C;
123     std::tie(SinkTo, C) = WorkList.pop_back_val();
124     auto *SinkCandidate = dyn_cast_or_null<VPReplicateRecipe>(C->Def);
125     if (!SinkCandidate || SinkCandidate->isUniform() ||
126         SinkCandidate->getParent() == SinkTo ||
127         SinkCandidate->mayHaveSideEffects() ||
128         SinkCandidate->mayReadOrWriteMemory())
129       continue;
130 
131     bool NeedsDuplicating = false;
132     // All recipe users of the sink candidate must be in the same block SinkTo
133     // or all users outside of SinkTo must be uniform-after-vectorization (
134     // i.e., only first lane is used) . In the latter case, we need to duplicate
135     // SinkCandidate. At the moment, we identify such UAV's by looking for the
136     // address operands of widened memory recipes.
137     auto CanSinkWithUser = [SinkTo, &NeedsDuplicating,
138                             SinkCandidate](VPUser *U) {
139       auto *UI = dyn_cast<VPRecipeBase>(U);
140       if (!UI)
141         return false;
142       if (UI->getParent() == SinkTo)
143         return true;
144       auto *WidenI = dyn_cast<VPWidenMemoryInstructionRecipe>(UI);
145       if (WidenI && WidenI->getAddr() == SinkCandidate) {
146         NeedsDuplicating = true;
147         return true;
148       }
149       return false;
150     };
151     if (!all_of(SinkCandidate->users(), CanSinkWithUser))
152       continue;
153 
154     if (NeedsDuplicating) {
155       Instruction *I = cast<Instruction>(SinkCandidate->getUnderlyingValue());
156       auto *Clone =
157           new VPReplicateRecipe(I, SinkCandidate->operands(), true, false);
158       // TODO: add ".cloned" suffix to name of Clone's VPValue.
159 
160       Clone->insertBefore(SinkCandidate);
161       SmallVector<VPUser *, 4> Users(SinkCandidate->users());
162       for (auto *U : Users) {
163         auto *UI = cast<VPRecipeBase>(U);
164         if (UI->getParent() == SinkTo)
165           continue;
166 
167         for (unsigned Idx = 0; Idx != UI->getNumOperands(); Idx++) {
168           if (UI->getOperand(Idx) != SinkCandidate)
169             continue;
170           UI->setOperand(Idx, Clone);
171         }
172       }
173     }
174     SinkCandidate->moveBefore(*SinkTo, SinkTo->getFirstNonPhi());
175     for (VPValue *Op : SinkCandidate->operands())
176       WorkList.insert(std::make_pair(SinkTo, Op));
177     Changed = true;
178   }
179   return Changed;
180 }
181 
182 /// If \p R is a region with a VPBranchOnMaskRecipe in the entry block, return
183 /// the mask.
184 VPValue *getPredicatedMask(VPRegionBlock *R) {
185   auto *EntryBB = dyn_cast<VPBasicBlock>(R->getEntry());
186   if (!EntryBB || EntryBB->size() != 1 ||
187       !isa<VPBranchOnMaskRecipe>(EntryBB->begin()))
188     return nullptr;
189 
190   return cast<VPBranchOnMaskRecipe>(&*EntryBB->begin())->getOperand(0);
191 }
192 
193 /// If \p R is a triangle region, return the 'then' block of the triangle.
194 static VPBasicBlock *getPredicatedThenBlock(VPRegionBlock *R) {
195   auto *EntryBB = cast<VPBasicBlock>(R->getEntry());
196   if (EntryBB->getNumSuccessors() != 2)
197     return nullptr;
198 
199   auto *Succ0 = dyn_cast<VPBasicBlock>(EntryBB->getSuccessors()[0]);
200   auto *Succ1 = dyn_cast<VPBasicBlock>(EntryBB->getSuccessors()[1]);
201   if (!Succ0 || !Succ1)
202     return nullptr;
203 
204   if (Succ0->getNumSuccessors() + Succ1->getNumSuccessors() != 1)
205     return nullptr;
206   if (Succ0->getSingleSuccessor() == Succ1)
207     return Succ0;
208   if (Succ1->getSingleSuccessor() == Succ0)
209     return Succ1;
210   return nullptr;
211 }
212 
213 bool VPlanTransforms::mergeReplicateRegions(VPlan &Plan) {
214   SetVector<VPRegionBlock *> DeletedRegions;
215   bool Changed = false;
216 
217   // Collect region blocks to process up-front, to avoid iterator invalidation
218   // issues while merging regions.
219   SmallVector<VPRegionBlock *, 8> CandidateRegions(
220       VPBlockUtils::blocksOnly<VPRegionBlock>(depth_first(
221           VPBlockRecursiveTraversalWrapper<VPBlockBase *>(Plan.getEntry()))));
222 
223   // Check if Base is a predicated triangle, followed by an empty block,
224   // followed by another predicate triangle. If that's the case, move the
225   // recipes from the first to the second triangle.
226   for (VPRegionBlock *Region1 : CandidateRegions) {
227     if (DeletedRegions.contains(Region1))
228       continue;
229     auto *MiddleBasicBlock =
230         dyn_cast_or_null<VPBasicBlock>(Region1->getSingleSuccessor());
231     if (!MiddleBasicBlock || !MiddleBasicBlock->empty())
232       continue;
233 
234     auto *Region2 =
235         dyn_cast_or_null<VPRegionBlock>(MiddleBasicBlock->getSingleSuccessor());
236     if (!Region2)
237       continue;
238 
239     VPValue *Mask1 = getPredicatedMask(Region1);
240     VPValue *Mask2 = getPredicatedMask(Region2);
241     if (!Mask1 || Mask1 != Mask2)
242       continue;
243     VPBasicBlock *Then1 = getPredicatedThenBlock(Region1);
244     VPBasicBlock *Then2 = getPredicatedThenBlock(Region2);
245     if (!Then1 || !Then2)
246       continue;
247 
248     assert(Mask1 && Mask2 && "both region must have conditions");
249 
250     // Note: No fusion-preventing memory dependencies are expected in either
251     // region. Such dependencies should be rejected during earlier dependence
252     // checks, which guarantee accesses can be re-ordered for vectorization.
253     //
254     // Move recipes to the successor region.
255     for (VPRecipeBase &ToMove : make_early_inc_range(reverse(*Then1)))
256       ToMove.moveBefore(*Then2, Then2->getFirstNonPhi());
257 
258     auto *Merge1 = cast<VPBasicBlock>(Then1->getSingleSuccessor());
259     auto *Merge2 = cast<VPBasicBlock>(Then2->getSingleSuccessor());
260 
261     // Move VPPredInstPHIRecipes from the merge block to the successor region's
262     // merge block. Update all users inside the successor region to use the
263     // original values.
264     for (VPRecipeBase &Phi1ToMove : make_early_inc_range(reverse(*Merge1))) {
265       VPValue *PredInst1 =
266           cast<VPPredInstPHIRecipe>(&Phi1ToMove)->getOperand(0);
267       VPValue *Phi1ToMoveV = Phi1ToMove.getVPSingleValue();
268       SmallVector<VPUser *> Users(Phi1ToMoveV->users());
269       for (VPUser *U : Users) {
270         auto *UI = dyn_cast<VPRecipeBase>(U);
271         if (!UI || UI->getParent() != Then2)
272           continue;
273         for (unsigned I = 0, E = U->getNumOperands(); I != E; ++I) {
274           if (Phi1ToMoveV != U->getOperand(I))
275             continue;
276           U->setOperand(I, PredInst1);
277         }
278       }
279 
280       Phi1ToMove.moveBefore(*Merge2, Merge2->begin());
281     }
282 
283     // Finally, remove the first region.
284     for (VPBlockBase *Pred : make_early_inc_range(Region1->getPredecessors())) {
285       VPBlockUtils::disconnectBlocks(Pred, Region1);
286       VPBlockUtils::connectBlocks(Pred, MiddleBasicBlock);
287     }
288     VPBlockUtils::disconnectBlocks(Region1, MiddleBasicBlock);
289     DeletedRegions.insert(Region1);
290   }
291 
292   for (VPRegionBlock *ToDelete : DeletedRegions)
293     delete ToDelete;
294   return Changed;
295 }
296 
297 void VPlanTransforms::removeRedundantInductionCasts(VPlan &Plan) {
298   SmallVector<std::pair<VPRecipeBase *, VPValue *>> CastsToRemove;
299   for (auto &Phi : Plan.getEntry()->getEntryBasicBlock()->phis()) {
300     auto *IV = dyn_cast<VPWidenIntOrFpInductionRecipe>(&Phi);
301     if (!IV || IV->getTruncInst())
302       continue;
303 
304     // Visit all casts connected to IV and in Casts. Collect them.
305     // remember them for removal.
306     auto &Casts = IV->getInductionDescriptor().getCastInsts();
307     VPValue *FindMyCast = IV;
308     for (Instruction *IRCast : reverse(Casts)) {
309       VPRecipeBase *FoundUserCast = nullptr;
310       for (auto *U : FindMyCast->users()) {
311         auto *UserCast = cast<VPRecipeBase>(U);
312         if (UserCast->getNumDefinedValues() == 1 &&
313             UserCast->getVPSingleValue()->getUnderlyingValue() == IRCast) {
314           FoundUserCast = UserCast;
315           break;
316         }
317       }
318       assert(FoundUserCast && "Missing a cast to remove");
319       CastsToRemove.emplace_back(FoundUserCast, IV);
320       FindMyCast = FoundUserCast->getVPSingleValue();
321     }
322   }
323   for (auto &E : CastsToRemove) {
324     E.first->getVPSingleValue()->replaceAllUsesWith(E.second);
325     E.first->eraseFromParent();
326   }
327 }
328 
329 void VPlanTransforms::removeRedundantCanonicalIVs(VPlan &Plan) {
330   VPCanonicalIVPHIRecipe *CanonicalIV = Plan.getCanonicalIV();
331   VPWidenCanonicalIVRecipe *WidenNewIV = nullptr;
332   for (VPUser *U : CanonicalIV->users()) {
333     WidenNewIV = dyn_cast<VPWidenCanonicalIVRecipe>(U);
334     if (WidenNewIV)
335       break;
336   }
337 
338   if (!WidenNewIV)
339     return;
340 
341   VPBasicBlock *HeaderVPBB = Plan.getVectorLoopRegion()->getEntryBasicBlock();
342   for (VPRecipeBase &Phi : HeaderVPBB->phis()) {
343     auto *WidenOriginalIV = dyn_cast<VPWidenIntOrFpInductionRecipe>(&Phi);
344 
345     if (!WidenOriginalIV || !WidenOriginalIV->isCanonical() ||
346         WidenOriginalIV->getScalarType() != WidenNewIV->getScalarType())
347       continue;
348 
349     // Replace WidenNewIV with WidenOriginalIV if WidenOriginalIV provides
350     // everything WidenNewIV's users need. That is, WidenOriginalIV will
351     // generate a vector phi or all users of WidenNewIV demand the first lane
352     // only.
353     if (WidenOriginalIV->needsVectorIV() ||
354         vputils::onlyFirstLaneUsed(WidenNewIV)) {
355       WidenNewIV->replaceAllUsesWith(WidenOriginalIV);
356       WidenNewIV->eraseFromParent();
357       return;
358     }
359   }
360 }
361