[clang] [Clang] Avoid crash with wide string CPU builtin argument (PR #245515)

Bhavya Gautam via cfe-commits cfe-commits at lists.llvm.org
Mon Nov 23 23:06:36 PST 2026


https://github.com/gautam899 created https://github.com/llvm/llvm-project/pull/245515

This fixes #244868 by checking the character width before calling
getstring.

To validate the fix, I ran clang-check and found no new fails.


>From d36121fa037852a6308141919c158edbd0588b3c Mon Sep 17 00:00:00 2001
From: Bhavya Gautam <gautambhavya899 at gmail.com>
Date: Tue, 24 Nov 2026 10:25:11 +0530
Subject: [PATCH] [Clang] Avoid crash with wide string CPU builtin argument

---
 clang/lib/Sema/SemaChecking.cpp        | 10 ++++++++--
 clang/test/Sema/builtin-cpu-supports.c |  2 ++
 2 files changed, 10 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index ccb303624182f2..8368ee0e21092e 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -2572,13 +2572,19 @@ static bool BuiltinCpu(Sema &S, const TargetInfo &TI, CallExpr *TheCall,
            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
 
   Expr *Arg = TheCall->getArg(0)->IgnoreParenImpCasts();
+
+  StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
   // Check if the argument is a string literal.
-  if (!isa<StringLiteral>(Arg))
+  if (!Literal)
     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
            << Arg->getSourceRange();
 
+  // Validate the Character Width
+  if (Literal->getCharByteWidth() != 1)
+    return false;
+
   // Check the contents of the string.
-  StringRef Feature = cast<StringLiteral>(Arg)->getString();
+  StringRef Feature = Literal->getString();
   if (IsCPUSupports && !TheTI->validateCpuSupports(Feature)) {
     S.Diag(TheCall->getBeginLoc(), diag::warn_invalid_cpu_supports)
         << Arg->getSourceRange();
diff --git a/clang/test/Sema/builtin-cpu-supports.c b/clang/test/Sema/builtin-cpu-supports.c
index 4dace25b42a970..4a33f223893f18 100644
--- a/clang/test/Sema/builtin-cpu-supports.c
+++ b/clang/test/Sema/builtin-cpu-supports.c
@@ -18,6 +18,8 @@ int main(void) {
   if (__builtin_cpu_supports(str)) // expected-error {{expression is not a string literal}}
     a(str);
 
+  (void)__builtin_cpu_supports(L"wide"); // expected-error {{incompatible pointer types}}
+
   if (__builtin_cpu_is("int")) // expected-error {{invalid cpu name for builtin}}
     a("intel");
 



More information about the cfe-commits mailing list