Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 23 additions & 2 deletions mlir/lib/Dialect/Vector/IR/VectorOps.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5992,8 +5992,29 @@ OpFoldResult ShapeCastOp::fold(FoldAdaptor adaptor) {

// shape_cast(constant) -> constant
if (auto splatAttr =
llvm::dyn_cast_if_present<SplatElementsAttr>(adaptor.getSource()))
return splatAttr.reshape(getType());
llvm::dyn_cast_if_present<SplatElementsAttr>(adaptor.getSource())) {

// The shape and 'scalable dims' of the new attribute must match the result
// of the shape_cast:
auto newShape = resultType.getShape();
auto newScalableDims = resultType.getScalableDims();

// The element type must be retained. Note that this is to handle currently
// valid IR like
//
// ```
// %0 = llvm.mlir.constant(dense<0.> : vector<1xf8E4M3FN>) : vector<1xi8>
// %1 = vector.shape_cast %0 : vector<1xi8> to vector<1x1xi8>
// ```
//
// where the element types of the attribute and result do not match.
auto newElementType = splatAttr.getElementType();

auto newAttr = VectorType::get(newShape, newElementType, newScalableDims);

return DenseElementsAttr::get(newAttr,
splatAttr.getSplatValue<Attribute>());
}

// shape_cast(poison) -> poison
if (llvm::dyn_cast_if_present<ub::PoisonAttr>(adaptor.getSource())) {
Expand Down
12 changes: 12 additions & 0 deletions mlir/test/Dialect/Vector/canonicalize.mlir
Original file line number Diff line number Diff line change
Expand Up @@ -1037,6 +1037,18 @@ func.func @fold_broadcast_shapecast(%arg0: vector<4xf32>) -> vector<4xf32> {

// -----

// CHECK-LABEL: func @canonicalize_extract_shapecast_different_element_type
Copy link
Contributor

@newling newling Jul 14, 2025

Choose a reason for hiding this comment

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

Something along the lines of:

// CHECK: [...] = llvm.mlir.constant
// CHECK-NEXT: return %[[CONST]] 

will be more explicit.

Wondering if it is ok to mix llvm dialect here, I guess so?

Copy link
Author

Choose a reason for hiding this comment

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

Yes it's OK. Updated.

// CHECK: %[[CONST:.*]] = llvm.mlir.constant
// CHECK-NEXT: return %[[CONST]]
func.func @canonicalize_extract_shapecast_different_element_type()->vector<12xi8> {
%0 = llvm.mlir.constant(dense<0.000000e+00> : vector<12xf8E4M3FN>) : vector<12xi8>
%1 = vector.shape_cast %0 : vector<12xi8> to vector<1x12xi8>
%2 = vector.extract %1[0] : vector<12xi8> from vector<1x12xi8>
return %2 : vector<12xi8>
}

// -----

// CHECK-LABEL: func @canonicalize_broadcast_shapecast_scalar
// CHECK: vector.broadcast
// CHECK-NOT: vector.shape_cast
Expand Down
Loading