[clang] [mlir] [mlir][llvm] Add tbaa_struct field attrs to the LLVM dialect (PR #238991)

Bruno Cardoso Lopes via cfe-commits cfe-commits at lists.llvm.org
Fri Nov 6 10:51:14 PST 2026


https://github.com/bcardosolopes updated https://github.com/llvm/llvm-project/pull/238991

>From 785184172a3f45bbc9125ddf4fb3b576fd93506b Mon Sep 17 00:00:00 2001
From: Bruno Cardoso Lopes <bruno.cardoso at gmail.com>
Date: Fri, 16 Oct 2026 15:55:13 -0700
Subject: [PATCH 01/11] [mlir][llvm] Add tbaa_struct field attrs to the LLVM
 dialect

The LLVM dialect models `!tbaa` access tags but has no representation for
`!tbaa.struct`, so aggregate copies with struct TBAA lose that metadata in
both directions: export drops it, import warns unhandled metadata.

This adds the missing piece:
- LLVMAttrDefs.td: new TBAAStructField attr (offset, size, tag triple)
  plus the TBAAStructFieldArray array, following the existing TBAA attrs.
- LLVMIntrinsicOps.td: optional tbaa_struct on memcpy, memmove, and
  memcpy.inline, with the export hook factored through a shared
  setTBAAStructMetadataCode fragment in LLVMOpBase.td.
- ModuleTranslation: emit the flat (offset, size, tag) node, and walk
  tbaa_struct tags in createTBAAMetadata since they are reachable from
  nowhere else (without the walk the exported node has null tags).
- Import: convert `!tbaa.struct` back to the attribute, with the tags
  pre-walked in convertMetadata; nodes that cannot be modeled (wide
  offsets, non-copy carriers) are declined with a warning.
- InlinerInterfaceImpl: pass the new optional argument at the one
  full-argument MemcpyOp::create call site.

Tests: tbaa-struct-metadata.mlir (export, mirror of the import test) and
Import/metadata-tbaa-struct.ll (import, tags pinned to their type
descriptors), plus two decline-path cases in Import/import-failure.ll.

The importer declines nodes it cannot model (null tags, empty nodes)
rather than representing them; MLIR-side verification of LLVM's
non-decreasing-offset rule is left for later.

Assisted-by: Muse Code (Muse).
---
 .../mlir/Dialect/LLVMIR/LLVMAttrDefs.td       | 37 +++++++++++++
 .../mlir/Dialect/LLVMIR/LLVMIntrinsicOps.td   | 22 +++++++-
 .../include/mlir/Dialect/LLVMIR/LLVMOpBase.td |  3 ++
 .../mlir/Target/LLVMIR/ModuleTranslation.h    |  4 ++
 .../Transforms/InlinerInterfaceImpl.cpp       |  1 +
 .../LLVMIR/LLVMIRToLLVMTranslation.cpp        | 52 +++++++++++++++++++
 mlir/lib/Target/LLVMIR/ModuleImport.cpp       | 11 ++++
 mlir/lib/Target/LLVMIR/ModuleTranslation.cpp  | 38 ++++++++++++++
 .../Target/LLVMIR/Import/import-failure.ll    | 35 +++++++++++++
 .../LLVMIR/Import/metadata-tbaa-struct.ll     | 40 ++++++++++++++
 .../Target/LLVMIR/tbaa-struct-metadata.mlir   | 34 ++++++++++++
 11 files changed, 275 insertions(+), 2 deletions(-)
 create mode 100644 mlir/test/Target/LLVMIR/Import/metadata-tbaa-struct.ll
 create mode 100644 mlir/test/Target/LLVMIR/tbaa-struct-metadata.mlir

diff --git a/mlir/include/mlir/Dialect/LLVMIR/LLVMAttrDefs.td b/mlir/include/mlir/Dialect/LLVMIR/LLVMAttrDefs.td
index 2dcc73dc38bfa1..2a4337ed107fc0 100644
--- a/mlir/include/mlir/Dialect/LLVMIR/LLVMAttrDefs.td
+++ b/mlir/include/mlir/Dialect/LLVMIR/LLVMAttrDefs.td
@@ -1385,6 +1385,43 @@ def LLVM_TBAATagArrayAttr
   let constBuilderCall = ?;
 }
 
+//===----------------------------------------------------------------------===//
+// TBAAStructFieldAttr
+//===----------------------------------------------------------------------===//
+
+def LLVM_TBAAStructFieldAttr
+    : LLVM_Attr<"TBAAStructField", "tbaa_struct_field"> {
+  let parameters = (ins
+    "int64_t":$offset,
+    "int64_t":$size,
+    "TBAATagAttr":$tag
+  );
+
+  let summary = "One field of an LLVM dialect tbaa.struct description";
+
+  let description = [{
+    One entry of a `!tbaa.struct` node, which describes the fields an aggregate
+    copy touches so that the copy is not treated as one opaque access. The
+    fields need not be contiguous: a gap is padding, which carries no data.
+
+    Example:
+    ```mlir
+    #field = #llvm.tbaa_struct_field<offset = 0, size = 4, tag = #tbaa_tag>
+    ```
+  }];
+
+  let assemblyFormat = "`<` struct(params) `>`";
+
+  // Generate mnemonic alias for the attribute.
+  let genMnemonicAlias = 1;
+}
+
+def LLVM_TBAAStructFieldArrayAttr
+    : TypedArrayAttrBase<LLVM_TBAAStructFieldAttr,
+                         LLVM_TBAAStructFieldAttr.summary # " array"> {
+  let constBuilderCall = ?;
+}
+
 //===----------------------------------------------------------------------===//
 // MMRATagAttr
 //===----------------------------------------------------------------------===//
diff --git a/mlir/include/mlir/Dialect/LLVMIR/LLVMIntrinsicOps.td b/mlir/include/mlir/Dialect/LLVMIR/LLVMIntrinsicOps.td
index 3695fcf52ebe14..5b418d2529e953 100644
--- a/mlir/include/mlir/Dialect/LLVMIR/LLVMIntrinsicOps.td
+++ b/mlir/include/mlir/Dialect/LLVMIR/LLVMIntrinsicOps.td
@@ -265,7 +265,10 @@ class LLVM_MemcpyIntrOpBase<string name> :
     /*immArgPositions=*/[3], /*immArgAttrNames=*/["isVolatile"]> {
   dag args = (ins Arg<LLVM_AnyPointer,"",[MemWrite]>:$dst,
                   Arg<LLVM_AnyPointer,"",[MemRead]>:$src,
-                  AnySignlessInteger:$len, I1Attr:$isVolatile);
+                  AnySignlessInteger:$len, I1Attr:$isVolatile,
+                  // `!tbaa.struct`: which fields of the aggregate the copy
+                  // touches, so it is not treated as one opaque access.
+                  OptionalAttr<LLVM_TBAAStructFieldArrayAttr>:$tbaa_struct);
   // Append the arguments defined by LLVM_IntrOpBase.
   let arguments = !con(args, baseArgs);
   let builders = [
@@ -277,11 +280,19 @@ class LLVM_MemcpyIntrOpBase<string name> :
     OpBuilder<(ins "Value":$dst, "Value":$src, "Value":$len,
                    "IntegerAttr":$isVolatile), [{
       build($_builder, $_state, dst, src, len, isVolatile,
+            /*tbaa_struct=*/nullptr,
             /*access_groups=*/nullptr, /*alias_scopes=*/nullptr,
             /*noalias_scopes=*/nullptr, /*tbaa=*/nullptr,
             /*arg_attrs=*/nullptr, /*res_attrs=*/nullptr);
     }]>
   ];
+
+  // The generated builder writes the alias metadata; tbaa.struct is specific to
+  // the aggregate-copy intrinsics, so it is appended here rather than in the
+  // shared alias code, which also covers loads and stores.
+  let llvmBuilder = baseLlvmBuilder # setAccessGroupsMetadataCode
+      # setAliasAnalysisMetadataCode # setTBAAStructMetadataCode
+      # baseLlvmBuilderArgAndResultAttrs # baseLlvmBuilderCoda;
 }
 
 def LLVM_MemcpyOp : LLVM_MemcpyIntrOpBase<"memcpy">;
@@ -297,7 +308,8 @@ def LLVM_MemcpyInlineOp :
     /*immArgPositions=*/[2, 3], /*immArgAttrNames=*/["len", "isVolatile"]> {
   dag args = (ins Arg<LLVM_AnyPointer,"",[MemWrite]>:$dst,
                   Arg<LLVM_AnyPointer,"",[MemRead]>:$src,
-                  APIntAttr:$len, I1Attr:$isVolatile);
+                  APIntAttr:$len, I1Attr:$isVolatile,
+                  OptionalAttr<LLVM_TBAAStructFieldArrayAttr>:$tbaa_struct);
   // Append the arguments defined by LLVM_IntrOpBase.
   let arguments = !con(args, baseArgs);
   let builders = [
@@ -309,11 +321,17 @@ def LLVM_MemcpyInlineOp :
     OpBuilder<(ins "Value":$dst, "Value":$src, "IntegerAttr":$len,
                    "IntegerAttr":$isVolatile), [{
       build($_builder, $_state, dst, src, len, isVolatile,
+            /*tbaa_struct=*/nullptr,
             /*access_groups=*/nullptr, /*alias_scopes=*/nullptr,
             /*noalias_scopes=*/nullptr, /*tbaa=*/nullptr,
             /*arg_attrs=*/nullptr, /*res_attrs=*/nullptr);
     }]>
   ];
+
+  // Same as the memcpy base: tbaa.struct is specific to the aggregate copies.
+  let llvmBuilder = baseLlvmBuilder # setAccessGroupsMetadataCode
+      # setAliasAnalysisMetadataCode # setTBAAStructMetadataCode
+      # baseLlvmBuilderArgAndResultAttrs # baseLlvmBuilderCoda;
 }
 
 def LLVM_MemsetOp : LLVM_ZeroResultIntrOp<"memset", [0, 2],
diff --git a/mlir/include/mlir/Dialect/LLVMIR/LLVMOpBase.td b/mlir/include/mlir/Dialect/LLVMIR/LLVMOpBase.td
index d0506f971b2c2a..66583a592b3f64 100644
--- a/mlir/include/mlir/Dialect/LLVMIR/LLVMOpBase.td
+++ b/mlir/include/mlir/Dialect/LLVMIR/LLVMOpBase.td
@@ -260,6 +260,9 @@ class LLVM_MemOpPatterns {
     moduleTranslation.setAliasScopeMetadata(op, inst);
     moduleTranslation.setTBAAMetadata(op, inst);
   }];
+  code setTBAAStructMetadataCode = [{
+    moduleTranslation.setTBAAStructMetadata(op.getTbaaStructAttr(), inst);
+  }];
 }
 
 //===----------------------------------------------------------------------===//
diff --git a/mlir/include/mlir/Target/LLVMIR/ModuleTranslation.h b/mlir/include/mlir/Target/LLVMIR/ModuleTranslation.h
index 323b44f7ddfa12..528775d8edc1cf 100644
--- a/mlir/include/mlir/Target/LLVMIR/ModuleTranslation.h
+++ b/mlir/include/mlir/Target/LLVMIR/ModuleTranslation.h
@@ -198,6 +198,10 @@ class ModuleTranslation {
   /// Sets LLVM TBAA metadata for memory operations that have TBAA attributes.
   void setTBAAMetadata(AliasAnalysisOpInterface op, llvm::Instruction *inst);
 
+  /// Sets LLVM tbaa.struct metadata on an aggregate copy, describing which
+  /// fields of the aggregate the copy touches.
+  void setTBAAStructMetadata(ArrayAttr fields, llvm::Instruction *inst);
+
   /// Sets LLVM dereferenceable metadata for operations that have
   /// dereferenceable attributes.
   void setDereferenceableMetadata(DereferenceableOpInterface op,
diff --git a/mlir/lib/Dialect/LLVMIR/Transforms/InlinerInterfaceImpl.cpp b/mlir/lib/Dialect/LLVMIR/Transforms/InlinerInterfaceImpl.cpp
index a57e0e37098755..e4d91d347e8c6b 100644
--- a/mlir/lib/Dialect/LLVMIR/Transforms/InlinerInterfaceImpl.cpp
+++ b/mlir/lib/Dialect/LLVMIR/Transforms/InlinerInterfaceImpl.cpp
@@ -716,6 +716,7 @@ static Value handleByValArgumentInit(OpBuilder &builder, Location loc,
       builder.getArrayAttr({builder.getDictionaryAttr({dstAlignAttr})});
   LLVM::MemcpyOp::create(builder, loc, allocaOp, argument, copySize,
                          /*isVolatile=*/false,
+                         /*tbaa_struct=*/nullptr,
                          /*access_groups=*/nullptr, /*alias_scopes=*/nullptr,
                          /*noalias_scopes=*/nullptr, /*tbaa=*/nullptr, argAttrs,
                          /*res_attrs=*/nullptr);
diff --git a/mlir/lib/Target/LLVMIR/Dialect/LLVMIR/LLVMIRToLLVMTranslation.cpp b/mlir/lib/Target/LLVMIR/Dialect/LLVMIR/LLVMIRToLLVMTranslation.cpp
index ae75a7690163a8..63d32e7a04bd1d 100644
--- a/mlir/lib/Target/LLVMIR/Dialect/LLVMIR/LLVMIRToLLVMTranslation.cpp
+++ b/mlir/lib/Target/LLVMIR/Dialect/LLVMIR/LLVMIRToLLVMTranslation.cpp
@@ -97,6 +97,7 @@ getSupportedMetadataImpl(llvm::LLVMContext &llvmContext) {
       llvm::LLVMContext::MD_mmra,
       llvm::LLVMContext::MD_memprof,
       llvm::LLVMContext::MD_callsite,
+      llvm::LLVMContext::MD_tbaa_struct,
       llvmContext.getMDKindID(vecTypeHintMDName),
       llvmContext.getMDKindID(workGroupSizeHintMDName),
       llvmContext.getMDKindID(reqdWorkGroupSizeMDName),
@@ -214,6 +215,55 @@ static LogicalResult setTBAAAttr(const llvm::MDNode *node, Operation *op,
   return success();
 }
 
+/// Converts `!tbaa.struct` to the `tbaa_struct` attribute on the imported
+/// aggregate copy. The node is a flat list of (offset, size, tag) triples: it
+/// says which fields of the aggregate the copy actually touches, so the copy is
+/// not treated as one opaque access and the gaps are known to be padding.
+static LogicalResult setTBAAStructAttr(OpBuilder &builder,
+                                       const llvm::MDNode *node, Operation *op,
+                                       LLVM::ModuleImport &moduleImport) {
+  if (!isa<LLVM::MemcpyOp, LLVM::MemcpyInlineOp, LLVM::MemmoveOp>(op))
+    return failure();
+
+  // Operands come in conceptual groups of three; anything else is malformed.
+  if (node->getNumOperands() == 0 || node->getNumOperands() % 3 != 0)
+    return failure();
+
+  SmallVector<Attribute> fields;
+  fields.reserve(node->getNumOperands() / 3);
+  for (unsigned i = 0, e = node->getNumOperands(); i != e; i += 3) {
+    auto *offset = llvm::mdconst::dyn_extract_or_null<llvm::ConstantInt>(
+        node->getOperand(i));
+    auto *size = llvm::mdconst::dyn_extract_or_null<llvm::ConstantInt>(
+        node->getOperand(i + 1));
+    if (!offset || !size)
+      return failure();
+    // Offsets and sizes are int64 in the attribute; wider constants cannot be
+    // represented, and extracting them would assert.
+    std::optional<int64_t> offsetValue = offset->getValue().trySExtValue();
+    std::optional<int64_t> sizeValue = size->getValue().trySExtValue();
+    if (!offsetValue || !sizeValue)
+      return failure();
+    auto *tagNode = dyn_cast_if_present<llvm::MDNode>(node->getOperand(i + 2));
+    if (!tagNode)
+      return failure();
+    auto tag =
+        dyn_cast_if_present<TBAATagAttr>(moduleImport.lookupTBAAAttr(tagNode));
+    if (!tag)
+      return failure();
+    fields.push_back(
+        builder.getAttr<TBAAStructFieldAttr>(*offsetValue, *sizeValue, tag));
+  }
+
+  return TypeSwitch<Operation *, LogicalResult>(op)
+      .Case<LLVM::MemcpyOp, LLVM::MemcpyInlineOp, LLVM::MemmoveOp>(
+          [&](auto copyOp) {
+            copyOp.setTbaaStructAttr(builder.getArrayAttr(fields));
+            return success();
+          })
+      .Default([](auto) { return failure(); });
+}
+
 /// Looks up all the access group attributes that map to the access group nodes
 /// starting from the access group metadata `node`, and attaches all of them to
 /// the imported operation if the lookups succeed. Returns failure otherwise.
@@ -604,6 +654,8 @@ class LLVMDialectLLVMIRImportInterface : public LLVMImportDialectInterface {
       return setMemProfAttr(builder, node, op);
     if (kind == llvm::LLVMContext::MD_callsite)
       return setCallsiteAttr(builder, node, op);
+    if (kind == llvm::LLVMContext::MD_tbaa_struct)
+      return setTBAAStructAttr(builder, node, op, moduleImport);
     llvm::LLVMContext &context = node->getContext();
     if (kind == context.getMDKindID(vecTypeHintMDName))
       return setVecTypeHintAttr(builder, node, op, moduleImport);
diff --git a/mlir/lib/Target/LLVMIR/ModuleImport.cpp b/mlir/lib/Target/LLVMIR/ModuleImport.cpp
index 0223c1e3343c7f..051b67cbf3f797 100644
--- a/mlir/lib/Target/LLVMIR/ModuleImport.cpp
+++ b/mlir/lib/Target/LLVMIR/ModuleImport.cpp
@@ -1170,6 +1170,17 @@ LogicalResult ModuleImport::convertMetadata() {
       if (aliasAnalysisNodes.TBAA)
         if (failed(processTBAAMetadata(aliasAnalysisNodes.TBAA)))
           return failure();
+      // A `!tbaa.struct` node reaches its own tags, and those tags may appear
+      // nowhere else in the module. Without walking them here the lookup in
+      // setTBAAStructAttr finds nothing and the node is declined.
+      if (aliasAnalysisNodes.TBAAStruct) {
+        const llvm::MDNode *structNode = aliasAnalysisNodes.TBAAStruct;
+        for (unsigned i = 2, e = structNode->getNumOperands(); i < e; i += 3)
+          if (auto *tag =
+                  dyn_cast_if_present<llvm::MDNode>(structNode->getOperand(i)))
+            if (failed(processTBAAMetadata(tag)))
+              return failure();
+      }
       if (aliasAnalysisNodes.Scope)
         if (failed(processAliasScopeMetadata(aliasAnalysisNodes.Scope)))
           return failure();
diff --git a/mlir/lib/Target/LLVMIR/ModuleTranslation.cpp b/mlir/lib/Target/LLVMIR/ModuleTranslation.cpp
index 41ead15f4ecb0d..1428ce906860de 100644
--- a/mlir/lib/Target/LLVMIR/ModuleTranslation.cpp
+++ b/mlir/lib/Target/LLVMIR/ModuleTranslation.cpp
@@ -2418,6 +2418,29 @@ void ModuleTranslation::setTBAAMetadata(AliasAnalysisOpInterface op,
   inst->setMetadata(llvm::LLVMContext::MD_tbaa, node);
 }
 
+void ModuleTranslation::setTBAAStructMetadata(ArrayAttr fields,
+                                              llvm::Instruction *inst) {
+  if (!fields || fields.empty())
+    return;
+
+  // The node is a flat list of (offset, size, tag) triples, not a list of
+  // per-field nodes.
+  llvm::LLVMContext &ctx = getLLVMContext();
+  llvm::Type *i64 = llvm::Type::getInt64Ty(ctx);
+  SmallVector<llvm::Metadata *> operands;
+  operands.reserve(fields.size() * 3);
+  for (Attribute field : fields) {
+    auto fieldAttr = cast<TBAAStructFieldAttr>(field);
+    operands.push_back(llvm::ConstantAsMetadata::get(
+        llvm::ConstantInt::getSigned(i64, fieldAttr.getOffset())));
+    operands.push_back(llvm::ConstantAsMetadata::get(
+        llvm::ConstantInt::getSigned(i64, fieldAttr.getSize())));
+    operands.push_back(getTBAANode(fieldAttr.getTag()));
+  }
+  inst->setMetadata(llvm::LLVMContext::MD_tbaa_struct,
+                    llvm::MDNode::get(ctx, operands));
+}
+
 void ModuleTranslation::setDereferenceableMetadata(
     DereferenceableOpInterface op, llvm::Instruction *inst) {
   DereferenceableAttr derefAttr = op.getDereferenceableOrNull();
@@ -2506,6 +2529,21 @@ LogicalResult ModuleTranslation::createTBAAMetadata() {
       walker.walk(attr);
   });
 
+  // The tags inside a `tbaa_struct` are reachable from nowhere else, so without
+  // this walk they never get an MDNode and the exported node has null tags.
+  auto walkStructFields = [&](ArrayAttr fields) {
+    if (fields)
+      walker.walk(fields);
+  };
+  mlirModule->walk([&](Operation *op) {
+    if (auto copyOp = dyn_cast<LLVM::MemcpyOp>(op))
+      walkStructFields(copyOp.getTbaaStructAttr());
+    else if (auto copyOp = dyn_cast<LLVM::MemcpyInlineOp>(op))
+      walkStructFields(copyOp.getTbaaStructAttr());
+    else if (auto copyOp = dyn_cast<LLVM::MemmoveOp>(op))
+      walkStructFields(copyOp.getTbaaStructAttr());
+  });
+
   return success();
 }
 
diff --git a/mlir/test/Target/LLVMIR/Import/import-failure.ll b/mlir/test/Target/LLVMIR/Import/import-failure.ll
index 083ea8b6ce81bf..a7f187b0a8c3d3 100644
--- a/mlir/test/Target/LLVMIR/Import/import-failure.ll
+++ b/mlir/test/Target/LLVMIR/Import/import-failure.ll
@@ -660,3 +660,38 @@ define ptr @wide_callsite_id() {
 declare ptr @alloc(i64)
 
 !0 = !{i128 1}
+; // -----
+
+; Only aggregate copies carry tbaa_struct; on any other instruction the node is
+; declined, and the import keeps going.
+; CHECK:      <unknown>
+; CHECK-SAME: warning: unhandled metadata: ![[ST:[0-9]+]] = !{i64 0, i64 4, ![[TAG:[0-9]+]]}
+define i32 @tbaa_struct_on_load(ptr %p) {
+  %v = load i32, ptr %p, !tbaa.struct !7
+  ret i32 %v
+}
+
+!5 = !{!"Simple C++ TBAA"}
+!0 = !{!"omnipotent char", !5, i64 0}
+!1 = !{!"int", !0, i64 0}
+!2 = !{!1, !1, i64 0}
+!7 = !{i64 0, i64 4, !2}
+
+; // -----
+
+; Offsets and sizes are int64 in the attribute; a wider constant cannot be
+; represented, so the node is declined instead of crashing.
+; CHECK:      <unknown>
+; CHECK-SAME: warning: unhandled metadata: ![[ST:[0-9]+]] = !{i128 18446744073709551616, i64 4, ![[TAG:[0-9]+]]}
+declare void @llvm.memcpy.p0.p0.i64(ptr, ptr, i64, i1)
+
+define void @tbaa_struct_wide_offset(ptr %d, ptr %s) {
+  call void @llvm.memcpy.p0.p0.i64(ptr %d, ptr %s, i64 12, i1 false), !tbaa.struct !8
+  ret void
+}
+
+!5 = !{!"Simple C++ TBAA"}
+!0 = !{!"omnipotent char", !5, i64 0}
+!1 = !{!"int", !0, i64 0}
+!2 = !{!1, !1, i64 0}
+!8 = !{i128 18446744073709551616, i64 4, !2}
diff --git a/mlir/test/Target/LLVMIR/Import/metadata-tbaa-struct.ll b/mlir/test/Target/LLVMIR/Import/metadata-tbaa-struct.ll
new file mode 100644
index 00000000000000..728168dbcc128f
--- /dev/null
+++ b/mlir/test/Target/LLVMIR/Import/metadata-tbaa-struct.ll
@@ -0,0 +1,40 @@
+; RUN: mlir-translate -import-llvm -emit-expensive-warnings %s 2>&1 | FileCheck %s
+
+; !tbaa.struct describes which fields of an aggregate a copy touches, so the
+; copy is not treated as one opaque access and the gaps are known to be padding.
+; The node is a flat list of (offset, size, tag) triples.
+
+; CHECK-NOT: warning
+
+declare void @llvm.memcpy.p0.p0.i64(ptr, ptr, i64, i1)
+declare void @llvm.memmove.p0.p0.i64(ptr, ptr, i64, i1)
+declare void @llvm.memcpy.inline.p0.p0.i64(ptr, ptr, i64, i1)
+
+; The two fields start eight bytes apart with a four byte hole between them;
+; that hole is padding the copy need not preserve.
+; CHECK-DAG: #[[INT:.*]] = #llvm.tbaa_type_desc<id = "int"
+; CHECK-DAG: #[[FLT:.*]] = #llvm.tbaa_type_desc<id = "float"
+; CHECK-DAG: #[[TI:.*]] = #llvm.tbaa_tag<base_type = #[[INT]], access_type = #[[INT]], offset = 0>
+; CHECK-DAG: #[[TF:.*]] = #llvm.tbaa_tag<base_type = #[[FLT]], access_type = #[[FLT]], offset = 0>
+; CHECK-DAG: #[[F0:.*]] = #llvm.tbaa_struct_field<offset = 0, size = 4, tag = #[[TI]]>
+; CHECK-DAG: #[[F1:.*]] = #llvm.tbaa_struct_field<offset = 8, size = 4, tag = #[[TF]]>
+; CHECK: llvm.intr.memcpy
+; CHECK-SAME: tbaa_struct = [#[[F0]], #[[F1]]]
+; CHECK: llvm.intr.memmove
+; CHECK-SAME: tbaa_struct = [#[[F0]], #[[F1]]]
+; CHECK: llvm.intr.memcpy.inline
+; CHECK-SAME: tbaa_struct = [#[[F0]], #[[F1]]]
+define void @cp(ptr %d, ptr %s) {
+  call void @llvm.memcpy.p0.p0.i64(ptr %d, ptr %s, i64 12, i1 false), !tbaa.struct !4
+  call void @llvm.memmove.p0.p0.i64(ptr %d, ptr %s, i64 12, i1 false), !tbaa.struct !4
+  call void @llvm.memcpy.inline.p0.p0.i64(ptr %d, ptr %s, i64 12, i1 false), !tbaa.struct !4
+  ret void
+}
+
+!0 = !{!"omnipotent char", !5, i64 0}
+!5 = !{!"Simple C++ TBAA"}
+!1 = !{!"int", !0, i64 0}
+!2 = !{!"float", !0, i64 0}
+!6 = !{!1, !1, i64 0}
+!7 = !{!2, !2, i64 0}
+!4 = !{ i64 0, i64 4, !6, i64 8, i64 4, !7 }
diff --git a/mlir/test/Target/LLVMIR/tbaa-struct-metadata.mlir b/mlir/test/Target/LLVMIR/tbaa-struct-metadata.mlir
new file mode 100644
index 00000000000000..cd1c87c069529d
--- /dev/null
+++ b/mlir/test/Target/LLVMIR/tbaa-struct-metadata.mlir
@@ -0,0 +1,34 @@
+// RUN: mlir-translate -mlir-to-llvmir %s | FileCheck %s
+// RUN: mlir-opt %s --verify-roundtrip -o /dev/null
+
+// The export mirror of Import/metadata-tbaa-struct.ll. The body is exactly what
+// the importer produces, so the two pin the whole trip.
+//
+// The tags inside a tbaa_struct are reachable from nowhere else in the module,
+// so the exporter has to walk them explicitly; without that the node comes out
+// with null tags.
+
+// CHECK: call void @llvm.memcpy.p0.p0.i64(ptr %{{.*}}, ptr %{{.*}}, i64 12, i1 false), !tbaa.struct ![[S:[0-9]+]]
+// CHECK: call void @llvm.memmove.p0.p0.i64(ptr %{{.*}}, ptr %{{.*}}, i64 12, i1 false), !tbaa.struct ![[S]]
+// CHECK: call void @llvm.memcpy.inline.p0.p0.i64(ptr %{{.*}}, ptr %{{.*}}, i64 12, i1 false), !tbaa.struct ![[S]]
+// CHECK: ![[S]] = !{i64 0, i64 4, ![[T0:[0-9]+]], i64 8, i64 4, ![[T1:[0-9]+]]}
+// CHECK-DAG: ![[T0]] = !{![[INT:[0-9]+]], ![[INT]], i64 0}
+// CHECK-DAG: ![[INT]] = !{!"int", !{{[0-9]+}}, i64 0}
+// CHECK-DAG: ![[T1]] = !{![[FLT:[0-9]+]], ![[FLT]], i64 0}
+// CHECK-DAG: ![[FLT]] = !{!"float", !{{[0-9]+}}, i64 0}
+
+#tbaa_root = #llvm.tbaa_root<id = "Simple C++ TBAA">
+#tbaa_type_desc = #llvm.tbaa_type_desc<id = "omnipotent char", members = {<#tbaa_root, 0>}>
+#tbaa_type_desc1 = #llvm.tbaa_type_desc<id = "int", members = {<#tbaa_type_desc, 0>}>
+#tbaa_type_desc2 = #llvm.tbaa_type_desc<id = "float", members = {<#tbaa_type_desc, 0>}>
+#tbaa_tag = #llvm.tbaa_tag<base_type = #tbaa_type_desc1, access_type = #tbaa_type_desc1, offset = 0>
+#tbaa_tag1 = #llvm.tbaa_tag<base_type = #tbaa_type_desc2, access_type = #tbaa_type_desc2, offset = 0>
+module {
+  llvm.func @cp(%arg0: !llvm.ptr, %arg1: !llvm.ptr) {
+    %0 = llvm.mlir.constant(12 : i64) : i64
+    "llvm.intr.memcpy"(%arg0, %arg1, %0) <{isVolatile = false, tbaa_struct = [#llvm.tbaa_struct_field<offset = 0, size = 4, tag = #tbaa_tag>, #llvm.tbaa_struct_field<offset = 8, size = 4, tag = #tbaa_tag1>]}> : (!llvm.ptr, !llvm.ptr, i64) -> ()
+    "llvm.intr.memmove"(%arg0, %arg1, %0) <{isVolatile = false, tbaa_struct = [#llvm.tbaa_struct_field<offset = 0, size = 4, tag = #tbaa_tag>, #llvm.tbaa_struct_field<offset = 8, size = 4, tag = #tbaa_tag1>]}> : (!llvm.ptr, !llvm.ptr, i64) -> ()
+    "llvm.intr.memcpy.inline"(%arg0, %arg1) <{isVolatile = false, len = 12 : i64, tbaa_struct = [#llvm.tbaa_struct_field<offset = 0, size = 4, tag = #tbaa_tag>, #llvm.tbaa_struct_field<offset = 8, size = 4, tag = #tbaa_tag1>]}> : (!llvm.ptr, !llvm.ptr) -> ()
+    llvm.return
+  }
+}

>From 85f4aca78e38c240416bc2dd1d4ec97a33e1fbed Mon Sep 17 00:00:00 2001
From: Bruno Cardoso Lopes <bruno.cardoso at gmail.com>
Date: Wed, 4 Nov 2026 16:22:39 -0800
Subject: [PATCH 02/11] Address review: verify tbaa.struct field offsets are
 non-decreasing

Add verifiers to the memcpy, memmove, and memcpy.inline ops checking
that tbaa.struct field offsets are non-decreasing, matching LLVM's
verifier rule (unsigned comparison, equal offsets allowed). Read
imported offsets and sizes unsigned so narrow constants keep their
value and high-bit i64 offsets round-trip through the signed
attribute unchanged.
---
 .../mlir/Dialect/LLVMIR/LLVMIntrinsicOps.td   | 10 +++-
 mlir/lib/Dialect/LLVMIR/IR/LLVMDialect.cpp    | 30 +++++++++++
 .../LLVMIR/LLVMIRToLLVMTranslation.cpp        | 19 ++++---
 mlir/test/Dialect/LLVMIR/invalid.mlir         | 50 +++++++++++++++++++
 .../LLVMIR/Import/metadata-tbaa-struct.ll     | 36 +++++++++++++
 5 files changed, 137 insertions(+), 8 deletions(-)

diff --git a/mlir/include/mlir/Dialect/LLVMIR/LLVMIntrinsicOps.td b/mlir/include/mlir/Dialect/LLVMIR/LLVMIntrinsicOps.td
index 5b418d2529e953..35d8e6ae68ff51 100644
--- a/mlir/include/mlir/Dialect/LLVMIR/LLVMIntrinsicOps.td
+++ b/mlir/include/mlir/Dialect/LLVMIR/LLVMIntrinsicOps.td
@@ -295,8 +295,12 @@ class LLVM_MemcpyIntrOpBase<string name> :
       # baseLlvmBuilderArgAndResultAttrs # baseLlvmBuilderCoda;
 }
 
-def LLVM_MemcpyOp : LLVM_MemcpyIntrOpBase<"memcpy">;
-def LLVM_MemmoveOp : LLVM_MemcpyIntrOpBase<"memmove">;
+def LLVM_MemcpyOp : LLVM_MemcpyIntrOpBase<"memcpy"> {
+  let hasVerifier = 1;
+}
+def LLVM_MemmoveOp : LLVM_MemcpyIntrOpBase<"memmove"> {
+  let hasVerifier = 1;
+}
 
 def LLVM_MemcpyInlineOp :
     LLVM_ZeroResultIntrOp<"memcpy.inline", [0, 1, 2],
@@ -332,6 +336,8 @@ def LLVM_MemcpyInlineOp :
   let llvmBuilder = baseLlvmBuilder # setAccessGroupsMetadataCode
       # setAliasAnalysisMetadataCode # setTBAAStructMetadataCode
       # baseLlvmBuilderArgAndResultAttrs # baseLlvmBuilderCoda;
+
+  let hasVerifier = 1;
 }
 
 def LLVM_MemsetOp : LLVM_ZeroResultIntrOp<"memset", [0, 2],
diff --git a/mlir/lib/Dialect/LLVMIR/IR/LLVMDialect.cpp b/mlir/lib/Dialect/LLVMIR/IR/LLVMDialect.cpp
index ce020fd50a1aeb..414a5916eeff36 100644
--- a/mlir/lib/Dialect/LLVMIR/IR/LLVMDialect.cpp
+++ b/mlir/lib/Dialect/LLVMIR/IR/LLVMDialect.cpp
@@ -451,6 +451,36 @@ LogicalResult AllocaOp::verify() {
   return success();
 }
 
+// tbaa.struct field offsets must be non-decreasing, matching LLVM's verifier
+// rule. Compare unsigned: LLVM zero-extends the offsets before comparing.
+static LogicalResult verifyTBAAStructFieldOffsets(Operation *op,
+                                                  ArrayAttr fields) {
+  if (!fields)
+    return success();
+  std::optional<uint64_t> prevOffset;
+  for (Attribute field : fields) {
+    uint64_t offset =
+        static_cast<uint64_t>(cast<TBAAStructFieldAttr>(field).getOffset());
+    if (prevOffset && offset < *prevOffset)
+      return op->emitOpError(
+          "tbaa.struct field offsets must be non-decreasing");
+    prevOffset = offset;
+  }
+  return success();
+}
+
+LogicalResult MemcpyOp::verify() {
+  return verifyTBAAStructFieldOffsets(getOperation(), getTbaaStructAttr());
+}
+
+LogicalResult MemmoveOp::verify() {
+  return verifyTBAAStructFieldOffsets(getOperation(), getTbaaStructAttr());
+}
+
+LogicalResult MemcpyInlineOp::verify() {
+  return verifyTBAAStructFieldOffsets(getOperation(), getTbaaStructAttr());
+}
+
 LogicalResult AllocaOp::canonicalize(AllocaOp op, PatternRewriter &rewriter) {
   // Convert `alloca Ty, C` to the canonical `alloca [C x Ty], 1` form.
   APInt numElements;
diff --git a/mlir/lib/Target/LLVMIR/Dialect/LLVMIR/LLVMIRToLLVMTranslation.cpp b/mlir/lib/Target/LLVMIR/Dialect/LLVMIR/LLVMIRToLLVMTranslation.cpp
index 63d32e7a04bd1d..dfc93a544c0a27 100644
--- a/mlir/lib/Target/LLVMIR/Dialect/LLVMIR/LLVMIRToLLVMTranslation.cpp
+++ b/mlir/lib/Target/LLVMIR/Dialect/LLVMIR/LLVMIRToLLVMTranslation.cpp
@@ -238,12 +238,19 @@ static LogicalResult setTBAAStructAttr(OpBuilder &builder,
         node->getOperand(i + 1));
     if (!offset || !size)
       return failure();
-    // Offsets and sizes are int64 in the attribute; wider constants cannot be
-    // represented, and extracting them would assert.
-    std::optional<int64_t> offsetValue = offset->getValue().trySExtValue();
-    std::optional<int64_t> sizeValue = size->getValue().trySExtValue();
-    if (!offsetValue || !sizeValue)
+    // Offsets and sizes are int64 in the attribute; values that do not fit
+    // in 64 bits cannot be represented, and extracting them would assert.
+    // Read them unsigned and keep the bits: LLVM compares offsets
+    // zero-extended, so a narrow constant with its high bit set (e.g. i32
+    // 0x80000000) must keep its unsigned value rather than sign-extending,
+    // and a high-bit i64 offset must round-trip through the signed
+    // attribute unchanged.
+    std::optional<uint64_t> offsetZExt = offset->getValue().tryZExtValue();
+    std::optional<uint64_t> sizeZExt = size->getValue().tryZExtValue();
+    if (!offsetZExt || !sizeZExt)
       return failure();
+    int64_t offsetValue = static_cast<int64_t>(*offsetZExt);
+    int64_t sizeValue = static_cast<int64_t>(*sizeZExt);
     auto *tagNode = dyn_cast_if_present<llvm::MDNode>(node->getOperand(i + 2));
     if (!tagNode)
       return failure();
@@ -252,7 +259,7 @@ static LogicalResult setTBAAStructAttr(OpBuilder &builder,
     if (!tag)
       return failure();
     fields.push_back(
-        builder.getAttr<TBAAStructFieldAttr>(*offsetValue, *sizeValue, tag));
+        builder.getAttr<TBAAStructFieldAttr>(offsetValue, sizeValue, tag));
   }
 
   return TypeSwitch<Operation *, LogicalResult>(op)
diff --git a/mlir/test/Dialect/LLVMIR/invalid.mlir b/mlir/test/Dialect/LLVMIR/invalid.mlir
index 8b7ce9ef3ed72f..dfb18fa7e809ea 100644
--- a/mlir/test/Dialect/LLVMIR/invalid.mlir
+++ b/mlir/test/Dialect/LLVMIR/invalid.mlir
@@ -2639,3 +2639,53 @@ llvm.func @rocdl_asyncmark_unknown_stage() {
   rocdl.asyncmark stages = not_a_stage
   llvm.return
 }
+
+// -----
+#tbaa_root = #llvm.tbaa_root<id = "Simple C++ TBAA">
+#tbaa_type_desc = #llvm.tbaa_type_desc<id = "omnipotent char", members = {<#tbaa_root, 0>}>
+#tbaa_type_desc1 = #llvm.tbaa_type_desc<id = "int", members = {<#tbaa_type_desc, 0>}>
+#tbaa_tag = #llvm.tbaa_tag<base_type = #tbaa_type_desc1, access_type = #tbaa_type_desc1, offset = 0>
+llvm.func @tbaa_struct_equal_offsets(%arg0: !llvm.ptr, %arg1: !llvm.ptr) {
+  %0 = llvm.mlir.constant(12 : i64) : i64
+  // Equal offsets are allowed: the rule is non-decreasing, not increasing.
+  "llvm.intr.memcpy"(%arg0, %arg1, %0) <{isVolatile = false, tbaa_struct = [#llvm.tbaa_struct_field<offset = 8, size = 4, tag = #tbaa_tag>, #llvm.tbaa_struct_field<offset = 8, size = 4, tag = #tbaa_tag>]}> : (!llvm.ptr, !llvm.ptr, i64) -> ()
+  llvm.return
+}
+
+// -----
+
+#tbaa_root = #llvm.tbaa_root<id = "Simple C++ TBAA">
+#tbaa_type_desc = #llvm.tbaa_type_desc<id = "omnipotent char", members = {<#tbaa_root, 0>}>
+#tbaa_type_desc1 = #llvm.tbaa_type_desc<id = "int", members = {<#tbaa_type_desc, 0>}>
+#tbaa_tag = #llvm.tbaa_tag<base_type = #tbaa_type_desc1, access_type = #tbaa_type_desc1, offset = 0>
+llvm.func @tbaa_struct_decreasing_memcpy(%arg0: !llvm.ptr, %arg1: !llvm.ptr) {
+  %0 = llvm.mlir.constant(12 : i64) : i64
+  // expected-error at +1 {{tbaa.struct field offsets must be non-decreasing}}
+  "llvm.intr.memcpy"(%arg0, %arg1, %0) <{isVolatile = false, tbaa_struct = [#llvm.tbaa_struct_field<offset = 8, size = 4, tag = #tbaa_tag>, #llvm.tbaa_struct_field<offset = 0, size = 4, tag = #tbaa_tag>]}> : (!llvm.ptr, !llvm.ptr, i64) -> ()
+  llvm.return
+}
+
+// -----
+
+#tbaa_root = #llvm.tbaa_root<id = "Simple C++ TBAA">
+#tbaa_type_desc = #llvm.tbaa_type_desc<id = "omnipotent char", members = {<#tbaa_root, 0>}>
+#tbaa_type_desc1 = #llvm.tbaa_type_desc<id = "int", members = {<#tbaa_type_desc, 0>}>
+#tbaa_tag = #llvm.tbaa_tag<base_type = #tbaa_type_desc1, access_type = #tbaa_type_desc1, offset = 0>
+llvm.func @tbaa_struct_decreasing_memmove(%arg0: !llvm.ptr, %arg1: !llvm.ptr) {
+  %0 = llvm.mlir.constant(12 : i64) : i64
+  // expected-error at +1 {{tbaa.struct field offsets must be non-decreasing}}
+  "llvm.intr.memmove"(%arg0, %arg1, %0) <{isVolatile = false, tbaa_struct = [#llvm.tbaa_struct_field<offset = 8, size = 4, tag = #tbaa_tag>, #llvm.tbaa_struct_field<offset = 0, size = 4, tag = #tbaa_tag>]}> : (!llvm.ptr, !llvm.ptr, i64) -> ()
+  llvm.return
+}
+
+// -----
+
+#tbaa_root = #llvm.tbaa_root<id = "Simple C++ TBAA">
+#tbaa_type_desc = #llvm.tbaa_type_desc<id = "omnipotent char", members = {<#tbaa_root, 0>}>
+#tbaa_type_desc1 = #llvm.tbaa_type_desc<id = "int", members = {<#tbaa_type_desc, 0>}>
+#tbaa_tag = #llvm.tbaa_tag<base_type = #tbaa_type_desc1, access_type = #tbaa_type_desc1, offset = 0>
+llvm.func @tbaa_struct_decreasing_memcpy_inline(%arg0: !llvm.ptr, %arg1: !llvm.ptr) {
+  // expected-error at +1 {{tbaa.struct field offsets must be non-decreasing}}
+  "llvm.intr.memcpy.inline"(%arg0, %arg1) <{isVolatile = false, len = 12 : i64, tbaa_struct = [#llvm.tbaa_struct_field<offset = 8, size = 4, tag = #tbaa_tag>, #llvm.tbaa_struct_field<offset = 0, size = 4, tag = #tbaa_tag>]}> : (!llvm.ptr, !llvm.ptr) -> ()
+  llvm.return
+}
diff --git a/mlir/test/Target/LLVMIR/Import/metadata-tbaa-struct.ll b/mlir/test/Target/LLVMIR/Import/metadata-tbaa-struct.ll
index 728168dbcc128f..89a753009d1731 100644
--- a/mlir/test/Target/LLVMIR/Import/metadata-tbaa-struct.ll
+++ b/mlir/test/Target/LLVMIR/Import/metadata-tbaa-struct.ll
@@ -18,6 +18,9 @@ declare void @llvm.memcpy.inline.p0.p0.i64(ptr, ptr, i64, i1)
 ; CHECK-DAG: #[[TF:.*]] = #llvm.tbaa_tag<base_type = #[[FLT]], access_type = #[[FLT]], offset = 0>
 ; CHECK-DAG: #[[F0:.*]] = #llvm.tbaa_struct_field<offset = 0, size = 4, tag = #[[TI]]>
 ; CHECK-DAG: #[[F1:.*]] = #llvm.tbaa_struct_field<offset = 8, size = 4, tag = #[[TF]]>
+; CHECK-DAG: #[[F2:.*]] = #llvm.tbaa_struct_field<offset = 2147483648, size = 4, tag = #[[TI]]>
+; CHECK-DAG: #[[F3:.*]] = #llvm.tbaa_struct_field<offset = -1, size = 4, tag = #[[TI]]>
+; CHECK-DAG: #[[F4:.*]] = #llvm.tbaa_struct_field<offset = 0, size = 2147483648, tag = #[[TI]]>
 ; CHECK: llvm.intr.memcpy
 ; CHECK-SAME: tbaa_struct = [#[[F0]], #[[F1]]]
 ; CHECK: llvm.intr.memmove
@@ -38,3 +41,36 @@ define void @cp(ptr %d, ptr %s) {
 !6 = !{!1, !1, i64 0}
 !7 = !{!2, !2, i64 0}
 !4 = !{ i64 0, i64 4, !6, i64 8, i64 4, !7 }
+
+; A narrow offset constant with its high bit set keeps its unsigned value:
+; LLVM compares offsets zero-extended, so i32 0x80000000 is 2147483648, not
+; a negative offset.
+; CHECK: llvm.intr.memcpy
+; CHECK-SAME: tbaa_struct = [#[[F2]]]
+define void @narrow_offset(ptr %d, ptr %s) {
+  call void @llvm.memcpy.p0.p0.i64(ptr %d, ptr %s, i64 12, i1 false), !tbaa.struct !8
+  ret void
+}
+
+!8 = !{ i32 2147483648, i64 4, !6 }
+
+; A high-bit i64 offset keeps its bits through the signed attribute; it is
+; not dropped as unrepresentable.
+; CHECK: llvm.intr.memcpy
+; CHECK-SAME: tbaa_struct = [#[[F3]]]
+define void @high_bit_offset(ptr %d, ptr %s) {
+  call void @llvm.memcpy.p0.p0.i64(ptr %d, ptr %s, i64 12, i1 false), !tbaa.struct !9
+  ret void
+}
+
+!9 = !{ i64 -1, i64 4, !6 }
+
+; A narrow size constant with its high bit set keeps its unsigned value too.
+; CHECK: llvm.intr.memcpy
+; CHECK-SAME: tbaa_struct = [#[[F4]]]
+define void @narrow_size(ptr %d, ptr %s) {
+  call void @llvm.memcpy.p0.p0.i64(ptr %d, ptr %s, i64 12, i1 false), !tbaa.struct !10
+  ret void
+}
+
+!10 = !{ i64 0, i32 2147483648, !6 }

>From ac915e12341a0b498e58e1e9643848b96b745dfb Mon Sep 17 00:00:00 2001
From: Bruno Cardoso Lopes <bruno.cardoso at gmail.com>
Date: Wed, 4 Nov 2026 16:22:40 -0800
Subject: [PATCH 03/11] Fix CI: pass tbaa_struct to CIR memcpy builders

The tbaa_struct argument added to the copy ops shifted the
positional builder arguments. Pass nullptr for it at the two
full-argument call sites so the build matches the new signatures.
---
 clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)

diff --git a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
index 2d3ded9796e22d..e18b7a7030a656 100644
--- a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
+++ b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
@@ -401,9 +401,9 @@ mlir::LogicalResult CIRToLLVMCopyOpLowering::matchAndRewrite(
 
   rewriter.replaceOpWithNewOp<mlir::LLVM::MemcpyOp>(
       op, adaptor.getDst(), adaptor.getSrc(), length, op.getIsVolatile(),
-      /*access_groups=*/nullptr, /*alias_scopes=*/nullptr,
-      /*noalias_scopes=*/nullptr, /*tbaa=*/nullptr, /*arg_attrs=*/argAttrs,
-      /*res_attrs=*/nullptr);
+      /*tbaa_struct=*/nullptr, /*access_groups=*/nullptr,
+      /*alias_scopes=*/nullptr, /*noalias_scopes=*/nullptr, /*tbaa=*/nullptr,
+      /*arg_attrs=*/argAttrs, /*res_attrs=*/nullptr);
   return mlir::success();
 }
 
@@ -426,7 +426,7 @@ lowerMemTransferOp(CIROp op, typename CIROp::Adaptor adaptor,
   }
   rewriter.replaceOpWithNewOp<LLVMOp>(
       op, adaptor.getDst(), adaptor.getSrc(), adaptor.getLen(),
-      /*isVolatile=*/false,
+      /*isVolatile=*/false, /*tbaa_struct=*/nullptr,
       /*access_groups=*/nullptr, /*alias_scopes=*/nullptr,
       /*noalias_scopes=*/nullptr, /*tbaa=*/nullptr, /*arg_attrs=*/argAttrs,
       /*res_attrs=*/nullptr);

>From a0a773a1117e004b4b01b652dd95dba6769518a0 Mon Sep 17 00:00:00 2001
From: Bruno Cardoso Lopes <bruno.cardoso at gmail.com>
Date: Wed, 4 Nov 2026 19:54:01 -0800
Subject: [PATCH 04/11] Address review: tbaa_struct via the baseArgs flag

Move the tbaa_struct argument from the per-op argument lists into a
new flag-gated baseArgs group (requiresTBAAStruct) in
LLVM_IntrOpBase, threaded through LLVM_IntrOp and
LLVM_ZeroResultIntrOp and enabled only for the memcpy, memmove, and
memcpy.inline ops. The argument now sits next to tbaa in the builder
signatures instead of hand-rolled per op; full-argument call sites
in TableGen builders, the inliner, and CIR lowering follow the new
order.
---
 .../CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp | 11 ++++-----
 .../mlir/Dialect/LLVMIR/LLVMIntrinsicOps.td   | 18 +++++++-------
 .../include/mlir/Dialect/LLVMIR/LLVMOpBase.td | 24 ++++++++++++++-----
 .../Transforms/InlinerInterfaceImpl.cpp       |  4 ++--
 4 files changed, 33 insertions(+), 24 deletions(-)

diff --git a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
index e18b7a7030a656..aac6ab024f4c86 100644
--- a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
+++ b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
@@ -401,8 +401,8 @@ mlir::LogicalResult CIRToLLVMCopyOpLowering::matchAndRewrite(
 
   rewriter.replaceOpWithNewOp<mlir::LLVM::MemcpyOp>(
       op, adaptor.getDst(), adaptor.getSrc(), length, op.getIsVolatile(),
-      /*tbaa_struct=*/nullptr, /*access_groups=*/nullptr,
-      /*alias_scopes=*/nullptr, /*noalias_scopes=*/nullptr, /*tbaa=*/nullptr,
+      /*access_groups=*/nullptr, /*alias_scopes=*/nullptr,
+      /*noalias_scopes=*/nullptr, /*tbaa=*/nullptr, /*tbaa_struct=*/nullptr,
       /*arg_attrs=*/argAttrs, /*res_attrs=*/nullptr);
   return mlir::success();
 }
@@ -426,10 +426,9 @@ lowerMemTransferOp(CIROp op, typename CIROp::Adaptor adaptor,
   }
   rewriter.replaceOpWithNewOp<LLVMOp>(
       op, adaptor.getDst(), adaptor.getSrc(), adaptor.getLen(),
-      /*isVolatile=*/false, /*tbaa_struct=*/nullptr,
-      /*access_groups=*/nullptr, /*alias_scopes=*/nullptr,
-      /*noalias_scopes=*/nullptr, /*tbaa=*/nullptr, /*arg_attrs=*/argAttrs,
-      /*res_attrs=*/nullptr);
+      /*isVolatile=*/false, /*access_groups=*/nullptr,
+      /*alias_scopes=*/nullptr, /*noalias_scopes=*/nullptr, /*tbaa=*/nullptr,
+      /*tbaa_struct=*/nullptr, /*arg_attrs=*/argAttrs, /*res_attrs=*/nullptr);
   return mlir::success();
 }
 
diff --git a/mlir/include/mlir/Dialect/LLVMIR/LLVMIntrinsicOps.td b/mlir/include/mlir/Dialect/LLVMIR/LLVMIntrinsicOps.td
index 35d8e6ae68ff51..ea67e1ef258142 100644
--- a/mlir/include/mlir/Dialect/LLVMIR/LLVMIntrinsicOps.td
+++ b/mlir/include/mlir/Dialect/LLVMIR/LLVMIntrinsicOps.td
@@ -262,13 +262,11 @@ class LLVM_MemcpyIntrOpBase<string name> :
      DeclareOpInterfaceMethods<SafeMemorySlotAccessOpInterface>],
     /*requiresAccessGroup=*/1, /*requiresAliasAnalysis=*/1,
     /*requiresArgAndResultAttrs=*/1, /*requiresOpBundles=*/0,
-    /*immArgPositions=*/[3], /*immArgAttrNames=*/["isVolatile"]> {
+    /*immArgPositions=*/[3], /*immArgAttrNames=*/["isVolatile"],
+    /*requiresTBAAStruct=*/1> {
   dag args = (ins Arg<LLVM_AnyPointer,"",[MemWrite]>:$dst,
                   Arg<LLVM_AnyPointer,"",[MemRead]>:$src,
-                  AnySignlessInteger:$len, I1Attr:$isVolatile,
-                  // `!tbaa.struct`: which fields of the aggregate the copy
-                  // touches, so it is not treated as one opaque access.
-                  OptionalAttr<LLVM_TBAAStructFieldArrayAttr>:$tbaa_struct);
+                  AnySignlessInteger:$len, I1Attr:$isVolatile);
   // Append the arguments defined by LLVM_IntrOpBase.
   let arguments = !con(args, baseArgs);
   let builders = [
@@ -280,9 +278,9 @@ class LLVM_MemcpyIntrOpBase<string name> :
     OpBuilder<(ins "Value":$dst, "Value":$src, "Value":$len,
                    "IntegerAttr":$isVolatile), [{
       build($_builder, $_state, dst, src, len, isVolatile,
-            /*tbaa_struct=*/nullptr,
             /*access_groups=*/nullptr, /*alias_scopes=*/nullptr,
             /*noalias_scopes=*/nullptr, /*tbaa=*/nullptr,
+            /*tbaa_struct=*/nullptr,
             /*arg_attrs=*/nullptr, /*res_attrs=*/nullptr);
     }]>
   ];
@@ -309,11 +307,11 @@ def LLVM_MemcpyInlineOp :
      DeclareOpInterfaceMethods<SafeMemorySlotAccessOpInterface>],
     /*requiresAccessGroup=*/1, /*requiresAliasAnalysis=*/1,
     /*requiresArgAndResultAttrs=*/1, /*requiresOpBundles=*/0,
-    /*immArgPositions=*/[2, 3], /*immArgAttrNames=*/["len", "isVolatile"]> {
+    /*immArgPositions=*/[2, 3], /*immArgAttrNames=*/["len", "isVolatile"],
+    /*requiresTBAAStruct=*/1> {
   dag args = (ins Arg<LLVM_AnyPointer,"",[MemWrite]>:$dst,
                   Arg<LLVM_AnyPointer,"",[MemRead]>:$src,
-                  APIntAttr:$len, I1Attr:$isVolatile,
-                  OptionalAttr<LLVM_TBAAStructFieldArrayAttr>:$tbaa_struct);
+                  APIntAttr:$len, I1Attr:$isVolatile);
   // Append the arguments defined by LLVM_IntrOpBase.
   let arguments = !con(args, baseArgs);
   let builders = [
@@ -325,9 +323,9 @@ def LLVM_MemcpyInlineOp :
     OpBuilder<(ins "Value":$dst, "Value":$src, "IntegerAttr":$len,
                    "IntegerAttr":$isVolatile), [{
       build($_builder, $_state, dst, src, len, isVolatile,
-            /*tbaa_struct=*/nullptr,
             /*access_groups=*/nullptr, /*alias_scopes=*/nullptr,
             /*noalias_scopes=*/nullptr, /*tbaa=*/nullptr,
+            /*tbaa_struct=*/nullptr,
             /*arg_attrs=*/nullptr, /*res_attrs=*/nullptr);
     }]>
   ];
diff --git a/mlir/include/mlir/Dialect/LLVMIR/LLVMOpBase.td b/mlir/include/mlir/Dialect/LLVMIR/LLVMOpBase.td
index 66583a592b3f64..138a840fce7628 100644
--- a/mlir/include/mlir/Dialect/LLVMIR/LLVMOpBase.td
+++ b/mlir/include/mlir/Dialect/LLVMIR/LLVMOpBase.td
@@ -310,7 +310,11 @@ class LLVM_MemAccessOpBase<string mnemonic, list<Trait> traits = []> :
 // interfaces the intrinsic implements. When a flag is set, the "baseArgs"
 // list includes the arguments required by the corresponding interface.
 // Derived intrinsics must append "baseArgs" to their argument list if they
-// enable any of these flags.
+// enable any of these flags. "requiresTBAAStruct" is not tied to an
+// interface: it adds the tbaa_struct argument after tbaa (when present),
+// for the aggregate-copy intrinsics only. It only wires the argument;
+// the export, import, and verifier sites name those three ops directly,
+// so a future op setting the flag also needs handling there.
 //
 // LLVM `immargs` can be represented as MLIR attributes by providing both
 // the `immArgPositions` and `immArgAttrNames` lists. These two lists should
@@ -324,7 +328,8 @@ class LLVM_IntrOpBase<Dialect dialect, string opName, string enumName,
                       bit requiresFastmath = 0, bit requiresArgAndResultAttrs = 0,
                       bit requiresOpBundles = 0,
                       list<int> immArgPositions = [],
-                      list<string> immArgAttrNames = []>
+                      list<string> immArgAttrNames = [],
+                      bit requiresTBAAStruct = 0>
     : LLVM_OpBase<dialect, opName, !listconcat(
         !if(!gt(requiresAccessGroup, 0),
             [DeclareOpInterfaceMethods<AccessGroupOpInterface>], []),
@@ -346,6 +351,9 @@ class LLVM_IntrOpBase<Dialect dialect, string opName, string enumName,
                  OptionalAttr<LLVM_AliasScopeArrayAttr>:$noalias_scopes,
                  OptionalAttr<LLVM_TBAATagArrayAttr>:$tbaa),
             (ins )),
+        !if(!gt(requiresTBAAStruct, 0),
+            (ins OptionalAttr<LLVM_TBAAStructFieldArrayAttr>:$tbaa_struct),
+            (ins )),
         !if(!gt(requiresArgAndResultAttrs, 0),
             (ins OptionalAttr<DictArrayAttr>:$arg_attrs,
                  OptionalAttr<DictArrayAttr>:$res_attrs),
@@ -456,12 +464,14 @@ class LLVM_IntrOp<string mnem, list<int> overloadedResults,
                   bit requiresAliasAnalysis = 0, bit requiresFastmath = 0,
                   bit requiresArgAndResultAttrs = 0, bit requiresOpBundles = 0,
                   list<int> immArgPositions = [],
-                  list<string> immArgAttrNames = []>
+                  list<string> immArgAttrNames = [],
+                  bit requiresTBAAStruct = 0>
     : LLVM_IntrOpBase<LLVM_Dialect, "intr." # mnem, !subst(".", "_", mnem),
                       overloadedResults, overloadedOperands, traits,
                       numResults, requiresAccessGroup, requiresAliasAnalysis,
                       requiresFastmath, requiresArgAndResultAttrs,
-                      requiresOpBundles, immArgPositions, immArgAttrNames>;
+                      requiresOpBundles, immArgPositions, immArgAttrNames,
+                      requiresTBAAStruct>;
 
 // Base class for LLVM intrinsic operations returning no results. Places the
 // intrinsic into the LLVM dialect and prefixes its name with "intr.".
@@ -484,11 +494,13 @@ class LLVM_ZeroResultIntrOp<string mnem, list<int> overloadedOperands = [],
                             bit requiresArgAndResultAttrs = 0,
                             bit requiresOpBundles = 0,
                             list<int> immArgPositions = [],
-                            list<string> immArgAttrNames = []>
+                            list<string> immArgAttrNames = [],
+                            bit requiresTBAAStruct = 0>
     : LLVM_IntrOp<mnem, [], overloadedOperands, traits, /*numResults=*/0,
                   requiresAccessGroup, requiresAliasAnalysis,
                   /*requiresFastMath=*/0, requiresArgAndResultAttrs,
-                  requiresOpBundles, immArgPositions, immArgAttrNames>;
+                  requiresOpBundles, immArgPositions, immArgAttrNames,
+                  requiresTBAAStruct>;
 
 // Base class for LLVM intrinsic operations returning one result. Places the
 // intrinsic into the LLVM dialect and prefixes its name with "intr.". This is
diff --git a/mlir/lib/Dialect/LLVMIR/Transforms/InlinerInterfaceImpl.cpp b/mlir/lib/Dialect/LLVMIR/Transforms/InlinerInterfaceImpl.cpp
index e4d91d347e8c6b..b2296917545f55 100644
--- a/mlir/lib/Dialect/LLVMIR/Transforms/InlinerInterfaceImpl.cpp
+++ b/mlir/lib/Dialect/LLVMIR/Transforms/InlinerInterfaceImpl.cpp
@@ -716,9 +716,9 @@ static Value handleByValArgumentInit(OpBuilder &builder, Location loc,
       builder.getArrayAttr({builder.getDictionaryAttr({dstAlignAttr})});
   LLVM::MemcpyOp::create(builder, loc, allocaOp, argument, copySize,
                          /*isVolatile=*/false,
-                         /*tbaa_struct=*/nullptr,
                          /*access_groups=*/nullptr, /*alias_scopes=*/nullptr,
-                         /*noalias_scopes=*/nullptr, /*tbaa=*/nullptr, argAttrs,
+                         /*noalias_scopes=*/nullptr, /*tbaa=*/nullptr,
+                         /*tbaa_struct=*/nullptr, argAttrs,
                          /*res_attrs=*/nullptr);
   return allocaOp;
 }

>From bfb7a63c497dccf3b5452333efb21806b02d206a Mon Sep 17 00:00:00 2001
From: Bruno Cardoso Lopes <bruno.cardoso at gmail.com>
Date: Thu, 5 Nov 2026 17:55:04 -0800
Subject: [PATCH 05/11] Address review: hoist tbaa.struct conversion, use LLVM
 helper

Convert !tbaa.struct nodes once in convertMetadata (after the tag
pre-walk) and cache the result in a separate tbaaStructMapping;
setTBAAStructAttr is now mostly a lookup, like setTBAAAttr for
access tags. A null value records nodes that could not be modeled
so they are declined at attach time without reconverting. The
separate map keeps struct nodes from being mistaken for TBAA tag
or descriptor nodes. Export builds the node with
MDBuilder::createTBAAStructNode.
---
 .../include/mlir/Target/LLVMIR/ModuleImport.h | 18 ++++++
 .../LLVMIR/LLVMIRToLLVMTranslation.cpp        | 56 ++++---------------
 mlir/lib/Target/LLVMIR/ModuleImport.cpp       | 51 ++++++++++++++++-
 mlir/lib/Target/LLVMIR/ModuleTranslation.cpp  | 19 +++----
 4 files changed, 85 insertions(+), 59 deletions(-)

diff --git a/mlir/include/mlir/Target/LLVMIR/ModuleImport.h b/mlir/include/mlir/Target/LLVMIR/ModuleImport.h
index ab46245b040d09..e9eaf2e78e737a 100644
--- a/mlir/include/mlir/Target/LLVMIR/ModuleImport.h
+++ b/mlir/include/mlir/Target/LLVMIR/ModuleImport.h
@@ -257,6 +257,12 @@ class ModuleImport {
     return tbaaMapping.lookup(node);
   }
 
+  /// Looks up a converted `!tbaa.struct` node. Returns null when the
+  /// node was never converted or could not be modeled.
+  Attribute lookupTBAAStructAttr(const llvm::MDNode *node) const {
+    return tbaaStructMapping.lookup(node);
+  }
+
   /// Returns the access group attributes that map to the access group nodes
   /// starting from the access group metadata `node`. Returns failure, if any of
   /// the attributes cannot be found.
@@ -471,6 +477,12 @@ class ModuleImport {
   /// (unless all dependencies have been converted by a previous
   /// invocation of this function).
   LogicalResult processTBAAMetadata(const llvm::MDNode *node);
+  /// Converts a `!tbaa.struct` node to the `tbaa_struct` attribute. The
+  /// node's tags must already be converted (see the pre-walk in
+  /// convertMetadata). Returns null for nodes that cannot be modeled;
+  /// callers record the null in tbaaStructMapping so the node is
+  /// declined at attach time.
+  Attribute convertTBAAStructMetadata(const llvm::MDNode *node);
   /// Converts all LLVM access groups starting from `node` to MLIR access group
   /// operations and stores a mapping from every nested access group node to the
   /// translated attribute. Returns success if all conversions succeed and
@@ -539,6 +551,12 @@ class ModuleImport {
   /// Mapping between LLVM TBAA metadata nodes and LLVM dialect TBAA attributes
   /// corresponding to these nodes.
   DenseMap<const llvm::MDNode *, Attribute> tbaaMapping;
+  /// Mapping between LLVM `!tbaa.struct` nodes and the converted
+  /// `tbaa_struct` attributes. Kept separate from tbaaMapping so a struct
+  /// node can never be mistaken for a TBAA tag or type descriptor node,
+  /// which processTBAAMetadata casts to those attribute kinds. A null
+  /// value records that the node was converted and could not be modeled.
+  DenseMap<const llvm::MDNode *, Attribute> tbaaStructMapping;
   /// Mapping between LLVM comdat structs and symbol references to LLVM dialect
   /// comdat selector operations corresponding to these structs.
   DenseMap<const llvm::Comdat *, SymbolRefAttr> comdatMapping;
diff --git a/mlir/lib/Target/LLVMIR/Dialect/LLVMIR/LLVMIRToLLVMTranslation.cpp b/mlir/lib/Target/LLVMIR/Dialect/LLVMIR/LLVMIRToLLVMTranslation.cpp
index dfc93a544c0a27..f0947a69f6012b 100644
--- a/mlir/lib/Target/LLVMIR/Dialect/LLVMIR/LLVMIRToLLVMTranslation.cpp
+++ b/mlir/lib/Target/LLVMIR/Dialect/LLVMIR/LLVMIRToLLVMTranslation.cpp
@@ -215,57 +215,21 @@ static LogicalResult setTBAAAttr(const llvm::MDNode *node, Operation *op,
   return success();
 }
 
-/// Converts `!tbaa.struct` to the `tbaa_struct` attribute on the imported
-/// aggregate copy. The node is a flat list of (offset, size, tag) triples: it
-/// says which fields of the aggregate the copy actually touches, so the copy is
-/// not treated as one opaque access and the gaps are known to be padding.
-static LogicalResult setTBAAStructAttr(OpBuilder &builder,
-                                       const llvm::MDNode *node, Operation *op,
+/// Attaches the `tbaa_struct` attribute converted from `!tbaa.struct` by
+/// ModuleImport::convertTBAAStructMetadata to the imported aggregate copy,
+/// like setTBAAAttr does for access tags. Nodes that could not be modeled
+/// are unmapped and declined here.
+static LogicalResult setTBAAStructAttr(const llvm::MDNode *node, Operation *op,
                                        LLVM::ModuleImport &moduleImport) {
-  if (!isa<LLVM::MemcpyOp, LLVM::MemcpyInlineOp, LLVM::MemmoveOp>(op))
+  auto fields =
+      dyn_cast_if_present<ArrayAttr>(moduleImport.lookupTBAAStructAttr(node));
+  if (!fields)
     return failure();
 
-  // Operands come in conceptual groups of three; anything else is malformed.
-  if (node->getNumOperands() == 0 || node->getNumOperands() % 3 != 0)
-    return failure();
-
-  SmallVector<Attribute> fields;
-  fields.reserve(node->getNumOperands() / 3);
-  for (unsigned i = 0, e = node->getNumOperands(); i != e; i += 3) {
-    auto *offset = llvm::mdconst::dyn_extract_or_null<llvm::ConstantInt>(
-        node->getOperand(i));
-    auto *size = llvm::mdconst::dyn_extract_or_null<llvm::ConstantInt>(
-        node->getOperand(i + 1));
-    if (!offset || !size)
-      return failure();
-    // Offsets and sizes are int64 in the attribute; values that do not fit
-    // in 64 bits cannot be represented, and extracting them would assert.
-    // Read them unsigned and keep the bits: LLVM compares offsets
-    // zero-extended, so a narrow constant with its high bit set (e.g. i32
-    // 0x80000000) must keep its unsigned value rather than sign-extending,
-    // and a high-bit i64 offset must round-trip through the signed
-    // attribute unchanged.
-    std::optional<uint64_t> offsetZExt = offset->getValue().tryZExtValue();
-    std::optional<uint64_t> sizeZExt = size->getValue().tryZExtValue();
-    if (!offsetZExt || !sizeZExt)
-      return failure();
-    int64_t offsetValue = static_cast<int64_t>(*offsetZExt);
-    int64_t sizeValue = static_cast<int64_t>(*sizeZExt);
-    auto *tagNode = dyn_cast_if_present<llvm::MDNode>(node->getOperand(i + 2));
-    if (!tagNode)
-      return failure();
-    auto tag =
-        dyn_cast_if_present<TBAATagAttr>(moduleImport.lookupTBAAAttr(tagNode));
-    if (!tag)
-      return failure();
-    fields.push_back(
-        builder.getAttr<TBAAStructFieldAttr>(offsetValue, sizeValue, tag));
-  }
-
   return TypeSwitch<Operation *, LogicalResult>(op)
       .Case<LLVM::MemcpyOp, LLVM::MemcpyInlineOp, LLVM::MemmoveOp>(
           [&](auto copyOp) {
-            copyOp.setTbaaStructAttr(builder.getArrayAttr(fields));
+            copyOp.setTbaaStructAttr(fields);
             return success();
           })
       .Default([](auto) { return failure(); });
@@ -662,7 +626,7 @@ class LLVMDialectLLVMIRImportInterface : public LLVMImportDialectInterface {
     if (kind == llvm::LLVMContext::MD_callsite)
       return setCallsiteAttr(builder, node, op);
     if (kind == llvm::LLVMContext::MD_tbaa_struct)
-      return setTBAAStructAttr(builder, node, op, moduleImport);
+      return setTBAAStructAttr(node, op, moduleImport);
     llvm::LLVMContext &context = node->getContext();
     if (kind == context.getMDKindID(vecTypeHintMDName))
       return setVecTypeHintAttr(builder, node, op, moduleImport);
diff --git a/mlir/lib/Target/LLVMIR/ModuleImport.cpp b/mlir/lib/Target/LLVMIR/ModuleImport.cpp
index 051b67cbf3f797..69499e83f34591 100644
--- a/mlir/lib/Target/LLVMIR/ModuleImport.cpp
+++ b/mlir/lib/Target/LLVMIR/ModuleImport.cpp
@@ -575,6 +575,46 @@ LogicalResult ModuleImport::processTBAAMetadata(const llvm::MDNode *node) {
   return success();
 }
 
+Attribute ModuleImport::convertTBAAStructMetadata(const llvm::MDNode *node) {
+  // Operands come in conceptual groups of three; anything else is malformed.
+  if (node->getNumOperands() == 0 || node->getNumOperands() % 3 != 0)
+    return {};
+
+  SmallVector<Attribute> fields;
+  fields.reserve(node->getNumOperands() / 3);
+  for (unsigned i = 0, e = node->getNumOperands(); i != e; i += 3) {
+    auto *offset = llvm::mdconst::dyn_extract_or_null<llvm::ConstantInt>(
+        node->getOperand(i));
+    auto *size = llvm::mdconst::dyn_extract_or_null<llvm::ConstantInt>(
+        node->getOperand(i + 1));
+    if (!offset || !size)
+      return {};
+    // Offsets and sizes are int64 in the attribute; values that do not fit
+    // in 64 bits cannot be represented, and extracting them would assert.
+    // Read them unsigned and keep the bits: LLVM compares offsets
+    // zero-extended, so a narrow constant with its high bit set (e.g. i32
+    // 0x80000000) must keep its unsigned value rather than sign-extending,
+    // and a high-bit i64 offset must round-trip through the signed
+    // attribute unchanged.
+    std::optional<uint64_t> offsetZExt = offset->getValue().tryZExtValue();
+    std::optional<uint64_t> sizeZExt = size->getValue().tryZExtValue();
+    if (!offsetZExt || !sizeZExt)
+      return {};
+    int64_t offsetValue = static_cast<int64_t>(*offsetZExt);
+    int64_t sizeValue = static_cast<int64_t>(*sizeZExt);
+    auto *tagNode = dyn_cast_if_present<llvm::MDNode>(node->getOperand(i + 2));
+    if (!tagNode)
+      return {};
+    auto tag = dyn_cast_if_present<TBAATagAttr>(lookupTBAAAttr(tagNode));
+    if (!tag)
+      return {};
+    fields.push_back(
+        builder.getAttr<TBAAStructFieldAttr>(offsetValue, sizeValue, tag));
+  }
+
+  return builder.getArrayAttr(fields);
+}
+
 LogicalResult
 ModuleImport::processAccessGroupMetadata(const llvm::MDNode *node) {
   Location loc = mlirModule.getLoc();
@@ -1171,8 +1211,8 @@ LogicalResult ModuleImport::convertMetadata() {
         if (failed(processTBAAMetadata(aliasAnalysisNodes.TBAA)))
           return failure();
       // A `!tbaa.struct` node reaches its own tags, and those tags may appear
-      // nowhere else in the module. Without walking them here the lookup in
-      // setTBAAStructAttr finds nothing and the node is declined.
+      // nowhere else in the module. Without walking them here the struct
+      // conversion below finds nothing and the node is declined.
       if (aliasAnalysisNodes.TBAAStruct) {
         const llvm::MDNode *structNode = aliasAnalysisNodes.TBAAStruct;
         for (unsigned i = 2, e = structNode->getNumOperands(); i < e; i += 3)
@@ -1180,6 +1220,13 @@ LogicalResult ModuleImport::convertMetadata() {
                   dyn_cast_if_present<llvm::MDNode>(structNode->getOperand(i)))
             if (failed(processTBAAMetadata(tag)))
               return failure();
+        // Convert the struct node itself once its tags are in the map. A
+        // node that cannot be modeled is recorded with a null value so it
+        // is not converted again for every instruction carrying it, and is
+        // declined at attach time.
+        if (!tbaaStructMapping.contains(structNode))
+          tbaaStructMapping.insert(
+              {structNode, convertTBAAStructMetadata(structNode)});
       }
       if (aliasAnalysisNodes.Scope)
         if (failed(processAliasScopeMetadata(aliasAnalysisNodes.Scope)))
diff --git a/mlir/lib/Target/LLVMIR/ModuleTranslation.cpp b/mlir/lib/Target/LLVMIR/ModuleTranslation.cpp
index 1428ce906860de..130f2cad5719b3 100644
--- a/mlir/lib/Target/LLVMIR/ModuleTranslation.cpp
+++ b/mlir/lib/Target/LLVMIR/ModuleTranslation.cpp
@@ -2425,20 +2425,17 @@ void ModuleTranslation::setTBAAStructMetadata(ArrayAttr fields,
 
   // The node is a flat list of (offset, size, tag) triples, not a list of
   // per-field nodes.
-  llvm::LLVMContext &ctx = getLLVMContext();
-  llvm::Type *i64 = llvm::Type::getInt64Ty(ctx);
-  SmallVector<llvm::Metadata *> operands;
-  operands.reserve(fields.size() * 3);
+  SmallVector<llvm::MDBuilder::TBAAStructField> structFields;
+  structFields.reserve(fields.size());
   for (Attribute field : fields) {
     auto fieldAttr = cast<TBAAStructFieldAttr>(field);
-    operands.push_back(llvm::ConstantAsMetadata::get(
-        llvm::ConstantInt::getSigned(i64, fieldAttr.getOffset())));
-    operands.push_back(llvm::ConstantAsMetadata::get(
-        llvm::ConstantInt::getSigned(i64, fieldAttr.getSize())));
-    operands.push_back(getTBAANode(fieldAttr.getTag()));
+    structFields.emplace_back(static_cast<uint64_t>(fieldAttr.getOffset()),
+                              static_cast<uint64_t>(fieldAttr.getSize()),
+                              getTBAANode(fieldAttr.getTag()));
   }
-  inst->setMetadata(llvm::LLVMContext::MD_tbaa_struct,
-                    llvm::MDNode::get(ctx, operands));
+  inst->setMetadata(
+      llvm::LLVMContext::MD_tbaa_struct,
+      llvm::MDBuilder(getLLVMContext()).createTBAAStructNode(structFields));
 }
 
 void ModuleTranslation::setDereferenceableMetadata(

>From c044048db201a861a2f6b465eff78f07ed30bd70 Mon Sep 17 00:00:00 2001
From: Bruno Cardoso Lopes <bruno.cardoso at gmail.com>
Date: Thu, 5 Nov 2026 18:26:44 -0800
Subject: [PATCH 06/11] Address review: requiresTBAAStruct as a let-set field

Make requiresTBAAStruct a plain field on LLVM_IntrOpBase, set with
let by the aggregate-copy intrinsics, instead of a constructor
argument. Enabling it then cannot shift the positional flag
arguments of every intrinsic definition. The generated code is
identical: tbaa_struct still sits next to tbaa in the builder
signatures.
---
 .../mlir/Dialect/LLVMIR/LLVMIntrinsicOps.td   |  8 +++---
 .../include/mlir/Dialect/LLVMIR/LLVMOpBase.td | 27 ++++++++++---------
 2 files changed, 18 insertions(+), 17 deletions(-)

diff --git a/mlir/include/mlir/Dialect/LLVMIR/LLVMIntrinsicOps.td b/mlir/include/mlir/Dialect/LLVMIR/LLVMIntrinsicOps.td
index ea67e1ef258142..a36db9601c8775 100644
--- a/mlir/include/mlir/Dialect/LLVMIR/LLVMIntrinsicOps.td
+++ b/mlir/include/mlir/Dialect/LLVMIR/LLVMIntrinsicOps.td
@@ -262,8 +262,8 @@ class LLVM_MemcpyIntrOpBase<string name> :
      DeclareOpInterfaceMethods<SafeMemorySlotAccessOpInterface>],
     /*requiresAccessGroup=*/1, /*requiresAliasAnalysis=*/1,
     /*requiresArgAndResultAttrs=*/1, /*requiresOpBundles=*/0,
-    /*immArgPositions=*/[3], /*immArgAttrNames=*/["isVolatile"],
-    /*requiresTBAAStruct=*/1> {
+    /*immArgPositions=*/[3], /*immArgAttrNames=*/["isVolatile"]> {
+  let requiresTBAAStruct = 1;
   dag args = (ins Arg<LLVM_AnyPointer,"",[MemWrite]>:$dst,
                   Arg<LLVM_AnyPointer,"",[MemRead]>:$src,
                   AnySignlessInteger:$len, I1Attr:$isVolatile);
@@ -307,8 +307,8 @@ def LLVM_MemcpyInlineOp :
      DeclareOpInterfaceMethods<SafeMemorySlotAccessOpInterface>],
     /*requiresAccessGroup=*/1, /*requiresAliasAnalysis=*/1,
     /*requiresArgAndResultAttrs=*/1, /*requiresOpBundles=*/0,
-    /*immArgPositions=*/[2, 3], /*immArgAttrNames=*/["len", "isVolatile"],
-    /*requiresTBAAStruct=*/1> {
+    /*immArgPositions=*/[2, 3], /*immArgAttrNames=*/["len", "isVolatile"]> {
+  let requiresTBAAStruct = 1;
   dag args = (ins Arg<LLVM_AnyPointer,"",[MemWrite]>:$dst,
                   Arg<LLVM_AnyPointer,"",[MemRead]>:$src,
                   APIntAttr:$len, I1Attr:$isVolatile);
diff --git a/mlir/include/mlir/Dialect/LLVMIR/LLVMOpBase.td b/mlir/include/mlir/Dialect/LLVMIR/LLVMOpBase.td
index 138a840fce7628..43856f686c12f3 100644
--- a/mlir/include/mlir/Dialect/LLVMIR/LLVMOpBase.td
+++ b/mlir/include/mlir/Dialect/LLVMIR/LLVMOpBase.td
@@ -312,9 +312,10 @@ class LLVM_MemAccessOpBase<string mnemonic, list<Trait> traits = []> :
 // Derived intrinsics must append "baseArgs" to their argument list if they
 // enable any of these flags. "requiresTBAAStruct" is not tied to an
 // interface: it adds the tbaa_struct argument after tbaa (when present),
-// for the aggregate-copy intrinsics only. It only wires the argument;
-// the export, import, and verifier sites name those three ops directly,
-// so a future op setting the flag also needs handling there.
+// for the aggregate-copy intrinsics only. It is set with `let` by those
+// intrinsics. It only wires the argument; the export, import, and
+// verifier sites name those three ops directly, so a future op setting
+// the flag also needs handling there.
 //
 // LLVM `immargs` can be represented as MLIR attributes by providing both
 // the `immArgPositions` and `immArgAttrNames` lists. These two lists should
@@ -328,8 +329,7 @@ class LLVM_IntrOpBase<Dialect dialect, string opName, string enumName,
                       bit requiresFastmath = 0, bit requiresArgAndResultAttrs = 0,
                       bit requiresOpBundles = 0,
                       list<int> immArgPositions = [],
-                      list<string> immArgAttrNames = [],
-                      bit requiresTBAAStruct = 0>
+                      list<string> immArgAttrNames = []>
     : LLVM_OpBase<dialect, opName, !listconcat(
         !if(!gt(requiresAccessGroup, 0),
             [DeclareOpInterfaceMethods<AccessGroupOpInterface>], []),
@@ -342,6 +342,11 @@ class LLVM_IntrOpBase<Dialect dialect, string opName, string enumName,
         traits)>,
       LLVM_MemOpPatterns,
       Results<!if(!gt(numResults, 0), (outs LLVM_Type:$res), (outs))> {
+  // Set with `let` by intrinsics carrying tbaa.struct metadata, like the
+  // aggregate-copy intrinsics. It is a plain field rather than a
+  // constructor argument so that enabling it does not shift the
+  // positional flag arguments of every intrinsic definition.
+  bit requiresTBAAStruct = 0;
   dag baseArgs = !con(
         !if(!gt(requiresAccessGroup, 0),
             (ins OptionalAttr<LLVM_AccessGroupArrayAttr>:$access_groups),
@@ -464,14 +469,12 @@ class LLVM_IntrOp<string mnem, list<int> overloadedResults,
                   bit requiresAliasAnalysis = 0, bit requiresFastmath = 0,
                   bit requiresArgAndResultAttrs = 0, bit requiresOpBundles = 0,
                   list<int> immArgPositions = [],
-                  list<string> immArgAttrNames = [],
-                  bit requiresTBAAStruct = 0>
+                  list<string> immArgAttrNames = []>
     : LLVM_IntrOpBase<LLVM_Dialect, "intr." # mnem, !subst(".", "_", mnem),
                       overloadedResults, overloadedOperands, traits,
                       numResults, requiresAccessGroup, requiresAliasAnalysis,
                       requiresFastmath, requiresArgAndResultAttrs,
-                      requiresOpBundles, immArgPositions, immArgAttrNames,
-                      requiresTBAAStruct>;
+                      requiresOpBundles, immArgPositions, immArgAttrNames>;
 
 // Base class for LLVM intrinsic operations returning no results. Places the
 // intrinsic into the LLVM dialect and prefixes its name with "intr.".
@@ -494,13 +497,11 @@ class LLVM_ZeroResultIntrOp<string mnem, list<int> overloadedOperands = [],
                             bit requiresArgAndResultAttrs = 0,
                             bit requiresOpBundles = 0,
                             list<int> immArgPositions = [],
-                            list<string> immArgAttrNames = [],
-                            bit requiresTBAAStruct = 0>
+                            list<string> immArgAttrNames = []>
     : LLVM_IntrOp<mnem, [], overloadedOperands, traits, /*numResults=*/0,
                   requiresAccessGroup, requiresAliasAnalysis,
                   /*requiresFastMath=*/0, requiresArgAndResultAttrs,
-                  requiresOpBundles, immArgPositions, immArgAttrNames,
-                  requiresTBAAStruct>;
+                  requiresOpBundles, immArgPositions, immArgAttrNames>;
 
 // Base class for LLVM intrinsic operations returning one result. Places the
 // intrinsic into the LLVM dialect and prefixes its name with "intr.". This is

>From 689efcbe2849b29f59b8c736df264abbb503430a Mon Sep 17 00:00:00 2001
From: Bruno Cardoso Lopes <bruno.cardoso at gmail.com>
Date: Thu, 5 Nov 2026 18:29:26 -0800
Subject: [PATCH 07/11] Address review: uint64_t offsets and sizes in
 tbaa_struct fields

Field offsets and sizes are unsigned quantities: LLVM compares
offsets zero-extended, and the values round-trip through i64
constants. Store them as uint64_t in the attribute instead of
int64_t, dropping the casts in the verifier, importer, and
exporter.
---
 .../mlir/Dialect/LLVMIR/LLVMAttrDefs.td       |  4 ++--
 mlir/lib/Dialect/LLVMIR/IR/LLVMDialect.cpp    |  3 +--
 mlir/lib/Target/LLVMIR/ModuleImport.cpp       | 22 ++++++++-----------
 mlir/lib/Target/LLVMIR/ModuleTranslation.cpp  |  3 +--
 .../LLVMIR/Import/metadata-tbaa-struct.ll     |  6 ++---
 5 files changed, 16 insertions(+), 22 deletions(-)

diff --git a/mlir/include/mlir/Dialect/LLVMIR/LLVMAttrDefs.td b/mlir/include/mlir/Dialect/LLVMIR/LLVMAttrDefs.td
index 2a4337ed107fc0..63790fac491824 100644
--- a/mlir/include/mlir/Dialect/LLVMIR/LLVMAttrDefs.td
+++ b/mlir/include/mlir/Dialect/LLVMIR/LLVMAttrDefs.td
@@ -1392,8 +1392,8 @@ def LLVM_TBAATagArrayAttr
 def LLVM_TBAAStructFieldAttr
     : LLVM_Attr<"TBAAStructField", "tbaa_struct_field"> {
   let parameters = (ins
-    "int64_t":$offset,
-    "int64_t":$size,
+    "uint64_t":$offset,
+    "uint64_t":$size,
     "TBAATagAttr":$tag
   );
 
diff --git a/mlir/lib/Dialect/LLVMIR/IR/LLVMDialect.cpp b/mlir/lib/Dialect/LLVMIR/IR/LLVMDialect.cpp
index 414a5916eeff36..92dc62e7044dad 100644
--- a/mlir/lib/Dialect/LLVMIR/IR/LLVMDialect.cpp
+++ b/mlir/lib/Dialect/LLVMIR/IR/LLVMDialect.cpp
@@ -459,8 +459,7 @@ static LogicalResult verifyTBAAStructFieldOffsets(Operation *op,
     return success();
   std::optional<uint64_t> prevOffset;
   for (Attribute field : fields) {
-    uint64_t offset =
-        static_cast<uint64_t>(cast<TBAAStructFieldAttr>(field).getOffset());
+    uint64_t offset = cast<TBAAStructFieldAttr>(field).getOffset();
     if (prevOffset && offset < *prevOffset)
       return op->emitOpError(
           "tbaa.struct field offsets must be non-decreasing");
diff --git a/mlir/lib/Target/LLVMIR/ModuleImport.cpp b/mlir/lib/Target/LLVMIR/ModuleImport.cpp
index 69499e83f34591..cbfd19b2b3229e 100644
--- a/mlir/lib/Target/LLVMIR/ModuleImport.cpp
+++ b/mlir/lib/Target/LLVMIR/ModuleImport.cpp
@@ -589,19 +589,15 @@ Attribute ModuleImport::convertTBAAStructMetadata(const llvm::MDNode *node) {
         node->getOperand(i + 1));
     if (!offset || !size)
       return {};
-    // Offsets and sizes are int64 in the attribute; values that do not fit
-    // in 64 bits cannot be represented, and extracting them would assert.
-    // Read them unsigned and keep the bits: LLVM compares offsets
-    // zero-extended, so a narrow constant with its high bit set (e.g. i32
-    // 0x80000000) must keep its unsigned value rather than sign-extending,
-    // and a high-bit i64 offset must round-trip through the signed
-    // attribute unchanged.
-    std::optional<uint64_t> offsetZExt = offset->getValue().tryZExtValue();
-    std::optional<uint64_t> sizeZExt = size->getValue().tryZExtValue();
-    if (!offsetZExt || !sizeZExt)
+    // Offsets and sizes are uint64_t in the attribute; values that do not
+    // fit in 64 bits cannot be represented, and extracting them would
+    // assert. Read them unsigned: LLVM compares offsets zero-extended, so
+    // a narrow constant with its high bit set (e.g. i32 0x80000000) must
+    // keep its unsigned value rather than sign-extending.
+    std::optional<uint64_t> offsetValue = offset->getValue().tryZExtValue();
+    std::optional<uint64_t> sizeValue = size->getValue().tryZExtValue();
+    if (!offsetValue || !sizeValue)
       return {};
-    int64_t offsetValue = static_cast<int64_t>(*offsetZExt);
-    int64_t sizeValue = static_cast<int64_t>(*sizeZExt);
     auto *tagNode = dyn_cast_if_present<llvm::MDNode>(node->getOperand(i + 2));
     if (!tagNode)
       return {};
@@ -609,7 +605,7 @@ Attribute ModuleImport::convertTBAAStructMetadata(const llvm::MDNode *node) {
     if (!tag)
       return {};
     fields.push_back(
-        builder.getAttr<TBAAStructFieldAttr>(offsetValue, sizeValue, tag));
+        builder.getAttr<TBAAStructFieldAttr>(*offsetValue, *sizeValue, tag));
   }
 
   return builder.getArrayAttr(fields);
diff --git a/mlir/lib/Target/LLVMIR/ModuleTranslation.cpp b/mlir/lib/Target/LLVMIR/ModuleTranslation.cpp
index 130f2cad5719b3..4b6a1c0eb45ab6 100644
--- a/mlir/lib/Target/LLVMIR/ModuleTranslation.cpp
+++ b/mlir/lib/Target/LLVMIR/ModuleTranslation.cpp
@@ -2429,8 +2429,7 @@ void ModuleTranslation::setTBAAStructMetadata(ArrayAttr fields,
   structFields.reserve(fields.size());
   for (Attribute field : fields) {
     auto fieldAttr = cast<TBAAStructFieldAttr>(field);
-    structFields.emplace_back(static_cast<uint64_t>(fieldAttr.getOffset()),
-                              static_cast<uint64_t>(fieldAttr.getSize()),
+    structFields.emplace_back(fieldAttr.getOffset(), fieldAttr.getSize(),
                               getTBAANode(fieldAttr.getTag()));
   }
   inst->setMetadata(
diff --git a/mlir/test/Target/LLVMIR/Import/metadata-tbaa-struct.ll b/mlir/test/Target/LLVMIR/Import/metadata-tbaa-struct.ll
index 89a753009d1731..1ed2df33a47987 100644
--- a/mlir/test/Target/LLVMIR/Import/metadata-tbaa-struct.ll
+++ b/mlir/test/Target/LLVMIR/Import/metadata-tbaa-struct.ll
@@ -19,7 +19,7 @@ declare void @llvm.memcpy.inline.p0.p0.i64(ptr, ptr, i64, i1)
 ; CHECK-DAG: #[[F0:.*]] = #llvm.tbaa_struct_field<offset = 0, size = 4, tag = #[[TI]]>
 ; CHECK-DAG: #[[F1:.*]] = #llvm.tbaa_struct_field<offset = 8, size = 4, tag = #[[TF]]>
 ; CHECK-DAG: #[[F2:.*]] = #llvm.tbaa_struct_field<offset = 2147483648, size = 4, tag = #[[TI]]>
-; CHECK-DAG: #[[F3:.*]] = #llvm.tbaa_struct_field<offset = -1, size = 4, tag = #[[TI]]>
+; CHECK-DAG: #[[F3:.*]] = #llvm.tbaa_struct_field<offset = 18446744073709551615, size = 4, tag = #[[TI]]>
 ; CHECK-DAG: #[[F4:.*]] = #llvm.tbaa_struct_field<offset = 0, size = 2147483648, tag = #[[TI]]>
 ; CHECK: llvm.intr.memcpy
 ; CHECK-SAME: tbaa_struct = [#[[F0]], #[[F1]]]
@@ -54,8 +54,8 @@ define void @narrow_offset(ptr %d, ptr %s) {
 
 !8 = !{ i32 2147483648, i64 4, !6 }
 
-; A high-bit i64 offset keeps its bits through the signed attribute; it is
-; not dropped as unrepresentable.
+; A high-bit i64 offset keeps its full unsigned value; it is not dropped
+; as unrepresentable.
 ; CHECK: llvm.intr.memcpy
 ; CHECK-SAME: tbaa_struct = [#[[F3]]]
 define void @high_bit_offset(ptr %d, ptr %s) {

>From 458322956693d5ca96fe3707e3d60781a923cf35 Mon Sep 17 00:00:00 2001
From: Bruno Cardoso Lopes <bruno.cardoso at gmail.com>
Date: Thu, 5 Nov 2026 18:40:42 -0800
Subject: [PATCH 08/11] Address review: TBAAStructOpInterface for tbaa.struct

Add an interface for operations carrying tbaa.struct metadata, like
AliasAnalysisOpInterface: accessors, and verification of the
non-decreasing-offset rule through the interface verify hook. The
three aggregate-copy ops implement it via their traits; the per-op
verify methods go away, and the import and export walks dispatch
through the interface instead of naming the three ops.
---
 .../mlir/Dialect/LLVMIR/LLVMInterfaces.h      |  4 ++
 .../mlir/Dialect/LLVMIR/LLVMInterfaces.td     | 37 +++++++++++++++++++
 .../mlir/Dialect/LLVMIR/LLVMIntrinsicOps.td   | 16 +++-----
 .../include/mlir/Dialect/LLVMIR/LLVMOpBase.td |  5 ++-
 mlir/lib/Dialect/LLVMIR/IR/LLVMDialect.cpp    | 29 ---------------
 mlir/lib/Dialect/LLVMIR/IR/LLVMInterfaces.cpp | 26 +++++++++++++
 .../LLVMIR/LLVMIRToLLVMTranslation.cpp        | 12 +++---
 mlir/lib/Target/LLVMIR/ModuleTranslation.cpp  |  9 +----
 8 files changed, 84 insertions(+), 54 deletions(-)

diff --git a/mlir/include/mlir/Dialect/LLVMIR/LLVMInterfaces.h b/mlir/include/mlir/Dialect/LLVMIR/LLVMInterfaces.h
index 0b8c254eb5e3a9..ed90002d4dfa8f 100644
--- a/mlir/include/mlir/Dialect/LLVMIR/LLVMInterfaces.h
+++ b/mlir/include/mlir/Dialect/LLVMIR/LLVMInterfaces.h
@@ -33,6 +33,10 @@ LogicalResult verifyAccessGroupOpInterface(Operation *op);
 /// the alias analysis interface.
 LogicalResult verifyAliasAnalysisOpInterface(Operation *op);
 
+/// Verifies that the tbaa.struct field offsets of memory operations that
+/// implement the tbaa.struct interface are non-decreasing.
+LogicalResult verifyTBAAStructOpInterface(Operation *op);
+
 /// Verifies that the operation implementing the dereferenceable interface has
 /// exactly one result of LLVM pointer type.
 LogicalResult verifyDereferenceableOpInterface(Operation *op);
diff --git a/mlir/include/mlir/Dialect/LLVMIR/LLVMInterfaces.td b/mlir/include/mlir/Dialect/LLVMIR/LLVMInterfaces.td
index 1e671ce42fbd28..7def8d7b531a2c 100644
--- a/mlir/include/mlir/Dialect/LLVMIR/LLVMInterfaces.td
+++ b/mlir/include/mlir/Dialect/LLVMIR/LLVMInterfaces.td
@@ -306,6 +306,43 @@ def AliasAnalysisOpInterface : OpInterface<"AliasAnalysisOpInterface"> {
   ];
 }
 
+def TBAAStructOpInterface : OpInterface<"TBAAStructOpInterface"> {
+  let description = [{
+    An interface for memory operations that can carry tbaa.struct metadata.
+    It provides setters and getters for the operation's tbaa.struct
+    attribute. The default implementations of the interface methods expect
+    the operation to have an attribute of type ArrayAttr named tbaa_struct.
+  }];
+
+  let cppNamespace = "::mlir::LLVM";
+  let verify = [{ return detail::verifyTBAAStructOpInterface($_op); }];
+
+  let methods = [
+    InterfaceMethod<
+      /*desc=*/        "Returns the tbaa.struct attribute or nullptr",
+      /*returnType=*/  "::mlir::ArrayAttr",
+      /*methodName=*/  "getTBAAStructOrNull",
+      /*args=*/        (ins),
+      /*methodBody=*/  [{}],
+      /*defaultImpl=*/ [{
+        auto op = cast<ConcreteOp>(this->getOperation());
+        return op.getTbaaStructAttr();
+      }]
+      >,
+    InterfaceMethod<
+      /*desc=*/        "Sets the tbaa.struct attribute",
+      /*returnType=*/  "void",
+      /*methodName=*/  "setTBAAStruct",
+      /*args=*/        (ins "const ::mlir::ArrayAttr":$attr),
+      /*methodBody=*/  [{}],
+      /*defaultImpl=*/ [{
+        auto op = cast<ConcreteOp>(this->getOperation());
+        op.setTbaaStructAttr(attr);
+      }]
+      >,
+  ];
+}
+
 def DereferenceableOpInterface : OpInterface<"DereferenceableOpInterface"> {
   let description = [{
     An interface for memory operations that can carry dereferenceable metadata.
diff --git a/mlir/include/mlir/Dialect/LLVMIR/LLVMIntrinsicOps.td b/mlir/include/mlir/Dialect/LLVMIR/LLVMIntrinsicOps.td
index a36db9601c8775..0e9d3830643504 100644
--- a/mlir/include/mlir/Dialect/LLVMIR/LLVMIntrinsicOps.td
+++ b/mlir/include/mlir/Dialect/LLVMIR/LLVMIntrinsicOps.td
@@ -259,7 +259,8 @@ class LLVM_MemcpyIntrOpBase<string name> :
     LLVM_ZeroResultIntrOp<name, [0, 1, 2],
     [DeclareOpInterfaceMethods<PromotableMemOpInterface>,
      DeclareOpInterfaceMethods<DestructurableAccessorOpInterface>,
-     DeclareOpInterfaceMethods<SafeMemorySlotAccessOpInterface>],
+     DeclareOpInterfaceMethods<SafeMemorySlotAccessOpInterface>,
+     DeclareOpInterfaceMethods<TBAAStructOpInterface>],
     /*requiresAccessGroup=*/1, /*requiresAliasAnalysis=*/1,
     /*requiresArgAndResultAttrs=*/1, /*requiresOpBundles=*/0,
     /*immArgPositions=*/[3], /*immArgAttrNames=*/["isVolatile"]> {
@@ -293,18 +294,15 @@ class LLVM_MemcpyIntrOpBase<string name> :
       # baseLlvmBuilderArgAndResultAttrs # baseLlvmBuilderCoda;
 }
 
-def LLVM_MemcpyOp : LLVM_MemcpyIntrOpBase<"memcpy"> {
-  let hasVerifier = 1;
-}
-def LLVM_MemmoveOp : LLVM_MemcpyIntrOpBase<"memmove"> {
-  let hasVerifier = 1;
-}
+def LLVM_MemcpyOp : LLVM_MemcpyIntrOpBase<"memcpy">;
+def LLVM_MemmoveOp : LLVM_MemcpyIntrOpBase<"memmove">;
 
 def LLVM_MemcpyInlineOp :
     LLVM_ZeroResultIntrOp<"memcpy.inline", [0, 1, 2],
     [DeclareOpInterfaceMethods<PromotableMemOpInterface>,
      DeclareOpInterfaceMethods<DestructurableAccessorOpInterface>,
-     DeclareOpInterfaceMethods<SafeMemorySlotAccessOpInterface>],
+     DeclareOpInterfaceMethods<SafeMemorySlotAccessOpInterface>,
+     DeclareOpInterfaceMethods<TBAAStructOpInterface>],
     /*requiresAccessGroup=*/1, /*requiresAliasAnalysis=*/1,
     /*requiresArgAndResultAttrs=*/1, /*requiresOpBundles=*/0,
     /*immArgPositions=*/[2, 3], /*immArgAttrNames=*/["len", "isVolatile"]> {
@@ -334,8 +332,6 @@ def LLVM_MemcpyInlineOp :
   let llvmBuilder = baseLlvmBuilder # setAccessGroupsMetadataCode
       # setAliasAnalysisMetadataCode # setTBAAStructMetadataCode
       # baseLlvmBuilderArgAndResultAttrs # baseLlvmBuilderCoda;
-
-  let hasVerifier = 1;
 }
 
 def LLVM_MemsetOp : LLVM_ZeroResultIntrOp<"memset", [0, 2],
diff --git a/mlir/include/mlir/Dialect/LLVMIR/LLVMOpBase.td b/mlir/include/mlir/Dialect/LLVMIR/LLVMOpBase.td
index 43856f686c12f3..8a6695f64e90b5 100644
--- a/mlir/include/mlir/Dialect/LLVMIR/LLVMOpBase.td
+++ b/mlir/include/mlir/Dialect/LLVMIR/LLVMOpBase.td
@@ -345,7 +345,10 @@ class LLVM_IntrOpBase<Dialect dialect, string opName, string enumName,
   // Set with `let` by intrinsics carrying tbaa.struct metadata, like the
   // aggregate-copy intrinsics. It is a plain field rather than a
   // constructor argument so that enabling it does not shift the
-  // positional flag arguments of every intrinsic definition.
+  // positional flag arguments of every intrinsic definition. Ops setting
+  // it must also add DeclareOpInterfaceMethods<TBAAStructOpInterface>
+  // to their traits: the flag only wires the argument, the trait
+  // attaches the verification and accessors.
   bit requiresTBAAStruct = 0;
   dag baseArgs = !con(
         !if(!gt(requiresAccessGroup, 0),
diff --git a/mlir/lib/Dialect/LLVMIR/IR/LLVMDialect.cpp b/mlir/lib/Dialect/LLVMIR/IR/LLVMDialect.cpp
index 92dc62e7044dad..ce020fd50a1aeb 100644
--- a/mlir/lib/Dialect/LLVMIR/IR/LLVMDialect.cpp
+++ b/mlir/lib/Dialect/LLVMIR/IR/LLVMDialect.cpp
@@ -451,35 +451,6 @@ LogicalResult AllocaOp::verify() {
   return success();
 }
 
-// tbaa.struct field offsets must be non-decreasing, matching LLVM's verifier
-// rule. Compare unsigned: LLVM zero-extends the offsets before comparing.
-static LogicalResult verifyTBAAStructFieldOffsets(Operation *op,
-                                                  ArrayAttr fields) {
-  if (!fields)
-    return success();
-  std::optional<uint64_t> prevOffset;
-  for (Attribute field : fields) {
-    uint64_t offset = cast<TBAAStructFieldAttr>(field).getOffset();
-    if (prevOffset && offset < *prevOffset)
-      return op->emitOpError(
-          "tbaa.struct field offsets must be non-decreasing");
-    prevOffset = offset;
-  }
-  return success();
-}
-
-LogicalResult MemcpyOp::verify() {
-  return verifyTBAAStructFieldOffsets(getOperation(), getTbaaStructAttr());
-}
-
-LogicalResult MemmoveOp::verify() {
-  return verifyTBAAStructFieldOffsets(getOperation(), getTbaaStructAttr());
-}
-
-LogicalResult MemcpyInlineOp::verify() {
-  return verifyTBAAStructFieldOffsets(getOperation(), getTbaaStructAttr());
-}
-
 LogicalResult AllocaOp::canonicalize(AllocaOp op, PatternRewriter &rewriter) {
   // Convert `alloca Ty, C` to the canonical `alloca [C x Ty], 1` form.
   APInt numElements;
diff --git a/mlir/lib/Dialect/LLVMIR/IR/LLVMInterfaces.cpp b/mlir/lib/Dialect/LLVMIR/IR/LLVMInterfaces.cpp
index 7d5a86d6740af5..25954ecd7a6127 100644
--- a/mlir/lib/Dialect/LLVMIR/IR/LLVMInterfaces.cpp
+++ b/mlir/lib/Dialect/LLVMIR/IR/LLVMInterfaces.cpp
@@ -64,6 +64,32 @@ mlir::LLVM::detail::verifyAliasAnalysisOpInterface(Operation *op) {
   return isArrayOf<TBAATagAttr>(op, tags);
 }
 
+//===----------------------------------------------------------------------===//
+// TBAAStructOpInterface
+//===----------------------------------------------------------------------===//
+
+LogicalResult mlir::LLVM::detail::verifyTBAAStructOpInterface(Operation *op) {
+  auto iface = cast<TBAAStructOpInterface>(op);
+  ArrayAttr fields = iface.getTBAAStructOrNull();
+  if (!fields)
+    return success();
+
+  if (failed(isArrayOf<TBAAStructFieldAttr>(op, fields)))
+    return failure();
+
+  // Field offsets must be non-decreasing, matching LLVM's verifier rule.
+  // Compare unsigned: LLVM zero-extends the offsets before comparing.
+  std::optional<uint64_t> prevOffset;
+  for (Attribute field : fields) {
+    uint64_t offset = cast<TBAAStructFieldAttr>(field).getOffset();
+    if (prevOffset && offset < *prevOffset)
+      return op->emitOpError(
+          "tbaa.struct field offsets must be non-decreasing");
+    prevOffset = offset;
+  }
+  return success();
+}
+
 //===----------------------------------------------------------------------===//
 // DereferenceableOpInterface
 //===----------------------------------------------------------------------===//
diff --git a/mlir/lib/Target/LLVMIR/Dialect/LLVMIR/LLVMIRToLLVMTranslation.cpp b/mlir/lib/Target/LLVMIR/Dialect/LLVMIR/LLVMIRToLLVMTranslation.cpp
index f0947a69f6012b..51d9449644ca31 100644
--- a/mlir/lib/Target/LLVMIR/Dialect/LLVMIR/LLVMIRToLLVMTranslation.cpp
+++ b/mlir/lib/Target/LLVMIR/Dialect/LLVMIR/LLVMIRToLLVMTranslation.cpp
@@ -226,13 +226,11 @@ static LogicalResult setTBAAStructAttr(const llvm::MDNode *node, Operation *op,
   if (!fields)
     return failure();
 
-  return TypeSwitch<Operation *, LogicalResult>(op)
-      .Case<LLVM::MemcpyOp, LLVM::MemcpyInlineOp, LLVM::MemmoveOp>(
-          [&](auto copyOp) {
-            copyOp.setTbaaStructAttr(fields);
-            return success();
-          })
-      .Default([](auto) { return failure(); });
+  auto iface = dyn_cast<TBAAStructOpInterface>(op);
+  if (!iface)
+    return failure();
+  iface.setTBAAStruct(fields);
+  return success();
 }
 
 /// Looks up all the access group attributes that map to the access group nodes
diff --git a/mlir/lib/Target/LLVMIR/ModuleTranslation.cpp b/mlir/lib/Target/LLVMIR/ModuleTranslation.cpp
index 4b6a1c0eb45ab6..391b4b5c0899c5 100644
--- a/mlir/lib/Target/LLVMIR/ModuleTranslation.cpp
+++ b/mlir/lib/Target/LLVMIR/ModuleTranslation.cpp
@@ -2531,13 +2531,8 @@ LogicalResult ModuleTranslation::createTBAAMetadata() {
     if (fields)
       walker.walk(fields);
   };
-  mlirModule->walk([&](Operation *op) {
-    if (auto copyOp = dyn_cast<LLVM::MemcpyOp>(op))
-      walkStructFields(copyOp.getTbaaStructAttr());
-    else if (auto copyOp = dyn_cast<LLVM::MemcpyInlineOp>(op))
-      walkStructFields(copyOp.getTbaaStructAttr());
-    else if (auto copyOp = dyn_cast<LLVM::MemmoveOp>(op))
-      walkStructFields(copyOp.getTbaaStructAttr());
+  mlirModule->walk([&](TBAAStructOpInterface tbaaStructOp) {
+    walkStructFields(tbaaStructOp.getTBAAStructOrNull());
   });
 
   return success();

>From 2a0a05a18bd11cd3fdb705533497766e356f2549 Mon Sep 17 00:00:00 2001
From: Bruno Cardoso Lopes <bruno.cardoso at gmail.com>
Date: Thu, 5 Nov 2026 18:40:42 -0800
Subject: [PATCH 09/11] Address review: stash APInts for tbaa.struct offsets
 and sizes

Read imported offsets and sizes as APInts, declining values that
use more than 64 active bits and zero-extending the rest. This keeps
narrow high-bit constants unsigned and high-bit i64 offsets intact
without the uint64_t temporaries and casts.
---
 mlir/lib/Target/LLVMIR/ModuleImport.cpp | 20 ++++++++++----------
 1 file changed, 10 insertions(+), 10 deletions(-)

diff --git a/mlir/lib/Target/LLVMIR/ModuleImport.cpp b/mlir/lib/Target/LLVMIR/ModuleImport.cpp
index cbfd19b2b3229e..3dc8d9ce961636 100644
--- a/mlir/lib/Target/LLVMIR/ModuleImport.cpp
+++ b/mlir/lib/Target/LLVMIR/ModuleImport.cpp
@@ -589,14 +589,14 @@ Attribute ModuleImport::convertTBAAStructMetadata(const llvm::MDNode *node) {
         node->getOperand(i + 1));
     if (!offset || !size)
       return {};
-    // Offsets and sizes are uint64_t in the attribute; values that do not
-    // fit in 64 bits cannot be represented, and extracting them would
-    // assert. Read them unsigned: LLVM compares offsets zero-extended, so
-    // a narrow constant with its high bit set (e.g. i32 0x80000000) must
-    // keep its unsigned value rather than sign-extending.
-    std::optional<uint64_t> offsetValue = offset->getValue().tryZExtValue();
-    std::optional<uint64_t> sizeValue = size->getValue().tryZExtValue();
-    if (!offsetValue || !sizeValue)
+    // Offsets and sizes are uint64_t in the attribute. Read them as APInts:
+    // LLVM compares offsets zero-extended, so a narrow constant with its
+    // high bit set (e.g. i32 0x80000000) must keep its unsigned value
+    // rather than sign-extending. Values using more than 64 bits cannot
+    // be represented and are declined.
+    const APInt &offsetAP = offset->getValue();
+    const APInt &sizeAP = size->getValue();
+    if (offsetAP.getActiveBits() > 64 || sizeAP.getActiveBits() > 64)
       return {};
     auto *tagNode = dyn_cast_if_present<llvm::MDNode>(node->getOperand(i + 2));
     if (!tagNode)
@@ -604,8 +604,8 @@ Attribute ModuleImport::convertTBAAStructMetadata(const llvm::MDNode *node) {
     auto tag = dyn_cast_if_present<TBAATagAttr>(lookupTBAAAttr(tagNode));
     if (!tag)
       return {};
-    fields.push_back(
-        builder.getAttr<TBAAStructFieldAttr>(*offsetValue, *sizeValue, tag));
+    fields.push_back(builder.getAttr<TBAAStructFieldAttr>(
+        offsetAP.getZExtValue(), sizeAP.getZExtValue(), tag));
   }
 
   return builder.getArrayAttr(fields);

>From daba5bd32cf3af57f223e3b1cc6ea80307a2f73f Mon Sep 17 00:00:00 2001
From: Bruno Cardoso Lopes <bruno.cardoso at gmail.com>
Date: Fri, 6 Nov 2026 10:19:28 -0800
Subject: [PATCH 10/11] Address review: check tbaa.struct shape before walking
 tags

Check the operand count is a multiple of three before walking a tbaa.struct node's tags. The conversion keeps the only copy of the shape rule, and attach-time behavior is unchanged.
---
 mlir/lib/Target/LLVMIR/ModuleImport.cpp | 16 +++++++++++-----
 1 file changed, 11 insertions(+), 5 deletions(-)

diff --git a/mlir/lib/Target/LLVMIR/ModuleImport.cpp b/mlir/lib/Target/LLVMIR/ModuleImport.cpp
index 3dc8d9ce961636..42c1c8f584f237 100644
--- a/mlir/lib/Target/LLVMIR/ModuleImport.cpp
+++ b/mlir/lib/Target/LLVMIR/ModuleImport.cpp
@@ -1211,11 +1211,17 @@ LogicalResult ModuleImport::convertMetadata() {
       // conversion below finds nothing and the node is declined.
       if (aliasAnalysisNodes.TBAAStruct) {
         const llvm::MDNode *structNode = aliasAnalysisNodes.TBAAStruct;
-        for (unsigned i = 2, e = structNode->getNumOperands(); i < e; i += 3)
-          if (auto *tag =
-                  dyn_cast_if_present<llvm::MDNode>(structNode->getOperand(i)))
-            if (failed(processTBAAMetadata(tag)))
-              return failure();
+        // Operands come in groups of three: check the count before
+        // walking the tags. The verifier rejects malformed nodes
+        // before CLI import, so this guards direct API use.
+        bool wellFormed = structNode->getNumOperands() % 3 == 0;
+        if (wellFormed) {
+          for (unsigned i = 2, e = structNode->getNumOperands(); i < e; i += 3)
+            if (auto *tag = dyn_cast_if_present<llvm::MDNode>(
+                    structNode->getOperand(i)))
+              if (failed(processTBAAMetadata(tag)))
+                return failure();
+        }
         // Convert the struct node itself once its tags are in the map. A
         // node that cannot be modeled is recorded with a null value so it
         // is not converted again for every instruction carrying it, and is

>From be418e208f571c0bcaf7965052993bd50ec7acac Mon Sep 17 00:00:00 2001
From: Bruno Cardoso Lopes <bruno.cardoso at gmail.com>
Date: Fri, 6 Nov 2026 10:50:52 -0800
Subject: [PATCH 11/11] Address review: append tbaa_struct directly in the
 memory intrinsic base class

Remove the requiresTBAAStruct flag mechanism and append the tbaa_struct argument directly to LLVM_MemcpyIntrOpBase and LLVM_MemcpyInlineOp, with the builder nullptrs reordered to match. Accessors and the verifier read the attribute by name, so behavior is unchanged.
---
 .../CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp  | 11 ++++++-----
 .../mlir/Dialect/LLVMIR/LLVMIntrinsicOps.td    | 12 ++++++------
 mlir/include/mlir/Dialect/LLVMIR/LLVMOpBase.td | 18 +-----------------
 .../LLVMIR/Transforms/InlinerInterfaceImpl.cpp |  4 ++--
 4 files changed, 15 insertions(+), 30 deletions(-)

diff --git a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
index aac6ab024f4c86..e18b7a7030a656 100644
--- a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
+++ b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
@@ -401,8 +401,8 @@ mlir::LogicalResult CIRToLLVMCopyOpLowering::matchAndRewrite(
 
   rewriter.replaceOpWithNewOp<mlir::LLVM::MemcpyOp>(
       op, adaptor.getDst(), adaptor.getSrc(), length, op.getIsVolatile(),
-      /*access_groups=*/nullptr, /*alias_scopes=*/nullptr,
-      /*noalias_scopes=*/nullptr, /*tbaa=*/nullptr, /*tbaa_struct=*/nullptr,
+      /*tbaa_struct=*/nullptr, /*access_groups=*/nullptr,
+      /*alias_scopes=*/nullptr, /*noalias_scopes=*/nullptr, /*tbaa=*/nullptr,
       /*arg_attrs=*/argAttrs, /*res_attrs=*/nullptr);
   return mlir::success();
 }
@@ -426,9 +426,10 @@ lowerMemTransferOp(CIROp op, typename CIROp::Adaptor adaptor,
   }
   rewriter.replaceOpWithNewOp<LLVMOp>(
       op, adaptor.getDst(), adaptor.getSrc(), adaptor.getLen(),
-      /*isVolatile=*/false, /*access_groups=*/nullptr,
-      /*alias_scopes=*/nullptr, /*noalias_scopes=*/nullptr, /*tbaa=*/nullptr,
-      /*tbaa_struct=*/nullptr, /*arg_attrs=*/argAttrs, /*res_attrs=*/nullptr);
+      /*isVolatile=*/false, /*tbaa_struct=*/nullptr,
+      /*access_groups=*/nullptr, /*alias_scopes=*/nullptr,
+      /*noalias_scopes=*/nullptr, /*tbaa=*/nullptr, /*arg_attrs=*/argAttrs,
+      /*res_attrs=*/nullptr);
   return mlir::success();
 }
 
diff --git a/mlir/include/mlir/Dialect/LLVMIR/LLVMIntrinsicOps.td b/mlir/include/mlir/Dialect/LLVMIR/LLVMIntrinsicOps.td
index 0e9d3830643504..80f791d091624e 100644
--- a/mlir/include/mlir/Dialect/LLVMIR/LLVMIntrinsicOps.td
+++ b/mlir/include/mlir/Dialect/LLVMIR/LLVMIntrinsicOps.td
@@ -264,10 +264,10 @@ class LLVM_MemcpyIntrOpBase<string name> :
     /*requiresAccessGroup=*/1, /*requiresAliasAnalysis=*/1,
     /*requiresArgAndResultAttrs=*/1, /*requiresOpBundles=*/0,
     /*immArgPositions=*/[3], /*immArgAttrNames=*/["isVolatile"]> {
-  let requiresTBAAStruct = 1;
   dag args = (ins Arg<LLVM_AnyPointer,"",[MemWrite]>:$dst,
                   Arg<LLVM_AnyPointer,"",[MemRead]>:$src,
-                  AnySignlessInteger:$len, I1Attr:$isVolatile);
+                  AnySignlessInteger:$len, I1Attr:$isVolatile,
+                  OptionalAttr<LLVM_TBAAStructFieldArrayAttr>:$tbaa_struct);
   // Append the arguments defined by LLVM_IntrOpBase.
   let arguments = !con(args, baseArgs);
   let builders = [
@@ -279,9 +279,9 @@ class LLVM_MemcpyIntrOpBase<string name> :
     OpBuilder<(ins "Value":$dst, "Value":$src, "Value":$len,
                    "IntegerAttr":$isVolatile), [{
       build($_builder, $_state, dst, src, len, isVolatile,
+            /*tbaa_struct=*/nullptr,
             /*access_groups=*/nullptr, /*alias_scopes=*/nullptr,
             /*noalias_scopes=*/nullptr, /*tbaa=*/nullptr,
-            /*tbaa_struct=*/nullptr,
             /*arg_attrs=*/nullptr, /*res_attrs=*/nullptr);
     }]>
   ];
@@ -306,10 +306,10 @@ def LLVM_MemcpyInlineOp :
     /*requiresAccessGroup=*/1, /*requiresAliasAnalysis=*/1,
     /*requiresArgAndResultAttrs=*/1, /*requiresOpBundles=*/0,
     /*immArgPositions=*/[2, 3], /*immArgAttrNames=*/["len", "isVolatile"]> {
-  let requiresTBAAStruct = 1;
   dag args = (ins Arg<LLVM_AnyPointer,"",[MemWrite]>:$dst,
                   Arg<LLVM_AnyPointer,"",[MemRead]>:$src,
-                  APIntAttr:$len, I1Attr:$isVolatile);
+                  APIntAttr:$len, I1Attr:$isVolatile,
+                  OptionalAttr<LLVM_TBAAStructFieldArrayAttr>:$tbaa_struct);
   // Append the arguments defined by LLVM_IntrOpBase.
   let arguments = !con(args, baseArgs);
   let builders = [
@@ -321,9 +321,9 @@ def LLVM_MemcpyInlineOp :
     OpBuilder<(ins "Value":$dst, "Value":$src, "IntegerAttr":$len,
                    "IntegerAttr":$isVolatile), [{
       build($_builder, $_state, dst, src, len, isVolatile,
+            /*tbaa_struct=*/nullptr,
             /*access_groups=*/nullptr, /*alias_scopes=*/nullptr,
             /*noalias_scopes=*/nullptr, /*tbaa=*/nullptr,
-            /*tbaa_struct=*/nullptr,
             /*arg_attrs=*/nullptr, /*res_attrs=*/nullptr);
     }]>
   ];
diff --git a/mlir/include/mlir/Dialect/LLVMIR/LLVMOpBase.td b/mlir/include/mlir/Dialect/LLVMIR/LLVMOpBase.td
index 8a6695f64e90b5..66583a592b3f64 100644
--- a/mlir/include/mlir/Dialect/LLVMIR/LLVMOpBase.td
+++ b/mlir/include/mlir/Dialect/LLVMIR/LLVMOpBase.td
@@ -310,12 +310,7 @@ class LLVM_MemAccessOpBase<string mnemonic, list<Trait> traits = []> :
 // interfaces the intrinsic implements. When a flag is set, the "baseArgs"
 // list includes the arguments required by the corresponding interface.
 // Derived intrinsics must append "baseArgs" to their argument list if they
-// enable any of these flags. "requiresTBAAStruct" is not tied to an
-// interface: it adds the tbaa_struct argument after tbaa (when present),
-// for the aggregate-copy intrinsics only. It is set with `let` by those
-// intrinsics. It only wires the argument; the export, import, and
-// verifier sites name those three ops directly, so a future op setting
-// the flag also needs handling there.
+// enable any of these flags.
 //
 // LLVM `immargs` can be represented as MLIR attributes by providing both
 // the `immArgPositions` and `immArgAttrNames` lists. These two lists should
@@ -342,14 +337,6 @@ class LLVM_IntrOpBase<Dialect dialect, string opName, string enumName,
         traits)>,
       LLVM_MemOpPatterns,
       Results<!if(!gt(numResults, 0), (outs LLVM_Type:$res), (outs))> {
-  // Set with `let` by intrinsics carrying tbaa.struct metadata, like the
-  // aggregate-copy intrinsics. It is a plain field rather than a
-  // constructor argument so that enabling it does not shift the
-  // positional flag arguments of every intrinsic definition. Ops setting
-  // it must also add DeclareOpInterfaceMethods<TBAAStructOpInterface>
-  // to their traits: the flag only wires the argument, the trait
-  // attaches the verification and accessors.
-  bit requiresTBAAStruct = 0;
   dag baseArgs = !con(
         !if(!gt(requiresAccessGroup, 0),
             (ins OptionalAttr<LLVM_AccessGroupArrayAttr>:$access_groups),
@@ -359,9 +346,6 @@ class LLVM_IntrOpBase<Dialect dialect, string opName, string enumName,
                  OptionalAttr<LLVM_AliasScopeArrayAttr>:$noalias_scopes,
                  OptionalAttr<LLVM_TBAATagArrayAttr>:$tbaa),
             (ins )),
-        !if(!gt(requiresTBAAStruct, 0),
-            (ins OptionalAttr<LLVM_TBAAStructFieldArrayAttr>:$tbaa_struct),
-            (ins )),
         !if(!gt(requiresArgAndResultAttrs, 0),
             (ins OptionalAttr<DictArrayAttr>:$arg_attrs,
                  OptionalAttr<DictArrayAttr>:$res_attrs),
diff --git a/mlir/lib/Dialect/LLVMIR/Transforms/InlinerInterfaceImpl.cpp b/mlir/lib/Dialect/LLVMIR/Transforms/InlinerInterfaceImpl.cpp
index b2296917545f55..e4d91d347e8c6b 100644
--- a/mlir/lib/Dialect/LLVMIR/Transforms/InlinerInterfaceImpl.cpp
+++ b/mlir/lib/Dialect/LLVMIR/Transforms/InlinerInterfaceImpl.cpp
@@ -716,9 +716,9 @@ static Value handleByValArgumentInit(OpBuilder &builder, Location loc,
       builder.getArrayAttr({builder.getDictionaryAttr({dstAlignAttr})});
   LLVM::MemcpyOp::create(builder, loc, allocaOp, argument, copySize,
                          /*isVolatile=*/false,
+                         /*tbaa_struct=*/nullptr,
                          /*access_groups=*/nullptr, /*alias_scopes=*/nullptr,
-                         /*noalias_scopes=*/nullptr, /*tbaa=*/nullptr,
-                         /*tbaa_struct=*/nullptr, argAttrs,
+                         /*noalias_scopes=*/nullptr, /*tbaa=*/nullptr, argAttrs,
                          /*res_attrs=*/nullptr);
   return allocaOp;
 }



More information about the cfe-commits mailing list