1 //===- llvm/unittest/Analysis/LoopPassManagerTest.cpp - LPM tests ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "llvm/Analysis/AliasAnalysis.h"
11 #include "llvm/Analysis/AssumptionCache.h"
12 #include "llvm/Analysis/ScalarEvolution.h"
13 #include "llvm/Analysis/TargetLibraryInfo.h"
14 #include "llvm/Analysis/TargetTransformInfo.h"
15 #include "llvm/AsmParser/Parser.h"
16 #include "llvm/IR/Dominators.h"
17 #include "llvm/IR/Function.h"
18 #include "llvm/IR/LLVMContext.h"
19 #include "llvm/IR/Module.h"
20 #include "llvm/IR/PassManager.h"
21 #include "llvm/Support/SourceMgr.h"
22 #include "llvm/Transforms/Scalar/LoopPassManager.h"
23 #include "gmock/gmock.h"
24 #include "gtest/gtest.h"
25 
26 using namespace llvm;
27 
28 namespace {
29 
30 using testing::DoDefault;
31 using testing::Return;
32 using testing::Expectation;
33 using testing::Invoke;
34 using testing::InvokeWithoutArgs;
35 using testing::_;
36 
37 template <typename DerivedT, typename IRUnitT,
38           typename AnalysisManagerT = AnalysisManager<IRUnitT>,
39           typename... ExtraArgTs>
40 class MockAnalysisHandleBase {
41 public:
42   class Analysis : public AnalysisInfoMixin<Analysis> {
43     friend AnalysisInfoMixin<Analysis>;
44     friend MockAnalysisHandleBase;
45     static AnalysisKey Key;
46 
47     DerivedT *Handle;
48 
49     Analysis(DerivedT &Handle) : Handle(&Handle) {}
50 
51   public:
52     class Result {
53       friend MockAnalysisHandleBase;
54 
55       DerivedT *Handle;
56 
57       Result(DerivedT &Handle) : Handle(&Handle) {}
58 
59     public:
60       // Forward invalidation events to the mock handle.
61       bool invalidate(IRUnitT &IR, const PreservedAnalyses &PA,
62                       typename AnalysisManagerT::Invalidator &Inv) {
63         return Handle->invalidate(IR, PA, Inv);
64       }
65     };
66 
67     Result run(IRUnitT &IR, AnalysisManagerT &AM, ExtraArgTs... ExtraArgs) {
68       return Handle->run(IR, AM, ExtraArgs...);
69     }
70   };
71 
72   Analysis getAnalysis() { return Analysis(static_cast<DerivedT &>(*this)); }
73   typename Analysis::Result getResult() {
74     return typename Analysis::Result(static_cast<DerivedT &>(*this));
75   }
76 
77 protected:
78   // FIXME: MSVC seems unable to handle a lambda argument to Invoke from within
79   // the template, so we use a boring static function.
80   static bool invalidateCallback(IRUnitT &IR, const PreservedAnalyses &PA,
81                                  typename AnalysisManagerT::Invalidator &Inv) {
82     auto PAC = PA.template getChecker<Analysis>();
83     return !PAC.preserved() &&
84            !PAC.template preservedSet<AllAnalysesOn<IRUnitT>>();
85   }
86 
87   /// Derived classes should call this in their constructor to set up default
88   /// mock actions. (We can't do this in our constructor because this has to
89   /// run after the DerivedT is constructed.)
90   void setDefaults() {
91     ON_CALL(static_cast<DerivedT &>(*this),
92             run(_, _, testing::Matcher<ExtraArgTs>(_)...))
93         .WillByDefault(Return(this->getResult()));
94     ON_CALL(static_cast<DerivedT &>(*this), invalidate(_, _, _))
95         .WillByDefault(Invoke(&invalidateCallback));
96   }
97 };
98 
99 template <typename DerivedT, typename IRUnitT, typename AnalysisManagerT,
100           typename... ExtraArgTs>
101 AnalysisKey MockAnalysisHandleBase<DerivedT, IRUnitT, AnalysisManagerT,
102                                    ExtraArgTs...>::Analysis::Key;
103 
104 /// Mock handle for loop analyses.
105 ///
106 /// This is provided as a template accepting an (optional) integer. Because
107 /// analyses are identified and queried by type, this allows constructing
108 /// multiple handles with distinctly typed nested 'Analysis' types that can be
109 /// registered and queried. If you want to register multiple loop analysis
110 /// passes, you'll need to instantiate this type with different values for I.
111 /// For example:
112 ///
113 ///   MockLoopAnalysisHandleTemplate<0> h0;
114 ///   MockLoopAnalysisHandleTemplate<1> h1;
115 ///   typedef decltype(h0)::Analysis Analysis0;
116 ///   typedef decltype(h1)::Analysis Analysis1;
117 template <size_t I = static_cast<size_t>(-1)>
118 struct MockLoopAnalysisHandleTemplate
119     : MockAnalysisHandleBase<MockLoopAnalysisHandleTemplate<I>, Loop,
120                              LoopAnalysisManager,
121                              LoopStandardAnalysisResults &> {
122   typedef typename MockLoopAnalysisHandleTemplate::Analysis Analysis;
123 
124   MOCK_METHOD3_T(run, typename Analysis::Result(Loop &, LoopAnalysisManager &,
125                                                 LoopStandardAnalysisResults &));
126 
127   MOCK_METHOD3_T(invalidate, bool(Loop &, const PreservedAnalyses &,
128                                   LoopAnalysisManager::Invalidator &));
129 
130   MockLoopAnalysisHandleTemplate() { this->setDefaults(); }
131 };
132 
133 typedef MockLoopAnalysisHandleTemplate<> MockLoopAnalysisHandle;
134 
135 struct MockFunctionAnalysisHandle
136     : MockAnalysisHandleBase<MockFunctionAnalysisHandle, Function> {
137   MOCK_METHOD2(run, Analysis::Result(Function &, FunctionAnalysisManager &));
138 
139   MOCK_METHOD3(invalidate, bool(Function &, const PreservedAnalyses &,
140                                 FunctionAnalysisManager::Invalidator &));
141 
142   MockFunctionAnalysisHandle() { setDefaults(); }
143 };
144 
145 template <typename DerivedT, typename IRUnitT,
146           typename AnalysisManagerT = AnalysisManager<IRUnitT>,
147           typename... ExtraArgTs>
148 class MockPassHandleBase {
149 public:
150   class Pass : public PassInfoMixin<Pass> {
151     friend MockPassHandleBase;
152 
153     DerivedT *Handle;
154 
155     Pass(DerivedT &Handle) : Handle(&Handle) {}
156 
157   public:
158     PreservedAnalyses run(IRUnitT &IR, AnalysisManagerT &AM,
159                           ExtraArgTs... ExtraArgs) {
160       return Handle->run(IR, AM, ExtraArgs...);
161     }
162   };
163 
164   Pass getPass() { return Pass(static_cast<DerivedT &>(*this)); }
165 
166 protected:
167   /// Derived classes should call this in their constructor to set up default
168   /// mock actions. (We can't do this in our constructor because this has to
169   /// run after the DerivedT is constructed.)
170   void setDefaults() {
171     ON_CALL(static_cast<DerivedT &>(*this),
172             run(_, _, testing::Matcher<ExtraArgTs>(_)...))
173         .WillByDefault(Return(PreservedAnalyses::all()));
174   }
175 };
176 
177 struct MockLoopPassHandle
178     : MockPassHandleBase<MockLoopPassHandle, Loop, LoopAnalysisManager,
179                          LoopStandardAnalysisResults &, LPMUpdater &> {
180   MOCK_METHOD4(run,
181                PreservedAnalyses(Loop &, LoopAnalysisManager &,
182                                  LoopStandardAnalysisResults &, LPMUpdater &));
183   MockLoopPassHandle() { setDefaults(); }
184 };
185 
186 struct MockFunctionPassHandle
187     : MockPassHandleBase<MockFunctionPassHandle, Function> {
188   MOCK_METHOD2(run, PreservedAnalyses(Function &, FunctionAnalysisManager &));
189 
190   MockFunctionPassHandle() { setDefaults(); }
191 };
192 
193 struct MockModulePassHandle : MockPassHandleBase<MockModulePassHandle, Module> {
194   MOCK_METHOD2(run, PreservedAnalyses(Module &, ModuleAnalysisManager &));
195 
196   MockModulePassHandle() { setDefaults(); }
197 };
198 
199 /// Define a custom matcher for objects which support a 'getName' method
200 /// returning a StringRef.
201 ///
202 /// LLVM often has IR objects or analysis objects which expose a StringRef name
203 /// and in tests it is convenient to match these by name for readability. This
204 /// matcher supports any type exposing a getName() method of this form.
205 ///
206 /// It should be used as:
207 ///
208 ///   HasName("my_function")
209 ///
210 /// No namespace or other qualification is required.
211 MATCHER_P(HasName, Name, "") {
212   // The matcher's name and argument are printed in the case of failure, but we
213   // also want to print out the name of the argument. This uses an implicitly
214   // avaiable std::ostream, so we have to construct a std::string.
215   *result_listener << "has name '" << arg.getName().str() << "'";
216   return Name == arg.getName();
217 }
218 
219 std::unique_ptr<Module> parseIR(LLVMContext &C, const char *IR) {
220   SMDiagnostic Err;
221   return parseAssemblyString(IR, Err, C);
222 }
223 
224 class LoopPassManagerTest : public ::testing::Test {
225 protected:
226   LLVMContext Context;
227   std::unique_ptr<Module> M;
228 
229   LoopAnalysisManager LAM;
230   FunctionAnalysisManager FAM;
231   ModuleAnalysisManager MAM;
232 
233   MockLoopAnalysisHandle MLAHandle;
234   MockLoopPassHandle MLPHandle;
235   MockFunctionPassHandle MFPHandle;
236   MockModulePassHandle MMPHandle;
237 
238   static PreservedAnalyses
239   getLoopAnalysisResult(Loop &L, LoopAnalysisManager &AM,
240                         LoopStandardAnalysisResults &AR, LPMUpdater &) {
241     (void)AM.getResult<MockLoopAnalysisHandle::Analysis>(L, AR);
242     return PreservedAnalyses::all();
243   };
244 
245 public:
246   LoopPassManagerTest()
247       : M(parseIR(Context, "define void @f() {\n"
248                            "entry:\n"
249                            "  br label %loop.0\n"
250                            "loop.0:\n"
251                            "  br i1 undef, label %loop.0.0, label %end\n"
252                            "loop.0.0:\n"
253                            "  br i1 undef, label %loop.0.0, label %loop.0.1\n"
254                            "loop.0.1:\n"
255                            "  br i1 undef, label %loop.0.1, label %loop.0\n"
256                            "end:\n"
257                            "  ret void\n"
258                            "}\n"
259                            "\n"
260                            "define void @g() {\n"
261                            "entry:\n"
262                            "  br label %loop.g.0\n"
263                            "loop.g.0:\n"
264                            "  br i1 undef, label %loop.g.0, label %end\n"
265                            "end:\n"
266                            "  ret void\n"
267                            "}\n")),
268         LAM(true), FAM(true), MAM(true) {
269     // Register our mock analysis.
270     LAM.registerPass([&] { return MLAHandle.getAnalysis(); });
271 
272     // We need DominatorTreeAnalysis for LoopAnalysis.
273     FAM.registerPass([&] { return DominatorTreeAnalysis(); });
274     FAM.registerPass([&] { return LoopAnalysis(); });
275     // We also allow loop passes to assume a set of other analyses and so need
276     // those.
277     FAM.registerPass([&] { return AAManager(); });
278     FAM.registerPass([&] { return AssumptionAnalysis(); });
279     FAM.registerPass([&] { return ScalarEvolutionAnalysis(); });
280     FAM.registerPass([&] { return TargetLibraryAnalysis(); });
281     FAM.registerPass([&] { return TargetIRAnalysis(); });
282 
283     // Cross-register proxies.
284     LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
285     FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
286     FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
287     MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
288   }
289 };
290 
291 TEST_F(LoopPassManagerTest, Basic) {
292   ModulePassManager MPM(true);
293   ::testing::InSequence MakeExpectationsSequenced;
294 
295   // First we just visit all the loops in all the functions and get their
296   // analysis results. This will run the analysis a total of four times,
297   // once for each loop.
298   EXPECT_CALL(MLPHandle, run(HasName("loop.0.0"), _, _, _))
299       .WillOnce(Invoke(getLoopAnalysisResult));
300   EXPECT_CALL(MLAHandle, run(HasName("loop.0.0"), _, _));
301   EXPECT_CALL(MLPHandle, run(HasName("loop.0.1"), _, _, _))
302       .WillOnce(Invoke(getLoopAnalysisResult));
303   EXPECT_CALL(MLAHandle, run(HasName("loop.0.1"), _, _));
304   EXPECT_CALL(MLPHandle, run(HasName("loop.0"), _, _, _))
305       .WillOnce(Invoke(getLoopAnalysisResult));
306   EXPECT_CALL(MLAHandle, run(HasName("loop.0"), _, _));
307   EXPECT_CALL(MLPHandle, run(HasName("loop.g.0"), _, _, _))
308       .WillOnce(Invoke(getLoopAnalysisResult));
309   EXPECT_CALL(MLAHandle, run(HasName("loop.g.0"), _, _));
310   // Wire the loop pass through pass managers into the module pipeline.
311   {
312     LoopPassManager LPM(true);
313     LPM.addPass(MLPHandle.getPass());
314     FunctionPassManager FPM(true);
315     FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM)));
316     MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
317   }
318 
319   // Next we run two passes over the loops. The first one invalidates the
320   // analyses for one loop, the second ones try to get the analysis results.
321   // This should force only one analysis to re-run within the loop PM, but will
322   // also invalidate everything after the loop pass manager finishes.
323   EXPECT_CALL(MLPHandle, run(HasName("loop.0.0"), _, _, _))
324       .WillOnce(DoDefault())
325       .WillOnce(Invoke(getLoopAnalysisResult));
326   EXPECT_CALL(MLPHandle, run(HasName("loop.0.1"), _, _, _))
327       .WillOnce(InvokeWithoutArgs([] { return PreservedAnalyses::none(); }))
328       .WillOnce(Invoke(getLoopAnalysisResult));
329   EXPECT_CALL(MLAHandle, run(HasName("loop.0.1"), _, _));
330   EXPECT_CALL(MLPHandle, run(HasName("loop.0"), _, _, _))
331       .WillOnce(DoDefault())
332       .WillOnce(Invoke(getLoopAnalysisResult));
333   EXPECT_CALL(MLPHandle, run(HasName("loop.g.0"), _, _, _))
334       .WillOnce(DoDefault())
335       .WillOnce(Invoke(getLoopAnalysisResult));
336   // Wire two loop pass runs into the module pipeline.
337   {
338     LoopPassManager LPM(true);
339     LPM.addPass(MLPHandle.getPass());
340     LPM.addPass(MLPHandle.getPass());
341     FunctionPassManager FPM(true);
342     FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM)));
343     MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
344   }
345 
346   // And now run the pipeline across the module.
347   MPM.run(*M, MAM);
348 }
349 
350 TEST_F(LoopPassManagerTest, FunctionPassInvalidationOfLoopAnalyses) {
351   ModulePassManager MPM(true);
352   FunctionPassManager FPM(true);
353   // We process each function completely in sequence.
354   ::testing::Sequence FSequence, GSequence;
355 
356   // First, force the analysis result to be computed for each loop.
357   EXPECT_CALL(MLAHandle, run(HasName("loop.0.0"), _, _))
358       .InSequence(FSequence)
359       .WillOnce(DoDefault());
360   EXPECT_CALL(MLAHandle, run(HasName("loop.0.1"), _, _))
361       .InSequence(FSequence)
362       .WillOnce(DoDefault());
363   EXPECT_CALL(MLAHandle, run(HasName("loop.0"), _, _))
364       .InSequence(FSequence)
365       .WillOnce(DoDefault());
366   EXPECT_CALL(MLAHandle, run(HasName("loop.g.0"), _, _))
367       .InSequence(GSequence)
368       .WillOnce(DoDefault());
369   FPM.addPass(createFunctionToLoopPassAdaptor(
370       RequireAnalysisLoopPass<MockLoopAnalysisHandle::Analysis>()));
371 
372   // No need to re-run if we require again from a fresh loop pass manager.
373   FPM.addPass(createFunctionToLoopPassAdaptor(
374       RequireAnalysisLoopPass<MockLoopAnalysisHandle::Analysis>()));
375 
376   // For 'f', preserve most things but not the specific loop analyses.
377   EXPECT_CALL(MFPHandle, run(HasName("f"), _))
378       .InSequence(FSequence)
379       .WillOnce(Return(getLoopPassPreservedAnalyses()));
380   EXPECT_CALL(MLAHandle, invalidate(HasName("loop.0.0"), _, _))
381       .InSequence(FSequence)
382       .WillOnce(DoDefault());
383   // On one loop, skip the invalidation (as though we did an internal update).
384   EXPECT_CALL(MLAHandle, invalidate(HasName("loop.0.1"), _, _))
385       .InSequence(FSequence)
386       .WillOnce(Return(false));
387   EXPECT_CALL(MLAHandle, invalidate(HasName("loop.0"), _, _))
388       .InSequence(FSequence)
389       .WillOnce(DoDefault());
390   // Now two loops still have to be recomputed.
391   EXPECT_CALL(MLAHandle, run(HasName("loop.0.0"), _, _))
392       .InSequence(FSequence)
393       .WillOnce(DoDefault());
394   EXPECT_CALL(MLAHandle, run(HasName("loop.0"), _, _))
395       .InSequence(FSequence)
396       .WillOnce(DoDefault());
397   // Preserve things in the second function to ensure invalidation remains
398   // isolated to one function.
399   EXPECT_CALL(MFPHandle, run(HasName("g"), _))
400       .InSequence(GSequence)
401       .WillOnce(DoDefault());
402   FPM.addPass(MFPHandle.getPass());
403   FPM.addPass(createFunctionToLoopPassAdaptor(
404       RequireAnalysisLoopPass<MockLoopAnalysisHandle::Analysis>()));
405 
406   EXPECT_CALL(MFPHandle, run(HasName("f"), _))
407       .InSequence(FSequence)
408       .WillOnce(DoDefault());
409   // For 'g', fail to preserve anything, causing the loops themselves to be
410   // cleared. We don't get an invalidation event here as the loop is gone, but
411   // we should still have to recompute the analysis.
412   EXPECT_CALL(MFPHandle, run(HasName("g"), _))
413       .InSequence(GSequence)
414       .WillOnce(Return(PreservedAnalyses::none()));
415   EXPECT_CALL(MLAHandle, run(HasName("loop.g.0"), _, _))
416       .InSequence(GSequence)
417       .WillOnce(DoDefault());
418   FPM.addPass(MFPHandle.getPass());
419   FPM.addPass(createFunctionToLoopPassAdaptor(
420       RequireAnalysisLoopPass<MockLoopAnalysisHandle::Analysis>()));
421 
422   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
423 
424   // Verify with a separate function pass run that we didn't mess up 'f's
425   // cache. No analysis runs should be necessary here.
426   MPM.addPass(createModuleToFunctionPassAdaptor(createFunctionToLoopPassAdaptor(
427       RequireAnalysisLoopPass<MockLoopAnalysisHandle::Analysis>())));
428 
429   MPM.run(*M, MAM);
430 }
431 
432 TEST_F(LoopPassManagerTest, ModulePassInvalidationOfLoopAnalyses) {
433   ModulePassManager MPM(true);
434   ::testing::InSequence MakeExpectationsSequenced;
435 
436   // First, force the analysis result to be computed for each loop.
437   EXPECT_CALL(MLAHandle, run(HasName("loop.0.0"), _, _));
438   EXPECT_CALL(MLAHandle, run(HasName("loop.0.1"), _, _));
439   EXPECT_CALL(MLAHandle, run(HasName("loop.0"), _, _));
440   EXPECT_CALL(MLAHandle, run(HasName("loop.g.0"), _, _));
441   MPM.addPass(createModuleToFunctionPassAdaptor(createFunctionToLoopPassAdaptor(
442       RequireAnalysisLoopPass<MockLoopAnalysisHandle::Analysis>())));
443 
444   // Walking all the way out and all the way back in doesn't re-run the
445   // analysis.
446   MPM.addPass(createModuleToFunctionPassAdaptor(createFunctionToLoopPassAdaptor(
447       RequireAnalysisLoopPass<MockLoopAnalysisHandle::Analysis>())));
448 
449   // But a module pass that doesn't preserve the actual mock loop analysis
450   // invalidates all the way down and forces recomputing.
451   EXPECT_CALL(MMPHandle, run(_, _)).WillOnce(InvokeWithoutArgs([] {
452     auto PA = getLoopPassPreservedAnalyses();
453     PA.preserve<FunctionAnalysisManagerModuleProxy>();
454     return PA;
455   }));
456   // All the loop analyses from both functions get invalidated before we
457   // recompute anything.
458   EXPECT_CALL(MLAHandle, invalidate(HasName("loop.0.0"), _, _));
459   // On one loop, again skip the invalidation (as though we did an internal
460   // update).
461   EXPECT_CALL(MLAHandle, invalidate(HasName("loop.0.1"), _, _))
462       .WillOnce(Return(false));
463   EXPECT_CALL(MLAHandle, invalidate(HasName("loop.0"), _, _));
464   EXPECT_CALL(MLAHandle, invalidate(HasName("loop.g.0"), _, _));
465   // Now all but one of the loops gets re-analyzed.
466   EXPECT_CALL(MLAHandle, run(HasName("loop.0.0"), _, _));
467   EXPECT_CALL(MLAHandle, run(HasName("loop.0"), _, _));
468   EXPECT_CALL(MLAHandle, run(HasName("loop.g.0"), _, _));
469   MPM.addPass(MMPHandle.getPass());
470   MPM.addPass(createModuleToFunctionPassAdaptor(createFunctionToLoopPassAdaptor(
471       RequireAnalysisLoopPass<MockLoopAnalysisHandle::Analysis>())));
472 
473   // Verify that the cached values persist.
474   MPM.addPass(createModuleToFunctionPassAdaptor(createFunctionToLoopPassAdaptor(
475       RequireAnalysisLoopPass<MockLoopAnalysisHandle::Analysis>())));
476 
477   // Now we fail to preserve the loop analysis and observe that the loop
478   // analyses are cleared (so no invalidation event) as the loops themselves
479   // are no longer valid.
480   EXPECT_CALL(MMPHandle, run(_, _)).WillOnce(InvokeWithoutArgs([] {
481     auto PA = PreservedAnalyses::none();
482     PA.preserve<FunctionAnalysisManagerModuleProxy>();
483     return PA;
484   }));
485   EXPECT_CALL(MLAHandle, run(HasName("loop.0.0"), _, _));
486   EXPECT_CALL(MLAHandle, run(HasName("loop.0.1"), _, _));
487   EXPECT_CALL(MLAHandle, run(HasName("loop.0"), _, _));
488   EXPECT_CALL(MLAHandle, run(HasName("loop.g.0"), _, _));
489   MPM.addPass(MMPHandle.getPass());
490   MPM.addPass(createModuleToFunctionPassAdaptor(createFunctionToLoopPassAdaptor(
491       RequireAnalysisLoopPass<MockLoopAnalysisHandle::Analysis>())));
492 
493   // Verify that the cached values persist.
494   MPM.addPass(createModuleToFunctionPassAdaptor(createFunctionToLoopPassAdaptor(
495       RequireAnalysisLoopPass<MockLoopAnalysisHandle::Analysis>())));
496 
497   // Next, check that even if we preserve everything within the function itelf,
498   // if the function's module pass proxy isn't preserved and the potential set
499   // of functions changes, the clear reaches the loop analyses as well. This
500   // will again trigger re-runs but not invalidation events.
501   EXPECT_CALL(MMPHandle, run(_, _)).WillOnce(InvokeWithoutArgs([] {
502     auto PA = PreservedAnalyses::none();
503     PA.preserveSet<AllAnalysesOn<Function>>();
504     PA.preserveSet<AllAnalysesOn<Loop>>();
505     return PA;
506   }));
507   EXPECT_CALL(MLAHandle, run(HasName("loop.0.0"), _, _));
508   EXPECT_CALL(MLAHandle, run(HasName("loop.0.1"), _, _));
509   EXPECT_CALL(MLAHandle, run(HasName("loop.0"), _, _));
510   EXPECT_CALL(MLAHandle, run(HasName("loop.g.0"), _, _));
511   MPM.addPass(MMPHandle.getPass());
512   MPM.addPass(createModuleToFunctionPassAdaptor(createFunctionToLoopPassAdaptor(
513       RequireAnalysisLoopPass<MockLoopAnalysisHandle::Analysis>())));
514 
515   MPM.run(*M, MAM);
516 }
517 
518 // Test that if any of the bundled analyses provided in the LPM's signature
519 // become invalid, the analysis proxy itself becomes invalid and we clear all
520 // loop analysis results.
521 TEST_F(LoopPassManagerTest, InvalidationOfBundledAnalyses) {
522   ModulePassManager MPM(true);
523   FunctionPassManager FPM(true);
524   ::testing::InSequence MakeExpectationsSequenced;
525 
526   // First, force the analysis result to be computed for each loop.
527   EXPECT_CALL(MLAHandle, run(HasName("loop.0.0"), _, _));
528   EXPECT_CALL(MLAHandle, run(HasName("loop.0.1"), _, _));
529   EXPECT_CALL(MLAHandle, run(HasName("loop.0"), _, _));
530   FPM.addPass(createFunctionToLoopPassAdaptor(
531       RequireAnalysisLoopPass<MockLoopAnalysisHandle::Analysis>()));
532 
533   // No need to re-run if we require again from a fresh loop pass manager.
534   FPM.addPass(createFunctionToLoopPassAdaptor(
535       RequireAnalysisLoopPass<MockLoopAnalysisHandle::Analysis>()));
536 
537   // Preserving everything but the loop analyses themselves results in
538   // invalidation and running.
539   EXPECT_CALL(MFPHandle, run(HasName("f"), _))
540       .WillOnce(Return(getLoopPassPreservedAnalyses()));
541   EXPECT_CALL(MLAHandle, invalidate(_, _, _)).Times(3);
542   EXPECT_CALL(MLAHandle, run(HasName("loop.0.0"), _, _));
543   EXPECT_CALL(MLAHandle, run(HasName("loop.0.1"), _, _));
544   EXPECT_CALL(MLAHandle, run(HasName("loop.0"), _, _));
545   FPM.addPass(MFPHandle.getPass());
546   FPM.addPass(createFunctionToLoopPassAdaptor(
547       RequireAnalysisLoopPass<MockLoopAnalysisHandle::Analysis>()));
548 
549   // The rest don't invalidate analyses, they only trigger re-runs because we
550   // clear the cache completely.
551   EXPECT_CALL(MFPHandle, run(HasName("f"), _)).WillOnce(InvokeWithoutArgs([] {
552     auto PA = PreservedAnalyses::none();
553     // Not preserving `AAManager`.
554     PA.preserve<DominatorTreeAnalysis>();
555     PA.preserve<LoopAnalysis>();
556     PA.preserve<LoopAnalysisManagerFunctionProxy>();
557     PA.preserve<ScalarEvolutionAnalysis>();
558     return PA;
559   }));
560   EXPECT_CALL(MLAHandle, run(HasName("loop.0.0"), _, _));
561   EXPECT_CALL(MLAHandle, run(HasName("loop.0.1"), _, _));
562   EXPECT_CALL(MLAHandle, run(HasName("loop.0"), _, _));
563   FPM.addPass(MFPHandle.getPass());
564   FPM.addPass(createFunctionToLoopPassAdaptor(
565       RequireAnalysisLoopPass<MockLoopAnalysisHandle::Analysis>()));
566 
567   EXPECT_CALL(MFPHandle, run(HasName("f"), _)).WillOnce(InvokeWithoutArgs([] {
568     auto PA = PreservedAnalyses::none();
569     PA.preserve<AAManager>();
570     // Not preserving `DominatorTreeAnalysis`.
571     PA.preserve<LoopAnalysis>();
572     PA.preserve<LoopAnalysisManagerFunctionProxy>();
573     PA.preserve<ScalarEvolutionAnalysis>();
574     return PA;
575   }));
576   EXPECT_CALL(MLAHandle, run(HasName("loop.0.0"), _, _));
577   EXPECT_CALL(MLAHandle, run(HasName("loop.0.1"), _, _));
578   EXPECT_CALL(MLAHandle, run(HasName("loop.0"), _, _));
579   FPM.addPass(MFPHandle.getPass());
580   FPM.addPass(createFunctionToLoopPassAdaptor(
581       RequireAnalysisLoopPass<MockLoopAnalysisHandle::Analysis>()));
582 
583   EXPECT_CALL(MFPHandle, run(HasName("f"), _)).WillOnce(InvokeWithoutArgs([] {
584     auto PA = PreservedAnalyses::none();
585     PA.preserve<AAManager>();
586     PA.preserve<DominatorTreeAnalysis>();
587     // Not preserving the `LoopAnalysis`.
588     PA.preserve<LoopAnalysisManagerFunctionProxy>();
589     PA.preserve<ScalarEvolutionAnalysis>();
590     return PA;
591   }));
592   EXPECT_CALL(MLAHandle, run(HasName("loop.0.0"), _, _));
593   EXPECT_CALL(MLAHandle, run(HasName("loop.0.1"), _, _));
594   EXPECT_CALL(MLAHandle, run(HasName("loop.0"), _, _));
595   FPM.addPass(MFPHandle.getPass());
596   FPM.addPass(createFunctionToLoopPassAdaptor(
597       RequireAnalysisLoopPass<MockLoopAnalysisHandle::Analysis>()));
598 
599   EXPECT_CALL(MFPHandle, run(HasName("f"), _)).WillOnce(InvokeWithoutArgs([] {
600     auto PA = PreservedAnalyses::none();
601     PA.preserve<AAManager>();
602     PA.preserve<DominatorTreeAnalysis>();
603     PA.preserve<LoopAnalysis>();
604     // Not preserving the `LoopAnalysisManagerFunctionProxy`.
605     PA.preserve<ScalarEvolutionAnalysis>();
606     return PA;
607   }));
608   EXPECT_CALL(MLAHandle, run(HasName("loop.0.0"), _, _));
609   EXPECT_CALL(MLAHandle, run(HasName("loop.0.1"), _, _));
610   EXPECT_CALL(MLAHandle, run(HasName("loop.0"), _, _));
611   FPM.addPass(MFPHandle.getPass());
612   FPM.addPass(createFunctionToLoopPassAdaptor(
613       RequireAnalysisLoopPass<MockLoopAnalysisHandle::Analysis>()));
614 
615   EXPECT_CALL(MFPHandle, run(HasName("f"), _)).WillOnce(InvokeWithoutArgs([] {
616     auto PA = PreservedAnalyses::none();
617     PA.preserve<AAManager>();
618     PA.preserve<DominatorTreeAnalysis>();
619     PA.preserve<LoopAnalysis>();
620     PA.preserve<LoopAnalysisManagerFunctionProxy>();
621     // Not preserving `ScalarEvolutionAnalysis`.
622     return PA;
623   }));
624   EXPECT_CALL(MLAHandle, run(HasName("loop.0.0"), _, _));
625   EXPECT_CALL(MLAHandle, run(HasName("loop.0.1"), _, _));
626   EXPECT_CALL(MLAHandle, run(HasName("loop.0"), _, _));
627   FPM.addPass(MFPHandle.getPass());
628   FPM.addPass(createFunctionToLoopPassAdaptor(
629       RequireAnalysisLoopPass<MockLoopAnalysisHandle::Analysis>()));
630 
631   // After all the churn on 'f', we'll compute the loop analysis results for
632   // 'g' once with a requires pass and then run our mock pass over g a bunch
633   // but just get cached results each time.
634   EXPECT_CALL(MLAHandle, run(HasName("loop.g.0"), _, _));
635   EXPECT_CALL(MFPHandle, run(HasName("g"), _)).Times(6);
636 
637   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
638   MPM.run(*M, MAM);
639 }
640 
641 TEST_F(LoopPassManagerTest, IndirectInvalidation) {
642   // We need two distinct analysis types and handles.
643   enum { A, B };
644   MockLoopAnalysisHandleTemplate<A> MLAHandleA;
645   MockLoopAnalysisHandleTemplate<B> MLAHandleB;
646   LAM.registerPass([&] { return MLAHandleA.getAnalysis(); });
647   LAM.registerPass([&] { return MLAHandleB.getAnalysis(); });
648   typedef decltype(MLAHandleA)::Analysis AnalysisA;
649   typedef decltype(MLAHandleB)::Analysis AnalysisB;
650 
651   // Set up AnalysisA to depend on our AnalysisB. For testing purposes we just
652   // need to get the AnalysisB results in AnalysisA's run method and check if
653   // AnalysisB gets invalidated in AnalysisA's invalidate method.
654   ON_CALL(MLAHandleA, run(_, _, _))
655       .WillByDefault(Invoke([&](Loop &L, LoopAnalysisManager &AM,
656                                 LoopStandardAnalysisResults &AR) {
657         (void)AM.getResult<AnalysisB>(L, AR);
658         return MLAHandleA.getResult();
659       }));
660   ON_CALL(MLAHandleA, invalidate(_, _, _))
661       .WillByDefault(Invoke([](Loop &L, const PreservedAnalyses &PA,
662                                LoopAnalysisManager::Invalidator &Inv) {
663         auto PAC = PA.getChecker<AnalysisA>();
664         return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Loop>>()) ||
665                Inv.invalidate<AnalysisB>(L, PA);
666       }));
667 
668   ::testing::InSequence MakeExpectationsSequenced;
669 
670   // Compute the analyses across all of 'f' first.
671   EXPECT_CALL(MLAHandleA, run(HasName("loop.0.0"), _, _));
672   EXPECT_CALL(MLAHandleB, run(HasName("loop.0.0"), _, _));
673   EXPECT_CALL(MLAHandleA, run(HasName("loop.0.1"), _, _));
674   EXPECT_CALL(MLAHandleB, run(HasName("loop.0.1"), _, _));
675   EXPECT_CALL(MLAHandleA, run(HasName("loop.0"), _, _));
676   EXPECT_CALL(MLAHandleB, run(HasName("loop.0"), _, _));
677 
678   // Now we invalidate AnalysisB (but not AnalysisA) for one of the loops and
679   // preserve everything for the rest. This in turn triggers that one loop to
680   // recompute both AnalysisB *and* AnalysisA if indirect invalidation is
681   // working.
682   EXPECT_CALL(MLPHandle, run(HasName("loop.0.0"), _, _, _))
683       .WillOnce(InvokeWithoutArgs([] {
684         auto PA = getLoopPassPreservedAnalyses();
685         // Specifically preserve AnalysisA so that it would survive if it
686         // didn't depend on AnalysisB.
687         PA.preserve<AnalysisA>();
688         return PA;
689       }));
690   // It happens that AnalysisB is invalidated first. That shouldn't matter
691   // though, and we should still call AnalysisA's invalidation.
692   EXPECT_CALL(MLAHandleB, invalidate(HasName("loop.0.0"), _, _));
693   EXPECT_CALL(MLAHandleA, invalidate(HasName("loop.0.0"), _, _));
694   EXPECT_CALL(MLPHandle, run(HasName("loop.0.0"), _, _, _))
695       .WillOnce(Invoke([](Loop &L, LoopAnalysisManager &AM,
696                           LoopStandardAnalysisResults &AR, LPMUpdater &) {
697         (void)AM.getResult<AnalysisA>(L, AR);
698         return PreservedAnalyses::all();
699       }));
700   EXPECT_CALL(MLAHandleA, run(HasName("loop.0.0"), _, _));
701   EXPECT_CALL(MLAHandleB, run(HasName("loop.0.0"), _, _));
702   // The rest of the loops should run and get cached results.
703   EXPECT_CALL(MLPHandle, run(HasName("loop.0.1"), _, _, _))
704       .Times(2)
705       .WillRepeatedly(Invoke([](Loop &L, LoopAnalysisManager &AM,
706                                 LoopStandardAnalysisResults &AR, LPMUpdater &) {
707         (void)AM.getResult<AnalysisA>(L, AR);
708         return PreservedAnalyses::all();
709       }));
710   EXPECT_CALL(MLPHandle, run(HasName("loop.0"), _, _, _))
711       .Times(2)
712       .WillRepeatedly(Invoke([](Loop &L, LoopAnalysisManager &AM,
713                                 LoopStandardAnalysisResults &AR, LPMUpdater &) {
714         (void)AM.getResult<AnalysisA>(L, AR);
715         return PreservedAnalyses::all();
716       }));
717 
718   // The run over 'g' should be boring, with us just computing the analyses once
719   // up front and then running loop passes and getting cached results.
720   EXPECT_CALL(MLAHandleA, run(HasName("loop.g.0"), _, _));
721   EXPECT_CALL(MLAHandleB, run(HasName("loop.g.0"), _, _));
722   EXPECT_CALL(MLPHandle, run(HasName("loop.g.0"), _, _, _))
723       .Times(2)
724       .WillRepeatedly(Invoke([](Loop &L, LoopAnalysisManager &AM,
725                                 LoopStandardAnalysisResults &AR, LPMUpdater &) {
726         (void)AM.getResult<AnalysisA>(L, AR);
727         return PreservedAnalyses::all();
728       }));
729 
730   // Build the pipeline and run it.
731   ModulePassManager MPM(true);
732   FunctionPassManager FPM(true);
733   FPM.addPass(
734       createFunctionToLoopPassAdaptor(RequireAnalysisLoopPass<AnalysisA>()));
735   LoopPassManager LPM(true);
736   LPM.addPass(MLPHandle.getPass());
737   LPM.addPass(MLPHandle.getPass());
738   FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM)));
739   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
740   MPM.run(*M, MAM);
741 }
742 
743 TEST_F(LoopPassManagerTest, IndirectOuterPassInvalidation) {
744   typedef decltype(MLAHandle)::Analysis LoopAnalysis;
745 
746   MockFunctionAnalysisHandle MFAHandle;
747   FAM.registerPass([&] { return MFAHandle.getAnalysis(); });
748   typedef decltype(MFAHandle)::Analysis FunctionAnalysis;
749 
750   // Set up the loop analysis to depend on both the function and module
751   // analysis.
752   ON_CALL(MLAHandle, run(_, _, _))
753       .WillByDefault(Invoke([&](Loop &L, LoopAnalysisManager &AM,
754                                 LoopStandardAnalysisResults &AR) {
755         auto &FAMP = AM.getResult<FunctionAnalysisManagerLoopProxy>(L, AR);
756         auto &FAM = FAMP.getManager();
757         Function &F = *L.getHeader()->getParent();
758         if (FAM.getCachedResult<FunctionAnalysis>(F))
759           FAMP.registerOuterAnalysisInvalidation<FunctionAnalysis,
760                                                  LoopAnalysis>();
761         return MLAHandle.getResult();
762       }));
763 
764   ::testing::InSequence MakeExpectationsSequenced;
765 
766   // Compute the analyses across all of 'f' first.
767   EXPECT_CALL(MFPHandle, run(HasName("f"), _))
768       .WillOnce(Invoke([](Function &F, FunctionAnalysisManager &AM) {
769         // Force the computing of the function analysis so it is available in
770         // this function.
771         (void)AM.getResult<FunctionAnalysis>(F);
772         return PreservedAnalyses::all();
773       }));
774   EXPECT_CALL(MLAHandle, run(HasName("loop.0.0"), _, _));
775   EXPECT_CALL(MLAHandle, run(HasName("loop.0.1"), _, _));
776   EXPECT_CALL(MLAHandle, run(HasName("loop.0"), _, _));
777 
778   // Now invalidate the function analysis but preserve the loop analyses.
779   // This should trigger immediate invalidation of the loop analyses, despite
780   // the fact that they were preserved.
781   EXPECT_CALL(MFPHandle, run(HasName("f"), _)).WillOnce(InvokeWithoutArgs([] {
782     auto PA = getLoopPassPreservedAnalyses();
783     PA.preserveSet<AllAnalysesOn<Loop>>();
784     return PA;
785   }));
786   EXPECT_CALL(MLAHandle, invalidate(HasName("loop.0.0"), _, _));
787   EXPECT_CALL(MLAHandle, invalidate(HasName("loop.0.1"), _, _));
788   EXPECT_CALL(MLAHandle, invalidate(HasName("loop.0"), _, _));
789 
790   // And re-running a requires pass recomputes them.
791   EXPECT_CALL(MLAHandle, run(HasName("loop.0.0"), _, _));
792   EXPECT_CALL(MLAHandle, run(HasName("loop.0.1"), _, _));
793   EXPECT_CALL(MLAHandle, run(HasName("loop.0"), _, _));
794 
795   // When we run over 'g' we don't populate the cache with the function
796   // analysis.
797   EXPECT_CALL(MFPHandle, run(HasName("g"), _))
798       .WillOnce(Return(PreservedAnalyses::all()));
799   EXPECT_CALL(MLAHandle, run(HasName("loop.g.0"), _, _));
800 
801   // Which means that no extra invalidation occurs and cached values are used.
802   EXPECT_CALL(MFPHandle, run(HasName("g"), _)).WillOnce(InvokeWithoutArgs([] {
803     auto PA = getLoopPassPreservedAnalyses();
804     PA.preserveSet<AllAnalysesOn<Loop>>();
805     return PA;
806   }));
807 
808   // Build the pipeline and run it.
809   ModulePassManager MPM(true);
810   FunctionPassManager FPM(true);
811   FPM.addPass(MFPHandle.getPass());
812   FPM.addPass(
813       createFunctionToLoopPassAdaptor(RequireAnalysisLoopPass<LoopAnalysis>()));
814   FPM.addPass(MFPHandle.getPass());
815   FPM.addPass(
816       createFunctionToLoopPassAdaptor(RequireAnalysisLoopPass<LoopAnalysis>()));
817   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
818   MPM.run(*M, MAM);
819 }
820 
821 TEST_F(LoopPassManagerTest, LoopChildInsertion) {
822   // Super boring module with three loops in a single loop nest.
823   M = parseIR(Context, "define void @f() {\n"
824                        "entry:\n"
825                        "  br label %loop.0\n"
826                        "loop.0:\n"
827                        "  br i1 undef, label %loop.0.0, label %end\n"
828                        "loop.0.0:\n"
829                        "  br i1 undef, label %loop.0.0, label %loop.0.1\n"
830                        "loop.0.1:\n"
831                        "  br i1 undef, label %loop.0.1, label %loop.0.2\n"
832                        "loop.0.2:\n"
833                        "  br i1 undef, label %loop.0.2, label %loop.0\n"
834                        "end:\n"
835                        "  ret void\n"
836                        "}\n");
837 
838   // Build up variables referring into the IR so we can rewrite it below
839   // easily.
840   Function &F = *M->begin();
841   ASSERT_THAT(F, HasName("f"));
842   auto BBI = F.begin();
843   BasicBlock &EntryBB = *BBI++;
844   ASSERT_THAT(EntryBB, HasName("entry"));
845   BasicBlock &Loop0BB = *BBI++;
846   ASSERT_THAT(Loop0BB, HasName("loop.0"));
847   BasicBlock &Loop00BB = *BBI++;
848   ASSERT_THAT(Loop00BB, HasName("loop.0.0"));
849   BasicBlock &Loop01BB = *BBI++;
850   ASSERT_THAT(Loop01BB, HasName("loop.0.1"));
851   BasicBlock &Loop02BB = *BBI++;
852   ASSERT_THAT(Loop02BB, HasName("loop.0.2"));
853   BasicBlock &EndBB = *BBI++;
854   ASSERT_THAT(EndBB, HasName("end"));
855   ASSERT_THAT(BBI, F.end());
856 
857   // Build the pass managers and register our pipeline. We build a single loop
858   // pass pipeline consisting of three mock pass runs over each loop. After
859   // this we run both domtree and loop verification passes to make sure that
860   // the IR remained valid during our mutations.
861   ModulePassManager MPM(true);
862   FunctionPassManager FPM(true);
863   LoopPassManager LPM(true);
864   LPM.addPass(MLPHandle.getPass());
865   LPM.addPass(MLPHandle.getPass());
866   LPM.addPass(MLPHandle.getPass());
867   FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM)));
868   FPM.addPass(DominatorTreeVerifierPass());
869   FPM.addPass(LoopVerifierPass());
870   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
871 
872   // All the visit orders are deterministic, so we use simple fully order
873   // expectations.
874   ::testing::InSequence MakeExpectationsSequenced;
875 
876   // We run loop passes three times over each of the loops.
877   EXPECT_CALL(MLPHandle, run(HasName("loop.0.0"), _, _, _))
878       .WillOnce(Invoke(getLoopAnalysisResult));
879   EXPECT_CALL(MLAHandle, run(HasName("loop.0.0"), _, _));
880   EXPECT_CALL(MLPHandle, run(HasName("loop.0.0"), _, _, _))
881       .Times(2)
882       .WillRepeatedly(Invoke(getLoopAnalysisResult));
883 
884   EXPECT_CALL(MLPHandle, run(HasName("loop.0.1"), _, _, _))
885       .WillOnce(Invoke(getLoopAnalysisResult));
886   EXPECT_CALL(MLAHandle, run(HasName("loop.0.1"), _, _));
887 
888   // When running over the middle loop, the second run inserts two new child
889   // loops, inserting them and itself into the worklist.
890   BasicBlock *NewLoop010BB;
891   EXPECT_CALL(MLPHandle, run(HasName("loop.0.1"), _, _, _))
892       .WillOnce(Invoke([&](Loop &L, LoopAnalysisManager &AM,
893                            LoopStandardAnalysisResults &AR,
894                            LPMUpdater &Updater) {
895         auto *NewLoop = new Loop();
896         L.addChildLoop(NewLoop);
897         NewLoop010BB = BasicBlock::Create(Context, "loop.0.1.0", &F, &Loop02BB);
898         BranchInst::Create(&Loop01BB, NewLoop010BB,
899                            UndefValue::get(Type::getInt1Ty(Context)),
900                            NewLoop010BB);
901         Loop01BB.getTerminator()->replaceUsesOfWith(&Loop01BB, NewLoop010BB);
902         AR.DT.addNewBlock(NewLoop010BB, &Loop01BB);
903         NewLoop->addBasicBlockToLoop(NewLoop010BB, AR.LI);
904         Updater.addChildLoops({NewLoop});
905         return PreservedAnalyses::all();
906       }));
907 
908   // We should immediately drop down to fully visit the new inner loop.
909   EXPECT_CALL(MLPHandle, run(HasName("loop.0.1.0"), _, _, _))
910       .WillOnce(Invoke(getLoopAnalysisResult));
911   EXPECT_CALL(MLAHandle, run(HasName("loop.0.1.0"), _, _));
912   EXPECT_CALL(MLPHandle, run(HasName("loop.0.1.0"), _, _, _))
913       .Times(2)
914       .WillRepeatedly(Invoke(getLoopAnalysisResult));
915 
916   // After visiting the inner loop, we should re-visit the second loop
917   // reflecting its new loop nest structure.
918   EXPECT_CALL(MLPHandle, run(HasName("loop.0.1"), _, _, _))
919       .WillOnce(Invoke(getLoopAnalysisResult));
920 
921   // In the second run over the middle loop after we've visited the new child,
922   // we add another child to check that we can repeatedly add children, and add
923   // children to a loop that already has children.
924   BasicBlock *NewLoop011BB;
925   EXPECT_CALL(MLPHandle, run(HasName("loop.0.1"), _, _, _))
926       .WillOnce(Invoke([&](Loop &L, LoopAnalysisManager &AM,
927                            LoopStandardAnalysisResults &AR,
928                            LPMUpdater &Updater) {
929         auto *NewLoop = new Loop();
930         L.addChildLoop(NewLoop);
931         NewLoop011BB = BasicBlock::Create(Context, "loop.0.1.1", &F, &Loop02BB);
932         BranchInst::Create(&Loop01BB, NewLoop011BB,
933                            UndefValue::get(Type::getInt1Ty(Context)),
934                            NewLoop011BB);
935         NewLoop010BB->getTerminator()->replaceUsesOfWith(&Loop01BB,
936                                                          NewLoop011BB);
937         AR.DT.addNewBlock(NewLoop011BB, NewLoop010BB);
938         NewLoop->addBasicBlockToLoop(NewLoop011BB, AR.LI);
939         Updater.addChildLoops({NewLoop});
940         return PreservedAnalyses::all();
941       }));
942 
943   // Again, we should immediately drop down to visit the new, unvisited child
944   // loop. We don't need to revisit the other child though.
945   EXPECT_CALL(MLPHandle, run(HasName("loop.0.1.1"), _, _, _))
946       .WillOnce(Invoke(getLoopAnalysisResult));
947   EXPECT_CALL(MLAHandle, run(HasName("loop.0.1.1"), _, _));
948   EXPECT_CALL(MLPHandle, run(HasName("loop.0.1.1"), _, _, _))
949       .Times(2)
950       .WillRepeatedly(Invoke(getLoopAnalysisResult));
951 
952   // And now we should pop back up to the second loop and do a full pipeline of
953   // three passes on its current form.
954   EXPECT_CALL(MLPHandle, run(HasName("loop.0.1"), _, _, _))
955       .Times(3)
956       .WillRepeatedly(Invoke(getLoopAnalysisResult));
957 
958   EXPECT_CALL(MLPHandle, run(HasName("loop.0.2"), _, _, _))
959       .WillOnce(Invoke(getLoopAnalysisResult));
960   EXPECT_CALL(MLAHandle, run(HasName("loop.0.2"), _, _));
961   EXPECT_CALL(MLPHandle, run(HasName("loop.0.2"), _, _, _))
962       .Times(2)
963       .WillRepeatedly(Invoke(getLoopAnalysisResult));
964 
965   EXPECT_CALL(MLPHandle, run(HasName("loop.0"), _, _, _))
966       .WillOnce(Invoke(getLoopAnalysisResult));
967   EXPECT_CALL(MLAHandle, run(HasName("loop.0"), _, _));
968   EXPECT_CALL(MLPHandle, run(HasName("loop.0"), _, _, _))
969       .Times(2)
970       .WillRepeatedly(Invoke(getLoopAnalysisResult));
971 
972   // Now that all the expected actions are registered, run the pipeline over
973   // our module. All of our expectations are verified when the test finishes.
974   MPM.run(*M, MAM);
975 }
976 
977 TEST_F(LoopPassManagerTest, LoopPeerInsertion) {
978   // Super boring module with two loop nests and loop nest with two child
979   // loops.
980   M = parseIR(Context, "define void @f() {\n"
981                        "entry:\n"
982                        "  br label %loop.0\n"
983                        "loop.0:\n"
984                        "  br i1 undef, label %loop.0.0, label %loop.2\n"
985                        "loop.0.0:\n"
986                        "  br i1 undef, label %loop.0.0, label %loop.0.2\n"
987                        "loop.0.2:\n"
988                        "  br i1 undef, label %loop.0.2, label %loop.0\n"
989                        "loop.2:\n"
990                        "  br i1 undef, label %loop.2, label %end\n"
991                        "end:\n"
992                        "  ret void\n"
993                        "}\n");
994 
995   // Build up variables referring into the IR so we can rewrite it below
996   // easily.
997   Function &F = *M->begin();
998   ASSERT_THAT(F, HasName("f"));
999   auto BBI = F.begin();
1000   BasicBlock &EntryBB = *BBI++;
1001   ASSERT_THAT(EntryBB, HasName("entry"));
1002   BasicBlock &Loop0BB = *BBI++;
1003   ASSERT_THAT(Loop0BB, HasName("loop.0"));
1004   BasicBlock &Loop00BB = *BBI++;
1005   ASSERT_THAT(Loop00BB, HasName("loop.0.0"));
1006   BasicBlock &Loop02BB = *BBI++;
1007   ASSERT_THAT(Loop02BB, HasName("loop.0.2"));
1008   BasicBlock &Loop2BB = *BBI++;
1009   ASSERT_THAT(Loop2BB, HasName("loop.2"));
1010   BasicBlock &EndBB = *BBI++;
1011   ASSERT_THAT(EndBB, HasName("end"));
1012   ASSERT_THAT(BBI, F.end());
1013   Constant *Undefi1 = UndefValue::get(Type::getInt1Ty(Context));
1014 
1015   // Build the pass managers and register our pipeline. We build a single loop
1016   // pass pipeline consisting of three mock pass runs over each loop. After
1017   // this we run both domtree and loop verification passes to make sure that
1018   // the IR remained valid during our mutations.
1019   ModulePassManager MPM(true);
1020   FunctionPassManager FPM(true);
1021   LoopPassManager LPM(true);
1022   LPM.addPass(MLPHandle.getPass());
1023   LPM.addPass(MLPHandle.getPass());
1024   LPM.addPass(MLPHandle.getPass());
1025   FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM)));
1026   FPM.addPass(DominatorTreeVerifierPass());
1027   FPM.addPass(LoopVerifierPass());
1028   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1029 
1030   // All the visit orders are deterministic, so we use simple fully order
1031   // expectations.
1032   ::testing::InSequence MakeExpectationsSequenced;
1033 
1034   // We run loop passes three times over each of the loops.
1035   EXPECT_CALL(MLPHandle, run(HasName("loop.0.0"), _, _, _))
1036       .WillOnce(Invoke(getLoopAnalysisResult));
1037   EXPECT_CALL(MLAHandle, run(HasName("loop.0.0"), _, _));
1038 
1039   // On the second run, we insert a sibling loop.
1040   BasicBlock *NewLoop01BB;
1041   EXPECT_CALL(MLPHandle, run(HasName("loop.0.0"), _, _, _))
1042       .WillOnce(Invoke([&](Loop &L, LoopAnalysisManager &AM,
1043                            LoopStandardAnalysisResults &AR,
1044                            LPMUpdater &Updater) {
1045         auto *NewLoop = new Loop();
1046         L.getParentLoop()->addChildLoop(NewLoop);
1047         NewLoop01BB = BasicBlock::Create(Context, "loop.0.1", &F, &Loop02BB);
1048         BranchInst::Create(&Loop02BB, NewLoop01BB, Undefi1, NewLoop01BB);
1049         Loop00BB.getTerminator()->replaceUsesOfWith(&Loop02BB, NewLoop01BB);
1050         auto *NewDTNode = AR.DT.addNewBlock(NewLoop01BB, &Loop00BB);
1051         AR.DT.changeImmediateDominator(AR.DT[&Loop02BB], NewDTNode);
1052         NewLoop->addBasicBlockToLoop(NewLoop01BB, AR.LI);
1053         Updater.addSiblingLoops({NewLoop});
1054         return PreservedAnalyses::all();
1055       }));
1056   // We finish processing this loop as sibling loops don't perturb the
1057   // postorder walk.
1058   EXPECT_CALL(MLPHandle, run(HasName("loop.0.0"), _, _, _))
1059       .WillOnce(Invoke(getLoopAnalysisResult));
1060 
1061   // We visit the inserted sibling next.
1062   EXPECT_CALL(MLPHandle, run(HasName("loop.0.1"), _, _, _))
1063       .WillOnce(Invoke(getLoopAnalysisResult));
1064   EXPECT_CALL(MLAHandle, run(HasName("loop.0.1"), _, _));
1065   EXPECT_CALL(MLPHandle, run(HasName("loop.0.1"), _, _, _))
1066       .Times(2)
1067       .WillRepeatedly(Invoke(getLoopAnalysisResult));
1068 
1069   EXPECT_CALL(MLPHandle, run(HasName("loop.0.2"), _, _, _))
1070       .WillOnce(Invoke(getLoopAnalysisResult));
1071   EXPECT_CALL(MLAHandle, run(HasName("loop.0.2"), _, _));
1072   EXPECT_CALL(MLPHandle, run(HasName("loop.0.2"), _, _, _))
1073       .WillOnce(Invoke(getLoopAnalysisResult));
1074   // Next, on the third pass run on the last inner loop we add more new
1075   // siblings, more than one, and one with nested child loops. By doing this at
1076   // the end we make sure that edge case works well.
1077   EXPECT_CALL(MLPHandle, run(HasName("loop.0.2"), _, _, _))
1078       .WillOnce(Invoke([&](Loop &L, LoopAnalysisManager &AM,
1079                            LoopStandardAnalysisResults &AR,
1080                            LPMUpdater &Updater) {
1081         Loop *NewLoops[] = {new Loop(), new Loop(), new Loop()};
1082         L.getParentLoop()->addChildLoop(NewLoops[0]);
1083         L.getParentLoop()->addChildLoop(NewLoops[1]);
1084         NewLoops[1]->addChildLoop(NewLoops[2]);
1085         auto *NewLoop03BB =
1086             BasicBlock::Create(Context, "loop.0.3", &F, &Loop2BB);
1087         auto *NewLoop04BB =
1088             BasicBlock::Create(Context, "loop.0.4", &F, &Loop2BB);
1089         auto *NewLoop040BB =
1090             BasicBlock::Create(Context, "loop.0.4.0", &F, &Loop2BB);
1091         Loop02BB.getTerminator()->replaceUsesOfWith(&Loop0BB, NewLoop03BB);
1092         BranchInst::Create(NewLoop04BB, NewLoop03BB, Undefi1, NewLoop03BB);
1093         BranchInst::Create(&Loop0BB, NewLoop040BB, Undefi1, NewLoop04BB);
1094         BranchInst::Create(NewLoop04BB, NewLoop040BB, Undefi1, NewLoop040BB);
1095         AR.DT.addNewBlock(NewLoop03BB, &Loop02BB);
1096         AR.DT.addNewBlock(NewLoop04BB, NewLoop03BB);
1097         AR.DT.addNewBlock(NewLoop040BB, NewLoop04BB);
1098         NewLoops[0]->addBasicBlockToLoop(NewLoop03BB, AR.LI);
1099         NewLoops[1]->addBasicBlockToLoop(NewLoop04BB, AR.LI);
1100         NewLoops[2]->addBasicBlockToLoop(NewLoop040BB, AR.LI);
1101         Updater.addSiblingLoops({NewLoops[0], NewLoops[1]});
1102         return PreservedAnalyses::all();
1103       }));
1104 
1105   EXPECT_CALL(MLPHandle, run(HasName("loop.0.3"), _, _, _))
1106       .WillOnce(Invoke(getLoopAnalysisResult));
1107   EXPECT_CALL(MLAHandle, run(HasName("loop.0.3"), _, _));
1108   EXPECT_CALL(MLPHandle, run(HasName("loop.0.3"), _, _, _))
1109       .Times(2)
1110       .WillRepeatedly(Invoke(getLoopAnalysisResult));
1111 
1112   // Note that we need to visit the inner loop of this added sibling before the
1113   // sibling itself!
1114   EXPECT_CALL(MLPHandle, run(HasName("loop.0.4.0"), _, _, _))
1115       .WillOnce(Invoke(getLoopAnalysisResult));
1116   EXPECT_CALL(MLAHandle, run(HasName("loop.0.4.0"), _, _));
1117   EXPECT_CALL(MLPHandle, run(HasName("loop.0.4.0"), _, _, _))
1118       .Times(2)
1119       .WillRepeatedly(Invoke(getLoopAnalysisResult));
1120 
1121   EXPECT_CALL(MLPHandle, run(HasName("loop.0.4"), _, _, _))
1122       .WillOnce(Invoke(getLoopAnalysisResult));
1123   EXPECT_CALL(MLAHandle, run(HasName("loop.0.4"), _, _));
1124   EXPECT_CALL(MLPHandle, run(HasName("loop.0.4"), _, _, _))
1125       .Times(2)
1126       .WillRepeatedly(Invoke(getLoopAnalysisResult));
1127 
1128   // And only now do we visit the outermost loop of the nest.
1129   EXPECT_CALL(MLPHandle, run(HasName("loop.0"), _, _, _))
1130       .WillOnce(Invoke(getLoopAnalysisResult));
1131   EXPECT_CALL(MLAHandle, run(HasName("loop.0"), _, _));
1132   // On the second pass, we add sibling loops which become new top-level loops.
1133   EXPECT_CALL(MLPHandle, run(HasName("loop.0"), _, _, _))
1134       .WillOnce(Invoke([&](Loop &L, LoopAnalysisManager &AM,
1135                            LoopStandardAnalysisResults &AR,
1136                            LPMUpdater &Updater) {
1137         auto *NewLoop = new Loop();
1138         AR.LI.addTopLevelLoop(NewLoop);
1139         auto *NewLoop1BB = BasicBlock::Create(Context, "loop.1", &F, &Loop2BB);
1140         BranchInst::Create(&Loop2BB, NewLoop1BB, Undefi1, NewLoop1BB);
1141         Loop0BB.getTerminator()->replaceUsesOfWith(&Loop2BB, NewLoop1BB);
1142         auto *NewDTNode = AR.DT.addNewBlock(NewLoop1BB, &Loop0BB);
1143         AR.DT.changeImmediateDominator(AR.DT[&Loop2BB], NewDTNode);
1144         NewLoop->addBasicBlockToLoop(NewLoop1BB, AR.LI);
1145         Updater.addSiblingLoops({NewLoop});
1146         return PreservedAnalyses::all();
1147       }));
1148   EXPECT_CALL(MLPHandle, run(HasName("loop.0"), _, _, _))
1149       .WillOnce(Invoke(getLoopAnalysisResult));
1150 
1151   EXPECT_CALL(MLPHandle, run(HasName("loop.1"), _, _, _))
1152       .WillOnce(Invoke(getLoopAnalysisResult));
1153   EXPECT_CALL(MLAHandle, run(HasName("loop.1"), _, _));
1154   EXPECT_CALL(MLPHandle, run(HasName("loop.1"), _, _, _))
1155       .Times(2)
1156       .WillRepeatedly(Invoke(getLoopAnalysisResult));
1157 
1158   EXPECT_CALL(MLPHandle, run(HasName("loop.2"), _, _, _))
1159       .WillOnce(Invoke(getLoopAnalysisResult));
1160   EXPECT_CALL(MLAHandle, run(HasName("loop.2"), _, _));
1161   EXPECT_CALL(MLPHandle, run(HasName("loop.2"), _, _, _))
1162       .Times(2)
1163       .WillRepeatedly(Invoke(getLoopAnalysisResult));
1164 
1165   // Now that all the expected actions are registered, run the pipeline over
1166   // our module. All of our expectations are verified when the test finishes.
1167   MPM.run(*M, MAM);
1168 }
1169 
1170 TEST_F(LoopPassManagerTest, LoopDeletion) {
1171   // Build a module with a single loop nest that contains one outer loop with
1172   // three subloops, and one of those with its own subloop. We will
1173   // incrementally delete all of these to test different deletion scenarios.
1174   M = parseIR(Context, "define void @f() {\n"
1175                        "entry:\n"
1176                        "  br label %loop.0\n"
1177                        "loop.0:\n"
1178                        "  br i1 undef, label %loop.0.0, label %end\n"
1179                        "loop.0.0:\n"
1180                        "  br i1 undef, label %loop.0.0, label %loop.0.1\n"
1181                        "loop.0.1:\n"
1182                        "  br i1 undef, label %loop.0.1, label %loop.0.2\n"
1183                        "loop.0.2:\n"
1184                        "  br i1 undef, label %loop.0.2.0, label %loop.0\n"
1185                        "loop.0.2.0:\n"
1186                        "  br i1 undef, label %loop.0.2.0, label %loop.0.2\n"
1187                        "end:\n"
1188                        "  ret void\n"
1189                        "}\n");
1190 
1191   // Build up variables referring into the IR so we can rewrite it below
1192   // easily.
1193   Function &F = *M->begin();
1194   ASSERT_THAT(F, HasName("f"));
1195   auto BBI = F.begin();
1196   BasicBlock &EntryBB = *BBI++;
1197   ASSERT_THAT(EntryBB, HasName("entry"));
1198   BasicBlock &Loop0BB = *BBI++;
1199   ASSERT_THAT(Loop0BB, HasName("loop.0"));
1200   BasicBlock &Loop00BB = *BBI++;
1201   ASSERT_THAT(Loop00BB, HasName("loop.0.0"));
1202   BasicBlock &Loop01BB = *BBI++;
1203   ASSERT_THAT(Loop01BB, HasName("loop.0.1"));
1204   BasicBlock &Loop02BB = *BBI++;
1205   ASSERT_THAT(Loop02BB, HasName("loop.0.2"));
1206   BasicBlock &Loop020BB = *BBI++;
1207   ASSERT_THAT(Loop020BB, HasName("loop.0.2.0"));
1208   BasicBlock &EndBB = *BBI++;
1209   ASSERT_THAT(EndBB, HasName("end"));
1210   ASSERT_THAT(BBI, F.end());
1211   Constant *Undefi1 = UndefValue::get(Type::getInt1Ty(Context));
1212 
1213   // Helper to do the actual deletion of a loop. We directly encode this here
1214   // to isolate ourselves from the rest of LLVM and for simplicity. Here we can
1215   // egregiously cheat based on knowledge of the test case. For example, we
1216   // have no PHI nodes and there is always a single i-dom.
1217   auto DeleteLoopBlocks = [](Loop &L, BasicBlock &IDomBB,
1218                              LoopStandardAnalysisResults &AR,
1219                              LPMUpdater &Updater) {
1220     for (BasicBlock *LoopBB : L.blocks()) {
1221       SmallVector<DomTreeNode *, 4> ChildNodes(AR.DT[LoopBB]->begin(),
1222                                                AR.DT[LoopBB]->end());
1223       for (DomTreeNode *ChildNode : ChildNodes)
1224         AR.DT.changeImmediateDominator(ChildNode, AR.DT[&IDomBB]);
1225       AR.DT.eraseNode(LoopBB);
1226       LoopBB->dropAllReferences();
1227     }
1228     SmallVector<BasicBlock *, 4> LoopBBs(L.block_begin(), L.block_end());
1229     Updater.markLoopAsDeleted(L);
1230     AR.LI.markAsRemoved(&L);
1231     for (BasicBlock *LoopBB : LoopBBs)
1232       LoopBB->eraseFromParent();
1233   };
1234 
1235   // Build up the pass managers.
1236   ModulePassManager MPM(true);
1237   FunctionPassManager FPM(true);
1238   // We run several loop pass pipelines across the loop nest, but they all take
1239   // the same form of three mock pass runs in a loop pipeline followed by
1240   // domtree and loop verification. We use a lambda to stamp this out each
1241   // time.
1242   auto AddLoopPipelineAndVerificationPasses = [&] {
1243     LoopPassManager LPM(true);
1244     LPM.addPass(MLPHandle.getPass());
1245     LPM.addPass(MLPHandle.getPass());
1246     LPM.addPass(MLPHandle.getPass());
1247     FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM)));
1248     FPM.addPass(DominatorTreeVerifierPass());
1249     FPM.addPass(LoopVerifierPass());
1250   };
1251 
1252   // All the visit orders are deterministic so we use simple fully order
1253   // expectations.
1254   ::testing::InSequence MakeExpectationsSequenced;
1255 
1256   // We run the loop pipeline with three passes over each of the loops. When
1257   // running over the middle loop, the second pass in the pipeline deletes it.
1258   // This should prevent the third pass from visiting it but otherwise leave
1259   // the process unimpacted.
1260   AddLoopPipelineAndVerificationPasses();
1261   EXPECT_CALL(MLPHandle, run(HasName("loop.0.0"), _, _, _))
1262       .WillOnce(Invoke(getLoopAnalysisResult));
1263   EXPECT_CALL(MLAHandle, run(HasName("loop.0.0"), _, _));
1264   EXPECT_CALL(MLPHandle, run(HasName("loop.0.0"), _, _, _))
1265       .Times(2)
1266       .WillRepeatedly(Invoke(getLoopAnalysisResult));
1267 
1268   EXPECT_CALL(MLPHandle, run(HasName("loop.0.1"), _, _, _))
1269       .WillOnce(Invoke(getLoopAnalysisResult));
1270   EXPECT_CALL(MLAHandle, run(HasName("loop.0.1"), _, _));
1271   EXPECT_CALL(MLPHandle, run(HasName("loop.0.1"), _, _, _))
1272       .WillOnce(
1273           Invoke([&](Loop &L, LoopAnalysisManager &AM,
1274                      LoopStandardAnalysisResults &AR, LPMUpdater &Updater) {
1275             AR.SE.forgetLoop(&L);
1276             Loop00BB.getTerminator()->replaceUsesOfWith(&Loop01BB, &Loop02BB);
1277             DeleteLoopBlocks(L, Loop00BB, AR, Updater);
1278             return PreservedAnalyses::all();
1279           }));
1280 
1281   EXPECT_CALL(MLPHandle, run(HasName("loop.0.2.0"), _, _, _))
1282       .WillOnce(Invoke(getLoopAnalysisResult));
1283   EXPECT_CALL(MLAHandle, run(HasName("loop.0.2.0"), _, _));
1284   EXPECT_CALL(MLPHandle, run(HasName("loop.0.2.0"), _, _, _))
1285       .Times(2)
1286       .WillRepeatedly(Invoke(getLoopAnalysisResult));
1287 
1288   EXPECT_CALL(MLPHandle, run(HasName("loop.0.2"), _, _, _))
1289       .WillOnce(Invoke(getLoopAnalysisResult));
1290   EXPECT_CALL(MLAHandle, run(HasName("loop.0.2"), _, _));
1291   EXPECT_CALL(MLPHandle, run(HasName("loop.0.2"), _, _, _))
1292       .Times(2)
1293       .WillRepeatedly(Invoke(getLoopAnalysisResult));
1294 
1295   EXPECT_CALL(MLPHandle, run(HasName("loop.0"), _, _, _))
1296       .WillOnce(Invoke(getLoopAnalysisResult));
1297   EXPECT_CALL(MLAHandle, run(HasName("loop.0"), _, _));
1298   EXPECT_CALL(MLPHandle, run(HasName("loop.0"), _, _, _))
1299       .Times(2)
1300       .WillRepeatedly(Invoke(getLoopAnalysisResult));
1301 
1302   // Run the loop pipeline again. This time we delete the last loop, which
1303   // contains a nested loop within it, and we reuse its inner loop object to
1304   // insert a new loop into the nest. This makes sure that we don't reuse
1305   // cached analysis results for loop objects when removed just because their
1306   // pointers match, and that we can handle nested loop deletion.
1307   AddLoopPipelineAndVerificationPasses();
1308   EXPECT_CALL(MLPHandle, run(HasName("loop.0.0"), _, _, _))
1309       .Times(3)
1310       .WillRepeatedly(Invoke(getLoopAnalysisResult));
1311 
1312   EXPECT_CALL(MLPHandle, run(HasName("loop.0.2.0"), _, _, _))
1313       .Times(3)
1314       .WillRepeatedly(Invoke(getLoopAnalysisResult));
1315 
1316   EXPECT_CALL(MLPHandle, run(HasName("loop.0.2"), _, _, _))
1317       .WillOnce(Invoke(getLoopAnalysisResult));
1318   BasicBlock *NewLoop03BB;
1319   EXPECT_CALL(MLPHandle, run(HasName("loop.0.2"), _, _, _))
1320       .WillOnce(
1321           Invoke([&](Loop &L, LoopAnalysisManager &AM,
1322                      LoopStandardAnalysisResults &AR, LPMUpdater &Updater) {
1323             // Delete the inner loop first. we also do this manually because we
1324             // want to preserve the loop object and reuse it.
1325             AR.SE.forgetLoop(*L.begin());
1326             Loop02BB.getTerminator()->replaceUsesOfWith(&Loop020BB, &Loop02BB);
1327             assert(std::next((*L.begin())->block_begin()) ==
1328                        (*L.begin())->block_end() &&
1329                    "There should only be one block.");
1330             assert(AR.DT[&Loop020BB]->getNumChildren() == 0 &&
1331                    "Cannot have children in the domtree!");
1332             AR.DT.eraseNode(&Loop020BB);
1333             Updater.markLoopAsDeleted(**L.begin());
1334             AR.LI.removeBlock(&Loop020BB);
1335             auto *OldL = L.removeChildLoop(L.begin());
1336             Loop020BB.eraseFromParent();
1337 
1338             auto *ParentL = L.getParentLoop();
1339             AR.SE.forgetLoop(&L);
1340             Loop00BB.getTerminator()->replaceUsesOfWith(&Loop02BB, &Loop0BB);
1341             DeleteLoopBlocks(L, Loop00BB, AR, Updater);
1342 
1343             // Now insert a new sibling loop, reusing a loop pointer.
1344             ParentL->addChildLoop(OldL);
1345             NewLoop03BB = BasicBlock::Create(Context, "loop.0.3", &F, &EndBB);
1346             BranchInst::Create(&Loop0BB, NewLoop03BB, Undefi1, NewLoop03BB);
1347             Loop00BB.getTerminator()->replaceUsesOfWith(&Loop0BB, NewLoop03BB);
1348             AR.DT.addNewBlock(NewLoop03BB, &Loop00BB);
1349             OldL->addBasicBlockToLoop(NewLoop03BB, AR.LI);
1350             Updater.addSiblingLoops({OldL});
1351             return PreservedAnalyses::all();
1352           }));
1353 
1354   // To respect our inner-to-outer traversal order, we must visit the
1355   // newly-inserted sibling of the loop we just deleted before we visit the
1356   // outer loop. When we do so, this must compute a fresh analysis result, even
1357   // though our new loop has the same pointer value as the loop we deleted.
1358   EXPECT_CALL(MLPHandle, run(HasName("loop.0.3"), _, _, _))
1359       .WillOnce(Invoke(getLoopAnalysisResult));
1360   EXPECT_CALL(MLAHandle, run(HasName("loop.0.3"), _, _));
1361   EXPECT_CALL(MLPHandle, run(HasName("loop.0.3"), _, _, _))
1362       .Times(2)
1363       .WillRepeatedly(Invoke(getLoopAnalysisResult));
1364 
1365   EXPECT_CALL(MLPHandle, run(HasName("loop.0"), _, _, _))
1366       .Times(3)
1367       .WillRepeatedly(Invoke(getLoopAnalysisResult));
1368 
1369   // In the final loop pipeline run we delete every loop, including the last
1370   // loop of the nest. We do this again in the second pass in the pipeline, and
1371   // as a consequence we never make it to three runs on any loop. We also cover
1372   // deleting multiple loops in a single pipeline, deleting the first loop and
1373   // deleting the (last) top level loop.
1374   AddLoopPipelineAndVerificationPasses();
1375   EXPECT_CALL(MLPHandle, run(HasName("loop.0.0"), _, _, _))
1376       .WillOnce(Invoke(getLoopAnalysisResult));
1377   EXPECT_CALL(MLPHandle, run(HasName("loop.0.0"), _, _, _))
1378       .WillOnce(
1379           Invoke([&](Loop &L, LoopAnalysisManager &AM,
1380                      LoopStandardAnalysisResults &AR, LPMUpdater &Updater) {
1381             AR.SE.forgetLoop(&L);
1382             Loop0BB.getTerminator()->replaceUsesOfWith(&Loop00BB, NewLoop03BB);
1383             DeleteLoopBlocks(L, Loop0BB, AR, Updater);
1384             return PreservedAnalyses::all();
1385           }));
1386 
1387   EXPECT_CALL(MLPHandle, run(HasName("loop.0.3"), _, _, _))
1388       .WillOnce(Invoke(getLoopAnalysisResult));
1389   EXPECT_CALL(MLPHandle, run(HasName("loop.0.3"), _, _, _))
1390       .WillOnce(
1391           Invoke([&](Loop &L, LoopAnalysisManager &AM,
1392                      LoopStandardAnalysisResults &AR, LPMUpdater &Updater) {
1393             AR.SE.forgetLoop(&L);
1394             Loop0BB.getTerminator()->replaceUsesOfWith(NewLoop03BB, &Loop0BB);
1395             DeleteLoopBlocks(L, Loop0BB, AR, Updater);
1396             return PreservedAnalyses::all();
1397           }));
1398 
1399   EXPECT_CALL(MLPHandle, run(HasName("loop.0"), _, _, _))
1400       .WillOnce(Invoke(getLoopAnalysisResult));
1401   EXPECT_CALL(MLPHandle, run(HasName("loop.0"), _, _, _))
1402       .WillOnce(
1403           Invoke([&](Loop &L, LoopAnalysisManager &AM,
1404                      LoopStandardAnalysisResults &AR, LPMUpdater &Updater) {
1405             AR.SE.forgetLoop(&L);
1406             EntryBB.getTerminator()->replaceUsesOfWith(&Loop0BB, &EndBB);
1407             DeleteLoopBlocks(L, EntryBB, AR, Updater);
1408             return PreservedAnalyses::all();
1409           }));
1410 
1411   // Add the function pass pipeline now that it is fully built up and run it
1412   // over the module's one function.
1413   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1414   MPM.run(*M, MAM);
1415 }
1416 }
1417