1//===- LoopUnrollAndJam.cpp - Loop unroll and jam pass --------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This pass implements an unroll and jam pass. Most of the work is done by
10// Utils/UnrollLoopAndJam.cpp.
11//===----------------------------------------------------------------------===//
12
13#include "llvm/Transforms/Scalar/LoopUnrollAndJamPass.h"
14#include "llvm/ADT/ArrayRef.h"
15#include "llvm/ADT/PriorityWorklist.h"
16#include "llvm/ADT/SmallPtrSet.h"
17#include "llvm/ADT/StringRef.h"
18#include "llvm/Analysis/AssumptionCache.h"
19#include "llvm/Analysis/CodeMetrics.h"
20#include "llvm/Analysis/DependenceAnalysis.h"
21#include "llvm/Analysis/LoopAnalysisManager.h"
22#include "llvm/Analysis/LoopInfo.h"
23#include "llvm/Analysis/LoopNestAnalysis.h"
24#include "llvm/Analysis/LoopPass.h"
25#include "llvm/Analysis/OptimizationRemarkEmitter.h"
26#include "llvm/Analysis/ScalarEvolution.h"
27#include "llvm/Analysis/TargetTransformInfo.h"
28#include "llvm/IR/BasicBlock.h"
29#include "llvm/IR/Constants.h"
30#include "llvm/IR/Dominators.h"
31#include "llvm/IR/Function.h"
32#include "llvm/IR/Instructions.h"
33#include "llvm/IR/Metadata.h"
34#include "llvm/IR/PassManager.h"
35#include "llvm/Support/Casting.h"
36#include "llvm/Support/CommandLine.h"
37#include "llvm/Support/Debug.h"
38#include "llvm/Support/raw_ostream.h"
39#include "llvm/Transforms/Scalar/LoopPassManager.h"
40#include "llvm/Transforms/Utils/LoopPeel.h"
41#include "llvm/Transforms/Utils/LoopUtils.h"
42#include "llvm/Transforms/Utils/UnrollLoop.h"
43#include <cassert>
44#include <cstdint>
45
46namespace llvm {
47class Instruction;
48class Value;
49} // namespace llvm
50
51using namespace llvm;
52
53#define DEBUG_TYPE "loop-unroll-and-jam"
54
55/// @{
56/// Metadata attribute names
57static const char *const LLVMLoopUnrollAndJamFollowupAll =
58 "llvm.loop.unroll_and_jam.followup_all";
59static const char *const LLVMLoopUnrollAndJamFollowupInner =
60 "llvm.loop.unroll_and_jam.followup_inner";
61static const char *const LLVMLoopUnrollAndJamFollowupOuter =
62 "llvm.loop.unroll_and_jam.followup_outer";
63static const char *const LLVMLoopUnrollAndJamFollowupRemainderInner =
64 "llvm.loop.unroll_and_jam.followup_remainder_inner";
65static const char *const LLVMLoopUnrollAndJamFollowupRemainderOuter =
66 "llvm.loop.unroll_and_jam.followup_remainder_outer";
67/// @}
68
69static cl::opt<bool>
70 AllowUnrollAndJam("allow-unroll-and-jam", cl::Hidden,
71 cl::desc("Allows loops to be unroll-and-jammed."));
72
73static cl::opt<unsigned> UnrollAndJamCount(
74 "unroll-and-jam-count", cl::Hidden,
75 cl::desc("Use this unroll count for all loops including those with "
76 "unroll_and_jam_count pragma values, for testing purposes"));
77
78static cl::opt<unsigned> UnrollAndJamThreshold(
79 "unroll-and-jam-threshold", cl::init(Val: 60), cl::Hidden,
80 cl::desc("Threshold to use for inner loop when doing unroll and jam."));
81
82static cl::opt<unsigned> PragmaUnrollAndJamThreshold(
83 "pragma-unroll-and-jam-threshold", cl::init(Val: 1024), cl::Hidden,
84 cl::desc("Unrolled size limit for loops with an unroll_and_jam(full) or "
85 "unroll_count pragma."));
86
87// Returns true if the loop has any metadata starting with Prefix. For example a
88// Prefix of "llvm.loop.unroll." returns true if we have any unroll metadata.
89static bool hasAnyUnrollPragma(const Loop *L, StringRef Prefix) {
90 if (MDNode *LoopID = L->getLoopID()) {
91 // First operand should refer to the loop id itself.
92 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
93 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
94
95 for (unsigned I = 1, E = LoopID->getNumOperands(); I < E; ++I) {
96 MDNode *MD = dyn_cast<MDNode>(Val: LoopID->getOperand(I));
97 if (!MD)
98 continue;
99
100 MDString *S = dyn_cast<MDString>(Val: MD->getOperand(I: 0));
101 if (!S)
102 continue;
103
104 if (S->getString().starts_with(Prefix))
105 return true;
106 }
107 }
108 return false;
109}
110
111// Returns true if the loop has an unroll_and_jam(enable) pragma.
112static bool hasUnrollAndJamEnablePragma(const Loop *L) {
113 return getUnrollMetadataForLoop(L, Name: "llvm.loop.unroll_and_jam.enable");
114}
115
116// If loop has an unroll_and_jam_count pragma return the (necessarily
117// positive) value from the pragma. Otherwise return 0.
118static unsigned unrollAndJamCountPragmaValue(const Loop *L) {
119 MDNode *MD = getUnrollMetadataForLoop(L, Name: "llvm.loop.unroll_and_jam.count");
120 if (MD) {
121 assert(MD->getNumOperands() == 2 &&
122 "Unroll count hint metadata should have two operands.");
123 unsigned Count =
124 mdconst::extract<ConstantInt>(MD: MD->getOperand(I: 1))->getZExtValue();
125 assert(Count >= 1 && "Unroll count must be positive.");
126 return Count;
127 }
128 return 0;
129}
130
131// Returns loop size estimation for an unrolled-and-jammed loop with the given
132// unroll count.
133static uint64_t
134getUnrollAndJammedLoopSize(unsigned LoopSize,
135 const TargetTransformInfo::UnrollingPreferences &UP,
136 unsigned Count) {
137 assert(LoopSize >= UP.BEInsns && "LoopSize should not be less than BEInsns!");
138 return static_cast<uint64_t>(LoopSize - UP.BEInsns) * Count + UP.BEInsns;
139}
140
141// Calculates unroll and jam count.
142static unsigned computeUnrollAndJamCount(
143 Loop *L, Loop *SubLoop, const TargetTransformInfo &TTI, DominatorTree &DT,
144 LoopInfo *LI, AssumptionCache *AC, ScalarEvolution &SE,
145 const SmallPtrSetImpl<const Value *> &EphValues,
146 OptimizationRemarkEmitter *ORE, unsigned OuterTripCount,
147 unsigned OuterTripMultiple, const UnrollCostEstimator &OuterUCE,
148 unsigned InnerTripCount, unsigned InnerLoopSize,
149 bool &IsExplicitUnrollAndJam, TargetTransformInfo::UnrollingPreferences &UP,
150 TargetTransformInfo::PeelingPreferences &PP) {
151 unsigned OuterLoopSize = OuterUCE.getRolledLoopSize();
152 IsExplicitUnrollAndJam = false;
153
154 // Use computeUnrollCount from the loop unroller to get a count for
155 // unrolling the outer loop. This uses UP.Threshold / UP.PartialThreshold /
156 // UP.MaxCount to come up with sensible loop values.
157 // We have already checked that the loop has no unroll.* pragmas.
158 unsigned Count =
159 computeUnrollCount(L, TTI, DT, LI, AC, SE, EphValues, ORE, TripCount: OuterTripCount,
160 /*MaxTripCount*/ 0, /*MaxOrZero*/ false,
161 TripMultiple: OuterTripMultiple, UCE: OuterUCE, UP, PP);
162
163 // Override with any explicit count from the "unroll-and-jam-count" option.
164 bool UserUnrollCount = UnrollAndJamCount.getNumOccurrences() > 0;
165 if (UserUnrollCount) {
166 Count = UnrollAndJamCount;
167 UP.Force = true;
168 if (UP.AllowRemainder &&
169 getUnrollAndJammedLoopSize(LoopSize: OuterLoopSize, UP, Count) < UP.Threshold &&
170 getUnrollAndJammedLoopSize(LoopSize: InnerLoopSize, UP, Count) <
171 UP.UnrollAndJamInnerLoopThreshold) {
172 IsExplicitUnrollAndJam = true;
173 return Count;
174 }
175 }
176
177 // Check for unroll_and_jam pragmas
178 unsigned PragmaCount = unrollAndJamCountPragmaValue(L);
179 if (PragmaCount > 0) {
180 Count = PragmaCount;
181 UP.Runtime = true;
182 UP.Force = true;
183 if ((UP.AllowRemainder || (OuterTripMultiple % PragmaCount == 0)) &&
184 getUnrollAndJammedLoopSize(LoopSize: OuterLoopSize, UP, Count) < UP.Threshold &&
185 getUnrollAndJammedLoopSize(LoopSize: InnerLoopSize, UP, Count) <
186 UP.UnrollAndJamInnerLoopThreshold) {
187 IsExplicitUnrollAndJam = true;
188 return Count;
189 }
190 }
191
192 bool PragmaEnableUnroll = hasUnrollAndJamEnablePragma(L);
193 bool ExplicitUnrollAndJamCount = PragmaCount > 0 || UserUnrollCount;
194 bool ExplicitUnrollAndJam = PragmaEnableUnroll || ExplicitUnrollAndJamCount;
195
196 // If the loop has an unrolling pragma, we want to be more aggressive with
197 // unrolling limits.
198 if (ExplicitUnrollAndJam)
199 UP.UnrollAndJamInnerLoopThreshold = PragmaUnrollAndJamThreshold;
200
201 if (!UP.AllowRemainder &&
202 getUnrollAndJammedLoopSize(LoopSize: InnerLoopSize, UP, Count) >=
203 UP.UnrollAndJamInnerLoopThreshold) {
204 LLVM_DEBUG(dbgs() << "Won't unroll-and-jam; can't create remainder and "
205 "inner loop too large\n");
206 return 0;
207 }
208
209 // We have a sensible limit for the outer loop, now adjust it for the inner
210 // loop and UP.UnrollAndJamInnerLoopThreshold. If the outer limit was set
211 // explicitly, we want to stick to it.
212 if (!ExplicitUnrollAndJamCount && UP.AllowRemainder) {
213 while (Count != 0 && getUnrollAndJammedLoopSize(LoopSize: InnerLoopSize, UP, Count) >=
214 UP.UnrollAndJamInnerLoopThreshold)
215 Count--;
216 }
217
218 // If we are explicitly unroll and jamming, we are done. Otherwise there are a
219 // number of extra performance heuristics to check.
220 if (ExplicitUnrollAndJam) {
221 IsExplicitUnrollAndJam = true;
222 return Count;
223 }
224
225 // If the inner loop count is known and small, leave the entire loop nest to
226 // be the unroller
227 if (InnerTripCount && InnerLoopSize * InnerTripCount < UP.Threshold) {
228 LLVM_DEBUG(dbgs() << "Won't unroll-and-jam; small inner loop count is "
229 "being left for the unroller\n");
230 return 0;
231 }
232
233 // Check for situations where UnJ is likely to be unprofitable. Including
234 // subloops with more than 1 block.
235 if (SubLoop->getBlocks().size() != 1) {
236 LLVM_DEBUG(
237 dbgs() << "Won't unroll-and-jam; More than one inner loop block\n");
238 return 0;
239 }
240
241 // Limit to loops where there is something to gain from unrolling and
242 // jamming the loop. In this case, look for loads that are invariant in the
243 // outer loop and can become shared.
244 unsigned NumInvariant = 0;
245 for (BasicBlock *BB : SubLoop->getBlocks()) {
246 for (Instruction &I : *BB) {
247 if (auto *Ld = dyn_cast<LoadInst>(Val: &I)) {
248 Value *V = Ld->getPointerOperand();
249 const SCEV *LSCEV = SE.getSCEVAtScope(V, L);
250 if (SE.isLoopInvariant(S: LSCEV, L))
251 NumInvariant++;
252 }
253 }
254 }
255 if (NumInvariant == 0) {
256 LLVM_DEBUG(dbgs() << "Won't unroll-and-jam; No loop invariant loads\n");
257 return 0;
258 }
259
260 return Count;
261}
262
263static LoopUnrollResult
264tryToUnrollAndJamLoop(Loop *L, DominatorTree &DT, LoopInfo *LI,
265 ScalarEvolution &SE, const TargetTransformInfo &TTI,
266 AssumptionCache &AC, DependenceInfo &DI,
267 OptimizationRemarkEmitter &ORE, int OptLevel) {
268 TargetTransformInfo::UnrollingPreferences UP = gatherUnrollingPreferences(
269 L, SE, TTI, BFI: nullptr, PSI: nullptr, ORE, OptLevel, UserThreshold: std::nullopt, UserAllowPartial: std::nullopt,
270 UserRuntime: std::nullopt, UserUpperBound: std::nullopt, UserFullUnrollMaxCount: std::nullopt);
271 TargetTransformInfo::PeelingPreferences PP =
272 gatherPeelingPreferences(L, SE, TTI, UserAllowPeeling: std::nullopt, UserAllowProfileBasedPeeling: std::nullopt);
273
274 TransformationMode EnableMode = hasUnrollAndJamTransformation(L);
275 if (EnableMode & TM_Disable)
276 return LoopUnrollResult::Unmodified;
277 if (EnableMode & TM_ForcedByUser)
278 UP.UnrollAndJam = true;
279
280 if (AllowUnrollAndJam.getNumOccurrences() > 0)
281 UP.UnrollAndJam = AllowUnrollAndJam;
282 if (UnrollAndJamThreshold.getNumOccurrences() > 0)
283 UP.UnrollAndJamInnerLoopThreshold = UnrollAndJamThreshold;
284 // Exit early if unrolling is disabled.
285 if (!UP.UnrollAndJam || UP.UnrollAndJamInnerLoopThreshold == 0)
286 return LoopUnrollResult::Unmodified;
287
288 LLVM_DEBUG(dbgs() << "Loop Unroll and Jam: F["
289 << L->getHeader()->getParent()->getName() << "] Loop %"
290 << L->getHeader()->getName() << "\n");
291
292 // A loop with any unroll pragma (enabling/disabling/count/etc) is left for
293 // the unroller, so long as it does not explicitly have unroll_and_jam
294 // metadata. This means #pragma nounroll will disable unroll and jam as well
295 // as unrolling
296 if (hasAnyUnrollPragma(L, Prefix: "llvm.loop.unroll.") &&
297 !hasAnyUnrollPragma(L, Prefix: "llvm.loop.unroll_and_jam.")) {
298 LLVM_DEBUG(dbgs() << " Disabled due to pragma.\n");
299 return LoopUnrollResult::Unmodified;
300 }
301
302 if (!isSafeToUnrollAndJam(L, SE, DT, DI, LI&: *LI)) {
303 LLVM_DEBUG(dbgs() << " Disabled due to not being safe.\n");
304 return LoopUnrollResult::Unmodified;
305 }
306
307 // Approximate the loop size and collect useful info
308 SmallPtrSet<const Value *, 32> EphValues;
309 CodeMetrics::collectEphemeralValues(L, AC: &AC, EphValues);
310 Loop *SubLoop = L->getSubLoops()[0];
311 UnrollCostEstimator InnerUCE(SubLoop, TTI, EphValues, UP.BEInsns);
312 UnrollCostEstimator OuterUCE(L, TTI, EphValues, UP.BEInsns);
313
314 if (!InnerUCE.canUnroll() || !OuterUCE.canUnroll()) {
315 LLVM_DEBUG(dbgs() << " Loop not considered unrollable\n");
316 return LoopUnrollResult::Unmodified;
317 }
318
319 unsigned InnerLoopSize = InnerUCE.getRolledLoopSize();
320 LLVM_DEBUG(dbgs() << " Outer Loop Size: " << OuterUCE.getRolledLoopSize()
321 << "\n");
322 LLVM_DEBUG(dbgs() << " Inner Loop Size: " << InnerLoopSize << "\n");
323
324 if (InnerUCE.NumInlineCandidates != 0 || OuterUCE.NumInlineCandidates != 0) {
325 LLVM_DEBUG(dbgs() << " Not unrolling loop with inlinable calls.\n");
326 return LoopUnrollResult::Unmodified;
327 }
328 // FIXME: The call to canUnroll() allows some controlled convergent
329 // operations, but we block them here for future changes.
330 if (InnerUCE.Convergence != ConvergenceKind::None ||
331 OuterUCE.Convergence != ConvergenceKind::None) {
332 LLVM_DEBUG(
333 dbgs() << " Not unrolling loop with convergent instructions.\n");
334 return LoopUnrollResult::Unmodified;
335 }
336
337 // Save original loop IDs for after the transformation.
338 MDNode *OrigOuterLoopID = L->getLoopID();
339 MDNode *OrigSubLoopID = SubLoop->getLoopID();
340
341 // To assign the loop id of the epilogue, assign it before unrolling it so it
342 // is applied to every inner loop of the epilogue. We later apply the loop ID
343 // for the jammed inner loop.
344 std::optional<MDNode *> NewInnerEpilogueLoopID = makeFollowupLoopID(
345 OrigLoopID: OrigOuterLoopID, FollowupAttrs: {LLVMLoopUnrollAndJamFollowupAll,
346 LLVMLoopUnrollAndJamFollowupRemainderInner});
347 if (NewInnerEpilogueLoopID)
348 SubLoop->setLoopID(*NewInnerEpilogueLoopID);
349
350 // Find trip count and trip multiple
351 BasicBlock *Latch = L->getLoopLatch();
352 BasicBlock *SubLoopLatch = SubLoop->getLoopLatch();
353 unsigned OuterTripCount = SE.getSmallConstantTripCount(L, ExitingBlock: Latch);
354 unsigned OuterTripMultiple = SE.getSmallConstantTripMultiple(L, ExitingBlock: Latch);
355 unsigned InnerTripCount = SE.getSmallConstantTripCount(L: SubLoop, ExitingBlock: SubLoopLatch);
356
357 // Decide if, and by how much, to unroll
358 bool IsExplicitUnrollAndJam = false;
359 unsigned Count = computeUnrollAndJamCount(
360 L, SubLoop, TTI, DT, LI, AC: &AC, SE, EphValues, ORE: &ORE, OuterTripCount,
361 OuterTripMultiple, OuterUCE, InnerTripCount, InnerLoopSize,
362 IsExplicitUnrollAndJam, UP, PP);
363 if (Count <= 1)
364 return LoopUnrollResult::Unmodified;
365 // Unroll factor (Count) must be less or equal to TripCount.
366 if (OuterTripCount && Count > OuterTripCount)
367 Count = OuterTripCount;
368
369 Loop *EpilogueOuterLoop = nullptr;
370 LoopUnrollResult UnrollResult = UnrollAndJamLoop(
371 L, Count, TripCount: OuterTripCount, TripMultiple: OuterTripMultiple, UnrollRemainder: UP.UnrollRemainder, LI, SE: &SE,
372 DT: &DT, AC: &AC, TTI: &TTI, ORE: &ORE, EpilogueLoop: &EpilogueOuterLoop);
373
374 // Assign new loop attributes.
375 if (EpilogueOuterLoop) {
376 std::optional<MDNode *> NewOuterEpilogueLoopID = makeFollowupLoopID(
377 OrigLoopID: OrigOuterLoopID, FollowupAttrs: {LLVMLoopUnrollAndJamFollowupAll,
378 LLVMLoopUnrollAndJamFollowupRemainderOuter});
379 if (NewOuterEpilogueLoopID)
380 EpilogueOuterLoop->setLoopID(*NewOuterEpilogueLoopID);
381 }
382
383 std::optional<MDNode *> NewInnerLoopID =
384 makeFollowupLoopID(OrigLoopID: OrigOuterLoopID, FollowupAttrs: {LLVMLoopUnrollAndJamFollowupAll,
385 LLVMLoopUnrollAndJamFollowupInner});
386 if (NewInnerLoopID)
387 SubLoop->setLoopID(*NewInnerLoopID);
388 else
389 SubLoop->setLoopID(OrigSubLoopID);
390
391 if (UnrollResult == LoopUnrollResult::PartiallyUnrolled) {
392 std::optional<MDNode *> NewOuterLoopID = makeFollowupLoopID(
393 OrigLoopID: OrigOuterLoopID,
394 FollowupAttrs: {LLVMLoopUnrollAndJamFollowupAll, LLVMLoopUnrollAndJamFollowupOuter});
395 if (NewOuterLoopID) {
396 L->setLoopID(*NewOuterLoopID);
397
398 // Do not setLoopAlreadyUnrolled if a followup was given.
399 return UnrollResult;
400 }
401 }
402
403 // If unroll-and-jam was explicitly requested, mark the loop as already
404 // unrolled to prevent unrolling beyond that request.
405 if (UnrollResult != LoopUnrollResult::FullyUnrolled && IsExplicitUnrollAndJam)
406 L->setLoopAlreadyUnrolled();
407
408 return UnrollResult;
409}
410
411static bool tryToUnrollAndJamLoop(LoopNest &LN, DominatorTree &DT, LoopInfo &LI,
412 ScalarEvolution &SE,
413 const TargetTransformInfo &TTI,
414 AssumptionCache &AC, DependenceInfo &DI,
415 OptimizationRemarkEmitter &ORE, int OptLevel,
416 LPMUpdater &U, bool &AnyLoopRemoved) {
417 bool DidSomething = false;
418 ArrayRef<Loop *> Loops = LN.getLoops();
419 Loop *OutmostLoop = &LN.getOutermostLoop();
420
421 // Add the loop nests in the reverse order of LN. See method
422 // declaration.
423 SmallPriorityWorklist<Loop *, 4> Worklist;
424 appendLoopsToWorklist(Loops, Worklist);
425 while (!Worklist.empty()) {
426 Loop *L = Worklist.pop_back_val();
427 std::string LoopName = std::string(L->getName());
428 LoopUnrollResult Result =
429 tryToUnrollAndJamLoop(L, DT, LI: &LI, SE, TTI, AC, DI, ORE, OptLevel);
430 if (Result != LoopUnrollResult::Unmodified)
431 DidSomething = true;
432 if (Result == LoopUnrollResult::FullyUnrolled) {
433 if (L == OutmostLoop)
434 U.markLoopAsDeleted(L&: *L, Name: LoopName);
435 AnyLoopRemoved = true;
436 }
437 }
438
439 return DidSomething;
440}
441
442PreservedAnalyses LoopUnrollAndJamPass::run(LoopNest &LN,
443 LoopAnalysisManager &AM,
444 LoopStandardAnalysisResults &AR,
445 LPMUpdater &U) {
446 Function &F = *LN.getParent();
447
448 DependenceInfo DI(&F, &AR.AA, &AR.SE, &AR.LI);
449 OptimizationRemarkEmitter ORE(&F);
450
451 bool AnyLoopRemoved = false;
452 if (!tryToUnrollAndJamLoop(LN, DT&: AR.DT, LI&: AR.LI, SE&: AR.SE, TTI: AR.TTI, AC&: AR.AC, DI, ORE,
453 OptLevel, U, AnyLoopRemoved))
454 return PreservedAnalyses::all();
455
456 auto PA = getLoopPassPreservedAnalyses();
457 if (!AnyLoopRemoved)
458 PA.preserve<LoopNestAnalysis>();
459 return PA;
460}
461