-
Notifications
You must be signed in to change notification settings - Fork 14.3k
[flang] Added fir.is_contiguous_box and fir.box_total_elements ops. #131047
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
These are helper operations to aid with expanding of fir.pack_array.
@llvm/pr-subscribers-flang-fir-hlfir @llvm/pr-subscribers-flang-driver Author: Slava Zakharin (vzakhari) ChangesThese are helper operations to aid with expanding of fir.pack_array. Patch is 34.51 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/131047.diff 19 Files Affected:
diff --git a/flang/include/flang/Optimizer/Builder/Runtime/Inquiry.h b/flang/include/flang/Optimizer/Builder/Runtime/Inquiry.h
index 3707273e0cbd4..9f90b64f40e48 100644
--- a/flang/include/flang/Optimizer/Builder/Runtime/Inquiry.h
+++ b/flang/include/flang/Optimizer/Builder/Runtime/Inquiry.h
@@ -50,9 +50,15 @@ mlir::Value genSize(fir::FirOpBuilder &builder, mlir::Location loc,
mlir::Value genSizeDim(fir::FirOpBuilder &builder, mlir::Location loc,
mlir::Value array, mlir::Value dim);
-/// Generate call to `Is_contiguous` runtime routine.
+/// Generate call to `IsContiguous` runtime routine.
mlir::Value genIsContiguous(fir::FirOpBuilder &builder, mlir::Location loc,
mlir::Value array);
+/// Generate call to `IsContiguousUpTo` runtime routine.
+/// \p dim specifies the dimension up to which contiguity
+/// needs to be checked (not exceeding the actual rank of the array).
+mlir::Value genIsContiguousUpTo(fir::FirOpBuilder &builder, mlir::Location loc,
+ mlir::Value array, mlir::Value dim);
+
} // namespace fir::runtime
#endif // FORTRAN_OPTIMIZER_BUILDER_RUNTIME_INQUIRY_H
diff --git a/flang/include/flang/Optimizer/Dialect/FIROps.td b/flang/include/flang/Optimizer/Dialect/FIROps.td
index 7147a2401baa7..2710c7def68be 100644
--- a/flang/include/flang/Optimizer/Dialect/FIROps.td
+++ b/flang/include/flang/Optimizer/Dialect/FIROps.td
@@ -3416,4 +3416,28 @@ def fir_UnpackArrayOp
let hasVerifier = 1;
}
+def fir_IsContiguousBoxOp : fir_Op<"is_contiguous_box", [NoMemoryEffect]> {
+ let summary = "Returns true if the boxed entity is contiguous";
+ let description = [{
+ Returns true iff the boxed entity is contiguous:
+ * in the leading dimension (if `innermost` attribute is set),
+ * in all dimensions (if `innermost` attribute is not set).
+ }];
+ let arguments = (ins AnyBoxLike:$box, UnitAttr:$innermost);
+ let results = (outs I1);
+
+ let assemblyFormat = [{
+ $box (`innermost` $innermost^):(`whole`)? attr-dict `:` functional-type(operands, results)
+ }];
+ let hasCanonicalizer = 1;
+}
+
+def fir_BoxTotalElementsOp
+ : fir_SimpleOneResultOp<"box_total_elements", [NoMemoryEffect]> {
+ let summary = "Returns the boxed entity's total size in elements";
+ let arguments = (ins AnyBoxLike:$box);
+ let results = (outs AnyIntegerLike);
+ let hasCanonicalizer = 1;
+}
+
#endif
diff --git a/flang/include/flang/Optimizer/Transforms/Passes.h b/flang/include/flang/Optimizer/Transforms/Passes.h
index afbbeb55632f1..406fedf220d26 100644
--- a/flang/include/flang/Optimizer/Transforms/Passes.h
+++ b/flang/include/flang/Optimizer/Transforms/Passes.h
@@ -62,6 +62,7 @@ namespace fir {
#define GEN_PASS_DECL_COMPILERGENERATEDNAMESCONVERSION
#define GEN_PASS_DECL_SETRUNTIMECALLATTRIBUTES
#define GEN_PASS_DECL_GENRUNTIMECALLSFORTEST
+#define GEN_PASS_DECL_SIMPLIFYFIROPERATIONS
#include "flang/Optimizer/Transforms/Passes.h.inc"
@@ -86,6 +87,9 @@ void populateCfgConversionRewrites(mlir::RewritePatternSet &patterns,
bool forceLoopToExecuteOnce = false,
bool setNSW = true);
+void populateSimplifyFIROperationsPatterns(mlir::RewritePatternSet &patterns,
+ bool preferInlineImplementation);
+
// declarative passes
#define GEN_PASS_REGISTRATION
#include "flang/Optimizer/Transforms/Passes.h.inc"
diff --git a/flang/include/flang/Optimizer/Transforms/Passes.td b/flang/include/flang/Optimizer/Transforms/Passes.td
index 64341b42bd1e4..e5c17cf7d8881 100644
--- a/flang/include/flang/Optimizer/Transforms/Passes.td
+++ b/flang/include/flang/Optimizer/Transforms/Passes.td
@@ -486,4 +486,18 @@ def GenRuntimeCallsForTest
let dependentDialects = ["fir::FIROpsDialect", "mlir::func::FuncDialect"];
}
+def SimplifyFIROperations : Pass<"simplify-fir-operations", "mlir::ModuleOp"> {
+ let summary = "Simplifies complex FIR operations";
+ let description = [{
+ Expands complex FIR operations into their equivalent using
+ FIR, SCF and other usual dialects. It may also generate calls
+ to Fortran runtime.
+ }];
+
+ let options = [Option<
+ "preferInlineImplementation", "prefer-inline-implementation", "bool",
+ /*default=*/"false",
+ "Prefer expanding without using Fortran runtime calls.">];
+}
+
#endif // FLANG_OPTIMIZER_TRANSFORMS_PASSES
diff --git a/flang/include/flang/Runtime/support.h b/flang/include/flang/Runtime/support.h
index 4a6d4357e8710..b2f43b811c0ab 100644
--- a/flang/include/flang/Runtime/support.h
+++ b/flang/include/flang/Runtime/support.h
@@ -34,6 +34,10 @@ extern "C" {
// Predicate: is the storage described by a Descriptor contiguous in memory?
bool RTDECL(IsContiguous)(const Descriptor &);
+// Predicate: is the storage described by a Descriptor contiguous in memory
+// up to the given dimension?
+bool RTDECL(IsContiguousUpTo)(const Descriptor &, char);
+
// Predicate: is this descriptor describing an assumed-size array?
bool RTDECL(IsAssumedSize)(const Descriptor &);
diff --git a/flang/lib/Optimizer/Builder/Runtime/Inquiry.cpp b/flang/lib/Optimizer/Builder/Runtime/Inquiry.cpp
index f4d03c95ae518..718c3533564e8 100644
--- a/flang/lib/Optimizer/Builder/Runtime/Inquiry.cpp
+++ b/flang/lib/Optimizer/Builder/Runtime/Inquiry.cpp
@@ -91,7 +91,7 @@ mlir::Value fir::runtime::genSize(fir::FirOpBuilder &builder,
return builder.create<fir::CallOp>(loc, sizeFunc, args).getResult(0);
}
-/// Generate call to `Is_contiguous` runtime routine.
+/// Generate call to `IsContiguous` runtime routine.
mlir::Value fir::runtime::genIsContiguous(fir::FirOpBuilder &builder,
mlir::Location loc,
mlir::Value array) {
@@ -102,6 +102,18 @@ mlir::Value fir::runtime::genIsContiguous(fir::FirOpBuilder &builder,
return builder.create<fir::CallOp>(loc, isContiguousFunc, args).getResult(0);
}
+/// Generate call to `IsContiguousUpTo` runtime routine.
+mlir::Value fir::runtime::genIsContiguousUpTo(fir::FirOpBuilder &builder,
+ mlir::Location loc,
+ mlir::Value array,
+ mlir::Value dim) {
+ mlir::func::FuncOp isContiguousFunc =
+ fir::runtime::getRuntimeFunc<mkRTKey(IsContiguousUpTo)>(loc, builder);
+ auto fTy = isContiguousFunc.getFunctionType();
+ auto args = fir::runtime::createArguments(builder, loc, fTy, array, dim);
+ return builder.create<fir::CallOp>(loc, isContiguousFunc, args).getResult(0);
+}
+
void fir::runtime::genShape(fir::FirOpBuilder &builder, mlir::Location loc,
mlir::Value resultAddr, mlir::Value array,
mlir::Value kind) {
diff --git a/flang/lib/Optimizer/Dialect/FIROps.cpp b/flang/lib/Optimizer/Dialect/FIROps.cpp
index 033d6453a619a..0e0745bc6d29d 100644
--- a/flang/lib/Optimizer/Dialect/FIROps.cpp
+++ b/flang/lib/Optimizer/Dialect/FIROps.cpp
@@ -4671,6 +4671,79 @@ void fir::UnpackArrayOp::getEffects(
mlir::SideEffects::DefaultResource::get());
}
+//===----------------------------------------------------------------------===//
+// IsContiguousBoxOp
+//===----------------------------------------------------------------------===//
+
+namespace {
+struct SimplifyIsContiguousBoxOp
+ : public mlir::OpRewritePattern<fir::IsContiguousBoxOp> {
+ using mlir::OpRewritePattern<fir::IsContiguousBoxOp>::OpRewritePattern;
+ mlir::LogicalResult
+ matchAndRewrite(fir::IsContiguousBoxOp op,
+ mlir::PatternRewriter &rewriter) const override;
+};
+} // namespace
+
+mlir::LogicalResult SimplifyIsContiguousBoxOp::matchAndRewrite(
+ fir::IsContiguousBoxOp op, mlir::PatternRewriter &rewriter) const {
+ auto boxType = mlir::cast<fir::BaseBoxType>(op.getBox().getType());
+ // Nothing to do for assumed-rank arrays and !fir.box<none>.
+ if (boxType.isAssumedRank() || fir::isBoxNone(boxType))
+ return mlir::failure();
+
+ if (fir::getBoxRank(boxType) == 0) {
+ // Scalars are always contiguous.
+ mlir::Type i1Type = rewriter.getI1Type();
+ rewriter.replaceOpWithNewOp<mlir::arith::ConstantOp>(
+ op, i1Type, rewriter.getIntegerAttr(i1Type, 1));
+ return mlir::success();
+ }
+
+ return mlir::failure();
+}
+
+void fir::IsContiguousBoxOp::getCanonicalizationPatterns(
+ mlir::RewritePatternSet &patterns, mlir::MLIRContext *context) {
+ patterns.add<SimplifyIsContiguousBoxOp>(context);
+}
+
+//===----------------------------------------------------------------------===//
+// BoxTotalElementsOp
+//===----------------------------------------------------------------------===//
+
+namespace {
+struct SimplifyBoxTotalElementsOp
+ : public mlir::OpRewritePattern<fir::BoxTotalElementsOp> {
+ using mlir::OpRewritePattern<fir::BoxTotalElementsOp>::OpRewritePattern;
+ mlir::LogicalResult
+ matchAndRewrite(fir::BoxTotalElementsOp op,
+ mlir::PatternRewriter &rewriter) const override;
+};
+} // namespace
+
+mlir::LogicalResult SimplifyBoxTotalElementsOp::matchAndRewrite(
+ fir::BoxTotalElementsOp op, mlir::PatternRewriter &rewriter) const {
+ auto boxType = mlir::cast<fir::BaseBoxType>(op.getBox().getType());
+ // Nothing to do for assumed-rank arrays and !fir.box<none>.
+ if (boxType.isAssumedRank() || fir::isBoxNone(boxType))
+ return mlir::failure();
+
+ if (fir::getBoxRank(boxType) == 0) {
+ // Scalar: 1 element.
+ rewriter.replaceOpWithNewOp<mlir::arith::ConstantOp>(
+ op, op.getType(), rewriter.getIntegerAttr(op.getType(), 1));
+ return mlir::success();
+ }
+
+ return mlir::failure();
+}
+
+void fir::BoxTotalElementsOp::getCanonicalizationPatterns(
+ mlir::RewritePatternSet &patterns, mlir::MLIRContext *context) {
+ patterns.add<SimplifyBoxTotalElementsOp>(context);
+}
+
//===----------------------------------------------------------------------===//
// FIROpsDialect
//===----------------------------------------------------------------------===//
diff --git a/flang/lib/Optimizer/Passes/Pipelines.cpp b/flang/lib/Optimizer/Passes/Pipelines.cpp
index 518be347fff85..3aea021e596f6 100644
--- a/flang/lib/Optimizer/Passes/Pipelines.cpp
+++ b/flang/lib/Optimizer/Passes/Pipelines.cpp
@@ -198,6 +198,11 @@ void createDefaultFIROptimizerPassPipeline(mlir::PassManager &pm,
pm.addPass(fir::createPolymorphicOpConversion());
pm.addPass(fir::createAssumedRankOpConversion());
+ // Expand FIR operations that may use SCF dialect for their
+ // implementation. This is a mandatory pass.
+ pm.addPass(fir::createSimplifyFIROperations(
+ {/*preferInlineImplementation=*/pc.OptLevel.isOptimizingForSpeed()}));
+
if (pc.AliasAnalysis && !disableFirAliasTags && !useOldAliasTags)
pm.addPass(fir::createAddAliasTags());
diff --git a/flang/lib/Optimizer/Transforms/CMakeLists.txt b/flang/lib/Optimizer/Transforms/CMakeLists.txt
index da4fc9cb716be..6e8666759ab83 100644
--- a/flang/lib/Optimizer/Transforms/CMakeLists.txt
+++ b/flang/lib/Optimizer/Transforms/CMakeLists.txt
@@ -31,6 +31,7 @@ add_flang_library(FIRTransforms
DebugTypeGenerator.cpp
SetRuntimeCallAttributes.cpp
GenRuntimeCallsForTest.cpp
+ SimplifyFIROperations.cpp
DEPENDS
CUFAttrs
diff --git a/flang/lib/Optimizer/Transforms/SimplifyFIROperations.cpp b/flang/lib/Optimizer/Transforms/SimplifyFIROperations.cpp
new file mode 100644
index 0000000000000..3c9e63cf9b18d
--- /dev/null
+++ b/flang/lib/Optimizer/Transforms/SimplifyFIROperations.cpp
@@ -0,0 +1,157 @@
+//===- SimplifyFIROperations.cpp -- simplify complex FIR operations ------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+//===----------------------------------------------------------------------===//
+/// \file
+/// This pass transforms some FIR operations into their equivalent
+/// implementations using other FIR operations. The transformation
+/// can legally use SCF dialect and generate Fortran runtime calls.
+//===----------------------------------------------------------------------===//
+
+#include "flang/Optimizer/Builder/BoxValue.h"
+#include "flang/Optimizer/Builder/CUFCommon.h"
+#include "flang/Optimizer/Builder/FIRBuilder.h"
+#include "flang/Optimizer/Builder/LowLevelIntrinsics.h"
+#include "flang/Optimizer/Builder/Todo.h"
+#include "flang/Optimizer/Dialect/FIROps.h"
+#include "flang/Optimizer/Dialect/FIRType.h"
+#include "flang/Optimizer/Dialect/Support/FIRContext.h"
+#include "flang/Optimizer/HLFIR/HLFIRDialect.h"
+#include "flang/Optimizer/Transforms/Passes.h"
+#include "flang/Optimizer/Transforms/Utils.h"
+#include "flang/Runtime/entry-names.h"
+#include "flang/Support/Fortran.h"
+#include "mlir/IR/Matchers.h"
+#include "mlir/IR/Operation.h"
+#include "mlir/Pass/Pass.h"
+#include "mlir/Transforms/DialectConversion.h"
+
+#include "flang/Optimizer/Builder/Runtime/Inquiry.h"
+
+namespace fir {
+#define GEN_PASS_DEF_SIMPLIFYFIROPERATIONS
+#include "flang/Optimizer/Transforms/Passes.h.inc"
+} // namespace fir
+
+#define DEBUG_TYPE "flang-simplify-fir-operations"
+
+namespace {
+/// Pass runner.
+class SimplifyFIROperationsPass
+ : public fir::impl::SimplifyFIROperationsBase<SimplifyFIROperationsPass> {
+public:
+ using fir::impl::SimplifyFIROperationsBase<
+ SimplifyFIROperationsPass>::SimplifyFIROperationsBase;
+
+ void runOnOperation() override final;
+};
+
+/// Base class for all conversions holding the pass options.
+template <typename Op>
+class ConversionBase : public mlir::OpRewritePattern<Op> {
+public:
+ using mlir::OpRewritePattern<Op>::OpRewritePattern;
+
+ template <typename... Args>
+ ConversionBase(mlir::MLIRContext *context, Args &&...args)
+ : mlir::OpRewritePattern<Op>(context),
+ options{std::forward<Args>(args)...} {}
+
+ mlir::LogicalResult matchAndRewrite(Op,
+ mlir::PatternRewriter &) const override;
+
+protected:
+ fir::SimplifyFIROperationsOptions options;
+};
+
+/// fir::IsContiguousBoxOp converter.
+using IsContiguousBoxCoversion = ConversionBase<fir::IsContiguousBoxOp>;
+
+/// fir::BoxTotalElementsOp converter.
+using BoxTotalElementsConversion = ConversionBase<fir::BoxTotalElementsOp>;
+} // namespace
+
+/// Generate a call to IsContiguous/IsContiguousUpTo function or an inline
+/// sequence reading extents/strides from the box and checking them.
+/// This conversion may produce fir.box_elesize and a loop (for assumed
+/// rank).
+template <>
+mlir::LogicalResult IsContiguousBoxCoversion::matchAndRewrite(
+ fir::IsContiguousBoxOp op, mlir::PatternRewriter &rewriter) const {
+ mlir::Location loc = op.getLoc();
+ fir::FirOpBuilder builder(rewriter, op.getOperation());
+ // TODO: support preferInlineImplementation.
+ bool doInline = options.preferInlineImplementation && false;
+ if (!doInline) {
+ // Generate Fortran runtime call.
+ mlir::Value result;
+ if (op.getInnermost()) {
+ mlir::Value one =
+ builder.createIntegerConstant(loc, builder.getI8Type(), 1);
+ result =
+ fir::runtime::genIsContiguousUpTo(builder, loc, op.getBox(), one);
+ } else {
+ result = fir::runtime::genIsContiguous(builder, loc, op.getBox());
+ }
+ result = builder.createConvert(loc, op.getType(), result);
+ rewriter.replaceOp(op, result);
+ return mlir::success();
+ }
+
+ // Generate inline implementation.
+ TODO(loc, "inline IsContiguousBoxOp");
+ return mlir::success();
+}
+
+/// Generate a call to Size runtime function or an inline
+/// sequence reading extents from the box an multiplying them.
+/// This conversion may produce a loop (for assumed rank).
+template <>
+mlir::LogicalResult BoxTotalElementsConversion::matchAndRewrite(
+ fir::BoxTotalElementsOp op, mlir::PatternRewriter &rewriter) const {
+ mlir::Location loc = op.getLoc();
+ fir::FirOpBuilder builder(rewriter, op.getOperation());
+ // TODO: support preferInlineImplementation.
+ // Reading the extent from the box for 1D arrays probably
+ // results in less code than the call, so we can always
+ // inline it.
+ bool doInline = options.preferInlineImplementation && false;
+ if (!doInline) {
+ // Generate Fortran runtime call.
+ mlir::Value result = fir::runtime::genSize(builder, loc, op.getBox());
+ result = builder.createConvert(loc, op.getType(), result);
+ rewriter.replaceOp(op, result);
+ return mlir::success();
+ }
+
+ // Generate inline implementation.
+ TODO(loc, "inline BoxTotalElementsOp");
+ return mlir::success();
+}
+
+void SimplifyFIROperationsPass::runOnOperation() {
+ mlir::ModuleOp module = getOperation();
+ mlir::MLIRContext &context = getContext();
+ mlir::ConversionTarget target(context);
+ target.addIllegalOp<fir::IsContiguousBoxOp>();
+ target.addIllegalOp<fir::BoxTotalElementsOp>();
+ mlir::RewritePatternSet patterns(&context);
+ fir::populateSimplifyFIROperationsPatterns(patterns,
+ preferInlineImplementation);
+ if (mlir::failed(
+ mlir::applyPartialConversion(module, target, std::move(patterns)))) {
+ mlir::emitError(module.getLoc(), DEBUG_TYPE " pass failed");
+ signalPassFailure();
+ }
+}
+
+void fir::populateSimplifyFIROperationsPatterns(
+ mlir::RewritePatternSet &patterns, bool preferInlineImplementation) {
+ patterns.insert<IsContiguousBoxCoversion, BoxTotalElementsConversion>(
+ patterns.getContext(), preferInlineImplementation);
+}
diff --git a/flang/test/Driver/bbc-mlir-pass-pipeline.f90 b/flang/test/Driver/bbc-mlir-pass-pipeline.f90
index 5520d750e2ce1..276ef818622a1 100644
--- a/flang/test/Driver/bbc-mlir-pass-pipeline.f90
+++ b/flang/test/Driver/bbc-mlir-pass-pipeline.f90
@@ -47,6 +47,7 @@
! CHECK-NEXT: PolymorphicOpConversion
! CHECK-NEXT: AssumedRankOpConversion
+! CHECK-NEXT: SimplifyFIROperations
! CHECK-NEXT: Pipeline Collection : ['fir.global', 'func.func', 'omp.declare_reduction', 'omp.private']
! CHECK-NEXT: 'fir.global' Pipeline
diff --git a/flang/test/Driver/mlir-debug-pass-pipeline.f90 b/flang/test/Driver/mlir-debug-pass-pipeline.f90
index edc6f59b0ad7c..70fa0cf5ae47c 100644
--- a/flang/test/Driver/mlir-debug-pass-pipeline.f90
+++ b/flang/test/Driver/mlir-debug-pass-pipeline.f90
@@ -77,6 +77,7 @@
! ALL-NEXT: PolymorphicOpConversion
! ALL-NEXT: AssumedRankOpConversion
+! ALL-NEXT: SimplifyFIROperations
! ALL-NEXT: Pipeline Collection : ['fir.global', 'func.func', 'omp.declare_reduction', 'omp.private']
! ALL-NEXT: 'fir.global' Pipeline
diff --git a/flang/test/Driver/mlir-pass-pipeline.f90 b/flang/test/Driver/mlir-pass-pipeline.f90
index 740897786dd37..852764be1f136 100644
--- a/flang/test/Driver/mlir-pass-pipeline.f90
+++ b/flang/test/Driver/mlir-pass-pipeline.f90
@@ -101,6 +101,7 @@
! ALL-NEXT: PolymorphicOpConversion
! ALL-NEXT: AssumedRankOpConversion
+! ALL-NEXT: SimplifyFIROperations
! O2-NEXT: AddAliasTags
! ALL-NEXT: Pipeline Collection : ['fir.global', 'func.func', 'omp.declare_reduction', 'omp.private']
diff --git a/flang/test/Fir/basic-program.fir b/flang/test/Fir/basic-program.fir
index 8b299674208fa..90bff80da1915 100644
--- a/flang/test/Fir/basic-program.fir
+++ b/flang/test/Fir/basic-program.fir
@@ -99,6 +99,7 @@ func.func @_QQmain() {
// PASSES-NEXT: PolymorphicOpConversion
// PASSES-NEXT: AssumedRankOpConversion
+// PASSES-NEXT: SimplifyFIROperations
// PASSES-NEXT: AddAliasTags
// PASSES-NEXT: Pipeline Collection : ['fir.global', 'func.func', 'omp.declare_reduction', 'omp.private']
diff --git a/flang/test/Fir/box-total-elements-fold.fir b/flang/test/Fir/box-total-elements-fold.fir
new file mode 100644
index 0000000000000..2df807dc27183
--- /dev/null
+++ b/flang/test/Fir/box-total-elements-fold.fir
@@ -0,0 +1,45 @@
+// RUN: fir-opt --canonicalize %s | FileCheck %s
+
+// No folding for !fir.box<none>.
+func.func @test_none(%arg0: !fir.box<none>) -> index {
+ %0 = fir.box_total_elements %arg0 : (!fir.box<none>) -> index
+ return %0 : index
+}
+// CHECK-LABEL: func.func @test_none(
+// CHECK-SAME: %[[VAL_0:[0-9]+|[a-zA-Z$._-][a-zA-Z0-9$._-]*]]: !fir.box<none>)...
[truncated]
|
I want to be able to check if the storage is contiguous in the innermost dimension, so I decided to add an entry point that takes `dim` as the number of leading dimensions to check. It seems that a runtime call might result in less code size even when `dim` is 1, so here it is. For opt-for-speed I am going to inline it in FIR. Depends on llvm#131047.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Looks great, those helper operations makes sense to me.
rewriter.replaceOpWithNewOp<mlir::arith::ConstantOp>( | ||
op, op.getType(), rewriter.getIntegerAttr(op.getType(), 1)); | ||
return mlir::success(); | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Result of fir.embox without slices can also fold to true (there are other cases, but it is a good start and some fir::isSimplyConintiguous(box) helper could be added later to try to walk back more, which could be helpful after inlining).
fir::populateSimplifyFIROperationsPatterns(patterns, | ||
preferInlineImplementation); | ||
if (mlir::failed( | ||
mlir::applyPartialConversion(module, target, std::move(patterns)))) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
As I understand it, dialect conversions are more expensive than applyPatternsAndFoldGreedily that could be used here given there is no operation result type change.
The illegal op check is nice, but I am not sure it is worth using it (codegen will complain anyway).
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks! I will use the greedy rewriter.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks for this. Why did you decide to lower these ops in a separate pass instead of in early codegen e.g. codegen-rewrite?
}; | ||
} // namespace | ||
|
||
mlir::LogicalResult SimplifyBoxTotalElementsOp::matchAndRewrite( |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think we could also canonicalize this for cases where the number of elements is known at compile time inside of the type e.g. !fir.box<!fir.array<10xi32>>
I plan to use FIR loops (and maybe SCF ifs) for expanding these ops, so this has to be done before SCF-to-CF conversion, thus, before codegen-rewrite. I guess I could try to use just |
I do not want to identify later whether the box might be absent and generate redundant present checks. To avoid redundant present checks I can add attribute like `present`/`maybe_absent`, but I think it should be easy to generate these ops under the present check upstream. So I would like to make them simple at least for now.
I hope you do not mind that I just put TODOs in the canonicalization area. I would like to focus on array repacking, and then get back to handling more canonicalization, and using new operations earlier in the compilation (e.g. in intrinsic lowering). |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks for the update, looks great!
LLVM Buildbot has detected a new failure on builder Full details are available at: https://lab.llvm.org/buildbot/#/builders/35/builds/8178 Here is the relevant piece of the build log for the reference
|
I want to be able to check if the storage is contiguous in the innermost dimension, so I decided to add an entry point that takes `dim` as the number of leading dimensions to check. It seems that a runtime call might result in less code size even when `dim` is 1, so here it is. For opt-for-speed I am going to inline it in FIR. Depends on #131047.
These are helper operations to aid with expanding of fir.pack_array.