[clang] [clang][Lex] Keep 'defined' operator in pre-expanding macro argument to match MSVC's behavior (PR #241157)
via cfe-commits
cfe-commits at lists.llvm.org
Tue Nov 10 23:12:55 PST 2026
llvmorg-github-actions[bot] wrote:
<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-clang
Author: Yihan Wang (yronglin)
<details>
<summary>Changes</summary>
Test Case:
```cpp
#define FOO(x) (defined __foo_##x && __foo_##x)
#define __foo_hello true
#define NOT(X) (!(X))
#if NOT(FOO(hello))
#error Clang says hello
#else
#error MSVC says hello
#endif
```
When pre-expanding macro arguments, `MacroArgs::getPreExpArgument` uses a comsumes all macro argument tokens through `PP.Lex(Tok)`, and fully expanding the entire argument at once. This process is unaware that it is taking place within an `#if` directive; consequently, in the expression `defined __foo_hello` resulting from the expansion of `FOO(hello)`, `__foo_hello` is expanded into `true`. By the time `EvaluateDefined` encounters it, the expression has already become `defined true`.
Even though it constitutes undefined behavior, we maintain the same behavior as the traditional MSVC preprocessor.
[Godbolt](https://godbolt.org/z/Tadqjffoz)
https://discourse.llvm.org/t/rfc-default-on-diagnostics-for-implement-p2843r3-preprocessing-is-never-undefined/90863/10?u=yronglin
AI-Assisted
---
Full diff: https://github.com/llvm/llvm-project/pull/241157.diff
3 Files Affected:
- (modified) clang/docs/ReleaseNotes.md (+7)
- (modified) clang/lib/Lex/MacroArgs.cpp (+27-2)
- (added) clang/test/Preprocessor/microsoft-defined-in-macro-arg.cpp (+68)
``````````diff
diff --git a/clang/docs/ReleaseNotes.md b/clang/docs/ReleaseNotes.md
index 0f9e7e01636d71..86f477d1b32999 100644
--- a/clang/docs/ReleaseNotes.md
+++ b/clang/docs/ReleaseNotes.md
@@ -1361,6 +1361,13 @@ documentation](CIR/index.md) for more information regarding ClangIR's status and
``_try``, ``_finally``, and ``_leave`` aliases. ``_except`` remains an ordinary
identifier outside that context.
+- With ``-fms-compatibility``, the operand of a ``defined`` operator that is
+ produced while expanding a macro argument in an ``#if`` or ``#elif``
+ condition is no longer macro-expanded, matching MSVC. For example, with
+ ``#define FOO(x) (defined M_##x && M_##x)``, ``#define M_a true`` and
+ ``#define NOT(X) (!(X))``, ``#if NOT(FOO(a))`` is now false, as it is in
+ MSVC.
+
- Fixed ``setjmp`` on 32-bit Arm passing the frame pointer, rather than the
stack pointer as it was on entry to the function, as the frame value the CRT
stores in the ``jmp_buf``. Clang now uses ``llvm.sponentry`` there, as it
diff --git a/clang/lib/Lex/MacroArgs.cpp b/clang/lib/Lex/MacroArgs.cpp
index 548df16c59f6b2..08529c5be812c1 100644
--- a/clang/lib/Lex/MacroArgs.cpp
+++ b/clang/lib/Lex/MacroArgs.cpp
@@ -180,11 +180,36 @@ const std::vector<Token> &MacroArgs::getPreExpArgument(unsigned Arg,
PP.EnterTokenStream(AT, NumToks, false /*disable expand*/,
false /*owns tokens*/, false /*is reinject*/);
+ // In MSVC compatibility mode, keep the operand of a 'defined' operator in a
+ // '#if'/'#elif' condition unexpanded. MSVC does not pre-expand macro
+ // arguments, so it never expands the operand of a 'defined' that an
+ // argument's expansion generates. For example, given
+ // #define FOO(x) (defined __foo_##x && __foo_##x)
+ // #define __foo_hello true
+ // #define NOT(X) (!(X))
+ // #if NOT(FOO(hello))
+ // '__foo_hello' must not become 'true' while pre-expanding NOT's argument.
+ bool KeepDefinedOperand =
+ PP.getLangOpts().MSVCCompat && PP.isParsingIfOrElifDirective();
+
// Lex all of the macro-expanded tokens into Result.
do {
- Result.push_back(Token());
- Token &Tok = Result.back();
+ Token &Tok = Result.emplace_back();
PP.Lex(Tok);
+ if (!KeepDefinedOperand || Tok.isNot(tok::identifier) ||
+ Tok.getIdentifierInfo()->getPPKeywordID() != tok::pp_defined)
+ continue;
+
+ // Handle 'defined X' and 'defined ( X )': lex the operand, and the '('
+ // before it, without expanding them. Malformed uses are left for
+ // EvaluateDefined to diagnose.
+ PP.LexUnexpandedToken(Result.emplace_back());
+ if (Result.back().is(tok::l_paren))
+ PP.LexUnexpandedToken(Result.emplace_back());
+
+ // Keep the operand from being expanded when the result is rescanned.
+ if (Result.back().isNot(tok::eof))
+ Result.back().setFlag(Token::DisableExpand);
} while (Result.back().isNot(tok::eof));
// Pop the token stream off the top of the stack. We know that the internal
diff --git a/clang/test/Preprocessor/microsoft-defined-in-macro-arg.cpp b/clang/test/Preprocessor/microsoft-defined-in-macro-arg.cpp
new file mode 100644
index 00000000000000..1b1c0fd302395b
--- /dev/null
+++ b/clang/test/Preprocessor/microsoft-defined-in-macro-arg.cpp
@@ -0,0 +1,68 @@
+// RUN: %clang_cc1 -E -fms-compatibility %s | FileCheck %s --check-prefix=MS
+// RUN: %clang_cc1 -E %s | FileCheck %s --check-prefix=STD
+
+// A 'defined' generated while pre-expanding a macro argument in an #if
+// condition. MSVC does not pre-expand macro arguments, so it never expands the
+// operand of such a 'defined'; with -fms-compatibility, clang does the same.
+
+#define FOO(x) (defined __foo_##x && __foo_##x)
+#define BAR(x) (defined(__foo_##x) && __foo_##x)
+#define __foo_hello true
+#define NOT(X) (!(X))
+#define ID(X) X
+
+// Without a surrounding macro, both modes see 'defined __foo_hello'.
+#if FOO(hello)
+direct_defined
+#else
+direct_undefined
+#endif
+// MS: direct_defined
+// STD: direct_defined
+
+#if NOT(FOO(hello))
+not_true
+#else
+not_false
+#endif
+// MS: not_false
+// STD: not_true
+
+#if NOT(BAR(hello))
+paren_not_true
+#else
+paren_not_false
+#endif
+// MS: paren_not_false
+// STD: paren_not_true
+
+#if ID(NOT(ID(FOO(hello))))
+nested_true
+#else
+nested_false
+#endif
+// MS: nested_false
+// STD: nested_true
+
+#if 0
+#elif ID(FOO(hello))
+elif_defined
+#else
+elif_undefined
+#endif
+// MS: elif_defined
+// STD: elif_undefined
+
+// An operand that is not a macro is unaffected.
+#if ID(FOO(world))
+world_defined
+#else
+world_undefined
+#endif
+// MS: world_undefined
+// STD: world_undefined
+
+// Outside #if, the argument is still pre-expanded as usual.
+ID(defined __foo_hello)
+// MS: defined true
+// STD: defined true
``````````
</details>
https://github.com/llvm/llvm-project/pull/241157
More information about the cfe-commits
mailing list