1//===-- LoopUtils.cpp - Loop Utility functions -------------------------===//
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 file defines common loop utility functions.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/Transforms/Utils/LoopUtils.h"
14#include "llvm/ADT/DenseSet.h"
15#include "llvm/ADT/PriorityWorklist.h"
16#include "llvm/ADT/ScopeExit.h"
17#include "llvm/ADT/SetVector.h"
18#include "llvm/ADT/SmallPtrSet.h"
19#include "llvm/ADT/SmallVector.h"
20#include "llvm/Analysis/AliasAnalysis.h"
21#include "llvm/Analysis/BasicAliasAnalysis.h"
22#include "llvm/Analysis/DomTreeUpdater.h"
23#include "llvm/Analysis/GlobalsModRef.h"
24#include "llvm/Analysis/InstSimplifyFolder.h"
25#include "llvm/Analysis/LoopAccessAnalysis.h"
26#include "llvm/Analysis/LoopInfo.h"
27#include "llvm/Analysis/LoopPass.h"
28#include "llvm/Analysis/MemorySSA.h"
29#include "llvm/Analysis/MemorySSAUpdater.h"
30#include "llvm/Analysis/ScalarEvolution.h"
31#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
32#include "llvm/Analysis/ScalarEvolutionExpressions.h"
33#include "llvm/IR/DIBuilder.h"
34#include "llvm/IR/Dominators.h"
35#include "llvm/IR/Instructions.h"
36#include "llvm/IR/IntrinsicInst.h"
37#include "llvm/IR/MDBuilder.h"
38#include "llvm/IR/Module.h"
39#include "llvm/IR/PatternMatch.h"
40#include "llvm/IR/ProfDataUtils.h"
41#include "llvm/IR/ValueHandle.h"
42#include "llvm/InitializePasses.h"
43#include "llvm/Pass.h"
44#include "llvm/Support/Compiler.h"
45#include "llvm/Support/Debug.h"
46#include "llvm/Transforms/Utils/BasicBlockUtils.h"
47#include "llvm/Transforms/Utils/Local.h"
48#include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
49
50using namespace llvm;
51using namespace llvm::PatternMatch;
52
53#define DEBUG_TYPE "loop-utils"
54
55static const char *LLVMLoopDisableNonforced = "llvm.loop.disable_nonforced";
56static const char *LLVMLoopDisableLICM = "llvm.licm.disable";
57namespace llvm {
58extern cl::opt<bool> ProfcheckDisableMetadataFixes;
59} // namespace llvm
60
61bool llvm::formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI,
62 MemorySSAUpdater *MSSAU,
63 bool PreserveLCSSA) {
64 bool Changed = false;
65
66 // We re-use a vector for the in-loop predecesosrs.
67 SmallVector<BasicBlock *, 4> InLoopPredecessors;
68
69 auto RewriteExit = [&](BasicBlock *BB) {
70 assert(InLoopPredecessors.empty() &&
71 "Must start with an empty predecessors list!");
72 llvm::scope_exit Cleanup([&] { InLoopPredecessors.clear(); });
73
74 // See if there are any non-loop predecessors of this exit block and
75 // keep track of the in-loop predecessors.
76 bool IsDedicatedExit = true;
77 for (auto *PredBB : predecessors(BB))
78 if (L->contains(BB: PredBB)) {
79 if (isa<IndirectBrInst>(Val: PredBB->getTerminator()))
80 // We cannot rewrite exiting edges from an indirectbr.
81 return false;
82
83 InLoopPredecessors.push_back(Elt: PredBB);
84 } else {
85 IsDedicatedExit = false;
86 }
87
88 assert(!InLoopPredecessors.empty() && "Must have *some* loop predecessor!");
89
90 // Nothing to do if this is already a dedicated exit.
91 if (IsDedicatedExit)
92 return false;
93
94 auto *NewExitBB = SplitBlockPredecessors(
95 BB, Preds: InLoopPredecessors, Suffix: ".loopexit", DT, LI, MSSAU, PreserveLCSSA);
96
97 if (!NewExitBB)
98 LLVM_DEBUG(
99 dbgs() << "WARNING: Can't create a dedicated exit block for loop: "
100 << *L << "\n");
101 else
102 LLVM_DEBUG(dbgs() << "LoopSimplify: Creating dedicated exit block "
103 << NewExitBB->getName() << "\n");
104 return true;
105 };
106
107 // Walk the exit blocks directly rather than building up a data structure for
108 // them, but only visit each one once.
109 SmallPtrSet<BasicBlock *, 4> Visited;
110 for (auto *BB : L->blocks())
111 for (auto *SuccBB : successors(BB)) {
112 // We're looking for exit blocks so skip in-loop successors.
113 if (L->contains(BB: SuccBB))
114 continue;
115
116 // Visit each exit block exactly once.
117 if (!Visited.insert(Ptr: SuccBB).second)
118 continue;
119
120 Changed |= RewriteExit(SuccBB);
121 }
122
123 return Changed;
124}
125
126/// Returns the instructions that use values defined in the loop.
127SmallVector<Instruction *, 8> llvm::findDefsUsedOutsideOfLoop(Loop *L) {
128 SmallVector<Instruction *, 8> UsedOutside;
129
130 for (auto *Block : L->getBlocks())
131 // FIXME: I believe that this could use copy_if if the Inst reference could
132 // be adapted into a pointer.
133 for (auto &Inst : *Block) {
134 auto Users = Inst.users();
135 if (any_of(Range&: Users, P: [&](User *U) {
136 auto *Use = cast<Instruction>(Val: U);
137 return !L->contains(BB: Use->getParent());
138 }))
139 UsedOutside.push_back(Elt: &Inst);
140 }
141
142 return UsedOutside;
143}
144
145void llvm::getLoopAnalysisUsage(AnalysisUsage &AU) {
146 // By definition, all loop passes need the LoopInfo analysis and the
147 // Dominator tree it depends on. Because they all participate in the loop
148 // pass manager, they must also preserve these.
149 AU.addRequired<DominatorTreeWrapperPass>();
150 AU.addPreserved<DominatorTreeWrapperPass>();
151 AU.addRequired<LoopInfoWrapperPass>();
152 AU.addPreserved<LoopInfoWrapperPass>();
153
154 // We must also preserve LoopSimplify and LCSSA. We locally access their IDs
155 // here because users shouldn't directly get them from this header.
156 extern char &LoopSimplifyID;
157 extern char &LCSSAID;
158 AU.addRequiredID(ID&: LoopSimplifyID);
159 AU.addPreservedID(ID&: LoopSimplifyID);
160 AU.addRequiredID(ID&: LCSSAID);
161 AU.addPreservedID(ID&: LCSSAID);
162 // This is used in the LPPassManager to perform LCSSA verification on passes
163 // which preserve lcssa form
164 AU.addRequired<LCSSAVerificationPass>();
165 AU.addPreserved<LCSSAVerificationPass>();
166
167 // Loop passes are designed to run inside of a loop pass manager which means
168 // that any function analyses they require must be required by the first loop
169 // pass in the manager (so that it is computed before the loop pass manager
170 // runs) and preserved by all loop pasess in the manager. To make this
171 // reasonably robust, the set needed for most loop passes is maintained here.
172 // If your loop pass requires an analysis not listed here, you will need to
173 // carefully audit the loop pass manager nesting structure that results.
174 AU.addRequired<AAResultsWrapperPass>();
175 AU.addPreserved<AAResultsWrapperPass>();
176 AU.addPreserved<BasicAAWrapperPass>();
177 AU.addPreserved<GlobalsAAWrapperPass>();
178 AU.addPreserved<SCEVAAWrapperPass>();
179 AU.addRequired<ScalarEvolutionWrapperPass>();
180 AU.addPreserved<ScalarEvolutionWrapperPass>();
181 // FIXME: When all loop passes preserve MemorySSA, it can be required and
182 // preserved here instead of the individual handling in each pass.
183}
184
185/// Manually defined generic "LoopPass" dependency initialization. This is used
186/// to initialize the exact set of passes from above in \c
187/// getLoopAnalysisUsage. It can be used within a loop pass's initialization
188/// with:
189///
190/// INITIALIZE_PASS_DEPENDENCY(LoopPass)
191///
192/// As-if "LoopPass" were a pass.
193void llvm::initializeLoopPassPass(PassRegistry &Registry) {
194 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
195 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
196 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
197 INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
198 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
199 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
200 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
201 INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
202 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
203 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
204}
205
206/// Create MDNode for input string.
207static MDNode *createStringMetadata(Loop *TheLoop, StringRef Name, unsigned V) {
208 LLVMContext &Context = TheLoop->getHeader()->getContext();
209 Metadata *MDs[] = {
210 MDString::get(Context, Str: Name),
211 ConstantAsMetadata::get(C: ConstantInt::get(Ty: Type::getInt32Ty(C&: Context), V))};
212 return MDNode::get(Context, MDs);
213}
214
215/// Set input string into loop metadata by keeping other values intact.
216/// If the string is already in loop metadata update value if it is
217/// different.
218void llvm::addStringMetadataToLoop(Loop *TheLoop, const char *StringMD,
219 unsigned V) {
220 SmallVector<Metadata *, 4> MDs(1);
221 // If the loop already has metadata, retain it.
222 MDNode *LoopID = TheLoop->getLoopID();
223 if (LoopID) {
224 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
225 MDNode *Node = cast<MDNode>(Val: LoopID->getOperand(I: i));
226 // If it is of form key = value, try to parse it.
227 if (Node->getNumOperands() == 2) {
228 MDString *S = dyn_cast<MDString>(Val: Node->getOperand(I: 0));
229 if (S && S->getString() == StringMD) {
230 ConstantInt *IntMD =
231 mdconst::extract_or_null<ConstantInt>(MD: Node->getOperand(I: 1));
232 if (IntMD && IntMD->getSExtValue() == V)
233 // It is already in place. Do nothing.
234 return;
235 // We need to update the value, so just skip it here and it will
236 // be added after copying other existed nodes.
237 continue;
238 }
239 }
240 MDs.push_back(Elt: Node);
241 }
242 }
243 // Add new metadata.
244 MDs.push_back(Elt: createStringMetadata(TheLoop, Name: StringMD, V));
245 // Replace current metadata node with new one.
246 LLVMContext &Context = TheLoop->getHeader()->getContext();
247 MDNode *NewLoopID = MDNode::get(Context, MDs);
248 // Set operand 0 to refer to the loop id itself.
249 NewLoopID->replaceOperandWith(I: 0, New: NewLoopID);
250 TheLoop->setLoopID(NewLoopID);
251}
252
253std::optional<ElementCount>
254llvm::getOptionalElementCountLoopAttribute(const Loop *TheLoop) {
255 std::optional<int> Width =
256 getOptionalIntLoopAttribute(TheLoop, Name: "llvm.loop.vectorize.width");
257
258 if (Width) {
259 std::optional<int> IsScalable = getOptionalIntLoopAttribute(
260 TheLoop, Name: "llvm.loop.vectorize.scalable.enable");
261 return ElementCount::get(MinVal: *Width, Scalable: IsScalable.value_or(u: false));
262 }
263
264 return std::nullopt;
265}
266
267std::optional<MDNode *> llvm::makeFollowupLoopID(
268 MDNode *OrigLoopID, ArrayRef<StringRef> FollowupOptions,
269 const char *InheritOptionsExceptPrefix, bool AlwaysNew) {
270 if (!OrigLoopID) {
271 if (AlwaysNew)
272 return nullptr;
273 return std::nullopt;
274 }
275
276 assert(OrigLoopID->getOperand(0) == OrigLoopID);
277
278 bool InheritAllAttrs = !InheritOptionsExceptPrefix;
279 bool InheritSomeAttrs =
280 InheritOptionsExceptPrefix && InheritOptionsExceptPrefix[0] != '\0';
281 SmallVector<Metadata *, 8> MDs;
282 MDs.push_back(Elt: nullptr);
283
284 bool Changed = false;
285 if (InheritAllAttrs || InheritSomeAttrs) {
286 for (const MDOperand &Existing : drop_begin(RangeOrContainer: OrigLoopID->operands())) {
287 MDNode *Op = cast<MDNode>(Val: Existing.get());
288
289 auto InheritThisAttribute = [InheritSomeAttrs,
290 InheritOptionsExceptPrefix](MDNode *Op) {
291 if (!InheritSomeAttrs)
292 return false;
293
294 // Skip malformatted attribute metadata nodes.
295 if (Op->getNumOperands() == 0)
296 return true;
297 Metadata *NameMD = Op->getOperand(I: 0).get();
298 if (!isa<MDString>(Val: NameMD))
299 return true;
300 StringRef AttrName = cast<MDString>(Val: NameMD)->getString();
301
302 // Do not inherit excluded attributes.
303 return !AttrName.starts_with(Prefix: InheritOptionsExceptPrefix);
304 };
305
306 if (InheritThisAttribute(Op))
307 MDs.push_back(Elt: Op);
308 else
309 Changed = true;
310 }
311 } else {
312 // Modified if we dropped at least one attribute.
313 Changed = OrigLoopID->getNumOperands() > 1;
314 }
315
316 bool HasAnyFollowup = false;
317 for (StringRef OptionName : FollowupOptions) {
318 MDNode *FollowupNode = findOptionMDForLoopID(LoopID: OrigLoopID, Name: OptionName);
319 if (!FollowupNode)
320 continue;
321
322 HasAnyFollowup = true;
323 for (const MDOperand &Option : drop_begin(RangeOrContainer: FollowupNode->operands())) {
324 MDs.push_back(Elt: Option.get());
325 Changed = true;
326 }
327 }
328
329 // Attributes of the followup loop not specified explicity, so signal to the
330 // transformation pass to add suitable attributes.
331 if (!AlwaysNew && !HasAnyFollowup)
332 return std::nullopt;
333
334 // If no attributes were added or remove, the previous loop Id can be reused.
335 if (!AlwaysNew && !Changed)
336 return OrigLoopID;
337
338 // No attributes is equivalent to having no !llvm.loop metadata at all.
339 if (MDs.size() == 1)
340 return nullptr;
341
342 // Build the new loop ID.
343 MDTuple *FollowupLoopID = MDNode::get(Context&: OrigLoopID->getContext(), MDs);
344 FollowupLoopID->replaceOperandWith(I: 0, New: FollowupLoopID);
345 return FollowupLoopID;
346}
347
348bool llvm::hasDisableAllTransformsHint(const Loop *L) {
349 return getBooleanLoopAttribute(TheLoop: L, Name: LLVMLoopDisableNonforced);
350}
351
352bool llvm::hasDisableLICMTransformsHint(const Loop *L) {
353 return getBooleanLoopAttribute(TheLoop: L, Name: LLVMLoopDisableLICM);
354}
355
356StringRef llvm::getLoopVectorizeKindPrefix(const Loop *L) {
357 bool IsVectorBody = getBooleanLoopAttribute(TheLoop: L, Name: "llvm.loop.vectorize.body");
358 bool IsEpilogue = getBooleanLoopAttribute(TheLoop: L, Name: "llvm.loop.vectorize.epilogue");
359 if (IsVectorBody && IsEpilogue)
360 return "vectorized epilogue ";
361 if (IsVectorBody)
362 return "vectorized ";
363 if (IsEpilogue)
364 return "epilogue ";
365 return "";
366}
367
368TransformationMode llvm::hasUnrollTransformation(const Loop *L) {
369 if (getBooleanLoopAttribute(TheLoop: L, Name: "llvm.loop.unroll.disable"))
370 return TM_SuppressedByUser;
371
372 std::optional<int> Count =
373 getOptionalIntLoopAttribute(TheLoop: L, Name: "llvm.loop.unroll.count");
374 if (Count)
375 return *Count == 1 ? TM_SuppressedByUser : TM_ForcedByUser;
376
377 if (getBooleanLoopAttribute(TheLoop: L, Name: "llvm.loop.unroll.enable"))
378 return TM_ForcedByUser;
379
380 if (getBooleanLoopAttribute(TheLoop: L, Name: "llvm.loop.unroll.full"))
381 return TM_ForcedByUser;
382
383 if (hasDisableAllTransformsHint(L))
384 return TM_Disable;
385
386 return TM_Unspecified;
387}
388
389TransformationMode llvm::hasUnrollAndJamTransformation(const Loop *L) {
390 if (getBooleanLoopAttribute(TheLoop: L, Name: "llvm.loop.unroll_and_jam.disable"))
391 return TM_SuppressedByUser;
392
393 std::optional<int> Count =
394 getOptionalIntLoopAttribute(TheLoop: L, Name: "llvm.loop.unroll_and_jam.count");
395 if (Count)
396 return *Count == 1 ? TM_SuppressedByUser : TM_ForcedByUser;
397
398 if (getBooleanLoopAttribute(TheLoop: L, Name: "llvm.loop.unroll_and_jam.enable"))
399 return TM_ForcedByUser;
400
401 if (hasDisableAllTransformsHint(L))
402 return TM_Disable;
403
404 return TM_Unspecified;
405}
406
407TransformationMode llvm::hasVectorizeTransformation(const Loop *L) {
408 std::optional<bool> Enable =
409 getOptionalBoolLoopAttribute(TheLoop: L, Name: "llvm.loop.vectorize.enable");
410
411 if (Enable == false)
412 return TM_SuppressedByUser;
413
414 std::optional<ElementCount> VectorizeWidth =
415 getOptionalElementCountLoopAttribute(TheLoop: L);
416 std::optional<int> InterleaveCount =
417 getOptionalIntLoopAttribute(TheLoop: L, Name: "llvm.loop.interleave.count");
418
419 // 'Forcing' vector width and interleave count to one effectively disables
420 // this tranformation.
421 if (Enable == true && VectorizeWidth && VectorizeWidth->isScalar() &&
422 InterleaveCount == 1)
423 return TM_SuppressedByUser;
424
425 if (getBooleanLoopAttribute(TheLoop: L, Name: "llvm.loop.isvectorized"))
426 return TM_Disable;
427
428 if (Enable == true)
429 return TM_ForcedByUser;
430
431 if ((VectorizeWidth && VectorizeWidth->isScalar()) && InterleaveCount == 1)
432 return TM_Disable;
433
434 if ((VectorizeWidth && VectorizeWidth->isVector()) || InterleaveCount > 1)
435 return TM_Enable;
436
437 if (hasDisableAllTransformsHint(L))
438 return TM_Disable;
439
440 return TM_Unspecified;
441}
442
443TransformationMode llvm::hasDistributeTransformation(const Loop *L) {
444 if (getBooleanLoopAttribute(TheLoop: L, Name: "llvm.loop.distribute.enable"))
445 return TM_ForcedByUser;
446
447 if (hasDisableAllTransformsHint(L))
448 return TM_Disable;
449
450 return TM_Unspecified;
451}
452
453TransformationMode llvm::hasLICMVersioningTransformation(const Loop *L) {
454 if (getBooleanLoopAttribute(TheLoop: L, Name: "llvm.loop.licm_versioning.disable"))
455 return TM_SuppressedByUser;
456
457 if (hasDisableAllTransformsHint(L))
458 return TM_Disable;
459
460 return TM_Unspecified;
461}
462
463/// Does a BFS from a given node to all of its children inside a given loop.
464/// The returned vector of basic blocks includes the starting point.
465SmallVector<BasicBlock *, 16> llvm::collectChildrenInLoop(DominatorTree *DT,
466 DomTreeNode *N,
467 const Loop *CurLoop) {
468 SmallVector<BasicBlock *, 16> Worklist;
469 auto AddRegionToWorklist = [&](DomTreeNode *DTN) {
470 // Only include subregions in the top level loop.
471 BasicBlock *BB = DTN->getBlock();
472 if (CurLoop->contains(BB))
473 Worklist.push_back(Elt: DTN->getBlock());
474 };
475
476 AddRegionToWorklist(N);
477
478 for (size_t I = 0; I < Worklist.size(); I++) {
479 for (DomTreeNode *Child : DT->getNode(BB: Worklist[I])->children())
480 AddRegionToWorklist(Child);
481 }
482
483 return Worklist;
484}
485
486bool llvm::isAlmostDeadIV(PHINode *PN, BasicBlock *LatchBlock, Value *Cond) {
487 int LatchIdx = PN->getBasicBlockIndex(BB: LatchBlock);
488 assert(LatchIdx != -1 && "LatchBlock is not a case in this PHINode");
489 Value *IncV = PN->getIncomingValue(i: LatchIdx);
490
491 for (User *U : PN->users())
492 if (U != Cond && U != IncV) return false;
493
494 for (User *U : IncV->users())
495 if (U != Cond && U != PN) return false;
496 return true;
497}
498
499
500void llvm::deleteDeadLoop(Loop *L, DominatorTree *DT, ScalarEvolution *SE,
501 LoopInfo *LI, MemorySSA *MSSA) {
502 assert((!DT || L->isLCSSAForm(*DT)) && "Expected LCSSA!");
503 auto *Preheader = L->getLoopPreheader();
504 assert(Preheader && "Preheader should exist!");
505
506 std::unique_ptr<MemorySSAUpdater> MSSAU;
507 if (MSSA)
508 MSSAU = std::make_unique<MemorySSAUpdater>(args&: MSSA);
509
510 // Now that we know the removal is safe, remove the loop by changing the
511 // branch from the preheader to go to the single exit block.
512 //
513 // Because we're deleting a large chunk of code at once, the sequence in which
514 // we remove things is very important to avoid invalidation issues.
515
516 // Tell ScalarEvolution that the loop is deleted. Do this before
517 // deleting the loop so that ScalarEvolution can look at the loop
518 // to determine what it needs to clean up.
519 if (SE) {
520 SE->forgetLoop(L);
521 SE->forgetBlockAndLoopDispositions();
522 }
523
524 Instruction *OldTerm = Preheader->getTerminator();
525 assert(!OldTerm->mayHaveSideEffects() &&
526 "Preheader must end with a side-effect-free terminator");
527 assert(OldTerm->getNumSuccessors() == 1 &&
528 "Preheader must have a single successor");
529 // Connect the preheader to the exit block. Keep the old edge to the header
530 // around to perform the dominator tree update in two separate steps
531 // -- #1 insertion of the edge preheader -> exit and #2 deletion of the edge
532 // preheader -> header.
533 //
534 //
535 // 0. Preheader 1. Preheader 2. Preheader
536 // | | | |
537 // V | V |
538 // Header <--\ | Header <--\ | Header <--\
539 // | | | | | | | | | | |
540 // | V | | | V | | | V |
541 // | Body --/ | | Body --/ | | Body --/
542 // V V V V V
543 // Exit Exit Exit
544 //
545 // By doing this is two separate steps we can perform the dominator tree
546 // update without using the batch update API.
547 //
548 // Even when the loop is never executed, we cannot remove the edge from the
549 // source block to the exit block. Consider the case where the unexecuted loop
550 // branches back to an outer loop. If we deleted the loop and removed the edge
551 // coming to this inner loop, this will break the outer loop structure (by
552 // deleting the backedge of the outer loop). If the outer loop is indeed a
553 // non-loop, it will be deleted in a future iteration of loop deletion pass.
554 IRBuilder<> Builder(OldTerm);
555
556 auto *ExitBlock = L->getUniqueExitBlock();
557 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
558 if (ExitBlock) {
559 assert(ExitBlock && "Should have a unique exit block!");
560 assert(L->hasDedicatedExits() && "Loop should have dedicated exits!");
561
562 Builder.CreateCondBr(Cond: Builder.getFalse(), True: L->getHeader(), False: ExitBlock);
563 // Remove the old branch. The conditional branch becomes a new terminator.
564 OldTerm->eraseFromParent();
565
566 // Rewrite phis in the exit block to get their inputs from the Preheader
567 // instead of the exiting block.
568 for (PHINode &P : ExitBlock->phis()) {
569 // Set the zero'th element of Phi to be from the preheader and remove all
570 // other incoming values. Given the loop has dedicated exits, all other
571 // incoming values must be from the exiting blocks.
572 int PredIndex = 0;
573 P.setIncomingBlock(i: PredIndex, BB: Preheader);
574 // Removes all incoming values from all other exiting blocks (including
575 // duplicate values from an exiting block).
576 // Nuke all entries except the zero'th entry which is the preheader entry.
577 P.removeIncomingValueIf(Predicate: [](unsigned Idx) { return Idx != 0; },
578 /* DeletePHIIfEmpty */ false);
579
580 assert((P.getNumIncomingValues() == 1 &&
581 P.getIncomingBlock(PredIndex) == Preheader) &&
582 "Should have exactly one value and that's from the preheader!");
583 }
584
585 if (DT) {
586 DTU.applyUpdates(Updates: {{DominatorTree::Insert, Preheader, ExitBlock}});
587 if (MSSA) {
588 MSSAU->applyUpdates(Updates: {{DominatorTree::Insert, Preheader, ExitBlock}},
589 DT&: *DT);
590 if (VerifyMemorySSA)
591 MSSA->verifyMemorySSA();
592 }
593 }
594
595 // Disconnect the loop body by branching directly to its exit.
596 Builder.SetInsertPoint(Preheader->getTerminator());
597 Builder.CreateBr(Dest: ExitBlock);
598 // Remove the old branch.
599 Preheader->getTerminator()->eraseFromParent();
600 } else {
601 assert(L->hasNoExitBlocks() &&
602 "Loop should have either zero or one exit blocks.");
603
604 Builder.SetInsertPoint(OldTerm);
605 Builder.CreateUnreachable();
606 Preheader->getTerminator()->eraseFromParent();
607 }
608
609 if (DT) {
610 DTU.applyUpdates(Updates: {{DominatorTree::Delete, Preheader, L->getHeader()}});
611 if (MSSA) {
612 MSSAU->applyUpdates(Updates: {{DominatorTree::Delete, Preheader, L->getHeader()}},
613 DT&: *DT);
614 SmallSetVector<BasicBlock *, 8> DeadBlockSet(L->block_begin(),
615 L->block_end());
616 MSSAU->removeBlocks(DeadBlocks: DeadBlockSet);
617 if (VerifyMemorySSA)
618 MSSA->verifyMemorySSA();
619 }
620 }
621
622 // Use a map to unique and a vector to guarantee deterministic ordering.
623 llvm::SmallDenseSet<DebugVariable, 4> DeadDebugSet;
624 llvm::SmallVector<DbgVariableRecord *, 4> DeadDbgVariableRecords;
625
626 // Given LCSSA form is satisfied, we should not have users of instructions
627 // within the dead loop outside of the loop. However, LCSSA doesn't take
628 // unreachable uses into account. We handle them here.
629 // We could do it after drop all references (in this case all users in the
630 // loop will be already eliminated and we have less work to do but according
631 // to API doc of User::dropAllReferences only valid operation after dropping
632 // references, is deletion. So let's substitute all usages of
633 // instruction from the loop with poison value of corresponding type first.
634 for (auto *Block : L->blocks())
635 for (Instruction &I : *Block) {
636 auto *Poison = PoisonValue::get(T: I.getType());
637 for (Use &U : llvm::make_early_inc_range(Range: I.uses())) {
638 if (auto *Usr = dyn_cast<Instruction>(Val: U.getUser()))
639 if (L->contains(BB: Usr->getParent()))
640 continue;
641 // If we have a DT then we can check that uses outside a loop only in
642 // unreachable block.
643 if (DT)
644 assert(!DT->isReachableFromEntry(U) &&
645 "Unexpected user in reachable block");
646 U.set(Poison);
647 }
648
649 if (ExitBlock) {
650 // For one of each variable encountered, preserve a debug record (set
651 // to Poison) and transfer it to the loop exit. This terminates any
652 // variable locations that were set during the loop.
653 for (DbgVariableRecord &DVR :
654 llvm::make_early_inc_range(Range: filterDbgVars(R: I.getDbgRecordRange()))) {
655 DebugVariable Key(DVR.getVariable(), DVR.getExpression(),
656 DVR.getDebugLoc().get());
657 if (!DeadDebugSet.insert(V: Key).second)
658 continue;
659 // Unlinks the DVR from it's container, for later insertion.
660 DVR.removeFromParent();
661 DeadDbgVariableRecords.push_back(Elt: &DVR);
662 }
663 }
664 }
665
666 if (ExitBlock) {
667 // After the loop has been deleted all the values defined and modified
668 // inside the loop are going to be unavailable. Values computed in the
669 // loop will have been deleted, automatically causing their debug uses
670 // be be replaced with undef. Loop invariant values will still be available.
671 // Move dbg.values out the loop so that earlier location ranges are still
672 // terminated and loop invariant assignments are preserved.
673 DIBuilder DIB(*ExitBlock->getModule());
674 BasicBlock::iterator InsertDbgValueBefore =
675 ExitBlock->getFirstInsertionPt();
676 assert(InsertDbgValueBefore != ExitBlock->end() &&
677 "There should be a non-PHI instruction in exit block, else these "
678 "instructions will have no parent.");
679
680 // Due to the "head" bit in BasicBlock::iterator, we're going to insert
681 // each DbgVariableRecord right at the start of the block, wheras dbg.values
682 // would be repeatedly inserted before the first instruction. To replicate
683 // this behaviour, do it backwards.
684 for (DbgVariableRecord *DVR : llvm::reverse(C&: DeadDbgVariableRecords))
685 ExitBlock->insertDbgRecordBefore(DR: DVR, Here: InsertDbgValueBefore);
686 }
687
688 // Remove the block from the reference counting scheme, so that we can
689 // delete it freely later.
690 for (auto *Block : L->blocks())
691 Block->dropAllReferences();
692
693 if (MSSA && VerifyMemorySSA)
694 MSSA->verifyMemorySSA();
695
696 if (LI) {
697 SmallPtrSet<BasicBlock *, 8> Blocks(llvm::from_range, L->blocks());
698
699 // Erase the instructions and the blocks without having to worry
700 // about ordering because we already dropped the references.
701 // Remove blocks from loopinfo before erasing them, otherwise the loopinfo
702 // cannot find the loop using block numbers.
703 for (BasicBlock *BB : Blocks) {
704 LI->removeBlock(BB);
705 BB->eraseFromParent();
706 }
707
708 // The last step is to update LoopInfo now that we've eliminated this loop.
709 // Note: LoopInfo::erase remove the given loop and relink its subloops with
710 // its parent. While removeLoop/removeChildLoop remove the given loop but
711 // not relink its subloops, which is what we want.
712 if (Loop *ParentLoop = L->getParentLoop()) {
713 Loop::iterator I = find(Range&: *ParentLoop, Val: L);
714 assert(I != ParentLoop->end() && "Couldn't find loop");
715 ParentLoop->removeChildLoop(I);
716 } else {
717 Loop::iterator I = find(Range&: *LI, Val: L);
718 assert(I != LI->end() && "Couldn't find loop");
719 LI->removeLoop(I);
720 }
721 LI->destroy(L);
722 }
723}
724
725void llvm::breakLoopBackedge(Loop *L, DominatorTree &DT, ScalarEvolution &SE,
726 LoopInfo &LI, MemorySSA *MSSA) {
727 auto *Latch = L->getLoopLatch();
728 assert(Latch && "multiple latches not yet supported");
729 auto *Header = L->getHeader();
730 Loop *OutermostLoop = L->getOutermostLoop();
731
732 SE.forgetLoop(L);
733 SE.forgetBlockAndLoopDispositions();
734
735 std::unique_ptr<MemorySSAUpdater> MSSAU;
736 if (MSSA)
737 MSSAU = std::make_unique<MemorySSAUpdater>(args&: MSSA);
738
739 // Update the CFG and domtree. We chose to special case a couple of
740 // of common cases for code quality and test readability reasons.
741 [&]() -> void {
742 if (auto *BI = dyn_cast<UncondBrInst>(Val: Latch->getTerminator())) {
743 DomTreeUpdater DTU(&DT, DomTreeUpdater::UpdateStrategy::Eager);
744 (void)changeToUnreachable(I: BI, /*PreserveLCSSA*/ true, DTU: &DTU, MSSAU: MSSAU.get());
745 return;
746 }
747 if (auto *BI = dyn_cast<CondBrInst>(Val: Latch->getTerminator())) {
748 // Conditional latch/exit - note that latch can be shared by inner
749 // and outer loop so the other target doesn't need to an exit
750 if (L->isLoopExiting(BB: Latch)) {
751 // TODO: Generalize ConstantFoldTerminator so that it can be used
752 // here without invalidating LCSSA or MemorySSA. (Tricky case for
753 // LCSSA: header is an exit block of a preceeding sibling loop w/o
754 // dedicated exits.)
755 const unsigned ExitIdx = L->contains(BB: BI->getSuccessor(i: 0)) ? 1 : 0;
756 BasicBlock *ExitBB = BI->getSuccessor(i: ExitIdx);
757
758 DomTreeUpdater DTU(&DT, DomTreeUpdater::UpdateStrategy::Eager);
759 Header->removePredecessor(Pred: Latch, KeepOneInputPHIs: true);
760
761 IRBuilder<> Builder(BI);
762 auto *NewBI = Builder.CreateBr(Dest: ExitBB);
763 // Transfer the metadata to the new branch instruction (minus the
764 // loop info since this is no longer a loop)
765 NewBI->copyMetadata(SrcInst: *BI, WL: {LLVMContext::MD_dbg,
766 LLVMContext::MD_annotation});
767
768 BI->eraseFromParent();
769 DTU.applyUpdates(Updates: {{DominatorTree::Delete, Latch, Header}});
770 if (MSSA)
771 MSSAU->applyUpdates(Updates: {{DominatorTree::Delete, Latch, Header}}, DT);
772 return;
773 }
774 }
775
776 // General case. By splitting the backedge, and then explicitly making it
777 // unreachable we gracefully handle corner cases such as switch and invoke
778 // termiantors.
779 auto *BackedgeBB = SplitEdge(From: Latch, To: Header, DT: &DT, LI: &LI, MSSAU: MSSAU.get());
780
781 DomTreeUpdater DTU(&DT, DomTreeUpdater::UpdateStrategy::Eager);
782 (void)changeToUnreachable(I: BackedgeBB->getTerminator(),
783 /*PreserveLCSSA*/ true, DTU: &DTU, MSSAU: MSSAU.get());
784 }();
785
786 // Erase (and destroy) this loop instance. Handles relinking sub-loops
787 // and blocks within the loop as needed.
788 LI.erase(L);
789
790 // If the loop we broke had a parent, then changeToUnreachable might have
791 // caused a block to be removed from the parent loop (see loop_nest_lcssa
792 // test case in zero-btc.ll for an example), thus changing the parent's
793 // exit blocks. If that happened, we need to rebuild LCSSA on the outermost
794 // loop which might have a had a block removed.
795 if (OutermostLoop != L)
796 formLCSSARecursively(L&: *OutermostLoop, DT, LI: &LI, SE: &SE);
797}
798
799
800/// Checks if \p L has an exiting latch branch. There may also be other
801/// exiting blocks. Returns branch instruction terminating the loop
802/// latch if above check is successful, nullptr otherwise.
803static CondBrInst *getExpectedExitLoopLatchBranch(Loop *L) {
804 BasicBlock *Latch = L->getLoopLatch();
805 if (!Latch)
806 return nullptr;
807
808 CondBrInst *LatchBR = dyn_cast<CondBrInst>(Val: Latch->getTerminator());
809 if (!LatchBR || !L->isLoopExiting(BB: Latch))
810 return nullptr;
811
812 assert((LatchBR->getSuccessor(0) == L->getHeader() ||
813 LatchBR->getSuccessor(1) == L->getHeader()) &&
814 "At least one edge out of the latch must go to the header");
815
816 return LatchBR;
817}
818
819struct DbgLoop {
820 const Loop *L;
821 explicit DbgLoop(const Loop *L) : L(L) {}
822};
823
824#ifndef NDEBUG
825static inline raw_ostream &operator<<(raw_ostream &OS, DbgLoop D) {
826 OS << "function ";
827 D.L->getHeader()->getParent()->printAsOperand(OS, /*PrintType=*/false);
828 return OS << " " << *D.L;
829}
830#endif // NDEBUG
831
832static std::optional<unsigned> estimateLoopTripCount(Loop *L) {
833 // Currently we take the estimate exit count only from the loop latch,
834 // ignoring other exiting blocks. This can overestimate the trip count
835 // if we exit through another exit, but can never underestimate it.
836 // TODO: incorporate information from other exits
837 CondBrInst *ExitingBranch = getExpectedExitLoopLatchBranch(L);
838 if (!ExitingBranch) {
839 LLVM_DEBUG(dbgs() << "estimateLoopTripCount: Failed to find exiting "
840 << "latch branch of required form in " << DbgLoop(L)
841 << "\n");
842 return std::nullopt;
843 }
844
845 // To estimate the number of times the loop body was executed, we want to
846 // know the number of times the backedge was taken, vs. the number of times
847 // we exited the loop.
848 uint64_t LoopWeight, ExitWeight;
849 if (!extractBranchWeights(I: *ExitingBranch, TrueVal&: LoopWeight, FalseVal&: ExitWeight)) {
850 LLVM_DEBUG(dbgs() << "estimateLoopTripCount: Failed to extract branch "
851 << "weights for " << DbgLoop(L) << "\n");
852 return std::nullopt;
853 }
854
855 if (L->contains(BB: ExitingBranch->getSuccessor(i: 1)))
856 std::swap(a&: LoopWeight, b&: ExitWeight);
857
858 if (!ExitWeight) {
859 // Don't have a way to return predicated infinite
860 LLVM_DEBUG(dbgs() << "estimateLoopTripCount: Failed because of zero exit "
861 << "probability for " << DbgLoop(L) << "\n");
862 return std::nullopt;
863 }
864
865 // Estimated exit count is a ratio of the loop weight by the weight of the
866 // edge exiting the loop, rounded to nearest.
867 uint64_t ExitCount = llvm::divideNearest(Numerator: LoopWeight, Denominator: ExitWeight);
868
869 // When ExitCount + 1 would wrap in unsigned, saturate at UINT_MAX.
870 if (ExitCount >= std::numeric_limits<unsigned>::max())
871 return std::numeric_limits<unsigned>::max();
872
873 // Estimated trip count is one plus estimated exit count.
874 uint64_t TC = ExitCount + 1;
875 LLVM_DEBUG(dbgs() << "estimateLoopTripCount: Estimated trip count of " << TC
876 << " for " << DbgLoop(L) << "\n");
877 return TC;
878}
879
880std::optional<unsigned>
881llvm::getLoopEstimatedTripCount(Loop *L,
882 unsigned *EstimatedLoopInvocationWeight) {
883 // If EstimatedLoopInvocationWeight, we do not support this loop if
884 // getExpectedExitLoopLatchBranch returns nullptr.
885 //
886 // FIXME: Also, this is a stop-gap solution for nested loops. It avoids
887 // mistaking LLVMLoopEstimatedTripCount metadata to be for an outer loop when
888 // it was created for an inner loop. The problem is that loop metadata is
889 // attached to the branch instruction in the loop latch block, but that can be
890 // shared by the loops. A solution is to attach loop metadata to loop headers
891 // instead, but that would be a large change to LLVM.
892 //
893 // Until that happens, we work around the problem as follows.
894 // getExpectedExitLoopLatchBranch (which also guards
895 // setLoopEstimatedTripCount) returns nullptr for a loop unless the loop has
896 // one latch and that latch has exactly two successors one of which is an exit
897 // from the loop. If the latch is shared by nested loops, then that condition
898 // might hold for the inner loop but cannot hold for the outer loop:
899 // - Because the latch is shared, it must have at least two successors: the
900 // inner loop header and the outer loop header, which is also an exit for
901 // the inner loop. That satisifies the condition for the inner loop.
902 // - To satsify the condition for the outer loop, the latch must have a third
903 // successor that is an exit for the outer loop. But that violates the
904 // condition for both loops.
905 CondBrInst *ExitingBranch = getExpectedExitLoopLatchBranch(L);
906 if (!ExitingBranch)
907 return std::nullopt;
908
909 // If requested, either compute *EstimatedLoopInvocationWeight or return
910 // nullopt if cannot.
911 //
912 // TODO: Eventually, once all passes have migrated away from setting branch
913 // weights to indicate estimated trip counts, this function will drop the
914 // EstimatedLoopInvocationWeight parameter.
915 if (EstimatedLoopInvocationWeight) {
916 uint64_t LoopWeight = 0, ExitWeight = 0; // Inits expected to be unused.
917 if (!extractBranchWeights(I: *ExitingBranch, TrueVal&: LoopWeight, FalseVal&: ExitWeight))
918 return std::nullopt;
919 if (L->contains(BB: ExitingBranch->getSuccessor(i: 1)))
920 std::swap(a&: LoopWeight, b&: ExitWeight);
921 if (!ExitWeight)
922 return std::nullopt;
923 *EstimatedLoopInvocationWeight = ExitWeight;
924 }
925
926 // Return the estimated trip count from metadata unless the metadata is
927 // missing or has no value.
928 //
929 // Some passes set llvm.loop.estimated_trip_count to 0. For example, after
930 // peeling 10 or more iterations from a loop with an estimated trip count of
931 // 10, llvm.loop.estimated_trip_count becomes 0 on the remaining loop. It
932 // indicates that, each time execution reaches the peeled iterations,
933 // execution is estimated to exit them without reaching the remaining loop's
934 // header.
935 //
936 // Even if the probability of reaching a loop's header is low, if it is
937 // reached, it is the start of an iteration. Consequently, some passes
938 // historically assume that llvm::getLoopEstimatedTripCount always returns a
939 // positive count or std::nullopt. Thus, return std::nullopt when
940 // llvm.loop.estimated_trip_count is 0.
941 if (std::optional<unsigned> TC =
942 getOptionalIntLoopAttribute(TheLoop: L, Name: LLVMLoopEstimatedTripCount)) {
943 LLVM_DEBUG(dbgs() << "getLoopEstimatedTripCount: "
944 << LLVMLoopEstimatedTripCount << " metadata has trip "
945 << "count of " << *TC
946 << (*TC == 0 ? " (returning std::nullopt)" : "")
947 << " for " << DbgLoop(L) << "\n");
948 return *TC == 0 ? std::nullopt : TC;
949 }
950
951 // Estimate the trip count from latch branch weights.
952 return estimateLoopTripCount(L);
953}
954
955bool llvm::setLoopEstimatedTripCount(
956 Loop *L, unsigned EstimatedTripCount,
957 std::optional<unsigned> EstimatedloopInvocationWeight) {
958 // If EstimatedLoopInvocationWeight, we do not support this loop if
959 // getExpectedExitLoopLatchBranch returns nullptr.
960 //
961 // FIXME: See comments in getLoopEstimatedTripCount for why this is required
962 // here regardless of EstimatedLoopInvocationWeight.
963 CondBrInst *LatchBranch = getExpectedExitLoopLatchBranch(L);
964 if (!LatchBranch)
965 return false;
966
967 // Set the metadata.
968 addStringMetadataToLoop(TheLoop: L, StringMD: LLVMLoopEstimatedTripCount, V: EstimatedTripCount);
969
970 // At the moment, we currently support changing the estimated trip count in
971 // the latch branch's branch weights only. We could extend this API to
972 // manipulate estimated trip counts for any exit.
973 //
974 // TODO: Eventually, once all passes have migrated away from setting branch
975 // weights to indicate estimated trip counts, we will not set branch weights
976 // here at all.
977 if (!EstimatedloopInvocationWeight)
978 return true;
979
980 // Calculate taken and exit weights.
981 unsigned LatchExitWeight = ProfcheckDisableMetadataFixes ? 0 : 1;
982 unsigned BackedgeTakenWeight = 0;
983
984 if (EstimatedTripCount != 0) {
985 LatchExitWeight = *EstimatedloopInvocationWeight;
986 BackedgeTakenWeight = (EstimatedTripCount - 1) * LatchExitWeight;
987 }
988
989 // Make a swap if back edge is taken when condition is "false".
990 if (LatchBranch->getSuccessor(i: 0) != L->getHeader())
991 std::swap(a&: BackedgeTakenWeight, b&: LatchExitWeight);
992
993 // Set/Update profile metadata.
994 setBranchWeights(I&: *LatchBranch, Weights: {BackedgeTakenWeight, LatchExitWeight},
995 /*IsExpected=*/false);
996
997 return true;
998}
999
1000BranchProbability llvm::getLoopProbability(Loop *L) {
1001 CondBrInst *LatchBranch = getExpectedExitLoopLatchBranch(L);
1002 if (!LatchBranch)
1003 return BranchProbability::getUnknown();
1004 bool FirstTargetIsLoop = LatchBranch->getSuccessor(i: 0) == L->getHeader();
1005 return getBranchProbability(B: LatchBranch, ForFirstTarget: FirstTargetIsLoop);
1006}
1007
1008bool llvm::setLoopProbability(Loop *L, BranchProbability P) {
1009 CondBrInst *LatchBranch = getExpectedExitLoopLatchBranch(L);
1010 if (!LatchBranch)
1011 return false;
1012 bool FirstTargetIsLoop = LatchBranch->getSuccessor(i: 0) == L->getHeader();
1013 setBranchProbability(B: LatchBranch, P, ForFirstTarget: FirstTargetIsLoop);
1014 return true;
1015}
1016
1017BranchProbability llvm::getBranchProbability(CondBrInst *B,
1018 bool ForFirstTarget) {
1019 uint64_t Weight0, Weight1;
1020 if (!extractBranchWeights(I: *B, TrueVal&: Weight0, FalseVal&: Weight1))
1021 return BranchProbability::getUnknown();
1022 uint64_t Denominator = Weight0 + Weight1;
1023 if (Denominator == 0)
1024 return BranchProbability::getUnknown();
1025 if (!ForFirstTarget)
1026 std::swap(a&: Weight0, b&: Weight1);
1027 return BranchProbability::getBranchProbability(Numerator: Weight0, Denominator);
1028}
1029
1030BranchProbability llvm::getBranchProbability(BasicBlock *Src, BasicBlock *Dst) {
1031 assert(Src != Dst && "Passed in same source as destination");
1032
1033 Instruction *TI = Src->getTerminator();
1034 if (!TI || TI->getNumSuccessors() == 0)
1035 return BranchProbability::getZero();
1036
1037 SmallVector<uint32_t, 4> Weights;
1038
1039 if (!extractBranchWeights(I: *TI, Weights)) {
1040 // No metadata
1041 return BranchProbability::getUnknown();
1042 }
1043 assert(TI->getNumSuccessors() == Weights.size() &&
1044 "Missing weights in branch_weights");
1045
1046 uint64_t Total = 0;
1047 uint32_t Numerator = 0;
1048 for (auto [i, Weight] : llvm::enumerate(First&: Weights)) {
1049 if (TI->getSuccessor(Idx: i) == Dst)
1050 Numerator += Weight;
1051 Total += Weight;
1052 }
1053
1054 // Total of edges might be 0 if the metadata is incorrect/set by hand
1055 // or missing. In such case return here to avoid division by 0 later on.
1056 // There might also be a case where the value of Total cannot fit into
1057 // uint32_t, in such case, just bail out.
1058 if (Total == 0 || Total > std::numeric_limits<uint32_t>::max())
1059 return BranchProbability::getUnknown();
1060
1061 return BranchProbability(Numerator, Total);
1062}
1063
1064void llvm::setBranchProbability(CondBrInst *B, BranchProbability P,
1065 bool ForFirstTarget) {
1066 BranchProbability Prob0 = P;
1067 BranchProbability Prob1 = P.getCompl();
1068 if (!ForFirstTarget)
1069 std::swap(a&: Prob0, b&: Prob1);
1070 setBranchWeights(I&: *B, Weights: {Prob0.getNumerator(), Prob1.getNumerator()},
1071 /*IsExpected=*/false);
1072}
1073
1074bool llvm::hasIterationCountInvariantInParent(Loop *InnerLoop,
1075 ScalarEvolution &SE) {
1076 Loop *OuterL = InnerLoop->getParentLoop();
1077 if (!OuterL)
1078 return true;
1079
1080 // Get the backedge taken count for the inner loop
1081 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
1082 const SCEV *InnerLoopBECountSC = SE.getExitCount(L: InnerLoop, ExitingBlock: InnerLoopLatch);
1083 if (isa<SCEVCouldNotCompute>(Val: InnerLoopBECountSC) ||
1084 !InnerLoopBECountSC->getType()->isIntegerTy())
1085 return false;
1086
1087 // Get whether count is invariant to the outer loop
1088 ScalarEvolution::LoopDisposition LD =
1089 SE.getLoopDisposition(S: InnerLoopBECountSC, L: OuterL);
1090 if (LD != ScalarEvolution::LoopInvariant)
1091 return false;
1092
1093 return true;
1094}
1095
1096constexpr Intrinsic::ID llvm::getReductionIntrinsicID(RecurKind RK) {
1097 switch (RK) {
1098 default:
1099 llvm_unreachable("Unexpected recurrence kind");
1100 case RecurKind::AddChainWithSubs:
1101 case RecurKind::Sub:
1102 case RecurKind::Add:
1103 return Intrinsic::vector_reduce_add;
1104 case RecurKind::Mul:
1105 return Intrinsic::vector_reduce_mul;
1106 case RecurKind::And:
1107 return Intrinsic::vector_reduce_and;
1108 case RecurKind::Or:
1109 return Intrinsic::vector_reduce_or;
1110 case RecurKind::Xor:
1111 return Intrinsic::vector_reduce_xor;
1112 case RecurKind::FMulAdd:
1113 case RecurKind::FAddChainWithSubs:
1114 case RecurKind::FSub:
1115 case RecurKind::FAdd:
1116 return Intrinsic::vector_reduce_fadd;
1117 case RecurKind::FMul:
1118 return Intrinsic::vector_reduce_fmul;
1119 case RecurKind::SMax:
1120 return Intrinsic::vector_reduce_smax;
1121 case RecurKind::SMin:
1122 return Intrinsic::vector_reduce_smin;
1123 case RecurKind::UMax:
1124 return Intrinsic::vector_reduce_umax;
1125 case RecurKind::UMin:
1126 return Intrinsic::vector_reduce_umin;
1127 case RecurKind::FMax:
1128 case RecurKind::FMaxNum:
1129 return Intrinsic::vector_reduce_fmax;
1130 case RecurKind::FMin:
1131 case RecurKind::FMinNum:
1132 return Intrinsic::vector_reduce_fmin;
1133 case RecurKind::FMaximum:
1134 return Intrinsic::vector_reduce_fmaximum;
1135 case RecurKind::FMinimum:
1136 return Intrinsic::vector_reduce_fminimum;
1137 case RecurKind::FMaximumNum:
1138 return Intrinsic::vector_reduce_fmax;
1139 case RecurKind::FMinimumNum:
1140 return Intrinsic::vector_reduce_fmin;
1141 }
1142}
1143
1144Intrinsic::ID llvm::getMinMaxReductionIntrinsicID(Intrinsic::ID IID) {
1145 switch (IID) {
1146 default:
1147 llvm_unreachable("Unexpected intrinsic id");
1148 case Intrinsic::umin:
1149 return Intrinsic::vector_reduce_umin;
1150 case Intrinsic::umax:
1151 return Intrinsic::vector_reduce_umax;
1152 case Intrinsic::smin:
1153 return Intrinsic::vector_reduce_smin;
1154 case Intrinsic::smax:
1155 return Intrinsic::vector_reduce_smax;
1156 }
1157}
1158
1159// This is the inverse to getReductionForBinop
1160unsigned llvm::getArithmeticReductionInstruction(Intrinsic::ID RdxID) {
1161 switch (RdxID) {
1162 case Intrinsic::vector_reduce_fadd:
1163 return Instruction::FAdd;
1164 case Intrinsic::vector_reduce_fmul:
1165 return Instruction::FMul;
1166 case Intrinsic::vector_reduce_add:
1167 return Instruction::Add;
1168 case Intrinsic::vector_reduce_mul:
1169 return Instruction::Mul;
1170 case Intrinsic::vector_reduce_and:
1171 return Instruction::And;
1172 case Intrinsic::vector_reduce_or:
1173 return Instruction::Or;
1174 case Intrinsic::vector_reduce_xor:
1175 return Instruction::Xor;
1176 case Intrinsic::vector_reduce_smax:
1177 case Intrinsic::vector_reduce_smin:
1178 case Intrinsic::vector_reduce_umax:
1179 case Intrinsic::vector_reduce_umin:
1180 return Instruction::ICmp;
1181 case Intrinsic::vector_reduce_fmax:
1182 case Intrinsic::vector_reduce_fmin:
1183 case Intrinsic::vector_reduce_fmaximum:
1184 case Intrinsic::vector_reduce_fminimum:
1185 return Instruction::FCmp;
1186 default:
1187 llvm_unreachable("Unexpected ID");
1188 }
1189}
1190
1191// This is the inverse to getArithmeticReductionInstruction
1192Intrinsic::ID llvm::getReductionForBinop(Instruction::BinaryOps Opc) {
1193 switch (Opc) {
1194 default:
1195 break;
1196 case Instruction::Add:
1197 return Intrinsic::vector_reduce_add;
1198 case Instruction::Mul:
1199 return Intrinsic::vector_reduce_mul;
1200 case Instruction::And:
1201 return Intrinsic::vector_reduce_and;
1202 case Instruction::Or:
1203 return Intrinsic::vector_reduce_or;
1204 case Instruction::Xor:
1205 return Intrinsic::vector_reduce_xor;
1206 case Instruction::FAdd:
1207 return Intrinsic::vector_reduce_fadd;
1208 case Instruction::FMul:
1209 return Intrinsic::vector_reduce_fmul;
1210 }
1211 return Intrinsic::not_intrinsic;
1212}
1213
1214Intrinsic::ID llvm::getMinMaxReductionIntrinsicOp(Intrinsic::ID RdxID) {
1215 switch (RdxID) {
1216 default:
1217 llvm_unreachable("Unknown min/max recurrence kind");
1218 case Intrinsic::vector_reduce_umin:
1219 return Intrinsic::umin;
1220 case Intrinsic::vector_reduce_umax:
1221 return Intrinsic::umax;
1222 case Intrinsic::vector_reduce_smin:
1223 return Intrinsic::smin;
1224 case Intrinsic::vector_reduce_smax:
1225 return Intrinsic::smax;
1226 case Intrinsic::vector_reduce_fmin:
1227 return Intrinsic::minnum;
1228 case Intrinsic::vector_reduce_fmax:
1229 return Intrinsic::maxnum;
1230 case Intrinsic::vector_reduce_fminimum:
1231 return Intrinsic::minimum;
1232 case Intrinsic::vector_reduce_fmaximum:
1233 return Intrinsic::maximum;
1234 }
1235}
1236
1237Intrinsic::ID llvm::getMinMaxReductionIntrinsicOp(RecurKind RK) {
1238 switch (RK) {
1239 default:
1240 llvm_unreachable("Unknown min/max recurrence kind");
1241 case RecurKind::UMin:
1242 return Intrinsic::umin;
1243 case RecurKind::UMax:
1244 return Intrinsic::umax;
1245 case RecurKind::SMin:
1246 return Intrinsic::smin;
1247 case RecurKind::SMax:
1248 return Intrinsic::smax;
1249 case RecurKind::FMin:
1250 case RecurKind::FMinNum:
1251 return Intrinsic::minnum;
1252 case RecurKind::FMax:
1253 case RecurKind::FMaxNum:
1254 return Intrinsic::maxnum;
1255 case RecurKind::FMinimum:
1256 return Intrinsic::minimum;
1257 case RecurKind::FMaximum:
1258 return Intrinsic::maximum;
1259 case RecurKind::FMinimumNum:
1260 return Intrinsic::minimumnum;
1261 case RecurKind::FMaximumNum:
1262 return Intrinsic::maximumnum;
1263 }
1264}
1265
1266RecurKind llvm::getMinMaxReductionRecurKind(Intrinsic::ID RdxID) {
1267 switch (RdxID) {
1268 case Intrinsic::vector_reduce_smax:
1269 return RecurKind::SMax;
1270 case Intrinsic::vector_reduce_smin:
1271 return RecurKind::SMin;
1272 case Intrinsic::vector_reduce_umax:
1273 return RecurKind::UMax;
1274 case Intrinsic::vector_reduce_umin:
1275 return RecurKind::UMin;
1276 case Intrinsic::vector_reduce_fmax:
1277 return RecurKind::FMax;
1278 case Intrinsic::vector_reduce_fmin:
1279 return RecurKind::FMin;
1280 case Intrinsic::vector_reduce_fmaximum:
1281 return RecurKind::FMaximum;
1282 case Intrinsic::vector_reduce_fminimum:
1283 return RecurKind::FMinimum;
1284 default:
1285 return RecurKind::None;
1286 }
1287}
1288
1289CmpInst::Predicate llvm::getMinMaxReductionPredicate(RecurKind RK) {
1290 switch (RK) {
1291 default:
1292 llvm_unreachable("Unknown min/max recurrence kind");
1293 case RecurKind::UMin:
1294 return CmpInst::ICMP_ULT;
1295 case RecurKind::UMax:
1296 return CmpInst::ICMP_UGT;
1297 case RecurKind::SMin:
1298 return CmpInst::ICMP_SLT;
1299 case RecurKind::SMax:
1300 return CmpInst::ICMP_SGT;
1301 case RecurKind::FMin:
1302 return CmpInst::FCMP_OLT;
1303 case RecurKind::FMax:
1304 return CmpInst::FCMP_OGT;
1305 // We do not add FMinimum/FMaximum recurrence kind here since there is no
1306 // equivalent predicate which compares signed zeroes according to the
1307 // semantics of the intrinsics (llvm.minimum/maximum).
1308 }
1309}
1310
1311Value *llvm::createMinMaxOp(IRBuilderBase &Builder, RecurKind RK, Value *Left,
1312 Value *Right) {
1313 Type *Ty = Left->getType();
1314 if (Ty->isIntOrIntVectorTy() ||
1315 (RK == RecurKind::FMinNum || RK == RecurKind::FMaxNum ||
1316 RK == RecurKind::FMinimum || RK == RecurKind::FMaximum ||
1317 RK == RecurKind::FMinimumNum || RK == RecurKind::FMaximumNum)) {
1318 Intrinsic::ID Id = getMinMaxReductionIntrinsicOp(RK);
1319 return Builder.CreateIntrinsic(RetTy: Ty, ID: Id, Args: {Left, Right}, FMFSource: nullptr,
1320 Name: "rdx.minmax");
1321 }
1322 CmpInst::Predicate Pred = getMinMaxReductionPredicate(RK);
1323 Value *Cmp = Builder.CreateCmp(Pred, LHS: Left, RHS: Right, Name: "rdx.minmax.cmp");
1324 Value *Select = Builder.CreateSelect(C: Cmp, True: Left, False: Right, Name: "rdx.minmax.select");
1325 // This select is synthesized fresh, not lowered from an existing branch, so
1326 // it carries no real profile. Mark its weights as explicitly unknown.
1327 if (auto *SI = dyn_cast<SelectInst>(Val: Select))
1328 setExplicitlyUnknownBranchWeightsIfProfiled(I&: *SI, DEBUG_TYPE);
1329 return Select;
1330}
1331
1332// Helper to generate an ordered reduction.
1333Value *llvm::getOrderedReduction(IRBuilderBase &Builder, Value *Acc, Value *Src,
1334 unsigned Op, RecurKind RdxKind) {
1335 unsigned VF = cast<FixedVectorType>(Val: Src->getType())->getNumElements();
1336
1337 // Extract and apply reduction ops in ascending order:
1338 // e.g. ((((Acc + Scl[0]) + Scl[1]) + Scl[2]) + ) ... + Scl[VF-1]
1339 Value *Result = Acc;
1340 for (unsigned ExtractIdx = 0; ExtractIdx != VF; ++ExtractIdx) {
1341 Value *Ext =
1342 Builder.CreateExtractElement(Vec: Src, Idx: Builder.getInt32(C: ExtractIdx));
1343
1344 if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
1345 Result = Builder.CreateBinOp(Opc: (Instruction::BinaryOps)Op, LHS: Result, RHS: Ext,
1346 Name: "bin.rdx");
1347 } else {
1348 assert(RecurrenceDescriptor::isMinMaxRecurrenceKind(RdxKind) &&
1349 "Invalid min/max");
1350 Result = createMinMaxOp(Builder, RK: RdxKind, Left: Result, Right: Ext);
1351 }
1352 }
1353
1354 return Result;
1355}
1356
1357Value *llvm::expandReductionViaLoop(IRBuilderBase &Builder, Value *Vec,
1358 unsigned RdxOpcode, Value *Acc,
1359 DominatorTree *DT, LoopInfo *LI) {
1360 auto *VTy = cast<VectorType>(Val: Vec->getType());
1361 Type *EltTy = VTy->getElementType();
1362 Function *F = Builder.GetInsertBlock()->getParent();
1363
1364 const DataLayout &DL = F->getDataLayout();
1365 Type *IdxTy = DL.getIndexType(C&: EltTy->getContext(), AddressSpace: 0);
1366 unsigned MinElts = VTy->getElementCount().getKnownMinValue();
1367 Value *NumElts = Builder.CreateVScale(Ty: IdxTy);
1368 NumElts = Builder.CreateMul(LHS: NumElts, RHS: ConstantInt::get(Ty: IdxTy, V: MinElts));
1369
1370 BasicBlock *EntryBB = Builder.GetInsertBlock();
1371 BasicBlock *LoopBB = BasicBlock::Create(Context&: F->getContext(), Name: "rdx.loop", Parent: F);
1372 BasicBlock *ExitBB = SplitBlock(Old: EntryBB, SplitPt: Builder.GetInsertPoint(), DT, LI,
1373 MSSAU: nullptr, BBName: "rdx.exit");
1374
1375 EntryBB->getTerminator()->eraseFromParent();
1376 Builder.SetInsertPoint(EntryBB);
1377 Builder.CreateBr(Dest: LoopBB);
1378
1379 Builder.SetInsertPoint(LoopBB);
1380 PHINode *IV = Builder.CreatePHI(Ty: IdxTy, NumReservedValues: 2, Name: "rdx.iv");
1381 PHINode *AccPhi = Builder.CreatePHI(Ty: EltTy, NumReservedValues: 2, Name: "rdx.acc");
1382 IV->addIncoming(V: ConstantInt::get(Ty: IdxTy, V: 0), BB: EntryBB);
1383 AccPhi->addIncoming(V: Acc, BB: EntryBB);
1384
1385 Value *Elt = Builder.CreateExtractElement(Vec, Idx: IV);
1386 Value *Res = Builder.CreateBinOp(Opc: (Instruction::BinaryOps)RdxOpcode, LHS: AccPhi,
1387 RHS: Elt, Name: "rdx.op");
1388
1389 Value *NextIV =
1390 Builder.CreateNUWAdd(LHS: IV, RHS: ConstantInt::get(Ty: IdxTy, V: 1), Name: "rdx.next");
1391 IV->addIncoming(V: NextIV, BB: LoopBB);
1392 AccPhi->addIncoming(V: Res, BB: LoopBB);
1393
1394 Value *Done = Builder.CreateICmpEQ(LHS: NextIV, RHS: NumElts, Name: "rdx.done");
1395 Builder.CreateCondBr(Cond: Done, True: ExitBB, False: LoopBB);
1396
1397 // SplitBlock above updated DT/LI for EntryBB -> ExitBB. Now update
1398 // for replacing that edge with EntryBB -> LoopBB -> {ExitBB, LoopBB}.
1399 if (DT)
1400 DT->applyUpdates(Updates: {{DominatorTree::Insert, EntryBB, LoopBB},
1401 {DominatorTree::Insert, LoopBB, LoopBB},
1402 {DominatorTree::Insert, LoopBB, ExitBB},
1403 {DominatorTree::Delete, EntryBB, ExitBB}});
1404
1405 if (LI) {
1406 Loop *NewLoop = LI->AllocateLoop();
1407 if (Loop *ParentLoop = LI->getLoopFor(BB: EntryBB))
1408 ParentLoop->addChildLoop(NewChild: NewLoop);
1409 else
1410 LI->addTopLevelLoop(New: NewLoop);
1411 NewLoop->addBasicBlockToLoop(NewBB: LoopBB, LI&: *LI);
1412 }
1413
1414 Builder.SetInsertPoint(TheBB: ExitBB, IP: ExitBB->begin());
1415 return Res;
1416}
1417
1418// Helper to generate a log2 shuffle reduction.
1419Value *llvm::getShuffleReduction(IRBuilderBase &Builder, Value *Src,
1420 unsigned Op,
1421 TargetTransformInfo::ReductionShuffle RS,
1422 RecurKind RdxKind) {
1423 unsigned VF = cast<FixedVectorType>(Val: Src->getType())->getNumElements();
1424 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
1425 // and vector ops, reducing the set of values being computed by half each
1426 // round.
1427 assert(isPowerOf2_32(VF) &&
1428 "Reduction emission only supported for pow2 vectors!");
1429 // Note: fast-math-flags flags are controlled by the builder configuration
1430 // and are assumed to apply to all generated arithmetic instructions. Other
1431 // poison generating flags (nsw/nuw/inbounds/inrange/exact) are not part
1432 // of the builder configuration, and since they're not passed explicitly,
1433 // will never be relevant here. Note that it would be generally unsound to
1434 // propagate these from an intrinsic call to the expansion anyways as we/
1435 // change the order of operations.
1436 auto BuildShuffledOp = [&Builder, &Op,
1437 &RdxKind](SmallVectorImpl<int> &ShuffleMask,
1438 Value *&TmpVec) -> void {
1439 Value *Shuf = Builder.CreateShuffleVector(V: TmpVec, Mask: ShuffleMask, Name: "rdx.shuf");
1440 if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
1441 TmpVec = Builder.CreateBinOp(Opc: (Instruction::BinaryOps)Op, LHS: TmpVec, RHS: Shuf,
1442 Name: "bin.rdx");
1443 } else {
1444 assert(RecurrenceDescriptor::isMinMaxRecurrenceKind(RdxKind) &&
1445 "Invalid min/max");
1446 TmpVec = createMinMaxOp(Builder, RK: RdxKind, Left: TmpVec, Right: Shuf);
1447 }
1448 };
1449
1450 Value *TmpVec = Src;
1451 if (TargetTransformInfo::ReductionShuffle::Pairwise == RS) {
1452 SmallVector<int, 32> ShuffleMask(VF);
1453 for (unsigned stride = 1; stride < VF; stride <<= 1) {
1454 // Initialise the mask with undef.
1455 llvm::fill(Range&: ShuffleMask, Value: -1);
1456 for (unsigned j = 0; j < VF; j += stride << 1) {
1457 ShuffleMask[j] = j + stride;
1458 }
1459 BuildShuffledOp(ShuffleMask, TmpVec);
1460 }
1461 } else {
1462 SmallVector<int, 32> ShuffleMask(VF);
1463 for (unsigned i = VF; i != 1; i >>= 1) {
1464 // Move the upper half of the vector to the lower half.
1465 for (unsigned j = 0; j != i / 2; ++j)
1466 ShuffleMask[j] = i / 2 + j;
1467
1468 // Fill the rest of the mask with undef.
1469 std::fill(first: &ShuffleMask[i / 2], last: ShuffleMask.end(), value: -1);
1470 BuildShuffledOp(ShuffleMask, TmpVec);
1471 }
1472 }
1473 // The result is in the first element of the vector.
1474 return Builder.CreateExtractElement(Vec: TmpVec, Idx: Builder.getInt32(C: 0));
1475}
1476
1477Value *llvm::createAnyOfReduction(IRBuilderBase &Builder, Value *Src,
1478 Value *InitVal, PHINode *OrigPhi) {
1479 Value *NewVal = nullptr;
1480
1481 // First use the original phi to determine the new value we're trying to
1482 // select from in the loop.
1483 SelectInst *SI = nullptr;
1484 for (auto *U : OrigPhi->users()) {
1485 if ((SI = dyn_cast<SelectInst>(Val: U)))
1486 break;
1487 }
1488 assert(SI && "One user of the original phi should be a select");
1489
1490 if (SI->getTrueValue() == OrigPhi)
1491 NewVal = SI->getFalseValue();
1492 else {
1493 assert(SI->getFalseValue() == OrigPhi &&
1494 "At least one input to the select should be the original Phi");
1495 NewVal = SI->getTrueValue();
1496 }
1497
1498 // If any predicate is true it means that we want to select the new value.
1499 Value *AnyOf =
1500 Src->getType()->isVectorTy() ? Builder.CreateOrReduce(Src) : Src;
1501 // The compares in the loop may yield poison, which propagates through the
1502 // bitwise ORs. Freeze it here before the condition is used.
1503 AnyOf = Builder.CreateFreeze(V: AnyOf);
1504 return Builder.CreateSelect(C: AnyOf, True: NewVal, False: InitVal, Name: "rdx.select");
1505}
1506
1507Value *llvm::getReductionIdentity(Intrinsic::ID RdxID, Type *Ty,
1508 FastMathFlags Flags) {
1509 bool Negative = false;
1510 switch (RdxID) {
1511 default:
1512 llvm_unreachable("Expecting a reduction intrinsic");
1513 case Intrinsic::vector_reduce_add:
1514 case Intrinsic::vector_reduce_mul:
1515 case Intrinsic::vector_reduce_or:
1516 case Intrinsic::vector_reduce_xor:
1517 case Intrinsic::vector_reduce_and:
1518 case Intrinsic::vector_reduce_fadd:
1519 case Intrinsic::vector_reduce_fmul: {
1520 unsigned Opc = getArithmeticReductionInstruction(RdxID);
1521 return ConstantExpr::getBinOpIdentity(Opcode: Opc, Ty, AllowRHSConstant: false,
1522 NSZ: Flags.noSignedZeros());
1523 }
1524 case Intrinsic::vector_reduce_umax:
1525 case Intrinsic::vector_reduce_umin:
1526 case Intrinsic::vector_reduce_smin:
1527 case Intrinsic::vector_reduce_smax: {
1528 Intrinsic::ID ScalarID = getMinMaxReductionIntrinsicOp(RdxID);
1529 return ConstantExpr::getIntrinsicIdentity(ScalarID, Ty);
1530 }
1531 case Intrinsic::vector_reduce_fmax:
1532 case Intrinsic::vector_reduce_fmaximum:
1533 Negative = true;
1534 [[fallthrough]];
1535 case Intrinsic::vector_reduce_fmin:
1536 case Intrinsic::vector_reduce_fminimum: {
1537 bool PropagatesNaN = RdxID == Intrinsic::vector_reduce_fminimum ||
1538 RdxID == Intrinsic::vector_reduce_fmaximum;
1539 const fltSemantics &Semantics = Ty->getFltSemantics();
1540 return (!Flags.noNaNs() && !PropagatesNaN)
1541 ? ConstantFP::getQNaN(Ty, Negative)
1542 : !Flags.noInfs()
1543 ? ConstantFP::getInfinity(Ty, Negative)
1544 : ConstantFP::get(Ty, V: APFloat::getLargest(Sem: Semantics, Negative));
1545 }
1546 }
1547}
1548
1549Value *llvm::getRecurrenceIdentity(RecurKind K, Type *Tp, FastMathFlags FMF) {
1550 assert((!(K == RecurKind::FMin || K == RecurKind::FMax) ||
1551 (FMF.noNaNs() && FMF.noSignedZeros())) &&
1552 "nnan, nsz is expected to be set for FP min/max reduction.");
1553 Intrinsic::ID RdxID = getReductionIntrinsicID(RK: K);
1554 return getReductionIdentity(RdxID, Ty: Tp, Flags: FMF);
1555}
1556
1557Value *llvm::createSimpleReduction(IRBuilderBase &Builder, Value *Src,
1558 RecurKind RdxKind) {
1559 auto *SrcVecEltTy = cast<VectorType>(Val: Src->getType())->getElementType();
1560 auto getIdentity = [&]() {
1561 return getRecurrenceIdentity(K: RdxKind, Tp: SrcVecEltTy,
1562 FMF: Builder.getFastMathFlags());
1563 };
1564 switch (RdxKind) {
1565 case RecurKind::AddChainWithSubs:
1566 case RecurKind::Sub:
1567 case RecurKind::Add:
1568 case RecurKind::Mul:
1569 case RecurKind::And:
1570 case RecurKind::Or:
1571 case RecurKind::Xor:
1572 case RecurKind::SMax:
1573 case RecurKind::SMin:
1574 case RecurKind::UMax:
1575 case RecurKind::UMin:
1576 case RecurKind::FMax:
1577 case RecurKind::FMin:
1578 case RecurKind::FMinNum:
1579 case RecurKind::FMaxNum:
1580 case RecurKind::FMinimum:
1581 case RecurKind::FMaximum:
1582 case RecurKind::FMinimumNum:
1583 case RecurKind::FMaximumNum:
1584 return Builder.CreateUnaryIntrinsic(ID: getReductionIntrinsicID(RK: RdxKind), Op: Src);
1585 case RecurKind::FMulAdd:
1586 case RecurKind::FAddChainWithSubs:
1587 case RecurKind::FSub:
1588 case RecurKind::FAdd:
1589 return Builder.CreateFAddReduce(Acc: getIdentity(), Src);
1590 case RecurKind::FMul:
1591 return Builder.CreateFMulReduce(Acc: getIdentity(), Src);
1592 default:
1593 llvm_unreachable("Unhandled opcode");
1594 }
1595}
1596
1597Value *llvm::createSimpleReduction(IRBuilderBase &Builder, Value *Src,
1598 RecurKind Kind, Value *Mask, Value *EVL) {
1599 assert(!RecurrenceDescriptor::isAnyOfRecurrenceKind(Kind) &&
1600 !RecurrenceDescriptor::isFindRecurrenceKind(Kind) &&
1601 "AnyOf and FindIV reductions are not supported.");
1602 Intrinsic::ID Id = getReductionIntrinsicID(RK: Kind);
1603 auto VPID = VPIntrinsic::getForIntrinsic(Id);
1604 assert(VPReductionIntrinsic::isVPReduction(VPID) &&
1605 "No VPIntrinsic for this reduction");
1606 auto *EltTy = cast<VectorType>(Val: Src->getType())->getElementType();
1607 Value *Iden = getRecurrenceIdentity(K: Kind, Tp: EltTy, FMF: Builder.getFastMathFlags());
1608 Value *Ops[] = {Iden, Src, Mask, EVL};
1609 return Builder.CreateIntrinsic(RetTy: EltTy, ID: VPID, Args: Ops);
1610}
1611
1612Value *llvm::createOrderedReduction(IRBuilderBase &B, RecurKind Kind,
1613 Value *Src, Value *Start) {
1614 assert((Kind == RecurKind::FAdd || Kind == RecurKind::FMulAdd) &&
1615 "Unexpected reduction kind");
1616 assert(Src->getType()->isVectorTy() && "Expected a vector type");
1617 assert(!Start->getType()->isVectorTy() && "Expected a scalar type");
1618
1619 return B.CreateFAddReduce(Acc: Start, Src);
1620}
1621
1622Value *llvm::createOrderedReduction(IRBuilderBase &Builder, RecurKind Kind,
1623 Value *Src, Value *Start, Value *Mask,
1624 Value *EVL) {
1625 assert((Kind == RecurKind::FAdd || Kind == RecurKind::FMulAdd) &&
1626 "Unexpected reduction kind");
1627 assert(Src->getType()->isVectorTy() && "Expected a vector type");
1628 assert(!Start->getType()->isVectorTy() && "Expected a scalar type");
1629
1630 Intrinsic::ID Id = getReductionIntrinsicID(RK: RecurKind::FAdd);
1631 auto VPID = VPIntrinsic::getForIntrinsic(Id);
1632 assert(VPReductionIntrinsic::isVPReduction(VPID) &&
1633 "No VPIntrinsic for this reduction");
1634 auto *EltTy = cast<VectorType>(Val: Src->getType())->getElementType();
1635 Value *Ops[] = {Start, Src, Mask, EVL};
1636 return Builder.CreateIntrinsic(RetTy: EltTy, ID: VPID, Args: Ops);
1637}
1638
1639void llvm::propagateIRFlags(Value *I, ArrayRef<Value *> VL, Value *OpValue,
1640 bool IncludeWrapFlags) {
1641 auto *VecOp = dyn_cast<Instruction>(Val: I);
1642 if (!VecOp)
1643 return;
1644 auto *Intersection = (OpValue == nullptr) ? dyn_cast<Instruction>(Val: VL[0])
1645 : dyn_cast<Instruction>(Val: OpValue);
1646 if (!Intersection)
1647 return;
1648 const unsigned Opcode = Intersection->getOpcode();
1649 VecOp->copyIRFlags(V: Intersection, IncludeWrapFlags);
1650 for (auto *V : VL) {
1651 auto *Instr = dyn_cast<Instruction>(Val: V);
1652 if (!Instr)
1653 continue;
1654 if (OpValue == nullptr || Opcode == Instr->getOpcode())
1655 VecOp->andIRFlags(V);
1656 }
1657}
1658
1659bool llvm::isKnownNegativeInLoop(const SCEV *S, const Loop *L,
1660 ScalarEvolution &SE) {
1661 const SCEV *Zero = SE.getZero(Ty: S->getType());
1662 return SE.isAvailableAtLoopEntry(S, L) &&
1663 SE.isLoopEntryGuardedByCond(L, Pred: ICmpInst::ICMP_SLT, LHS: S, RHS: Zero);
1664}
1665
1666bool llvm::isKnownNonNegativeInLoop(const SCEV *S, const Loop *L,
1667 ScalarEvolution &SE) {
1668 const SCEV *Zero = SE.getZero(Ty: S->getType());
1669 return SE.isAvailableAtLoopEntry(S, L) &&
1670 SE.isLoopEntryGuardedByCond(L, Pred: ICmpInst::ICMP_SGE, LHS: S, RHS: Zero);
1671}
1672
1673bool llvm::isKnownPositiveInLoop(const SCEV *S, const Loop *L,
1674 ScalarEvolution &SE) {
1675 const SCEV *Zero = SE.getZero(Ty: S->getType());
1676 return SE.isAvailableAtLoopEntry(S, L) &&
1677 SE.isLoopEntryGuardedByCond(L, Pred: ICmpInst::ICMP_SGT, LHS: S, RHS: Zero);
1678}
1679
1680bool llvm::isKnownNonPositiveInLoop(const SCEV *S, const Loop *L,
1681 ScalarEvolution &SE) {
1682 const SCEV *Zero = SE.getZero(Ty: S->getType());
1683 return SE.isAvailableAtLoopEntry(S, L) &&
1684 SE.isLoopEntryGuardedByCond(L, Pred: ICmpInst::ICMP_SLE, LHS: S, RHS: Zero);
1685}
1686
1687bool llvm::cannotBeMinInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE,
1688 bool Signed) {
1689 unsigned BitWidth = cast<IntegerType>(Val: S->getType())->getBitWidth();
1690 APInt Min = Signed ? APInt::getSignedMinValue(numBits: BitWidth) :
1691 APInt::getMinValue(numBits: BitWidth);
1692 auto Predicate = Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1693 return SE.isAvailableAtLoopEntry(S, L) &&
1694 SE.isLoopEntryGuardedByCond(L, Pred: Predicate, LHS: S,
1695 RHS: SE.getConstant(Val: Min));
1696}
1697
1698bool llvm::cannotBeMaxInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE,
1699 bool Signed) {
1700 unsigned BitWidth = cast<IntegerType>(Val: S->getType())->getBitWidth();
1701 APInt Max = Signed ? APInt::getSignedMaxValue(numBits: BitWidth) :
1702 APInt::getMaxValue(numBits: BitWidth);
1703 auto Predicate = Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1704 return SE.isAvailableAtLoopEntry(S, L) &&
1705 SE.isLoopEntryGuardedByCond(L, Pred: Predicate, LHS: S,
1706 RHS: SE.getConstant(Val: Max));
1707}
1708
1709//===----------------------------------------------------------------------===//
1710// rewriteLoopExitValues - Optimize IV users outside the loop.
1711// As a side effect, reduces the amount of IV processing within the loop.
1712//===----------------------------------------------------------------------===//
1713
1714static bool hasHardUserWithinLoop(const Loop *L, const Instruction *I) {
1715 SmallPtrSet<const Instruction *, 8> Visited;
1716 SmallVector<const Instruction *, 8> WorkList;
1717 Visited.insert(Ptr: I);
1718 WorkList.push_back(Elt: I);
1719 while (!WorkList.empty()) {
1720 const Instruction *Curr = WorkList.pop_back_val();
1721 // This use is outside the loop, nothing to do.
1722 if (!L->contains(Inst: Curr))
1723 continue;
1724 // Do we assume it is a "hard" use which will not be eliminated easily?
1725 if (Curr->mayHaveSideEffects())
1726 return true;
1727 // Otherwise, add all its users to worklist.
1728 for (const auto *U : Curr->users()) {
1729 auto *UI = cast<Instruction>(Val: U);
1730 if (Visited.insert(Ptr: UI).second)
1731 WorkList.push_back(Elt: UI);
1732 }
1733 }
1734 return false;
1735}
1736
1737// Collect information about PHI nodes which can be transformed in
1738// rewriteLoopExitValues.
1739struct RewritePhi {
1740 PHINode *PN; // For which PHI node is this replacement?
1741 unsigned Ith; // For which incoming value?
1742 const SCEV *ExpansionSCEV; // The SCEV of the incoming value we are rewriting.
1743 Instruction *ExpansionPoint; // Where we'd like to expand that SCEV?
1744 bool HighCost; // Is this expansion a high-cost?
1745
1746 RewritePhi(PHINode *P, unsigned I, const SCEV *Val, Instruction *ExpansionPt,
1747 bool H)
1748 : PN(P), Ith(I), ExpansionSCEV(Val), ExpansionPoint(ExpansionPt),
1749 HighCost(H) {}
1750};
1751
1752// Check whether it is possible to delete the loop after rewriting exit
1753// value. If it is possible, ignore ReplaceExitValue and do rewriting
1754// aggressively.
1755static bool canLoopBeDeleted(Loop *L, SmallVector<RewritePhi, 8> &RewritePhiSet) {
1756 BasicBlock *Preheader = L->getLoopPreheader();
1757 // If there is no preheader, the loop will not be deleted.
1758 if (!Preheader)
1759 return false;
1760
1761 // In LoopDeletion pass Loop can be deleted when ExitingBlocks.size() > 1.
1762 // We obviate multiple ExitingBlocks case for simplicity.
1763 // TODO: If we see testcase with multiple ExitingBlocks can be deleted
1764 // after exit value rewriting, we can enhance the logic here.
1765 SmallVector<BasicBlock *, 4> ExitingBlocks;
1766 L->getExitingBlocks(ExitingBlocks);
1767 SmallVector<BasicBlock *, 8> ExitBlocks;
1768 L->getUniqueExitBlocks(ExitBlocks);
1769 if (ExitBlocks.size() != 1 || ExitingBlocks.size() != 1)
1770 return false;
1771
1772 BasicBlock *ExitBlock = ExitBlocks[0];
1773 BasicBlock::iterator BI = ExitBlock->begin();
1774 while (PHINode *P = dyn_cast<PHINode>(Val&: BI)) {
1775 Value *Incoming = P->getIncomingValueForBlock(BB: ExitingBlocks[0]);
1776
1777 // If the Incoming value of P is found in RewritePhiSet, we know it
1778 // could be rewritten to use a loop invariant value in transformation
1779 // phase later. Skip it in the loop invariant check below.
1780 bool found = false;
1781 for (const RewritePhi &Phi : RewritePhiSet) {
1782 unsigned i = Phi.Ith;
1783 if (Phi.PN == P && (Phi.PN)->getIncomingValue(i) == Incoming) {
1784 found = true;
1785 break;
1786 }
1787 }
1788
1789 Instruction *I;
1790 if (!found && (I = dyn_cast<Instruction>(Val: Incoming)))
1791 if (!L->hasLoopInvariantOperands(I))
1792 return false;
1793
1794 ++BI;
1795 }
1796
1797 for (auto *BB : L->blocks())
1798 if (llvm::any_of(Range&: *BB, P: [](Instruction &I) {
1799 return I.mayHaveSideEffects();
1800 }))
1801 return false;
1802
1803 return true;
1804}
1805
1806/// Checks if it is safe to call InductionDescriptor::isInductionPHI for \p Phi,
1807/// and returns true if this Phi is an induction phi in the loop. When
1808/// isInductionPHI returns true, \p ID will be also be set by isInductionPHI.
1809static bool checkIsIndPhi(PHINode *Phi, Loop *L, ScalarEvolution *SE,
1810 InductionDescriptor &ID) {
1811 if (!Phi)
1812 return false;
1813 if (!L->getLoopPreheader())
1814 return false;
1815 if (Phi->getParent() != L->getHeader())
1816 return false;
1817 return InductionDescriptor::isInductionPHI(Phi, L, SE, D&: ID);
1818}
1819
1820int llvm::rewriteLoopExitValues(Loop *L, LoopInfo *LI, TargetLibraryInfo *TLI,
1821 ScalarEvolution *SE,
1822 const TargetTransformInfo *TTI,
1823 SCEVExpander &Rewriter, DominatorTree *DT,
1824 ReplaceExitVal ReplaceExitValue,
1825 SmallVector<WeakTrackingVH, 16> &DeadInsts) {
1826 // Check a pre-condition.
1827 assert(L->isRecursivelyLCSSAForm(*DT, *LI) &&
1828 "Caller did not preserve LCSSA!");
1829
1830 SmallVector<BasicBlock*, 8> ExitBlocks;
1831 L->getUniqueExitBlocks(ExitBlocks);
1832
1833 SmallVector<RewritePhi, 8> RewritePhiSet;
1834 // Find all values that are computed inside the loop, but used outside of it.
1835 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
1836 // the exit blocks of the loop to find them.
1837 for (BasicBlock *ExitBB : ExitBlocks) {
1838 // If there are no PHI nodes in this exit block, then no values defined
1839 // inside the loop are used on this path, skip it.
1840 PHINode *PN = dyn_cast<PHINode>(Val: ExitBB->begin());
1841 if (!PN) continue;
1842
1843 unsigned NumPreds = PN->getNumIncomingValues();
1844
1845 // Iterate over all of the PHI nodes.
1846 BasicBlock::iterator BBI = ExitBB->begin();
1847 while ((PN = dyn_cast<PHINode>(Val: BBI++))) {
1848 if (PN->use_empty())
1849 continue; // dead use, don't replace it
1850
1851 if (!SE->isSCEVable(Ty: PN->getType()))
1852 continue;
1853
1854 // Iterate over all of the values in all the PHI nodes.
1855 for (unsigned i = 0; i != NumPreds; ++i) {
1856 // If the value being merged in is not integer or is not defined
1857 // in the loop, skip it.
1858 Value *InVal = PN->getIncomingValue(i);
1859 if (!isa<Instruction>(Val: InVal))
1860 continue;
1861
1862 // If this pred is for a subloop, not L itself, skip it.
1863 if (LI->getLoopFor(BB: PN->getIncomingBlock(i)) != L)
1864 continue; // The Block is in a subloop, skip it.
1865
1866 // Check that InVal is defined in the loop.
1867 Instruction *Inst = cast<Instruction>(Val: InVal);
1868 if (!L->contains(Inst))
1869 continue;
1870
1871 // Find exit values which are induction variables in the loop, and are
1872 // unused in the loop, with the only use being the exit block PhiNode,
1873 // and the induction variable update binary operator.
1874 // The exit value can be replaced with the final value when it is cheap
1875 // to do so.
1876 if (ReplaceExitValue == UnusedIndVarInLoop) {
1877 InductionDescriptor ID;
1878 PHINode *IndPhi = dyn_cast<PHINode>(Val: Inst);
1879 if (IndPhi) {
1880 if (!checkIsIndPhi(Phi: IndPhi, L, SE, ID))
1881 continue;
1882 // This is an induction PHI. Check that the only users are PHI
1883 // nodes, and induction variable update binary operators.
1884 if (llvm::any_of(Range: Inst->users(), P: [&](User *U) {
1885 if (!isa<PHINode>(Val: U) && !isa<BinaryOperator>(Val: U))
1886 return true;
1887 BinaryOperator *B = dyn_cast<BinaryOperator>(Val: U);
1888 if (B && B != ID.getInductionBinOp())
1889 return true;
1890 return false;
1891 }))
1892 continue;
1893 } else {
1894 // If it is not an induction phi, it must be an induction update
1895 // binary operator with an induction phi user.
1896 BinaryOperator *B = dyn_cast<BinaryOperator>(Val: Inst);
1897 if (!B)
1898 continue;
1899 if (llvm::any_of(Range: Inst->users(), P: [&](User *U) {
1900 PHINode *Phi = dyn_cast<PHINode>(Val: U);
1901 if (Phi != PN && !checkIsIndPhi(Phi, L, SE, ID))
1902 return true;
1903 return false;
1904 }))
1905 continue;
1906 if (B != ID.getInductionBinOp())
1907 continue;
1908 }
1909 }
1910
1911 // Okay, this instruction has a user outside of the current loop
1912 // and varies predictably *inside* the loop. Evaluate the value it
1913 // contains when the loop exits, if possible. We prefer to start with
1914 // expressions which are true for all exits (so as to maximize
1915 // expression reuse by the SCEVExpander), but resort to per-exit
1916 // evaluation if that fails.
1917 const SCEV *ExitValue = SE->getSCEVAtScope(V: Inst, L: L->getParentLoop());
1918 if (isa<SCEVCouldNotCompute>(Val: ExitValue) ||
1919 !SE->isLoopInvariant(S: ExitValue, L) ||
1920 !Rewriter.isSafeToExpand(S: ExitValue)) {
1921 // TODO: This should probably be sunk into SCEV in some way; maybe a
1922 // getSCEVForExit(SCEV*, L, ExitingBB)? It can be generalized for
1923 // most SCEV expressions and other recurrence types (e.g. shift
1924 // recurrences). Is there existing code we can reuse?
1925 const SCEV *ExitCount = SE->getExitCount(L, ExitingBlock: PN->getIncomingBlock(i));
1926 if (isa<SCEVCouldNotCompute>(Val: ExitCount))
1927 continue;
1928 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Val: SE->getSCEV(V: Inst)))
1929 if (AddRec->getLoop() == L)
1930 ExitValue = AddRec->evaluateAtIteration(It: ExitCount, SE&: *SE);
1931 if (isa<SCEVCouldNotCompute>(Val: ExitValue) ||
1932 !SE->isLoopInvariant(S: ExitValue, L) ||
1933 !Rewriter.isSafeToExpand(S: ExitValue))
1934 continue;
1935 }
1936
1937 // Computing the value outside of the loop brings no benefit if it is
1938 // definitely used inside the loop in a way which can not be optimized
1939 // away. Avoid doing so unless we know we have a value which computes
1940 // the ExitValue already. TODO: This should be merged into SCEV
1941 // expander to leverage its knowledge of existing expressions.
1942 if (ReplaceExitValue != AlwaysRepl && !isa<SCEVConstant>(Val: ExitValue) &&
1943 !isa<SCEVUnknown>(Val: ExitValue) && hasHardUserWithinLoop(L, I: Inst))
1944 continue;
1945
1946 // Check if expansions of this SCEV would count as being high cost.
1947 bool HighCost = Rewriter.isHighCostExpansion(
1948 Exprs: ExitValue, L, Budget: SCEVCheapExpansionBudget, TTI, At: Inst);
1949
1950 // Note that we must not perform expansions until after
1951 // we query *all* the costs, because if we perform temporary expansion
1952 // inbetween, one that we might not intend to keep, said expansion
1953 // *may* affect cost calculation of the next SCEV's we'll query,
1954 // and next SCEV may errneously get smaller cost.
1955
1956 // Collect all the candidate PHINodes to be rewritten.
1957 Instruction *InsertPt =
1958 (isa<PHINode>(Val: Inst) || isa<LandingPadInst>(Val: Inst)) ?
1959 &*Inst->getParent()->getFirstInsertionPt() : Inst;
1960 RewritePhiSet.emplace_back(Args&: PN, Args&: i, Args&: ExitValue, Args&: InsertPt, Args&: HighCost);
1961 }
1962 }
1963 }
1964
1965 // TODO: evaluate whether it is beneficial to change how we calculate
1966 // high-cost: if we have SCEV 'A' which we know we will expand, should we
1967 // calculate the cost of other SCEV's after expanding SCEV 'A', thus
1968 // potentially giving cost bonus to those other SCEV's?
1969
1970 bool LoopCanBeDel = canLoopBeDeleted(L, RewritePhiSet);
1971 int NumReplaced = 0;
1972
1973 // Transformation.
1974 for (const RewritePhi &Phi : RewritePhiSet) {
1975 PHINode *PN = Phi.PN;
1976
1977 // Only do the rewrite when the ExitValue can be expanded cheaply.
1978 // If LoopCanBeDel is true, rewrite exit value aggressively.
1979 if ((ReplaceExitValue == OnlyCheapRepl ||
1980 ReplaceExitValue == UnusedIndVarInLoop) &&
1981 !LoopCanBeDel && Phi.HighCost)
1982 continue;
1983
1984 Value *ExitVal = Rewriter.expandCodeFor(
1985 SH: Phi.ExpansionSCEV, Ty: Phi.PN->getType(), I: Phi.ExpansionPoint);
1986
1987 LLVM_DEBUG(dbgs() << "rewriteLoopExitValues: AfterLoopVal = " << *ExitVal
1988 << '\n'
1989 << " LoopVal = " << *(Phi.ExpansionPoint) << "\n");
1990
1991#ifndef NDEBUG
1992 // If we reuse an instruction from a loop which is neither L nor one of
1993 // its containing loops, we end up breaking LCSSA form for this loop by
1994 // creating a new use of its instruction.
1995 if (auto *ExitInsn = dyn_cast<Instruction>(ExitVal))
1996 if (auto *EVL = LI->getLoopFor(ExitInsn->getParent()))
1997 if (EVL != L)
1998 assert(EVL->contains(L) && "LCSSA breach detected!");
1999#endif
2000
2001 NumReplaced++;
2002 Instruction *Inst = cast<Instruction>(Val: PN->getIncomingValue(i: Phi.Ith));
2003 PN->setIncomingValue(i: Phi.Ith, V: ExitVal);
2004 // It's necessary to tell ScalarEvolution about this explicitly so that
2005 // it can walk the def-use list and forget all SCEVs, as it may not be
2006 // watching the PHI itself. Once the new exit value is in place, there
2007 // may not be a def-use connection between the loop and every instruction
2008 // which got a SCEVAddRecExpr for that loop.
2009 SE->forgetValue(V: PN);
2010
2011 // If this instruction is dead now, delete it. Don't do it now to avoid
2012 // invalidating iterators.
2013 if (isInstructionTriviallyDead(I: Inst, TLI))
2014 DeadInsts.push_back(Elt: Inst);
2015
2016 // Replace PN with ExitVal if that is legal and does not break LCSSA.
2017 if (PN->getNumIncomingValues() == 1 &&
2018 LI->replacementPreservesLCSSAForm(From: PN, To: ExitVal)) {
2019 PN->replaceAllUsesWith(V: ExitVal);
2020 PN->eraseFromParent();
2021 }
2022 }
2023
2024 // The insertion point instruction may have been deleted; clear it out
2025 // so that the rewriter doesn't trip over it later.
2026 Rewriter.clearInsertPoint();
2027 return NumReplaced;
2028}
2029
2030/// Utility that implements appending of loops onto a worklist.
2031/// Loops are added in preorder (analogous for reverse postorder for trees),
2032/// and the worklist is processed LIFO.
2033template <typename RangeT>
2034void llvm::appendReversedLoopsToWorklist(
2035 RangeT &&Loops, SmallPriorityWorklist<Loop *, 4> &Worklist) {
2036 // We use an internal worklist to build up the preorder traversal without
2037 // recursion.
2038 SmallVector<Loop *, 4> PreOrderLoops, PreOrderWorklist;
2039
2040 // We walk the initial sequence of loops in reverse because we generally want
2041 // to visit defs before uses and the worklist is LIFO.
2042 for (Loop *RootL : Loops) {
2043 assert(PreOrderLoops.empty() && "Must start with an empty preorder walk.");
2044 assert(PreOrderWorklist.empty() &&
2045 "Must start with an empty preorder walk worklist.");
2046 PreOrderWorklist.push_back(Elt: RootL);
2047 do {
2048 Loop *L = PreOrderWorklist.pop_back_val();
2049 PreOrderWorklist.append(in_start: L->begin(), in_end: L->end());
2050 PreOrderLoops.push_back(Elt: L);
2051 } while (!PreOrderWorklist.empty());
2052
2053 Worklist.insert(Input: std::move(PreOrderLoops));
2054 PreOrderLoops.clear();
2055 }
2056}
2057
2058template <typename RangeT>
2059void llvm::appendLoopsToWorklist(RangeT &&Loops,
2060 SmallPriorityWorklist<Loop *, 4> &Worklist) {
2061 appendReversedLoopsToWorklist(reverse(Loops), Worklist);
2062}
2063
2064template LLVM_EXPORT_TEMPLATE void
2065llvm::appendLoopsToWorklist<ArrayRef<Loop *> &>(
2066 ArrayRef<Loop *> &Loops, SmallPriorityWorklist<Loop *, 4> &Worklist);
2067
2068template LLVM_EXPORT_TEMPLATE void
2069llvm::appendLoopsToWorklist<Loop &>(Loop &L,
2070 SmallPriorityWorklist<Loop *, 4> &Worklist);
2071
2072void llvm::appendLoopsToWorklist(LoopInfo &LI,
2073 SmallPriorityWorklist<Loop *, 4> &Worklist) {
2074 appendReversedLoopsToWorklist(Loops&: LI, Worklist);
2075}
2076
2077Loop *llvm::cloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM,
2078 LoopInfo *LI, LPPassManager *LPM) {
2079 Loop &New = *LI->AllocateLoop();
2080 if (PL)
2081 PL->addChildLoop(NewChild: &New);
2082 else
2083 LI->addTopLevelLoop(New: &New);
2084
2085 if (LPM)
2086 LPM->addLoop(L&: New);
2087
2088 // Add all of the blocks in L to the new loop.
2089 for (BasicBlock *BB : L->blocks())
2090 if (LI->getLoopFor(BB) == L)
2091 New.addBasicBlockToLoop(NewBB: cast<BasicBlock>(Val&: VM[BB]), LI&: *LI);
2092
2093 // Add all of the subloops to the new loop.
2094 for (Loop *I : *L)
2095 cloneLoop(L: I, PL: &New, VM, LI, LPM);
2096
2097 return &New;
2098}
2099
2100/// IR Values for the lower and upper bounds of a pointer evolution. We
2101/// need to use value-handles because SCEV expansion can invalidate previously
2102/// expanded values. Thus expansion of a pointer can invalidate the bounds for
2103/// a previous one.
2104struct PointerBounds {
2105 TrackingVH<Value> Start;
2106 TrackingVH<Value> End;
2107 Value *StrideToCheck;
2108};
2109
2110/// Expand code for the lower and upper bound of the pointer group \p CG
2111/// in \p TheLoop. \return the values for the bounds.
2112static PointerBounds expandBounds(const RuntimeCheckingPtrGroup *CG,
2113 Loop *TheLoop, Instruction *Loc,
2114 SCEVExpander &Exp, bool HoistRuntimeChecks) {
2115 LLVMContext &Ctx = Loc->getContext();
2116 Type *PtrArithTy = PointerType::get(C&: Ctx, AddressSpace: CG->AddressSpace);
2117
2118 Value *Start = nullptr, *End = nullptr;
2119 LLVM_DEBUG(dbgs() << "LAA: Adding RT check for range:\n");
2120 const SCEV *Low = CG->Low, *High = CG->High, *Stride = nullptr;
2121
2122 // If the Low and High values are themselves loop-variant, then we may want
2123 // to expand the range to include those covered by the outer loop as well.
2124 // There is a trade-off here with the advantage being that creating checks
2125 // using the expanded range permits the runtime memory checks to be hoisted
2126 // out of the outer loop. This reduces the cost of entering the inner loop,
2127 // which can be significant for low trip counts. The disadvantage is that
2128 // there is a chance we may now never enter the vectorized inner loop,
2129 // whereas using a restricted range check could have allowed us to enter at
2130 // least once. This is why the behaviour is not currently the default and is
2131 // controlled by the parameter 'HoistRuntimeChecks'.
2132 if (HoistRuntimeChecks && TheLoop->getParentLoop() &&
2133 isa<SCEVAddRecExpr>(Val: High) && isa<SCEVAddRecExpr>(Val: Low)) {
2134 auto *HighAR = cast<SCEVAddRecExpr>(Val: High);
2135 auto *LowAR = cast<SCEVAddRecExpr>(Val: Low);
2136 const Loop *OuterLoop = TheLoop->getParentLoop();
2137 ScalarEvolution &SE = *Exp.getSE();
2138 const SCEV *Recur = LowAR->getStepRecurrence(SE);
2139 if (Recur == HighAR->getStepRecurrence(SE) &&
2140 HighAR->getLoop() == OuterLoop && LowAR->getLoop() == OuterLoop) {
2141 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
2142 const SCEV *OuterExitCount = SE.getExitCount(L: OuterLoop, ExitingBlock: OuterLoopLatch);
2143 if (!isa<SCEVCouldNotCompute>(Val: OuterExitCount) &&
2144 OuterExitCount->getType()->isIntegerTy()) {
2145 const SCEV *NewHigh =
2146 cast<SCEVAddRecExpr>(Val: High)->evaluateAtIteration(It: OuterExitCount, SE);
2147 if (!isa<SCEVCouldNotCompute>(Val: NewHigh)) {
2148 LLVM_DEBUG(dbgs() << "LAA: Expanded RT check for range to include "
2149 "outer loop in order to permit hoisting\n");
2150 High = NewHigh;
2151 Low = cast<SCEVAddRecExpr>(Val: Low)->getStart();
2152 // If there is a possibility that the stride is negative then we have
2153 // to generate extra checks to ensure the stride is positive.
2154 if (!SE.isKnownNonNegative(
2155 S: SE.applyLoopGuards(Expr: Recur, L: HighAR->getLoop()))) {
2156 Stride = Recur;
2157 LLVM_DEBUG(dbgs() << "LAA: ... but need to check stride is "
2158 "positive: "
2159 << *Stride << '\n');
2160 }
2161 }
2162 }
2163 }
2164 }
2165
2166 Start = Exp.expandCodeFor(SH: Low, Ty: PtrArithTy, I: Loc);
2167 End = Exp.expandCodeFor(SH: High, Ty: PtrArithTy, I: Loc);
2168 if (CG->NeedsFreeze) {
2169 IRBuilder<> Builder(Loc);
2170 Start = Builder.CreateFreeze(V: Start, Name: Start->getName() + ".fr");
2171 End = Builder.CreateFreeze(V: End, Name: End->getName() + ".fr");
2172 }
2173 Value *StrideVal =
2174 Stride ? Exp.expandCodeFor(SH: Stride, Ty: Stride->getType(), I: Loc) : nullptr;
2175 LLVM_DEBUG(dbgs() << "Start: " << *Low << " End: " << *High << "\n");
2176 return {.Start: Start, .End: End, .StrideToCheck: StrideVal};
2177}
2178
2179/// Turns a collection of checks into a collection of expanded upper and
2180/// lower bounds for both pointers in the check.
2181static SmallVector<std::pair<PointerBounds, PointerBounds>, 4>
2182expandBounds(const SmallVectorImpl<RuntimePointerCheck> &PointerChecks, Loop *L,
2183 Instruction *Loc, SCEVExpander &Exp, bool HoistRuntimeChecks) {
2184 SmallVector<std::pair<PointerBounds, PointerBounds>, 4> ChecksWithBounds;
2185
2186 // Here we're relying on the SCEV Expander's cache to only emit code for the
2187 // same bounds once.
2188 transform(Range: PointerChecks, d_first: std::back_inserter(x&: ChecksWithBounds),
2189 F: [&](const RuntimePointerCheck &Check) {
2190 PointerBounds First = expandBounds(CG: Check.first, TheLoop: L, Loc, Exp,
2191 HoistRuntimeChecks),
2192 Second = expandBounds(CG: Check.second, TheLoop: L, Loc, Exp,
2193 HoistRuntimeChecks);
2194 return std::make_pair(x&: First, y&: Second);
2195 });
2196
2197 return ChecksWithBounds;
2198}
2199
2200Value *llvm::addRuntimeChecks(
2201 Instruction *Loc, Loop *TheLoop,
2202 const SmallVectorImpl<RuntimePointerCheck> &PointerChecks,
2203 SCEVExpander &Exp, bool HoistRuntimeChecks) {
2204 // TODO: Move noalias annotation code from LoopVersioning here and share with LV if possible.
2205 // TODO: Pass RtPtrChecking instead of PointerChecks and SE separately, if possible
2206 auto ExpandedChecks =
2207 expandBounds(PointerChecks, L: TheLoop, Loc, Exp, HoistRuntimeChecks);
2208
2209 LLVMContext &Ctx = Loc->getContext();
2210 IRBuilder ChkBuilder(Ctx, InstSimplifyFolder(Loc->getDataLayout()));
2211 ChkBuilder.SetInsertPoint(Loc);
2212 // Our instructions might fold to a constant.
2213 Value *MemoryRuntimeCheck = nullptr;
2214
2215 for (const auto &[A, B] : ExpandedChecks) {
2216 // Check if two pointers (A and B) conflict where conflict is computed as:
2217 // start(A) <= end(B) && start(B) <= end(A)
2218
2219 assert((A.Start->getType()->getPointerAddressSpace() ==
2220 B.End->getType()->getPointerAddressSpace()) &&
2221 (B.Start->getType()->getPointerAddressSpace() ==
2222 A.End->getType()->getPointerAddressSpace()) &&
2223 "Trying to bounds check pointers with different address spaces");
2224
2225 // [A|B].Start points to the first accessed byte under base [A|B].
2226 // [A|B].End points to the last accessed byte, plus one.
2227 // There is no conflict when the intervals are disjoint:
2228 // NoConflict = (B.Start >= A.End) || (A.Start >= B.End)
2229 //
2230 // bound0 = (B.Start < A.End)
2231 // bound1 = (A.Start < B.End)
2232 // IsConflict = bound0 & bound1
2233 Value *Cmp0 = ChkBuilder.CreateICmpULT(LHS: A.Start, RHS: B.End, Name: "bound0");
2234 Value *Cmp1 = ChkBuilder.CreateICmpULT(LHS: B.Start, RHS: A.End, Name: "bound1");
2235 Value *IsConflict = ChkBuilder.CreateAnd(LHS: Cmp0, RHS: Cmp1, Name: "found.conflict");
2236 if (A.StrideToCheck) {
2237 Value *IsNegativeStride = ChkBuilder.CreateICmpSLT(
2238 LHS: A.StrideToCheck, RHS: ConstantInt::get(Ty: A.StrideToCheck->getType(), V: 0),
2239 Name: "stride.check");
2240 IsConflict = ChkBuilder.CreateOr(LHS: IsConflict, RHS: IsNegativeStride);
2241 }
2242 if (B.StrideToCheck) {
2243 Value *IsNegativeStride = ChkBuilder.CreateICmpSLT(
2244 LHS: B.StrideToCheck, RHS: ConstantInt::get(Ty: B.StrideToCheck->getType(), V: 0),
2245 Name: "stride.check");
2246 IsConflict = ChkBuilder.CreateOr(LHS: IsConflict, RHS: IsNegativeStride);
2247 }
2248 if (MemoryRuntimeCheck) {
2249 IsConflict =
2250 ChkBuilder.CreateOr(LHS: MemoryRuntimeCheck, RHS: IsConflict, Name: "conflict.rdx");
2251 }
2252 MemoryRuntimeCheck = IsConflict;
2253 }
2254
2255 Exp.eraseDeadInstructions(Root: MemoryRuntimeCheck);
2256 return MemoryRuntimeCheck;
2257}
2258
2259namespace {
2260/// Rewriter to replace SCEVPtrToIntExpr with SCEVPtrToAddrExpr when the result
2261/// type matches the pointer address type. This allows expressions mixing
2262/// ptrtoint and ptrtoaddr to simplify properly.
2263struct SCEVPtrToAddrRewriter : SCEVRewriteVisitor<SCEVPtrToAddrRewriter> {
2264 const DataLayout &DL;
2265 SCEVPtrToAddrRewriter(ScalarEvolution &SE, const DataLayout &DL)
2266 : SCEVRewriteVisitor(SE), DL(DL) {}
2267
2268 const SCEV *visitPtrToIntExpr(const SCEVPtrToIntExpr *E) {
2269 const SCEV *Op = visit(S: E->getOperand());
2270 if (E->getType() == DL.getAddressType(PtrTy: E->getOperand()->getType()))
2271 return SE.getPtrToAddrExpr(Op);
2272 return Op == E->getOperand() ? E : SE.getPtrToIntExpr(Op, Ty: E->getType());
2273 }
2274};
2275} // namespace
2276
2277Value *llvm::addDiffRuntimeChecks(
2278 Instruction *Loc, ArrayRef<PointerDiffInfo> Checks, SCEVExpander &Expander,
2279 function_ref<Value *(IRBuilderBase &, unsigned)> GetVF, unsigned IC) {
2280
2281 LLVMContext &Ctx = Loc->getContext();
2282 IRBuilder ChkBuilder(Ctx, InstSimplifyFolder(Loc->getDataLayout()));
2283 ChkBuilder.SetInsertPoint(Loc);
2284 // Our instructions might fold to a constant.
2285 Value *MemoryRuntimeCheck = nullptr;
2286
2287 auto &SE = *Expander.getSE();
2288 const DataLayout &DL = Loc->getDataLayout();
2289 SCEVPtrToAddrRewriter Rewriter(SE, DL);
2290 // Map to keep track of created compares, The key is the pair of operands for
2291 // the compare, to allow detecting and re-using redundant compares.
2292 DenseMap<std::pair<Value *, Value *>, Value *> SeenCompares;
2293 // Cache of (VF * IC * AccessSize) - 1, shared across checks with matching
2294 // type and IC*AccessSize to avoid emitting duplicate runtime computations.
2295 DenseMap<std::pair<Type *, unsigned>, Value *> ThresholdCache;
2296 for (const auto &[SrcStart, SinkStart, AccessSize, NeedsFreeze] : Checks) {
2297 assert(IC * AccessSize > 0 &&
2298 "Threshold must be non-zero to use diff-check");
2299 Type *Ty = SinkStart->getType();
2300 unsigned ICTimesAccessSize = IC * AccessSize;
2301 Value *One = ConstantInt::get(Ty, V: 1);
2302 Value *&ThresholdMinusOne = ThresholdCache[{Ty, ICTimesAccessSize}];
2303 if (!ThresholdMinusOne) {
2304 Value *VFTimesICTimesSize =
2305 ChkBuilder.CreateMul(LHS: GetVF(ChkBuilder, Ty->getScalarSizeInBits()),
2306 RHS: ConstantInt::get(Ty, V: ICTimesAccessSize));
2307 ThresholdMinusOne = ChkBuilder.CreateSub(LHS: VFTimesICTimesSize, RHS: One);
2308 }
2309 const SCEV *SinkStartRewritten = Rewriter.visit(S: SinkStart);
2310 const SCEV *SrcStartRewritten = Rewriter.visit(S: SrcStart);
2311 Value *Diff = Expander.expandCodeFor(
2312 SH: SE.getMinusSCEV(LHS: SinkStartRewritten, RHS: SrcStartRewritten), Ty, I: Loc);
2313
2314 // Check if the same compare has already been created earlier. In that case,
2315 // there is no need to check it again.
2316 Value *IsConflict = SeenCompares.lookup(Val: {Diff, ThresholdMinusOne});
2317 if (IsConflict)
2318 continue;
2319
2320 // Use (Diff - 1) <u (Threshold - 1), equivalent to 0 < Diff <u Threshold,
2321 // to exclude Diff == 0 (equal pointers are safe).
2322 IsConflict = ChkBuilder.CreateICmpULT(LHS: ChkBuilder.CreateSub(LHS: Diff, RHS: One),
2323 RHS: ThresholdMinusOne, Name: "diff.check");
2324 SeenCompares.insert(KV: {{Diff, ThresholdMinusOne}, IsConflict});
2325 if (NeedsFreeze)
2326 IsConflict =
2327 ChkBuilder.CreateFreeze(V: IsConflict, Name: IsConflict->getName() + ".fr");
2328 if (MemoryRuntimeCheck) {
2329 IsConflict =
2330 ChkBuilder.CreateOr(LHS: MemoryRuntimeCheck, RHS: IsConflict, Name: "conflict.rdx");
2331 }
2332 MemoryRuntimeCheck = IsConflict;
2333 }
2334
2335 Expander.eraseDeadInstructions(Root: MemoryRuntimeCheck);
2336 return MemoryRuntimeCheck;
2337}
2338
2339std::optional<IVConditionInfo>
2340llvm::hasPartialIVCondition(const Loop &L, unsigned MSSAThreshold,
2341 const MemorySSA &MSSA, AAResults &AA) {
2342 auto *TI = dyn_cast<CondBrInst>(Val: L.getHeader()->getTerminator());
2343 if (!TI)
2344 return {};
2345
2346 auto *CondI = dyn_cast<Instruction>(Val: TI->getCondition());
2347 // The case with the condition outside the loop should already be handled
2348 // earlier.
2349 // Allow CmpInst and TruncInsts as they may be users of load instructions
2350 // and have potential for partial unswitching
2351 if (!CondI || !isa<CmpInst, TruncInst>(Val: CondI) || !L.contains(Inst: CondI))
2352 return {};
2353
2354 SmallVector<Instruction *> InstToDuplicate;
2355 InstToDuplicate.push_back(Elt: CondI);
2356
2357 SmallVector<Value *, 4> WorkList;
2358 WorkList.append(in_start: CondI->op_begin(), in_end: CondI->op_end());
2359
2360 SmallVector<MemoryAccess *, 4> AccessesToCheck;
2361 SmallVector<MemoryLocation, 4> AccessedLocs;
2362 while (!WorkList.empty()) {
2363 Instruction *I = dyn_cast<Instruction>(Val: WorkList.pop_back_val());
2364 if (!I || !L.contains(Inst: I))
2365 continue;
2366
2367 // TODO: support additional instructions.
2368 if (!isa<LoadInst>(Val: I) && !isa<GetElementPtrInst>(Val: I))
2369 return {};
2370
2371 // Do not duplicate volatile and atomic loads.
2372 if (auto *LI = dyn_cast<LoadInst>(Val: I))
2373 if (LI->isVolatile() || LI->isAtomic())
2374 return {};
2375
2376 InstToDuplicate.push_back(Elt: I);
2377 if (MemoryAccess *MA = MSSA.getMemoryAccess(I)) {
2378 if (auto *MemUse = dyn_cast_or_null<MemoryUse>(Val: MA)) {
2379 // Queue the defining access to check for alias checks.
2380 AccessesToCheck.push_back(Elt: MemUse->getDefiningAccess());
2381 AccessedLocs.push_back(Elt: MemoryLocation::get(Inst: I));
2382 } else {
2383 // MemoryDefs may clobber the location or may be atomic memory
2384 // operations. Bail out.
2385 return {};
2386 }
2387 }
2388 WorkList.append(in_start: I->op_begin(), in_end: I->op_end());
2389 }
2390
2391 if (InstToDuplicate.empty())
2392 return {};
2393
2394 SmallVector<BasicBlock *, 4> ExitingBlocks;
2395 L.getExitingBlocks(ExitingBlocks);
2396 auto HasNoClobbersOnPath =
2397 [&L, &AA, &AccessedLocs, &ExitingBlocks, &InstToDuplicate,
2398 MSSAThreshold](BasicBlock *Succ, BasicBlock *Header,
2399 SmallVector<MemoryAccess *, 4> AccessesToCheck)
2400 -> std::optional<IVConditionInfo> {
2401 IVConditionInfo Info;
2402 // First, collect all blocks in the loop that are on a patch from Succ
2403 // to the header.
2404 SmallVector<BasicBlock *, 4> WorkList;
2405 WorkList.push_back(Elt: Succ);
2406 WorkList.push_back(Elt: Header);
2407 SmallPtrSet<BasicBlock *, 4> Seen;
2408 Seen.insert(Ptr: Header);
2409 Info.PathIsNoop &=
2410 all_of(Range&: *Header, P: [](Instruction &I) { return !I.mayHaveSideEffects(); });
2411
2412 while (!WorkList.empty()) {
2413 BasicBlock *Current = WorkList.pop_back_val();
2414 if (!L.contains(BB: Current))
2415 continue;
2416 const auto &SeenIns = Seen.insert(Ptr: Current);
2417 if (!SeenIns.second)
2418 continue;
2419
2420 Info.PathIsNoop &= all_of(
2421 Range&: *Current, P: [](Instruction &I) { return !I.mayHaveSideEffects(); });
2422 WorkList.append(in_start: succ_begin(BB: Current), in_end: succ_end(BB: Current));
2423 }
2424
2425 // Require at least 2 blocks on a path through the loop. This skips
2426 // paths that directly exit the loop.
2427 if (Seen.size() < 2)
2428 return {};
2429
2430 // Next, check if there are any MemoryDefs that are on the path through
2431 // the loop (in the Seen set) and they may-alias any of the locations in
2432 // AccessedLocs. If that is the case, they may modify the condition and
2433 // partial unswitching is not possible.
2434 SmallPtrSet<MemoryAccess *, 4> SeenAccesses;
2435 while (!AccessesToCheck.empty()) {
2436 MemoryAccess *Current = AccessesToCheck.pop_back_val();
2437 auto SeenI = SeenAccesses.insert(Ptr: Current);
2438 if (!SeenI.second || !Seen.contains(Ptr: Current->getBlock()))
2439 continue;
2440
2441 // Bail out if exceeded the threshold.
2442 if (SeenAccesses.size() >= MSSAThreshold)
2443 return {};
2444
2445 // MemoryUse are read-only accesses.
2446 if (isa<MemoryUse>(Val: Current))
2447 continue;
2448
2449 // For a MemoryDef, check if is aliases any of the location feeding
2450 // the original condition.
2451 if (auto *CurrentDef = dyn_cast<MemoryDef>(Val: Current)) {
2452 if (any_of(Range&: AccessedLocs, P: [&AA, CurrentDef](MemoryLocation &Loc) {
2453 return isModSet(
2454 MRI: AA.getModRefInfo(I: CurrentDef->getMemoryInst(), OptLoc: Loc));
2455 }))
2456 return {};
2457 }
2458
2459 for (Use &U : Current->uses())
2460 AccessesToCheck.push_back(Elt: cast<MemoryAccess>(Val: U.getUser()));
2461 }
2462
2463 // We could also allow loops with known trip counts without mustprogress,
2464 // but ScalarEvolution may not be available.
2465 Info.PathIsNoop &= isMustProgress(L: &L);
2466
2467 // If the path is considered a no-op so far, check if it reaches a
2468 // single exit block without any phis. This ensures no values from the
2469 // loop are used outside of the loop.
2470 if (Info.PathIsNoop) {
2471 for (auto *Exiting : ExitingBlocks) {
2472 if (!Seen.contains(Ptr: Exiting))
2473 continue;
2474 for (auto *Succ : successors(BB: Exiting)) {
2475 if (L.contains(BB: Succ))
2476 continue;
2477
2478 Info.PathIsNoop &= Succ->phis().empty() &&
2479 (!Info.ExitForPath || Info.ExitForPath == Succ);
2480 if (!Info.PathIsNoop)
2481 break;
2482 assert((!Info.ExitForPath || Info.ExitForPath == Succ) &&
2483 "cannot have multiple exit blocks");
2484 Info.ExitForPath = Succ;
2485 }
2486 }
2487 }
2488 if (!Info.ExitForPath)
2489 Info.PathIsNoop = false;
2490
2491 Info.InstToDuplicate = std::move(InstToDuplicate);
2492 return Info;
2493 };
2494
2495 // If we branch to the same successor, partial unswitching will not be
2496 // beneficial.
2497 if (TI->getSuccessor(i: 0) == TI->getSuccessor(i: 1))
2498 return {};
2499
2500 if (auto Info = HasNoClobbersOnPath(TI->getSuccessor(i: 0), L.getHeader(),
2501 AccessesToCheck)) {
2502 Info->KnownValue = ConstantInt::getTrue(Context&: TI->getContext());
2503 return Info;
2504 }
2505 if (auto Info = HasNoClobbersOnPath(TI->getSuccessor(i: 1), L.getHeader(),
2506 AccessesToCheck)) {
2507 Info->KnownValue = ConstantInt::getFalse(Context&: TI->getContext());
2508 return Info;
2509 }
2510
2511 return {};
2512}
2513