Skip to content

Conversation

@Islam-Imad
Copy link
Contributor

This patch refactors the handling of elementwise integer unary operations to use a unified callback-based approach, eliminating code duplication.

Changes:

  • Extended interp__builtin_elementwise_int_unaryop to handle vector types
  • Replaced BI__builtin_elementwise_popcount with callback invocation
  • Replaced BI__builtin_elementwise_bitreverse with callback invocation
  • Removed interp__builtin_elementwise_popcount function

The new approach uses a lambda function to specify the operation (popcount or reverseBits), which is applied uniformly to both scalar and vector operands. This reduces code duplication and makes it easier to add similar builtins in the future.

Fixes #169657

…attern

This patch refactors the handling of elementwise integer unary
operations to use a unified callback-based approach, eliminating
code duplication.

Changes:
- Extended interp__builtin_elementwise_int_unaryop to handle vector types
- Replaced BI__builtin_elementwise_popcount with callback invocation
- Replaced BI__builtin_elementwise_bitreverse with callback invocation
- Removed  interp__builtin_elementwise_popcount function

The new approach uses a lambda function to specify the operation
(popcount or reverseBits), which is applied uniformly to both scalar
and vector operands. This reduces code duplication and makes it easier
to add similar builtins in the future.

Fixes llvm#169657
@github-actions
Copy link

Thank you for submitting a Pull Request (PR) to the LLVM Project!

This PR will be automatically labeled and the relevant teams will be notified.

If you wish to, you can add reviewers by using the "Reviewers" section on this page.

If this is not working for you, it is probably because you do not have write permissions for the repository. In which case you can instead tag reviewers by name in a comment by using @ followed by their GitHub username.

If you have received no comments on your PR for a week, you can request a review by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate is once a week. Please remember that you are asking for valuable time from other developers.

If you have further questions, they may be answered by the LLVM GitHub User Guide.

You can also ask questions in a comment on this PR, on the LLVM Discord or on the forums.

@llvmbot llvmbot added clang Clang issues not falling into any other category clang:frontend Language frontend issues, e.g. anything involving "Sema" clang:bytecode Issues for the clang bytecode constexpr interpreter labels Nov 28, 2025
@llvmbot
Copy link
Member

llvmbot commented Nov 28, 2025

@llvm/pr-subscribers-clang

Author: Islam Imad (Islam-Imad)

Changes

This patch refactors the handling of elementwise integer unary operations to use a unified callback-based approach, eliminating code duplication.

Changes:

  • Extended interp__builtin_elementwise_int_unaryop to handle vector types
  • Replaced BI__builtin_elementwise_popcount with callback invocation
  • Replaced BI__builtin_elementwise_bitreverse with callback invocation
  • Removed interp__builtin_elementwise_popcount function

The new approach uses a lambda function to specify the operation (popcount or reverseBits), which is applied uniformly to both scalar and vector operands. This reduces code duplication and makes it easier to add similar builtins in the future.

Fixes #169657


Full diff: https://github.com/llvm/llvm-project/pull/169957.diff

1 Files Affected:

  • (modified) clang/lib/AST/ByteCode/InterpBuiltin.cpp (+30-50)
diff --git a/clang/lib/AST/ByteCode/InterpBuiltin.cpp b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
index d21f42d94d3a5..8496b58105c7a 100644
--- a/clang/lib/AST/ByteCode/InterpBuiltin.cpp
+++ b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
@@ -1626,51 +1626,6 @@ static bool interp__builtin_elementwise_abs(InterpState &S, CodePtr OpPC,
   return true;
 }
 
-/// Can be called with an integer or vector as the first and only parameter.
-static bool interp__builtin_elementwise_popcount(InterpState &S, CodePtr OpPC,
-                                                 const InterpFrame *Frame,
-                                                 const CallExpr *Call,
-                                                 unsigned BuiltinID) {
-  assert(Call->getNumArgs() == 1);
-  if (Call->getArg(0)->getType()->isIntegerType()) {
-    APSInt Val = popToAPSInt(S, Call->getArg(0));
-
-    if (BuiltinID == Builtin::BI__builtin_elementwise_popcount) {
-      pushInteger(S, Val.popcount(), Call->getType());
-    } else {
-      pushInteger(S, Val.reverseBits(), Call->getType());
-    }
-    return true;
-  }
-  // Otherwise, the argument must be a vector.
-  assert(Call->getArg(0)->getType()->isVectorType());
-  const Pointer &Arg = S.Stk.pop<Pointer>();
-  assert(Arg.getFieldDesc()->isPrimitiveArray());
-  const Pointer &Dst = S.Stk.peek<Pointer>();
-  assert(Dst.getFieldDesc()->isPrimitiveArray());
-  assert(Arg.getFieldDesc()->getNumElems() ==
-         Dst.getFieldDesc()->getNumElems());
-
-  QualType ElemType = Arg.getFieldDesc()->getElemQualType();
-  PrimType ElemT = *S.getContext().classify(ElemType);
-  unsigned NumElems = Arg.getNumElems();
-
-  // FIXME: Reading from uninitialized vector elements?
-  for (unsigned I = 0; I != NumElems; ++I) {
-    INT_TYPE_SWITCH_NO_BOOL(ElemT, {
-      if (BuiltinID == Builtin::BI__builtin_elementwise_popcount) {
-        Dst.elem<T>(I) = T::from(Arg.elem<T>(I).toAPSInt().popcount());
-      } else {
-        Dst.elem<T>(I) =
-            T::from(Arg.elem<T>(I).toAPSInt().reverseBits().getZExtValue());
-      }
-    });
-  }
-  Dst.initializeAllElements();
-
-  return true;
-}
-
 /// Can be called with an integer or vector as the first and only parameter.
 static bool interp__builtin_elementwise_countzeroes(InterpState &S,
                                                     CodePtr OpPC,
@@ -2407,18 +2362,39 @@ static bool interp__builtin_elementwise_int_unaryop(
     InterpState &S, CodePtr OpPC, const CallExpr *Call,
     llvm::function_ref<APInt(const APSInt &)> Fn) {
   assert(Call->getNumArgs() == 1);
-  assert(Call->getType()->isIntegerType());
 
   // Single integer case.
   if (!Call->getArg(0)->getType()->isVectorType()) {
+    assert(Call->getType()->isIntegerType());
     APSInt Src = popToAPSInt(S, Call->getArg(0));
     APInt Result = Fn(Src);
     pushInteger(S, APSInt(std::move(Result), !Src.isSigned()), Call->getType());
     return true;
   }
 
-  // TODO: Add vector integer handling.
-  return false;
+  // Vector case.
+  const Pointer &Arg = S.Stk.pop<Pointer>();
+  assert(Arg.getFieldDesc()->isPrimitiveArray());
+  const Pointer &Dst = S.Stk.peek<Pointer>();
+  assert(Dst.getFieldDesc()->isPrimitiveArray());
+  assert(Arg.getFieldDesc()->getNumElems() ==
+         Dst.getFieldDesc()->getNumElems());
+
+  QualType ElemType = Arg.getFieldDesc()->getElemQualType();
+  PrimType ElemT = *S.getContext().classify(ElemType);
+  unsigned NumElems = Arg.getNumElems();
+  bool DestUnsigned = Call->getType()->isUnsignedIntegerOrEnumerationType();
+
+  for (unsigned I = 0; I != NumElems; ++I) {
+    INT_TYPE_SWITCH_NO_BOOL(ElemT, {
+      APSInt Src = Arg.elem<T>(I).toAPSInt();
+      APInt Result = Fn(Src);
+      Dst.elem<T>(I) = static_cast<T>(APSInt(std::move(Result), DestUnsigned));
+    });
+  }
+  Dst.initializeAllElements();
+
+  return true;
 }
 
 static bool interp__builtin_elementwise_int_binop(
@@ -4212,9 +4188,13 @@ bool InterpretBuiltin(InterpState &S, CodePtr OpPC, const CallExpr *Call,
     return interp__builtin_vector_reduce(S, OpPC, Call, BuiltinID);
 
   case Builtin::BI__builtin_elementwise_popcount:
+    return interp__builtin_elementwise_int_unaryop(
+        S, OpPC, Call, [](const APSInt &Src) {
+          return APInt(Src.getBitWidth(), Src.popcount());
+        });
   case Builtin::BI__builtin_elementwise_bitreverse:
-    return interp__builtin_elementwise_popcount(S, OpPC, Frame, Call,
-                                                BuiltinID);
+    return interp__builtin_elementwise_int_unaryop(
+        S, OpPC, Call, [](const APSInt &Src) { return Src.reverseBits(); });
 
   case Builtin::BI__builtin_elementwise_abs:
     return interp__builtin_elementwise_abs(S, OpPC, Frame, Call, BuiltinID);

@RKSimon RKSimon requested review from RKSimon and tbaederr November 29, 2025 12:38
Copy link
Collaborator

@RKSimon RKSimon left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM - cheers!

@RKSimon RKSimon enabled auto-merge (squash) November 29, 2025 17:08
@RKSimon RKSimon merged commit 246528c into llvm:main Nov 29, 2025
9 of 10 checks passed
@github-actions
Copy link

@Islam-Imad Congratulations on having your first Pull Request (PR) merged into the LLVM Project!

Your changes will be combined with recent changes from other authors, then tested by our build bots. If there is a problem with a build, you may receive a report in an email or a comment on this PR.

Please check whether problems have been caused by your change specifically, as the builds can include changes from many authors. It is not uncommon for your change to be included in a build that fails due to someone else's changes, or infrastructure issues.

How to do this, and the rest of the post-merge process, is covered in detail here.

If your change does cause a problem, it may be reverted, or you can revert it yourself. This is a normal part of LLVM development. You can fix your changes and open a new PR to merge them again.

If you don't get any reports, no action is required from you. Your changes are working as expected, well done!

@llvm-ci
Copy link
Collaborator

llvm-ci commented Nov 29, 2025

LLVM Buildbot has detected a new failure on builder clang-aarch64-sve-vla running on linaro-g3-02 while building clang at step 7 "ninja check 1".

Full details are available at: https://lab.llvm.org/buildbot/#/builders/17/builds/13061

Here is the relevant piece of the build log for the reference
Step 7 (ninja check 1) failure: stage 1 checked (failure)
******************** TEST 'SanitizerCommon-lsan-aarch64-Linux :: compress_stack_depot.cpp' FAILED ********************
Exit Code: 1

Command Output (stderr):
--
/home/tcwg-buildbot/worker/clang-aarch64-sve-vla/stage1/./bin/clang  --driver-mode=g++ -gline-tables-only -fsanitize=leak   -Wthread-safety -Wthread-safety-reference -Wthread-safety-beta  -funwind-tables  -I/home/tcwg-buildbot/worker/clang-aarch64-sve-vla/llvm/compiler-rt/test -ldl /home/tcwg-buildbot/worker/clang-aarch64-sve-vla/llvm/compiler-rt/test/sanitizer_common/TestCases/compress_stack_depot.cpp -fsanitize-memory-track-origins=1 -o /home/tcwg-buildbot/worker/clang-aarch64-sve-vla/stage1/runtimes/runtimes-bins/compiler-rt/test/sanitizer_common/lsan-aarch64-Linux/Output/compress_stack_depot.cpp.tmp # RUN: at line 1
+ /home/tcwg-buildbot/worker/clang-aarch64-sve-vla/stage1/./bin/clang --driver-mode=g++ -gline-tables-only -fsanitize=leak -Wthread-safety -Wthread-safety-reference -Wthread-safety-beta -funwind-tables -I/home/tcwg-buildbot/worker/clang-aarch64-sve-vla/llvm/compiler-rt/test -ldl /home/tcwg-buildbot/worker/clang-aarch64-sve-vla/llvm/compiler-rt/test/sanitizer_common/TestCases/compress_stack_depot.cpp -fsanitize-memory-track-origins=1 -o /home/tcwg-buildbot/worker/clang-aarch64-sve-vla/stage1/runtimes/runtimes-bins/compiler-rt/test/sanitizer_common/lsan-aarch64-Linux/Output/compress_stack_depot.cpp.tmp
clang: warning: argument unused during compilation: '-fsanitize-memory-track-origins=1' [-Wunused-command-line-argument]
env LSAN_OPTIONS="compress_stack_depot=0:malloc_context_size=128:verbosity=1"  /home/tcwg-buildbot/worker/clang-aarch64-sve-vla/stage1/runtimes/runtimes-bins/compiler-rt/test/sanitizer_common/lsan-aarch64-Linux/Output/compress_stack_depot.cpp.tmp 2>&1 | FileCheck /home/tcwg-buildbot/worker/clang-aarch64-sve-vla/llvm/compiler-rt/test/sanitizer_common/TestCases/compress_stack_depot.cpp --implicit-check-not="StackDepot released" # RUN: at line 2
+ FileCheck /home/tcwg-buildbot/worker/clang-aarch64-sve-vla/llvm/compiler-rt/test/sanitizer_common/TestCases/compress_stack_depot.cpp '--implicit-check-not=StackDepot released'
+ env LSAN_OPTIONS=compress_stack_depot=0:malloc_context_size=128:verbosity=1 /home/tcwg-buildbot/worker/clang-aarch64-sve-vla/stage1/runtimes/runtimes-bins/compiler-rt/test/sanitizer_common/lsan-aarch64-Linux/Output/compress_stack_depot.cpp.tmp
env LSAN_OPTIONS="compress_stack_depot=-1:malloc_context_size=128:verbosity=1"  /home/tcwg-buildbot/worker/clang-aarch64-sve-vla/stage1/runtimes/runtimes-bins/compiler-rt/test/sanitizer_common/lsan-aarch64-Linux/Output/compress_stack_depot.cpp.tmp 2>&1 | FileCheck /home/tcwg-buildbot/worker/clang-aarch64-sve-vla/llvm/compiler-rt/test/sanitizer_common/TestCases/compress_stack_depot.cpp --check-prefixes=COMPRESS # RUN: at line 3
+ env LSAN_OPTIONS=compress_stack_depot=-1:malloc_context_size=128:verbosity=1 /home/tcwg-buildbot/worker/clang-aarch64-sve-vla/stage1/runtimes/runtimes-bins/compiler-rt/test/sanitizer_common/lsan-aarch64-Linux/Output/compress_stack_depot.cpp.tmp
+ FileCheck /home/tcwg-buildbot/worker/clang-aarch64-sve-vla/llvm/compiler-rt/test/sanitizer_common/TestCases/compress_stack_depot.cpp --check-prefixes=COMPRESS
env LSAN_OPTIONS="compress_stack_depot=-2:malloc_context_size=128:verbosity=1"  /home/tcwg-buildbot/worker/clang-aarch64-sve-vla/stage1/runtimes/runtimes-bins/compiler-rt/test/sanitizer_common/lsan-aarch64-Linux/Output/compress_stack_depot.cpp.tmp 2>&1 | FileCheck /home/tcwg-buildbot/worker/clang-aarch64-sve-vla/llvm/compiler-rt/test/sanitizer_common/TestCases/compress_stack_depot.cpp --check-prefixes=COMPRESS # RUN: at line 4
+ env LSAN_OPTIONS=compress_stack_depot=-2:malloc_context_size=128:verbosity=1 /home/tcwg-buildbot/worker/clang-aarch64-sve-vla/stage1/runtimes/runtimes-bins/compiler-rt/test/sanitizer_common/lsan-aarch64-Linux/Output/compress_stack_depot.cpp.tmp
+ FileCheck /home/tcwg-buildbot/worker/clang-aarch64-sve-vla/llvm/compiler-rt/test/sanitizer_common/TestCases/compress_stack_depot.cpp --check-prefixes=COMPRESS
env LSAN_OPTIONS="compress_stack_depot=1:malloc_context_size=128:verbosity=1"  /home/tcwg-buildbot/worker/clang-aarch64-sve-vla/stage1/runtimes/runtimes-bins/compiler-rt/test/sanitizer_common/lsan-aarch64-Linux/Output/compress_stack_depot.cpp.tmp 2>&1 | FileCheck /home/tcwg-buildbot/worker/clang-aarch64-sve-vla/llvm/compiler-rt/test/sanitizer_common/TestCases/compress_stack_depot.cpp --check-prefixes=COMPRESS,THREAD # RUN: at line 5
+ env LSAN_OPTIONS=compress_stack_depot=1:malloc_context_size=128:verbosity=1 /home/tcwg-buildbot/worker/clang-aarch64-sve-vla/stage1/runtimes/runtimes-bins/compiler-rt/test/sanitizer_common/lsan-aarch64-Linux/Output/compress_stack_depot.cpp.tmp
+ FileCheck /home/tcwg-buildbot/worker/clang-aarch64-sve-vla/llvm/compiler-rt/test/sanitizer_common/TestCases/compress_stack_depot.cpp --check-prefixes=COMPRESS,THREAD
/home/tcwg-buildbot/worker/clang-aarch64-sve-vla/llvm/compiler-rt/test/sanitizer_common/TestCases/compress_stack_depot.cpp:53:14: error: COMPRESS: expected string not found in input
// COMPRESS: StackDepot released {{[0-9]+}}
             ^
<stdin>:12:53: note: scanning from here
LeakSanitizer: StackDepot compression thread started
                                                    ^
<stdin>:13:16: note: possible intended match here
LeakSanitizer: StackDepot compression thread stopped
               ^

Input file: <stdin>
Check file: /home/tcwg-buildbot/worker/clang-aarch64-sve-vla/llvm/compiler-rt/test/sanitizer_common/TestCases/compress_stack_depot.cpp

-dump-input=help explains the following input dump.

Input was:
<<<<<<
            .
            .
            .
            7: ==3360772==Unregistered root region at 0xff43a6a03190 of size 208 
            8: ==3360772==Unregistered root region at 0xff43a7400780 of size 32 
            9: ==3360772==Installed the sigaction for signal 11 
           10: ==3360772==Installed the sigaction for signal 7 
           11: ==3360772==Installed the sigaction for signal 8 
           12: LeakSanitizer: StackDepot compression thread started 
check:53'0                                                         X error: no match found
           13: LeakSanitizer: StackDepot compression thread stopped 
check:53'0     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
check:53'1                    ?                                      possible intended match
...

@Islam-Imad
Copy link
Contributor Author

Hi @RKSimon ,

I hope you're doing well. I noticed the buildbot reported some failures after my PR was merged. Could you help me understand how these are related to my changes?

Thank you for your time!

@RKSimon
Copy link
Collaborator

RKSimon commented Nov 29, 2025

I think you're ok. A good quick check is to see if the buildbot went green again in the following build. Some of the bots can be intermittent.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

clang:bytecode Issues for the clang bytecode constexpr interpreter clang:frontend Language frontend issues, e.g. anything involving "Sema" clang Clang issues not falling into any other category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[clang] InterpBuiltin - replace interp__builtin_elementwise_popcount with interp__builtin_elementwise_int_unaryop callback

5 participants