[PATCH] D157440: [clang][ConstExprEmitter] handle BinaryOperators that don't have signedness or overflow concerns for integrals

Nick Desaulniers via Phabricator via cfe-commits cfe-commits at lists.llvm.org
Tue Aug 8 14:30:13 PDT 2023


nickdesaulniers created this revision.
Herald added a project: All.
nickdesaulniers requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Handles binary operators: & ^ | == !=

Check that each side evaluates to a ConstantInt then combine the
results.

We probably can reuse DataRecursiveIntBinOpEvaluator or
handleIntIntBinOp from ExprConstant.cpp for the rest, or even these
cases as well.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D157440

Files:
  clang/lib/CodeGen/CGExprConstant.cpp


Index: clang/lib/CodeGen/CGExprConstant.cpp
===================================================================
--- clang/lib/CodeGen/CGExprConstant.cpp
+++ clang/lib/CodeGen/CGExprConstant.cpp
@@ -1401,6 +1401,64 @@
     return nullptr;
   }
 
+  llvm::Constant *VisitBinaryOperator(BinaryOperator *B, QualType T) {
+    // Can we attempt to handle this opcode?
+    switch (B->getOpcode()) {
+    default:
+      return nullptr;
+    case BO_And:
+    case BO_Xor:
+    case BO_Or:
+    case BO_EQ:
+    case BO_NE:
+      break;
+    }
+
+    // Constant evaluate LHS
+    Expr *LHS = B->getLHS();
+    llvm::Constant *LHSC = Visit(LHS, T);
+
+    // Only handle integers for now.
+    if (!LHSC || !isa<llvm::ConstantInt>(LHSC))
+      return nullptr;
+
+    // Constant evaluate RHS
+    Expr *RHS = B->getRHS();
+    llvm::Constant *RHSC = Visit(RHS, T);
+
+    // Only handle integers for now.
+    if (!RHSC || !isa<llvm::ConstantInt>(RHSC))
+      return nullptr;
+
+    const llvm::APInt R = cast<llvm::ConstantInt>(RHSC)->getValue();
+    const llvm::APInt L = cast<llvm::ConstantInt>(LHSC)->getValue();
+    llvm::APInt Ret;
+
+    // Fold
+    switch (B->getOpcode()) {
+    default:
+      // Should have return earlier.
+      llvm_unreachable("unhandled BinaryOperator kind");
+    case BO_And:
+      Ret = L & R;
+      break;
+    case BO_Xor:
+      Ret = L ^ R;
+      break;
+    case BO_Or:
+      Ret = L | R;
+      break;
+    case BO_EQ:
+      Ret = L == R;
+      break;
+    case BO_NE:
+      Ret = L != R;
+      break;
+    }
+
+    return llvm::ConstantInt::get(CGM.getLLVMContext(), Ret);
+  }
+
   // Utility methods
   llvm::Type *ConvertType(QualType T) {
     return CGM.getTypes().ConvertType(T);


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D157440.548356.patch
Type: text/x-patch
Size: 1737 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/cfe-commits/attachments/20230808/93cdef71/attachment.bin>


More information about the cfe-commits mailing list