Skip to content

Conversation

xlauko
Copy link
Contributor

@xlauko xlauko commented Jul 29, 2025

This applies similar changes to #150428

@xlauko
Copy link
Contributor Author

xlauko commented Jul 29, 2025

@xlauko xlauko requested a review from erichkeane July 29, 2025 20:00
@xlauko xlauko marked this pull request as ready for review July 29, 2025 20:00
@llvmbot llvmbot added clang Clang issues not falling into any other category ClangIR Anything related to the ClangIR project labels Jul 29, 2025
@llvmbot
Copy link
Member

llvmbot commented Jul 29, 2025

@llvm/pr-subscribers-clangir

@llvm/pr-subscribers-clang

Author: Henrich Lauko (xlauko)

Changes

This applies similar changes to llvm/llvm-project#150428


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

6 Files Affected:

  • (modified) clang/lib/CIR/CodeGen/Address.h (+11)
  • (modified) clang/lib/CIR/CodeGen/CIRGenDecl.cpp (+2-2)
  • (modified) clang/lib/CIR/CodeGen/CIRGenExpr.cpp (+7-11)
  • (modified) clang/lib/CIR/CodeGen/CIRGenFunction.cpp (+1-1)
  • (modified) clang/lib/CIR/Dialect/IR/CIRDialect.cpp (+4-6)
  • (modified) clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp (+3-5)
diff --git a/clang/lib/CIR/CodeGen/Address.h b/clang/lib/CIR/CodeGen/Address.h
index 6f76c3ebb1c5e..affacaf92bf84 100644
--- a/clang/lib/CIR/CodeGen/Address.h
+++ b/clang/lib/CIR/CodeGen/Address.h
@@ -101,6 +101,17 @@ class Address {
   }
 
   clang::CharUnits getAlignment() const { return alignment; }
+
+  /// Get the operation which defines this address.
+  mlir::Operation *getDefiningOp() const {
+    if (!isValid())
+      return nullptr;
+    return getPointer().getDefiningOp();
+  }
+
+  template <typename T> T getDefiningOp() const {
+    return mlir::dyn_cast_or_null<T>(getDefiningOp());
+  }
 };
 
 } // namespace clang::CIRGen
diff --git a/clang/lib/CIR/CodeGen/CIRGenDecl.cpp b/clang/lib/CIR/CodeGen/CIRGenDecl.cpp
index a28ac3c16ce59..7a99960d9e6de 100644
--- a/clang/lib/CIR/CodeGen/CIRGenDecl.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenDecl.cpp
@@ -156,7 +156,7 @@ void CIRGenFunction::emitAutoVarInit(
     // out of it while trying to build the expression, mark it as such.
     mlir::Value val = lv.getAddress().getPointer();
     assert(val && "Should have an address");
-    auto allocaOp = dyn_cast_or_null<cir::AllocaOp>(val.getDefiningOp());
+    auto allocaOp = val.getDefiningOp<cir::AllocaOp>();
     assert(allocaOp && "Address should come straight out of the alloca");
 
     if (!allocaOp.use_empty())
@@ -410,7 +410,7 @@ void CIRGenFunction::emitStaticVarDecl(const VarDecl &d,
   // TODO(cir): we should have a way to represent global ops as values without
   // having to emit a get global op. Sometimes these emissions are not used.
   mlir::Value addr = builder.createGetGlobal(globalOp);
-  auto getAddrOp = mlir::cast<cir::GetGlobalOp>(addr.getDefiningOp());
+  auto getAddrOp = addr.getDefiningOp<cir::GetGlobalOp>();
 
   CharUnits alignment = getContext().getDeclAlign(&d);
 
diff --git a/clang/lib/CIR/CodeGen/CIRGenExpr.cpp b/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
index 3a6732394f1cb..5425d3f0a7041 100644
--- a/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
@@ -303,8 +303,7 @@ void CIRGenFunction::emitStoreOfScalar(mlir::Value value, Address addr,
 
   // Update the alloca with more info on initialization.
   assert(addr.getPointer() && "expected pointer to exist");
-  auto srcAlloca =
-      dyn_cast_or_null<cir::AllocaOp>(addr.getPointer().getDefiningOp());
+  auto srcAlloca = addr.getDefiningOp<cir::AllocaOp>();
   if (currVarDecl && srcAlloca) {
     const VarDecl *vd = currVarDecl;
     assert(vd && "VarDecl expected");
@@ -626,10 +625,8 @@ LValue CIRGenFunction::emitUnaryOpLValue(const UnaryOperator *e) {
     // Tag 'load' with deref attribute.
     // FIXME: This misses some derefence cases and has problematic interactions
     // with other operators.
-    if (auto loadOp =
-            dyn_cast<cir::LoadOp>(addr.getPointer().getDefiningOp())) {
+    if (auto loadOp = addr.getDefiningOp<cir::LoadOp>())
       loadOp.setIsDerefAttr(mlir::UnitAttr::get(&getMLIRContext()));
-    }
 
     LValue lv = makeAddrLValue(addr, t, baseInfo);
     assert(!cir::MissingFeatures::addressSpace());
@@ -1812,9 +1809,9 @@ cir::AllocaOp CIRGenFunction::createTempAlloca(mlir::Type ty,
                                                const Twine &name,
                                                mlir::Value arraySize,
                                                bool insertIntoFnEntryBlock) {
-  return cast<cir::AllocaOp>(emitAlloca(name.str(), ty, loc, CharUnits(),
-                                        insertIntoFnEntryBlock, arraySize)
-                                 .getDefiningOp());
+  return emitAlloca(name.str(), ty, loc, CharUnits(), insertIntoFnEntryBlock,
+                    arraySize)
+      .getDefiningOp<cir::AllocaOp>();
 }
 
 /// This creates an alloca and inserts it into the provided insertion point
@@ -1824,9 +1821,8 @@ cir::AllocaOp CIRGenFunction::createTempAlloca(mlir::Type ty,
                                                mlir::OpBuilder::InsertPoint ip,
                                                mlir::Value arraySize) {
   assert(ip.isSet() && "Insertion point is not set");
-  return cast<cir::AllocaOp>(
-      emitAlloca(name.str(), ty, loc, CharUnits(), ip, arraySize)
-          .getDefiningOp());
+  return emitAlloca(name.str(), ty, loc, CharUnits(), ip, arraySize)
+      .getDefiningOp<cir::AllocaOp>();
 }
 
 /// Try to emit a reference to the given value without producing it as
diff --git a/clang/lib/CIR/CodeGen/CIRGenFunction.cpp b/clang/lib/CIR/CodeGen/CIRGenFunction.cpp
index c65d0254bf8e6..a888e5e8b35ea 100644
--- a/clang/lib/CIR/CodeGen/CIRGenFunction.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenFunction.cpp
@@ -220,7 +220,7 @@ void CIRGenFunction::declare(mlir::Value addrVal, const Decl *var, QualType ty,
   assert(namedVar && "Needs a named decl");
   assert(!cir::MissingFeatures::cgfSymbolTable());
 
-  auto allocaOp = cast<cir::AllocaOp>(addrVal.getDefiningOp());
+  auto allocaOp = addrVal.getDefiningOp<cir::AllocaOp>();
   if (isParam)
     allocaOp.setInitAttr(mlir::UnitAttr::get(&getMLIRContext()));
   if (ty->isReferenceType() || ty.isConstQualified())
diff --git a/clang/lib/CIR/Dialect/IR/CIRDialect.cpp b/clang/lib/CIR/Dialect/IR/CIRDialect.cpp
index 6cde1fc2d300e..a6c7ad91ad076 100644
--- a/clang/lib/CIR/Dialect/IR/CIRDialect.cpp
+++ b/clang/lib/CIR/Dialect/IR/CIRDialect.cpp
@@ -606,7 +606,7 @@ static Value tryFoldCastChain(cir::CastOp op) {
     if (!isIntOrBoolCast(op))
       break;
     head = op;
-    op = dyn_cast_or_null<cir::CastOp>(head.getSrc().getDefiningOp());
+    op = head.getSrc().getDefiningOp<cir::CastOp>();
   }
 
   if (head == tail)
@@ -1795,7 +1795,7 @@ OpFoldResult cir::UnaryOp::fold(FoldAdaptor adaptor) {
   }
 
   if (isBoolNot(*this))
-    if (auto previous = dyn_cast_or_null<UnaryOp>(getInput().getDefiningOp()))
+    if (auto previous = getInput().getDefiningOp<cir::UnaryOp>())
       if (isBoolNot(previous))
         return previous.getInput();
 
@@ -2177,8 +2177,7 @@ LogicalResult cir::ComplexRealOp::verify() {
 }
 
 OpFoldResult cir::ComplexRealOp::fold(FoldAdaptor adaptor) {
-  if (auto complexCreateOp =
-          dyn_cast_or_null<cir::ComplexCreateOp>(getOperand().getDefiningOp()))
+  if (auto complexCreateOp = getOperand().getDefiningOp<cir::ComplexCreateOp>())
     return complexCreateOp.getOperand(0);
 
   auto complex =
@@ -2199,8 +2198,7 @@ LogicalResult cir::ComplexImagOp::verify() {
 }
 
 OpFoldResult cir::ComplexImagOp::fold(FoldAdaptor adaptor) {
-  if (auto complexCreateOp =
-          dyn_cast_or_null<cir::ComplexCreateOp>(getOperand().getDefiningOp()))
+  if (auto complexCreateOp = getOperand().getDefiningOp<cir::ComplexCreateOp>())
     return complexCreateOp.getOperand(1);
 
   auto complex =
diff --git a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
index b15205f95bc95..acc4a8a7de2cf 100644
--- a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
+++ b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
@@ -821,8 +821,7 @@ mlir::LogicalResult CIRToLLVMPtrStrideOpLowering::matchAndRewrite(
     // before it. To achieve that, look at unary minus, which already got
     // lowered to "sub 0, x".
     const auto sub = dyn_cast<mlir::LLVM::SubOp>(indexOp);
-    auto unary = dyn_cast_if_present<cir::UnaryOp>(
-        ptrStrideOp.getStride().getDefiningOp());
+    auto unary = ptrStrideOp.getStride().getDefiningOp<cir::UnaryOp>();
     bool rewriteSub =
         unary && unary.getKind() == cir::UnaryOpKind::Minus && sub;
     if (rewriteSub)
@@ -2317,15 +2316,14 @@ mlir::LogicalResult CIRToLLVMVecSplatOpLowering::matchAndRewrite(
   mlir::Value poison = rewriter.create<mlir::LLVM::PoisonOp>(loc, llvmTy);
 
   mlir::Value elementValue = adaptor.getValue();
-  if (mlir::isa<mlir::LLVM::PoisonOp>(elementValue.getDefiningOp())) {
+  if (elementValue.getDefiningOp<mlir::LLVM::PoisonOp>()) {
     // If the splat value is poison, then we can just use poison value
     // for the entire vector.
     rewriter.replaceOp(op, poison);
     return mlir::success();
   }
 
-  if (auto constValue =
-          dyn_cast<mlir::LLVM::ConstantOp>(elementValue.getDefiningOp())) {
+  if (auto constValue = elementValue.getDefiningOp<mlir::LLVM::ConstantOp>()) {
     if (auto intAttr = dyn_cast<mlir::IntegerAttr>(constValue.getValue())) {
       mlir::DenseIntElementsAttr denseVec = mlir::DenseIntElementsAttr::get(
           mlir::cast<mlir::ShapedType>(llvmTy), intAttr.getValue());

Copy link
Contributor

@andykaylor andykaylor left a comment

Choose a reason for hiding this comment

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

This looks good, but there are several places where the old code was using mlir::cast, which asserts if the type isn't what was expected, whereas the new code will silently return a null pointer. I definitely like the new form better, but we should probably use explicit asserts where we're assuming the result will be non-null.

@xlauko xlauko force-pushed the users/xlauko/cir-typed-get-defining-ops branch from dc74a82 to 66cd1e9 Compare August 1, 2025 14:57
@xlauko xlauko force-pushed the users/xlauko/cir-constant-op-accesses branch from f149cb8 to 1770a46 Compare August 1, 2025 14:58
@xlauko xlauko force-pushed the users/xlauko/cir-typed-get-defining-ops branch from 66cd1e9 to 1c9856c Compare August 1, 2025 14:58
@xlauko xlauko force-pushed the users/xlauko/cir-constant-op-accesses branch from 1770a46 to fddf527 Compare August 1, 2025 17:18
@xlauko xlauko force-pushed the users/xlauko/cir-typed-get-defining-ops branch from 1c9856c to 2cb065a Compare August 1, 2025 17:18
@xlauko xlauko force-pushed the users/xlauko/cir-constant-op-accesses branch from fddf527 to cce12ad Compare August 1, 2025 17:42
@xlauko xlauko force-pushed the users/xlauko/cir-typed-get-defining-ops branch from 2cb065a to bc5b477 Compare August 1, 2025 17:42
@xlauko xlauko force-pushed the users/xlauko/cir-constant-op-accesses branch from cce12ad to 3f27255 Compare August 1, 2025 17:43
@xlauko xlauko force-pushed the users/xlauko/cir-typed-get-defining-ops branch from bc5b477 to 2128e98 Compare August 1, 2025 17:43
@xlauko xlauko force-pushed the users/xlauko/cir-constant-op-accesses branch 5 times, most recently from 05b0240 to 88e5e8b Compare August 1, 2025 18:40
Base automatically changed from users/xlauko/cir-constant-op-accesses to main August 1, 2025 19:04
@graphite-app
Copy link

graphite-app bot commented Aug 1, 2025

Merge activity

  • Aug 1, 7:09 PM UTC: This pull request can not be added to the Graphite merge queue. Please try rebasing and resubmitting to merge when ready.
  • Aug 1, 7:09 PM UTC: Graphite disabled "merge when ready" on this PR due to: a merge conflict with the target branch; resolve the conflict and try again..
  • Aug 2, 6:59 AM UTC: Graphite rebased this pull request as part of a merge.
  • Aug 2, 7:21 AM UTC: @xlauko merged this pull request with Graphite.

@xlauko xlauko force-pushed the users/xlauko/cir-typed-get-defining-ops branch from 2128e98 to 4d76a80 Compare August 2, 2025 06:31
@xlauko xlauko force-pushed the users/xlauko/cir-typed-get-defining-ops branch from 4d76a80 to 320cabc Compare August 2, 2025 06:58
@xlauko xlauko merged commit 44500ae into main Aug 2, 2025
9 checks passed
@xlauko xlauko deleted the users/xlauko/cir-typed-get-defining-ops branch August 2, 2025 07:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

clang Clang issues not falling into any other category ClangIR Anything related to the ClangIR project

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants