[clang][msvc] Define _HAS_STATIC_RTTI to 0, when compiling with -fno-rtti
authorMarkus Böck <markus.boeck02@gmail.com>
Thu, 10 Jun 2021 15:02:44 +0000 (17:02 +0200)
committerMarkus Böck <markus.boeck02@gmail.com>
Thu, 10 Jun 2021 15:02:44 +0000 (17:02 +0200)
When using the -fno-rtti option of the GCC style clang++, using typeid results in an error. The MSVC STL however kindly provides a define flag called _HAS_STATIC_RTTI, which either enables or disables uses of typeid throughout the STL. By default, if undefined, it is set to 1, enabling the use of typeid.

With this patch, _HAS_STATIC_RTTI is set to 0 when -fno-rtti is specified. This way various headers of the MSVC STL like functional can be consumed without compilation failures.

Differential Revision: https://reviews.llvm.org/D103771

clang/lib/Driver/ToolChains/MSVC.cpp
clang/lib/Driver/ToolChains/MSVC.h
clang/test/Driver/msvc-static-rtti.cpp [new file with mode: 0644]

index dd7fa5e..9b1c320 100644 (file)
@@ -1573,3 +1573,13 @@ MSVCToolChain::TranslateArgs(const llvm::opt::DerivedArgList &Args,
 
   return DAL;
 }
+
+void MSVCToolChain::addClangTargetOptions(
+    const ArgList &DriverArgs, ArgStringList &CC1Args,
+    Action::OffloadKind DeviceOffloadKind) const {
+  // MSVC STL kindly allows removing all usages of typeid by defining
+  // _HAS_STATIC_RTTI to 0. Do so, when compiling with -fno-rtti
+  if (DriverArgs.hasArg(options::OPT_fno_rtti, options::OPT_frtti,
+                        /*Default=*/false))
+    CC1Args.push_back("-D_HAS_STATIC_RTTI=0");
+}
index 432d399..19d94c5 100644 (file)
@@ -122,6 +122,11 @@ public:
 
   bool FoundMSVCInstall() const { return !VCToolChainPath.empty(); }
 
+  void
+  addClangTargetOptions(const llvm::opt::ArgList &DriverArgs,
+                        llvm::opt::ArgStringList &CC1Args,
+                        Action::OffloadKind DeviceOffloadKind) const override;
+
 protected:
   void AddSystemIncludeWithSubfolder(const llvm::opt::ArgList &DriverArgs,
                                      llvm::opt::ArgStringList &CC1Args,
diff --git a/clang/test/Driver/msvc-static-rtti.cpp b/clang/test/Driver/msvc-static-rtti.cpp
new file mode 100644 (file)
index 0000000..b352f07
--- /dev/null
@@ -0,0 +1,5 @@
+// RUN: %clang -target x86_64-pc-windows-msvc -fno-rtti -### %s 2>&1 | FileCheck %s -check-prefix STATIC-RTTI-DEF
+// RUN: %clang -target x86_64-pc-windows-msvc -frtti -### %s 2>&1 | FileCheck %s -check-prefix STATIC-RTTI-DEF-NOT
+
+// STATIC-RTTI-DEF: -D_HAS_STATIC_RTTI=0
+// STATIC-RTTI-DEF-NOT: -D_HAS_STATIC_RTTI=0