1 //===- LoopDistribute.cpp - Loop Distribution Pass ------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
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
20 // Similarly to the Vectorizer, the pass also supports loop versioning to
21 // run-time disambiguate potentially overlapping arrays.
23 //===----------------------------------------------------------------------===//
25 #include "llvm/ADT/DepthFirstIterator.h"
26 #include "llvm/ADT/EquivalenceClasses.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/Analysis/LoopAccessAnalysis.h"
30 #include "llvm/Analysis/LoopInfo.h"
31 #include "llvm/IR/Dominators.h"
32 #include "llvm/Pass.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
36 #include "llvm/Transforms/Utils/Cloning.h"
37 #include "llvm/Transforms/Utils/LoopVersioning.h"
40 #define LDIST_NAME "loop-distribute"
41 #define DEBUG_TYPE LDIST_NAME
46 LDistVerify("loop-distribute-verify", cl::Hidden,
47 cl::desc("Turn on DominatorTree and LoopInfo verification "
48 "after Loop Distribution"),
51 static cl::opt<bool> DistributeNonIfConvertible(
52 "loop-distribute-non-if-convertible", cl::Hidden,
53 cl::desc("Whether to distribute into a loop that may not be "
54 "if-convertible by the loop vectorizer"),
57 STATISTIC(NumLoopsDistributed, "Number of loops distributed");
60 /// \brief Maintains the set of instructions of the loop for a partition before
61 /// cloning. After cloning, it hosts the new loop.
63 typedef SmallPtrSet<Instruction *, 8> InstructionSet;
66 InstPartition(Instruction *I, Loop *L, bool DepCycle = false)
67 : DepCycle(DepCycle), OrigLoop(L), ClonedLoop(nullptr) {
71 /// \brief Returns whether this partition contains a dependence cycle.
72 bool hasDepCycle() const { return DepCycle; }
74 /// \brief Adds an instruction to this partition.
75 void add(Instruction *I) { Set.insert(I); }
77 /// \brief Collection accessors.
78 InstructionSet::iterator begin() { return Set.begin(); }
79 InstructionSet::iterator end() { return Set.end(); }
80 InstructionSet::const_iterator begin() const { return Set.begin(); }
81 InstructionSet::const_iterator end() const { return Set.end(); }
82 bool empty() const { return Set.empty(); }
84 /// \brief Moves this partition into \p Other. This partition becomes empty
86 void moveTo(InstPartition &Other) {
87 Other.Set.insert(Set.begin(), Set.end());
89 Other.DepCycle |= DepCycle;
92 /// \brief Populates the partition with a transitive closure of all the
93 /// instructions that the seeded instructions dependent on.
94 void populateUsedSet() {
95 // FIXME: We currently don't use control-dependence but simply include all
96 // blocks (possibly empty at the end) and let simplifycfg mostly clean this
98 for (auto *B : OrigLoop->getBlocks())
99 Set.insert(B->getTerminator());
101 // Follow the use-def chains to form a transitive closure of all the
102 // instructions that the originally seeded instructions depend on.
103 SmallVector<Instruction *, 8> Worklist(Set.begin(), Set.end());
104 while (!Worklist.empty()) {
105 Instruction *I = Worklist.pop_back_val();
106 // Insert instructions from the loop that we depend on.
107 for (Value *V : I->operand_values()) {
108 auto *I = dyn_cast<Instruction>(V);
109 if (I && OrigLoop->contains(I->getParent()) && Set.insert(I).second)
110 Worklist.push_back(I);
115 /// \brief Clones the original loop.
117 /// Updates LoopInfo and DominatorTree using the information that block \p
118 /// LoopDomBB dominates the loop.
119 Loop *cloneLoopWithPreheader(BasicBlock *InsertBefore, BasicBlock *LoopDomBB,
120 unsigned Index, LoopInfo *LI,
122 ClonedLoop = ::cloneLoopWithPreheader(InsertBefore, LoopDomBB, OrigLoop,
123 VMap, Twine(".ldist") + Twine(Index),
124 LI, DT, ClonedLoopBlocks);
128 /// \brief The cloned loop. If this partition is mapped to the original loop,
130 const Loop *getClonedLoop() const { return ClonedLoop; }
132 /// \brief Returns the loop where this partition ends up after distribution.
133 /// If this partition is mapped to the original loop then use the block from
135 const Loop *getDistributedLoop() const {
136 return ClonedLoop ? ClonedLoop : OrigLoop;
139 /// \brief The VMap that is populated by cloning and then used in
140 /// remapinstruction to remap the cloned instructions.
141 ValueToValueMapTy &getVMap() { return VMap; }
143 /// \brief Remaps the cloned instructions using VMap.
144 void remapInstructions() {
145 remapInstructionsInBlocks(ClonedLoopBlocks, VMap);
148 /// \brief Based on the set of instructions selected for this partition,
149 /// removes the unnecessary ones.
150 void removeUnusedInsts() {
151 SmallVector<Instruction *, 8> Unused;
153 for (auto *Block : OrigLoop->getBlocks())
154 for (auto &Inst : *Block)
155 if (!Set.count(&Inst)) {
156 Instruction *NewInst = &Inst;
158 NewInst = cast<Instruction>(VMap[NewInst]);
160 assert(!isa<BranchInst>(NewInst) &&
161 "Branches are marked used early on");
162 Unused.push_back(NewInst);
165 // Delete the instructions backwards, as it has a reduced likelihood of
166 // having to update as many def-use and use-def chains.
167 for (auto I = Unused.rbegin(), E = Unused.rend(); I != E; ++I) {
170 if (!Inst->use_empty())
171 Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
172 Inst->eraseFromParent();
178 dbgs() << " (cycle)\n";
180 // Prefix with the block name.
181 dbgs() << " " << I->getParent()->getName() << ":" << *I << "\n";
184 void printBlocks() const {
185 for (auto *BB : getDistributedLoop()->getBlocks())
190 /// \brief Instructions from OrigLoop selected for this partition.
193 /// \brief Whether this partition contains a dependence cycle.
196 /// \brief The original loop.
199 /// \brief The cloned loop. If this partition is mapped to the original loop,
203 /// \brief The blocks of ClonedLoop including the preheader. If this
204 /// partition is mapped to the original loop, this is empty.
205 SmallVector<BasicBlock *, 8> ClonedLoopBlocks;
207 /// \brief These gets populated once the set of instructions have been
208 /// finalized. If this partition is mapped to the original loop, these are not
210 ValueToValueMapTy VMap;
213 /// \brief Holds the set of Partitions. It populates them, merges them and then
214 /// clones the loops.
215 class InstPartitionContainer {
216 typedef DenseMap<Instruction *, int> InstToPartitionIdT;
219 InstPartitionContainer(Loop *L, LoopInfo *LI, DominatorTree *DT)
220 : L(L), LI(LI), DT(DT) {}
222 /// \brief Returns the number of partitions.
223 unsigned getSize() const { return PartitionContainer.size(); }
225 /// \brief Adds \p Inst into the current partition if that is marked to
226 /// contain cycles. Otherwise start a new partition for it.
227 void addToCyclicPartition(Instruction *Inst) {
228 // If the current partition is non-cyclic. Start a new one.
229 if (PartitionContainer.empty() || !PartitionContainer.back().hasDepCycle())
230 PartitionContainer.emplace_back(Inst, L, /*DepCycle=*/true);
232 PartitionContainer.back().add(Inst);
235 /// \brief Adds \p Inst into a partition that is not marked to contain
236 /// dependence cycles.
238 // Initially we isolate memory instructions into as many partitions as
239 // possible, then later we may merge them back together.
240 void addToNewNonCyclicPartition(Instruction *Inst) {
241 PartitionContainer.emplace_back(Inst, L);
244 /// \brief Merges adjacent non-cyclic partitions.
246 /// The idea is that we currently only want to isolate the non-vectorizable
247 /// partition. We could later allow more distribution among these partition
249 void mergeAdjacentNonCyclic() {
250 mergeAdjacentPartitionsIf(
251 [](const InstPartition *P) { return !P->hasDepCycle(); });
254 /// \brief If a partition contains only conditional stores, we won't vectorize
255 /// it. Try to merge it with a previous cyclic partition.
256 void mergeNonIfConvertible() {
257 mergeAdjacentPartitionsIf([&](const InstPartition *Partition) {
258 if (Partition->hasDepCycle())
261 // Now, check if all stores are conditional in this partition.
262 bool seenStore = false;
264 for (auto *Inst : *Partition)
265 if (isa<StoreInst>(Inst)) {
267 if (!LoopAccessInfo::blockNeedsPredication(Inst->getParent(), L, DT))
274 /// \brief Merges the partitions according to various heuristics.
275 void mergeBeforePopulating() {
276 mergeAdjacentNonCyclic();
277 if (!DistributeNonIfConvertible)
278 mergeNonIfConvertible();
281 /// \brief Merges partitions in order to ensure that no loads are duplicated.
283 /// We can't duplicate loads because that could potentially reorder them.
284 /// LoopAccessAnalysis provides dependency information with the context that
285 /// the order of memory operation is preserved.
287 /// Return if any partitions were merged.
288 bool mergeToAvoidDuplicatedLoads() {
289 typedef DenseMap<Instruction *, InstPartition *> LoadToPartitionT;
290 typedef EquivalenceClasses<InstPartition *> ToBeMergedT;
292 LoadToPartitionT LoadToPartition;
293 ToBeMergedT ToBeMerged;
295 // Step through the partitions and create equivalence between partitions
296 // that contain the same load. Also put partitions in between them in the
297 // same equivalence class to avoid reordering of memory operations.
298 for (PartitionContainerT::iterator I = PartitionContainer.begin(),
299 E = PartitionContainer.end();
303 // If a load occurs in two partitions PartI and PartJ, merge all
304 // partitions (PartI, PartJ] into PartI.
305 for (Instruction *Inst : *PartI)
306 if (isa<LoadInst>(Inst)) {
308 LoadToPartitionT::iterator LoadToPart;
310 std::tie(LoadToPart, NewElt) =
311 LoadToPartition.insert(std::make_pair(Inst, PartI));
313 DEBUG(dbgs() << "Merging partitions due to this load in multiple "
314 << "partitions: " << PartI << ", "
315 << LoadToPart->second << "\n" << *Inst << "\n");
320 ToBeMerged.unionSets(PartI, &*PartJ);
321 } while (&*PartJ != LoadToPart->second);
325 if (ToBeMerged.empty())
328 // Merge the member of an equivalence class into its class leader. This
329 // makes the members empty.
330 for (ToBeMergedT::iterator I = ToBeMerged.begin(), E = ToBeMerged.end();
335 auto PartI = I->getData();
336 for (auto PartJ : make_range(std::next(ToBeMerged.member_begin(I)),
337 ToBeMerged.member_end())) {
338 PartJ->moveTo(*PartI);
342 // Remove the empty partitions.
343 PartitionContainer.remove_if(
344 [](const InstPartition &P) { return P.empty(); });
349 /// \brief Sets up the mapping between instructions to partitions. If the
350 /// instruction is duplicated across multiple partitions, set the entry to -1.
351 void setupPartitionIdOnInstructions() {
353 for (const auto &Partition : PartitionContainer) {
354 for (Instruction *Inst : Partition) {
356 InstToPartitionIdT::iterator Iter;
358 std::tie(Iter, NewElt) =
359 InstToPartitionId.insert(std::make_pair(Inst, PartitionID));
367 /// \brief Populates the partition with everything that the seeding
368 /// instructions require.
369 void populateUsedSet() {
370 for (auto &P : PartitionContainer)
374 /// \brief This performs the main chunk of the work of cloning the loops for
376 void cloneLoops(Pass *P) {
377 BasicBlock *OrigPH = L->getLoopPreheader();
378 // At this point the predecessor of the preheader is either the memcheck
379 // block or the top part of the original preheader.
380 BasicBlock *Pred = OrigPH->getSinglePredecessor();
381 assert(Pred && "Preheader does not have a single predecessor");
382 BasicBlock *ExitBlock = L->getExitBlock();
383 assert(ExitBlock && "No single exit block");
386 assert(!PartitionContainer.empty() && "at least two partitions expected");
387 // We're cloning the preheader along with the loop so we already made sure
389 assert(&*OrigPH->begin() == OrigPH->getTerminator() &&
390 "preheader not empty");
392 // Create a loop for each partition except the last. Clone the original
393 // loop before PH along with adding a preheader for the cloned loop. Then
394 // update PH to point to the newly added preheader.
395 BasicBlock *TopPH = OrigPH;
396 unsigned Index = getSize() - 1;
397 for (auto I = std::next(PartitionContainer.rbegin()),
398 E = PartitionContainer.rend();
399 I != E; ++I, --Index, TopPH = NewLoop->getLoopPreheader()) {
402 NewLoop = Part->cloneLoopWithPreheader(TopPH, Pred, Index, LI, DT);
404 Part->getVMap()[ExitBlock] = TopPH;
405 Part->remapInstructions();
407 Pred->getTerminator()->replaceUsesOfWith(OrigPH, TopPH);
409 // Now go in forward order and update the immediate dominator for the
410 // preheaders with the exiting block of the previous loop. Dominance
411 // within the loop is updated in cloneLoopWithPreheader.
412 for (auto Curr = PartitionContainer.cbegin(),
413 Next = std::next(PartitionContainer.cbegin()),
414 E = PartitionContainer.cend();
415 Next != E; ++Curr, ++Next)
416 DT->changeImmediateDominator(
417 Next->getDistributedLoop()->getLoopPreheader(),
418 Curr->getDistributedLoop()->getExitingBlock());
421 /// \brief Removes the dead instructions from the cloned loops.
422 void removeUnusedInsts() {
423 for (auto &Partition : PartitionContainer)
424 Partition.removeUnusedInsts();
427 /// \brief For each memory pointer, it computes the partitionId the pointer is
430 /// This returns an array of int where the I-th entry corresponds to I-th
431 /// entry in LAI.getRuntimePointerCheck(). If the pointer is used in multiple
432 /// partitions its entry is set to -1.
434 computePartitionSetForPointers(const LoopAccessInfo &LAI) {
435 const RuntimePointerChecking *RtPtrCheck = LAI.getRuntimePointerChecking();
437 unsigned N = RtPtrCheck->Pointers.size();
438 SmallVector<int, 8> PtrToPartitions(N);
439 for (unsigned I = 0; I < N; ++I) {
440 Value *Ptr = RtPtrCheck->Pointers[I];
442 LAI.getInstructionsForAccess(Ptr, RtPtrCheck->IsWritePtr[I]);
444 int &Partition = PtrToPartitions[I];
445 // First set it to uninitialized.
447 for (Instruction *Inst : Instructions) {
448 // Note that this could be -1 if Inst is duplicated across multiple
450 int ThisPartition = this->InstToPartitionId[Inst];
452 Partition = ThisPartition;
453 // -1 means belonging to multiple partitions.
454 else if (Partition == -1)
456 else if (Partition != (int)ThisPartition)
459 assert(Partition != -2 && "Pointer not belonging to any partition");
462 return PtrToPartitions;
465 void print(raw_ostream &OS) const {
467 for (const auto &P : PartitionContainer) {
468 OS << "Partition " << Index++ << " (" << &P << "):\n";
473 void dump() const { print(dbgs()); }
476 friend raw_ostream &operator<<(raw_ostream &OS,
477 const InstPartitionContainer &Partitions) {
478 Partitions.print(OS);
483 void printBlocks() const {
485 for (const auto &P : PartitionContainer) {
486 dbgs() << "\nPartition " << Index++ << " (" << &P << "):\n";
492 typedef std::list<InstPartition> PartitionContainerT;
494 /// \brief List of partitions.
495 PartitionContainerT PartitionContainer;
497 /// \brief Mapping from Instruction to partition Id. If the instruction
498 /// belongs to multiple partitions the entry contains -1.
499 InstToPartitionIdT InstToPartitionId;
505 /// \brief The control structure to merge adjacent partitions if both satisfy
506 /// the \p Predicate.
507 template <class UnaryPredicate>
508 void mergeAdjacentPartitionsIf(UnaryPredicate Predicate) {
509 InstPartition *PrevMatch = nullptr;
510 for (auto I = PartitionContainer.begin(); I != PartitionContainer.end();) {
511 auto DoesMatch = Predicate(&*I);
512 if (PrevMatch == nullptr && DoesMatch) {
515 } else if (PrevMatch != nullptr && DoesMatch) {
516 I->moveTo(*PrevMatch);
517 I = PartitionContainer.erase(I);
526 /// \brief For each memory instruction, this class maintains difference of the
527 /// number of unsafe dependences that start out from this instruction minus
528 /// those that end here.
530 /// By traversing the memory instructions in program order and accumulating this
531 /// number, we know whether any unsafe dependence crosses over a program point.
532 class MemoryInstructionDependences {
533 typedef MemoryDepChecker::Dependence Dependence;
538 unsigned NumUnsafeDependencesStartOrEnd;
540 Entry(Instruction *Inst) : Inst(Inst), NumUnsafeDependencesStartOrEnd(0) {}
543 typedef SmallVector<Entry, 8> AccessesType;
545 AccessesType::const_iterator begin() const { return Accesses.begin(); }
546 AccessesType::const_iterator end() const { return Accesses.end(); }
548 MemoryInstructionDependences(
549 const SmallVectorImpl<Instruction *> &Instructions,
550 const SmallVectorImpl<Dependence> &InterestingDependences) {
551 Accesses.append(Instructions.begin(), Instructions.end());
553 DEBUG(dbgs() << "Backward dependences:\n");
554 for (auto &Dep : InterestingDependences)
555 if (Dep.isPossiblyBackward()) {
556 // Note that the designations source and destination follow the program
557 // order, i.e. source is always first. (The direction is given by the
559 ++Accesses[Dep.Source].NumUnsafeDependencesStartOrEnd;
560 --Accesses[Dep.Destination].NumUnsafeDependencesStartOrEnd;
562 DEBUG(Dep.print(dbgs(), 2, Instructions));
567 AccessesType Accesses;
570 /// \brief Returns the instructions that use values defined in the loop.
571 static SmallVector<Instruction *, 8> findDefsUsedOutsideOfLoop(Loop *L) {
572 SmallVector<Instruction *, 8> UsedOutside;
574 for (auto *Block : L->getBlocks())
575 // FIXME: I believe that this could use copy_if if the Inst reference could
576 // be adapted into a pointer.
577 for (auto &Inst : *Block) {
578 auto Users = Inst.users();
579 if (std::any_of(Users.begin(), Users.end(), [&](User *U) {
580 auto *Use = cast<Instruction>(U);
581 return !L->contains(Use->getParent());
583 UsedOutside.push_back(&Inst);
589 /// \brief The pass class.
590 class LoopDistribute : public FunctionPass {
592 LoopDistribute() : FunctionPass(ID) {
593 initializeLoopDistributePass(*PassRegistry::getPassRegistry());
596 bool runOnFunction(Function &F) override {
597 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
598 LAA = &getAnalysis<LoopAccessAnalysis>();
599 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
601 // Build up a worklist of inner-loops to vectorize. This is necessary as the
602 // act of distributing a loop creates new loops and can invalidate iterators
604 SmallVector<Loop *, 8> Worklist;
606 for (Loop *TopLevelLoop : *LI)
607 for (Loop *L : depth_first(TopLevelLoop))
608 // We only handle inner-most loops.
610 Worklist.push_back(L);
612 // Now walk the identified inner loops.
613 bool Changed = false;
614 for (Loop *L : Worklist)
615 Changed |= processLoop(L);
617 // Process each loop nest in the function.
621 void getAnalysisUsage(AnalysisUsage &AU) const override {
622 AU.addRequired<LoopInfoWrapperPass>();
623 AU.addPreserved<LoopInfoWrapperPass>();
624 AU.addRequired<LoopAccessAnalysis>();
625 AU.addRequired<DominatorTreeWrapperPass>();
626 AU.addPreserved<DominatorTreeWrapperPass>();
632 /// \brief Try to distribute an inner-most loop.
633 bool processLoop(Loop *L) {
634 assert(L->empty() && "Only process inner loops.");
636 DEBUG(dbgs() << "\nLDist: In \"" << L->getHeader()->getParent()->getName()
637 << "\" checking " << *L << "\n");
639 BasicBlock *PH = L->getLoopPreheader();
641 DEBUG(dbgs() << "Skipping; no preheader");
644 if (!L->getExitBlock()) {
645 DEBUG(dbgs() << "Skipping; multiple exit blocks");
648 // LAA will check that we only have a single exiting block.
650 const LoopAccessInfo &LAI = LAA->getInfo(L, ValueToValueMap());
652 // Currently, we only distribute to isolate the part of the loop with
653 // dependence cycles to enable partial vectorization.
654 if (LAI.canVectorizeMemory()) {
655 DEBUG(dbgs() << "Skipping; memory operations are safe for vectorization");
658 auto *InterestingDependences =
659 LAI.getDepChecker().getInterestingDependences();
660 if (!InterestingDependences || InterestingDependences->empty()) {
661 DEBUG(dbgs() << "Skipping; No unsafe dependences to isolate");
665 InstPartitionContainer Partitions(L, LI, DT);
667 // First, go through each memory operation and assign them to consecutive
668 // partitions (the order of partitions follows program order). Put those
669 // with unsafe dependences into "cyclic" partition otherwise put each store
670 // in its own "non-cyclic" partition (we'll merge these later).
672 // Note that a memory operation (e.g. Load2 below) at a program point that
673 // has an unsafe dependence (Store3->Load1) spanning over it must be
674 // included in the same cyclic partition as the dependent operations. This
675 // is to preserve the original program order after distribution. E.g.:
677 // NumUnsafeDependencesStartOrEnd NumUnsafeDependencesActive
679 // Load2 | /Unsafe/ 0 1
683 // NumUnsafeDependencesActive > 0 indicates this situation and in this case
684 // we just keep assigning to the same cyclic partition until
685 // NumUnsafeDependencesActive reaches 0.
686 const MemoryDepChecker &DepChecker = LAI.getDepChecker();
687 MemoryInstructionDependences MID(DepChecker.getMemoryInstructions(),
688 *InterestingDependences);
690 int NumUnsafeDependencesActive = 0;
691 for (auto &InstDep : MID) {
692 Instruction *I = InstDep.Inst;
693 // We update NumUnsafeDependencesActive post-instruction, catch the
694 // start of a dependence directly via NumUnsafeDependencesStartOrEnd.
695 if (NumUnsafeDependencesActive ||
696 InstDep.NumUnsafeDependencesStartOrEnd > 0)
697 Partitions.addToCyclicPartition(I);
699 Partitions.addToNewNonCyclicPartition(I);
700 NumUnsafeDependencesActive += InstDep.NumUnsafeDependencesStartOrEnd;
701 assert(NumUnsafeDependencesActive >= 0 &&
702 "Negative number of dependences active");
705 // Add partitions for values used outside. These partitions can be out of
706 // order from the original program order. This is OK because if the
707 // partition uses a load we will merge this partition with the original
708 // partition of the load that we set up in the previous loop (see
709 // mergeToAvoidDuplicatedLoads).
710 auto DefsUsedOutside = findDefsUsedOutsideOfLoop(L);
711 for (auto *Inst : DefsUsedOutside)
712 Partitions.addToNewNonCyclicPartition(Inst);
714 DEBUG(dbgs() << "Seeded partitions:\n" << Partitions);
715 if (Partitions.getSize() < 2)
718 // Run the merge heuristics: Merge non-cyclic adjacent partitions since we
719 // should be able to vectorize these together.
720 Partitions.mergeBeforePopulating();
721 DEBUG(dbgs() << "\nMerged partitions:\n" << Partitions);
722 if (Partitions.getSize() < 2)
725 // Now, populate the partitions with non-memory operations.
726 Partitions.populateUsedSet();
727 DEBUG(dbgs() << "\nPopulated partitions:\n" << Partitions);
729 // In order to preserve original lexical order for loads, keep them in the
730 // partition that we set up in the MemoryInstructionDependences loop.
731 if (Partitions.mergeToAvoidDuplicatedLoads()) {
732 DEBUG(dbgs() << "\nPartitions merged to ensure unique loads:\n"
734 if (Partitions.getSize() < 2)
738 DEBUG(dbgs() << "\nDistributing loop: " << *L << "\n");
739 // We're done forming the partitions set up the reverse mapping from
740 // instructions to partitions.
741 Partitions.setupPartitionIdOnInstructions();
743 // To keep things simple have an empty preheader before we version or clone
744 // the loop. (Also split if this has no predecessor, i.e. entry, because we
745 // rely on PH having a predecessor.)
746 if (!PH->getSinglePredecessor() || &*PH->begin() != PH->getTerminator())
747 SplitBlock(PH, PH->getTerminator(), DT, LI);
749 // If we need run-time checks to disambiguate pointers are run-time, version
751 auto PtrToPartition = Partitions.computePartitionSetForPointers(LAI);
752 LoopVersioning LVer(LAI, L, LI, DT, &PtrToPartition);
753 if (LVer.needsRuntimeChecks()) {
754 DEBUG(dbgs() << "\nPointers:\n");
755 DEBUG(LAI.getRuntimePointerChecking()->print(dbgs(), 0, &PtrToPartition));
756 LVer.versionLoop(this);
757 LVer.addPHINodes(DefsUsedOutside);
760 // Create identical copies of the original loop for each partition and hook
761 // them up sequentially.
762 Partitions.cloneLoops(this);
764 // Now, we remove the instruction from each loop that don't belong to that
766 Partitions.removeUnusedInsts();
767 DEBUG(dbgs() << "\nAfter removing unused Instrs:\n");
768 DEBUG(Partitions.printBlocks());
775 ++NumLoopsDistributed;
781 LoopAccessAnalysis *LAA;
784 } // anonymous namespace
786 char LoopDistribute::ID;
787 static const char ldist_name[] = "Loop Distribition";
789 INITIALIZE_PASS_BEGIN(LoopDistribute, LDIST_NAME, ldist_name, false, false)
790 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
791 INITIALIZE_PASS_DEPENDENCY(LoopAccessAnalysis)
792 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
793 INITIALIZE_PASS_END(LoopDistribute, LDIST_NAME, ldist_name, false, false)
796 FunctionPass *createLoopDistributePass() { return new LoopDistribute(); }