VPlanTransforms.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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 "VPlanCFG.h"
  15. #include "llvm/ADT/PostOrderIterator.h"
  16. #include "llvm/ADT/SetVector.h"
  17. #include "llvm/Analysis/IVDescriptors.h"
  18. #include "llvm/Analysis/VectorUtils.h"
  19. #include "llvm/IR/Intrinsics.h"
  20. using namespace llvm;
  21. void VPlanTransforms::VPInstructionsToVPRecipes(
  22. Loop *OrigLoop, VPlanPtr &Plan,
  23. function_ref<const InductionDescriptor *(PHINode *)>
  24. GetIntOrFpInductionDescriptor,
  25. SmallPtrSetImpl<Instruction *> &DeadInstructions, ScalarEvolution &SE,
  26. const TargetLibraryInfo &TLI) {
  27. ReversePostOrderTraversal<VPBlockDeepTraversalWrapper<VPBlockBase *>> RPOT(
  28. Plan->getEntry());
  29. for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(RPOT)) {
  30. VPRecipeBase *Term = VPBB->getTerminator();
  31. auto EndIter = Term ? Term->getIterator() : VPBB->end();
  32. // Introduce each ingredient into VPlan.
  33. for (VPRecipeBase &Ingredient :
  34. make_early_inc_range(make_range(VPBB->begin(), EndIter))) {
  35. VPValue *VPV = Ingredient.getVPSingleValue();
  36. Instruction *Inst = cast<Instruction>(VPV->getUnderlyingValue());
  37. if (DeadInstructions.count(Inst)) {
  38. VPValue DummyValue;
  39. VPV->replaceAllUsesWith(&DummyValue);
  40. Ingredient.eraseFromParent();
  41. continue;
  42. }
  43. VPRecipeBase *NewRecipe = nullptr;
  44. if (auto *VPPhi = dyn_cast<VPWidenPHIRecipe>(&Ingredient)) {
  45. auto *Phi = cast<PHINode>(VPPhi->getUnderlyingValue());
  46. if (const auto *II = GetIntOrFpInductionDescriptor(Phi)) {
  47. VPValue *Start = Plan->getOrAddVPValue(II->getStartValue());
  48. VPValue *Step =
  49. vputils::getOrCreateVPValueForSCEVExpr(*Plan, II->getStep(), SE);
  50. NewRecipe =
  51. new VPWidenIntOrFpInductionRecipe(Phi, Start, Step, *II, 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. getVectorIntrinsicIDForCall(CI, &TLI));
  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. 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. bool VPlanTransforms::sinkScalarOperands(VPlan &Plan) {
  102. auto Iter = vp_depth_first_deep(Plan.getEntry());
  103. bool Changed = false;
  104. // First, collect the operands of all recipes in replicate blocks as seeds for
  105. // sinking.
  106. SetVector<std::pair<VPBasicBlock *, VPRecipeBase *>> WorkList;
  107. for (VPRegionBlock *VPR : VPBlockUtils::blocksOnly<VPRegionBlock>(Iter)) {
  108. VPBasicBlock *EntryVPBB = VPR->getEntryBasicBlock();
  109. if (!VPR->isReplicator() || EntryVPBB->getSuccessors().size() != 2)
  110. continue;
  111. VPBasicBlock *VPBB = dyn_cast<VPBasicBlock>(EntryVPBB->getSuccessors()[0]);
  112. if (!VPBB || VPBB->getSingleSuccessor() != VPR->getExitingBasicBlock())
  113. continue;
  114. for (auto &Recipe : *VPBB) {
  115. for (VPValue *Op : Recipe.operands())
  116. if (auto *Def = Op->getDefiningRecipe())
  117. WorkList.insert(std::make_pair(VPBB, Def));
  118. }
  119. }
  120. bool ScalarVFOnly = Plan.hasScalarVFOnly();
  121. // Try to sink each replicate or scalar IV steps recipe in the worklist.
  122. for (unsigned I = 0; I != WorkList.size(); ++I) {
  123. VPBasicBlock *SinkTo;
  124. VPRecipeBase *SinkCandidate;
  125. std::tie(SinkTo, SinkCandidate) = WorkList[I];
  126. if (SinkCandidate->getParent() == SinkTo ||
  127. SinkCandidate->mayHaveSideEffects() ||
  128. SinkCandidate->mayReadOrWriteMemory())
  129. continue;
  130. if (auto *RepR = dyn_cast<VPReplicateRecipe>(SinkCandidate)) {
  131. if (!ScalarVFOnly && RepR->isUniform())
  132. continue;
  133. } else if (!isa<VPScalarIVStepsRecipe>(SinkCandidate))
  134. continue;
  135. bool NeedsDuplicating = false;
  136. // All recipe users of the sink candidate must be in the same block SinkTo
  137. // or all users outside of SinkTo must be uniform-after-vectorization (
  138. // i.e., only first lane is used) . In the latter case, we need to duplicate
  139. // SinkCandidate.
  140. auto CanSinkWithUser = [SinkTo, &NeedsDuplicating,
  141. SinkCandidate](VPUser *U) {
  142. auto *UI = dyn_cast<VPRecipeBase>(U);
  143. if (!UI)
  144. return false;
  145. if (UI->getParent() == SinkTo)
  146. return true;
  147. NeedsDuplicating =
  148. UI->onlyFirstLaneUsed(SinkCandidate->getVPSingleValue());
  149. // We only know how to duplicate VPRecipeRecipes for now.
  150. return NeedsDuplicating && isa<VPReplicateRecipe>(SinkCandidate);
  151. };
  152. if (!all_of(SinkCandidate->getVPSingleValue()->users(), CanSinkWithUser))
  153. continue;
  154. if (NeedsDuplicating) {
  155. if (ScalarVFOnly)
  156. continue;
  157. Instruction *I = cast<Instruction>(
  158. cast<VPReplicateRecipe>(SinkCandidate)->getUnderlyingValue());
  159. auto *Clone =
  160. new VPReplicateRecipe(I, SinkCandidate->operands(), true, false);
  161. // TODO: add ".cloned" suffix to name of Clone's VPValue.
  162. Clone->insertBefore(SinkCandidate);
  163. for (auto *U : to_vector(SinkCandidate->getVPSingleValue()->users())) {
  164. auto *UI = cast<VPRecipeBase>(U);
  165. if (UI->getParent() == SinkTo)
  166. continue;
  167. for (unsigned Idx = 0; Idx != UI->getNumOperands(); Idx++) {
  168. if (UI->getOperand(Idx) != SinkCandidate->getVPSingleValue())
  169. continue;
  170. UI->setOperand(Idx, Clone);
  171. }
  172. }
  173. }
  174. SinkCandidate->moveBefore(*SinkTo, SinkTo->getFirstNonPhi());
  175. for (VPValue *Op : SinkCandidate->operands())
  176. if (auto *Def = Op->getDefiningRecipe())
  177. WorkList.insert(std::make_pair(SinkTo, Def));
  178. Changed = true;
  179. }
  180. return Changed;
  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. return cast<VPBranchOnMaskRecipe>(&*EntryBB->begin())->getOperand(0);
  190. }
  191. /// If \p R is a triangle region, return the 'then' block of the triangle.
  192. static VPBasicBlock *getPredicatedThenBlock(VPRegionBlock *R) {
  193. auto *EntryBB = cast<VPBasicBlock>(R->getEntry());
  194. if (EntryBB->getNumSuccessors() != 2)
  195. return nullptr;
  196. auto *Succ0 = dyn_cast<VPBasicBlock>(EntryBB->getSuccessors()[0]);
  197. auto *Succ1 = dyn_cast<VPBasicBlock>(EntryBB->getSuccessors()[1]);
  198. if (!Succ0 || !Succ1)
  199. return nullptr;
  200. if (Succ0->getNumSuccessors() + Succ1->getNumSuccessors() != 1)
  201. return nullptr;
  202. if (Succ0->getSingleSuccessor() == Succ1)
  203. return Succ0;
  204. if (Succ1->getSingleSuccessor() == Succ0)
  205. return Succ1;
  206. return nullptr;
  207. }
  208. bool VPlanTransforms::mergeReplicateRegionsIntoSuccessors(VPlan &Plan) {
  209. SetVector<VPRegionBlock *> DeletedRegions;
  210. // Collect replicate regions followed by an empty block, followed by another
  211. // replicate region with matching masks to process front. This is to avoid
  212. // iterator invalidation issues while merging regions.
  213. SmallVector<VPRegionBlock *, 8> WorkList;
  214. for (VPRegionBlock *Region1 : VPBlockUtils::blocksOnly<VPRegionBlock>(
  215. vp_depth_first_deep(Plan.getEntry()))) {
  216. if (!Region1->isReplicator())
  217. continue;
  218. auto *MiddleBasicBlock =
  219. dyn_cast_or_null<VPBasicBlock>(Region1->getSingleSuccessor());
  220. if (!MiddleBasicBlock || !MiddleBasicBlock->empty())
  221. continue;
  222. auto *Region2 =
  223. dyn_cast_or_null<VPRegionBlock>(MiddleBasicBlock->getSingleSuccessor());
  224. if (!Region2 || !Region2->isReplicator())
  225. continue;
  226. VPValue *Mask1 = getPredicatedMask(Region1);
  227. VPValue *Mask2 = getPredicatedMask(Region2);
  228. if (!Mask1 || Mask1 != Mask2)
  229. continue;
  230. assert(Mask1 && Mask2 && "both region must have conditions");
  231. WorkList.push_back(Region1);
  232. }
  233. // Move recipes from Region1 to its successor region, if both are triangles.
  234. for (VPRegionBlock *Region1 : WorkList) {
  235. if (DeletedRegions.contains(Region1))
  236. continue;
  237. auto *MiddleBasicBlock = cast<VPBasicBlock>(Region1->getSingleSuccessor());
  238. auto *Region2 = cast<VPRegionBlock>(MiddleBasicBlock->getSingleSuccessor());
  239. VPBasicBlock *Then1 = getPredicatedThenBlock(Region1);
  240. VPBasicBlock *Then2 = getPredicatedThenBlock(Region2);
  241. if (!Then1 || !Then2)
  242. continue;
  243. // Note: No fusion-preventing memory dependencies are expected in either
  244. // region. Such dependencies should be rejected during earlier dependence
  245. // checks, which guarantee accesses can be re-ordered for vectorization.
  246. //
  247. // Move recipes to the successor region.
  248. for (VPRecipeBase &ToMove : make_early_inc_range(reverse(*Then1)))
  249. ToMove.moveBefore(*Then2, Then2->getFirstNonPhi());
  250. auto *Merge1 = cast<VPBasicBlock>(Then1->getSingleSuccessor());
  251. auto *Merge2 = cast<VPBasicBlock>(Then2->getSingleSuccessor());
  252. // Move VPPredInstPHIRecipes from the merge block to the successor region's
  253. // merge block. Update all users inside the successor region to use the
  254. // original values.
  255. for (VPRecipeBase &Phi1ToMove : make_early_inc_range(reverse(*Merge1))) {
  256. VPValue *PredInst1 =
  257. cast<VPPredInstPHIRecipe>(&Phi1ToMove)->getOperand(0);
  258. VPValue *Phi1ToMoveV = Phi1ToMove.getVPSingleValue();
  259. for (VPUser *U : to_vector(Phi1ToMoveV->users())) {
  260. auto *UI = dyn_cast<VPRecipeBase>(U);
  261. if (!UI || UI->getParent() != Then2)
  262. continue;
  263. for (unsigned I = 0, E = U->getNumOperands(); I != E; ++I) {
  264. if (Phi1ToMoveV != U->getOperand(I))
  265. continue;
  266. U->setOperand(I, PredInst1);
  267. }
  268. }
  269. Phi1ToMove.moveBefore(*Merge2, Merge2->begin());
  270. }
  271. // Finally, remove the first region.
  272. for (VPBlockBase *Pred : make_early_inc_range(Region1->getPredecessors())) {
  273. VPBlockUtils::disconnectBlocks(Pred, Region1);
  274. VPBlockUtils::connectBlocks(Pred, MiddleBasicBlock);
  275. }
  276. VPBlockUtils::disconnectBlocks(Region1, MiddleBasicBlock);
  277. DeletedRegions.insert(Region1);
  278. }
  279. for (VPRegionBlock *ToDelete : DeletedRegions)
  280. delete ToDelete;
  281. return !DeletedRegions.empty();
  282. }
  283. bool VPlanTransforms::mergeBlocksIntoPredecessors(VPlan &Plan) {
  284. SmallVector<VPBasicBlock *> WorkList;
  285. for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(
  286. vp_depth_first_deep(Plan.getEntry()))) {
  287. auto *PredVPBB =
  288. dyn_cast_or_null<VPBasicBlock>(VPBB->getSinglePredecessor());
  289. if (PredVPBB && PredVPBB->getNumSuccessors() == 1)
  290. WorkList.push_back(VPBB);
  291. }
  292. for (VPBasicBlock *VPBB : WorkList) {
  293. VPBasicBlock *PredVPBB = cast<VPBasicBlock>(VPBB->getSinglePredecessor());
  294. for (VPRecipeBase &R : make_early_inc_range(*VPBB))
  295. R.moveBefore(*PredVPBB, PredVPBB->end());
  296. VPBlockUtils::disconnectBlocks(PredVPBB, VPBB);
  297. auto *ParentRegion = cast_or_null<VPRegionBlock>(VPBB->getParent());
  298. if (ParentRegion && ParentRegion->getExiting() == VPBB)
  299. ParentRegion->setExiting(PredVPBB);
  300. for (auto *Succ : to_vector(VPBB->successors())) {
  301. VPBlockUtils::disconnectBlocks(VPBB, Succ);
  302. VPBlockUtils::connectBlocks(PredVPBB, Succ);
  303. }
  304. delete VPBB;
  305. }
  306. return !WorkList.empty();
  307. }
  308. void VPlanTransforms::removeRedundantInductionCasts(VPlan &Plan) {
  309. for (auto &Phi : Plan.getVectorLoopRegion()->getEntryBasicBlock()->phis()) {
  310. auto *IV = dyn_cast<VPWidenIntOrFpInductionRecipe>(&Phi);
  311. if (!IV || IV->getTruncInst())
  312. continue;
  313. // A sequence of IR Casts has potentially been recorded for IV, which
  314. // *must be bypassed* when the IV is vectorized, because the vectorized IV
  315. // will produce the desired casted value. This sequence forms a def-use
  316. // chain and is provided in reverse order, ending with the cast that uses
  317. // the IV phi. Search for the recipe of the last cast in the chain and
  318. // replace it with the original IV. Note that only the final cast is
  319. // expected to have users outside the cast-chain and the dead casts left
  320. // over will be cleaned up later.
  321. auto &Casts = IV->getInductionDescriptor().getCastInsts();
  322. VPValue *FindMyCast = IV;
  323. for (Instruction *IRCast : reverse(Casts)) {
  324. VPRecipeBase *FoundUserCast = nullptr;
  325. for (auto *U : FindMyCast->users()) {
  326. auto *UserCast = cast<VPRecipeBase>(U);
  327. if (UserCast->getNumDefinedValues() == 1 &&
  328. UserCast->getVPSingleValue()->getUnderlyingValue() == IRCast) {
  329. FoundUserCast = UserCast;
  330. break;
  331. }
  332. }
  333. FindMyCast = FoundUserCast->getVPSingleValue();
  334. }
  335. FindMyCast->replaceAllUsesWith(IV);
  336. }
  337. }
  338. void VPlanTransforms::removeRedundantCanonicalIVs(VPlan &Plan) {
  339. VPCanonicalIVPHIRecipe *CanonicalIV = Plan.getCanonicalIV();
  340. VPWidenCanonicalIVRecipe *WidenNewIV = nullptr;
  341. for (VPUser *U : CanonicalIV->users()) {
  342. WidenNewIV = dyn_cast<VPWidenCanonicalIVRecipe>(U);
  343. if (WidenNewIV)
  344. break;
  345. }
  346. if (!WidenNewIV)
  347. return;
  348. VPBasicBlock *HeaderVPBB = Plan.getVectorLoopRegion()->getEntryBasicBlock();
  349. for (VPRecipeBase &Phi : HeaderVPBB->phis()) {
  350. auto *WidenOriginalIV = dyn_cast<VPWidenIntOrFpInductionRecipe>(&Phi);
  351. if (!WidenOriginalIV || !WidenOriginalIV->isCanonical() ||
  352. WidenOriginalIV->getScalarType() != WidenNewIV->getScalarType())
  353. continue;
  354. // Replace WidenNewIV with WidenOriginalIV if WidenOriginalIV provides
  355. // everything WidenNewIV's users need. That is, WidenOriginalIV will
  356. // generate a vector phi or all users of WidenNewIV demand the first lane
  357. // only.
  358. if (WidenOriginalIV->needsVectorIV() ||
  359. vputils::onlyFirstLaneUsed(WidenNewIV)) {
  360. WidenNewIV->replaceAllUsesWith(WidenOriginalIV);
  361. WidenNewIV->eraseFromParent();
  362. return;
  363. }
  364. }
  365. }
  366. void VPlanTransforms::removeDeadRecipes(VPlan &Plan) {
  367. ReversePostOrderTraversal<VPBlockDeepTraversalWrapper<VPBlockBase *>> RPOT(
  368. Plan.getEntry());
  369. for (VPBasicBlock *VPBB : reverse(VPBlockUtils::blocksOnly<VPBasicBlock>(RPOT))) {
  370. // The recipes in the block are processed in reverse order, to catch chains
  371. // of dead recipes.
  372. for (VPRecipeBase &R : make_early_inc_range(reverse(*VPBB))) {
  373. if (R.mayHaveSideEffects() || any_of(R.definedValues(), [](VPValue *V) {
  374. return V->getNumUsers() > 0;
  375. }))
  376. continue;
  377. R.eraseFromParent();
  378. }
  379. }
  380. }
  381. void VPlanTransforms::optimizeInductions(VPlan &Plan, ScalarEvolution &SE) {
  382. SmallVector<VPRecipeBase *> ToRemove;
  383. VPBasicBlock *HeaderVPBB = Plan.getVectorLoopRegion()->getEntryBasicBlock();
  384. bool HasOnlyVectorVFs = !Plan.hasVF(ElementCount::getFixed(1));
  385. for (VPRecipeBase &Phi : HeaderVPBB->phis()) {
  386. auto *WideIV = dyn_cast<VPWidenIntOrFpInductionRecipe>(&Phi);
  387. if (!WideIV)
  388. continue;
  389. if (HasOnlyVectorVFs && none_of(WideIV->users(), [WideIV](VPUser *U) {
  390. return U->usesScalars(WideIV);
  391. }))
  392. continue;
  393. auto IP = HeaderVPBB->getFirstNonPhi();
  394. VPCanonicalIVPHIRecipe *CanonicalIV = Plan.getCanonicalIV();
  395. Type *ResultTy = WideIV->getPHINode()->getType();
  396. if (Instruction *TruncI = WideIV->getTruncInst())
  397. ResultTy = TruncI->getType();
  398. const InductionDescriptor &ID = WideIV->getInductionDescriptor();
  399. VPValue *Step =
  400. vputils::getOrCreateVPValueForSCEVExpr(Plan, ID.getStep(), SE);
  401. VPValue *BaseIV = CanonicalIV;
  402. if (!CanonicalIV->isCanonical(ID, ResultTy)) {
  403. BaseIV = new VPDerivedIVRecipe(ID, WideIV->getStartValue(), CanonicalIV,
  404. Step, ResultTy);
  405. HeaderVPBB->insert(BaseIV->getDefiningRecipe(), IP);
  406. }
  407. VPScalarIVStepsRecipe *Steps = new VPScalarIVStepsRecipe(ID, BaseIV, Step);
  408. HeaderVPBB->insert(Steps, IP);
  409. // Update scalar users of IV to use Step instead. Use SetVector to ensure
  410. // the list of users doesn't contain duplicates.
  411. SetVector<VPUser *> Users(WideIV->user_begin(), WideIV->user_end());
  412. for (VPUser *U : Users) {
  413. if (HasOnlyVectorVFs && !U->usesScalars(WideIV))
  414. continue;
  415. for (unsigned I = 0, E = U->getNumOperands(); I != E; I++) {
  416. if (U->getOperand(I) != WideIV)
  417. continue;
  418. U->setOperand(I, Steps);
  419. }
  420. }
  421. }
  422. }
  423. void VPlanTransforms::removeRedundantExpandSCEVRecipes(VPlan &Plan) {
  424. DenseMap<const SCEV *, VPValue *> SCEV2VPV;
  425. for (VPRecipeBase &R :
  426. make_early_inc_range(*Plan.getEntry()->getEntryBasicBlock())) {
  427. auto *ExpR = dyn_cast<VPExpandSCEVRecipe>(&R);
  428. if (!ExpR)
  429. continue;
  430. auto I = SCEV2VPV.insert({ExpR->getSCEV(), ExpR});
  431. if (I.second)
  432. continue;
  433. ExpR->replaceAllUsesWith(I.first->second);
  434. ExpR->eraseFromParent();
  435. }
  436. }
  437. static bool canSimplifyBranchOnCond(VPInstruction *Term) {
  438. VPInstruction *Not = dyn_cast<VPInstruction>(Term->getOperand(0));
  439. if (!Not || Not->getOpcode() != VPInstruction::Not)
  440. return false;
  441. VPInstruction *ALM = dyn_cast<VPInstruction>(Not->getOperand(0));
  442. return ALM && ALM->getOpcode() == VPInstruction::ActiveLaneMask;
  443. }
  444. void VPlanTransforms::optimizeForVFAndUF(VPlan &Plan, ElementCount BestVF,
  445. unsigned BestUF,
  446. PredicatedScalarEvolution &PSE) {
  447. assert(Plan.hasVF(BestVF) && "BestVF is not available in Plan");
  448. assert(Plan.hasUF(BestUF) && "BestUF is not available in Plan");
  449. VPBasicBlock *ExitingVPBB =
  450. Plan.getVectorLoopRegion()->getExitingBasicBlock();
  451. auto *Term = dyn_cast<VPInstruction>(&ExitingVPBB->back());
  452. // Try to simplify the branch condition if TC <= VF * UF when preparing to
  453. // execute the plan for the main vector loop. We only do this if the
  454. // terminator is:
  455. // 1. BranchOnCount, or
  456. // 2. BranchOnCond where the input is Not(ActiveLaneMask).
  457. if (!Term || (Term->getOpcode() != VPInstruction::BranchOnCount &&
  458. (Term->getOpcode() != VPInstruction::BranchOnCond ||
  459. !canSimplifyBranchOnCond(Term))))
  460. return;
  461. Type *IdxTy =
  462. Plan.getCanonicalIV()->getStartValue()->getLiveInIRValue()->getType();
  463. const SCEV *TripCount = createTripCountSCEV(IdxTy, PSE);
  464. ScalarEvolution &SE = *PSE.getSE();
  465. const SCEV *C =
  466. SE.getConstant(TripCount->getType(), BestVF.getKnownMinValue() * BestUF);
  467. if (TripCount->isZero() ||
  468. !SE.isKnownPredicate(CmpInst::ICMP_ULE, TripCount, C))
  469. return;
  470. LLVMContext &Ctx = SE.getContext();
  471. auto *BOC =
  472. new VPInstruction(VPInstruction::BranchOnCond,
  473. {Plan.getOrAddExternalDef(ConstantInt::getTrue(Ctx))});
  474. Term->eraseFromParent();
  475. ExitingVPBB->appendRecipe(BOC);
  476. Plan.setVF(BestVF);
  477. Plan.setUF(BestUF);
  478. // TODO: Further simplifications are possible
  479. // 1. Replace inductions with constants.
  480. // 2. Replace vector loop region with VPBasicBlock.
  481. }