blob: 29e7c5260f46174736f15460320cd9945af104e3 [file] [log] [blame]
Owen Andersonf3dd3e22006-05-26 21:11:53 +00001//===-- LCSSA.cpp - Convert loops into loop-closed SSA form ---------------===//
Owen Anderson8eca8912006-05-26 13:58:26 +00002//
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
Owen Anderson8eca8912006-05-26 13:58:26 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This pass transforms loops by placing phi nodes at the end of the loops for
10// all values that are live across the loop boundary. For example, it turns
11// the left into the right code:
Fangrui Songf78650a2018-07-30 19:41:25 +000012//
Owen Anderson8eca8912006-05-26 13:58:26 +000013// for (...) for (...)
Dan Gohmanb5650eb2007-05-11 21:10:54 +000014// if (c) if (c)
Owen Anderson8eca8912006-05-26 13:58:26 +000015// X1 = ... X1 = ...
16// else else
17// X2 = ... X2 = ...
18// X3 = phi(X1, X2) X3 = phi(X1, X2)
Dan Gohman2ad7e732008-06-03 00:57:21 +000019// ... = X3 + 4 X4 = phi(X3)
20// ... = X4 + 4
Owen Anderson8eca8912006-05-26 13:58:26 +000021//
22// This is still valid LLVM; the extra phi nodes are purely redundant, and will
Fangrui Songf78650a2018-07-30 19:41:25 +000023// be trivially eliminated by InstCombine. The major benefit of this
24// transformation is that it makes many other loop optimizations, such as
Owen Anderson8eca8912006-05-26 13:58:26 +000025// LoopUnswitching, simpler.
26//
27//===----------------------------------------------------------------------===//
28
Easwaran Ramane12c4872016-06-09 19:44:46 +000029#include "llvm/Transforms/Utils/LCSSA.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000030#include "llvm/ADT/STLExtras.h"
31#include "llvm/ADT/Statistic.h"
Chandler Carruth756c22c2014-02-10 19:39:35 +000032#include "llvm/Analysis/AliasAnalysis.h"
Chandler Carruthac072702016-02-19 03:12:14 +000033#include "llvm/Analysis/BasicAliasAnalysis.h"
Philip Reames37104d72019-04-22 17:13:43 +000034#include "llvm/Analysis/BranchProbabilityInfo.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000035#include "llvm/Analysis/GlobalsModRef.h"
Devang Patel4cd14132007-07-13 23:57:11 +000036#include "llvm/Analysis/LoopPass.h"
Alina Sbirlea4fd1f262019-04-23 20:59:44 +000037#include "llvm/Analysis/MemorySSA.h"
Devang Patel4cd14132007-07-13 23:57:11 +000038#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000039#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000040#include "llvm/IR/Constants.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000041#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000042#include "llvm/IR/Function.h"
43#include "llvm/IR/Instructions.h"
David Stenbergc9163852018-10-16 08:06:48 +000044#include "llvm/IR/IntrinsicInst.h"
Chandler Carruthaa0ab632014-03-04 12:09:19 +000045#include "llvm/IR/PredIteratorCache.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000046#include "llvm/Pass.h"
David Blaikiea373d182018-03-28 17:44:36 +000047#include "llvm/Transforms/Utils.h"
Alina Sbirlea4fd1f262019-04-23 20:59:44 +000048#include "llvm/Transforms/Utils/Local.h"
Chandler Carruth8765cf72014-01-25 04:07:24 +000049#include "llvm/Transforms/Utils/LoopUtils.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000050#include "llvm/Transforms/Utils/SSAUpdater.h"
Owen Anderson8eca8912006-05-26 13:58:26 +000051using namespace llvm;
52
Chandler Carruth964daaa2014-04-22 02:55:47 +000053#define DEBUG_TYPE "lcssa"
54
Chris Lattner45f966d2006-12-19 22:17:40 +000055STATISTIC(NumLCSSA, "Number of live out of a loop variables");
56
Igor Laevskyc3ccf5d2016-10-28 12:57:20 +000057#ifdef EXPENSIVE_CHECKS
58static bool VerifyLoopLCSSA = true;
59#else
60static bool VerifyLoopLCSSA = false;
61#endif
Zachary Turner8065f0b2017-12-01 00:53:10 +000062static cl::opt<bool, true>
63 VerifyLoopLCSSAFlag("verify-loop-lcssa", cl::location(VerifyLoopLCSSA),
64 cl::Hidden,
65 cl::desc("Verify loop lcssa form (time consuming)"));
Igor Laevskyc3ccf5d2016-10-28 12:57:20 +000066
Chandler Carruth8765cf72014-01-25 04:07:24 +000067/// Return true if the specified block is in the list.
Chris Lattner71d353d2009-10-11 02:53:37 +000068static bool isExitBlock(BasicBlock *BB,
Chandler Carruth8765cf72014-01-25 04:07:24 +000069 const SmallVectorImpl<BasicBlock *> &ExitBlocks) {
David Majnemer0d955d02016-08-11 22:21:41 +000070 return is_contained(ExitBlocks, BB);
Chris Lattner71d353d2009-10-11 02:53:37 +000071}
72
Michael Zolotukhina78937a2016-07-15 21:08:41 +000073/// For every instruction from the worklist, check to see if it has any uses
74/// that are outside the current loop. If so, insert LCSSA PHI nodes and
75/// rewrite the uses.
76bool llvm::formLCSSAForInstructions(SmallVectorImpl<Instruction *> &Worklist,
77 DominatorTree &DT, LoopInfo &LI) {
Chandler Carruth8765cf72014-01-25 04:07:24 +000078 SmallVector<Use *, 16> UsesToRewrite;
Michael Zolotukhin6bc56d52016-07-20 01:55:27 +000079 SmallSetVector<PHINode *, 16> PHIsToRemove;
Michael Zolotukhina78937a2016-07-15 21:08:41 +000080 PredIteratorCache PredCache;
81 bool Changed = false;
Chandler Carruth8765cf72014-01-25 04:07:24 +000082
Philip Reamesb1472ff2016-09-19 23:30:23 +000083 // Cache the Loop ExitBlocks across this loop. We expect to get a lot of
84 // instructions within the same loops, computing the exit blocks is
85 // expensive, and we're not mutating the loop structure.
86 SmallDenseMap<Loop*, SmallVector<BasicBlock *,1>> LoopExitBlocks;
87
Michael Zolotukhina78937a2016-07-15 21:08:41 +000088 while (!Worklist.empty()) {
89 UsesToRewrite.clear();
Andrew Kaylor123048d2015-12-18 18:12:35 +000090
Michael Zolotukhina78937a2016-07-15 21:08:41 +000091 Instruction *I = Worklist.pop_back_val();
Davide Italianoce161a72017-04-17 14:32:05 +000092 assert(!I->getType()->isTokenTy() && "Tokens shouldn't be in the worklist");
Michael Zolotukhina78937a2016-07-15 21:08:41 +000093 BasicBlock *InstBB = I->getParent();
94 Loop *L = LI.getLoopFor(InstBB);
Davide Italiano0b302272017-04-13 20:05:37 +000095 assert(L && "Instruction belongs to a BB that's not part of a loop");
Davide Italiano549078d2017-04-13 20:02:27 +000096 if (!LoopExitBlocks.count(L))
Philip Reamesb1472ff2016-09-19 23:30:23 +000097 L->getExitBlocks(LoopExitBlocks[L]);
98 assert(LoopExitBlocks.count(L));
99 const SmallVectorImpl<BasicBlock *> &ExitBlocks = LoopExitBlocks[L];
Chandler Carruth8765cf72014-01-25 04:07:24 +0000100
Michael Zolotukhina78937a2016-07-15 21:08:41 +0000101 if (ExitBlocks.empty())
Chandler Carruth8765cf72014-01-25 04:07:24 +0000102 continue;
103
Michael Zolotukhina78937a2016-07-15 21:08:41 +0000104 for (Use &U : I->uses()) {
105 Instruction *User = cast<Instruction>(U.getUser());
106 BasicBlock *UserBB = User->getParent();
Davide Italiano51299512017-04-13 20:01:30 +0000107 if (auto *PN = dyn_cast<PHINode>(User))
Michael Zolotukhina78937a2016-07-15 21:08:41 +0000108 UserBB = PN->getIncomingBlock(U);
Chris Lattner984d6e12006-10-31 18:56:48 +0000109
Michael Zolotukhina78937a2016-07-15 21:08:41 +0000110 if (InstBB != UserBB && !L->contains(UserBB))
111 UsesToRewrite.push_back(&U);
Dan Gohmanc146c7802009-11-09 18:28:24 +0000112 }
Cameron Zwarich0b8cdfb2011-03-15 07:41:25 +0000113
Michael Zolotukhina78937a2016-07-15 21:08:41 +0000114 // If there are no uses outside the loop, exit with no change.
115 if (UsesToRewrite.empty())
Chris Lattner5a2bc782006-08-02 00:06:09 +0000116 continue;
Michael Zolotukhina78937a2016-07-15 21:08:41 +0000117
118 ++NumLCSSA; // We are applying the transformation
119
120 // Invoke instructions are special in that their result value is not
121 // available along their unwind edge. The code below tests to see whether
122 // DomBB dominates the value, so adjust DomBB to the normal destination
123 // block, which is effectively where the value is first usable.
124 BasicBlock *DomBB = InstBB;
Davide Italiano51299512017-04-13 20:01:30 +0000125 if (auto *Inv = dyn_cast<InvokeInst>(I))
Michael Zolotukhina78937a2016-07-15 21:08:41 +0000126 DomBB = Inv->getNormalDest();
127
128 DomTreeNode *DomNode = DT.getNode(DomBB);
129
130 SmallVector<PHINode *, 16> AddedPHIs;
131 SmallVector<PHINode *, 8> PostProcessPHIs;
132
Michael Zolotukhin6bc56d52016-07-20 01:55:27 +0000133 SmallVector<PHINode *, 4> InsertedPHIs;
134 SSAUpdater SSAUpdate(&InsertedPHIs);
Michael Zolotukhina78937a2016-07-15 21:08:41 +0000135 SSAUpdate.Initialize(I->getType(), I->getName());
136
137 // Insert the LCSSA phi's into all of the exit blocks dominated by the
138 // value, and add them to the Phi's map.
139 for (BasicBlock *ExitBB : ExitBlocks) {
140 if (!DT.dominates(DomNode, DT.getNode(ExitBB)))
141 continue;
142
143 // If we already inserted something for this BB, don't reprocess it.
144 if (SSAUpdate.HasValueForBlock(ExitBB))
145 continue;
146
147 PHINode *PN = PHINode::Create(I->getType(), PredCache.size(ExitBB),
148 I->getName() + ".lcssa", &ExitBB->front());
Anastasis Grammenosac3f8022018-07-31 14:54:52 +0000149 // Get the debug location from the original instruction.
150 PN->setDebugLoc(I->getDebugLoc());
Michael Zolotukhina78937a2016-07-15 21:08:41 +0000151 // Add inputs from inside the loop for this PHI.
152 for (BasicBlock *Pred : PredCache.get(ExitBB)) {
153 PN->addIncoming(I, Pred);
154
155 // If the exit block has a predecessor not within the loop, arrange for
156 // the incoming value use corresponding to that predecessor to be
157 // rewritten in terms of a different LCSSA PHI.
158 if (!L->contains(Pred))
159 UsesToRewrite.push_back(
160 &PN->getOperandUse(PN->getOperandNumForIncomingValue(
161 PN->getNumIncomingValues() - 1)));
162 }
163
164 AddedPHIs.push_back(PN);
165
166 // Remember that this phi makes the value alive in this block.
167 SSAUpdate.AddAvailableValue(ExitBB, PN);
168
169 // LoopSimplify might fail to simplify some loops (e.g. when indirect
170 // branches are involved). In such situations, it might happen that an
171 // exit for Loop L1 is the header of a disjoint Loop L2. Thus, when we
172 // create PHIs in such an exit block, we are also inserting PHIs into L2's
173 // header. This could break LCSSA form for L2 because these inserted PHIs
174 // can also have uses outside of L2. Remember all PHIs in such situation
175 // as to revisit than later on. FIXME: Remove this if indirectbr support
176 // into LoopSimplify gets improved.
177 if (auto *OtherLoop = LI.getLoopFor(ExitBB))
178 if (!L->contains(OtherLoop))
179 PostProcessPHIs.push_back(PN);
Owen Andersoncd76fa02006-06-01 06:05:47 +0000180 }
Chandler Carruth8765cf72014-01-25 04:07:24 +0000181
Michael Zolotukhina78937a2016-07-15 21:08:41 +0000182 // Rewrite all uses outside the loop in terms of the new PHIs we just
183 // inserted.
184 for (Use *UseToRewrite : UsesToRewrite) {
185 // If this use is in an exit block, rewrite to use the newly inserted PHI.
186 // This is required for correctness because SSAUpdate doesn't handle uses
187 // in the same block. It assumes the PHI we inserted is at the end of the
188 // block.
189 Instruction *User = cast<Instruction>(UseToRewrite->getUser());
190 BasicBlock *UserBB = User->getParent();
Davide Italiano51299512017-04-13 20:01:30 +0000191 if (auto *PN = dyn_cast<PHINode>(User))
Michael Zolotukhina78937a2016-07-15 21:08:41 +0000192 UserBB = PN->getIncomingBlock(*UseToRewrite);
193
194 if (isa<PHINode>(UserBB->begin()) && isExitBlock(UserBB, ExitBlocks)) {
195 // Tell the VHs that the uses changed. This updates SCEV's caches.
196 if (UseToRewrite->get()->hasValueHandle())
197 ValueHandleBase::ValueIsRAUWd(*UseToRewrite, &UserBB->front());
198 UseToRewrite->set(&UserBB->front());
199 continue;
200 }
201
Florian Hahndd2ef0a2019-02-02 15:26:05 +0000202 // If we added a single PHI, it must dominate all uses and we can directly
203 // rename it.
204 if (AddedPHIs.size() == 1) {
205 // Tell the VHs that the uses changed. This updates SCEV's caches.
206 // We might call ValueIsRAUWd multiple times for the same value.
207 if (UseToRewrite->get()->hasValueHandle())
208 ValueHandleBase::ValueIsRAUWd(*UseToRewrite, AddedPHIs[0]);
209 UseToRewrite->set(AddedPHIs[0]);
210 continue;
211 }
212
Michael Zolotukhina78937a2016-07-15 21:08:41 +0000213 // Otherwise, do full PHI insertion.
214 SSAUpdate.RewriteUse(*UseToRewrite);
Rong Xu63f970e2016-08-10 17:49:11 +0000215 }
Michael Zolotukhin6bc56d52016-07-20 01:55:27 +0000216
David Stenbergc9163852018-10-16 08:06:48 +0000217 SmallVector<DbgValueInst *, 4> DbgValues;
218 llvm::findDbgValues(DbgValues, I);
219
220 // Update pre-existing debug value uses that reside outside the loop.
221 auto &Ctx = I->getContext();
222 for (auto DVI : DbgValues) {
223 BasicBlock *UserBB = DVI->getParent();
224 if (InstBB == UserBB || L->contains(UserBB))
225 continue;
Florian Hahndd2ef0a2019-02-02 15:26:05 +0000226 // We currently only handle debug values residing in blocks that were
227 // traversed while rewriting the uses. If we inserted just a single PHI,
228 // we will handle all relevant debug values.
229 Value *V = AddedPHIs.size() == 1 ? AddedPHIs[0]
230 : SSAUpdate.FindValueForBlock(UserBB);
231 if (V)
David Stenbergc9163852018-10-16 08:06:48 +0000232 DVI->setOperand(0, MetadataAsValue::get(Ctx, ValueAsMetadata::get(V)));
233 }
234
Rong Xu63f970e2016-08-10 17:49:11 +0000235 // SSAUpdater might have inserted phi-nodes inside other loops. We'll need
236 // to post-process them to keep LCSSA form.
237 for (PHINode *InsertedPN : InsertedPHIs) {
238 if (auto *OtherLoop = LI.getLoopFor(InsertedPN->getParent()))
239 if (!L->contains(OtherLoop))
240 PostProcessPHIs.push_back(InsertedPN);
Michael Zolotukhina78937a2016-07-15 21:08:41 +0000241 }
242
243 // Post process PHI instructions that were inserted into another disjoint
244 // loop and update their exits properly.
Davide Italianoee654bf2017-04-17 00:02:45 +0000245 for (auto *PostProcessPN : PostProcessPHIs)
246 if (!PostProcessPN->use_empty())
247 Worklist.push_back(PostProcessPN);
Michael Zolotukhina78937a2016-07-15 21:08:41 +0000248
Michael Zolotukhin6bc56d52016-07-20 01:55:27 +0000249 // Keep track of PHI nodes that we want to remove because they did not have
Matt Davis523c6562018-02-23 17:38:27 +0000250 // any uses rewritten. If the new PHI is used, store it so that we can
251 // try to propagate dbg.value intrinsics to it.
252 SmallVector<PHINode *, 2> NeedDbgValues;
Michael Zolotukhina78937a2016-07-15 21:08:41 +0000253 for (PHINode *PN : AddedPHIs)
254 if (PN->use_empty())
Michael Zolotukhin6bc56d52016-07-20 01:55:27 +0000255 PHIsToRemove.insert(PN);
Matt Davis523c6562018-02-23 17:38:27 +0000256 else
257 NeedDbgValues.push_back(PN);
258 insertDebugValuesForPHIs(InstBB, NeedDbgValues);
Michael Zolotukhina78937a2016-07-15 21:08:41 +0000259 Changed = true;
Chris Lattner5a2bc782006-08-02 00:06:09 +0000260 }
Bjorn Pettersson51cebc92018-05-08 06:59:47 +0000261 // Remove PHI nodes that did not have any uses rewritten. We need to redo the
262 // use_empty() check here, because even if the PHI node wasn't used when added
263 // to PHIsToRemove, later added PHI nodes can be using it. This cleanup is
264 // not guaranteed to handle trees/cycles of PHI nodes that only are used by
265 // each other. Such situations has only been noticed when the input IR
266 // contains unreachable code, and leaving some extra redundant PHI nodes in
267 // such situations is considered a minor problem.
268 for (PHINode *PN : PHIsToRemove)
269 if (PN->use_empty())
270 PN->eraseFromParent();
Michael Zolotukhina78937a2016-07-15 21:08:41 +0000271 return Changed;
Owen Andersondad8c572006-05-31 20:55:06 +0000272}
Chris Lattner5a2bc782006-08-02 00:06:09 +0000273
Davide Italianoaf36d022017-04-13 20:36:59 +0000274// Compute the set of BasicBlocks in the loop `L` dominating at least one exit.
275static void computeBlocksDominatingExits(
276 Loop &L, DominatorTree &DT, SmallVector<BasicBlock *, 8> &ExitBlocks,
Davide Italianodd37c672017-04-16 21:07:04 +0000277 SmallSetVector<BasicBlock *, 8> &BlocksDominatingExits) {
Davide Italianoaf36d022017-04-13 20:36:59 +0000278 SmallVector<BasicBlock *, 8> BBWorklist;
279
280 // We start from the exit blocks, as every block trivially dominates itself
281 // (not strictly).
282 for (BasicBlock *BB : ExitBlocks)
283 BBWorklist.push_back(BB);
284
285 while (!BBWorklist.empty()) {
286 BasicBlock *BB = BBWorklist.pop_back_val();
287
288 // Check if this is a loop header. If this is the case, we're done.
289 if (L.getHeader() == BB)
290 continue;
291
292 // Otherwise, add its immediate predecessor in the dominator tree to the
293 // worklist, unless we visited it already.
294 BasicBlock *IDomBB = DT.getNode(BB)->getIDom()->getBlock();
295
296 // Exit blocks can have an immediate dominator not beloinging to the
297 // loop. For an exit block to be immediately dominated by another block
298 // outside the loop, it implies not all paths from that dominator, to the
299 // exit block, go through the loop.
300 // Example:
301 //
302 // |---- A
303 // | |
304 // | B<--
305 // | | |
306 // |---> C --
307 // |
308 // D
309 //
310 // C is the exit block of the loop and it's immediately dominated by A,
311 // which doesn't belong to the loop.
312 if (!L.contains(IDomBB))
313 continue;
314
Davide Italianodd37c672017-04-16 21:07:04 +0000315 if (BlocksDominatingExits.insert(IDomBB))
Davide Italianoaf36d022017-04-13 20:36:59 +0000316 BBWorklist.push_back(IDomBB);
317 }
Chandler Carruth8765cf72014-01-25 04:07:24 +0000318}
319
Bruno Cardoso Lopesbad65c32014-12-22 22:35:46 +0000320bool llvm::formLCSSA(Loop &L, DominatorTree &DT, LoopInfo *LI,
321 ScalarEvolution *SE) {
Chandler Carruth8765cf72014-01-25 04:07:24 +0000322 bool Changed = false;
323
Florian Hahn509b48a2019-02-02 14:42:27 +0000324#ifdef EXPENSIVE_CHECKS
325 // Verify all sub-loops are in LCSSA form already.
326 for (Loop *SubLoop: L)
327 assert(SubLoop->isRecursivelyLCSSAForm(DT, *LI) && "Subloop not in LCSSA!");
328#endif
329
Chandler Carruth8765cf72014-01-25 04:07:24 +0000330 SmallVector<BasicBlock *, 8> ExitBlocks;
331 L.getExitBlocks(ExitBlocks);
Chandler Carruth8765cf72014-01-25 04:07:24 +0000332 if (ExitBlocks.empty())
333 return false;
334
Davide Italianodd37c672017-04-16 21:07:04 +0000335 SmallSetVector<BasicBlock *, 8> BlocksDominatingExits;
Davide Italianoaf36d022017-04-13 20:36:59 +0000336
337 // We want to avoid use-scanning leveraging dominance informations.
338 // If a block doesn't dominate any of the loop exits, the none of the values
339 // defined in the loop can be used outside.
340 // We compute the set of blocks fullfilling the conditions in advance
341 // walking the dominator tree upwards until we hit a loop header.
342 computeBlocksDominatingExits(L, DT, ExitBlocks, BlocksDominatingExits);
343
Michael Zolotukhina78937a2016-07-15 21:08:41 +0000344 SmallVector<Instruction *, 8> Worklist;
Chandler Carruth8765cf72014-01-25 04:07:24 +0000345
346 // Look at all the instructions in the loop, checking to see if they have uses
Michael Zolotukhina78937a2016-07-15 21:08:41 +0000347 // outside the loop. If so, put them into the worklist to rewrite those uses.
Davide Italianoaf36d022017-04-13 20:36:59 +0000348 for (BasicBlock *BB : BlocksDominatingExits) {
Florian Hahnbe7cbe32019-01-18 17:36:22 +0000349 // Skip blocks that are part of any sub-loops, they must be in LCSSA
350 // already.
351 if (LI->getLoopFor(BB) != &L)
352 continue;
Sanjoy Das331521c2015-10-25 19:08:32 +0000353 for (Instruction &I : *BB) {
Chandler Carruth8765cf72014-01-25 04:07:24 +0000354 // Reject two common cases fast: instructions with no uses (like stores)
355 // and instructions with one use that is in the same block as this.
Sanjoy Das331521c2015-10-25 19:08:32 +0000356 if (I.use_empty() ||
357 (I.hasOneUse() && I.user_back()->getParent() == BB &&
358 !isa<PHINode>(I.user_back())))
Chandler Carruth8765cf72014-01-25 04:07:24 +0000359 continue;
360
Davide Italianoce161a72017-04-17 14:32:05 +0000361 // Tokens cannot be used in PHI nodes, so we skip over them.
362 // We can run into tokens which are live out of a loop with catchswitch
363 // instructions in Windows EH if the catchswitch has one catchpad which
364 // is inside the loop and another which is not.
365 if (I.getType()->isTokenTy())
366 continue;
367
Michael Zolotukhina78937a2016-07-15 21:08:41 +0000368 Worklist.push_back(&I);
Chandler Carruth8765cf72014-01-25 04:07:24 +0000369 }
370 }
Michael Zolotukhina78937a2016-07-15 21:08:41 +0000371 Changed = formLCSSAForInstructions(Worklist, DT, *LI);
Chandler Carruth8765cf72014-01-25 04:07:24 +0000372
373 // If we modified the code, remove any caches about the loop from SCEV to
374 // avoid dangling entries.
375 // FIXME: This is a big hammer, can we clear the cache more selectively?
376 if (SE && Changed)
377 SE->forgetLoop(&L);
378
379 assert(L.isLCSSAForm(DT));
380
381 return Changed;
382}
383
Chandler Carruthd84f7762014-01-28 01:25:38 +0000384/// Process a loop nest depth first.
Bruno Cardoso Lopesbad65c32014-12-22 22:35:46 +0000385bool llvm::formLCSSARecursively(Loop &L, DominatorTree &DT, LoopInfo *LI,
Chandler Carruthd84f7762014-01-28 01:25:38 +0000386 ScalarEvolution *SE) {
387 bool Changed = false;
388
389 // Recurse depth-first through inner loops.
Sanjoy Das15c4c462015-10-25 19:27:17 +0000390 for (Loop *SubLoop : L.getSubLoops())
391 Changed |= formLCSSARecursively(*SubLoop, DT, LI, SE);
Chandler Carruthd84f7762014-01-28 01:25:38 +0000392
Bruno Cardoso Lopesbad65c32014-12-22 22:35:46 +0000393 Changed |= formLCSSA(L, DT, LI, SE);
Chandler Carruthd84f7762014-01-28 01:25:38 +0000394 return Changed;
395}
396
Easwaran Ramane12c4872016-06-09 19:44:46 +0000397/// Process all loops in the function, inner-most out.
398static bool formLCSSAOnAllLoops(LoopInfo *LI, DominatorTree &DT,
399 ScalarEvolution *SE) {
400 bool Changed = false;
401 for (auto &L : *LI)
402 Changed |= formLCSSARecursively(*L, DT, LI, SE);
403 return Changed;
404}
405
Chandler Carruth8765cf72014-01-25 04:07:24 +0000406namespace {
Easwaran Ramane12c4872016-06-09 19:44:46 +0000407struct LCSSAWrapperPass : public FunctionPass {
Chandler Carruth8765cf72014-01-25 04:07:24 +0000408 static char ID; // Pass identification, replacement for typeid
Easwaran Ramane12c4872016-06-09 19:44:46 +0000409 LCSSAWrapperPass() : FunctionPass(ID) {
410 initializeLCSSAWrapperPassPass(*PassRegistry::getPassRegistry());
Chandler Carruth8765cf72014-01-25 04:07:24 +0000411 }
412
413 // Cached analysis information for the current function.
414 DominatorTree *DT;
415 LoopInfo *LI;
416 ScalarEvolution *SE;
417
Craig Topper3e4c6972014-03-05 09:10:37 +0000418 bool runOnFunction(Function &F) override;
Michael Zolotukhinff5ce632016-07-27 23:35:53 +0000419 void verifyAnalysis() const override {
Igor Laevskyc3ccf5d2016-10-28 12:57:20 +0000420 // This check is very expensive. On the loop intensive compiles it may cause
421 // up to 10x slowdown. Currently it's disabled by default. LPPassManager
422 // always does limited form of the LCSSA verification. Similar reasoning
423 // was used for the LoopInfo verifier.
424 if (VerifyLoopLCSSA) {
425 assert(all_of(*LI,
426 [&](Loop *L) {
427 return L->isRecursivelyLCSSAForm(*DT, *LI);
428 }) &&
429 "LCSSA form is broken!");
430 }
Michael Zolotukhinff5ce632016-07-27 23:35:53 +0000431 };
Chandler Carruth8765cf72014-01-25 04:07:24 +0000432
433 /// This transformation requires natural loop information & requires that
434 /// loop preheaders be inserted into the CFG. It maintains both of these,
435 /// as well as the CFG. It also requires dominator information.
Craig Topper3e4c6972014-03-05 09:10:37 +0000436 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth8765cf72014-01-25 04:07:24 +0000437 AU.setPreservesCFG();
438
439 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000440 AU.addRequired<LoopInfoWrapperPass>();
Chandler Carruth8765cf72014-01-25 04:07:24 +0000441 AU.addPreservedID(LoopSimplifyID);
Chandler Carruth7b560d42015-09-09 17:55:00 +0000442 AU.addPreserved<AAResultsWrapperPass>();
Chandler Carruthac072702016-02-19 03:12:14 +0000443 AU.addPreserved<BasicAAWrapperPass>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000444 AU.addPreserved<GlobalsAAWrapperPass>();
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000445 AU.addPreserved<ScalarEvolutionWrapperPass>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000446 AU.addPreserved<SCEVAAWrapperPass>();
Philip Reames37104d72019-04-22 17:13:43 +0000447 AU.addPreserved<BranchProbabilityInfoWrapperPass>();
Alina Sbirlea4fd1f262019-04-23 20:59:44 +0000448 AU.addPreserved<MemorySSAWrapperPass>();
Igor Laevskyc3ccf5d2016-10-28 12:57:20 +0000449
450 // This is needed to perform LCSSA verification inside LPPassManager
451 AU.addRequired<LCSSAVerificationPass>();
452 AU.addPreserved<LCSSAVerificationPass>();
Chandler Carruth8765cf72014-01-25 04:07:24 +0000453 }
Chandler Carruth8765cf72014-01-25 04:07:24 +0000454};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000455}
Chandler Carruth8765cf72014-01-25 04:07:24 +0000456
Easwaran Ramane12c4872016-06-09 19:44:46 +0000457char LCSSAWrapperPass::ID = 0;
458INITIALIZE_PASS_BEGIN(LCSSAWrapperPass, "lcssa", "Loop-Closed SSA Form Pass",
459 false, false)
Chandler Carruth8765cf72014-01-25 04:07:24 +0000460INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000461INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Igor Laevskyc3ccf5d2016-10-28 12:57:20 +0000462INITIALIZE_PASS_DEPENDENCY(LCSSAVerificationPass)
Easwaran Ramane12c4872016-06-09 19:44:46 +0000463INITIALIZE_PASS_END(LCSSAWrapperPass, "lcssa", "Loop-Closed SSA Form Pass",
464 false, false)
Chandler Carruth8765cf72014-01-25 04:07:24 +0000465
Easwaran Ramane12c4872016-06-09 19:44:46 +0000466Pass *llvm::createLCSSAPass() { return new LCSSAWrapperPass(); }
467char &llvm::LCSSAID = LCSSAWrapperPass::ID;
Chandler Carruth8765cf72014-01-25 04:07:24 +0000468
Easwaran Ramane12c4872016-06-09 19:44:46 +0000469/// Transform \p F into loop-closed SSA form.
470bool LCSSAWrapperPass::runOnFunction(Function &F) {
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000471 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Chandler Carruth8765cf72014-01-25 04:07:24 +0000472 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000473 auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
474 SE = SEWP ? &SEWP->getSE() : nullptr;
Chandler Carruth8765cf72014-01-25 04:07:24 +0000475
Easwaran Ramane12c4872016-06-09 19:44:46 +0000476 return formLCSSAOnAllLoops(LI, *DT, SE);
Chandler Carruth8765cf72014-01-25 04:07:24 +0000477}
478
Sean Silva36e0d012016-08-09 00:28:15 +0000479PreservedAnalyses LCSSAPass::run(Function &F, FunctionAnalysisManager &AM) {
Easwaran Ramane12c4872016-06-09 19:44:46 +0000480 auto &LI = AM.getResult<LoopAnalysis>(F);
481 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
482 auto *SE = AM.getCachedResult<ScalarEvolutionAnalysis>(F);
483 if (!formLCSSAOnAllLoops(&LI, DT, SE))
484 return PreservedAnalyses::all();
485
Easwaran Ramane12c4872016-06-09 19:44:46 +0000486 PreservedAnalyses PA;
Chandler Carruthca68a3e2017-01-15 06:32:49 +0000487 PA.preserveSet<CFGAnalyses>();
Easwaran Ramane12c4872016-06-09 19:44:46 +0000488 PA.preserve<BasicAA>();
489 PA.preserve<GlobalsAA>();
490 PA.preserve<SCEVAA>();
491 PA.preserve<ScalarEvolutionAnalysis>();
Philip Reames37104d72019-04-22 17:13:43 +0000492 // BPI maps terminators to probabilities, since we don't modify the CFG, no
493 // updates are needed to preserve it.
494 PA.preserve<BranchProbabilityAnalysis>();
Alina Sbirlea4fd1f262019-04-23 20:59:44 +0000495 PA.preserve<MemorySSAAnalysis>();
Easwaran Ramane12c4872016-06-09 19:44:46 +0000496 return PA;
497}