VPlanTransforms.cpp 14 KB

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