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