vitalybuka created this revision.
vitalybuka added reviewers: eugenis, pcc.
Herald added subscribers: llvm-commits, cfe-commits, dexonsmith, steven_wu, 
hiraditya.
Herald added projects: clang, LLVM.

MAYBE? let me know if you think we need it. I'll improve the patch.

This way we don't need to rely on MTE attributes and let
clang to controll when to include this info into summary.

Depends on D81242 <https://reviews.llvm.org/D81242>.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D81244

Files:
  clang/lib/CodeGen/BackendUtil.cpp
  llvm/include/llvm/Analysis/ModuleSummaryAnalysis.h
  llvm/include/llvm/Analysis/StackSafetyAnalysis.h
  llvm/include/llvm/Bitcode/BitcodeWriterPass.h
  llvm/include/llvm/Transforms/IPO.h
  llvm/include/llvm/Transforms/IPO/ThinLTOBitcodeWriter.h
  llvm/lib/Analysis/ModuleSummaryAnalysis.cpp
  llvm/lib/Analysis/StackSafetyAnalysis.cpp
  llvm/lib/Bitcode/Writer/BitcodeWriterPass.cpp
  llvm/lib/LTO/ThinLTOCodeGenerator.cpp
  llvm/lib/Transforms/IPO/PassManagerBuilder.cpp
  llvm/lib/Transforms/IPO/ThinLTOBitcodeWriter.cpp
  llvm/test/Analysis/StackSafetyAnalysis/ipa-alias.ll
  llvm/test/Analysis/StackSafetyAnalysis/ipa.ll
  llvm/test/Bitcode/thinlto-function-summary-paramaccess.ll
  llvm/tools/llvm-extract/llvm-extract.cpp
  llvm/tools/opt/NewPMDriver.cpp
  llvm/tools/opt/NewPMDriver.h
  llvm/tools/opt/opt.cpp

Index: llvm/tools/opt/opt.cpp
===================================================================
--- llvm/tools/opt/opt.cpp
+++ llvm/tools/opt/opt.cpp
@@ -192,6 +192,10 @@
 static cl::opt<bool> EmitModuleHash("module-hash", cl::desc("Emit module hash"),
                                     cl::init(false));
 
+cl::opt<bool> ModuleSummaryStackSafety("module-summary-stack-safety",
+                                       cl::init(false), cl::Hidden,
+                                       cl::desc("Emit Stack Safety summary."));
+
 static cl::opt<bool>
 DisableSimplifyLibCalls("disable-simplify-libcalls",
                         cl::desc("Disable simplify-libcalls"));
@@ -754,7 +758,8 @@
                            RemarksFile.get(), PassPipeline, OK, VK,
                            PreserveAssemblyUseListOrder,
                            PreserveBitcodeUseListOrder, EmitSummaryIndex,
-                           EmitModuleHash, EnableDebugify, Coroutines)
+                           EmitModuleHash, EnableDebugify, Coroutines,
+                           ModuleSummaryStackSafety)
                ? 0
                : 1;
   }
@@ -964,10 +969,12 @@
       Passes.add(createPrintModulePass(*OS, "", PreserveAssemblyUseListOrder));
     } else if (OutputThinLTOBC)
       Passes.add(createWriteThinLTOBitcodePass(
-          *OS, ThinLinkOut ? &ThinLinkOut->os() : nullptr));
+          *OS, ThinLinkOut ? &ThinLinkOut->os() : nullptr,
+          ModuleSummaryStackSafety));
     else
       Passes.add(createBitcodeWriterPass(*OS, PreserveBitcodeUseListOrder,
-                                         EmitSummaryIndex, EmitModuleHash));
+                                         EmitSummaryIndex, EmitModuleHash,
+                                         ModuleSummaryStackSafety));
   }
 
   // Before executing passes, print the final values of the LLVM options.
Index: llvm/tools/opt/NewPMDriver.h
===================================================================
--- llvm/tools/opt/NewPMDriver.h
+++ llvm/tools/opt/NewPMDriver.h
@@ -63,7 +63,8 @@
                      bool ShouldPreserveAssemblyUseListOrder,
                      bool ShouldPreserveBitcodeUseListOrder,
                      bool EmitSummaryIndex, bool EmitModuleHash,
-                     bool EnableDebugify, bool Coroutines);
+                     bool EnableDebugify, bool Coroutines,
+                     bool ModuleSummaryStackSafety);
 } // namespace llvm
 
 #endif
Index: llvm/tools/opt/NewPMDriver.cpp
===================================================================
--- llvm/tools/opt/NewPMDriver.cpp
+++ llvm/tools/opt/NewPMDriver.cpp
@@ -219,7 +219,8 @@
                            bool ShouldPreserveAssemblyUseListOrder,
                            bool ShouldPreserveBitcodeUseListOrder,
                            bool EmitSummaryIndex, bool EmitModuleHash,
-                           bool EnableDebugify, bool Coroutines) {
+                           bool EnableDebugify, bool Coroutines,
+                           bool ModuleSummaryStackSafety) {
   bool VerifyEachPass = VK == VK_VerifyEachPass;
 
   Optional<PGOOptions> P;
@@ -357,7 +358,8 @@
     break;
   case OK_OutputThinLTOBitcode:
     MPM.addPass(ThinLTOBitcodeWriterPass(
-        Out->os(), ThinLTOLinkOut ? &ThinLTOLinkOut->os() : nullptr));
+        Out->os(), ThinLTOLinkOut ? &ThinLTOLinkOut->os() : nullptr,
+        ModuleSummaryStackSafety));
     break;
   }
 
Index: llvm/tools/llvm-extract/llvm-extract.cpp
===================================================================
--- llvm/tools/llvm-extract/llvm-extract.cpp
+++ llvm/tools/llvm-extract/llvm-extract.cpp
@@ -382,7 +382,8 @@
     Passes.add(
         createPrintModulePass(Out.os(), "", PreserveAssemblyUseListOrder));
   else if (Force || !CheckBitcodeOutputToConsole(Out.os(), true))
-    Passes.add(createBitcodeWriterPass(Out.os(), PreserveBitcodeUseListOrder));
+    Passes.add(createBitcodeWriterPass(Out.os(), PreserveBitcodeUseListOrder,
+                                       false, false, false));
 
   Passes.run(*M.get());
 
Index: llvm/test/Bitcode/thinlto-function-summary-paramaccess.ll
===================================================================
--- llvm/test/Bitcode/thinlto-function-summary-paramaccess.ll
+++ llvm/test/Bitcode/thinlto-function-summary-paramaccess.ll
@@ -3,14 +3,14 @@
 ; For convenience, to show what is being serialized.
 ; RUN: opt -S -passes="print<stack-safety-local>" -disable-output < %s 2>&1 | FileCheck %s --check-prefixes=SSI
 
-; RUN: opt -module-summary %s -o %t.bc
+; RUN: opt -module-summary -module-summary-stack-safety %s -o %t.bc
 ; RUN: llvm-bcanalyzer -dump %t.bc | FileCheck %s -check-prefixes=BC
 
 ; RUN: llvm-dis -o - %t.bc | FileCheck %s --check-prefix=DIS
 ; Round trip it through llvm-as
 ; RUN: llvm-dis -o - %t.bc | llvm-as -o - | llvm-dis -o - | FileCheck %s --check-prefix=DIS
 
-; RUN: opt -thinlto-bc %s -o %t.bc
+; RUN: opt -thinlto-bc -module-summary-stack-safety %s -o %t.bc
 ; RUN: llvm-bcanalyzer -dump %t.bc | FileCheck %s -check-prefixes=BC
 
 ; RUN: llvm-dis -o - %t.bc | FileCheck %s --check-prefix=DIS
@@ -250,6 +250,6 @@
 }
 
 ; BC-NOT: <PERMODULE
-; BC-NOT: <PARAM_ACCESS1
+; BC-NOT: <PARAM_ACCESS
 
 
Index: llvm/test/Analysis/StackSafetyAnalysis/ipa.ll
===================================================================
--- llvm/test/Analysis/StackSafetyAnalysis/ipa.ll
+++ llvm/test/Analysis/StackSafetyAnalysis/ipa.ll
@@ -12,8 +12,8 @@
 
 ; Do an end-to-test using the new LTO API
 ; TODO: Hideous llvm-lto2 invocation, add a --default-symbol-resolution to llvm-lto2?
-; RUN: opt -module-summary %s -o %t.summ0.bc
-; RUN: opt -module-summary %S/Inputs/ipa.ll -o %t.summ1.bc
+; RUN: opt -module-summary -module-summary-stack-safety %s -o %t.summ0.bc
+; RUN: opt -module-summary -module-summary-stack-safety %S/Inputs/ipa.ll -o %t.summ1.bc
 
 ; RUN: llvm-lto2 run %t.summ0.bc %t.summ1.bc -o %t.lto -stack-safety-print -stack-safety-run -save-temps -thinlto-threads 1 -O0 \
 ; RUN:  -r %t.summ0.bc,Write1, \
Index: llvm/test/Analysis/StackSafetyAnalysis/ipa-alias.ll
===================================================================
--- llvm/test/Analysis/StackSafetyAnalysis/ipa-alias.ll
+++ llvm/test/Analysis/StackSafetyAnalysis/ipa-alias.ll
@@ -12,8 +12,8 @@
 ; RUN: opt -S -passes="print-stack-safety" -disable-output %t.combined.bc 2>&1 | FileCheck %s --check-prefixes=CHECK,GLOBAL,NOLTO
 
 ; Do an end-to-test using the new LTO API
-; RUN: opt -module-summary %s -o %t.summ0.bc
-; RUN: opt -module-summary %S/Inputs/ipa-alias.ll -o %t.summ1.bc
+; RUN: opt -module-summary -module-summary-stack-safety %s -o %t.summ0.bc
+; RUN: opt -module-summary -module-summary-stack-safety %S/Inputs/ipa-alias.ll -o %t.summ1.bc
 
 ; RUN: llvm-lto2 run %t.summ0.bc %t.summ1.bc -o %t.lto -stack-safety-print -stack-safety-run -save-temps -thinlto-threads 1 -O0 \
 ; RUN:  -r %t.summ0.bc,PreemptableAliasWrite1, \
Index: llvm/lib/Transforms/IPO/ThinLTOBitcodeWriter.cpp
===================================================================
--- llvm/lib/Transforms/IPO/ThinLTOBitcodeWriter.cpp
+++ llvm/lib/Transforms/IPO/ThinLTOBitcodeWriter.cpp
@@ -10,6 +10,7 @@
 #include "llvm/Analysis/BasicAliasAnalysis.h"
 #include "llvm/Analysis/ModuleSummaryAnalysis.h"
 #include "llvm/Analysis/ProfileSummaryInfo.h"
+#include "llvm/Analysis/StackSafetyAnalysis.h"
 #include "llvm/Analysis/TypeMetadataUtils.h"
 #include "llvm/Bitcode/BitcodeWriter.h"
 #include "llvm/IR/Constants.h"
@@ -28,6 +29,7 @@
 #include "llvm/Transforms/IPO/LowerTypeTests.h"
 #include "llvm/Transforms/Utils/Cloning.h"
 #include "llvm/Transforms/Utils/ModuleUtils.h"
+#include <memory>
 using namespace llvm;
 
 namespace {
@@ -199,14 +201,16 @@
 // regular LTO bitcode file to OS.
 void splitAndWriteThinLTOBitcode(
     raw_ostream &OS, raw_ostream *ThinLinkOS,
-    function_ref<AAResults &(Function &)> AARGetter, Module &M) {
+    function_ref<AAResults &(Function &)> AARGetter, Module &M,
+    function_ref<const StackSafetyInfo *(const Function &)> SSIGetter) {
   std::string ModuleId = getUniqueModuleId(&M);
   if (ModuleId.empty()) {
     // We couldn't generate a module ID for this module, write it out as a
     // regular LTO module with an index for summary-based dead stripping.
     ProfileSummaryInfo PSI(M);
     M.addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
-    ModuleSummaryIndex Index = buildModuleSummaryIndex(M, nullptr, &PSI);
+    ModuleSummaryIndex Index =
+        buildModuleSummaryIndex(M, nullptr, &PSI, SSIGetter);
     WriteBitcodeToFile(M, OS, /*ShouldPreserveUseListOrder=*/false, &Index);
 
     if (ThinLinkOS)
@@ -389,13 +393,14 @@
 
   // FIXME: Try to re-use BSI and PFI from the original module here.
   ProfileSummaryInfo PSI(M);
-  ModuleSummaryIndex Index = buildModuleSummaryIndex(M, nullptr, &PSI);
+  ModuleSummaryIndex Index =
+      buildModuleSummaryIndex(M, nullptr, &PSI, SSIGetter);
 
   // Mark the merged module as requiring full LTO. We still want an index for
   // it though, so that it can participate in summary-based dead stripping.
   MergedM->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
   ModuleSummaryIndex MergedMIndex =
-      buildModuleSummaryIndex(*MergedM, nullptr, &PSI);
+      buildModuleSummaryIndex(*MergedM, nullptr, &PSI, SSIGetter);
 
   SmallVector<char, 0> Buffer;
 
@@ -445,15 +450,18 @@
   return false;
 }
 
-void writeThinLTOBitcode(raw_ostream &OS, raw_ostream *ThinLinkOS,
-                         function_ref<AAResults &(Function &)> AARGetter,
-                         Module &M, const ModuleSummaryIndex *Index) {
-  std::unique_ptr<ModuleSummaryIndex> NewIndex = nullptr;
+void writeThinLTOBitcode(
+    raw_ostream &OS, raw_ostream *ThinLinkOS,
+    function_ref<AAResults &(Function &)> AARGetter, Module &M,
+    function_ref<ModuleSummaryIndex()> IndexGetter,
+    function_ref<const StackSafetyInfo *(const Function &)> SSIGetter) {
+  std::unique_ptr<ModuleSummaryIndex> Index;
   // See if this module has any type metadata. If so, we try to split it
   // or at least promote type ids to enable WPD.
   if (hasTypeMetadata(M)) {
     if (enableSplitLTOUnit(M))
-      return splitAndWriteThinLTOBitcode(OS, ThinLinkOS, AARGetter, M);
+      return splitAndWriteThinLTOBitcode(OS, ThinLinkOS, AARGetter, M,
+                                         SSIGetter);
     // Promote type ids as needed for index-based WPD.
     std::string ModuleId = getUniqueModuleId(&M);
     if (!ModuleId.empty()) {
@@ -467,11 +475,12 @@
       // splitAndWriteThinLTOBitcode). Just always build it once via the
       // buildModuleSummaryIndex when Module(s) are ready.
       ProfileSummaryInfo PSI(M);
-      NewIndex = std::make_unique<ModuleSummaryIndex>(
-          buildModuleSummaryIndex(M, nullptr, &PSI));
-      Index = NewIndex.get();
+      Index = std::make_unique<ModuleSummaryIndex>(
+          buildModuleSummaryIndex(M, nullptr, &PSI, SSIGetter));
     }
   }
+  if (!Index)
+    Index = std::make_unique<ModuleSummaryIndex>(IndexGetter());
 
   // Write it out as an unsplit ThinLTO module.
 
@@ -479,7 +488,7 @@
   // be used in the backends, and use that in the minimized bitcode
   // produced for the full link.
   ModuleHash ModHash = {{0}};
-  WriteBitcodeToFile(M, OS, /*ShouldPreserveUseListOrder=*/false, Index,
+  WriteBitcodeToFile(M, OS, /*ShouldPreserveUseListOrder=*/false, Index.get(),
                      /*GenerateHash=*/true, &ModHash);
   // If a minimized bitcode module was requested for the thin link, only
   // the information that is needed by thin link will be written in the
@@ -493,6 +502,7 @@
   // The output stream on which to emit a minimized module for use
   // just in the thin link, if requested.
   raw_ostream *ThinLinkOS;
+  bool StackSafety;
 
 public:
   static char ID; // Pass identification, replacement for typeid
@@ -500,23 +510,35 @@
     initializeWriteThinLTOBitcodePass(*PassRegistry::getPassRegistry());
   }
 
-  explicit WriteThinLTOBitcode(raw_ostream &o, raw_ostream *ThinLinkOS)
-      : ModulePass(ID), OS(o), ThinLinkOS(ThinLinkOS) {
+  explicit WriteThinLTOBitcode(raw_ostream &o, raw_ostream *ThinLinkOS,
+                               bool StackSafety)
+      : ModulePass(ID), OS(o), ThinLinkOS(ThinLinkOS),
+        StackSafety(StackSafety) {
     initializeWriteThinLTOBitcodePass(*PassRegistry::getPassRegistry());
   }
 
   StringRef getPassName() const override { return "ThinLTO Bitcode Writer"; }
 
   bool runOnModule(Module &M) override {
-    const ModuleSummaryIndex *Index =
-        &(getAnalysis<ModuleSummaryIndexWrapperPass>().getIndex());
-    writeThinLTOBitcode(OS, ThinLinkOS, LegacyAARGetter(*this), M, Index);
+    writeThinLTOBitcode(
+        OS, ThinLinkOS, LegacyAARGetter(*this), M,
+        [&]() {
+          return getAnalysis<ModuleSummaryIndexWrapperPass>().getIndex(
+              StackSafety);
+        },
+        [&](const Function &F) -> const StackSafetyInfo * {
+          return StackSafety ? &getAnalysis<StackSafetyInfoWrapperPass>(
+                                    const_cast<Function &>(F))
+                                    .getResult()
+                             : nullptr;
+        });
     return true;
   }
   void getAnalysisUsage(AnalysisUsage &AU) const override {
     AU.setPreservesAll();
     AU.addRequired<AssumptionCacheTracker>();
     AU.addRequired<ModuleSummaryIndexWrapperPass>();
+    AU.addRequired<StackSafetyInfoWrapperPass>();
     AU.addRequired<TargetLibraryInfoWrapperPass>();
   }
 };
@@ -527,23 +549,34 @@
                       "Write ThinLTO Bitcode", false, true)
 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
 INITIALIZE_PASS_DEPENDENCY(ModuleSummaryIndexWrapperPass)
+INITIALIZE_PASS_DEPENDENCY(StackSafetyInfoWrapperPass)
 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
 INITIALIZE_PASS_END(WriteThinLTOBitcode, "write-thinlto-bitcode",
                     "Write ThinLTO Bitcode", false, true)
 
 ModulePass *llvm::createWriteThinLTOBitcodePass(raw_ostream &Str,
-                                                raw_ostream *ThinLinkOS) {
-  return new WriteThinLTOBitcode(Str, ThinLinkOS);
+                                                raw_ostream *ThinLinkOS,
+                                                bool StackSafety) {
+  return new WriteThinLTOBitcode(Str, ThinLinkOS, StackSafety);
 }
 
 PreservedAnalyses
 llvm::ThinLTOBitcodeWriterPass::run(Module &M, ModuleAnalysisManager &AM) {
   FunctionAnalysisManager &FAM =
       AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
-  writeThinLTOBitcode(OS, ThinLinkOS,
-                      [&FAM](Function &F) -> AAResults & {
-                        return FAM.getResult<AAManager>(F);
-                      },
-                      M, &AM.getResult<ModuleSummaryIndexAnalysis>(M));
+  writeThinLTOBitcode(
+      OS, ThinLinkOS,
+      [&FAM](Function &F) -> AAResults & {
+        return FAM.getResult<AAManager>(F);
+      },
+      M,
+      [&]() {
+        return AM.getResult<ModuleSummaryIndexAnalysis>(M)(StackSafety);
+      },
+      [&](const Function &F) -> const StackSafetyInfo * {
+        return StackSafety ? &FAM.getResult<StackSafetyAnalysis>(
+                                 const_cast<Function &>(F))
+                           : nullptr;
+      });
   return PreservedAnalyses::all();
 }
Index: llvm/lib/Transforms/IPO/PassManagerBuilder.cpp
===================================================================
--- llvm/lib/Transforms/IPO/PassManagerBuilder.cpp
+++ llvm/lib/Transforms/IPO/PassManagerBuilder.cpp
@@ -22,6 +22,7 @@
 #include "llvm/Analysis/InlineCost.h"
 #include "llvm/Analysis/Passes.h"
 #include "llvm/Analysis/ScopedNoAliasAA.h"
+#include "llvm/Analysis/StackSafetyAnalysis.h"
 #include "llvm/Analysis/TargetLibraryInfo.h"
 #include "llvm/Analysis/TypeBasedAliasAnalysis.h"
 #include "llvm/IR/DataLayout.h"
Index: llvm/lib/LTO/ThinLTOCodeGenerator.cpp
===================================================================
--- llvm/lib/LTO/ThinLTOCodeGenerator.cpp
+++ llvm/lib/LTO/ThinLTOCodeGenerator.cpp
@@ -18,6 +18,7 @@
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/Analysis/ModuleSummaryAnalysis.h"
 #include "llvm/Analysis/ProfileSummaryInfo.h"
+#include "llvm/Analysis/StackSafetyAnalysis.h"
 #include "llvm/Analysis/TargetLibraryInfo.h"
 #include "llvm/Analysis/TargetTransformInfo.h"
 #include "llvm/Bitcode/BitcodeReader.h"
@@ -456,9 +457,14 @@
     // Configured to stop before CodeGen, serialize the bitcode and return.
     SmallVector<char, 128> OutputBuffer;
     {
+      // TODO: No unit tests reach this
+      // legacy::PassManager PM;
+      // PM.add(createWriteThinLTOBitcodePass(OS, nullptr));
+      // PM.run(TheModule);
+
       raw_svector_ostream OS(OutputBuffer);
       ProfileSummaryInfo PSI(TheModule);
-      auto Index = buildModuleSummaryIndex(TheModule, nullptr, &PSI);
+      auto Index = buildModuleSummaryIndex(TheModule, nullptr, &PSI, nullptr);
       WriteBitcodeToFile(TheModule, OS, true, &Index);
     }
     return std::make_unique<SmallVectorMemoryBuffer>(std::move(OutputBuffer));
Index: llvm/lib/Bitcode/Writer/BitcodeWriterPass.cpp
===================================================================
--- llvm/lib/Bitcode/Writer/BitcodeWriterPass.cpp
+++ llvm/lib/Bitcode/Writer/BitcodeWriterPass.cpp
@@ -20,10 +20,15 @@
 using namespace llvm;
 
 PreservedAnalyses BitcodeWriterPass::run(Module &M, ModuleAnalysisManager &AM) {
-  const ModuleSummaryIndex *Index =
-      EmitSummaryIndex ? &(AM.getResult<ModuleSummaryIndexAnalysis>(M))
-                       : nullptr;
-  WriteBitcodeToFile(M, OS, ShouldPreserveUseListOrder, Index, EmitModuleHash);
+  if (EmitSummaryIndex) {
+    ModuleSummaryIndex Index =
+        AM.getResult<ModuleSummaryIndexAnalysis>(M)(false);
+    WriteBitcodeToFile(M, OS, ShouldPreserveUseListOrder, &Index,
+                       EmitModuleHash);
+  } else {
+    WriteBitcodeToFile(M, OS, ShouldPreserveUseListOrder, nullptr,
+                       EmitModuleHash);
+  }
   return PreservedAnalyses::all();
 }
 
@@ -33,6 +38,7 @@
     bool ShouldPreserveUseListOrder;
     bool EmitSummaryIndex;
     bool EmitModuleHash;
+    bool StackSafety;
 
   public:
     static char ID; // Pass identification, replacement for typeid
@@ -41,22 +47,27 @@
     }
 
     explicit WriteBitcodePass(raw_ostream &o, bool ShouldPreserveUseListOrder,
-                              bool EmitSummaryIndex, bool EmitModuleHash)
+                              bool EmitSummaryIndex, bool EmitModuleHash,
+                              bool StackSafety)
         : ModulePass(ID), OS(o),
           ShouldPreserveUseListOrder(ShouldPreserveUseListOrder),
-          EmitSummaryIndex(EmitSummaryIndex), EmitModuleHash(EmitModuleHash) {
+          EmitSummaryIndex(EmitSummaryIndex), EmitModuleHash(EmitModuleHash),
+          StackSafety(StackSafety) {
       initializeWriteBitcodePassPass(*PassRegistry::getPassRegistry());
     }
 
     StringRef getPassName() const override { return "Bitcode Writer"; }
 
     bool runOnModule(Module &M) override {
-      const ModuleSummaryIndex *Index =
-          EmitSummaryIndex
-              ? &(getAnalysis<ModuleSummaryIndexWrapperPass>().getIndex())
-              : nullptr;
-      WriteBitcodeToFile(M, OS, ShouldPreserveUseListOrder, Index,
-                         EmitModuleHash);
+      if (EmitSummaryIndex) {
+        ModuleSummaryIndex Index =
+            getAnalysis<ModuleSummaryIndexWrapperPass>().getIndex(StackSafety);
+        WriteBitcodeToFile(M, OS, ShouldPreserveUseListOrder, &Index,
+                           EmitModuleHash);
+      } else {
+        WriteBitcodeToFile(M, OS, ShouldPreserveUseListOrder, nullptr,
+                           EmitModuleHash);
+      }
       return false;
     }
     void getAnalysisUsage(AnalysisUsage &AU) const override {
@@ -76,9 +87,11 @@
 
 ModulePass *llvm::createBitcodeWriterPass(raw_ostream &Str,
                                           bool ShouldPreserveUseListOrder,
-                                          bool EmitSummaryIndex, bool EmitModuleHash) {
-  return new WriteBitcodePass(Str, ShouldPreserveUseListOrder,
-                              EmitSummaryIndex, EmitModuleHash);
+                                          bool EmitSummaryIndex,
+                                          bool EmitModuleHash,
+                                          bool StackSafety) {
+  return new WriteBitcodePass(Str, ShouldPreserveUseListOrder, EmitSummaryIndex,
+                              EmitModuleHash, StackSafety);
 }
 
 bool llvm::isBitcodeWriterPass(Pass *P) {
Index: llvm/lib/Analysis/StackSafetyAnalysis.cpp
===================================================================
--- llvm/lib/Analysis/StackSafetyAnalysis.cpp
+++ llvm/lib/Analysis/StackSafetyAnalysis.cpp
@@ -727,8 +727,6 @@
 // constructor fields
 std::vector<FunctionSummary::ParamAccess>
 StackSafetyInfo::getParamAccesses() const {
-  assert(needsParamAccessSummary(*F->getParent()));
-
   std::vector<FunctionSummary::ParamAccess> ParamAccesses;
   for (const auto &KV : getInfo().Info.Params) {
     auto &PS = KV.second;
@@ -881,15 +879,6 @@
   return false;
 }
 
-bool llvm::needsParamAccessSummary(const Module &M) {
-  if (StackSafetyRun)
-    return true;
-  for (auto &F : M.functions())
-    if (F.hasFnAttribute(Attribute::SanitizeMemTag))
-      return true;
-  return false;
-}
-
 void llvm::processParamAccessSummary(ModuleSummaryIndex &Index) {
   const ConstantRange FullSet(FunctionSummary::ParamAccess::RangeWidth, true);
   std::map<const FunctionSummary *, FunctionInfo<FunctionSummary>> Functions;
Index: llvm/lib/Analysis/ModuleSummaryAnalysis.cpp
===================================================================
--- llvm/lib/Analysis/ModuleSummaryAnalysis.cpp
+++ llvm/lib/Analysis/ModuleSummaryAnalysis.cpp
@@ -840,23 +840,25 @@
 
 AnalysisKey ModuleSummaryIndexAnalysis::Key;
 
-ModuleSummaryIndex
+ModuleSummaryIndexAnalysis::Result
 ModuleSummaryIndexAnalysis::run(Module &M, ModuleAnalysisManager &AM) {
   ProfileSummaryInfo &PSI = AM.getResult<ProfileSummaryAnalysis>(M);
   auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
-  bool NeedSSI = needsParamAccessSummary(M);
-  return buildModuleSummaryIndex(
-      M,
-      [&FAM](const Function &F) {
-        return &FAM.getResult<BlockFrequencyAnalysis>(
-            *const_cast<Function *>(&F));
-      },
-      &PSI,
-      [&FAM, NeedSSI](const Function &F) -> const StackSafetyInfo * {
-        return NeedSSI ? &FAM.getResult<StackSafetyAnalysis>(
-                             const_cast<Function &>(F))
-                       : nullptr;
-      });
+  return [&](bool StackSafety) -> ModuleSummaryIndex {
+    return buildModuleSummaryIndex(
+        M,
+        [&FAM](const Function &F) {
+          return &FAM.getResult<BlockFrequencyAnalysis>(
+              *const_cast<Function *>(&F));
+        },
+        &PSI,
+        [&](const Function &F) -> const StackSafetyInfo * {
+          return (StackSafety /*|| ModuleSummaryStackSafety*/)
+                     ? &FAM.getResult<StackSafetyAnalysis>(
+                           const_cast<Function &>(F))
+                     : nullptr;
+        });
+  };
 }
 
 char ModuleSummaryIndexWrapperPass::ID = 0;
@@ -879,27 +881,23 @@
 }
 
 bool ModuleSummaryIndexWrapperPass::runOnModule(Module &M) {
-  auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
-  bool NeedSSI = needsParamAccessSummary(M);
-  Index.emplace(buildModuleSummaryIndex(
-      M,
-      [this](const Function &F) {
-        return &(this->getAnalysis<BlockFrequencyInfoWrapperPass>(
-                         *const_cast<Function *>(&F))
-                     .getBFI());
-      },
-      PSI,
-      [&](const Function &F) -> const StackSafetyInfo * {
-        return NeedSSI ? &getAnalysis<StackSafetyInfoWrapperPass>(
-                              const_cast<Function &>(F))
-                              .getResult()
-                       : nullptr;
-      }));
-  return false;
-}
-
-bool ModuleSummaryIndexWrapperPass::doFinalization(Module &M) {
-  Index.reset();
+  Getter = [this, &M](bool StackSafety) {
+    auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
+    return buildModuleSummaryIndex(
+        M,
+        [this](const Function &F) {
+          return &(this->getAnalysis<BlockFrequencyInfoWrapperPass>(
+                           *const_cast<Function *>(&F))
+                       .getBFI());
+        },
+        PSI,
+        [&](const Function &F) -> const StackSafetyInfo * {
+          return StackSafety ? &getAnalysis<StackSafetyInfoWrapperPass>(
+                                    const_cast<Function &>(F))
+                                    .getResult()
+                             : nullptr;
+        });
+  };
   return false;
 }
 
Index: llvm/include/llvm/Transforms/IPO/ThinLTOBitcodeWriter.h
===================================================================
--- llvm/include/llvm/Transforms/IPO/ThinLTOBitcodeWriter.h
+++ llvm/include/llvm/Transforms/IPO/ThinLTOBitcodeWriter.h
@@ -25,12 +25,14 @@
     : public PassInfoMixin<ThinLTOBitcodeWriterPass> {
   raw_ostream &OS;
   raw_ostream *ThinLinkOS;
+  bool StackSafety;
 
 public:
   // Writes bitcode to OS. Also write thin link file to ThinLinkOS, if
   // it's not nullptr.
-  ThinLTOBitcodeWriterPass(raw_ostream &OS, raw_ostream *ThinLinkOS)
-      : OS(OS), ThinLinkOS(ThinLinkOS) {}
+  ThinLTOBitcodeWriterPass(raw_ostream &OS, raw_ostream *ThinLinkOS,
+                           bool StackSafety)
+      : OS(OS), ThinLinkOS(ThinLinkOS), StackSafety(StackSafety) {}
 
   PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM);
 };
Index: llvm/include/llvm/Transforms/IPO.h
===================================================================
--- llvm/include/llvm/Transforms/IPO.h
+++ llvm/include/llvm/Transforms/IPO.h
@@ -280,7 +280,8 @@
 
 /// Write ThinLTO-ready bitcode to Str.
 ModulePass *createWriteThinLTOBitcodePass(raw_ostream &Str,
-                                          raw_ostream *ThinLinkOS = nullptr);
+                                          raw_ostream *ThinLinkOS,
+                                          bool StackSafety = false);
 
 } // End llvm namespace
 
Index: llvm/include/llvm/Bitcode/BitcodeWriterPass.h
===================================================================
--- llvm/include/llvm/Bitcode/BitcodeWriterPass.h
+++ llvm/include/llvm/Bitcode/BitcodeWriterPass.h
@@ -36,9 +36,9 @@
 /// If \c EmitModuleHash, compute and emit the module hash in the bitcode
 /// (currently for use in ThinLTO incremental build).
 ModulePass *createBitcodeWriterPass(raw_ostream &Str,
-                                    bool ShouldPreserveUseListOrder = false,
-                                    bool EmitSummaryIndex = false,
-                                    bool EmitModuleHash = false);
+                                    bool ShouldPreserveUseListOrder,
+                                    bool EmitSummaryIndex, bool EmitModuleHash,
+                                    bool StackSafety);
 
 /// Check whether a pass is a BitcodeWriterPass.
 bool isBitcodeWriterPass(Pass *P);
Index: llvm/include/llvm/Analysis/StackSafetyAnalysis.h
===================================================================
--- llvm/include/llvm/Analysis/StackSafetyAnalysis.h
+++ llvm/include/llvm/Analysis/StackSafetyAnalysis.h
@@ -149,8 +149,6 @@
   bool runOnModule(Module &M) override;
 };
 
-bool needsParamAccessSummary(const Module &M);
-
 void processParamAccessSummary(ModuleSummaryIndex &Index);
 
 } // end namespace llvm
Index: llvm/include/llvm/Analysis/ModuleSummaryAnalysis.h
===================================================================
--- llvm/include/llvm/Analysis/ModuleSummaryAnalysis.h
+++ llvm/include/llvm/Analysis/ModuleSummaryAnalysis.h
@@ -37,8 +37,7 @@
     const Module &M,
     std::function<BlockFrequencyInfo *(const Function &F)> GetBFICallback,
     ProfileSummaryInfo *PSI,
-    std::function<const StackSafetyInfo *(const Function &F)> GetSSICallback =
-        [](const Function &F) -> const StackSafetyInfo * { return nullptr; });
+    std::function<const StackSafetyInfo *(const Function &F)> GetSSICallback);
 
 /// Analysis pass to provide the ModuleSummaryIndex object.
 class ModuleSummaryIndexAnalysis
@@ -48,26 +47,23 @@
   static AnalysisKey Key;
 
 public:
-  using Result = ModuleSummaryIndex;
+  using Result = std::function<ModuleSummaryIndex(bool StackSafety)>;
 
   Result run(Module &M, ModuleAnalysisManager &AM);
 };
 
 /// Legacy wrapper pass to provide the ModuleSummaryIndex object.
 class ModuleSummaryIndexWrapperPass : public ModulePass {
-  Optional<ModuleSummaryIndex> Index;
-
 public:
   static char ID;
+  std::function<ModuleSummaryIndex(bool StackSafety)> Getter;
 
-  ModuleSummaryIndexWrapperPass();
+  explicit ModuleSummaryIndexWrapperPass();
 
   /// Get the index built by pass
-  ModuleSummaryIndex &getIndex() { return *Index; }
-  const ModuleSummaryIndex &getIndex() const { return *Index; }
+  ModuleSummaryIndex getIndex(bool StackSafety) { return Getter(StackSafety); }
 
   bool runOnModule(Module &M) override;
-  bool doFinalization(Module &M) override;
   void getAnalysisUsage(AnalysisUsage &AU) const override;
 };
 
Index: clang/lib/CodeGen/BackendUtil.cpp
===================================================================
--- clang/lib/CodeGen/BackendUtil.cpp
+++ clang/lib/CodeGen/BackendUtil.cpp
@@ -894,7 +894,9 @@
       TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
                                CodeGenOpts.EnableSplitLTOUnit);
       PerModulePasses.add(createWriteThinLTOBitcodePass(
-          *OS, ThinLinkOS ? &ThinLinkOS->os() : nullptr));
+          *OS, ThinLinkOS ? &ThinLinkOS->os() : nullptr,
+          CodeGenOpts.OptimizationLevel > 0 &&
+              LangOpts.Sanitize.has(SanitizerKind::MemTag)));
     } else {
       // Emit a module summary by default for Regular LTO except for ld64
       // targets
@@ -911,7 +913,9 @@
       }
 
       PerModulePasses.add(createBitcodeWriterPass(
-          *OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
+          *OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary, false,
+          EmitLTOSummary && CodeGenOpts.OptimizationLevel > 0 &&
+              LangOpts.Sanitize.has(SanitizerKind::MemTag)));
     }
     break;
 
@@ -1400,8 +1404,10 @@
       }
       TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
                                CodeGenOpts.EnableSplitLTOUnit);
-      MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os()
-                                                           : nullptr));
+      MPM.addPass(ThinLTOBitcodeWriterPass(
+          *OS, ThinLinkOS ? &ThinLinkOS->os() : nullptr,
+          CodeGenOpts.OptimizationLevel > 0 &&
+              LangOpts.Sanitize.has(SanitizerKind::MemTag)));
     } else {
       // Emit a module summary by default for Regular LTO except for ld64
       // targets
_______________________________________________
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
  • [PATCH] D81244: [StackSaf... Vitaly Buka via Phabricator via cfe-commits

Reply via email to