[Polly] Invalidate passes after Scop processing in NewPM.

ScopDetection's DetectionContext holds AssertionVH for
RequiredInvariantLoads. An assertion is thrown if the handle's value is
erased and the ScopDetection is not yet invalidated. The ScopDetection
must remain valid durting the ScopPassManager. Enusure that all Scop
analyses are free'd when the ScopPass manager is done.

If IR generation has happened, also invalidate all other passes to avoid
possible issues because, like for the legacy pass manager, Polly does not
yet perfectly preserve them.

GitOrigin-RevId: d09491895f8cd9fdc8ca4cdf45f30d4c2e3066a6
diff --git a/include/polly/ScopPass.h b/include/polly/ScopPass.h
index f3c3020..fdcd2a4 100644
--- a/include/polly/ScopPass.h
+++ b/include/polly/ScopPass.h
@@ -222,11 +222,17 @@
   explicit FunctionToScopPassAdaptor(ScopPassT Pass) : Pass(std::move(Pass)) {}
 
   PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM) {
-    PreservedAnalyses PA = PreservedAnalyses::all();
-    auto &SD = AM.getResult<ScopAnalysis>(F);
-    auto &SI = AM.getResult<ScopInfoAnalysis>(F);
-    if (SI.empty())
-      return PA;
+    ScopDetection &SD = AM.getResult<ScopAnalysis>(F);
+    ScopInfo &SI = AM.getResult<ScopInfoAnalysis>(F);
+    if (SI.empty()) {
+      // With no scops having been detected, no IR changes have been made and
+      // therefore all analyses are preserved. However, we must still free the
+      // Scop analysis results which may hold AssertingVH that cause an error
+      // if its value is destroyed.
+      AM.invalidate<ScopInfoAnalysis>(F);
+      AM.invalidate<ScopAnalysis>(F);
+      return PreservedAnalyses::all();
+    }
 
     SmallPriorityWorklist<Region *, 4> Worklist;
     for (auto &S : SI)
@@ -257,20 +263,18 @@
       PreservedAnalyses PassPA = Pass.run(*scop, SAM, AR, Updater);
 
       SAM.invalidate(*scop, PassPA);
-      PA.intersect(std::move(PassPA));
       if (Updater.invalidateCurrentScop())
         SI.recompute();
     };
 
-    PA.preserveSet<AllAnalysesOn<Scop>>();
-    PA.preserve<ScopAnalysisManagerFunctionProxy>();
-    PA.preserve<DominatorTreeAnalysis>();
-    PA.preserve<ScopAnalysis>();
-    PA.preserve<ScopInfoAnalysis>();
-    PA.preserve<ScalarEvolutionAnalysis>();
-    PA.preserve<LoopAnalysis>();
-    PA.preserve<RegionInfoAnalysis>();
-    return PA;
+    // FIXME: For the same reason as we add a BarrierNoopPass in the legacy pass
+    // manager, do not preserve any analyses. While CodeGeneration may preserve
+    // IR analyses sufficiently to process another Scop in the same function (it
+    // has to, otherwise the ScopDetection result itself would need to be
+    // invalidated), it is not sufficient for other purposes. For instance,
+    // CodeGeneration does not inform LoopInfo about new loops in the
+    // Polly-generated IR.
+    return PreservedAnalyses::none();
   }
 
 private: