LoopPassManagerTest.cpp 68 KB

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