← Back to Pull requests

[mlir] Reland SymbolUserTypeInterface with verification proportional to participating IR #212354

Open
jaredhoberock opened this pull request with 764 lines diff across 14 files
View on GitHub
jaredhoberock jaredhoberock commented on Jul 27, 2026 21:51 UTC
Author

This PR now also relands SymbolUserTypeInterface (#198435), reverted in #217959 pending verification cost mitigation.

Motivation: #198435 made the SymbolTable verifier walk every op's types and full attribute dictionary per pass; @ehein6 measured 14.1s -> 26.1s on a real pipeline with zero participating types (#212160).

On a synthetic reproduction (8000 functions, big dictionaries, 40 passes) this patch takes this pipeline from 8.75s to 1.77s. This PR composes with, and does not subsume, the registration-level skip proposed in #212160.

Whether an attribute or type contains a SymbolRefAttr is a fixed fact of that object, so we can compute it once and consult it to avoid pointless traversal during SymbolTable verification.

This PR keeps that fact in a set inside MLIRContext holding the types and attributes proven to contain no SymbolRefAttr. Membership in the set lets the symbol-use walk prune; everything else is walked and left unrecorded. "Everything else" includes objects with mutable storage, which must be treated conservatively. The set fills lazily as verification encounters objects.

This solution uses the same concurrency discipline as the lazily-grown OperationName map, with one difference forced by the non-reentrant mutex: a fill computes its answer before taking the writer lock, so racing duplicate fills are idempotent. Since #217320's transient scopes free storage interned during the scope and may cause recycled addresses, the cache is cleared when a transient scope ends.

Additionally:
1. One walker with one deduped visited set is hoisted once per SymbolTable scope so that the attributes & types which do get traversed get traversed at most once per symbol table scope, rather than once per operation they appear on.
2. Avoid materializing a DictionaryAttr value when checking an operation's attributes & properties.

One semantic change: the contract on SymbolUserTypeInterface now requires that the symbols an implementation references be spelled as SymbolRefAttr sub-elements. So, a use is a structural fact about a type. An implementation that references symbols in some other encoding (e.g., a string) is treated as referencing no symbols and may no longer have verifySymbolUses invoked. SymbolUserAttrInterface's contract and behavior are unchanged.

Other than tightening the contract on SymbolUserTypeInterface, the set of things verified against each symbol table scope is unchanged. This PR just removes all the pointless traversal.

Assisted-by: Claude Code (Anthropic)

Diff: 764 lines (+744 / -20) across 14 files Reviewer: joker-eph Review duration: 187304m
All Vouch review confidence checks passed
Residual risk 0.08 = Change Risk (0.69) × (1 − Review Confidence (0.89)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.69 · 764 lines diff across 14 files
0.69
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.89 · 5 substantive comment(s)
0.89
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
88%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.397
Real PR Conversation Timeline
32 items
llvmorg-github-actions[bot] llvmorg-github-actions[bot] commented on Jul 27, 2026 21:52 UTC
Bot

<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-mlir-core

@llvm/pr-subscribers-mlir-ods

Author: Jared Hoberock (jaredhoberock)

<details>
<summary>Changes</summary>

Motivation: #<!-- -->198435 made the SymbolTable verifier walk every op's types and full attribute dictionary per pass; @<!-- -->ehein6 measured 14.1s -&gt; 26.1s on a real pipeline with zero participating types (#<!-- -->212160).

On a synthetic reproduction (8000 functions, big dictionaries, 40 passes) this patch takes this pipeline from ~1.27s to ~0.64s. This PR composes with, and does not subsume, the registration-level skip proposed in #<!-- -->212160.

Whether or not an attribute or type contains a SymbolRefAttr is a fact known at uniquing time, so precompute and store this fact in the uniqued storage.

This PR adds a field to the storage of types &amp; attributes and records, at uniquing time, whether the thing in question might contain a SymbolRefAttr somewhere in its tree. "Might", because implementations with mutable storage need to answer this question conservatively.

At SymbolTable verification time, we look at that field to avoid traversing types and attributes which do not contain any symbols.

Additionally:
1. One walker with one deduped visited set is hoisted once per SymbolTable scope so that the attributes &amp; types which do get traversed get traversed at most once per symbol table scope, rather than once per operation they appear on.
2. Avoid materializing a DictionaryAttr value when checking an operation's attributes &amp; properties.

One semantic change: the contract on SymbolUserTypeInterface &amp; SymbolUserAttrInterface now requires that the symbols an implementation references be spelled as SymbolRefAttr sub-elements. So, a use is a structural fact about an attribute or type. As a consequence, an implementation that references symbols in some other encoding (e.g., a string) is treated as referencing no symbols and may no longer have verifySymbolUses invoked.

Other than tightening the contract on the two symbol user interfaces, the set of things verified against each symbol table scope is unchanged. This PR just removes all the pointless traversal.

Assisted-by: Claude Code (Anthropic)

---

Patch is 32.97 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/212354.diff

12 Files Affected:

  • (modified) mlir/include/mlir/IR/AttributeSupport.h (+34)

  • (modified) mlir/include/mlir/IR/Attributes.h (+9)

  • (modified) mlir/include/mlir/IR/SymbolInterfaces.td (+16)

  • (modified) mlir/include/mlir/IR/TypeSupport.h (+32)

  • (modified) mlir/include/mlir/IR/Types.h (+8)

  • (modified) mlir/lib/IR/AttributeDetail.h (+4)

  • (modified) mlir/lib/IR/Attributes.cpp (+28)

  • (modified) mlir/lib/IR/SymbolTable.cpp (+55-32)

  • (modified) mlir/lib/IR/Types.cpp (+28)

  • (modified) mlir/unittests/IR/AttributeTest.cpp (+14-10)

  • (modified) mlir/unittests/IR/CMakeLists.txt (+1)

  • (added) mlir/unittests/IR/SymbolReferenceContainmentTest.cpp (+211)
  • ``````

    diff --git a/mlir/include/mlir/IR/AttributeSupport.h b/mlir/include/mlir/IR/AttributeSupport.h
    index 9f36ee4aae278..07aeb7cf47790 100644
    --- a/mlir/include/mlir/IR/AttributeSupport.h
    +++ b/mlir/include/mlir/IR/AttributeSupport.h
    @@ -159,9 +159,21 @@ class AbstractAttribute {
     // AttributeStorage
     //===----------------------------------------------------------------------===//
     
    +class AttributeStorage;
    +
     namespace detail {
     class AttributeUniquer;
     class DistinctAttributeUniquer;
    +
    +/// Compute, and record on `storage`, whether this attribute transitively
    +/// contains a SymbolRefAttr, i.e. whether it is one or has a sub-element that
    +/// is. Kinds carrying the mutable-storage trait, and anything containing them,
    +/// report true conservatively. Called once per newly uniqued instance, after
    +/// its abstract descriptor and sub-elements are set and before it is published,
    +/// so that the bits of its immediate sub-elements (interned first) are final.
    +/// Runs under the uniquer lock; walk implementations must not create new
    +/// attributes or types.
    +void populateAttrContainsSymbolReferences(AttributeStorage *storage);
     } // namespace detail
     
     /// Base storage class appearing in an attribute. Derived storage classes should
    @@ -170,6 +182,7 @@ class alignas(8) AttributeStorage : public StorageUniquer::BaseStorage {
       friend detail::AttributeUniquer;
       friend detail::DistinctAttributeUniquer;
       friend StorageUniquer;
    +  friend void detail::populateAttrContainsSymbolReferences(AttributeStorage *);
     
     public:
       /// Return the abstract descriptor for this attribute.
    @@ -178,6 +191,14 @@ class alignas(8) AttributeStorage : public StorageUniquer::BaseStorage {
         return *abstractAttribute;
       }
     
    +  /// Return whether this attribute may transitively contain a SymbolRefAttr.
    +  /// False is authoritative: no SymbolRefAttr is reachable through the
    +  /// sub-element tree. True may be conservative: mutable-storage kinds, and
    +  /// anything containing them, report true. A pure function of the attribute's
    +  /// interned structure, synthesized at uniquing; not part of the unique key
    +  /// and taking no part in hashing or equality.
    +  bool mayContainSymbolRefs() const { return mayContainSymbolRefsBit; }
    +
     protected:
       /// Set the abstract attribute for this storage instance. This is used by the
       /// AttributeUniquer when initializing a newly constructed storage object.
    @@ -190,8 +211,18 @@ class alignas(8) AttributeStorage : public StorageUniquer::BaseStorage {
       void initialize(MLIRContext *context) {}
     
     private:
    +  /// Record the symbol-reference containment bit. Set once at uniquing.
    +  void setMayContainSymbolRefs(bool mayContain) {
    +    mayContainSymbolRefsBit = mayContain;
    +  }
    +
       /// The abstract descriptor for this attribute.
       const AbstractAttribute *abstractAttribute = nullptr;
    +
    +  /// Whether this attribute may transitively contain a SymbolRefAttr; a pure
    +  /// function of the interned structure, taking no part in the unique key,
    +  /// hashing, or equality.
    +  bool mayContainSymbolRefsBit = false;
     };
     
     /// Default storage type for attributes that require no additional
    @@ -243,6 +274,8 @@ class AttributeUniquer {
               // Execute any additional attribute storage initialization with the
               // context.
               static_cast<typename T::ImplType *>(storage)->initialize(ctx);
    +
    +          populateAttrContainsSymbolReferences(storage);
             },
             typeID, std::forward<Args>(args)...);
       }
    @@ -299,6 +332,7 @@ class AttributeUniquer {
             .registerSingletonStorageType<typename T::ImplType>(
                 typeID, [ctx, typeID](AttributeStorage *storage) {
                   initializeAttributeStorage(storage, ctx, typeID);
    +              populateAttrContainsSymbolReferences(storage);
                 });
       }
     
    diff --git a/mlir/include/mlir/IR/Attributes.h b/mlir/include/mlir/IR/Attributes.h
    index a2f9c5fcda873..9035a6c39597f 100644
    --- a/mlir/include/mlir/IR/Attributes.h
    +++ b/mlir/include/mlir/IR/Attributes.h
    @@ -143,6 +143,15 @@ class Attribute {
       /// Return the internal Attribute implementation.
       ImplType *getImpl() const { return impl; }
     
    +  /// Return whether this attribute may transitively contain a SymbolRefAttr.
    +  /// False is authoritative: no SymbolRefAttr is reachable through the
    +  /// sub-element tree. True may be conservative: mutable-storage kinds, and
    +  /// anything containing them, report true. A pure function of the interned
    +  /// structure; not part of the unique key, hashing, or equality. Symbol-table
    +  /// verification uses it to skip attributes that cannot hold a symbol
    +  /// reference.
    +  bool mayContainSymbolRefs() const { return impl->mayContainSymbolRefs(); }
    +
     protected:
       ImplType *impl{nullptr};
     };
    diff --git a/mlir/include/mlir/IR/SymbolInterfaces.td b/mlir/include/mlir/IR/SymbolInterfaces.td
    index 292c355cbe157..49d7fe5ac53cc 100644
    --- a/mlir/include/mlir/IR/SymbolInterfaces.td
    +++ b/mlir/include/mlir/IR/SymbolInterfaces.td
    @@ -229,6 +229,14 @@ def SymbolUserAttrInterface : AttrInterface<"SymbolUserAttrInterface"> {
         symbol related utilities that are either costly or otherwise disallowed
         within an operation (e.g., recreating symbol users per op verified rather
         than per symbol table, or querying symbols usage of siblings).
    +
    +    Implementations must represent the symbols they reference as `SymbolRefAttr`s
    +    nested anywhere within their sub-element tree, i.e. reachable by recursive
    +    application of `walkImmediateSubElements`, rather than in some other encoding
    +    such as a string. This is what lets the symbol machinery cheaply dismiss
    +    instances that cannot reference a symbol: an instance with no `SymbolRefAttr`
    +    anywhere in its sub-element tree is treated as referencing no symbols, so
    +    symbol-table verification may never invoke its `verifySymbolUses`.
       }];
       let cppNamespace = "::mlir";
     
    @@ -248,6 +256,14 @@ def SymbolUserTypeInterface : TypeInterface<"SymbolUserTypeInterface"> {
         costly or otherwise disallowed within type construction and uniquing.
         `op` is the operation whose verification triggered the check and should be
         used as the anchor for symbol lookups.
    +
    +    Implementations must represent the symbols they reference as `SymbolRefAttr`s
    +    nested anywhere within their sub-element tree, i.e. reachable by recursive
    +    application of `walkImmediateSubElements`, rather than in some other encoding
    +    such as a string. This is what lets the symbol machinery cheaply dismiss
    +    instances that cannot reference a symbol: an instance with no `SymbolRefAttr`
    +    anywhere in its sub-element tree is treated as referencing no symbols, so
    +    symbol-table verification may never invoke its `verifySymbolUses`.
       }];
       let cppNamespace = "::mlir";
     
    diff --git a/mlir/include/mlir/IR/TypeSupport.h b/mlir/include/mlir/IR/TypeSupport.h
    index 36ef696ba4f6f..81b4563b3ce2a 100644
    --- a/mlir/include/mlir/IR/TypeSupport.h
    +++ b/mlir/include/mlir/IR/TypeSupport.h
    @@ -158,14 +158,26 @@ class AbstractType {
     // TypeStorage
     //===----------------------------------------------------------------------===//
     
    +class TypeStorage;
    +
     namespace detail {
     struct TypeUniquer;
    +
    +/// Compute, and record on `storage`, whether this type transitively contains a
    +/// SymbolRefAttr. Kinds carrying the mutable-storage trait, and anything
    +/// containing them, report true conservatively. Called once per newly uniqued
    +/// instance, after its abstract descriptor and sub-elements are set and before
    +/// it is published, so that the bits of its immediate sub-elements (interned
    +/// first) are final. Runs under the uniquer lock; walk implementations must not
    +/// create new attributes or types.
    +void populateTypeContainsSymbolReferences(TypeStorage *storage);
     } // namespace detail
     
     /// Base storage class appearing in a Type.
     class TypeStorage : public StorageUniquer::BaseStorage {
       friend detail::TypeUniquer;
       friend StorageUniquer;
    +  friend void detail::populateTypeContainsSymbolReferences(TypeStorage *);
     
     public:
       /// Return the abstract type descriptor for this type.
    @@ -174,6 +186,14 @@ class TypeStorage : public StorageUniquer::BaseStorage {
         return *abstractType;
       }
     
    +  /// Return whether this type may transitively contain a SymbolRefAttr. False
    +  /// is authoritative: no SymbolRefAttr is reachable through the sub-element
    +  /// tree. True may be conservative: mutable-storage kinds, and anything
    +  /// containing them, report true. A pure function of the type's interned
    +  /// structure, synthesized at uniquing; not part of the unique key and taking
    +  /// no part in hashing or equality.
    +  bool mayContainSymbolRefs() const { return mayContainSymbolRefsBit; }
    +
     protected:
       /// This constructor is used by derived classes as part of the TypeUniquer.
       TypeStorage() {}
    @@ -185,8 +205,18 @@ class TypeStorage : public StorageUniquer::BaseStorage {
         abstractType = const_cast<AbstractType *>(&abstractTy);
       }
     
    +  /// Record the symbol-reference containment bit. Set once at uniquing.
    +  void setMayContainSymbolRefs(bool mayContain) {
    +    mayContainSymbolRefsBit = mayContain;
    +  }
    +
       /// The abstract description for this type.
       AbstractType *abstractType{nullptr};
    +
    +  /// Whether this type may transitively contain a SymbolRefAttr; a pure
    +  /// function of the interned structure, taking no part in the unique key,
    +  /// hashing, or equality.
    +  bool mayContainSymbolRefsBit = false;
     };
     
     /// Default storage type for types that require no additional initialization or
    @@ -233,6 +263,7 @@ struct TypeUniquer {
         return ctx->getTypeUniquer().get<typename T::ImplType>(
             [&, typeID](TypeStorage *storage) {
               storage->initialize(AbstractType::lookup(typeID, ctx));
    +          populateTypeContainsSymbolReferences(storage);
             },
             typeID, std::forward<Args>(args)...);
       }
    @@ -290,6 +321,7 @@ struct TypeUniquer {
         ctx->getTypeUniquer().registerSingletonStorageType<TypeStorage>(
             typeID, [&ctx, typeID](TypeStorage *storage) {
               storage->initialize(AbstractType::lookup(typeID, ctx));
    +          populateTypeContainsSymbolReferences(storage);
             });
       }
     };
    diff --git a/mlir/include/mlir/IR/Types.h b/mlir/include/mlir/IR/Types.h
    index 70599b448f76e..879a2e7e1b281 100644
    --- a/mlir/include/mlir/IR/Types.h
    +++ b/mlir/include/mlir/IR/Types.h
    @@ -192,6 +192,14 @@ class Type {
       /// Return the Type implementation.
       ImplType *getImpl() const { return impl; }
     
    +  /// Return whether this type may transitively contain a SymbolRefAttr. False
    +  /// is authoritative: no SymbolRefAttr is reachable through the sub-element
    +  /// tree. True may be conservative: mutable-storage kinds, and anything
    +  /// containing them, report true. A pure function of the interned structure;
    +  /// not part of the unique key, hashing, or equality. Symbol-table
    +  /// verification uses it to skip types that cannot hold a symbol reference.
    +  bool mayContainSymbolRefs() const { return impl->mayContainSymbolRefs(); }
    +
       /// Walk all of the immediately nested sub-attributes and sub-types. This
       /// method does not recurse into sub elements.
       void walkImmediateSubElements(function_ref<void(Attribute)> walkAttrsFn,
    diff --git a/mlir/lib/IR/AttributeDetail.h b/mlir/lib/IR/AttributeDetail.h
    index 4b7e7dd5677e8..63ef097003b7b 100644
    --- a/mlir/lib/IR/AttributeDetail.h
    +++ b/mlir/lib/IR/AttributeDetail.h
    @@ -300,6 +300,10 @@ class DistinctAttributeUniquer {
             context, std::forward<Args>(args)...);
         storage->initializeAbstractAttribute(
             AbstractAttribute::lookup(DistinctAttr::getTypeID(), context));
    +    // Distinct attributes bypass the uniquer, so synthesize their
    +    // "contains a SymbolRefAttr" bit here from the already-final bit of the
    +    // referenced attribute.
    +    populateAttrContainsSymbolReferences(storage);
         return storage;
       }
     
    diff --git a/mlir/lib/IR/Attributes.cpp b/mlir/lib/IR/Attributes.cpp
    index ff1cd8432fb07..c0123b1049639 100644
    --- a/mlir/lib/IR/Attributes.cpp
    +++ b/mlir/lib/IR/Attributes.cpp
    @@ -7,6 +7,7 @@
     //===----------------------------------------------------------------------===//
     
     #include "mlir/IR/Attributes.h"
    +#include "mlir/IR/BuiltinAttributes.h"
     #include "mlir/IR/Dialect.h"
     
     using namespace mlir;
    @@ -72,3 +73,30 @@ bool NamedAttribute::operator<(const NamedAttribute &rhs) const {
     bool NamedAttribute::operator<(StringRef rhs) const {
       return getName().getValue().compare(rhs) < 0;
     }
    +
    +//===----------------------------------------------------------------------===//
    +// Symbol-reference containment bit synthesis
    +//===----------------------------------------------------------------------===//
    +
    +/// Synthesize the interning-time "contains a SymbolRefAttr" bit for a newly
    +/// uniqued attribute. The bit is set when this attribute is a SymbolRefAttr
    +/// (including FlatSymbolRefAttr), when it carries a mutable component, or when
    +/// any immediate sub-element already carries the bit.
    +void mlir::detail::populateAttrContainsSymbolReferences(
    +    AttributeStorage *storage) {
    +  Attribute attr(storage);
    +  const AbstractAttribute &abstractAttr = storage->getAbstractAttribute();
    +  bool mayContain = isa<SymbolRefAttr>(attr) ||
    +                    abstractAttr.hasTrait<StorageUserTrait::IsMutable>();
    +  if (!mayContain) {
    +    abstractAttr.walkImmediateSubElements(
    +        attr,
    +        [&](Attribute subAttr) {
    +          mayContain |= subAttr && subAttr.mayContainSymbolRefs();
    +        },
    +        [&](Type subType) {
    +          mayContain |= subType && subType.mayContainSymbolRefs();
    +        });
    +  }
    +  storage->setMayContainSymbolRefs(mayContain);
    +}
    diff --git a/mlir/lib/IR/SymbolTable.cpp b/mlir/lib/IR/SymbolTable.cpp
    index 100eba7146d81..e170ba0a024aa 100644
    --- a/mlir/lib/IR/SymbolTable.cpp
    +++ b/mlir/lib/IR/SymbolTable.cpp
    @@ -476,49 +476,57 @@ raw_ostream &mlir::operator<<(raw_ostream &os,
     // SymbolTable Trait Types
     //===----------------------------------------------------------------------===//
     
    -/// Verify the symbol uses held by the types owned by `op`: its operand,
    -/// result, and block-argument types, and any types nested within its
    -/// attributes. `op` is the anchor used for symbol lookups. `verifiedTypes`
    -/// records the types already verified within the current symbol table so that
    -/// each type, which may be uniqued and shared across many positions or
    -/// operations, is verified at most once. Verification fails fast on the first
    -/// invalid symbol use.
    +/// Verify the symbol uses held by the types owned by `op`: its operand, result,
    +/// and block-argument types, and any types nested within its attributes.
    +/// `typeWalker` carries the SymbolUserTypeInterface check as a walk callback,
    +/// anchored at `op` for symbol lookups, and its shared visited set makes each
    +/// uniqued type, which may recur across many positions and operations, verified
    +/// against the enclosing symbol table at most once. A type or attribute whose
    +/// interning-time bit is clear is skipped: it provably contains no
    +/// SymbolRefAttr, and a SymbolUserTypeInterface type is required to spell its
    +/// references as SymbolRefAttr sub-elements, so walking it would verify
    +/// nothing. Verification fails fast on the first invalid symbol use.
     static LogicalResult verifyOpTypeSymbolUses(Operation *op,
    -                                            SymbolTableCollection &symbolTable,
    -                                            SetVector<Type> &verifiedTypes) {
    -  // Walk `type` and any nested type parameters reachable from it, verifying
    -  // each not-yet-seen type and interrupting on the first failure.
    -  auto verify = [&](Type type) {
    -    return type.walk<WalkOrder::PreOrder>([&](Type nestedType) {
    -      if (!verifiedTypes.insert(nestedType))
    -        return WalkResult::advance();
    -      if (auto user = dyn_cast<SymbolUserTypeInterface>(nestedType))
    -        if (failed(user.verifySymbolUses(op, symbolTable)))
    -          return WalkResult::interrupt();
    +                                            AttrTypeWalker &typeWalker) {
    +  auto verifyType = [&](Type type) {
    +    if (!type.mayContainSymbolRefs())
           return WalkResult::advance();
    -    });
    +    return typeWalker.walk<WalkOrder::PreOrder>(type);
    +  };
    +  auto verifyAttr = [&](Attribute attr) {
    +    if (!attr || !attr.mayContainSymbolRefs())
    +      return WalkResult::advance();
    +    return typeWalker.walk<WalkOrder::PreOrder>(attr);
       };
     
       for (Type type : op->getOperandTypes())
    -    if (verify(type).wasInterrupted())
    +    if (verifyType(type).wasInterrupted())
           return failure();
       for (Type type : op->getResultTypes())
    -    if (verify(type).wasInterrupted())
    +    if (verifyType(type).wasInterrupted())
           return failure();
       for (Region &region : op->getRegions())
         for (Block &block : region)
           for (BlockArgument argument : block.getArguments())
    -        if (verify(argument.getType()).wasInterrupted())
    +        if (verifyType(argument.getType()).wasInterrupted())
               return failure();
     
    -  // Verify types nested within the operation's attributes.
    -  WalkResult attrResult =
    -      op->getAttrDictionary().walk<WalkOrder::PreOrder>([&](Type type) {
    -        if (verify(type).wasInterrupted())
    -          return WalkResult::interrupt();
    -        return WalkResult::advance();
    -      });
    -  return failure(attrResult.wasInterrupted());
    +  // Verify types nested within the operation's attributes. Read the raw stored
    +  // attribute dictionary rather than getAttrDictionary(): the latter allocates
    +  // and uniques a fresh dictionary for every operation that keeps its inherent
    +  // attributes in properties. The raw dictionary already covers inherent
    +  // attributes for operations that do not use properties; the properties-held
    +  // inherent attributes are walked separately below.
    +  if (verifyAttr(op->getRawDictionaryAttrs()).wasInterrupted())
    +    return failure();
    +  if (op->getPropertiesStorageSize()) {
    +    NamedAttrList inherentAttrs;
    +    op->getName().populateInherentAttrs(op, inherentAttrs);
    +    for (const NamedAttribute &namedAttr : inherentAttrs)
    +      if (verifyAttr(namedAttr.getValue()).wasInterrupted())
    +        return failure();
    +  }
    +  return success();
     }
     
     LogicalResult detail::verifySymbolTable(Operation *op) {
    @@ -557,7 +565,21 @@ LogicalResult detail::verifySymbolTable(Operation *op) {
       // regardless of which operation anchors the lookup, so each is verified at
       // most once across the whole scope.
       SetVector<Attribute> verifiedAttrs;
    -  SetVector<Type> verifiedTypes;
    +
    +  // A single walker, shared across the whole scope, checks the symbol uses of
    +  // every SymbolUserTypeInterface type. Its visited set records each uniqued
    +  // type once, so a type recurring across operand/result/block-argument and
    +  // attribute positions is verified only at its first occurrence, whose
    +  // operation supplies the lookup anchor.
    +  Operation *typeSymbolUseAnchor = nullptr;
    +  AttrTypeWalker typeWalker;
    +  typeWalker.addWalk([&](Type type) -> WalkResult {
    +    if (auto user = dyn_cast<SymbolUserTypeInterface>(type))
    +      if (failed(user.verifySymbolUses(typeSymbolUseAnchor, symbolTable)))
    +        return WalkResult::interrupt();
    +    return WalkResult::advance();
    +  });
    +
       auto verifySymbolUserFn = [&](Operation *op) -> std::optional<WalkResult> {
         if (SymbolUserOpInterface user = dyn_cast<SymbolUserOpInterface>(op))
           if (failed(user.verifySymbolUses(symbolTable)))
    @@ -570,7 +592,8 @@ LogicalResult detail::verifySymbolTable(Operation *op) {
               return WalkResult::interrupt();
           }
         }
    -    if (failed(verifyOpTypeSymbolUses(op, symbolTable, verifiedTypes)))
    +    typeSymbolUseAnchor = op;
    +    if (failed(verifyOpTypeSymbolUses(op, typeWalker)))
           return WalkResult::interrupt();
         return WalkResult::advance();
       };
    diff --git a/mlir/lib/IR/Types.cpp b/mlir/lib/IR/Types.cpp
    index ec10a5ce9e2e7..f2abede851e13 100644
    --- a/mlir/lib/IR/Types.cpp
    +++ b/mlir/lib/IR/Types.cpp
    @@ -6,6 +6,7 @@
     //
     //===----------------------------------------------------------------------===//
     
    +#include "mlir/IR/Attributes.h"
     #include "mlir/IR/BuiltinTypes.h"
     #include "mlir/IR/Dialect.h"
     
    @@ -127,3 +128,30 @@ unsigned Type::getIntOrFloatBitWidth() const {
         return intType.getWidth();
       return llvm::cast<FloatType>(*this).getWidth();
     }
    +
    +//===----------------...
    [truncated]
    
    
    ``````

    </details>

    llvmorg-github-actions[bot] llvmorg-github-actions[bot] commented on Jul 27, 2026 21:52 UTC
    Bot

    <!--LLVM PR SUMMARY COMMENT-->

    @llvm/pr-subscribers-mlir

    Author: Jared Hoberock (jaredhoberock)

    <details>
    <summary>Changes</summary>

    Motivation: #<!-- -->198435 made the SymbolTable verifier walk every op's types and full attribute dictionary per pass; @<!-- -->ehein6 measured 14.1s -&gt; 26.1s on a real pipeline with zero participating types (#<!-- -->212160).

    On a synthetic reproduction (8000 functions, big dictionaries, 40 passes) this patch takes this pipeline from ~1.27s to ~0.64s. This PR composes with, and does not subsume, the registration-level skip proposed in #<!-- -->212160.

    Whether or not an attribute or type contains a SymbolRefAttr is a fact known at uniquing time, so precompute and store this fact in the uniqued storage.

    This PR adds a field to the storage of types &amp; attributes and records, at uniquing time, whether the thing in question might contain a SymbolRefAttr somewhere in its tree. "Might", because implementations with mutable storage need to answer this question conservatively.

    At SymbolTable verification time, we look at that field to avoid traversing types and attributes which do not contain any symbols.

    Additionally:
    1. One walker with one deduped visited set is hoisted once per SymbolTable scope so that the attributes &amp; types which do get traversed get traversed at most once per symbol table scope, rather than once per operation they appear on.
    2. Avoid materializing a DictionaryAttr value when checking an operation's attributes &amp; properties.

    One semantic change: the contract on SymbolUserTypeInterface &amp; SymbolUserAttrInterface now requires that the symbols an implementation references be spelled as SymbolRefAttr sub-elements. So, a use is a structural fact about an attribute or type. As a consequence, an implementation that references symbols in some other encoding (e.g., a string) is treated as referencing no symbols and may no longer have verifySymbolUses invoked.

    Other than tightening the contract on the two symbol user interfaces, the set of things verified against each symbol table scope is unchanged. This PR just removes all the pointless traversal.

    Assisted-by: Claude Code (Anthropic)

    ---

    Patch is 32.97 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/212354.diff

    12 Files Affected:

  • (modified) mlir/include/mlir/IR/AttributeSupport.h (+34)

  • (modified) mlir/include/mlir/IR/Attributes.h (+9)

  • (modified) mlir/include/mlir/IR/SymbolInterfaces.td (+16)

  • (modified) mlir/include/mlir/IR/TypeSupport.h (+32)

  • (modified) mlir/include/mlir/IR/Types.h (+8)

  • (modified) mlir/lib/IR/AttributeDetail.h (+4)

  • (modified) mlir/lib/IR/Attributes.cpp (+28)

  • (modified) mlir/lib/IR/SymbolTable.cpp (+55-32)

  • (modified) mlir/lib/IR/Types.cpp (+28)

  • (modified) mlir/unittests/IR/AttributeTest.cpp (+14-10)

  • (modified) mlir/unittests/IR/CMakeLists.txt (+1)

  • (added) mlir/unittests/IR/SymbolReferenceContainmentTest.cpp (+211)
  • ``````

    diff --git a/mlir/include/mlir/IR/AttributeSupport.h b/mlir/include/mlir/IR/AttributeSupport.h
    index 9f36ee4aae278..07aeb7cf47790 100644
    --- a/mlir/include/mlir/IR/AttributeSupport.h
    +++ b/mlir/include/mlir/IR/AttributeSupport.h
    @@ -159,9 +159,21 @@ class AbstractAttribute {
     // AttributeStorage
     //===----------------------------------------------------------------------===//
     
    +class AttributeStorage;
    +
     namespace detail {
     class AttributeUniquer;
     class DistinctAttributeUniquer;
    +
    +/// Compute, and record on `storage`, whether this attribute transitively
    +/// contains a SymbolRefAttr, i.e. whether it is one or has a sub-element that
    +/// is. Kinds carrying the mutable-storage trait, and anything containing them,
    +/// report true conservatively. Called once per newly uniqued instance, after
    +/// its abstract descriptor and sub-elements are set and before it is published,
    +/// so that the bits of its immediate sub-elements (interned first) are final.
    +/// Runs under the uniquer lock; walk implementations must not create new
    +/// attributes or types.
    +void populateAttrContainsSymbolReferences(AttributeStorage *storage);
     } // namespace detail
     
     /// Base storage class appearing in an attribute. Derived storage classes should
    @@ -170,6 +182,7 @@ class alignas(8) AttributeStorage : public StorageUniquer::BaseStorage {
       friend detail::AttributeUniquer;
       friend detail::DistinctAttributeUniquer;
       friend StorageUniquer;
    +  friend void detail::populateAttrContainsSymbolReferences(AttributeStorage *);
     
     public:
       /// Return the abstract descriptor for this attribute.
    @@ -178,6 +191,14 @@ class alignas(8) AttributeStorage : public StorageUniquer::BaseStorage {
         return *abstractAttribute;
       }
     
    +  /// Return whether this attribute may transitively contain a SymbolRefAttr.
    +  /// False is authoritative: no SymbolRefAttr is reachable through the
    +  /// sub-element tree. True may be conservative: mutable-storage kinds, and
    +  /// anything containing them, report true. A pure function of the attribute's
    +  /// interned structure, synthesized at uniquing; not part of the unique key
    +  /// and taking no part in hashing or equality.
    +  bool mayContainSymbolRefs() const { return mayContainSymbolRefsBit; }
    +
     protected:
       /// Set the abstract attribute for this storage instance. This is used by the
       /// AttributeUniquer when initializing a newly constructed storage object.
    @@ -190,8 +211,18 @@ class alignas(8) AttributeStorage : public StorageUniquer::BaseStorage {
       void initialize(MLIRContext *context) {}
     
     private:
    +  /// Record the symbol-reference containment bit. Set once at uniquing.
    +  void setMayContainSymbolRefs(bool mayContain) {
    +    mayContainSymbolRefsBit = mayContain;
    +  }
    +
       /// The abstract descriptor for this attribute.
       const AbstractAttribute *abstractAttribute = nullptr;
    +
    +  /// Whether this attribute may transitively contain a SymbolRefAttr; a pure
    +  /// function of the interned structure, taking no part in the unique key,
    +  /// hashing, or equality.
    +  bool mayContainSymbolRefsBit = false;
     };
     
     /// Default storage type for attributes that require no additional
    @@ -243,6 +274,8 @@ class AttributeUniquer {
               // Execute any additional attribute storage initialization with the
               // context.
               static_cast<typename T::ImplType *>(storage)->initialize(ctx);
    +
    +          populateAttrContainsSymbolReferences(storage);
             },
             typeID, std::forward<Args>(args)...);
       }
    @@ -299,6 +332,7 @@ class AttributeUniquer {
             .registerSingletonStorageType<typename T::ImplType>(
                 typeID, [ctx, typeID](AttributeStorage *storage) {
                   initializeAttributeStorage(storage, ctx, typeID);
    +              populateAttrContainsSymbolReferences(storage);
                 });
       }
     
    diff --git a/mlir/include/mlir/IR/Attributes.h b/mlir/include/mlir/IR/Attributes.h
    index a2f9c5fcda873..9035a6c39597f 100644
    --- a/mlir/include/mlir/IR/Attributes.h
    +++ b/mlir/include/mlir/IR/Attributes.h
    @@ -143,6 +143,15 @@ class Attribute {
       /// Return the internal Attribute implementation.
       ImplType *getImpl() const { return impl; }
     
    +  /// Return whether this attribute may transitively contain a SymbolRefAttr.
    +  /// False is authoritative: no SymbolRefAttr is reachable through the
    +  /// sub-element tree. True may be conservative: mutable-storage kinds, and
    +  /// anything containing them, report true. A pure function of the interned
    +  /// structure; not part of the unique key, hashing, or equality. Symbol-table
    +  /// verification uses it to skip attributes that cannot hold a symbol
    +  /// reference.
    +  bool mayContainSymbolRefs() const { return impl->mayContainSymbolRefs(); }
    +
     protected:
       ImplType *impl{nullptr};
     };
    diff --git a/mlir/include/mlir/IR/SymbolInterfaces.td b/mlir/include/mlir/IR/SymbolInterfaces.td
    index 292c355cbe157..49d7fe5ac53cc 100644
    --- a/mlir/include/mlir/IR/SymbolInterfaces.td
    +++ b/mlir/include/mlir/IR/SymbolInterfaces.td
    @@ -229,6 +229,14 @@ def SymbolUserAttrInterface : AttrInterface<"SymbolUserAttrInterface"> {
         symbol related utilities that are either costly or otherwise disallowed
         within an operation (e.g., recreating symbol users per op verified rather
         than per symbol table, or querying symbols usage of siblings).
    +
    +    Implementations must represent the symbols they reference as `SymbolRefAttr`s
    +    nested anywhere within their sub-element tree, i.e. reachable by recursive
    +    application of `walkImmediateSubElements`, rather than in some other encoding
    +    such as a string. This is what lets the symbol machinery cheaply dismiss
    +    instances that cannot reference a symbol: an instance with no `SymbolRefAttr`
    +    anywhere in its sub-element tree is treated as referencing no symbols, so
    +    symbol-table verification may never invoke its `verifySymbolUses`.
       }];
       let cppNamespace = "::mlir";
     
    @@ -248,6 +256,14 @@ def SymbolUserTypeInterface : TypeInterface<"SymbolUserTypeInterface"> {
         costly or otherwise disallowed within type construction and uniquing.
         `op` is the operation whose verification triggered the check and should be
         used as the anchor for symbol lookups.
    +
    +    Implementations must represent the symbols they reference as `SymbolRefAttr`s
    +    nested anywhere within their sub-element tree, i.e. reachable by recursive
    +    application of `walkImmediateSubElements`, rather than in some other encoding
    +    such as a string. This is what lets the symbol machinery cheaply dismiss
    +    instances that cannot reference a symbol: an instance with no `SymbolRefAttr`
    +    anywhere in its sub-element tree is treated as referencing no symbols, so
    +    symbol-table verification may never invoke its `verifySymbolUses`.
       }];
       let cppNamespace = "::mlir";
     
    diff --git a/mlir/include/mlir/IR/TypeSupport.h b/mlir/include/mlir/IR/TypeSupport.h
    index 36ef696ba4f6f..81b4563b3ce2a 100644
    --- a/mlir/include/mlir/IR/TypeSupport.h
    +++ b/mlir/include/mlir/IR/TypeSupport.h
    @@ -158,14 +158,26 @@ class AbstractType {
     // TypeStorage
     //===----------------------------------------------------------------------===//
     
    +class TypeStorage;
    +
     namespace detail {
     struct TypeUniquer;
    +
    +/// Compute, and record on `storage`, whether this type transitively contains a
    +/// SymbolRefAttr. Kinds carrying the mutable-storage trait, and anything
    +/// containing them, report true conservatively. Called once per newly uniqued
    +/// instance, after its abstract descriptor and sub-elements are set and before
    +/// it is published, so that the bits of its immediate sub-elements (interned
    +/// first) are final. Runs under the uniquer lock; walk implementations must not
    +/// create new attributes or types.
    +void populateTypeContainsSymbolReferences(TypeStorage *storage);
     } // namespace detail
     
     /// Base storage class appearing in a Type.
     class TypeStorage : public StorageUniquer::BaseStorage {
       friend detail::TypeUniquer;
       friend StorageUniquer;
    +  friend void detail::populateTypeContainsSymbolReferences(TypeStorage *);
     
     public:
       /// Return the abstract type descriptor for this type.
    @@ -174,6 +186,14 @@ class TypeStorage : public StorageUniquer::BaseStorage {
         return *abstractType;
       }
     
    +  /// Return whether this type may transitively contain a SymbolRefAttr. False
    +  /// is authoritative: no SymbolRefAttr is reachable through the sub-element
    +  /// tree. True may be conservative: mutable-storage kinds, and anything
    +  /// containing them, report true. A pure function of the type's interned
    +  /// structure, synthesized at uniquing; not part of the unique key and taking
    +  /// no part in hashing or equality.
    +  bool mayContainSymbolRefs() const { return mayContainSymbolRefsBit; }
    +
     protected:
       /// This constructor is used by derived classes as part of the TypeUniquer.
       TypeStorage() {}
    @@ -185,8 +205,18 @@ class TypeStorage : public StorageUniquer::BaseStorage {
         abstractType = const_cast<AbstractType *>(&abstractTy);
       }
     
    +  /// Record the symbol-reference containment bit. Set once at uniquing.
    +  void setMayContainSymbolRefs(bool mayContain) {
    +    mayContainSymbolRefsBit = mayContain;
    +  }
    +
       /// The abstract description for this type.
       AbstractType *abstractType{nullptr};
    +
    +  /// Whether this type may transitively contain a SymbolRefAttr; a pure
    +  /// function of the interned structure, taking no part in the unique key,
    +  /// hashing, or equality.
    +  bool mayContainSymbolRefsBit = false;
     };
     
     /// Default storage type for types that require no additional initialization or
    @@ -233,6 +263,7 @@ struct TypeUniquer {
         return ctx->getTypeUniquer().get<typename T::ImplType>(
             [&, typeID](TypeStorage *storage) {
               storage->initialize(AbstractType::lookup(typeID, ctx));
    +          populateTypeContainsSymbolReferences(storage);
             },
             typeID, std::forward<Args>(args)...);
       }
    @@ -290,6 +321,7 @@ struct TypeUniquer {
         ctx->getTypeUniquer().registerSingletonStorageType<TypeStorage>(
             typeID, [&ctx, typeID](TypeStorage *storage) {
               storage->initialize(AbstractType::lookup(typeID, ctx));
    +          populateTypeContainsSymbolReferences(storage);
             });
       }
     };
    diff --git a/mlir/include/mlir/IR/Types.h b/mlir/include/mlir/IR/Types.h
    index 70599b448f76e..879a2e7e1b281 100644
    --- a/mlir/include/mlir/IR/Types.h
    +++ b/mlir/include/mlir/IR/Types.h
    @@ -192,6 +192,14 @@ class Type {
       /// Return the Type implementation.
       ImplType *getImpl() const { return impl; }
     
    +  /// Return whether this type may transitively contain a SymbolRefAttr. False
    +  /// is authoritative: no SymbolRefAttr is reachable through the sub-element
    +  /// tree. True may be conservative: mutable-storage kinds, and anything
    +  /// containing them, report true. A pure function of the interned structure;
    +  /// not part of the unique key, hashing, or equality. Symbol-table
    +  /// verification uses it to skip types that cannot hold a symbol reference.
    +  bool mayContainSymbolRefs() const { return impl->mayContainSymbolRefs(); }
    +
       /// Walk all of the immediately nested sub-attributes and sub-types. This
       /// method does not recurse into sub elements.
       void walkImmediateSubElements(function_ref<void(Attribute)> walkAttrsFn,
    diff --git a/mlir/lib/IR/AttributeDetail.h b/mlir/lib/IR/AttributeDetail.h
    index 4b7e7dd5677e8..63ef097003b7b 100644
    --- a/mlir/lib/IR/AttributeDetail.h
    +++ b/mlir/lib/IR/AttributeDetail.h
    @@ -300,6 +300,10 @@ class DistinctAttributeUniquer {
             context, std::forward<Args>(args)...);
         storage->initializeAbstractAttribute(
             AbstractAttribute::lookup(DistinctAttr::getTypeID(), context));
    +    // Distinct attributes bypass the uniquer, so synthesize their
    +    // "contains a SymbolRefAttr" bit here from the already-final bit of the
    +    // referenced attribute.
    +    populateAttrContainsSymbolReferences(storage);
         return storage;
       }
     
    diff --git a/mlir/lib/IR/Attributes.cpp b/mlir/lib/IR/Attributes.cpp
    index ff1cd8432fb07..c0123b1049639 100644
    --- a/mlir/lib/IR/Attributes.cpp
    +++ b/mlir/lib/IR/Attributes.cpp
    @@ -7,6 +7,7 @@
     //===----------------------------------------------------------------------===//
     
     #include "mlir/IR/Attributes.h"
    +#include "mlir/IR/BuiltinAttributes.h"
     #include "mlir/IR/Dialect.h"
     
     using namespace mlir;
    @@ -72,3 +73,30 @@ bool NamedAttribute::operator<(const NamedAttribute &rhs) const {
     bool NamedAttribute::operator<(StringRef rhs) const {
       return getName().getValue().compare(rhs) < 0;
     }
    +
    +//===----------------------------------------------------------------------===//
    +// Symbol-reference containment bit synthesis
    +//===----------------------------------------------------------------------===//
    +
    +/// Synthesize the interning-time "contains a SymbolRefAttr" bit for a newly
    +/// uniqued attribute. The bit is set when this attribute is a SymbolRefAttr
    +/// (including FlatSymbolRefAttr), when it carries a mutable component, or when
    +/// any immediate sub-element already carries the bit.
    +void mlir::detail::populateAttrContainsSymbolReferences(
    +    AttributeStorage *storage) {
    +  Attribute attr(storage);
    +  const AbstractAttribute &abstractAttr = storage->getAbstractAttribute();
    +  bool mayContain = isa<SymbolRefAttr>(attr) ||
    +                    abstractAttr.hasTrait<StorageUserTrait::IsMutable>();
    +  if (!mayContain) {
    +    abstractAttr.walkImmediateSubElements(
    +        attr,
    +        [&](Attribute subAttr) {
    +          mayContain |= subAttr && subAttr.mayContainSymbolRefs();
    +        },
    +        [&](Type subType) {
    +          mayContain |= subType && subType.mayContainSymbolRefs();
    +        });
    +  }
    +  storage->setMayContainSymbolRefs(mayContain);
    +}
    diff --git a/mlir/lib/IR/SymbolTable.cpp b/mlir/lib/IR/SymbolTable.cpp
    index 100eba7146d81..e170ba0a024aa 100644
    --- a/mlir/lib/IR/SymbolTable.cpp
    +++ b/mlir/lib/IR/SymbolTable.cpp
    @@ -476,49 +476,57 @@ raw_ostream &mlir::operator<<(raw_ostream &os,
     // SymbolTable Trait Types
     //===----------------------------------------------------------------------===//
     
    -/// Verify the symbol uses held by the types owned by `op`: its operand,
    -/// result, and block-argument types, and any types nested within its
    -/// attributes. `op` is the anchor used for symbol lookups. `verifiedTypes`
    -/// records the types already verified within the current symbol table so that
    -/// each type, which may be uniqued and shared across many positions or
    -/// operations, is verified at most once. Verification fails fast on the first
    -/// invalid symbol use.
    +/// Verify the symbol uses held by the types owned by `op`: its operand, result,
    +/// and block-argument types, and any types nested within its attributes.
    +/// `typeWalker` carries the SymbolUserTypeInterface check as a walk callback,
    +/// anchored at `op` for symbol lookups, and its shared visited set makes each
    +/// uniqued type, which may recur across many positions and operations, verified
    +/// against the enclosing symbol table at most once. A type or attribute whose
    +/// interning-time bit is clear is skipped: it provably contains no
    +/// SymbolRefAttr, and a SymbolUserTypeInterface type is required to spell its
    +/// references as SymbolRefAttr sub-elements, so walking it would verify
    +/// nothing. Verification fails fast on the first invalid symbol use.
     static LogicalResult verifyOpTypeSymbolUses(Operation *op,
    -                                            SymbolTableCollection &symbolTable,
    -                                            SetVector<Type> &verifiedTypes) {
    -  // Walk `type` and any nested type parameters reachable from it, verifying
    -  // each not-yet-seen type and interrupting on the first failure.
    -  auto verify = [&](Type type) {
    -    return type.walk<WalkOrder::PreOrder>([&](Type nestedType) {
    -      if (!verifiedTypes.insert(nestedType))
    -        return WalkResult::advance();
    -      if (auto user = dyn_cast<SymbolUserTypeInterface>(nestedType))
    -        if (failed(user.verifySymbolUses(op, symbolTable)))
    -          return WalkResult::interrupt();
    +                                            AttrTypeWalker &typeWalker) {
    +  auto verifyType = [&](Type type) {
    +    if (!type.mayContainSymbolRefs())
           return WalkResult::advance();
    -    });
    +    return typeWalker.walk<WalkOrder::PreOrder>(type);
    +  };
    +  auto verifyAttr = [&](Attribute attr) {
    +    if (!attr || !attr.mayContainSymbolRefs())
    +      return WalkResult::advance();
    +    return typeWalker.walk<WalkOrder::PreOrder>(attr);
       };
     
       for (Type type : op->getOperandTypes())
    -    if (verify(type).wasInterrupted())
    +    if (verifyType(type).wasInterrupted())
           return failure();
       for (Type type : op->getResultTypes())
    -    if (verify(type).wasInterrupted())
    +    if (verifyType(type).wasInterrupted())
           return failure();
       for (Region &region : op->getRegions())
         for (Block &block : region)
           for (BlockArgument argument : block.getArguments())
    -        if (verify(argument.getType()).wasInterrupted())
    +        if (verifyType(argument.getType()).wasInterrupted())
               return failure();
     
    -  // Verify types nested within the operation's attributes.
    -  WalkResult attrResult =
    -      op->getAttrDictionary().walk<WalkOrder::PreOrder>([&](Type type) {
    -        if (verify(type).wasInterrupted())
    -          return WalkResult::interrupt();
    -        return WalkResult::advance();
    -      });
    -  return failure(attrResult.wasInterrupted());
    +  // Verify types nested within the operation's attributes. Read the raw stored
    +  // attribute dictionary rather than getAttrDictionary(): the latter allocates
    +  // and uniques a fresh dictionary for every operation that keeps its inherent
    +  // attributes in properties. The raw dictionary already covers inherent
    +  // attributes for operations that do not use properties; the properties-held
    +  // inherent attributes are walked separately below.
    +  if (verifyAttr(op->getRawDictionaryAttrs()).wasInterrupted())
    +    return failure();
    +  if (op->getPropertiesStorageSize()) {
    +    NamedAttrList inherentAttrs;
    +    op->getName().populateInherentAttrs(op, inherentAttrs);
    +    for (const NamedAttribute &namedAttr : inherentAttrs)
    +      if (verifyAttr(namedAttr.getValue()).wasInterrupted())
    +        return failure();
    +  }
    +  return success();
     }
     
     LogicalResult detail::verifySymbolTable(Operation *op) {
    @@ -557,7 +565,21 @@ LogicalResult detail::verifySymbolTable(Operation *op) {
       // regardless of which operation anchors the lookup, so each is verified at
       // most once across the whole scope.
       SetVector<Attribute> verifiedAttrs;
    -  SetVector<Type> verifiedTypes;
    +
    +  // A single walker, shared across the whole scope, checks the symbol uses of
    +  // every SymbolUserTypeInterface type. Its visited set records each uniqued
    +  // type once, so a type recurring across operand/result/block-argument and
    +  // attribute positions is verified only at its first occurrence, whose
    +  // operation supplies the lookup anchor.
    +  Operation *typeSymbolUseAnchor = nullptr;
    +  AttrTypeWalker typeWalker;
    +  typeWalker.addWalk([&](Type type) -> WalkResult {
    +    if (auto user = dyn_cast<SymbolUserTypeInterface>(type))
    +      if (failed(user.verifySymbolUses(typeSymbolUseAnchor, symbolTable)))
    +        return WalkResult::interrupt();
    +    return WalkResult::advance();
    +  });
    +
       auto verifySymbolUserFn = [&](Operation *op) -> std::optional<WalkResult> {
         if (SymbolUserOpInterface user = dyn_cast<SymbolUserOpInterface>(op))
           if (failed(user.verifySymbolUses(symbolTable)))
    @@ -570,7 +592,8 @@ LogicalResult detail::verifySymbolTable(Operation *op) {
               return WalkResult::interrupt();
           }
         }
    -    if (failed(verifyOpTypeSymbolUses(op, symbolTable, verifiedTypes)))
    +    typeSymbolUseAnchor = op;
    +    if (failed(verifyOpTypeSymbolUses(op, typeWalker)))
           return WalkResult::interrupt();
         return WalkResult::advance();
       };
    diff --git a/mlir/lib/IR/Types.cpp b/mlir/lib/IR/Types.cpp
    index ec10a5ce9e2e7..f2abede851e13 100644
    --- a/mlir/lib/IR/Types.cpp
    +++ b/mlir/lib/IR/Types.cpp
    @@ -6,6 +6,7 @@
     //
     //===----------------------------------------------------------------------===//
     
    +#include "mlir/IR/Attributes.h"
     #include "mlir/IR/BuiltinTypes.h"
     #include "mlir/IR/Dialect.h"
     
    @@ -127,3 +128,30 @@ unsigned Type::getIntOrFloatBitWidth() const {
         return intType.getWidth();
       return llvm::cast<FloatType>(*this).getWidth();
     }
    +
    +//===----------------...
    [truncated]
    
    
    ``````

    </details>

    jaredhoberock jaredhoberock commented on Jul 27, 2026 23:17 UTC
    Author

    @joker-eph Here is a first cut of the general fix you asked about on #212160
    @ehein6 Could you run your repro case on this branch?

    ehein6 ehein6 commented on Jul 28, 2026 13:09 UTC
    Contributor

    I re-ran my test case using your branch, my branch, and both. All three cases fixed the performance regression w.r.t. main (within noise).

    Note that in my case, none of the types implement SymbolUserTypeInterface so it's especially good that this worked. Up to you if you want to keep my PR, just merge this, or keep both. Thanks for taking a look!

    jaredhoberock jaredhoberock commented on Jul 28, 2026 18:25 UTC
    Author

    @ehein6 thanks for taking the time to benchmark this patch. It sounds like either PR suffices for your case. No objection from me either way on keeping yours, the two PRs should compose.

    joker-eph joker-eph commented on code on Aug 18, 2026 08:59 UTC
    Code Review
    mlir/lib/IR/SymbolTable.cpp:1
    @@ -476,49 +476,57 @@ raw_ostream &mlir::operator<<(raw_ostream &os,
     // SymbolTable Trait Types
     //===----------------------------------------------------------------------===//
     
    -/// Verify the symbol uses held by the types owned by `op`: its operand,
    -/// result, and block-argument types, and any types nested within its
    -/// attributes. `op` is the anchor used for symbol lookups. `verifiedTypes`
    -/// records the types already verified within the current symbol table so that
    -/// each type, which may be uniqued and shared across many positions or
    -/// operations, is verified at most once. Verification fails fast on the first
    -/// invalid symbol use.
    +/// Verify the symbol uses held by the types owned by `op`: its operand, result,
    +/// and block-argument types, and any types nested within its attributes.
    +/// `typeWalker` carries the SymbolUserTypeInterface check as a walk callback,
    +/// anchored at `op` for symbol lookups, and its shared visited set makes each
    +/// uniqued type, which may recur across many positions and operations, verified
    +/// against the enclosing symbol table at most once. A type or attribute whose
    +/// interning-time bit is clear is skipped: it provably contains no
    +/// SymbolRefAttr, and a SymbolUserTypeInterface type is required to spell its
    +/// references as SymbolRefAttr sub-elements, so walking it would verify
    +/// nothing. Verification fails fast on the first invalid symbol use.
     static LogicalResult verifyOpTypeSymbolUses(Operation *op,
    -                                            SymbolTableCollection &symbolTable,
    -                                            SetVector<Type> &verifiedTypes) {
    -  // Walk `type` and any nested type parameters reachable from it, verifying
    -  // each not-yet-seen type and interrupting on the first failure.
    -  auto verify = [&](Type type) {
    -    return type.walk<WalkOrder::PreOrder>([&](Type nestedType) {
    -      if (!verifiedTypes.insert(nestedType))
    -        return WalkResult::advance();
    -      if (auto user = dyn_cast<SymbolUserTypeInterface>(nestedType))
    -        if (failed(user.verifySymbolUses(op, symbolTable)))
    -          return WalkResult::interrupt();
    +                                            AttrTypeWalker &typeWalker) {
    +  auto verifyType = [&](Type type) {
    +    if (!type.mayContainSymbolRefs())
           return WalkResult::advance();
    -    });
    +    return typeWalker.walk<WalkOrder::PreOrder>(type);
    +  };
    +  auto verifyAttr = [&](Attribute attr) {
    +    if (!attr || !attr.mayContainSymbolRefs())
    +      return WalkResult::advance();
    +    return typeWalker.walk<WalkOrder::PreOrder>(attr);
       };
     
       for (Type type : op->getOperandTypes())
    -    if (verify(type).wasInterrupted())
    +    if (verifyType(type).wasInterrupted())
           return failure();
       for (Type type : op->getResultTypes())
    -    if (verify(type).wasInterrupted())
    +    if (verifyType(type).wasInterrupted())
           return failure();
       for (Region &region : op->getRegions())
         for (Block &block : region)
           for (BlockArgument argument : block.getArguments())
    -        if (verify(argument.getType()).wasInterrupted())
    +        if (verifyType(argument.getType()).wasInterrupted())
               return failure();
     
    -  // Verify types nested within the operation's attributes.
    -  WalkResult attrResult =
    -      op->getAttrDictionary().walk<WalkOrder::PreOrder>([&](Type type) {
    -        if (verify(type).wasInterrupted())
    -          return WalkResult::interrupt();
    -        return WalkResult::advance();
    -      });
    -  return failure(attrResult.wasInterrupted());
    +  // Verify types nested within the operation's attributes. Read the raw stored
    +  // attribute dictionary rather than getAttrDictionary(): the latter allocates
    +  // and uniques a fresh dictionary for every operation that keeps its inherent
    +  // attributes in properties. The raw dictionary already covers inherent
    +  // attributes for operations that do not use properties; the properties-held
    +  // inherent attributes are walked separately below.
    +  if (verifyAttr(op->getRawDictionaryAttrs()).wasInterrupted())
    +    return failure();
    +  if (op->getPropertiesStorageSize()) {
    +    NamedAttrList inherentAttrs;
    +    op->getName().populateInherentAttrs(op, inherentAttrs);

    That seems expensive: converting properties to attribute does not seem like something we'd want to do. We should try to instead generate some dispatch hook with every property to avoid this.

    joker-eph joker-eph commented on Aug 18, 2026 09:01 UTC
    Contributor

    Haven't had time to dedicated enough brain power to this, but I'm a bit wary of how intrusive this is (the part touching Attributes.h, AttributeSupport.h, Type.h, TypeSupport.h) right now.

    jaredhoberock jaredhoberock commented on Aug 18, 2026 19:04 UTC
    Author

    I'm working on putting together an alternative solution that doesn't reach into the guts of type storage and will be easier to review

    dtzSiFive dtzSiFive commented on Aug 18, 2026 20:23 UTC
    Contributor

    I'm working on putting together an alternative solution that doesn't reach into the guts of type storage and will be easier to review

    Thanks, @jaredhoberock ! Appreciate you putting this together and how quickly you're iterating on this!
    (and for the original work!)

    FWIW the current version bench'd well on our side, ~89% recovery of the regression. We're checking things we didn't before, so more work will always cost something.

    Happy to review and rerun numbers against the alternative once your new version is up.

    jaredhoberock jaredhoberock commented on Aug 19, 2026 02:06 UTC
    Author

    This PR has been reworked in place and is hopefully easier to evaluate. The previous approach is at a0ba771be0b2 for reference.

    The gist of the solution is that we want the SymbolTable verifier to avoid traversing types & attributes which are known not to contain any symbols. We can do that if we precompute and store, for each type and attribute, whether it might contain a symbol.

    The question is where to store that per-object bit? This PR stashes it in a hash map inside of MLIRContext.

    Here are the alternatives we explored and rejected:

    1. In the type/attr's storage (the previous revision of this PR): too invasive for a niche concern
    2. A static map owned by the SymbolUserTypeInterface machinery: global state forbidden explicitly
    3. On the interface itself, or in a dialect: structurally impossible because interfaces are stateless and have no associated dialect
    4. On SymbolTable: the verifier's symbol-table objects are function-locals, so nothing survives to help the repeated-verification that motivated the PR
    5. A general-purpose MLIRContext user-state mechanism: doesn't exist

    The chosen placement inside of MLIRContext follows existing precedent for similar state and avoids changing any public headers except for SymbolTable.h.

    dtzSiFive dtzSiFive commented on code on Aug 19, 2026 20:14 UTC
    Code Review
    mlir/lib/IR/SymbolTable.cpp:1
    @@ -472,31 +473,86 @@ raw_ostream &mlir::operator<<(raw_ostream &os,
       llvm_unreachable("Unexpected visibility");
     }
     
    +//===----------------------------------------------------------------------===//
    +// SymbolRefAttr containment query
    +//===----------------------------------------------------------------------===//
    +
    +static bool computeMayContainSymbolRefs(Type type);
    +static bool computeMayContainSymbolRefs(Attribute attr);
    +
    +/// Fill (once) and return the "may transitively contain a SymbolRefAttr" fact
    +/// for a uniqued type or attribute `obj`, seeded by `selfIsRef` for an object
    +/// that is itself a symbol reference. The answer is computed entirely outside
    +/// the cache lock -- which is taken only for the write-once insert -- so no
    +/// lock is held across the recursion and a racing duplicate fill computes the
    +/// same fact idempotently. A mutable-storage kind may gain sub-elements after
    +/// this point, so its contents are never read; it and its containers report
    +/// may-contain conservatively.
    +template <typename T>
    +static bool fillMayContainSymbolRefs(T obj, bool selfIsRef) {
    +  MLIRContext *ctx = obj.getContext();
    +  bool lock = ctx->isMultithreadingEnabled();
    +  detail::SymbolRefContainmentCache &cache =
    +      detail::getSymbolRefContainmentCache(ctx);
    +  if (std::optional<bool> cached = cache.lookup(obj, lock))
    +    return *cached;
    +
    +  bool mayContain =
    +      selfIsRef || obj.template hasTrait<detail::StorageUserTrait::IsMutable>();
    +  // The recursion needs no in-progress guard: immutable objects form a DAG
    +  // (sub-elements are interned before their parents), so every cycle passes
    +  // through a mutable kind, where the fill stops above before descending.
    +  if (!mayContain)
    +    obj.walkImmediateSubElements(
    +        [&](Attribute sub) {
    +          mayContain |= sub && computeMayContainSymbolRefs(sub);

    We can't interrupt here but we can early-exit to avoid recursing into siblings. While having that cached too could be useful, doing so lazily (only if needed at top-level elsewhere) can save walks.

              if (!mayContain && sub)
                mayContain = computeMayContainSymbolRefs(sub);
    

    dtzSiFive dtzSiFive commented on code on Aug 19, 2026 20:47 UTC
    Code Review
    mlir/lib/IR/SymbolTable.cpp:1
    @@ -472,31 +473,86 @@ raw_ostream &mlir::operator<<(raw_ostream &os,
       llvm_unreachable("Unexpected visibility");
     }
     
    +//===----------------------------------------------------------------------===//
    +// SymbolRefAttr containment query
    +//===----------------------------------------------------------------------===//
    +
    +static bool computeMayContainSymbolRefs(Type type);
    +static bool computeMayContainSymbolRefs(Attribute attr);
    +
    +/// Fill (once) and return the "may transitively contain a SymbolRefAttr" fact
    +/// for a uniqued type or attribute `obj`, seeded by `selfIsRef` for an object
    +/// that is itself a symbol reference. The answer is computed entirely outside
    +/// the cache lock -- which is taken only for the write-once insert -- so no
    +/// lock is held across the recursion and a racing duplicate fill computes the
    +/// same fact idempotently. A mutable-storage kind may gain sub-elements after
    +/// this point, so its contents are never read; it and its containers report
    +/// may-contain conservatively.
    +template <typename T>
    +static bool fillMayContainSymbolRefs(T obj, bool selfIsRef) {
    +  MLIRContext *ctx = obj.getContext();
    +  bool lock = ctx->isMultithreadingEnabled();
    +  detail::SymbolRefContainmentCache &cache =
    +      detail::getSymbolRefContainmentCache(ctx);
    +  if (std::optional<bool> cached = cache.lookup(obj, lock))
    +    return *cached;
    +
    +  bool mayContain =
    +      selfIsRef || obj.template hasTrait<detail::StorageUserTrait::IsMutable>();
    +  // The recursion needs no in-progress guard: immutable objects form a DAG
    +  // (sub-elements are interned before their parents), so every cycle passes
    +  // through a mutable kind, where the fill stops above before descending.
    +  if (!mayContain)
    +    obj.walkImmediateSubElements(
    +        [&](Attribute sub) {
    +          mayContain |= sub && computeMayContainSymbolRefs(sub);
    +        },
    +        [&](Type sub) {
    +          mayContain |= sub && computeMayContainSymbolRefs(sub);
    +        });
    +  return cache.insert(obj, mayContain, lock);
    +}
    +
    +// A type is never itself a SymbolRefAttr; an attribute is one exactly when
    +// isa<SymbolRefAttr> holds (covering FlatSymbolRefAttr).
    +static bool computeMayContainSymbolRefs(Type type) {
    +  return fillMayContainSymbolRefs(type, /*selfIsRef=*/false);
    +}
    +static bool computeMayContainSymbolRefs(Attribute attr) {
    +  return fillMayContainSymbolRefs(attr, /*selfIsRef=*/isa<SymbolRefAttr>(attr));
    +}
    +
    +bool SymbolTable::mayContainSymbolRefs(Type type) {
    +  return computeMayContainSymbolRefs(type);
    +}
    +bool SymbolTable::mayContainSymbolRefs(Attribute attr) {
    +  return computeMayContainSymbolRefs(attr);
    +}
    +
     //===----------------------------------------------------------------------===//
     // SymbolTable Trait Types
     //===----------------------------------------------------------------------===//
     
    -/// Verify the symbol uses held by the types owned by `op`: its operand,
    -/// result, and block-argument types, and any types nested within its
    -/// attributes. `op` is the anchor used for symbol lookups. `verifiedTypes`
    -/// records the types already verified within the current symbol table so that
    -/// each type, which may be uniqued and shared across many positions or
    -/// operations, is verified at most once. Verification fails fast on the first
    -/// invalid symbol use.
    +/// Verify the symbol uses held by the types owned by `op`: its operand, result,
    +/// and block-argument types, and any types nested within its attributes.
    +/// `walker` carries the SymbolUserTypeInterface check as a type-walk callback,
    +/// anchored at the operation currently being verified, and its visited memo
    +/// makes each uniqued type, which may recur across many positions and
    +/// operations, verified against the enclosing symbol table at most once.
    +/// Verification fails fast on the first invalid symbol use.
     static LogicalResult verifyOpTypeSymbolUses(Operation *op,
    -                                            SymbolTableCollection &symbolTable,
    -                                            SetVector<Type> &verifiedTypes) {
    -  // Walk `type` and any nested type parameters reachable from it, verifying
    -  // each not-yet-seen type and interrupting on the first failure.
    +                                            AttrTypeWalker &walker) {
    +  // A root that provably contains no SymbolRefAttr is not worth entering; the
    +  // walker's callbacks prune interior subtrees the same way.
       auto verify = [&](Type type) {
    -    return type.walk<WalkOrder::PreOrder>([&](Type nestedType) {
    -      if (!verifiedTypes.insert(nestedType))
    -        return WalkResult::advance();
    -      if (auto user = dyn_cast<SymbolUserTypeInterface>(nestedType))
    -        if (failed(user.verifySymbolUses(op, symbolTable)))
    -          return WalkResult::interrupt();
    +    if (!SymbolTable::mayContainSymbolRefs(type))

    We can tighten this.

    Minimal version:

    Drop this guard: the walker performs the same query per node and its memo already handles duplicate visits within the verification. So this is strictly redundant probing multiplied by the occurrence count.

    Fuller version, what I tested: we're duplicating hash probes here and we don't need to.

    Replacing this with a (admittedly, quick prototype hacked to test whether this idea among a handful of others) scope-lived map that answers both "have we visited this yet" and "may this contain refs" in a single probe per node benchmarked end-to-end: recovery goes 70% -> 77% in my runs.
    Concretely this saved another ~50s of a ~550s end-to-end compile (~1/4 of this patch's remaining gap).

    dtzSiFive dtzSiFive commented on code on Aug 19, 2026 21:05 UTC
    Code Review
    mlir/lib/IR/SymbolTable.cpp:1
    @@ -511,14 +567,27 @@ static LogicalResult verifyOpTypeSymbolUses(Operation *op,
             if (verify(argument.getType()).wasInterrupted())
               return failure();
     
    -  // Verify types nested within the operation's attributes.
    -  WalkResult attrResult =
    -      op->getAttrDictionary().walk<WalkOrder::PreOrder>([&](Type type) {
    -        if (verify(type).wasInterrupted())
    -          return WalkResult::interrupt();
    -        return WalkResult::advance();
    -      });
    -  return failure(attrResult.wasInterrupted());
    +  // Verify types nested within the operation's attributes, routed through the
    +  // same walker (and thus the same visited memo) as the type positions above.
    +  // Read the raw stored attribute dictionary rather than getAttrDictionary():
    +  // the latter allocates and uniques a fresh DictionaryAttr for every operation
    +  // that keeps its inherent attributes in properties. The raw dictionary
    +  // already covers inherent attributes for operations that do not use
    +  // properties, and the discardable attributes otherwise; the properties-held
    +  // inherent attributes are appended into a stack-local NamedAttrList via
    +  // populateInherentAttrs and walked separately -- the same coverage
    +  // getAttrDictionary() provides, since it calls the same
    +  // populateInherentAttrs.
    +  if (verifyAttr(op->getRawDictionaryAttrs()).wasInterrupted())
    +    return failure();
    +  if (op->getPropertiesStorageSize()) {
    +    NamedAttrList inherentAttrs;

    Elsewhere, I found minor benefit to hoisting the NamedAttrList out, to avoid malloc traffic (it can reuse its internal storage). If this shows up that's something to consider. No action requested just noting.

    dtzSiFive dtzSiFive commented on Aug 19, 2026 21:05 UTC
    Reviewer

    Thanks, @jaredhoberock !

    Benchmarking quite a bit:

  • current main: ~3.2x end-to-end (~30 verification passes, ~93% of the cost is from after-first verification (--> this isn't just a cost we pay once to fill the map))

  • this PR as of your new version from this morning: ~70% end-to-end recovered (leaves +66% on our compiles).

  • the previous storage-bit version, FWIW: recovered ~88%

  • #212160 alone: full recovery (within noise), zero memory delta. Not surprising but just reporting.
  • I spent some time looking into where the costs of this version go.

    It doesn't appear to be the mutex (disabling threading, as well as using a lock-free two-level variant, recover nothing) and not obviously cache locality (LLC misses same, IPC actually rises), so I went focusing primarily on instruction count.

    In particular, the per-object map lookup is a hash/probe for every type/attr/sub-element per verification... ~+2.8% retired instructions at scale.
    Compared to the storage bit approach, where the load is from memory we already touch.

    I explored a few ways of shaving things down since this is still quite expensive.

    Please see my comments below. In short:

    1. Don't recurse more than needed, exit early
    2. Collapse the 3x hash/probe as much as we can

    None of this has to block, adapt and explore as you see fit. Especially (2) I can push on in a follow-up PR if we'd like.

    On the memory side, this rework appears to be a clear win, FWIW. The materialization of dictionaries permanently interned is gone (~780MB on a larger design end-to-end vs current main).

    jaredhoberock jaredhoberock commented on Aug 19, 2026 21:16 UTC
    Author

    @dtzSiFive Thanks a lot for testing and the suggestions, will keep working on it!

    jaredhoberock jaredhoberock commented on code on Aug 20, 2026 01:15 UTC
    Code Review
    mlir/lib/IR/SymbolTable.cpp:1
    @@ -476,49 +476,57 @@ raw_ostream &mlir::operator<<(raw_ostream &os,
     // SymbolTable Trait Types
     //===----------------------------------------------------------------------===//
     
    -/// Verify the symbol uses held by the types owned by `op`: its operand,
    -/// result, and block-argument types, and any types nested within its
    -/// attributes. `op` is the anchor used for symbol lookups. `verifiedTypes`
    -/// records the types already verified within the current symbol table so that
    -/// each type, which may be uniqued and shared across many positions or
    -/// operations, is verified at most once. Verification fails fast on the first
    -/// invalid symbol use.
    +/// Verify the symbol uses held by the types owned by `op`: its operand, result,
    +/// and block-argument types, and any types nested within its attributes.
    +/// `typeWalker` carries the SymbolUserTypeInterface check as a walk callback,
    +/// anchored at `op` for symbol lookups, and its shared visited set makes each
    +/// uniqued type, which may recur across many positions and operations, verified
    +/// against the enclosing symbol table at most once. A type or attribute whose
    +/// interning-time bit is clear is skipped: it provably contains no
    +/// SymbolRefAttr, and a SymbolUserTypeInterface type is required to spell its
    +/// references as SymbolRefAttr sub-elements, so walking it would verify
    +/// nothing. Verification fails fast on the first invalid symbol use.
     static LogicalResult verifyOpTypeSymbolUses(Operation *op,
    -                                            SymbolTableCollection &symbolTable,
    -                                            SetVector<Type> &verifiedTypes) {
    -  // Walk `type` and any nested type parameters reachable from it, verifying
    -  // each not-yet-seen type and interrupting on the first failure.
    -  auto verify = [&](Type type) {
    -    return type.walk<WalkOrder::PreOrder>([&](Type nestedType) {
    -      if (!verifiedTypes.insert(nestedType))
    -        return WalkResult::advance();
    -      if (auto user = dyn_cast<SymbolUserTypeInterface>(nestedType))
    -        if (failed(user.verifySymbolUses(op, symbolTable)))
    -          return WalkResult::interrupt();
    +                                            AttrTypeWalker &typeWalker) {
    +  auto verifyType = [&](Type type) {
    +    if (!type.mayContainSymbolRefs())
           return WalkResult::advance();
    -    });
    +    return typeWalker.walk<WalkOrder::PreOrder>(type);
    +  };
    +  auto verifyAttr = [&](Attribute attr) {
    +    if (!attr || !attr.mayContainSymbolRefs())
    +      return WalkResult::advance();
    +    return typeWalker.walk<WalkOrder::PreOrder>(attr);
       };
     
       for (Type type : op->getOperandTypes())
    -    if (verify(type).wasInterrupted())
    +    if (verifyType(type).wasInterrupted())
           return failure();
       for (Type type : op->getResultTypes())
    -    if (verify(type).wasInterrupted())
    +    if (verifyType(type).wasInterrupted())
           return failure();
       for (Region &region : op->getRegions())
         for (Block &block : region)
           for (BlockArgument argument : block.getArguments())
    -        if (verify(argument.getType()).wasInterrupted())
    +        if (verifyType(argument.getType()).wasInterrupted())
               return failure();
     
    -  // Verify types nested within the operation's attributes.
    -  WalkResult attrResult =
    -      op->getAttrDictionary().walk<WalkOrder::PreOrder>([&](Type type) {
    -        if (verify(type).wasInterrupted())
    -          return WalkResult::interrupt();
    -        return WalkResult::advance();
    -      });
    -  return failure(attrResult.wasInterrupted());
    +  // Verify types nested within the operation's attributes. Read the raw stored
    +  // attribute dictionary rather than getAttrDictionary(): the latter allocates
    +  // and uniques a fresh dictionary for every operation that keeps its inherent
    +  // attributes in properties. The raw dictionary already covers inherent
    +  // attributes for operations that do not use properties; the properties-held
    +  // inherent attributes are walked separately below.
    +  if (verifyAttr(op->getRawDictionaryAttrs()).wasInterrupted())
    +    return failure();
    +  if (op->getPropertiesStorageSize()) {
    +    NamedAttrList inherentAttrs;
    +    op->getName().populateInherentAttrs(op, inherentAttrs);

    Makes sense, I will look into a more natural way to visit properties once the surrounding code settles

    jaredhoberock jaredhoberock commented on Aug 20, 2026 20:09 UTC
    Author

    @dtzSiFive Thanks for testing and the suggestions. We applied two of them: populating the cache early-exits and NamedAttrList is hoisted. The other we tested against the current simpler implementation and found it was slightly worse (+3.5%) on our synthetic tests.

    Here are some findings from synthetic testing (retired instructions per pass, steady state):

    40k-op module (20k functions, wide signatures, sparse symbol refs):
    main 1583M -> this PR 328M (storage-bit design: 314M)

    500k-op module (50k functions, same shape plus function bodies):
    main 9033M -> this PR 2796M (storage-bit design: 2723M)

    Could you rerun your benchmarks against these changes when you get a chance?

    joker-eph joker-eph commented on Aug 20, 2026 21:17 UTC
    Contributor

    In the type/attr's storage (the previous revision of this PR): too invasive for a niche concern

    It's not clear to me why storing it in the context is less invasive? That equally touches the very core of the IR data structures here?

    Can't we cache this in the verifier instance itself?

    On SymbolTable: the verifier's symbol-table objects are function-locals

    Do you have a pointer to this? Can the verifier owns the cache somehow and leave the context out of this?

    jaredhoberock jaredhoberock commented on Aug 21, 2026 01:31 UTC
    Author

    Can't we cache this in the verifier instance itself?

    We can, but the cache needs to be longer-lived than that to be useful. When the cache is attached to the verifier, it rebuilds on every verification and is often not much better than no cache at all.

    Here are some results from my synthetic tests, lower is better:

                                                main   no cache   verifier-scoped   context-owned (this PR)
      End-to-end wall clock:
    
      distinct-per-op dictionaries, 40 passes   1.02s    0.92s        0.71s            0.33s
      640 nested symbol tables, 21 passes       2.10s    1.03s        0.98s            0.71s
      wide signatures, 40k ops, 21 passes       1.95s    0.80s        0.74s            0.70s
      500k ops, parse-dominated, 11 passes      7.44s    4.15s        4.06s            4.05s
      properties-dense, 21 passes               1.92s    1.20s        1.21s            1.22s
      
      Retired instructions per verification pass:
      
      distinct-per-op dictionaries               333M     175M         170M              68M
      640 nested symbol tables                  1597M     521M         487M             350M
      wide signatures, 40k ops                  1588M     372M         358M             329M
      500k ops, parse-dominated                 9126M    2979M        2893M            2816M
      properties-dense                          1462M     801M         778M             779M
    

    @dtzSiFive are you able to easily share your benchmark so that I can benchmark these different options on a real workload?

    dtzSiFive dtzSiFive commented on Aug 21, 2026 16:09 UTC
    Contributor

    Hi folks! Thanks for the great work here!

    I'll respond soon with some additional feedback/thoughts, but to avoid very high costs to ourselves and other users while we work on sorting out the verification strategy, I've opened a PR to back out this interface.

    This crosses the threshold for (blameless) revert due to performance regressions, and our users and specifically CIRCT need to use a recent LLVM (without a 2-3x slowdown, YMMV) in the interim when they use the very common SymbolTable infrastructure.

    We can reland it once we get this squared away; I'm optimistic we can get this within noise or at least single-digit when there's no work to be done generally but let's see what we can figure out and how we'd like to move forward with this.

    https://github.com/llvm/llvm-project/pull/217959

    dtzSiFive dtzSiFive commented on Aug 21, 2026 17:15 UTC
    Contributor

    Some high-level thoughts:

    First:
    The general philosophy for verifiers is they're on the simple side. I don't know that we've crossed that boundary but something to keep in mind. We don't want a who-verifies-the-verifiers situation.

    Second:
    There's a lot of walking done here that at compile-time we (could) know is unnecessary, and it's by leveraging this I'm hoping we can arrive at an answer that dramatically reduces the additional cost of this verification.
    Basic idea is store immutable bits per type/attribute/op kind.

    I'm prototyping this presently. This appears to be entirely orthogonal to our optimizations above/so far; it's a different sort of intrusive however as it still needs to store the knowledge somewhere[1]. While verification is the primary motivating user here, I think it could be leveraged elsewhere to some benefit as well beyond verification, such as walks looking for symbol users.

    All attributes and types : we can determine in ODS whether an attribute/type is known to necessarily be "symbol ref free". We can compute this as a simple fold over their structure at generation time. The answer would tentatively end up set in AbstractType/AbstractAttribute, as an immutable bit set at registration.
    All operations: for all inherent attributes and for all operand and result types, are they "symbol ref free"? If so, only look to their discardable attributes. This would tentatively live in OperationName.

    How do we feel about this sort of direction?

    [1] Ideas welcome for ways to capture this static information for our use that are less intrusive and ideally extensible for other use cases!

    jaredhoberock jaredhoberock commented on Aug 21, 2026 18:46 UTC
    Author

    The kind-level bit sounds interesting as a partial solution for statically-classifiable objects. There's still the gap left by instance-sensitive containers like DictionaryAttr.

    In any case, these bits born as early as possible and stored close to the object of interest is probably the most principled shape, if intrusive. It eliminates all the complexity and performance concerns of caching and locking.

    So I'm for this direction if maintainers feel like it's a worthwhile trade-off.

    dtzSiFive dtzSiFive commented on Aug 21, 2026 19:54 UTC
    Contributor

    @dtzSiFive are you able to easily share your benchmark so that I can benchmark these different options on a real workload?

    The real workload, no, it's a private design.

    I've also been using a public RocketChip core and can direct you how to generate that or share the MLIR with you if that's useful. However it's primarily using dialects specific to the CIRCT project, so I'm not sure if that's how you'd like to proceed.

    The other we tested against the current simpler implementation and found it was slightly worse (+3.5%) on our synthetic tests.

    Good catch, apologies. This was the "minimal" suggestion I made, right? Yeah that was a mistake on my end.
    The full version drops the walker entirely and combines its memo table with a local cache / state bits for the walk, essentially. That was the improvement. Thanks for the careful benchmarking on your end.

    FWIW I don't see in your table entries for "before this interface was added", which might help re:apples-to-apples as we weigh the cost of this verification. If you're able to see 2-3x, that's about what we're seeing, then your synthetic workloads are likely enough to continue development against.

    jaredhoberock jaredhoberock commented on Aug 21, 2026 21:52 UTC
    Author

    Rebased onto current main, and now the branch begins with the reland of #198435. I'm not proposing to land this draft, just housekeeping this PR.

    Also, the synthetic (and AI-generated) benchmark suite I've been using is here in case it is useful. It now includes the before-the-interface baseline. The regression factor is 1.7x-3.3x across test program shapes on my machine which roughly agrees with what you observe.

    The real workload, no, it's a private design.

    @dtzSiFive no worries, your kind-bits prototype should be able to run on the public benchmark suite without issue. ./bench.sh /path/to/your/mlir-opt adds it to the comparison.

    Mogball Mogball commented on Aug 23, 2026 22:32 UTC
    Contributor

    Hey just commenting here that your original pull request can also cause compiler blowups when validating large LLVM types. Compiler programs that used to take ~500 MB of memory blew up to >16GB and started crashing my laptop :/

    joker-eph joker-eph commented on Aug 28, 2026 10:25 UTC
    Contributor

    @Mogball : Can you take your LLVM program and extract the pattern so we can generate synthetic examples that reproduce it? An agent should be able to do that easily hopefully.

    Mogball Mogball commented on Aug 28, 2026 16:43 UTC
    Contributor

    Yes

    jeffniu-openai jeffniu-openai commented on Sep 02, 2026 21:11 UTC
    Contributor

    Message from Jeff's Codex

    Here’s an upstream-only MLIR [reproducer](GIST_URL). Run with LLVM b010a18d2b64:

    time mlir-opt reproducer.mlir --emit-bytecode -o /dev/null
    

    Locally, this takes 1.39 s with the original verifier versus 0.15 s with the revert. It repeatedly walks the same wide LLVM struct.

    This reproduces the slowdown, but not the previously reported 16 GB memory growth.

    jaredhoberock jaredhoberock commented on Sep 03, 2026 21:43 UTC
    Author

    @Mogball the reproducer link in the Codex message came through as a literal GIST_URL. Could you post the actual link? I'd like to incorporate your reproducer into my benchmark suite.

    @dtzSiFive are you still planning on exploring your kinds-bit prototype idea? If so, I'll hold off, but if not I'm happy to prototype the idea in this branch and benchmark.

    jaredhoberock jaredhoberock commented on Sep 04, 2026 03:40 UTC
    Author

    Thanks, added your repro to the benchmark suite and measured the five design points on it:

    | build | wall | instructions / pass | peak RSS |
    |---|---|---|---|
    | before the interface (post-revert main) | 1.17 s | 165 M | 79 MB |
    | interface as landed (#198435) | 3.80 s | 6.0 G | 79 MB |
    | this branch, walker only (no cache) | 1.20 s | 184 M | 79 MB |
    | this branch, cache per verifier scope | 1.18 s | 182 M | 79 MB |
    | this branch, cache on the context | 1.18 s | 181 M | 79 MB |

    So the current PR brings your program back to within ~1% of the pre-interface floor on wall time (~10% on instructions per pass), and the hoisted walker alone accounts for essentially all of the recovery.

    Reviewers
    Assignees
    jaredhoberock jaredhoberock
    Labels
    risk: low confidence: 88.8% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 68.8% (HIGH) · Higher = larger blast radius
    68.8%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 88.8% · Lower = rushed or shallow review
    88.8%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 7.7% · Safe to merge
    7.7%