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 #include "llvm/ADT/SetVector.h"
17 
18 using namespace llvm;
19 
20 void VPlanTransforms::VPInstructionsToVPRecipes(
21     Loop *OrigLoop, VPlanPtr &Plan,
22     function_ref<const InductionDescriptor *(PHINode *)>
23         GetIntOrFpInductionDescriptor,
24     SmallPtrSetImpl<Instruction *> &DeadInstructions, ScalarEvolution &SE) {
25 
26   auto *TopRegion = cast<VPRegionBlock>(Plan->getEntry());
27   ReversePostOrderTraversal<VPBlockBase *> RPOT(TopRegion->getEntry());
28 
29   for (VPBlockBase *Base : RPOT) {
30     // Do not widen instructions in pre-header and exit blocks.
31     if (Base->getNumPredecessors() == 0 || Base->getNumSuccessors() == 0)
32       continue;
33 
34     VPBasicBlock *VPBB = Base->getEntryBasicBlock();
35     // Introduce each ingredient into VPlan.
36     for (VPRecipeBase &Ingredient : llvm::make_early_inc_range(*VPBB)) {
37       VPValue *VPV = Ingredient.getVPSingleValue();
38       Instruction *Inst = cast<Instruction>(VPV->getUnderlyingValue());
39       if (DeadInstructions.count(Inst)) {
40         VPValue DummyValue;
41         VPV->replaceAllUsesWith(&DummyValue);
42         Ingredient.eraseFromParent();
43         continue;
44       }
45 
46       VPRecipeBase *NewRecipe = nullptr;
47       if (auto *VPPhi = dyn_cast<VPWidenPHIRecipe>(&Ingredient)) {
48         auto *Phi = cast<PHINode>(VPPhi->getUnderlyingValue());
49         if (const auto *II = GetIntOrFpInductionDescriptor(Phi)) {
50           VPValue *Start = Plan->getOrAddVPValue(II->getStartValue());
51           NewRecipe = new VPWidenIntOrFpInductionRecipe(Phi, Start, *II, false,
52                                                         true, SE);
53         } else {
54           Plan->addVPValue(Phi, VPPhi);
55           continue;
56         }
57       } else {
58         assert(isa<VPInstruction>(&Ingredient) &&
59                "only VPInstructions expected here");
60         assert(!isa<PHINode>(Inst) && "phis should be handled above");
61         // Create VPWidenMemoryInstructionRecipe for loads and stores.
62         if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
63           NewRecipe = new VPWidenMemoryInstructionRecipe(
64               *Load, Plan->getOrAddVPValue(getLoadStorePointerOperand(Inst)),
65               nullptr /*Mask*/, false /*Consecutive*/, false /*Reverse*/);
66         } else if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) {
67           NewRecipe = new VPWidenMemoryInstructionRecipe(
68               *Store, Plan->getOrAddVPValue(getLoadStorePointerOperand(Inst)),
69               Plan->getOrAddVPValue(Store->getValueOperand()), nullptr /*Mask*/,
70               false /*Consecutive*/, false /*Reverse*/);
71         } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Inst)) {
72           NewRecipe = new VPWidenGEPRecipe(
73               GEP, Plan->mapToVPValues(GEP->operands()), OrigLoop);
74         } else if (CallInst *CI = dyn_cast<CallInst>(Inst)) {
75           NewRecipe =
76               new VPWidenCallRecipe(*CI, Plan->mapToVPValues(CI->args()));
77         } else if (SelectInst *SI = dyn_cast<SelectInst>(Inst)) {
78           bool InvariantCond =
79               SE.isLoopInvariant(SE.getSCEV(SI->getOperand(0)), OrigLoop);
80           NewRecipe = new VPWidenSelectRecipe(
81               *SI, Plan->mapToVPValues(SI->operands()), InvariantCond);
82         } else {
83           NewRecipe =
84               new VPWidenRecipe(*Inst, Plan->mapToVPValues(Inst->operands()));
85         }
86       }
87 
88       NewRecipe->insertBefore(&Ingredient);
89       if (NewRecipe->getNumDefinedValues() == 1)
90         VPV->replaceAllUsesWith(NewRecipe->getVPSingleValue());
91       else
92         assert(NewRecipe->getNumDefinedValues() == 0 &&
93                "Only recpies with zero or one defined values expected");
94       Ingredient.eraseFromParent();
95       Plan->removeVPValueFor(Inst);
96       for (auto *Def : NewRecipe->definedValues()) {
97         Plan->addVPValue(Inst, Def);
98       }
99     }
100   }
101 }
102 
103 bool VPlanTransforms::sinkScalarOperands(VPlan &Plan) {
104   auto Iter = depth_first(
105       VPBlockRecursiveTraversalWrapper<VPBlockBase *>(Plan.getEntry()));
106   bool Changed = false;
107   // First, collect the operands of all predicated replicate recipes as seeds
108   // for sinking.
109   SetVector<std::pair<VPBasicBlock *, VPValue *>> WorkList;
110   for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(Iter)) {
111     for (auto &Recipe : *VPBB) {
112       auto *RepR = dyn_cast<VPReplicateRecipe>(&Recipe);
113       if (!RepR || !RepR->isPredicated())
114         continue;
115       for (VPValue *Op : RepR->operands())
116         WorkList.insert(std::make_pair(RepR->getParent(), Op));
117     }
118   }
119 
120   // Try to sink each replicate recipe in the worklist.
121   while (!WorkList.empty()) {
122     VPBasicBlock *SinkTo;
123     VPValue *C;
124     std::tie(SinkTo, C) = WorkList.pop_back_val();
125     auto *SinkCandidate = dyn_cast_or_null<VPReplicateRecipe>(C->Def);
126     if (!SinkCandidate || SinkCandidate->isUniform() ||
127         SinkCandidate->getParent() == SinkTo ||
128         SinkCandidate->mayHaveSideEffects() ||
129         SinkCandidate->mayReadOrWriteMemory())
130       continue;
131 
132     bool NeedsDuplicating = false;
133     // All recipe users of the sink candidate must be in the same block SinkTo
134     // or all users outside of SinkTo must be uniform-after-vectorization (
135     // i.e., only first lane is used) . In the latter case, we need to duplicate
136     // SinkCandidate. At the moment, we identify such UAV's by looking for the
137     // address operands of widened memory recipes.
138     auto CanSinkWithUser = [SinkTo, &NeedsDuplicating,
139                             SinkCandidate](VPUser *U) {
140       auto *UI = dyn_cast<VPRecipeBase>(U);
141       if (!UI)
142         return false;
143       if (UI->getParent() == SinkTo)
144         return true;
145       auto *WidenI = dyn_cast<VPWidenMemoryInstructionRecipe>(UI);
146       if (WidenI && WidenI->getAddr() == SinkCandidate) {
147         NeedsDuplicating = true;
148         return true;
149       }
150       return false;
151     };
152     if (!all_of(SinkCandidate->users(), CanSinkWithUser))
153       continue;
154 
155     if (NeedsDuplicating) {
156       Instruction *I = cast<Instruction>(SinkCandidate->getUnderlyingValue());
157       auto *Clone =
158           new VPReplicateRecipe(I, SinkCandidate->operands(), true, false);
159       // TODO: add ".cloned" suffix to name of Clone's VPValue.
160 
161       Clone->insertBefore(SinkCandidate);
162       SmallVector<VPUser *, 4> Users(SinkCandidate->users());
163       for (auto *U : Users) {
164         auto *UI = cast<VPRecipeBase>(U);
165         if (UI->getParent() == SinkTo)
166           continue;
167 
168         for (unsigned Idx = 0; Idx != UI->getNumOperands(); Idx++) {
169           if (UI->getOperand(Idx) != SinkCandidate)
170             continue;
171           UI->setOperand(Idx, Clone);
172         }
173       }
174     }
175     SinkCandidate->moveBefore(*SinkTo, SinkTo->getFirstNonPhi());
176     for (VPValue *Op : SinkCandidate->operands())
177       WorkList.insert(std::make_pair(SinkTo, Op));
178     Changed = true;
179   }
180   return Changed;
181 }
182 
183 /// If \p R is a region with a VPBranchOnMaskRecipe in the entry block, return
184 /// the mask.
185 VPValue *getPredicatedMask(VPRegionBlock *R) {
186   auto *EntryBB = dyn_cast<VPBasicBlock>(R->getEntry());
187   if (!EntryBB || EntryBB->size() != 1 ||
188       !isa<VPBranchOnMaskRecipe>(EntryBB->begin()))
189     return nullptr;
190 
191   return cast<VPBranchOnMaskRecipe>(&*EntryBB->begin())->getOperand(0);
192 }
193 
194 /// If \p R is a triangle region, return the 'then' block of the triangle.
195 static VPBasicBlock *getPredicatedThenBlock(VPRegionBlock *R) {
196   auto *EntryBB = cast<VPBasicBlock>(R->getEntry());
197   if (EntryBB->getNumSuccessors() != 2)
198     return nullptr;
199 
200   auto *Succ0 = dyn_cast<VPBasicBlock>(EntryBB->getSuccessors()[0]);
201   auto *Succ1 = dyn_cast<VPBasicBlock>(EntryBB->getSuccessors()[1]);
202   if (!Succ0 || !Succ1)
203     return nullptr;
204 
205   if (Succ0->getNumSuccessors() + Succ1->getNumSuccessors() != 1)
206     return nullptr;
207   if (Succ0->getSingleSuccessor() == Succ1)
208     return Succ0;
209   if (Succ1->getSingleSuccessor() == Succ0)
210     return Succ1;
211   return nullptr;
212 }
213 
214 bool VPlanTransforms::mergeReplicateRegions(VPlan &Plan) {
215   SetVector<VPRegionBlock *> DeletedRegions;
216   bool Changed = false;
217 
218   // Collect region blocks to process up-front, to avoid iterator invalidation
219   // issues while merging regions.
220   SmallVector<VPRegionBlock *, 8> CandidateRegions(
221       VPBlockUtils::blocksOnly<VPRegionBlock>(depth_first(
222           VPBlockRecursiveTraversalWrapper<VPBlockBase *>(Plan.getEntry()))));
223 
224   // Check if Base is a predicated triangle, followed by an empty block,
225   // followed by another predicate triangle. If that's the case, move the
226   // recipes from the first to the second triangle.
227   for (VPRegionBlock *Region1 : CandidateRegions) {
228     if (DeletedRegions.contains(Region1))
229       continue;
230     auto *MiddleBasicBlock =
231         dyn_cast_or_null<VPBasicBlock>(Region1->getSingleSuccessor());
232     if (!MiddleBasicBlock || !MiddleBasicBlock->empty())
233       continue;
234 
235     auto *Region2 =
236         dyn_cast_or_null<VPRegionBlock>(MiddleBasicBlock->getSingleSuccessor());
237     if (!Region2)
238       continue;
239 
240     VPValue *Mask1 = getPredicatedMask(Region1);
241     VPValue *Mask2 = getPredicatedMask(Region2);
242     if (!Mask1 || Mask1 != Mask2)
243       continue;
244     VPBasicBlock *Then1 = getPredicatedThenBlock(Region1);
245     VPBasicBlock *Then2 = getPredicatedThenBlock(Region2);
246     if (!Then1 || !Then2)
247       continue;
248 
249     assert(Mask1 && Mask2 && "both region must have conditions");
250 
251     // Note: No fusion-preventing memory dependencies are expected in either
252     // region. Such dependencies should be rejected during earlier dependence
253     // checks, which guarantee accesses can be re-ordered for vectorization.
254     //
255     // Move recipes to the successor region.
256     for (VPRecipeBase &ToMove : make_early_inc_range(reverse(*Then1)))
257       ToMove.moveBefore(*Then2, Then2->getFirstNonPhi());
258 
259     auto *Merge1 = cast<VPBasicBlock>(Then1->getSingleSuccessor());
260     auto *Merge2 = cast<VPBasicBlock>(Then2->getSingleSuccessor());
261 
262     // Move VPPredInstPHIRecipes from the merge block to the successor region's
263     // merge block. Update all users inside the successor region to use the
264     // original values.
265     for (VPRecipeBase &Phi1ToMove : make_early_inc_range(reverse(*Merge1))) {
266       VPValue *PredInst1 =
267           cast<VPPredInstPHIRecipe>(&Phi1ToMove)->getOperand(0);
268       VPValue *Phi1ToMoveV = Phi1ToMove.getVPSingleValue();
269       SmallVector<VPUser *> Users(Phi1ToMoveV->users());
270       for (VPUser *U : Users) {
271         auto *UI = dyn_cast<VPRecipeBase>(U);
272         if (!UI || UI->getParent() != Then2)
273           continue;
274         for (unsigned I = 0, E = U->getNumOperands(); I != E; ++I) {
275           if (Phi1ToMoveV != U->getOperand(I))
276             continue;
277           U->setOperand(I, PredInst1);
278         }
279       }
280 
281       Phi1ToMove.moveBefore(*Merge2, Merge2->begin());
282     }
283 
284     // Finally, remove the first region.
285     for (VPBlockBase *Pred : make_early_inc_range(Region1->getPredecessors())) {
286       VPBlockUtils::disconnectBlocks(Pred, Region1);
287       VPBlockUtils::connectBlocks(Pred, MiddleBasicBlock);
288     }
289     VPBlockUtils::disconnectBlocks(Region1, MiddleBasicBlock);
290     DeletedRegions.insert(Region1);
291   }
292 
293   for (VPRegionBlock *ToDelete : DeletedRegions)
294     delete ToDelete;
295   return Changed;
296 }
297 
298 void VPlanTransforms::removeRedundantInductionCasts(VPlan &Plan) {
299   for (auto &Phi : Plan.getEntry()->getEntryBasicBlock()->phis()) {
300     auto *IV = dyn_cast<VPWidenIntOrFpInductionRecipe>(&Phi);
301     if (!IV || IV->getTruncInst())
302       continue;
303 
304     // A sequence of IR Casts has potentially been recorded for IV, which
305     // *must be bypassed* when the IV is vectorized, because the vectorized IV
306     // will produce the desired casted value. This sequence forms a def-use
307     // chain and is provided in reverse order, ending with the cast that uses
308     // the IV phi. Search for the recipe of the last cast in the chain and
309     // replace it with the original IV. Note that only the final cast is
310     // expected to have users outside the cast-chain and the dead casts left
311     // over will be cleaned up later.
312     auto &Casts = IV->getInductionDescriptor().getCastInsts();
313     VPValue *FindMyCast = IV;
314     for (Instruction *IRCast : reverse(Casts)) {
315       VPRecipeBase *FoundUserCast = nullptr;
316       for (auto *U : FindMyCast->users()) {
317         auto *UserCast = cast<VPRecipeBase>(U);
318         if (UserCast->getNumDefinedValues() == 1 &&
319             UserCast->getVPSingleValue()->getUnderlyingValue() == IRCast) {
320           FoundUserCast = UserCast;
321           break;
322         }
323       }
324       FindMyCast = FoundUserCast->getVPSingleValue();
325     }
326     FindMyCast->replaceAllUsesWith(IV);
327   }
328 }
329 
330 void VPlanTransforms::removeRedundantCanonicalIVs(VPlan &Plan) {
331   VPCanonicalIVPHIRecipe *CanonicalIV = Plan.getCanonicalIV();
332   VPWidenCanonicalIVRecipe *WidenNewIV = nullptr;
333   for (VPUser *U : CanonicalIV->users()) {
334     WidenNewIV = dyn_cast<VPWidenCanonicalIVRecipe>(U);
335     if (WidenNewIV)
336       break;
337   }
338 
339   if (!WidenNewIV)
340     return;
341 
342   VPBasicBlock *HeaderVPBB = Plan.getVectorLoopRegion()->getEntryBasicBlock();
343   for (VPRecipeBase &Phi : HeaderVPBB->phis()) {
344     auto *WidenOriginalIV = dyn_cast<VPWidenIntOrFpInductionRecipe>(&Phi);
345 
346     if (!WidenOriginalIV || !WidenOriginalIV->isCanonical() ||
347         WidenOriginalIV->getScalarType() != WidenNewIV->getScalarType())
348       continue;
349 
350     // Replace WidenNewIV with WidenOriginalIV if WidenOriginalIV provides
351     // everything WidenNewIV's users need. That is, WidenOriginalIV will
352     // generate a vector phi or all users of WidenNewIV demand the first lane
353     // only.
354     if (WidenOriginalIV->needsVectorIV() ||
355         vputils::onlyFirstLaneUsed(WidenNewIV)) {
356       WidenNewIV->replaceAllUsesWith(WidenOriginalIV);
357       WidenNewIV->eraseFromParent();
358       return;
359     }
360   }
361 }
362 
363 // Check for live-out users currently not modeled in VPlan.
364 // Note that exit values of inductions are generated independent of
365 // the recipe. This means  VPWidenIntOrFpInductionRecipe &
366 // VPScalarIVStepsRecipe can be removed, independent of uses outside
367 // the loop.
368 // TODO: Remove once live-outs are modeled in VPlan.
369 static bool hasOutsideUser(Instruction &I, Loop &OrigLoop) {
370   return any_of(I.users(), [&OrigLoop](User *U) {
371     if (!OrigLoop.contains(cast<Instruction>(U)))
372       return true;
373 
374     // Look through single-value phis in the loop, as they won't be modeled in
375     // VPlan and may be used outside the loop.
376     if (auto *PN = dyn_cast<PHINode>(U))
377       if (PN->getNumIncomingValues() == 1)
378         return hasOutsideUser(*PN, OrigLoop);
379 
380     return false;
381   });
382 }
383 
384 void VPlanTransforms::removeDeadRecipes(VPlan &Plan, Loop &OrigLoop) {
385   VPBasicBlock *Header = Plan.getVectorLoopRegion()->getEntryBasicBlock();
386   // Check if \p R is used outside the loop, if required.
387   // TODO: Remove once live-outs are modeled in VPlan.
388   auto HasUsersOutsideLoop = [&OrigLoop](VPRecipeBase &R) {
389     // Exit values for induction recipes are generated independent of the
390     // recipes, expect for truncated inductions. Hence there is no need to check
391     // for users outside the loop for them.
392     if (isa<VPScalarIVStepsRecipe>(&R) ||
393         (isa<VPWidenIntOrFpInductionRecipe>(&R) &&
394          !isa<TruncInst>(R.getUnderlyingInstr())))
395       return false;
396     return R.getUnderlyingInstr() &&
397            hasOutsideUser(*R.getUnderlyingInstr(), OrigLoop);
398   };
399   // Remove dead recipes in header block. The recipes in the block are processed
400   // in reverse order, to catch chains of dead recipes.
401   // TODO: Remove dead recipes across whole plan.
402   for (VPRecipeBase &R : make_early_inc_range(reverse(*Header))) {
403     if (R.mayHaveSideEffects() ||
404         any_of(R.definedValues(),
405                [](VPValue *V) { return V->getNumUsers() > 0; }) ||
406         HasUsersOutsideLoop(R))
407       continue;
408     R.eraseFromParent();
409   }
410 }
411 
412 void VPlanTransforms::optimizeInductions(VPlan &Plan, ScalarEvolution &SE) {
413   SmallVector<VPRecipeBase *> ToRemove;
414   VPBasicBlock *HeaderVPBB = Plan.getVectorLoopRegion()->getEntryBasicBlock();
415   for (VPRecipeBase &Phi : HeaderVPBB->phis()) {
416     auto *IV = dyn_cast<VPWidenIntOrFpInductionRecipe>(&Phi);
417     if (!IV || !IV->needsScalarIV())
418       continue;
419 
420     const InductionDescriptor &ID = IV->getInductionDescriptor();
421     const SCEV *StepSCEV = ID.getStep();
422     VPValue *Step = nullptr;
423     if (auto *E = dyn_cast<SCEVConstant>(StepSCEV)) {
424       Step = new VPValue(E->getValue());
425       Plan.addExternalDef(Step);
426     } else if (auto *E = dyn_cast<SCEVUnknown>(StepSCEV)) {
427       Step = new VPValue(E->getValue());
428       Plan.addExternalDef(Step);
429     } else {
430       Step = new VPExpandSCEVRecipe(StepSCEV, SE);
431     }
432 
433     Instruction *TruncI = IV->getTruncInst();
434     VPScalarIVStepsRecipe *Steps = new VPScalarIVStepsRecipe(
435         IV->getPHINode()->getType(), ID, Plan.getCanonicalIV(),
436         IV->getStartValue(), Step, TruncI ? TruncI->getType() : nullptr);
437 
438     HeaderVPBB->insert(Steps, HeaderVPBB->getFirstNonPhi());
439     if (Step->getDef()) {
440       // TODO: Place the step in the preheader, once it is explicitly modeled in
441       // VPlan.
442       HeaderVPBB->insert(cast<VPRecipeBase>(Step->getDef()),
443                          HeaderVPBB->getFirstNonPhi());
444     }
445 
446     // If there are no vector users of IV, simply update all users to use Step
447     // instead.
448     if (!IV->needsVectorIV()) {
449       IV->replaceAllUsesWith(Steps);
450       continue;
451     }
452 
453     // Otherwise only update scalar users of IV to use Step instead. Use
454     // SetVector to ensure the list of users doesn't contain duplicates.
455     SetVector<VPUser *> Users(IV->user_begin(), IV->user_end());
456     for (VPUser *U : Users) {
457       VPRecipeBase *R = cast<VPRecipeBase>(U);
458       if (!R->usesScalars(IV))
459         continue;
460       for (unsigned I = 0, E = R->getNumOperands(); I != E; I++) {
461         if (R->getOperand(I) != IV)
462           continue;
463         R->setOperand(I, Steps);
464       }
465     }
466   }
467 }
468