xref: /llvm-project/flang/lib/Optimizer/Transforms/PolymorphicOpConversion.cpp (revision a78359c2ed68489b2dde558c2660515e481ae60f)
1ff761f2cSRenaud-K //===-- PolymorphicOpConversion.cpp ---------------------------------------===//
2ff761f2cSRenaud-K //
3ff761f2cSRenaud-K // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4ff761f2cSRenaud-K // See https://llvm.org/LICENSE.txt for license information.
5ff761f2cSRenaud-K // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6ff761f2cSRenaud-K //
7ff761f2cSRenaud-K //===----------------------------------------------------------------------===//
8ff761f2cSRenaud-K 
94c5dee77SRenaud-K #include "flang/Lower/BuiltinModules.h"
104c5dee77SRenaud-K #include "flang/Optimizer/Builder/Todo.h"
11ff761f2cSRenaud-K #include "flang/Optimizer/Dialect/FIRDialect.h"
12ff761f2cSRenaud-K #include "flang/Optimizer/Dialect/FIROps.h"
13ff761f2cSRenaud-K #include "flang/Optimizer/Dialect/FIROpsSupport.h"
144c5dee77SRenaud-K #include "flang/Optimizer/Dialect/FIRType.h"
15b07ef9e7SRenaud-K #include "flang/Optimizer/Dialect/Support/FIRContext.h"
16b07ef9e7SRenaud-K #include "flang/Optimizer/Dialect/Support/KindMapping.h"
17ff761f2cSRenaud-K #include "flang/Optimizer/Support/InternalNames.h"
18ff761f2cSRenaud-K #include "flang/Optimizer/Support/TypeCode.h"
194c5dee77SRenaud-K #include "flang/Optimizer/Support/Utils.h"
20ff761f2cSRenaud-K #include "flang/Optimizer/Transforms/Passes.h"
21ff761f2cSRenaud-K #include "flang/Runtime/derived-api.h"
224c5dee77SRenaud-K #include "flang/Semantics/runtime-type-info.h"
23ff761f2cSRenaud-K #include "mlir/Dialect/Affine/IR/AffineOps.h"
244c5dee77SRenaud-K #include "mlir/Dialect/Arith/IR/Arith.h"
25ff761f2cSRenaud-K #include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h"
26ff761f2cSRenaud-K #include "mlir/Dialect/Func/IR/FuncOps.h"
274c5dee77SRenaud-K #include "mlir/IR/BuiltinOps.h"
28ff761f2cSRenaud-K #include "mlir/Pass/Pass.h"
29ff761f2cSRenaud-K #include "mlir/Transforms/DialectConversion.h"
30ff761f2cSRenaud-K #include "llvm/ADT/SmallSet.h"
31ff761f2cSRenaud-K #include "llvm/Support/CommandLine.h"
32ff761f2cSRenaud-K 
33ff761f2cSRenaud-K namespace fir {
34ff761f2cSRenaud-K #define GEN_PASS_DEF_POLYMORPHICOPCONVERSION
35ff761f2cSRenaud-K #include "flang/Optimizer/Transforms/Passes.h.inc"
36ff761f2cSRenaud-K } // namespace fir
37ff761f2cSRenaud-K 
38ff761f2cSRenaud-K using namespace fir;
39ff761f2cSRenaud-K using namespace mlir;
40ff761f2cSRenaud-K 
41ff761f2cSRenaud-K namespace {
42ff761f2cSRenaud-K 
43ff761f2cSRenaud-K /// SelectTypeOp converted to an if-then-else chain
44ff761f2cSRenaud-K ///
45ff761f2cSRenaud-K /// This lowers the test conditions to calls into the runtime.
46ff761f2cSRenaud-K class SelectTypeConv : public OpConversionPattern<fir::SelectTypeOp> {
47ff761f2cSRenaud-K public:
48ff761f2cSRenaud-K   using OpConversionPattern<fir::SelectTypeOp>::OpConversionPattern;
49ff761f2cSRenaud-K 
50d1b3648eSTom Eccles   SelectTypeConv(mlir::MLIRContext *ctx)
51d1b3648eSTom Eccles       : mlir::OpConversionPattern<fir::SelectTypeOp>(ctx) {}
52ff761f2cSRenaud-K 
53db791b27SRamkumar Ramachandra   llvm::LogicalResult
54ff761f2cSRenaud-K   matchAndRewrite(fir::SelectTypeOp selectType, OpAdaptor adaptor,
55ff761f2cSRenaud-K                   mlir::ConversionPatternRewriter &rewriter) const override;
56ff761f2cSRenaud-K 
57ff761f2cSRenaud-K private:
58ff761f2cSRenaud-K   // Generate comparison of type descriptor addresses.
59ff761f2cSRenaud-K   mlir::Value genTypeDescCompare(mlir::Location loc, mlir::Value selector,
60ff761f2cSRenaud-K                                  mlir::Type ty, mlir::ModuleOp mod,
61ff761f2cSRenaud-K                                  mlir::PatternRewriter &rewriter) const;
62ff761f2cSRenaud-K 
63db791b27SRamkumar Ramachandra   llvm::LogicalResult genTypeLadderStep(mlir::Location loc,
64ff761f2cSRenaud-K                                         mlir::Value selector,
65ff761f2cSRenaud-K                                         mlir::Attribute attr, mlir::Block *dest,
66ff761f2cSRenaud-K                                         std::optional<mlir::ValueRange> destOps,
67ff761f2cSRenaud-K                                         mlir::ModuleOp mod,
68ff761f2cSRenaud-K                                         mlir::PatternRewriter &rewriter,
69ff761f2cSRenaud-K                                         fir::KindMapping &kindMap) const;
70ff761f2cSRenaud-K 
714ccd57ddSjeanPerier   llvm::SmallSet<llvm::StringRef, 4> collectAncestors(fir::TypeInfoOp dt,
72ff761f2cSRenaud-K                                                       mlir::ModuleOp mod) const;
73ff761f2cSRenaud-K };
74ff761f2cSRenaud-K 
754c5dee77SRenaud-K /// Lower `fir.dispatch` operation. A virtual call to a method in a dispatch
764c5dee77SRenaud-K /// table.
774c5dee77SRenaud-K struct DispatchOpConv : public OpConversionPattern<fir::DispatchOp> {
784c5dee77SRenaud-K   using OpConversionPattern<fir::DispatchOp>::OpConversionPattern;
794c5dee77SRenaud-K 
804c5dee77SRenaud-K   DispatchOpConv(mlir::MLIRContext *ctx, const BindingTables &bindingTables)
814c5dee77SRenaud-K       : mlir::OpConversionPattern<fir::DispatchOp>(ctx),
824c5dee77SRenaud-K         bindingTables(bindingTables) {}
834c5dee77SRenaud-K 
84db791b27SRamkumar Ramachandra   llvm::LogicalResult
854c5dee77SRenaud-K   matchAndRewrite(fir::DispatchOp dispatch, OpAdaptor adaptor,
864c5dee77SRenaud-K                   mlir::ConversionPatternRewriter &rewriter) const override {
874c5dee77SRenaud-K     mlir::Location loc = dispatch.getLoc();
884c5dee77SRenaud-K 
894c5dee77SRenaud-K     if (bindingTables.empty())
904c5dee77SRenaud-K       return emitError(loc) << "no binding tables found";
914c5dee77SRenaud-K 
924c5dee77SRenaud-K     // Get derived type information.
934c5dee77SRenaud-K     mlir::Type declaredType =
944c5dee77SRenaud-K         fir::getDerivedType(dispatch.getObject().getType().getEleTy());
95fac349a1SChristian Sigg     assert(mlir::isa<fir::RecordType>(declaredType) && "expecting fir.type");
96fac349a1SChristian Sigg     auto recordType = mlir::dyn_cast<fir::RecordType>(declaredType);
974c5dee77SRenaud-K 
984c5dee77SRenaud-K     // Lookup for the binding table.
994c5dee77SRenaud-K     auto bindingsIter = bindingTables.find(recordType.getName());
1004c5dee77SRenaud-K     if (bindingsIter == bindingTables.end())
1014c5dee77SRenaud-K       return emitError(loc)
1024c5dee77SRenaud-K              << "cannot find binding table for " << recordType.getName();
1034c5dee77SRenaud-K 
1044c5dee77SRenaud-K     // Lookup for the binding.
1054c5dee77SRenaud-K     const BindingTable &bindingTable = bindingsIter->second;
1064c5dee77SRenaud-K     auto bindingIter = bindingTable.find(dispatch.getMethod());
1074c5dee77SRenaud-K     if (bindingIter == bindingTable.end())
1084c5dee77SRenaud-K       return emitError(loc)
1094c5dee77SRenaud-K              << "cannot find binding for " << dispatch.getMethod();
1104c5dee77SRenaud-K     unsigned bindingIdx = bindingIter->second;
1114c5dee77SRenaud-K 
1124c5dee77SRenaud-K     mlir::Value passedObject = dispatch.getObject();
1134c5dee77SRenaud-K 
1144c5dee77SRenaud-K     auto module = dispatch.getOperation()->getParentOfType<mlir::ModuleOp>();
1154c5dee77SRenaud-K     Type typeDescTy;
1164c5dee77SRenaud-K     std::string typeDescName =
1174c5dee77SRenaud-K         NameUniquer::getTypeDescriptorName(recordType.getName());
1184c5dee77SRenaud-K     if (auto global = module.lookupSymbol<fir::GlobalOp>(typeDescName)) {
1194c5dee77SRenaud-K       typeDescTy = global.getType();
1204c5dee77SRenaud-K     }
1214c5dee77SRenaud-K 
1224c5dee77SRenaud-K     // clang-format off
1234c5dee77SRenaud-K     // Before:
1244c5dee77SRenaud-K     //   fir.dispatch "proc1"(%11 :
1254c5dee77SRenaud-K     //   !fir.class<!fir.heap<!fir.type<_QMpolyTp1{a:i32,b:i32}>>>)
1264c5dee77SRenaud-K 
1274c5dee77SRenaud-K     // After:
1284c5dee77SRenaud-K     //   %12 = fir.box_tdesc %11 : (!fir.class<!fir.heap<!fir.type<_QMpolyTp1{a:i32,b:i32}>>>) -> !fir.tdesc<none>
1294c5dee77SRenaud-K     //   %13 = fir.convert %12 : (!fir.tdesc<none>) -> !fir.ref<!fir.type<_QM__fortran_type_infoTderivedtype>>
1304c5dee77SRenaud-K     //   %14 = fir.field_index binding, !fir.type<_QM__fortran_type_infoTderivedtype>
1314c5dee77SRenaud-K     //   %15 = fir.coordinate_of %13, %14 : (!fir.ref<!fir.type<_QM__fortran_type_infoTderivedtype>>, !fir.field) -> !fir.ref<!fir.box<!fir.ptr<!fir.array<?x!fir.type<_QM__fortran_type_infoTbinding>>>>>
1324c5dee77SRenaud-K     //   %bindings = fir.load %15 : !fir.ref<!fir.box<!fir.ptr<!fir.array<?x!fir.type<_QM__fortran_type_infoTbinding>>>>>
1334c5dee77SRenaud-K     //   %16 = fir.box_addr %bindings : (!fir.box<!fir.ptr<!fir.array<?x!fir.type<_QM__fortran_type_infoTbinding>>>>) -> !fir.ptr<!fir.array<?x!fir.type<_QM__fortran_type_infoTbinding>>>
1344c5dee77SRenaud-K     //   %17 = fir.coordinate_of %16, %c0 : (!fir.ptr<!fir.array<?x!fir.type<_QM__fortran_type_infoTbinding>>>, index) -> !fir.ref<!fir.type<_QM__fortran_type_infoTbinding>>
1354c5dee77SRenaud-K     //   %18 = fir.field_index proc, !fir.type<_QM__fortran_type_infoTbinding>
1364c5dee77SRenaud-K     //   %19 = fir.coordinate_of %17, %18 : (!fir.ref<!fir.type<_QM__fortran_type_infoTbinding>>, !fir.field) -> !fir.ref<!fir.type<_QM__fortran_builtinsT__builtin_c_funptr>>
1374c5dee77SRenaud-K     //   %20 = fir.field_index __address, !fir.type<_QM__fortran_builtinsT__builtin_c_funptr>
1384c5dee77SRenaud-K     //   %21 = fir.coordinate_of %19, %20 : (!fir.ref<!fir.type<_QM__fortran_builtinsT__builtin_c_funptr>>, !fir.field) -> !fir.ref<i64>
1394c5dee77SRenaud-K     //   %22 = fir.load %21 : !fir.ref<i64>
1404c5dee77SRenaud-K     //   %23 = fir.convert %22 : (i64) -> (() -> ())
1414c5dee77SRenaud-K     //   fir.call %23()  : () -> ()
1424c5dee77SRenaud-K     // clang-format on
1434c5dee77SRenaud-K 
1444c5dee77SRenaud-K     // Load the descriptor.
1454c5dee77SRenaud-K     mlir::Type fieldTy = fir::FieldType::get(rewriter.getContext());
1464c5dee77SRenaud-K     mlir::Type tdescType =
1474c5dee77SRenaud-K         fir::TypeDescType::get(mlir::NoneType::get(rewriter.getContext()));
1484c5dee77SRenaud-K     mlir::Value boxDesc =
1494c5dee77SRenaud-K         rewriter.create<fir::BoxTypeDescOp>(loc, tdescType, passedObject);
1504c5dee77SRenaud-K     boxDesc = rewriter.create<fir::ConvertOp>(
1514c5dee77SRenaud-K         loc, fir::ReferenceType::get(typeDescTy), boxDesc);
1524c5dee77SRenaud-K 
1534c5dee77SRenaud-K     // Load the bindings descriptor.
1544c5dee77SRenaud-K     auto bindingsCompName = Fortran::semantics::bindingDescCompName;
155fac349a1SChristian Sigg     fir::RecordType typeDescRecTy = mlir::cast<fir::RecordType>(typeDescTy);
1564c5dee77SRenaud-K     mlir::Value field = rewriter.create<fir::FieldIndexOp>(
1574c5dee77SRenaud-K         loc, fieldTy, bindingsCompName, typeDescRecTy, mlir::ValueRange{});
1584c5dee77SRenaud-K     mlir::Type coorTy =
1594c5dee77SRenaud-K         fir::ReferenceType::get(typeDescRecTy.getType(bindingsCompName));
1604c5dee77SRenaud-K     mlir::Value bindingBoxAddr =
1614c5dee77SRenaud-K         rewriter.create<fir::CoordinateOp>(loc, coorTy, boxDesc, field);
1624c5dee77SRenaud-K     mlir::Value bindingBox = rewriter.create<fir::LoadOp>(loc, bindingBoxAddr);
1634c5dee77SRenaud-K 
1644c5dee77SRenaud-K     // Load the correct binding.
1654c5dee77SRenaud-K     mlir::Value bindings = rewriter.create<fir::BoxAddrOp>(loc, bindingBox);
166fac349a1SChristian Sigg     fir::RecordType bindingTy = fir::unwrapIfDerived(
167fac349a1SChristian Sigg         mlir::cast<fir::BaseBoxType>(bindingBox.getType()));
1684c5dee77SRenaud-K     mlir::Type bindingAddrTy = fir::ReferenceType::get(bindingTy);
1694c5dee77SRenaud-K     mlir::Value bindingIdxVal = rewriter.create<mlir::arith::ConstantOp>(
1704c5dee77SRenaud-K         loc, rewriter.getIndexType(), rewriter.getIndexAttr(bindingIdx));
1714c5dee77SRenaud-K     mlir::Value bindingAddr = rewriter.create<fir::CoordinateOp>(
1724c5dee77SRenaud-K         loc, bindingAddrTy, bindings, bindingIdxVal);
1734c5dee77SRenaud-K 
1744c5dee77SRenaud-K     // Get the function pointer.
1754c5dee77SRenaud-K     auto procCompName = Fortran::semantics::procCompName;
1764c5dee77SRenaud-K     mlir::Value procField = rewriter.create<fir::FieldIndexOp>(
1774c5dee77SRenaud-K         loc, fieldTy, procCompName, bindingTy, mlir::ValueRange{});
1784c5dee77SRenaud-K     fir::RecordType procTy =
179fac349a1SChristian Sigg         mlir::cast<fir::RecordType>(bindingTy.getType(procCompName));
1804c5dee77SRenaud-K     mlir::Type procRefTy = fir::ReferenceType::get(procTy);
1814c5dee77SRenaud-K     mlir::Value procRef = rewriter.create<fir::CoordinateOp>(
1824c5dee77SRenaud-K         loc, procRefTy, bindingAddr, procField);
1834c5dee77SRenaud-K 
1844c5dee77SRenaud-K     auto addressFieldName = Fortran::lower::builtin::cptrFieldName;
1854c5dee77SRenaud-K     mlir::Value addressField = rewriter.create<fir::FieldIndexOp>(
1864c5dee77SRenaud-K         loc, fieldTy, addressFieldName, procTy, mlir::ValueRange{});
1874c5dee77SRenaud-K     mlir::Type addressTy = procTy.getType(addressFieldName);
1884c5dee77SRenaud-K     mlir::Type addressRefTy = fir::ReferenceType::get(addressTy);
1894c5dee77SRenaud-K     mlir::Value addressRef = rewriter.create<fir::CoordinateOp>(
1904c5dee77SRenaud-K         loc, addressRefTy, procRef, addressField);
1914c5dee77SRenaud-K     mlir::Value address = rewriter.create<fir::LoadOp>(loc, addressRef);
1924c5dee77SRenaud-K 
1934c5dee77SRenaud-K     // Get the function type.
1944c5dee77SRenaud-K     llvm::SmallVector<mlir::Type> argTypes;
1954c5dee77SRenaud-K     for (mlir::Value operand : dispatch.getArgs())
1964c5dee77SRenaud-K       argTypes.push_back(operand.getType());
1974c5dee77SRenaud-K     llvm::SmallVector<mlir::Type> resTypes;
1984c5dee77SRenaud-K     if (!dispatch.getResults().empty())
1994c5dee77SRenaud-K       resTypes.push_back(dispatch.getResults()[0].getType());
2004c5dee77SRenaud-K 
2014c5dee77SRenaud-K     mlir::Type funTy =
2024c5dee77SRenaud-K         mlir::FunctionType::get(rewriter.getContext(), argTypes, resTypes);
2034c5dee77SRenaud-K     mlir::Value funcPtr = rewriter.create<fir::ConvertOp>(loc, funTy, address);
2044c5dee77SRenaud-K 
2054c5dee77SRenaud-K     // Make the call.
2064c5dee77SRenaud-K     llvm::SmallVector<mlir::Value> args{funcPtr};
2074c5dee77SRenaud-K     args.append(dispatch.getArgs().begin(), dispatch.getArgs().end());
208*a78359c2SjeanPerier     rewriter.replaceOpWithNewOp<fir::CallOp>(dispatch, resTypes, nullptr, args,
209*a78359c2SjeanPerier                                              dispatch.getProcedureAttrsAttr());
2104c5dee77SRenaud-K     return mlir::success();
2114c5dee77SRenaud-K   }
2124c5dee77SRenaud-K 
2134c5dee77SRenaud-K private:
2144c5dee77SRenaud-K   BindingTables bindingTables;
2154c5dee77SRenaud-K };
2164c5dee77SRenaud-K 
217ff761f2cSRenaud-K /// Convert FIR structured control flow ops to CFG ops.
218ff761f2cSRenaud-K class PolymorphicOpConversion
219ff761f2cSRenaud-K     : public fir::impl::PolymorphicOpConversionBase<PolymorphicOpConversion> {
220ff761f2cSRenaud-K public:
221db791b27SRamkumar Ramachandra   llvm::LogicalResult initialize(mlir::MLIRContext *ctx) override {
222ff761f2cSRenaud-K     return mlir::success();
223ff761f2cSRenaud-K   }
224ff761f2cSRenaud-K 
225ff761f2cSRenaud-K   void runOnOperation() override {
226ff761f2cSRenaud-K     auto *context = &getContext();
227d1b3648eSTom Eccles     mlir::ModuleOp mod = getOperation();
228ff761f2cSRenaud-K     mlir::RewritePatternSet patterns(context);
2294c5dee77SRenaud-K 
2304c5dee77SRenaud-K     BindingTables bindingTables;
2314c5dee77SRenaud-K     buildBindingTables(bindingTables, mod);
2324c5dee77SRenaud-K 
233d1b3648eSTom Eccles     patterns.insert<SelectTypeConv>(context);
2344c5dee77SRenaud-K     patterns.insert<DispatchOpConv>(context, bindingTables);
235ff761f2cSRenaud-K     mlir::ConversionTarget target(*context);
2364c48f016SMatthias Springer     target.addLegalDialect<mlir::affine::AffineDialect,
2374c48f016SMatthias Springer                            mlir::cf::ControlFlowDialect, FIROpsDialect,
2384c48f016SMatthias Springer                            mlir::func::FuncDialect>();
239ff761f2cSRenaud-K 
240ff761f2cSRenaud-K     // apply the patterns
241ff761f2cSRenaud-K     target.addIllegalOp<SelectTypeOp>();
2424c5dee77SRenaud-K     target.addIllegalOp<DispatchOp>();
243ff761f2cSRenaud-K     target.markUnknownOpDynamicallyLegal([](Operation *) { return true; });
244ff761f2cSRenaud-K     if (mlir::failed(mlir::applyPartialConversion(getOperation(), target,
245ff761f2cSRenaud-K                                                   std::move(patterns)))) {
246ff761f2cSRenaud-K       mlir::emitError(mlir::UnknownLoc::get(context),
247ff761f2cSRenaud-K                       "error in converting to CFG\n");
248ff761f2cSRenaud-K       signalPassFailure();
249ff761f2cSRenaud-K     }
250ff761f2cSRenaud-K   }
251ff761f2cSRenaud-K };
252ff761f2cSRenaud-K } // namespace
253ff761f2cSRenaud-K 
254db791b27SRamkumar Ramachandra llvm::LogicalResult SelectTypeConv::matchAndRewrite(
255ff761f2cSRenaud-K     fir::SelectTypeOp selectType, OpAdaptor adaptor,
256ff761f2cSRenaud-K     mlir::ConversionPatternRewriter &rewriter) const {
257ff761f2cSRenaud-K   auto operands = adaptor.getOperands();
258ff761f2cSRenaud-K   auto typeGuards = selectType.getCases();
259ff761f2cSRenaud-K   unsigned typeGuardNum = typeGuards.size();
260ff761f2cSRenaud-K   auto selector = selectType.getSelector();
261ff761f2cSRenaud-K   auto loc = selectType.getLoc();
262ff761f2cSRenaud-K   auto mod = selectType.getOperation()->getParentOfType<mlir::ModuleOp>();
263ff761f2cSRenaud-K   fir::KindMapping kindMap = fir::getKindMapping(mod);
264ff761f2cSRenaud-K 
265ff761f2cSRenaud-K   // Order type guards so the condition and branches are done to respect the
266ff761f2cSRenaud-K   // Execution of SELECT TYPE construct as described in the Fortran 2018
267ff761f2cSRenaud-K   // standard 11.1.11.2 point 4.
268ff761f2cSRenaud-K   // 1. If a TYPE IS type guard statement matches the selector, the block
269ff761f2cSRenaud-K   //    following that statement is executed.
270ff761f2cSRenaud-K   // 2. Otherwise, if exactly one CLASS IS type guard statement matches the
271ff761f2cSRenaud-K   //    selector, the block following that statement is executed.
272ff761f2cSRenaud-K   // 3. Otherwise, if several CLASS IS type guard statements match the
273ff761f2cSRenaud-K   //    selector, one of these statements will inevitably specify a type that
274ff761f2cSRenaud-K   //    is an extension of all the types specified in the others; the block
275ff761f2cSRenaud-K   //    following that statement is executed.
276ff761f2cSRenaud-K   // 4. Otherwise, if there is a CLASS DEFAULT type guard statement, the block
277ff761f2cSRenaud-K   //    following that statement is executed.
278ff761f2cSRenaud-K   // 5. Otherwise, no block is executed.
279ff761f2cSRenaud-K 
280ff761f2cSRenaud-K   llvm::SmallVector<unsigned> orderedTypeGuards;
281ff761f2cSRenaud-K   llvm::SmallVector<unsigned> orderedClassIsGuards;
282ff761f2cSRenaud-K   unsigned defaultGuard = typeGuardNum - 1;
283ff761f2cSRenaud-K 
284ff761f2cSRenaud-K   // The following loop go through the type guards in the fir.select_type
285ff761f2cSRenaud-K   // operation and sort them into two lists.
286ff761f2cSRenaud-K   // - All the TYPE IS type guard are added in order to the orderedTypeGuards
287ff761f2cSRenaud-K   //   list. This list is used at the end to generate the if-then-else ladder.
288ff761f2cSRenaud-K   // - CLASS IS type guard are added in a separate list. If a CLASS IS type
289ff761f2cSRenaud-K   //   guard type extends a type already present, the type guard is inserted
290ff761f2cSRenaud-K   //   before in the list to respect point 3. above. Otherwise it is just
291ff761f2cSRenaud-K   //   added in order at the end.
292ff761f2cSRenaud-K   for (unsigned t = 0; t < typeGuardNum; ++t) {
293fac349a1SChristian Sigg     if (auto a = mlir::dyn_cast<fir::ExactTypeAttr>(typeGuards[t])) {
294ff761f2cSRenaud-K       orderedTypeGuards.push_back(t);
295ff761f2cSRenaud-K       continue;
296ff761f2cSRenaud-K     }
297ff761f2cSRenaud-K 
298fac349a1SChristian Sigg     if (auto a = mlir::dyn_cast<fir::SubclassAttr>(typeGuards[t])) {
299fac349a1SChristian Sigg       if (auto recTy = mlir::dyn_cast<fir::RecordType>(a.getType())) {
3004ccd57ddSjeanPerier         auto dt = mod.lookupSymbol<fir::TypeInfoOp>(recTy.getName());
301ff761f2cSRenaud-K         assert(dt && "dispatch table not found");
302ff761f2cSRenaud-K         llvm::SmallSet<llvm::StringRef, 4> ancestors =
303ff761f2cSRenaud-K             collectAncestors(dt, mod);
304ff761f2cSRenaud-K         if (!ancestors.empty()) {
305ff761f2cSRenaud-K           auto it = orderedClassIsGuards.begin();
306ff761f2cSRenaud-K           while (it != orderedClassIsGuards.end()) {
307ff761f2cSRenaud-K             fir::SubclassAttr sAttr =
308fac349a1SChristian Sigg                 mlir::dyn_cast<fir::SubclassAttr>(typeGuards[*it]);
309fac349a1SChristian Sigg             if (auto ty = mlir::dyn_cast<fir::RecordType>(sAttr.getType())) {
310ff761f2cSRenaud-K               if (ancestors.contains(ty.getName()))
311ff761f2cSRenaud-K                 break;
312ff761f2cSRenaud-K             }
313ff761f2cSRenaud-K             ++it;
314ff761f2cSRenaud-K           }
315ff761f2cSRenaud-K           if (it != orderedClassIsGuards.end()) {
316ff761f2cSRenaud-K             // Parent type is present so place it before.
317ff761f2cSRenaud-K             orderedClassIsGuards.insert(it, t);
318ff761f2cSRenaud-K             continue;
319ff761f2cSRenaud-K           }
320ff761f2cSRenaud-K         }
321ff761f2cSRenaud-K       }
322ff761f2cSRenaud-K       orderedClassIsGuards.push_back(t);
323ff761f2cSRenaud-K     }
324ff761f2cSRenaud-K   }
325ff761f2cSRenaud-K   orderedTypeGuards.append(orderedClassIsGuards);
326ff761f2cSRenaud-K   orderedTypeGuards.push_back(defaultGuard);
327ff761f2cSRenaud-K   assert(orderedTypeGuards.size() == typeGuardNum &&
328ff761f2cSRenaud-K          "ordered type guard size doesn't match number of type guards");
329ff761f2cSRenaud-K 
330ff761f2cSRenaud-K   for (unsigned idx : orderedTypeGuards) {
331ff761f2cSRenaud-K     auto *dest = selectType.getSuccessor(idx);
332ff761f2cSRenaud-K     std::optional<mlir::ValueRange> destOps =
333ff761f2cSRenaud-K         selectType.getSuccessorOperands(operands, idx);
334fac349a1SChristian Sigg     if (mlir::dyn_cast<mlir::UnitAttr>(typeGuards[idx]))
3357e584357SSlava Zakharin       rewriter.replaceOpWithNewOp<mlir::cf::BranchOp>(
3367e584357SSlava Zakharin           selectType, dest, destOps.value_or(mlir::ValueRange{}));
337ff761f2cSRenaud-K     else if (mlir::failed(genTypeLadderStep(loc, selector, typeGuards[idx],
338ff761f2cSRenaud-K                                             dest, destOps, mod, rewriter,
339ff761f2cSRenaud-K                                             kindMap)))
340ff761f2cSRenaud-K       return mlir::failure();
341ff761f2cSRenaud-K   }
342ff761f2cSRenaud-K   return mlir::success();
343ff761f2cSRenaud-K }
344ff761f2cSRenaud-K 
345db791b27SRamkumar Ramachandra llvm::LogicalResult SelectTypeConv::genTypeLadderStep(
346ff761f2cSRenaud-K     mlir::Location loc, mlir::Value selector, mlir::Attribute attr,
347ff761f2cSRenaud-K     mlir::Block *dest, std::optional<mlir::ValueRange> destOps,
348ff761f2cSRenaud-K     mlir::ModuleOp mod, mlir::PatternRewriter &rewriter,
349ff761f2cSRenaud-K     fir::KindMapping &kindMap) const {
350ff761f2cSRenaud-K   mlir::Value cmp;
351ff761f2cSRenaud-K   // TYPE IS type guard comparison are all done inlined.
352fac349a1SChristian Sigg   if (auto a = mlir::dyn_cast<fir::ExactTypeAttr>(attr)) {
353ff761f2cSRenaud-K     if (fir::isa_trivial(a.getType()) ||
354fac349a1SChristian Sigg         mlir::isa<fir::CharacterType>(a.getType())) {
355ff761f2cSRenaud-K       // For type guard statement with Intrinsic type spec the type code of
356ff761f2cSRenaud-K       // the descriptor is compared.
357bddd7a64SV Donaldson       int code = fir::getTypeCode(a.getType(), kindMap);
358ff761f2cSRenaud-K       if (code == 0)
359ff761f2cSRenaud-K         return mlir::emitError(loc)
360ff761f2cSRenaud-K                << "type code unavailable for " << a.getType();
361ff761f2cSRenaud-K       mlir::Value typeCode = rewriter.create<mlir::arith::ConstantOp>(
362ff761f2cSRenaud-K           loc, rewriter.getI8IntegerAttr(code));
363ff761f2cSRenaud-K       mlir::Value selectorTypeCode = rewriter.create<fir::BoxTypeCodeOp>(
364ff761f2cSRenaud-K           loc, rewriter.getI8Type(), selector);
365ff761f2cSRenaud-K       cmp = rewriter.create<mlir::arith::CmpIOp>(
366ff761f2cSRenaud-K           loc, mlir::arith::CmpIPredicate::eq, selectorTypeCode, typeCode);
367ff761f2cSRenaud-K     } else {
368ff761f2cSRenaud-K       // Flang inline the kind parameter in the type descriptor so we can
369ff761f2cSRenaud-K       // directly check if the type descriptor addresses are identical for
370ff761f2cSRenaud-K       // the TYPE IS type guard statement.
371ff761f2cSRenaud-K       mlir::Value res =
372ff761f2cSRenaud-K           genTypeDescCompare(loc, selector, a.getType(), mod, rewriter);
373ff761f2cSRenaud-K       if (!res)
374ff761f2cSRenaud-K         return mlir::failure();
375ff761f2cSRenaud-K       cmp = res;
376ff761f2cSRenaud-K     }
377ff761f2cSRenaud-K     // CLASS IS type guard statement is done with a runtime call.
378fac349a1SChristian Sigg   } else if (auto a = mlir::dyn_cast<fir::SubclassAttr>(attr)) {
379ff761f2cSRenaud-K     // Retrieve the type descriptor from the type guard statement record type.
380fac349a1SChristian Sigg     assert(mlir::isa<fir::RecordType>(a.getType()) && "expect fir.record type");
381fac349a1SChristian Sigg     fir::RecordType recTy = mlir::dyn_cast<fir::RecordType>(a.getType());
382ff761f2cSRenaud-K     std::string typeDescName =
383ff761f2cSRenaud-K         fir::NameUniquer::getTypeDescriptorName(recTy.getName());
384ff761f2cSRenaud-K     auto typeDescGlobal = mod.lookupSymbol<fir::GlobalOp>(typeDescName);
385ff761f2cSRenaud-K     auto typeDescAddr = rewriter.create<fir::AddrOfOp>(
386ff761f2cSRenaud-K         loc, fir::ReferenceType::get(typeDescGlobal.getType()),
387ff761f2cSRenaud-K         typeDescGlobal.getSymbol());
388ff761f2cSRenaud-K     mlir::Type typeDescTy = ReferenceType::get(rewriter.getNoneType());
389ff761f2cSRenaud-K     mlir::Value typeDesc =
390ff761f2cSRenaud-K         rewriter.create<ConvertOp>(loc, typeDescTy, typeDescAddr);
391ff761f2cSRenaud-K 
392ff761f2cSRenaud-K     // Prepare the selector descriptor for the runtime call.
393ff761f2cSRenaud-K     mlir::Type descNoneTy = fir::BoxType::get(rewriter.getNoneType());
394ff761f2cSRenaud-K     mlir::Value descSelector =
395ff761f2cSRenaud-K         rewriter.create<ConvertOp>(loc, descNoneTy, selector);
396ff761f2cSRenaud-K 
397ff761f2cSRenaud-K     // Generate runtime call.
398ff761f2cSRenaud-K     llvm::StringRef fctName = RTNAME_STRING(ClassIs);
399ff761f2cSRenaud-K     mlir::func::FuncOp callee;
400ff761f2cSRenaud-K     {
401ff761f2cSRenaud-K       // Since conversion is done in parallel for each fir.select_type
402ff761f2cSRenaud-K       // operation, the runtime function insertion must be threadsafe.
403ff761f2cSRenaud-K       callee =
404ff761f2cSRenaud-K           fir::createFuncOp(rewriter.getUnknownLoc(), mod, fctName,
405ff761f2cSRenaud-K                             rewriter.getFunctionType({descNoneTy, typeDescTy},
406ff761f2cSRenaud-K                                                      rewriter.getI1Type()));
407ff761f2cSRenaud-K     }
408ff761f2cSRenaud-K     cmp = rewriter
409ff761f2cSRenaud-K               .create<fir::CallOp>(loc, callee,
410ff761f2cSRenaud-K                                    mlir::ValueRange{descSelector, typeDesc})
411ff761f2cSRenaud-K               .getResult(0);
412ff761f2cSRenaud-K   }
413ff761f2cSRenaud-K 
414ff761f2cSRenaud-K   auto *thisBlock = rewriter.getInsertionBlock();
415ff761f2cSRenaud-K   auto *newBlock =
416ff761f2cSRenaud-K       rewriter.createBlock(dest->getParent(), mlir::Region::iterator(dest));
417ff761f2cSRenaud-K   rewriter.setInsertionPointToEnd(thisBlock);
418ff761f2cSRenaud-K   if (destOps.has_value())
419ff761f2cSRenaud-K     rewriter.create<mlir::cf::CondBranchOp>(loc, cmp, dest, destOps.value(),
420ff761f2cSRenaud-K                                             newBlock, std::nullopt);
421ff761f2cSRenaud-K   else
422ff761f2cSRenaud-K     rewriter.create<mlir::cf::CondBranchOp>(loc, cmp, dest, newBlock);
423ff761f2cSRenaud-K   rewriter.setInsertionPointToEnd(newBlock);
424ff761f2cSRenaud-K   return mlir::success();
425ff761f2cSRenaud-K }
426ff761f2cSRenaud-K 
427ff761f2cSRenaud-K // Generate comparison of type descriptor addresses.
428ff761f2cSRenaud-K mlir::Value
429ff761f2cSRenaud-K SelectTypeConv::genTypeDescCompare(mlir::Location loc, mlir::Value selector,
430ff761f2cSRenaud-K                                    mlir::Type ty, mlir::ModuleOp mod,
431ff761f2cSRenaud-K                                    mlir::PatternRewriter &rewriter) const {
432fac349a1SChristian Sigg   assert(mlir::isa<fir::RecordType>(ty) && "expect fir.record type");
433fac349a1SChristian Sigg   fir::RecordType recTy = mlir::dyn_cast<fir::RecordType>(ty);
434ff761f2cSRenaud-K   std::string typeDescName =
435ff761f2cSRenaud-K       fir::NameUniquer::getTypeDescriptorName(recTy.getName());
436ff761f2cSRenaud-K   auto typeDescGlobal = mod.lookupSymbol<fir::GlobalOp>(typeDescName);
437ff761f2cSRenaud-K   if (!typeDescGlobal)
438ff761f2cSRenaud-K     return {};
439ff761f2cSRenaud-K   auto typeDescAddr = rewriter.create<fir::AddrOfOp>(
440ff761f2cSRenaud-K       loc, fir::ReferenceType::get(typeDescGlobal.getType()),
441ff761f2cSRenaud-K       typeDescGlobal.getSymbol());
442ff761f2cSRenaud-K   auto intPtrTy = rewriter.getIndexType();
443ff761f2cSRenaud-K   mlir::Type tdescType =
444ff761f2cSRenaud-K       fir::TypeDescType::get(mlir::NoneType::get(rewriter.getContext()));
445ff761f2cSRenaud-K   mlir::Value selectorTdescAddr =
446ff761f2cSRenaud-K       rewriter.create<fir::BoxTypeDescOp>(loc, tdescType, selector);
447ff761f2cSRenaud-K   auto typeDescInt =
448ff761f2cSRenaud-K       rewriter.create<fir::ConvertOp>(loc, intPtrTy, typeDescAddr);
449ff761f2cSRenaud-K   auto selectorTdescInt =
450ff761f2cSRenaud-K       rewriter.create<fir::ConvertOp>(loc, intPtrTy, selectorTdescAddr);
451ff761f2cSRenaud-K   return rewriter.create<mlir::arith::CmpIOp>(
452ff761f2cSRenaud-K       loc, mlir::arith::CmpIPredicate::eq, typeDescInt, selectorTdescInt);
453ff761f2cSRenaud-K }
454ff761f2cSRenaud-K 
455ff761f2cSRenaud-K llvm::SmallSet<llvm::StringRef, 4>
4564ccd57ddSjeanPerier SelectTypeConv::collectAncestors(fir::TypeInfoOp dt, mlir::ModuleOp mod) const {
457ff761f2cSRenaud-K   llvm::SmallSet<llvm::StringRef, 4> ancestors;
4584ccd57ddSjeanPerier   while (auto parentName = dt.getIfParentName()) {
4594ccd57ddSjeanPerier     ancestors.insert(*parentName);
4604ccd57ddSjeanPerier     dt = mod.lookupSymbol<fir::TypeInfoOp>(*parentName);
4614ccd57ddSjeanPerier     assert(dt && "parent type info not generated");
462ff761f2cSRenaud-K   }
463ff761f2cSRenaud-K   return ancestors;
464ff761f2cSRenaud-K }
465