blob: d0908b594c9316c26431cf431e906726bd644948 [file] [log] [blame]
Dan Gohman3dc2d922008-05-14 00:24:14 +00001//===-- UnrollLoop.cpp - Loop unrolling utilities -------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Dan Gohman3dc2d922008-05-14 00:24:14 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements some loop unrolling utilities. It does not define any
10// actual pass or policy, but provides a single function to perform loop
11// unrolling.
12//
Dan Gohman3dc2d922008-05-14 00:24:14 +000013// The process of unrolling can produce extraneous basic blocks linked with
14// unconditional branches. This will be corrected in the future.
Chris Lattnerdfcfcb42011-01-11 08:00:40 +000015//
Dan Gohman3dc2d922008-05-14 00:24:14 +000016//===----------------------------------------------------------------------===//
17
Mark Heffernan675d4012014-07-10 23:30:06 +000018#include "llvm/ADT/SmallPtrSet.h"
Dan Gohman3dc2d922008-05-14 00:24:14 +000019#include "llvm/ADT/Statistic.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000020#include "llvm/Analysis/AssumptionCache.h"
Duncan Sands433c1672010-11-23 20:26:33 +000021#include "llvm/Analysis/InstructionSimplify.h"
Andrew Trickb72bbe22011-08-10 00:28:10 +000022#include "llvm/Analysis/LoopIterator.h"
Adam Nemet0965da22017-10-09 23:19:02 +000023#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Dan Gohmana7908ae2010-07-26 18:02:06 +000024#include "llvm/Analysis/ScalarEvolution.h"
David Blaikie31b98d22018-06-04 21:23:21 +000025#include "llvm/Transforms/Utils/Local.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/BasicBlock.h"
Hal Finkela995f922014-07-10 14:41:31 +000027#include "llvm/IR/DataLayout.h"
Dehao Chenfb02f712017-02-10 21:09:07 +000028#include "llvm/IR/DebugInfoMetadata.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000029#include "llvm/IR/Dominators.h"
David Majnemer110522b2016-08-16 21:09:46 +000030#include "llvm/IR/IntrinsicInst.h"
Diego Novillo34fc8a72014-04-29 14:27:31 +000031#include "llvm/IR/LLVMContext.h"
Dan Gohman3dc2d922008-05-14 00:24:14 +000032#include "llvm/Support/Debug.h"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +000033#include "llvm/Support/raw_ostream.h"
Chris Lattnerdc3f6f22008-12-03 19:44:02 +000034#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Dan Gohman3dc2d922008-05-14 00:24:14 +000035#include "llvm/Transforms/Utils/Cloning.h"
Davide Italianocd96cfd2016-07-09 03:03:01 +000036#include "llvm/Transforms/Utils/LoopSimplify.h"
Chandler Carruthaa7fa5e2014-01-23 11:23:19 +000037#include "llvm/Transforms/Utils/LoopUtils.h"
Andrew Trick4d0040b2011-08-10 04:29:49 +000038#include "llvm/Transforms/Utils/SimplifyIndVar.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000039#include "llvm/Transforms/Utils/UnrollLoop.h"
Dan Gohman3dc2d922008-05-14 00:24:14 +000040using namespace llvm;
41
Chandler Carruth964daaa2014-04-22 02:55:47 +000042#define DEBUG_TYPE "loop-unroll"
43
Chris Lattnerdc3f6f22008-12-03 19:44:02 +000044// TODO: Should these be here or in LoopUnroll?
Dan Gohman3dc2d922008-05-14 00:24:14 +000045STATISTIC(NumCompletelyUnrolled, "Number of loops completely unrolled");
Chris Lattnerdfcfcb42011-01-11 08:00:40 +000046STATISTIC(NumUnrolled, "Number of loops unrolled (completely or otherwise)");
Dan Gohman3dc2d922008-05-14 00:24:14 +000047
David L Kreitzer188de5a2016-04-05 12:19:35 +000048static cl::opt<bool>
Michael Zolotukhinb2738e42016-08-02 21:24:14 +000049UnrollRuntimeEpilog("unroll-runtime-epilog", cl::init(false), cl::Hidden,
David L Kreitzer188de5a2016-04-05 12:19:35 +000050 cl::desc("Allow runtime unrolled loops to be unrolled "
51 "with epilog instead of prolog."));
52
Eli Friedman0a217452017-01-18 23:26:37 +000053static cl::opt<bool>
54UnrollVerifyDomtree("unroll-verify-domtree", cl::Hidden,
55 cl::desc("Verify domtree after unrolling"),
Eli Friedman3af2f532018-12-21 01:28:49 +000056#ifdef EXPENSIVE_CHECKS
Eli Friedman0a217452017-01-18 23:26:37 +000057 cl::init(true)
Eli Friedman3af2f532018-12-21 01:28:49 +000058#else
59 cl::init(false)
Eli Friedman0a217452017-01-18 23:26:37 +000060#endif
61 );
62
Sanjay Patel5b8d7412016-03-08 16:26:39 +000063/// Convert the instruction operands from referencing the current values into
64/// those specified by VMap.
David Green963401d2018-07-01 12:47:30 +000065void llvm::remapInstruction(Instruction *I, ValueToValueMapTy &VMap) {
Dan Gohman3dc2d922008-05-14 00:24:14 +000066 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
67 Value *Op = I->getOperand(op);
Adrian Prantlbfa77c42017-11-01 23:12:35 +000068
69 // Unwrap arguments of dbg.value intrinsics.
70 bool Wrapped = false;
71 if (auto *V = dyn_cast<MetadataAsValue>(Op))
72 if (auto *Unwrapped = dyn_cast<ValueAsMetadata>(V->getMetadata())) {
73 Op = Unwrapped->getValue();
74 Wrapped = true;
75 }
76
77 auto wrap = [&](Value *V) {
78 auto &C = I->getContext();
79 return Wrapped ? MetadataAsValue::get(C, ValueAsMetadata::get(V)) : V;
80 };
81
Rafael Espindola229e38f2010-10-13 01:36:30 +000082 ValueToValueMapTy::iterator It = VMap.find(Op);
Devang Patelb8f11de2010-06-23 23:55:51 +000083 if (It != VMap.end())
Adrian Prantlbfa77c42017-11-01 23:12:35 +000084 I->setOperand(op, wrap(It->second));
Dan Gohman3dc2d922008-05-14 00:24:14 +000085 }
Jay Foad61ea0e42011-06-23 09:09:15 +000086
87 if (PHINode *PN = dyn_cast<PHINode>(I)) {
88 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
89 ValueToValueMapTy::iterator It = VMap.find(PN->getIncomingBlock(i));
90 if (It != VMap.end())
91 PN->setIncomingBlock(i, cast<BasicBlock>(It->second));
92 }
93 }
Dan Gohman3dc2d922008-05-14 00:24:14 +000094}
95
Michael Zolotukhin73957172016-02-05 02:17:36 +000096/// Check if unrolling created a situation where we need to insert phi nodes to
97/// preserve LCSSA form.
98/// \param Blocks is a vector of basic blocks representing unrolled loop.
99/// \param L is the outer loop.
100/// It's possible that some of the blocks are in L, and some are not. In this
101/// case, if there is a use is outside L, and definition is inside L, we need to
102/// insert a phi-node, otherwise LCSSA will be broken.
103/// The function is just a helper function for llvm::UnrollLoop that returns
104/// true if this situation occurs, indicating that LCSSA needs to be fixed.
105static bool needToInsertPhisForLCSSA(Loop *L, std::vector<BasicBlock *> Blocks,
106 LoopInfo *LI) {
107 for (BasicBlock *BB : Blocks) {
108 if (LI->getLoopFor(BB) == L)
109 continue;
110 for (Instruction &I : *BB) {
111 for (Use &U : I.operands()) {
Michael Zolotukhind734bea2016-02-22 21:21:45 +0000112 if (auto Def = dyn_cast<Instruction>(U)) {
113 Loop *DefLoop = LI->getLoopFor(Def->getParent());
114 if (!DefLoop)
115 continue;
116 if (DefLoop->contains(L))
Michael Zolotukhin73957172016-02-05 02:17:36 +0000117 return true;
Michael Zolotukhind734bea2016-02-22 21:21:45 +0000118 }
Michael Zolotukhin73957172016-02-05 02:17:36 +0000119 }
120 }
121 }
122 return false;
123}
124
Florian Hahnfdea2e42017-01-10 23:24:54 +0000125/// Adds ClonedBB to LoopInfo, creates a new loop for ClonedBB if necessary
126/// and adds a mapping from the original loop to the new loop to NewLoops.
127/// Returns nullptr if no new loop was created and a pointer to the
128/// original loop OriginalBB was part of otherwise.
129const Loop* llvm::addClonedBlockToLoopInfo(BasicBlock *OriginalBB,
130 BasicBlock *ClonedBB, LoopInfo *LI,
131 NewLoopsMap &NewLoops) {
132 // Figure out which loop New is in.
133 const Loop *OldLoop = LI->getLoopFor(OriginalBB);
134 assert(OldLoop && "Should (at least) be in the loop being unrolled!");
135
136 Loop *&NewLoop = NewLoops[OldLoop];
137 if (!NewLoop) {
138 // Found a new sub-loop.
139 assert(OriginalBB == OldLoop->getHeader() &&
140 "Header should be first in RPO");
141
Sanjoy Dasdef17292017-09-28 02:45:42 +0000142 NewLoop = LI->AllocateLoop();
Florian Hahnfdea2e42017-01-10 23:24:54 +0000143 Loop *NewLoopParent = NewLoops.lookup(OldLoop->getParentLoop());
Michael Kuperstein5dd55e82017-01-26 01:04:11 +0000144
145 if (NewLoopParent)
146 NewLoopParent->addChildLoop(NewLoop);
147 else
148 LI->addTopLevelLoop(NewLoop);
149
Florian Hahnfdea2e42017-01-10 23:24:54 +0000150 NewLoop->addBasicBlockToLoop(ClonedBB, *LI);
151 return OldLoop;
152 } else {
153 NewLoop->addBasicBlockToLoop(ClonedBB, *LI);
154 return nullptr;
155 }
156}
157
Evgeny Stupachenko21bef2c2017-03-02 17:38:46 +0000158/// The function chooses which type of unroll (epilog or prolog) is more
159/// profitabale.
160/// Epilog unroll is more profitable when there is PHI that starts from
161/// constant. In this case epilog will leave PHI start from constant,
162/// but prolog will convert it to non-constant.
163///
164/// loop:
165/// PN = PHI [I, Latch], [CI, PreHeader]
166/// I = foo(PN)
167/// ...
168///
169/// Epilog unroll case.
170/// loop:
171/// PN = PHI [I2, Latch], [CI, PreHeader]
172/// I1 = foo(PN)
173/// I2 = foo(I1)
174/// ...
175/// Prolog unroll case.
176/// NewPN = PHI [PrologI, Prolog], [CI, PreHeader]
177/// loop:
178/// PN = PHI [I2, Latch], [NewPN, PreHeader]
179/// I1 = foo(PN)
180/// I2 = foo(I1)
181/// ...
182///
183static bool isEpilogProfitable(Loop *L) {
184 BasicBlock *PreHeader = L->getLoopPreheader();
185 BasicBlock *Header = L->getHeader();
186 assert(PreHeader && Header);
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000187 for (const PHINode &PN : Header->phis()) {
188 if (isa<ConstantInt>(PN.getIncomingValueForBlock(PreHeader)))
Evgeny Stupachenko21bef2c2017-03-02 17:38:46 +0000189 return true;
190 }
191 return false;
192}
193
David Greencdee1d92018-05-16 10:41:58 +0000194/// Perform some cleanup and simplifications on loops after unrolling. It is
195/// useful to simplify the IV's in the new loop, as well as do a quick
196/// simplify/dce pass of the instructions.
David Green963401d2018-07-01 12:47:30 +0000197void llvm::simplifyLoopAfterUnroll(Loop *L, bool SimplifyIVs, LoopInfo *LI,
198 ScalarEvolution *SE, DominatorTree *DT,
199 AssumptionCache *AC) {
David Greencdee1d92018-05-16 10:41:58 +0000200 // Simplify any new induction variables in the partially unrolled loop.
201 if (SE && SimplifyIVs) {
202 SmallVector<WeakTrackingVH, 16> DeadInsts;
203 simplifyLoopIVs(L, SE, DT, LI, DeadInsts);
204
205 // Aggressively clean up dead instructions that simplifyLoopIVs already
206 // identified. Any remaining should be cleaned up below.
207 while (!DeadInsts.empty())
208 if (Instruction *Inst =
209 dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val()))
210 RecursivelyDeleteTriviallyDeadInstructions(Inst);
211 }
212
213 // At this point, the code is well formed. We now do a quick sweep over the
214 // inserted code, doing constant propagation and dead code elimination as we
215 // go.
216 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
Benjamin Kramer28559a22018-09-10 12:32:06 +0000217 for (BasicBlock *BB : L->getBlocks()) {
David Greencdee1d92018-05-16 10:41:58 +0000218 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
219 Instruction *Inst = &*I++;
220
221 if (Value *V = SimplifyInstruction(Inst, {DL, nullptr, DT, AC}))
222 if (LI->replacementPreservesLCSSAForm(Inst, V))
223 Inst->replaceAllUsesWith(V);
224 if (isInstructionTriviallyDead(Inst))
225 BB->getInstList().erase(Inst);
226 }
227 }
228
229 // TODO: after peeling or unrolling, previously loop variant conditions are
230 // likely to fold to constants, eagerly propagating those here will require
231 // fewer cleanup passes to be run. Alternatively, a LoopEarlyCSE might be
232 // appropriate.
233}
234
Sanjoy Das09613b12017-09-20 02:31:57 +0000235/// Unroll the given loop by Count. The loop must be in LCSSA form. Unrolling
Dan Gohman3dc2d922008-05-14 00:24:14 +0000236/// can only fail when the loop's latch block is not terminated by a conditional
237/// branch instruction. However, if the trip count (and multiple) are not known,
238/// loop unrolling will mostly produce more code that is no faster.
239///
Haicheng Wub29dd012016-12-20 20:23:48 +0000240/// TripCount is the upper bound of the iteration on which control exits
241/// LatchBlock. Control may exit the loop prior to TripCount iterations either
242/// via an early branch in other loop block or via LatchBlock terminator. This
243/// is relaxed from the general definition of trip count which is the number of
244/// times the loop header executes. Note that UnrollLoop assumes that the loop
245/// counter test is in LatchBlock in order to remove unnecesssary instances of
246/// the test. If control can exit the loop from the LatchBlock's terminator
247/// prior to TripCount iterations, flag PreserveCondBr needs to be set.
Andrew Trick990f7712011-07-25 22:17:47 +0000248///
Haicheng Wu1ef17e92016-10-12 21:29:38 +0000249/// PreserveCondBr indicates whether the conditional branch of the LatchBlock
250/// needs to be preserved. It is needed when we use trip count upper bound to
John Brawn84b21832016-10-21 11:08:48 +0000251/// fully unroll the loop. If PreserveOnlyFirst is also set then only the first
252/// conditional branch needs to be preserved.
Haicheng Wu1ef17e92016-10-12 21:29:38 +0000253///
Andrew Trick990f7712011-07-25 22:17:47 +0000254/// Similarly, TripMultiple divides the number of times that the LatchBlock may
255/// execute without exiting the loop.
256///
Sanjoy Dase178f462015-04-14 03:20:38 +0000257/// If AllowRuntime is true then UnrollLoop will consider unrolling loops that
258/// have a runtime (i.e. not compile time constant) trip count. Unrolling these
259/// loops require a unroll "prologue" that runs "RuntimeTripCount % Count"
260/// iterations before branching into the unrolled loop. UnrollLoop will not
261/// runtime-unroll the loop if computing RuntimeTripCount will be expensive and
262/// AllowExpensiveTripCount is false.
263///
Sanjoy Das09613b12017-09-20 02:31:57 +0000264/// If we want to perform PGO-based loop peeling, PeelCount is set to the
Michael Kupersteinb151a642016-11-30 21:13:57 +0000265/// number of iterations we want to peel off.
266///
Dan Gohman3dc2d922008-05-14 00:24:14 +0000267/// The LoopInfo Analysis that is passed will be kept consistent.
268///
Justin Bogner843fb202015-12-15 19:40:57 +0000269/// This utility preserves LoopInfo. It will also preserve ScalarEvolution and
270/// DominatorTree if they are non-null.
Michael Kruse72448522018-12-12 17:32:52 +0000271///
272/// If RemainderLoop is non-null, it will receive the remainder loop (if
273/// required and not fully unrolled).
Alina Sbirleada0f71a2019-04-18 23:43:49 +0000274LoopUnrollResult llvm::UnrollLoop(Loop *L, UnrollLoopOptions ULO, LoopInfo *LI,
275 ScalarEvolution *SE, DominatorTree *DT,
276 AssumptionCache *AC,
277 OptimizationRemarkEmitter *ORE,
278 bool PreserveLCSSA, Loop **RemainderLoop) {
Michael Kupersteinb151a642016-11-30 21:13:57 +0000279
Dan Gohman415c64e2009-11-05 19:44:06 +0000280 BasicBlock *Preheader = L->getLoopPreheader();
281 if (!Preheader) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000282 LLVM_DEBUG(dbgs() << " Can't unroll; loop preheader-insertion failed.\n");
Sanjoy Das3567d3d2017-09-27 21:45:19 +0000283 return LoopUnrollResult::Unmodified;
Dan Gohman415c64e2009-11-05 19:44:06 +0000284 }
285
Dan Gohman3dc2d922008-05-14 00:24:14 +0000286 BasicBlock *LatchBlock = L->getLoopLatch();
Dan Gohman415c64e2009-11-05 19:44:06 +0000287 if (!LatchBlock) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000288 LLVM_DEBUG(dbgs() << " Can't unroll; loop exit-block-insertion failed.\n");
Sanjoy Das3567d3d2017-09-27 21:45:19 +0000289 return LoopUnrollResult::Unmodified;
Dan Gohman415c64e2009-11-05 19:44:06 +0000290 }
291
Andrew Trick4442bfe2012-04-10 05:14:42 +0000292 // Loops with indirectbr cannot be cloned.
293 if (!L->isSafeToClone()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000294 LLVM_DEBUG(dbgs() << " Can't unroll; Loop body cannot be cloned.\n");
Sanjoy Das3567d3d2017-09-27 21:45:19 +0000295 return LoopUnrollResult::Unmodified;
Andrew Trick4442bfe2012-04-10 05:14:42 +0000296 }
297
Davide Italiano0f62eea2017-04-24 20:14:11 +0000298 // The current loop unroll pass can only unroll loops with a single latch
299 // that's a conditional branch exiting the loop.
300 // FIXME: The implementation can be extended to work with more complicated
301 // cases, e.g. loops with multiple latches.
Dan Gohman415c64e2009-11-05 19:44:06 +0000302 BasicBlock *Header = L->getHeader();
Dan Gohman3dc2d922008-05-14 00:24:14 +0000303 BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
Andrew Trick279e7a62011-07-23 00:29:16 +0000304
Dan Gohman3dc2d922008-05-14 00:24:14 +0000305 if (!BI || BI->isUnconditional()) {
306 // The loop-rotate pass can be helpful to avoid this in many cases.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000307 LLVM_DEBUG(
308 dbgs()
309 << " Can't unroll; loop not terminated by a conditional branch.\n");
Sanjoy Das3567d3d2017-09-27 21:45:19 +0000310 return LoopUnrollResult::Unmodified;
Dan Gohman3dc2d922008-05-14 00:24:14 +0000311 }
Andrew Trick279e7a62011-07-23 00:29:16 +0000312
Davide Italiano0f62eea2017-04-24 20:14:11 +0000313 auto CheckSuccessors = [&](unsigned S1, unsigned S2) {
314 return BI->getSuccessor(S1) == Header && !L->contains(BI->getSuccessor(S2));
Davide Italiano0f62eea2017-04-24 20:14:11 +0000315 };
316
317 if (!CheckSuccessors(0, 1) && !CheckSuccessors(1, 0)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000318 LLVM_DEBUG(dbgs() << "Can't unroll; only loops with one conditional latch"
319 " exiting the loop can be unrolled\n");
Sanjoy Das3567d3d2017-09-27 21:45:19 +0000320 return LoopUnrollResult::Unmodified;
Davide Italiano0f62eea2017-04-24 20:14:11 +0000321 }
322
Chris Lattner4a14fbc2011-02-18 04:25:21 +0000323 if (Header->hasAddressTaken()) {
324 // The loop-rotate pass can be helpful to avoid this in many cases.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000325 LLVM_DEBUG(
326 dbgs() << " Won't unroll loop: address of header block is taken.\n");
Sanjoy Das3567d3d2017-09-27 21:45:19 +0000327 return LoopUnrollResult::Unmodified;
Chris Lattner4a14fbc2011-02-18 04:25:21 +0000328 }
Dan Gohman3dc2d922008-05-14 00:24:14 +0000329
Alina Sbirleada0f71a2019-04-18 23:43:49 +0000330 if (ULO.TripCount != 0)
331 LLVM_DEBUG(dbgs() << " Trip Count = " << ULO.TripCount << "\n");
332 if (ULO.TripMultiple != 1)
333 LLVM_DEBUG(dbgs() << " Trip Multiple = " << ULO.TripMultiple << "\n");
Dan Gohman3dc2d922008-05-14 00:24:14 +0000334
335 // Effectively "DCE" unrolled iterations that are beyond the tripcount
336 // and will never be executed.
Alina Sbirleada0f71a2019-04-18 23:43:49 +0000337 if (ULO.TripCount != 0 && ULO.Count > ULO.TripCount)
338 ULO.Count = ULO.TripCount;
Dan Gohman3dc2d922008-05-14 00:24:14 +0000339
Michael Kupersteinb151a642016-11-30 21:13:57 +0000340 // Don't enter the unroll code if there is nothing to do.
Alina Sbirleada0f71a2019-04-18 23:43:49 +0000341 if (ULO.TripCount == 0 && ULO.Count < 2 && ULO.PeelCount == 0) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000342 LLVM_DEBUG(dbgs() << "Won't unroll; almost nothing to do\n");
Sanjoy Das3567d3d2017-09-27 21:45:19 +0000343 return LoopUnrollResult::Unmodified;
Anna Thomase7d865e2017-01-27 17:57:05 +0000344 }
Andrew Trickca3417e2011-12-16 02:03:48 +0000345
Alina Sbirleada0f71a2019-04-18 23:43:49 +0000346 assert(ULO.Count > 0);
347 assert(ULO.TripMultiple > 0);
348 assert(ULO.TripCount == 0 || ULO.TripCount % ULO.TripMultiple == 0);
Dan Gohman3dc2d922008-05-14 00:24:14 +0000349
350 // Are we eliminating the loop control altogether?
Alina Sbirleada0f71a2019-04-18 23:43:49 +0000351 bool CompletelyUnroll = ULO.Count == ULO.TripCount;
Michael Zolotukhin78760ee2015-12-09 18:20:28 +0000352 SmallVector<BasicBlock *, 4> ExitBlocks;
353 L->getExitBlocks(ExitBlocks);
Michael Zolotukhin97567e12016-04-06 21:47:12 +0000354 std::vector<BasicBlock*> OriginalLoopBlocks = L->getBlocks();
Michael Zolotukhin73957172016-02-05 02:17:36 +0000355
356 // Go through all exits of L and see if there are any phi-nodes there. We just
357 // conservatively assume that they're inserted to preserve LCSSA form, which
358 // means that complete unrolling might break this form. We need to either fix
359 // it in-place after the transformation, or entirely rebuild LCSSA. TODO: For
360 // now we just recompute LCSSA for the outer loop, but it should be possible
361 // to fix it in-place.
362 bool NeedToFixLCSSA = PreserveLCSSA && CompletelyUnroll &&
David Majnemer0a16c222016-08-11 21:15:00 +0000363 any_of(ExitBlocks, [](const BasicBlock *BB) {
364 return isa<PHINode>(BB->begin());
365 });
Dan Gohman3dc2d922008-05-14 00:24:14 +0000366
Andrew Trickd04d15292011-12-09 06:19:40 +0000367 // We assume a run-time trip count if the compiler cannot
368 // figure out the loop trip count and the unroll-runtime
369 // flag is specified.
Alina Sbirleada0f71a2019-04-18 23:43:49 +0000370 bool RuntimeTripCount =
371 (ULO.TripCount == 0 && ULO.Count > 0 && ULO.AllowRuntime);
Andrew Trickd04d15292011-12-09 06:19:40 +0000372
Alina Sbirleada0f71a2019-04-18 23:43:49 +0000373 assert((!RuntimeTripCount || !ULO.PeelCount) &&
Michael Kupersteinb151a642016-11-30 21:13:57 +0000374 "Did not expect runtime trip-count unrolling "
375 "and peeling for the same loop");
376
Florian Hahn52436a52018-03-23 10:38:12 +0000377 bool Peeled = false;
Alina Sbirleada0f71a2019-04-18 23:43:49 +0000378 if (ULO.PeelCount) {
379 Peeled = peelLoop(L, ULO.PeelCount, LI, SE, DT, AC, PreserveLCSSA);
Davide Italiano20cb7e82017-08-28 20:29:33 +0000380
381 // Successful peeling may result in a change in the loop preheader/trip
382 // counts. If we later unroll the loop, we want these to be updated.
383 if (Peeled) {
384 BasicBlock *ExitingBlock = L->getExitingBlock();
385 assert(ExitingBlock && "Loop without exiting block?");
386 Preheader = L->getLoopPreheader();
Alina Sbirleada0f71a2019-04-18 23:43:49 +0000387 ULO.TripCount = SE->getSmallConstantTripCount(L, ExitingBlock);
388 ULO.TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock);
Davide Italiano20cb7e82017-08-28 20:29:33 +0000389 }
390 }
Michael Kupersteinb151a642016-11-30 21:13:57 +0000391
Justin Lebar6827de12016-03-14 23:15:34 +0000392 // Loops containing convergent instructions must have a count that divides
393 // their TripMultiple.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000394 LLVM_DEBUG(
Eric Christopher257338f2016-03-15 03:01:31 +0000395 {
396 bool HasConvergent = false;
Justin Lebar50deb6d2016-05-10 00:31:23 +0000397 for (auto &BB : L->blocks())
Eric Christopher257338f2016-03-15 03:01:31 +0000398 for (auto &I : *BB)
399 if (auto CS = CallSite(&I))
400 HasConvergent |= CS.isConvergent();
Alina Sbirleada0f71a2019-04-18 23:43:49 +0000401 assert((!HasConvergent || ULO.TripMultiple % ULO.Count == 0) &&
Eric Christopheree00abe2016-03-15 02:19:06 +0000402 "Unroll count must divide trip multiple if loop contains a "
Justin Lebar50deb6d2016-05-10 00:31:23 +0000403 "convergent operation.");
Eric Christopher257338f2016-03-15 03:01:31 +0000404 });
Michael Kupersteinb151a642016-11-30 21:13:57 +0000405
Evgeny Stupachenko21bef2c2017-03-02 17:38:46 +0000406 bool EpilogProfitability =
407 UnrollRuntimeEpilog.getNumOccurrences() ? UnrollRuntimeEpilog
408 : isEpilogProfitable(L);
409
Alina Sbirleada0f71a2019-04-18 23:43:49 +0000410 if (RuntimeTripCount && ULO.TripMultiple % ULO.Count != 0 &&
411 !UnrollRuntimeLoopRemainder(L, ULO.Count, ULO.AllowExpensiveTripCount,
412 EpilogProfitability, ULO.UnrollRemainder,
413 ULO.ForgetAllSCEV, LI, SE, DT, AC,
414 PreserveLCSSA, RemainderLoop)) {
415 if (ULO.Force)
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +0000416 RuntimeTripCount = false;
Anna Thomase7d865e2017-01-27 17:57:05 +0000417 else {
David Green963401d2018-07-01 12:47:30 +0000418 LLVM_DEBUG(dbgs() << "Won't unroll; remainder loop could not be "
419 "generated when assuming runtime trip count\n");
Sanjoy Das3567d3d2017-09-27 21:45:19 +0000420 return LoopUnrollResult::Unmodified;
Anna Thomase7d865e2017-01-27 17:57:05 +0000421 }
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +0000422 }
Andrew Trickd04d15292011-12-09 06:19:40 +0000423
Dan Gohman3dc2d922008-05-14 00:24:14 +0000424 // If we know the trip count, we know the multiple...
425 unsigned BreakoutTrip = 0;
Alina Sbirleada0f71a2019-04-18 23:43:49 +0000426 if (ULO.TripCount != 0) {
427 BreakoutTrip = ULO.TripCount % ULO.Count;
428 ULO.TripMultiple = 0;
Dan Gohman3dc2d922008-05-14 00:24:14 +0000429 } else {
430 // Figure out what multiple to use.
Alina Sbirleada0f71a2019-04-18 23:43:49 +0000431 BreakoutTrip = ULO.TripMultiple =
432 (unsigned)GreatestCommonDivisor64(ULO.Count, ULO.TripMultiple);
Dan Gohman3dc2d922008-05-14 00:24:14 +0000433 }
434
Adam Nemetf57cc622016-09-30 03:44:16 +0000435 using namespace ore;
Diego Novillo34fc8a72014-04-29 14:27:31 +0000436 // Report the unrolling decision.
Dan Gohman3dc2d922008-05-14 00:24:14 +0000437 if (CompletelyUnroll) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000438 LLVM_DEBUG(dbgs() << "COMPLETELY UNROLLING loop %" << Header->getName()
Alina Sbirleada0f71a2019-04-18 23:43:49 +0000439 << " with trip count " << ULO.TripCount << "!\n");
David Green64f53b42017-10-31 10:47:46 +0000440 if (ORE)
441 ORE->emit([&]() {
442 return OptimizationRemark(DEBUG_TYPE, "FullyUnrolled", L->getStartLoc(),
443 L->getHeader())
444 << "completely unrolled loop with "
Alina Sbirleada0f71a2019-04-18 23:43:49 +0000445 << NV("UnrollCount", ULO.TripCount) << " iterations";
David Green64f53b42017-10-31 10:47:46 +0000446 });
Alina Sbirleada0f71a2019-04-18 23:43:49 +0000447 } else if (ULO.PeelCount) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000448 LLVM_DEBUG(dbgs() << "PEELING loop %" << Header->getName()
Alina Sbirleada0f71a2019-04-18 23:43:49 +0000449 << " with iteration count " << ULO.PeelCount << "!\n");
David Green64f53b42017-10-31 10:47:46 +0000450 if (ORE)
451 ORE->emit([&]() {
452 return OptimizationRemark(DEBUG_TYPE, "Peeled", L->getStartLoc(),
453 L->getHeader())
Alina Sbirleada0f71a2019-04-18 23:43:49 +0000454 << " peeled loop by " << NV("PeelCount", ULO.PeelCount)
David Green64f53b42017-10-31 10:47:46 +0000455 << " iterations";
456 });
Dan Gohman3dc2d922008-05-14 00:24:14 +0000457 } else {
Adam Nemet15fccf02017-09-19 23:00:55 +0000458 auto DiagBuilder = [&]() {
459 OptimizationRemark Diag(DEBUG_TYPE, "PartialUnrolled", L->getStartLoc(),
460 L->getHeader());
461 return Diag << "unrolled loop by a factor of "
Alina Sbirleada0f71a2019-04-18 23:43:49 +0000462 << NV("UnrollCount", ULO.Count);
Adam Nemet15fccf02017-09-19 23:00:55 +0000463 };
Benjamin Kramercccdadc2014-07-08 14:55:06 +0000464
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000465 LLVM_DEBUG(dbgs() << "UNROLLING loop %" << Header->getName() << " by "
Alina Sbirleada0f71a2019-04-18 23:43:49 +0000466 << ULO.Count);
467 if (ULO.TripMultiple == 0 || BreakoutTrip != ULO.TripMultiple) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000468 LLVM_DEBUG(dbgs() << " with a breakout at trip " << BreakoutTrip);
David Green64f53b42017-10-31 10:47:46 +0000469 if (ORE)
470 ORE->emit([&]() {
471 return DiagBuilder() << " with a breakout at trip "
472 << NV("BreakoutTrip", BreakoutTrip);
473 });
Alina Sbirleada0f71a2019-04-18 23:43:49 +0000474 } else if (ULO.TripMultiple != 1) {
475 LLVM_DEBUG(dbgs() << " with " << ULO.TripMultiple << " trips per branch");
David Green64f53b42017-10-31 10:47:46 +0000476 if (ORE)
477 ORE->emit([&]() {
Alina Sbirleada0f71a2019-04-18 23:43:49 +0000478 return DiagBuilder()
479 << " with " << NV("TripMultiple", ULO.TripMultiple)
480 << " trips per branch";
David Green64f53b42017-10-31 10:47:46 +0000481 });
Andrew Trickd04d15292011-12-09 06:19:40 +0000482 } else if (RuntimeTripCount) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000483 LLVM_DEBUG(dbgs() << " with run-time trip count");
David Green64f53b42017-10-31 10:47:46 +0000484 if (ORE)
485 ORE->emit(
486 [&]() { return DiagBuilder() << " with run-time trip count"; });
Dan Gohman3dc2d922008-05-14 00:24:14 +0000487 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000488 LLVM_DEBUG(dbgs() << "!\n");
Dan Gohman3dc2d922008-05-14 00:24:14 +0000489 }
490
Max Kazantseva5574932018-03-26 11:31:46 +0000491 // We are going to make changes to this loop. SCEV may be keeping cached info
492 // about it, in particular about backedge taken count. The changes we make
493 // are guaranteed to invalidate this information for our loop. It is tempting
494 // to only invalidate the loop being unrolled, but it is incorrect as long as
495 // all exiting branches from all inner loops have impact on the outer loops,
496 // and if something changes inside them then any of outer loops may also
497 // change. When we forget outermost loop, we also forget all contained loops
498 // and this is what we need here.
Alina Sbirlea2312a062019-04-12 19:16:07 +0000499 if (SE) {
Alina Sbirleada0f71a2019-04-18 23:43:49 +0000500 if (ULO.ForgetAllSCEV)
Alina Sbirlea2312a062019-04-12 19:16:07 +0000501 SE->forgetAllLoops();
502 else
503 SE->forgetTopmostLoop(L);
504 }
Max Kazantseva5574932018-03-26 11:31:46 +0000505
Dan Gohman04c8bd72008-06-24 20:44:42 +0000506 bool ContinueOnTrue = L->contains(BI->getSuccessor(0));
Dan Gohman3dc2d922008-05-14 00:24:14 +0000507 BasicBlock *LoopExit = BI->getSuccessor(ContinueOnTrue);
508
509 // For the first iteration of the loop, we should use the precloned values for
510 // PHI nodes. Insert associations now.
Devang Patel21766432010-04-20 22:24:18 +0000511 ValueToValueMapTy LastValueMap;
Dan Gohman04c8bd72008-06-24 20:44:42 +0000512 std::vector<PHINode*> OrigPHINode;
Dan Gohman3dc2d922008-05-14 00:24:14 +0000513 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
Andrew Trick5e0ee1c2011-08-09 03:11:29 +0000514 OrigPHINode.push_back(cast<PHINode>(I));
Dan Gohman3dc2d922008-05-14 00:24:14 +0000515 }
516
517 std::vector<BasicBlock*> Headers;
518 std::vector<BasicBlock*> Latches;
519 Headers.push_back(Header);
520 Latches.push_back(LatchBlock);
521
Andrew Trickb72bbe22011-08-10 00:28:10 +0000522 // The current on-the-fly SSA update requires blocks to be processed in
523 // reverse postorder so that LastValueMap contains the correct value at each
524 // exit.
525 LoopBlocksDFS DFS(L);
Andrew Trick78b40c32011-08-10 01:59:05 +0000526 DFS.perform(LI);
527
Andrew Trickb72bbe22011-08-10 00:28:10 +0000528 // Stash the DFS iterators before adding blocks to the loop.
529 LoopBlocksDFS::RPOIterator BlockBegin = DFS.beginRPO();
530 LoopBlocksDFS::RPOIterator BlockEnd = DFS.endRPO();
531
Michael Zolotukhin73957172016-02-05 02:17:36 +0000532 std::vector<BasicBlock*> UnrolledLoopBlocks = L->getBlocks();
Michael Zolotukhin2f507252016-08-08 19:02:15 +0000533
534 // Loop Unrolling might create new loops. While we do preserve LoopInfo, we
535 // might break loop-simplified form for these loops (as they, e.g., would
536 // share the same exit blocks). We'll keep track of loops for which we can
537 // break this so that later we can re-simplify them.
538 SmallSetVector<Loop *, 4> LoopsToSimplify;
539 for (Loop *SubLoop : *L)
540 LoopsToSimplify.insert(SubLoop);
541
Dehao Chenfb02f712017-02-10 21:09:07 +0000542 if (Header->getParent()->isDebugInfoForProfiling())
543 for (BasicBlock *BB : L->getBlocks())
544 for (Instruction &I : *BB)
Dehao Chened2d5402017-10-26 21:20:52 +0000545 if (!isa<DbgInfoIntrinsic>(&I))
Mircea Trofinb53eeb62018-12-21 22:48:50 +0000546 if (const DILocation *DIL = I.getDebugLoc()) {
Alina Sbirleada0f71a2019-04-18 23:43:49 +0000547 auto NewDIL = DIL->cloneByMultiplyingDuplicationFactor(ULO.Count);
Mircea Trofinb53eeb62018-12-21 22:48:50 +0000548 if (NewDIL)
549 I.setDebugLoc(NewDIL.getValue());
550 else
551 LLVM_DEBUG(dbgs()
552 << "Failed to create new discriminator: "
553 << DIL->getFilename() << " Line: " << DIL->getLine());
554 }
Dehao Chenfb02f712017-02-10 21:09:07 +0000555
Alina Sbirleada0f71a2019-04-18 23:43:49 +0000556 for (unsigned It = 1; It != ULO.Count; ++It) {
Dan Gohman3dc2d922008-05-14 00:24:14 +0000557 std::vector<BasicBlock*> NewBlocks;
Duncan P. N. Exon Smithc46cfcb2014-10-07 21:19:00 +0000558 SmallDenseMap<const Loop *, Loop *, 4> NewLoops;
559 NewLoops[L] = L;
Andrew Trick279e7a62011-07-23 00:29:16 +0000560
Andrew Trickb72bbe22011-08-10 00:28:10 +0000561 for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
Devang Patelb8f11de2010-06-23 23:55:51 +0000562 ValueToValueMapTy VMap;
563 BasicBlock *New = CloneBasicBlock(*BB, VMap, "." + Twine(It));
Dan Gohman04c8bd72008-06-24 20:44:42 +0000564 Header->getParent()->getBasicBlockList().push_back(New);
Dan Gohman3dc2d922008-05-14 00:24:14 +0000565
Michael Kuperstein3c6b3ba2017-02-01 21:06:33 +0000566 assert((*BB != Header || LI->getLoopFor(*BB) == L) &&
Florian Hahna35b8a42017-02-01 10:39:35 +0000567 "Header should not be in a sub-loop");
Duncan P. N. Exon Smithc46cfcb2014-10-07 21:19:00 +0000568 // Tell LI about New.
Florian Hahna35b8a42017-02-01 10:39:35 +0000569 const Loop *OldLoop = addClonedBlockToLoopInfo(*BB, New, LI, NewLoops);
Max Kazantseva5574932018-03-26 11:31:46 +0000570 if (OldLoop)
Florian Hahna35b8a42017-02-01 10:39:35 +0000571 LoopsToSimplify.insert(NewLoops[OldLoop]);
Duncan P. N. Exon Smithc46cfcb2014-10-07 21:19:00 +0000572
Dan Gohman04c8bd72008-06-24 20:44:42 +0000573 if (*BB == Header)
Duncan P. N. Exon Smith0bbf5412014-10-06 22:04:59 +0000574 // Loop over all of the PHI nodes in the block, changing them to use
575 // the incoming values from the previous block.
Sanjay Pateleaf06852016-03-08 17:12:32 +0000576 for (PHINode *OrigPHI : OrigPHINode) {
577 PHINode *NewPHI = cast<PHINode>(VMap[OrigPHI]);
Dan Gohman3dc2d922008-05-14 00:24:14 +0000578 Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
579 if (Instruction *InValI = dyn_cast<Instruction>(InVal))
Dan Gohman18fa5682009-12-18 01:24:09 +0000580 if (It > 1 && L->contains(InValI))
Dan Gohman3dc2d922008-05-14 00:24:14 +0000581 InVal = LastValueMap[InValI];
Sanjay Pateleaf06852016-03-08 17:12:32 +0000582 VMap[OrigPHI] = InVal;
Dan Gohman3dc2d922008-05-14 00:24:14 +0000583 New->getInstList().erase(NewPHI);
584 }
585
586 // Update our running map of newest clones
Dan Gohman04c8bd72008-06-24 20:44:42 +0000587 LastValueMap[*BB] = New;
Devang Patelb8f11de2010-06-23 23:55:51 +0000588 for (ValueToValueMapTy::iterator VI = VMap.begin(), VE = VMap.end();
Dan Gohman3dc2d922008-05-14 00:24:14 +0000589 VI != VE; ++VI)
590 LastValueMap[VI->first] = VI->second;
591
Andrew Trickb72bbe22011-08-10 00:28:10 +0000592 // Add phi entries for newly created values to all exit blocks.
Sanjay Pateleaf06852016-03-08 17:12:32 +0000593 for (BasicBlock *Succ : successors(*BB)) {
594 if (L->contains(Succ))
Andrew Trickb72bbe22011-08-10 00:28:10 +0000595 continue;
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000596 for (PHINode &PHI : Succ->phis()) {
597 Value *Incoming = PHI.getIncomingValueForBlock(*BB);
Andrew Trickb72bbe22011-08-10 00:28:10 +0000598 ValueToValueMapTy::iterator It = LastValueMap.find(Incoming);
599 if (It != LastValueMap.end())
600 Incoming = It->second;
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000601 PHI.addIncoming(Incoming, New);
Andrew Trickb72bbe22011-08-10 00:28:10 +0000602 }
603 }
Dan Gohman04c8bd72008-06-24 20:44:42 +0000604 // Keep track of new headers and latches as we create them, so that
605 // we can insert the proper branches later.
606 if (*BB == Header)
607 Headers.push_back(New);
Andrew Trickb72bbe22011-08-10 00:28:10 +0000608 if (*BB == LatchBlock)
Dan Gohman04c8bd72008-06-24 20:44:42 +0000609 Latches.push_back(New);
610
Dan Gohman04c8bd72008-06-24 20:44:42 +0000611 NewBlocks.push_back(New);
Michael Zolotukhin73957172016-02-05 02:17:36 +0000612 UnrolledLoopBlocks.push_back(New);
Michael Zolotukhinde19ed12016-02-23 00:30:50 +0000613
614 // Update DomTree: since we just copy the loop body, and each copy has a
615 // dedicated entry block (copy of the header block), this header's copy
616 // dominates all copied blocks. That means, dominance relations in the
617 // copied body are the same as in the original body.
618 if (DT) {
619 if (*BB == Header)
620 DT->addNewBlock(New, Latches[It - 1]);
621 else {
622 auto BBDomNode = DT->getNode(*BB);
623 auto BBIDom = BBDomNode->getIDom();
624 BasicBlock *OriginalBBIDom = BBIDom->getBlock();
625 DT->addNewBlock(
626 New, cast<BasicBlock>(LastValueMap[cast<Value>(OriginalBBIDom)]));
627 }
628 }
Dan Gohman3dc2d922008-05-14 00:24:14 +0000629 }
Andrew Trick279e7a62011-07-23 00:29:16 +0000630
Dan Gohman3dc2d922008-05-14 00:24:14 +0000631 // Remap all instructions in the most recent iteration
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000632 for (BasicBlock *NewBlock : NewBlocks) {
633 for (Instruction &I : *NewBlock) {
Sanjay Pateleaf06852016-03-08 17:12:32 +0000634 ::remapInstruction(&I, LastValueMap);
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000635 if (auto *II = dyn_cast<IntrinsicInst>(&I))
636 if (II->getIntrinsicID() == Intrinsic::assume)
637 AC->registerAssumption(II);
638 }
639 }
Dan Gohman3dc2d922008-05-14 00:24:14 +0000640 }
Andrew Trick279e7a62011-07-23 00:29:16 +0000641
Andrew Trickb72bbe22011-08-10 00:28:10 +0000642 // Loop over the PHI nodes in the original block, setting incoming values.
Sanjay Pateleaf06852016-03-08 17:12:32 +0000643 for (PHINode *PN : OrigPHINode) {
Andrew Trickb72bbe22011-08-10 00:28:10 +0000644 if (CompletelyUnroll) {
Dan Gohman04c8bd72008-06-24 20:44:42 +0000645 PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
646 Header->getInstList().erase(PN);
Alina Sbirleada0f71a2019-04-18 23:43:49 +0000647 } else if (ULO.Count > 1) {
Andrew Trickb72bbe22011-08-10 00:28:10 +0000648 Value *InVal = PN->removeIncomingValue(LatchBlock, false);
649 // If this value was defined in the loop, take the value defined by the
650 // last iteration of the loop.
651 if (Instruction *InValI = dyn_cast<Instruction>(InVal)) {
652 if (L->contains(InValI))
653 InVal = LastValueMap[InVal];
654 }
655 assert(Latches.back() == LastValueMap[LatchBlock] && "bad last latch");
656 PN->addIncoming(InVal, Latches.back());
657 }
Dan Gohman04c8bd72008-06-24 20:44:42 +0000658 }
Dan Gohman3dc2d922008-05-14 00:24:14 +0000659
660 // Now that all the basic blocks for the unrolled iterations are in place,
661 // set up the branches to connect them.
Dan Gohman04c8bd72008-06-24 20:44:42 +0000662 for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
Dan Gohman3dc2d922008-05-14 00:24:14 +0000663 // The original branch was replicated in each unrolled iteration.
Dan Gohman04c8bd72008-06-24 20:44:42 +0000664 BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
Dan Gohman3dc2d922008-05-14 00:24:14 +0000665
666 // The branch destination.
Dan Gohman04c8bd72008-06-24 20:44:42 +0000667 unsigned j = (i + 1) % e;
668 BasicBlock *Dest = Headers[j];
Dan Gohman3dc2d922008-05-14 00:24:14 +0000669 bool NeedConditional = true;
670
Andrew Trickd04d15292011-12-09 06:19:40 +0000671 if (RuntimeTripCount && j != 0) {
672 NeedConditional = false;
673 }
674
Dan Gohman04c8bd72008-06-24 20:44:42 +0000675 // For a complete unroll, make the last iteration end with a branch
676 // to the exit block.
Michael Zolotukhind56ee062015-09-23 23:12:43 +0000677 if (CompletelyUnroll) {
678 if (j == 0)
679 Dest = LoopExit;
Haicheng Wu1ef17e92016-10-12 21:29:38 +0000680 // If using trip count upper bound to completely unroll, we need to keep
681 // the conditional branch except the last one because the loop may exit
682 // after any iteration.
683 assert(NeedConditional &&
684 "NeedCondition cannot be modified by both complete "
685 "unrolling and runtime unrolling");
Alina Sbirleada0f71a2019-04-18 23:43:49 +0000686 NeedConditional =
687 (ULO.PreserveCondBr && j && !(ULO.PreserveOnlyFirst && i != 0));
688 } else if (j != BreakoutTrip &&
689 (ULO.TripMultiple == 0 || j % ULO.TripMultiple != 0)) {
Haicheng Wu1ef17e92016-10-12 21:29:38 +0000690 // If we know the trip count or a multiple of it, we can safely use an
691 // unconditional branch for some iterations.
Dan Gohman3dc2d922008-05-14 00:24:14 +0000692 NeedConditional = false;
693 }
694
695 if (NeedConditional) {
696 // Update the conditional branch's successor for the following
697 // iteration.
698 Term->setSuccessor(!ContinueOnTrue, Dest);
699 } else {
Andrew Trickb72bbe22011-08-10 00:28:10 +0000700 // Remove phi operands at this loop exit
701 if (Dest != LoopExit) {
702 BasicBlock *BB = Latches[i];
Sanjay Pateleaf06852016-03-08 17:12:32 +0000703 for (BasicBlock *Succ: successors(BB)) {
704 if (Succ == Headers[i])
Andrew Trickb72bbe22011-08-10 00:28:10 +0000705 continue;
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000706 for (PHINode &Phi : Succ->phis())
707 Phi.removeIncomingValue(BB, false);
Andrew Trickb72bbe22011-08-10 00:28:10 +0000708 }
709 }
Jay Foad89afb432011-01-07 20:25:56 +0000710 // Replace the conditional branch with an unconditional one.
711 BranchInst::Create(Dest, Term);
712 Term->eraseFromParent();
Jay Foada97a2c92011-06-21 10:33:19 +0000713 }
714 }
Eli Friedman0a217452017-01-18 23:26:37 +0000715
Michael Zolotukhin97567e12016-04-06 21:47:12 +0000716 // Update dominators of blocks we might reach through exits.
717 // Immediate dominator of such block might change, because we add more
Michael Zolotukhinde19ed12016-02-23 00:30:50 +0000718 // routes which can lead to the exit: we can now reach it from the copied
Eli Friedman0a217452017-01-18 23:26:37 +0000719 // iterations too.
Alina Sbirleada0f71a2019-04-18 23:43:49 +0000720 if (DT && ULO.Count > 1) {
Michael Zolotukhin97567e12016-04-06 21:47:12 +0000721 for (auto *BB : OriginalLoopBlocks) {
722 auto *BBDomNode = DT->getNode(BB);
Michael Zolotukhin56ad4042016-04-07 00:09:42 +0000723 SmallVector<BasicBlock *, 16> ChildrenToUpdate;
Michael Zolotukhin97567e12016-04-06 21:47:12 +0000724 for (auto *ChildDomNode : BBDomNode->getChildren()) {
725 auto *ChildBB = ChildDomNode->getBlock();
Michael Zolotukhin56ad4042016-04-07 00:09:42 +0000726 if (!L->contains(ChildBB))
727 ChildrenToUpdate.push_back(ChildBB);
Michael Zolotukhin97567e12016-04-06 21:47:12 +0000728 }
Eli Friedman0a217452017-01-18 23:26:37 +0000729 BasicBlock *NewIDom;
730 if (BB == LatchBlock) {
731 // The latch is special because we emit unconditional branches in
732 // some cases where the original loop contained a conditional branch.
733 // Since the latch is always at the bottom of the loop, if the latch
734 // dominated an exit before unrolling, the new dominator of that exit
735 // must also be a latch. Specifically, the dominator is the first
736 // latch which ends in a conditional branch, or the last latch if
737 // there is no such latch.
738 NewIDom = Latches.back();
739 for (BasicBlock *IterLatch : Latches) {
Chandler Carruthedb12a82018-10-15 10:04:59 +0000740 Instruction *Term = IterLatch->getTerminator();
Eli Friedman0a217452017-01-18 23:26:37 +0000741 if (isa<BranchInst>(Term) && cast<BranchInst>(Term)->isConditional()) {
742 NewIDom = IterLatch;
743 break;
744 }
745 }
746 } else {
747 // The new idom of the block will be the nearest common dominator
748 // of all copies of the previous idom. This is equivalent to the
749 // nearest common dominator of the previous idom and the first latch,
750 // which dominates all copies of the previous idom.
751 NewIDom = DT->findNearestCommonDominator(BB, LatchBlock);
752 }
Michael Zolotukhin56ad4042016-04-07 00:09:42 +0000753 for (auto *ChildBB : ChildrenToUpdate)
754 DT->changeImmediateDominator(ChildBB, NewIDom);
Michael Zolotukhinde19ed12016-02-23 00:30:50 +0000755 }
756 }
Jay Foada97a2c92011-06-21 10:33:19 +0000757
David Green7c35de12018-02-28 11:00:08 +0000758 assert(!DT || !UnrollVerifyDomtree ||
759 DT->verify(DominatorTree::VerificationLevel::Fast));
Eli Friedman0a217452017-01-18 23:26:37 +0000760
Alina Sbirleabfceed42019-06-04 18:45:15 +0000761 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
Jay Foad61ea0e42011-06-23 09:09:15 +0000762 // Merge adjacent basic blocks, if possible.
Sanjay Pateleaf06852016-03-08 17:12:32 +0000763 for (BasicBlock *Latch : Latches) {
764 BranchInst *Term = cast<BranchInst>(Latch->getTerminator());
Jay Foad61ea0e42011-06-23 09:09:15 +0000765 if (Term->isUnconditional()) {
766 BasicBlock *Dest = Term->getSuccessor(0);
Alina Sbirleabfceed42019-06-04 18:45:15 +0000767 BasicBlock *Fold = Dest->getUniquePredecessor();
768 if (MergeBlockIntoPredecessor(Dest, &DTU, LI)) {
Michael Zolotukhin73957172016-02-05 02:17:36 +0000769 // Dest has been folded into Fold. Update our worklists accordingly.
Jay Foad61ea0e42011-06-23 09:09:15 +0000770 std::replace(Latches.begin(), Latches.end(), Dest, Fold);
Michael Zolotukhin73957172016-02-05 02:17:36 +0000771 UnrolledLoopBlocks.erase(std::remove(UnrolledLoopBlocks.begin(),
772 UnrolledLoopBlocks.end(), Dest),
773 UnrolledLoopBlocks.end());
774 }
Jay Foad61ea0e42011-06-23 09:09:15 +0000775 }
776 }
Andrew Trick279e7a62011-07-23 00:29:16 +0000777
David Greencdee1d92018-05-16 10:41:58 +0000778 // At this point, the code is well formed. We now simplify the unrolled loop,
779 // doing constant propagation and dead code elimination as we go.
Alina Sbirleada0f71a2019-04-18 23:43:49 +0000780 simplifyLoopAfterUnroll(L, !CompletelyUnroll && (ULO.Count > 1 || Peeled), LI,
781 SE, DT, AC);
Philip Reamesfac031a2016-12-30 22:10:19 +0000782
Dan Gohman3dc2d922008-05-14 00:24:14 +0000783 NumCompletelyUnrolled += CompletelyUnroll;
784 ++NumUnrolled;
Chandler Carruthaa7fa5e2014-01-23 11:23:19 +0000785
786 Loop *OuterL = L->getParentLoop();
Justin Bogner883a3ea2015-12-16 18:40:20 +0000787 // Update LoopInfo if the loop is completely removed.
788 if (CompletelyUnroll)
Sanjoy Das388b0122017-09-22 01:47:41 +0000789 LI->erase(L);
Dan Gohman3dc2d922008-05-14 00:24:14 +0000790
Michael Zolotukhin73957172016-02-05 02:17:36 +0000791 // After complete unrolling most of the blocks should be contained in OuterL.
792 // However, some of them might happen to be out of OuterL (e.g. if they
793 // precede a loop exit). In this case we might need to insert PHI nodes in
794 // order to preserve LCSSA form.
795 // We don't need to check this if we already know that we need to fix LCSSA
796 // form.
797 // TODO: For now we just recompute LCSSA for the outer loop in this case, but
798 // it should be possible to fix it in-place.
799 if (PreserveLCSSA && OuterL && CompletelyUnroll && !NeedToFixLCSSA)
800 NeedToFixLCSSA |= ::needToInsertPhisForLCSSA(OuterL, UnrolledLoopBlocks, LI);
801
Chandler Carruthaa7fa5e2014-01-23 11:23:19 +0000802 // If we have a pass and a DominatorTree we should re-simplify impacted loops
803 // to ensure subsequent analyses can rely on this form. We want to simplify
804 // at least one layer outside of the loop that was unrolled so that any
805 // changes to the parent loop exposed by the unrolling are considered.
Justin Bogner843fb202015-12-15 19:40:57 +0000806 if (DT) {
Chandler Carruthd84f7762014-01-28 01:25:38 +0000807 if (OuterL) {
Michael Zolotukhin2f507252016-08-08 19:02:15 +0000808 // OuterL includes all loops for which we can break loop-simplify, so
809 // it's sufficient to simplify only it (it'll recursively simplify inner
810 // loops too).
Michael Kuperstein461aa572017-01-23 23:45:42 +0000811 if (NeedToFixLCSSA) {
812 // LCSSA must be performed on the outermost affected loop. The unrolled
813 // loop's last loop latch is guaranteed to be in the outermost loop
Sanjoy Das388b0122017-09-22 01:47:41 +0000814 // after LoopInfo's been updated by LoopInfo::erase.
Michael Kuperstein461aa572017-01-23 23:45:42 +0000815 Loop *LatchLoop = LI->getLoopFor(Latches.back());
816 Loop *FixLCSSALoop = OuterL;
817 if (!FixLCSSALoop->contains(LatchLoop))
818 while (FixLCSSALoop->getParentLoop() != LatchLoop)
819 FixLCSSALoop = FixLCSSALoop->getParentLoop();
Dinesh Dwivedid266cb12014-05-29 06:47:23 +0000820
Michael Kuperstein461aa572017-01-23 23:45:42 +0000821 formLCSSARecursively(*FixLCSSALoop, *DT, LI, SE);
822 } else if (PreserveLCSSA) {
Michael Zolotukhin78760ee2015-12-09 18:20:28 +0000823 assert(OuterL->isLCSSAForm(*DT) &&
824 "Loops should be in LCSSA form after loop-unroll.");
Michael Kuperstein461aa572017-01-23 23:45:42 +0000825 }
826
827 // TODO: That potentially might be compile-time expensive. We should try
828 // to fix the loop-simplified form incrementally.
Alina Sbirleaf31eba62019-05-08 17:05:36 +0000829 simplifyLoop(OuterL, DT, LI, SE, AC, nullptr, PreserveLCSSA);
Michael Zolotukhin2f507252016-08-08 19:02:15 +0000830 } else {
831 // Simplify loops for which we might've broken loop-simplify form.
832 for (Loop *SubLoop : LoopsToSimplify)
Alina Sbirleaf31eba62019-05-08 17:05:36 +0000833 simplifyLoop(SubLoop, DT, LI, SE, AC, nullptr, PreserveLCSSA);
Chandler Carruthd84f7762014-01-28 01:25:38 +0000834 }
Chandler Carruthaa7fa5e2014-01-23 11:23:19 +0000835 }
836
Sanjoy Das3567d3d2017-09-27 21:45:19 +0000837 return CompletelyUnroll ? LoopUnrollResult::FullyUnrolled
838 : LoopUnrollResult::PartiallyUnrolled;
Dan Gohman3dc2d922008-05-14 00:24:14 +0000839}
Jingyue Wu0220df02015-02-01 02:27:45 +0000840
841/// Given an llvm.loop loop id metadata node, returns the loop hint metadata
842/// node with the given name (for example, "llvm.loop.unroll.count"). If no
843/// such metadata node exists, then nullptr is returned.
Jingyue Wu49a766e2015-02-02 20:41:11 +0000844MDNode *llvm::GetUnrollMetadata(MDNode *LoopID, StringRef Name) {
Jingyue Wu0220df02015-02-01 02:27:45 +0000845 // First operand should refer to the loop id itself.
846 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
Jingyue Wu49a766e2015-02-02 20:41:11 +0000847 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
Jingyue Wu0220df02015-02-01 02:27:45 +0000848
849 for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
Jingyue Wu49a766e2015-02-02 20:41:11 +0000850 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
Jingyue Wu0220df02015-02-01 02:27:45 +0000851 if (!MD)
852 continue;
853
Jingyue Wu49a766e2015-02-02 20:41:11 +0000854 MDString *S = dyn_cast<MDString>(MD->getOperand(0));
Jingyue Wu0220df02015-02-01 02:27:45 +0000855 if (!S)
856 continue;
857
858 if (Name.equals(S->getString()))
859 return MD;
860 }
861 return nullptr;
862}