LoopDistribute.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802
  1. //===- LoopDistribute.cpp - Loop Distribution Pass ------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the Loop Distribution Pass. Its main focus is to
  11. // distribute loops that cannot be vectorized due to dependence cycles. It
  12. // tries to isolate the offending dependences into a new loop allowing
  13. // vectorization of the remaining parts.
  14. //
  15. // For dependence analysis, the pass uses the LoopVectorizer's
  16. // LoopAccessAnalysis. Because this analysis presumes no change in the order of
  17. // memory operations, special care is taken to preserve the lexical order of
  18. // these operations.
  19. //
  20. // Similarly to the Vectorizer, the pass also supports loop versioning to
  21. // run-time disambiguate potentially overlapping arrays.
  22. //
  23. //===----------------------------------------------------------------------===//
  24. #include "llvm/ADT/DepthFirstIterator.h"
  25. #include "llvm/ADT/EquivalenceClasses.h"
  26. #include "llvm/ADT/STLExtras.h"
  27. #include "llvm/ADT/Statistic.h"
  28. #include "llvm/Analysis/LoopAccessAnalysis.h"
  29. #include "llvm/Analysis/LoopInfo.h"
  30. #include "llvm/IR/Dominators.h"
  31. #include "llvm/Pass.h"
  32. #include "llvm/Support/CommandLine.h"
  33. #include "llvm/Support/Debug.h"
  34. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  35. #include "llvm/Transforms/Utils/Cloning.h"
  36. #include "llvm/Transforms/Utils/LoopVersioning.h"
  37. #include <list>
  38. #define LDIST_NAME "loop-distribute"
  39. #define DEBUG_TYPE LDIST_NAME
  40. using namespace llvm;
  41. #if 0 // HLSL Change Starts - option pending
  42. static cl::opt<bool>
  43. LDistVerify("loop-distribute-verify", cl::Hidden,
  44. cl::desc("Turn on DominatorTree and LoopInfo verification "
  45. "after Loop Distribution"),
  46. cl::init(false));
  47. static cl::opt<bool> DistributeNonIfConvertible(
  48. "loop-distribute-non-if-convertible", cl::Hidden,
  49. cl::desc("Whether to distribute into a loop that may not be "
  50. "if-convertible by the loop vectorizer"),
  51. cl::init(false));
  52. #else
  53. static const bool LDistVerify = false;
  54. static const bool DistributeNonIfConvertible = false;
  55. #endif
  56. STATISTIC(NumLoopsDistributed, "Number of loops distributed");
  57. namespace {
  58. /// \brief Maintains the set of instructions of the loop for a partition before
  59. /// cloning. After cloning, it hosts the new loop.
  60. class InstPartition {
  61. typedef SmallPtrSet<Instruction *, 8> InstructionSet;
  62. public:
  63. InstPartition(Instruction *I, Loop *L, bool DepCycle = false)
  64. : DepCycle(DepCycle), OrigLoop(L), ClonedLoop(nullptr) {
  65. Set.insert(I);
  66. }
  67. /// \brief Returns whether this partition contains a dependence cycle.
  68. bool hasDepCycle() const { return DepCycle; }
  69. /// \brief Adds an instruction to this partition.
  70. void add(Instruction *I) { Set.insert(I); }
  71. /// \brief Collection accessors.
  72. InstructionSet::iterator begin() { return Set.begin(); }
  73. InstructionSet::iterator end() { return Set.end(); }
  74. InstructionSet::const_iterator begin() const { return Set.begin(); }
  75. InstructionSet::const_iterator end() const { return Set.end(); }
  76. bool empty() const { return Set.empty(); }
  77. /// \brief Moves this partition into \p Other. This partition becomes empty
  78. /// after this.
  79. void moveTo(InstPartition &Other) {
  80. Other.Set.insert(Set.begin(), Set.end());
  81. Set.clear();
  82. Other.DepCycle |= DepCycle;
  83. }
  84. /// \brief Populates the partition with a transitive closure of all the
  85. /// instructions that the seeded instructions dependent on.
  86. void populateUsedSet() {
  87. // FIXME: We currently don't use control-dependence but simply include all
  88. // blocks (possibly empty at the end) and let simplifycfg mostly clean this
  89. // up.
  90. for (auto *B : OrigLoop->getBlocks())
  91. Set.insert(B->getTerminator());
  92. // Follow the use-def chains to form a transitive closure of all the
  93. // instructions that the originally seeded instructions depend on.
  94. SmallVector<Instruction *, 8> Worklist(Set.begin(), Set.end());
  95. while (!Worklist.empty()) {
  96. Instruction *I = Worklist.pop_back_val();
  97. // Insert instructions from the loop that we depend on.
  98. for (Value *V : I->operand_values()) {
  99. auto *I = dyn_cast<Instruction>(V);
  100. if (I && OrigLoop->contains(I->getParent()) && Set.insert(I).second)
  101. Worklist.push_back(I);
  102. }
  103. }
  104. }
  105. /// \brief Clones the original loop.
  106. ///
  107. /// Updates LoopInfo and DominatorTree using the information that block \p
  108. /// LoopDomBB dominates the loop.
  109. Loop *cloneLoopWithPreheader(BasicBlock *InsertBefore, BasicBlock *LoopDomBB,
  110. unsigned Index, LoopInfo *LI,
  111. DominatorTree *DT) {
  112. ClonedLoop = ::cloneLoopWithPreheader(InsertBefore, LoopDomBB, OrigLoop,
  113. VMap, Twine(".ldist") + Twine(Index),
  114. LI, DT, ClonedLoopBlocks);
  115. return ClonedLoop;
  116. }
  117. /// \brief The cloned loop. If this partition is mapped to the original loop,
  118. /// this is null.
  119. const Loop *getClonedLoop() const { return ClonedLoop; }
  120. /// \brief Returns the loop where this partition ends up after distribution.
  121. /// If this partition is mapped to the original loop then use the block from
  122. /// the loop.
  123. const Loop *getDistributedLoop() const {
  124. return ClonedLoop ? ClonedLoop : OrigLoop;
  125. }
  126. /// \brief The VMap that is populated by cloning and then used in
  127. /// remapinstruction to remap the cloned instructions.
  128. ValueToValueMapTy &getVMap() { return VMap; }
  129. /// \brief Remaps the cloned instructions using VMap.
  130. void remapInstructions() {
  131. remapInstructionsInBlocks(ClonedLoopBlocks, VMap);
  132. }
  133. /// \brief Based on the set of instructions selected for this partition,
  134. /// removes the unnecessary ones.
  135. void removeUnusedInsts() {
  136. SmallVector<Instruction *, 8> Unused;
  137. for (auto *Block : OrigLoop->getBlocks())
  138. for (auto &Inst : *Block)
  139. if (!Set.count(&Inst)) {
  140. Instruction *NewInst = &Inst;
  141. if (!VMap.empty())
  142. NewInst = cast<Instruction>(VMap[NewInst]);
  143. assert(!isa<BranchInst>(NewInst) &&
  144. "Branches are marked used early on");
  145. Unused.push_back(NewInst);
  146. }
  147. // Delete the instructions backwards, as it has a reduced likelihood of
  148. // having to update as many def-use and use-def chains.
  149. for (auto I = Unused.rbegin(), E = Unused.rend(); I != E; ++I) {
  150. auto *Inst = *I;
  151. if (!Inst->use_empty())
  152. Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
  153. Inst->eraseFromParent();
  154. }
  155. }
  156. void print() const {
  157. if (DepCycle)
  158. dbgs() << " (cycle)\n";
  159. for (auto *I : Set)
  160. // Prefix with the block name.
  161. dbgs() << " " << I->getParent()->getName() << ":" << *I << "\n";
  162. }
  163. void printBlocks() const {
  164. for (auto *BB : getDistributedLoop()->getBlocks())
  165. dbgs() << *BB;
  166. }
  167. private:
  168. /// \brief Instructions from OrigLoop selected for this partition.
  169. InstructionSet Set;
  170. /// \brief Whether this partition contains a dependence cycle.
  171. bool DepCycle;
  172. /// \brief The original loop.
  173. Loop *OrigLoop;
  174. /// \brief The cloned loop. If this partition is mapped to the original loop,
  175. /// this is null.
  176. Loop *ClonedLoop;
  177. /// \brief The blocks of ClonedLoop including the preheader. If this
  178. /// partition is mapped to the original loop, this is empty.
  179. SmallVector<BasicBlock *, 8> ClonedLoopBlocks;
  180. /// \brief These gets populated once the set of instructions have been
  181. /// finalized. If this partition is mapped to the original loop, these are not
  182. /// set.
  183. ValueToValueMapTy VMap;
  184. };
  185. /// \brief Holds the set of Partitions. It populates them, merges them and then
  186. /// clones the loops.
  187. class InstPartitionContainer {
  188. typedef DenseMap<Instruction *, int> InstToPartitionIdT;
  189. public:
  190. InstPartitionContainer(Loop *L, LoopInfo *LI, DominatorTree *DT)
  191. : L(L), LI(LI), DT(DT) {}
  192. /// \brief Returns the number of partitions.
  193. unsigned getSize() const { return PartitionContainer.size(); }
  194. /// \brief Adds \p Inst into the current partition if that is marked to
  195. /// contain cycles. Otherwise start a new partition for it.
  196. void addToCyclicPartition(Instruction *Inst) {
  197. // If the current partition is non-cyclic. Start a new one.
  198. if (PartitionContainer.empty() || !PartitionContainer.back().hasDepCycle())
  199. PartitionContainer.emplace_back(Inst, L, /*DepCycle=*/true);
  200. else
  201. PartitionContainer.back().add(Inst);
  202. }
  203. /// \brief Adds \p Inst into a partition that is not marked to contain
  204. /// dependence cycles.
  205. ///
  206. // Initially we isolate memory instructions into as many partitions as
  207. // possible, then later we may merge them back together.
  208. void addToNewNonCyclicPartition(Instruction *Inst) {
  209. PartitionContainer.emplace_back(Inst, L);
  210. }
  211. /// \brief Merges adjacent non-cyclic partitions.
  212. ///
  213. /// The idea is that we currently only want to isolate the non-vectorizable
  214. /// partition. We could later allow more distribution among these partition
  215. /// too.
  216. void mergeAdjacentNonCyclic() {
  217. mergeAdjacentPartitionsIf(
  218. [](const InstPartition *P) { return !P->hasDepCycle(); });
  219. }
  220. /// \brief If a partition contains only conditional stores, we won't vectorize
  221. /// it. Try to merge it with a previous cyclic partition.
  222. void mergeNonIfConvertible() {
  223. mergeAdjacentPartitionsIf([&](const InstPartition *Partition) {
  224. if (Partition->hasDepCycle())
  225. return true;
  226. // Now, check if all stores are conditional in this partition.
  227. bool seenStore = false;
  228. for (auto *Inst : *Partition)
  229. if (isa<StoreInst>(Inst)) {
  230. seenStore = true;
  231. if (!LoopAccessInfo::blockNeedsPredication(Inst->getParent(), L, DT))
  232. return false;
  233. }
  234. return seenStore;
  235. });
  236. }
  237. /// \brief Merges the partitions according to various heuristics.
  238. void mergeBeforePopulating() {
  239. mergeAdjacentNonCyclic();
  240. if (!DistributeNonIfConvertible)
  241. mergeNonIfConvertible();
  242. }
  243. /// \brief Merges partitions in order to ensure that no loads are duplicated.
  244. ///
  245. /// We can't duplicate loads because that could potentially reorder them.
  246. /// LoopAccessAnalysis provides dependency information with the context that
  247. /// the order of memory operation is preserved.
  248. ///
  249. /// Return if any partitions were merged.
  250. bool mergeToAvoidDuplicatedLoads() {
  251. typedef DenseMap<Instruction *, InstPartition *> LoadToPartitionT;
  252. typedef EquivalenceClasses<InstPartition *> ToBeMergedT;
  253. LoadToPartitionT LoadToPartition;
  254. ToBeMergedT ToBeMerged;
  255. // Step through the partitions and create equivalence between partitions
  256. // that contain the same load. Also put partitions in between them in the
  257. // same equivalence class to avoid reordering of memory operations.
  258. for (PartitionContainerT::iterator I = PartitionContainer.begin(),
  259. E = PartitionContainer.end();
  260. I != E; ++I) {
  261. auto *PartI = &*I;
  262. // If a load occurs in two partitions PartI and PartJ, merge all
  263. // partitions (PartI, PartJ] into PartI.
  264. for (Instruction *Inst : *PartI)
  265. if (isa<LoadInst>(Inst)) {
  266. bool NewElt;
  267. LoadToPartitionT::iterator LoadToPart;
  268. std::tie(LoadToPart, NewElt) =
  269. LoadToPartition.insert(std::make_pair(Inst, PartI));
  270. if (!NewElt) {
  271. DEBUG(dbgs() << "Merging partitions due to this load in multiple "
  272. << "partitions: " << PartI << ", "
  273. << LoadToPart->second << "\n" << *Inst << "\n");
  274. auto PartJ = I;
  275. do {
  276. --PartJ;
  277. ToBeMerged.unionSets(PartI, &*PartJ);
  278. } while (&*PartJ != LoadToPart->second);
  279. }
  280. }
  281. }
  282. if (ToBeMerged.empty())
  283. return false;
  284. // Merge the member of an equivalence class into its class leader. This
  285. // makes the members empty.
  286. for (ToBeMergedT::iterator I = ToBeMerged.begin(), E = ToBeMerged.end();
  287. I != E; ++I) {
  288. if (!I->isLeader())
  289. continue;
  290. auto PartI = I->getData();
  291. for (auto PartJ : make_range(std::next(ToBeMerged.member_begin(I)),
  292. ToBeMerged.member_end())) {
  293. PartJ->moveTo(*PartI);
  294. }
  295. }
  296. // Remove the empty partitions.
  297. PartitionContainer.remove_if(
  298. [](const InstPartition &P) { return P.empty(); });
  299. return true;
  300. }
  301. /// \brief Sets up the mapping between instructions to partitions. If the
  302. /// instruction is duplicated across multiple partitions, set the entry to -1.
  303. void setupPartitionIdOnInstructions() {
  304. int PartitionID = 0;
  305. for (const auto &Partition : PartitionContainer) {
  306. for (Instruction *Inst : Partition) {
  307. bool NewElt;
  308. InstToPartitionIdT::iterator Iter;
  309. std::tie(Iter, NewElt) =
  310. InstToPartitionId.insert(std::make_pair(Inst, PartitionID));
  311. if (!NewElt)
  312. Iter->second = -1;
  313. }
  314. ++PartitionID;
  315. }
  316. }
  317. /// \brief Populates the partition with everything that the seeding
  318. /// instructions require.
  319. void populateUsedSet() {
  320. for (auto &P : PartitionContainer)
  321. P.populateUsedSet();
  322. }
  323. /// \brief This performs the main chunk of the work of cloning the loops for
  324. /// the partitions.
  325. void cloneLoops(Pass *P) {
  326. BasicBlock *OrigPH = L->getLoopPreheader();
  327. // At this point the predecessor of the preheader is either the memcheck
  328. // block or the top part of the original preheader.
  329. BasicBlock *Pred = OrigPH->getSinglePredecessor();
  330. assert(Pred && "Preheader does not have a single predecessor");
  331. BasicBlock *ExitBlock = L->getExitBlock();
  332. assert(ExitBlock && "No single exit block");
  333. Loop *NewLoop;
  334. assert(!PartitionContainer.empty() && "at least two partitions expected");
  335. // We're cloning the preheader along with the loop so we already made sure
  336. // it was empty.
  337. assert(&*OrigPH->begin() == OrigPH->getTerminator() &&
  338. "preheader not empty");
  339. // Create a loop for each partition except the last. Clone the original
  340. // loop before PH along with adding a preheader for the cloned loop. Then
  341. // update PH to point to the newly added preheader.
  342. BasicBlock *TopPH = OrigPH;
  343. unsigned Index = getSize() - 1;
  344. for (auto I = std::next(PartitionContainer.rbegin()),
  345. E = PartitionContainer.rend();
  346. I != E; ++I, --Index, TopPH = NewLoop->getLoopPreheader()) {
  347. auto *Part = &*I;
  348. NewLoop = Part->cloneLoopWithPreheader(TopPH, Pred, Index, LI, DT);
  349. Part->getVMap()[ExitBlock] = TopPH;
  350. Part->remapInstructions();
  351. }
  352. Pred->getTerminator()->replaceUsesOfWith(OrigPH, TopPH);
  353. // Now go in forward order and update the immediate dominator for the
  354. // preheaders with the exiting block of the previous loop. Dominance
  355. // within the loop is updated in cloneLoopWithPreheader.
  356. for (auto Curr = PartitionContainer.cbegin(),
  357. Next = std::next(PartitionContainer.cbegin()),
  358. E = PartitionContainer.cend();
  359. Next != E; ++Curr, ++Next)
  360. DT->changeImmediateDominator(
  361. Next->getDistributedLoop()->getLoopPreheader(),
  362. Curr->getDistributedLoop()->getExitingBlock());
  363. }
  364. /// \brief Removes the dead instructions from the cloned loops.
  365. void removeUnusedInsts() {
  366. for (auto &Partition : PartitionContainer)
  367. Partition.removeUnusedInsts();
  368. }
  369. /// \brief For each memory pointer, it computes the partitionId the pointer is
  370. /// used in.
  371. ///
  372. /// This returns an array of int where the I-th entry corresponds to I-th
  373. /// entry in LAI.getRuntimePointerCheck(). If the pointer is used in multiple
  374. /// partitions its entry is set to -1.
  375. SmallVector<int, 8>
  376. computePartitionSetForPointers(const LoopAccessInfo &LAI) {
  377. const RuntimePointerChecking *RtPtrCheck = LAI.getRuntimePointerChecking();
  378. unsigned N = RtPtrCheck->Pointers.size();
  379. SmallVector<int, 8> PtrToPartitions(N);
  380. for (unsigned I = 0; I < N; ++I) {
  381. Value *Ptr = RtPtrCheck->Pointers[I].PointerValue;
  382. auto Instructions =
  383. LAI.getInstructionsForAccess(Ptr, RtPtrCheck->Pointers[I].IsWritePtr);
  384. int &Partition = PtrToPartitions[I];
  385. // First set it to uninitialized.
  386. Partition = -2;
  387. for (Instruction *Inst : Instructions) {
  388. // Note that this could be -1 if Inst is duplicated across multiple
  389. // partitions.
  390. int ThisPartition = this->InstToPartitionId[Inst];
  391. if (Partition == -2)
  392. Partition = ThisPartition;
  393. // -1 means belonging to multiple partitions.
  394. else if (Partition == -1)
  395. break;
  396. else if (Partition != (int)ThisPartition)
  397. Partition = -1;
  398. }
  399. assert(Partition != -2 && "Pointer not belonging to any partition");
  400. }
  401. return PtrToPartitions;
  402. }
  403. void print(raw_ostream &OS) const {
  404. unsigned Index = 0;
  405. for (const auto &P : PartitionContainer) {
  406. OS << "Partition " << Index++ << " (" << &P << "):\n";
  407. P.print();
  408. }
  409. }
  410. void dump() const { print(dbgs()); }
  411. #ifndef NDEBUG
  412. friend raw_ostream &operator<<(raw_ostream &OS,
  413. const InstPartitionContainer &Partitions) {
  414. Partitions.print(OS);
  415. return OS;
  416. }
  417. #endif
  418. void printBlocks() const {
  419. unsigned Index = 0;
  420. for (const auto &P : PartitionContainer) {
  421. dbgs() << "\nPartition " << Index++ << " (" << &P << "):\n";
  422. P.printBlocks();
  423. }
  424. }
  425. private:
  426. typedef std::list<InstPartition> PartitionContainerT;
  427. /// \brief List of partitions.
  428. PartitionContainerT PartitionContainer;
  429. /// \brief Mapping from Instruction to partition Id. If the instruction
  430. /// belongs to multiple partitions the entry contains -1.
  431. InstToPartitionIdT InstToPartitionId;
  432. Loop *L;
  433. LoopInfo *LI;
  434. DominatorTree *DT;
  435. /// \brief The control structure to merge adjacent partitions if both satisfy
  436. /// the \p Predicate.
  437. template <class UnaryPredicate>
  438. void mergeAdjacentPartitionsIf(UnaryPredicate Predicate) {
  439. InstPartition *PrevMatch = nullptr;
  440. for (auto I = PartitionContainer.begin(); I != PartitionContainer.end();) {
  441. auto DoesMatch = Predicate(&*I);
  442. if (PrevMatch == nullptr && DoesMatch) {
  443. PrevMatch = &*I;
  444. ++I;
  445. } else if (PrevMatch != nullptr && DoesMatch) {
  446. I->moveTo(*PrevMatch);
  447. I = PartitionContainer.erase(I);
  448. } else {
  449. PrevMatch = nullptr;
  450. ++I;
  451. }
  452. }
  453. }
  454. };
  455. /// \brief For each memory instruction, this class maintains difference of the
  456. /// number of unsafe dependences that start out from this instruction minus
  457. /// those that end here.
  458. ///
  459. /// By traversing the memory instructions in program order and accumulating this
  460. /// number, we know whether any unsafe dependence crosses over a program point.
  461. class MemoryInstructionDependences {
  462. typedef MemoryDepChecker::Dependence Dependence;
  463. public:
  464. struct Entry {
  465. Instruction *Inst;
  466. unsigned NumUnsafeDependencesStartOrEnd;
  467. Entry(Instruction *Inst) : Inst(Inst), NumUnsafeDependencesStartOrEnd(0) {}
  468. };
  469. typedef SmallVector<Entry, 8> AccessesType;
  470. AccessesType::const_iterator begin() const { return Accesses.begin(); }
  471. AccessesType::const_iterator end() const { return Accesses.end(); }
  472. MemoryInstructionDependences(
  473. const SmallVectorImpl<Instruction *> &Instructions,
  474. const SmallVectorImpl<Dependence> &InterestingDependences) {
  475. Accesses.append(Instructions.begin(), Instructions.end());
  476. DEBUG(dbgs() << "Backward dependences:\n");
  477. for (auto &Dep : InterestingDependences)
  478. if (Dep.isPossiblyBackward()) {
  479. // Note that the designations source and destination follow the program
  480. // order, i.e. source is always first. (The direction is given by the
  481. // DepType.)
  482. ++Accesses[Dep.Source].NumUnsafeDependencesStartOrEnd;
  483. --Accesses[Dep.Destination].NumUnsafeDependencesStartOrEnd;
  484. DEBUG(Dep.print(dbgs(), 2, Instructions));
  485. }
  486. }
  487. private:
  488. AccessesType Accesses;
  489. };
  490. /// \brief Returns the instructions that use values defined in the loop.
  491. static SmallVector<Instruction *, 8> findDefsUsedOutsideOfLoop(Loop *L) {
  492. SmallVector<Instruction *, 8> UsedOutside;
  493. for (auto *Block : L->getBlocks())
  494. // FIXME: I believe that this could use copy_if if the Inst reference could
  495. // be adapted into a pointer.
  496. for (auto &Inst : *Block) {
  497. auto Users = Inst.users();
  498. if (std::any_of(Users.begin(), Users.end(), [&](User *U) {
  499. auto *Use = cast<Instruction>(U);
  500. return !L->contains(Use->getParent());
  501. }))
  502. UsedOutside.push_back(&Inst);
  503. }
  504. return UsedOutside;
  505. }
  506. /// \brief The pass class.
  507. class LoopDistribute : public FunctionPass {
  508. public:
  509. LoopDistribute() : FunctionPass(ID) {
  510. initializeLoopDistributePass(*PassRegistry::getPassRegistry());
  511. }
  512. bool runOnFunction(Function &F) override {
  513. LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  514. LAA = &getAnalysis<LoopAccessAnalysis>();
  515. DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  516. // Build up a worklist of inner-loops to vectorize. This is necessary as the
  517. // act of distributing a loop creates new loops and can invalidate iterators
  518. // across the loops.
  519. SmallVector<Loop *, 8> Worklist;
  520. for (Loop *TopLevelLoop : *LI)
  521. for (Loop *L : depth_first(TopLevelLoop))
  522. // We only handle inner-most loops.
  523. if (L->empty())
  524. Worklist.push_back(L);
  525. // Now walk the identified inner loops.
  526. bool Changed = false;
  527. for (Loop *L : Worklist)
  528. Changed |= processLoop(L);
  529. // Process each loop nest in the function.
  530. return Changed;
  531. }
  532. void getAnalysisUsage(AnalysisUsage &AU) const override {
  533. AU.addRequired<LoopInfoWrapperPass>();
  534. AU.addPreserved<LoopInfoWrapperPass>();
  535. AU.addRequired<LoopAccessAnalysis>();
  536. AU.addRequired<DominatorTreeWrapperPass>();
  537. AU.addPreserved<DominatorTreeWrapperPass>();
  538. }
  539. static char ID;
  540. private:
  541. /// \brief Try to distribute an inner-most loop.
  542. bool processLoop(Loop *L) {
  543. assert(L->empty() && "Only process inner loops.");
  544. DEBUG(dbgs() << "\nLDist: In \"" << L->getHeader()->getParent()->getName()
  545. << "\" checking " << *L << "\n");
  546. BasicBlock *PH = L->getLoopPreheader();
  547. if (!PH) {
  548. DEBUG(dbgs() << "Skipping; no preheader");
  549. return false;
  550. }
  551. if (!L->getExitBlock()) {
  552. DEBUG(dbgs() << "Skipping; multiple exit blocks");
  553. return false;
  554. }
  555. // LAA will check that we only have a single exiting block.
  556. const LoopAccessInfo &LAI = LAA->getInfo(L, ValueToValueMap());
  557. // Currently, we only distribute to isolate the part of the loop with
  558. // dependence cycles to enable partial vectorization.
  559. if (LAI.canVectorizeMemory()) {
  560. DEBUG(dbgs() << "Skipping; memory operations are safe for vectorization");
  561. return false;
  562. }
  563. auto *InterestingDependences =
  564. LAI.getDepChecker().getInterestingDependences();
  565. if (!InterestingDependences || InterestingDependences->empty()) {
  566. DEBUG(dbgs() << "Skipping; No unsafe dependences to isolate");
  567. return false;
  568. }
  569. InstPartitionContainer Partitions(L, LI, DT);
  570. // First, go through each memory operation and assign them to consecutive
  571. // partitions (the order of partitions follows program order). Put those
  572. // with unsafe dependences into "cyclic" partition otherwise put each store
  573. // in its own "non-cyclic" partition (we'll merge these later).
  574. //
  575. // Note that a memory operation (e.g. Load2 below) at a program point that
  576. // has an unsafe dependence (Store3->Load1) spanning over it must be
  577. // included in the same cyclic partition as the dependent operations. This
  578. // is to preserve the original program order after distribution. E.g.:
  579. //
  580. // NumUnsafeDependencesStartOrEnd NumUnsafeDependencesActive
  581. // Load1 -. 1 0->1
  582. // Load2 | /Unsafe/ 0 1
  583. // Store3 -' -1 1->0
  584. // Load4 0 0
  585. //
  586. // NumUnsafeDependencesActive > 0 indicates this situation and in this case
  587. // we just keep assigning to the same cyclic partition until
  588. // NumUnsafeDependencesActive reaches 0.
  589. const MemoryDepChecker &DepChecker = LAI.getDepChecker();
  590. MemoryInstructionDependences MID(DepChecker.getMemoryInstructions(),
  591. *InterestingDependences);
  592. int NumUnsafeDependencesActive = 0;
  593. for (auto &InstDep : MID) {
  594. Instruction *I = InstDep.Inst;
  595. // We update NumUnsafeDependencesActive post-instruction, catch the
  596. // start of a dependence directly via NumUnsafeDependencesStartOrEnd.
  597. if (NumUnsafeDependencesActive ||
  598. InstDep.NumUnsafeDependencesStartOrEnd > 0)
  599. Partitions.addToCyclicPartition(I);
  600. else
  601. Partitions.addToNewNonCyclicPartition(I);
  602. NumUnsafeDependencesActive += InstDep.NumUnsafeDependencesStartOrEnd;
  603. assert(NumUnsafeDependencesActive >= 0 &&
  604. "Negative number of dependences active");
  605. }
  606. // Add partitions for values used outside. These partitions can be out of
  607. // order from the original program order. This is OK because if the
  608. // partition uses a load we will merge this partition with the original
  609. // partition of the load that we set up in the previous loop (see
  610. // mergeToAvoidDuplicatedLoads).
  611. auto DefsUsedOutside = findDefsUsedOutsideOfLoop(L);
  612. for (auto *Inst : DefsUsedOutside)
  613. Partitions.addToNewNonCyclicPartition(Inst);
  614. DEBUG(dbgs() << "Seeded partitions:\n" << Partitions);
  615. if (Partitions.getSize() < 2)
  616. return false;
  617. // Run the merge heuristics: Merge non-cyclic adjacent partitions since we
  618. // should be able to vectorize these together.
  619. Partitions.mergeBeforePopulating();
  620. DEBUG(dbgs() << "\nMerged partitions:\n" << Partitions);
  621. if (Partitions.getSize() < 2)
  622. return false;
  623. // Now, populate the partitions with non-memory operations.
  624. Partitions.populateUsedSet();
  625. DEBUG(dbgs() << "\nPopulated partitions:\n" << Partitions);
  626. // In order to preserve original lexical order for loads, keep them in the
  627. // partition that we set up in the MemoryInstructionDependences loop.
  628. if (Partitions.mergeToAvoidDuplicatedLoads()) {
  629. DEBUG(dbgs() << "\nPartitions merged to ensure unique loads:\n"
  630. << Partitions);
  631. if (Partitions.getSize() < 2)
  632. return false;
  633. }
  634. DEBUG(dbgs() << "\nDistributing loop: " << *L << "\n");
  635. // We're done forming the partitions set up the reverse mapping from
  636. // instructions to partitions.
  637. Partitions.setupPartitionIdOnInstructions();
  638. // To keep things simple have an empty preheader before we version or clone
  639. // the loop. (Also split if this has no predecessor, i.e. entry, because we
  640. // rely on PH having a predecessor.)
  641. if (!PH->getSinglePredecessor() || &*PH->begin() != PH->getTerminator())
  642. SplitBlock(PH, PH->getTerminator(), DT, LI);
  643. // If we need run-time checks to disambiguate pointers are run-time, version
  644. // the loop now.
  645. auto PtrToPartition = Partitions.computePartitionSetForPointers(LAI);
  646. LoopVersioning LVer(LAI, L, LI, DT, &PtrToPartition);
  647. if (LVer.needsRuntimeChecks()) {
  648. DEBUG(dbgs() << "\nPointers:\n");
  649. DEBUG(LAI.getRuntimePointerChecking()->print(dbgs(), 0, &PtrToPartition));
  650. LVer.versionLoop(this);
  651. LVer.addPHINodes(DefsUsedOutside);
  652. }
  653. // Create identical copies of the original loop for each partition and hook
  654. // them up sequentially.
  655. Partitions.cloneLoops(this);
  656. // Now, we remove the instruction from each loop that don't belong to that
  657. // partition.
  658. Partitions.removeUnusedInsts();
  659. DEBUG(dbgs() << "\nAfter removing unused Instrs:\n");
  660. DEBUG(Partitions.printBlocks());
  661. if (LDistVerify) {
  662. LI->verify();
  663. DT->verifyDomTree();
  664. }
  665. ++NumLoopsDistributed;
  666. return true;
  667. }
  668. // Analyses used.
  669. LoopInfo *LI;
  670. LoopAccessAnalysis *LAA;
  671. DominatorTree *DT;
  672. };
  673. } // anonymous namespace
  674. char LoopDistribute::ID;
  675. static const char ldist_name[] = "Loop Distribition";
  676. INITIALIZE_PASS_BEGIN(LoopDistribute, LDIST_NAME, ldist_name, false, false)
  677. INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
  678. INITIALIZE_PASS_DEPENDENCY(LoopAccessAnalysis)
  679. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  680. INITIALIZE_PASS_END(LoopDistribute, LDIST_NAME, ldist_name, false, false)
  681. namespace llvm {
  682. FunctionPass *createLoopDistributePass() { return new LoopDistribute(); }
  683. }