[cfe-dev] new predefined macros to expose target triple values?

Bob Wilson via cfe-dev cfe-dev at lists.llvm.org
Thu Nov 30 17:15:09 PST 2017

I wondering if anyone besides Apple would be interested in having predefined macros to identify the target OS and environment.

Background: Over the last few years, Apple has added several new platforms (tvOS and watchOS) as well as simulator variants for those, and we’ve accumulated a fair bit of complexity by adding Clang support for those platforms with a copy-and-paste approach. The -mmacosx-version-min option worked well when there was only one Apple platform, but it’s not so great now that we have a lot of -m*-version-min options. We’re trying to move toward the more standard approach of using the -target option to specify the target triple, including the OS version. Akira added support for that earlier (Clang r307982) and we’ve started moving toward identifying simulator targets via the environment field of the triple (LLVM r316380). Related to that, we also need a way to identify via predefined macros what target we’re building for. We recently added the __APPLE_EMBEDDED_SIMULATOR__ macro to distinguish the simulator targets (although it is currently not working when you use the -target option alone), but we don’t have anything to distinguish iOS vs. tvOS vs. watchOS.

It occurred to me that we can do this in a very general way by exposing the OS and Environment fields of the target triple directly in predefined macros. (We could do the same for the Arch and Vendor fields if anyone has a use for those.)

We could add these new macros only for Darwin targets, but since they are not at all Darwin-specific, what do you all think of adding them for all targets?

To be specific, here’s the change that I’m suggesting. (I’ll put it up for a proper review with a testcase if there is positive feedback for doing it this way.)

diff --git lib/Frontend/InitPreprocessor.cpp lib/Frontend/InitPreprocessor.cpp
index 67c1faddc3..c1dfb39c37 100644
--- lib/Frontend/InitPreprocessor.cpp
+++ lib/Frontend/InitPreprocessor.cpp
@@ -713,6 +713,14 @@ static void InitializePredefinedMacros(const TargetInfo &TI,
   // Initialize target-specific preprocessor defines.
+  // Identify the OS and Environment fields of the target triple.
+  Builder.defineMacro("__TARGET_OS__",
+                      TI.getTriple().getOSTypeName(TI.getTriple().getOS()));
+  if (TI.getTriple().hasEnvironment()) {
+    Builder.defineMacro("__TARGET_ENVIRONMENT__",
+      TI.getTriple().getEnvironmentTypeName(TI.getTriple().getEnvironment()));
+  }
   // __BYTE_ORDER__ was added in GCC 4.6. It's analogous
   // to the macro __BYTE_ORDER (no trailing underscores)
   // from glibc's <endian.h> header.

More information about the cfe-dev mailing list