brintos

brintos / llvm-project-archived public Read only

0
0
Text · 22.5 KiB · c9d52c4 Raw
500 lines · cpp
1//===-- PolymorphicOpConversion.cpp ---------------------------------------===//2//3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.4// See https://llvm.org/LICENSE.txt for license information.5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception6//7//===----------------------------------------------------------------------===//8 9#include "flang/Lower/BuiltinModules.h"10#include "flang/Optimizer/Builder/Todo.h"11#include "flang/Optimizer/Dialect/FIRDialect.h"12#include "flang/Optimizer/Dialect/FIROps.h"13#include "flang/Optimizer/Dialect/FIROpsSupport.h"14#include "flang/Optimizer/Dialect/FIRType.h"15#include "flang/Optimizer/Dialect/Support/FIRContext.h"16#include "flang/Optimizer/Dialect/Support/KindMapping.h"17#include "flang/Optimizer/Support/InternalNames.h"18#include "flang/Optimizer/Support/TypeCode.h"19#include "flang/Optimizer/Transforms/Passes.h"20#include "flang/Runtime/derived-api.h"21#include "flang/Semantics/runtime-type-info.h"22#include "mlir/Dialect/Affine/IR/AffineOps.h"23#include "mlir/Dialect/Arith/IR/Arith.h"24#include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h"25#include "mlir/Dialect/Func/IR/FuncOps.h"26#include "mlir/IR/BuiltinOps.h"27#include "mlir/Pass/Pass.h"28#include "mlir/Transforms/DialectConversion.h"29#include "llvm/ADT/SmallSet.h"30#include "llvm/Support/CommandLine.h"31 32namespace fir {33#define GEN_PASS_DEF_POLYMORPHICOPCONVERSION34#include "flang/Optimizer/Transforms/Passes.h.inc"35} // namespace fir36 37using namespace fir;38using namespace mlir;39 40// Reconstruct binding tables for dynamic dispatch.41using BindingTable = llvm::DenseMap<llvm::StringRef, unsigned>;42using BindingTables = llvm::DenseMap<llvm::StringRef, BindingTable>;43 44static std::string getTypeDescriptorTypeName() {45  llvm::SmallVector<llvm::StringRef, 1> modules = {46      Fortran::semantics::typeInfoBuiltinModule};47  return fir::NameUniquer::doType(modules, /*proc=*/{}, /*blockId=*/0,48                                  Fortran::semantics::typeDescriptorTypeName,49                                  /*kinds=*/{});50}51 52static std::optional<mlir::Type>53buildBindingTables(BindingTables &bindingTables, mlir::ModuleOp mod) {54 55  std::optional<mlir::Type> typeDescriptorType;56  std::string typeDescriptorTypeName = getTypeDescriptorTypeName();57  // The binding tables are defined in FIR after lowering inside fir.type_info58  // operations. Go through each binding tables and store the procedure name and59  // binding index for later use by the fir.dispatch conversion pattern.60  for (auto typeInfo : mod.getOps<fir::TypeInfoOp>()) {61    if (!typeDescriptorType && typeInfo.getSymName() == typeDescriptorTypeName)62      typeDescriptorType = typeInfo.getType();63    unsigned bindingIdx = 0;64    BindingTable bindings;65    if (typeInfo.getDispatchTable().empty()) {66      bindingTables[typeInfo.getSymName()] = bindings;67      continue;68    }69    for (auto dtEntry :70         typeInfo.getDispatchTable().front().getOps<fir::DTEntryOp>()) {71      bindings[dtEntry.getMethod()] = bindingIdx;72      ++bindingIdx;73    }74    bindingTables[typeInfo.getSymName()] = bindings;75  }76  return typeDescriptorType;77}78 79namespace {80 81/// SelectTypeOp converted to an if-then-else chain82///83/// This lowers the test conditions to calls into the runtime.84class SelectTypeConv : public OpConversionPattern<fir::SelectTypeOp> {85public:86  using OpConversionPattern<fir::SelectTypeOp>::OpConversionPattern;87 88  SelectTypeConv(mlir::MLIRContext *ctx)89      : mlir::OpConversionPattern<fir::SelectTypeOp>(ctx) {}90 91  llvm::LogicalResult92  matchAndRewrite(fir::SelectTypeOp selectType, OpAdaptor adaptor,93                  mlir::ConversionPatternRewriter &rewriter) const override;94 95private:96  // Generate comparison of type descriptor addresses.97  mlir::Value genTypeDescCompare(mlir::Location loc, mlir::Value selector,98                                 mlir::Type ty, mlir::ModuleOp mod,99                                 mlir::PatternRewriter &rewriter) const;100 101  llvm::LogicalResult genTypeLadderStep(mlir::Location loc,102                                        mlir::Value selector,103                                        mlir::Attribute attr, mlir::Block *dest,104                                        std::optional<mlir::ValueRange> destOps,105                                        mlir::ModuleOp mod,106                                        mlir::PatternRewriter &rewriter,107                                        fir::KindMapping &kindMap) const;108 109  llvm::SmallSet<llvm::StringRef, 4> collectAncestors(fir::TypeInfoOp dt,110                                                      mlir::ModuleOp mod) const;111};112 113/// Lower `fir.dispatch` operation. A virtual call to a method in a dispatch114/// table.115struct DispatchOpConv : public OpConversionPattern<fir::DispatchOp> {116  using OpConversionPattern<fir::DispatchOp>::OpConversionPattern;117 118  DispatchOpConv(mlir::MLIRContext *ctx, const BindingTables &bindingTables,119                 std::optional<mlir::Type> typeDescriptorType)120      : mlir::OpConversionPattern<fir::DispatchOp>(ctx),121        bindingTables(bindingTables), typeDescriptorType{typeDescriptorType} {}122 123  llvm::LogicalResult124  matchAndRewrite(fir::DispatchOp dispatch, OpAdaptor adaptor,125                  mlir::ConversionPatternRewriter &rewriter) const override {126    mlir::Location loc = dispatch.getLoc();127 128    if (bindingTables.empty())129      return emitError(loc) << "no binding tables found";130 131    // Get derived type information.132    mlir::Type declaredType =133        fir::getDerivedType(dispatch.getObject().getType().getEleTy());134    assert(mlir::isa<fir::RecordType>(declaredType) && "expecting fir.type");135    auto recordType = mlir::dyn_cast<fir::RecordType>(declaredType);136 137    // Lookup for the binding table.138    auto bindingsIter = bindingTables.find(recordType.getName());139    if (bindingsIter == bindingTables.end())140      return emitError(loc)141             << "cannot find binding table for " << recordType.getName();142 143    // Lookup for the binding.144    const BindingTable &bindingTable = bindingsIter->second;145    auto bindingIter = bindingTable.find(dispatch.getMethod());146    if (bindingIter == bindingTable.end())147      return emitError(loc)148             << "cannot find binding for " << dispatch.getMethod();149    unsigned bindingIdx = bindingIter->second;150 151    mlir::Value passedObject = dispatch.getObject();152 153    if (!typeDescriptorType)154      return emitError(loc) << "cannot find " << getTypeDescriptorTypeName()155                            << " fir.type_info that is required to get the "156                               "related builtin type and lower fir.dispatch";157    mlir::Type typeDescTy = *typeDescriptorType;158 159    // clang-format off160    // Before:161    //   fir.dispatch "proc1"(%11 :162    //   !fir.class<!fir.heap<!fir.type<_QMpolyTp1{a:i32,b:i32}>>>)163 164    // After:165    //   %12 = fir.box_tdesc %11 : (!fir.class<!fir.heap<!fir.type<_QMpolyTp1{a:i32,b:i32}>>>) -> !fir.tdesc<none>166    //   %13 = fir.convert %12 : (!fir.tdesc<none>) -> !fir.ref<!fir.type<_QM__fortran_type_infoTderivedtype>>167    //   %14 = fir.field_index binding, !fir.type<_QM__fortran_type_infoTderivedtype>168    //   %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>>>>>169    //   %bindings = fir.load %15 : !fir.ref<!fir.box<!fir.ptr<!fir.array<?x!fir.type<_QM__fortran_type_infoTbinding>>>>>170    //   %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>>>171    //   %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>>172    //   %18 = fir.field_index proc, !fir.type<_QM__fortran_type_infoTbinding>173    //   %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>>174    //   %20 = fir.field_index __address, !fir.type<_QM__fortran_builtinsT__builtin_c_funptr>175    //   %21 = fir.coordinate_of %19, %20 : (!fir.ref<!fir.type<_QM__fortran_builtinsT__builtin_c_funptr>>, !fir.field) -> !fir.ref<i64>176    //   %22 = fir.load %21 : !fir.ref<i64>177    //   %23 = fir.convert %22 : (i64) -> (() -> ())178    //   fir.call %23()  : () -> ()179    // clang-format on180 181    // Load the descriptor.182    mlir::Type fieldTy = fir::FieldType::get(rewriter.getContext());183    mlir::Type tdescType =184        fir::TypeDescType::get(mlir::NoneType::get(rewriter.getContext()));185    mlir::Value boxDesc =186        fir::BoxTypeDescOp::create(rewriter, loc, tdescType, passedObject);187    boxDesc = fir::ConvertOp::create(188        rewriter, loc, fir::ReferenceType::get(typeDescTy), boxDesc);189 190    // Load the bindings descriptor.191    auto bindingsCompName = Fortran::semantics::bindingDescCompName;192    fir::RecordType typeDescRecTy = mlir::cast<fir::RecordType>(typeDescTy);193    mlir::Value field =194        fir::FieldIndexOp::create(rewriter, loc, fieldTy, bindingsCompName,195                                  typeDescRecTy, mlir::ValueRange{});196    mlir::Type coorTy =197        fir::ReferenceType::get(typeDescRecTy.getType(bindingsCompName));198    mlir::Value bindingBoxAddr =199        fir::CoordinateOp::create(rewriter, loc, coorTy, boxDesc, field);200    mlir::Value bindingBox = fir::LoadOp::create(rewriter, loc, bindingBoxAddr);201 202    // Load the correct binding.203    mlir::Value bindings = fir::BoxAddrOp::create(rewriter, loc, bindingBox);204    fir::RecordType bindingTy = fir::unwrapIfDerived(205        mlir::cast<fir::BaseBoxType>(bindingBox.getType()));206    mlir::Type bindingAddrTy = fir::ReferenceType::get(bindingTy);207    mlir::Value bindingIdxVal =208        mlir::arith::ConstantOp::create(rewriter, loc, rewriter.getIndexType(),209                                        rewriter.getIndexAttr(bindingIdx));210    mlir::Value bindingAddr = fir::CoordinateOp::create(211        rewriter, loc, bindingAddrTy, bindings, bindingIdxVal);212 213    // Get the function pointer.214    auto procCompName = Fortran::semantics::procCompName;215    mlir::Value procField = fir::FieldIndexOp::create(216        rewriter, loc, fieldTy, procCompName, bindingTy, mlir::ValueRange{});217    fir::RecordType procTy =218        mlir::cast<fir::RecordType>(bindingTy.getType(procCompName));219    mlir::Type procRefTy = fir::ReferenceType::get(procTy);220    mlir::Value procRef = fir::CoordinateOp::create(rewriter, loc, procRefTy,221                                                    bindingAddr, procField);222 223    auto addressFieldName = Fortran::lower::builtin::cptrFieldName;224    mlir::Value addressField = fir::FieldIndexOp::create(225        rewriter, loc, fieldTy, addressFieldName, procTy, mlir::ValueRange{});226    mlir::Type addressTy = procTy.getType(addressFieldName);227    mlir::Type addressRefTy = fir::ReferenceType::get(addressTy);228    mlir::Value addressRef = fir::CoordinateOp::create(229        rewriter, loc, addressRefTy, procRef, addressField);230    mlir::Value address = fir::LoadOp::create(rewriter, loc, addressRef);231 232    // Get the function type.233    llvm::SmallVector<mlir::Type> argTypes;234    for (mlir::Value operand : dispatch.getArgs())235      argTypes.push_back(operand.getType());236    llvm::SmallVector<mlir::Type> resTypes;237    if (!dispatch.getResults().empty())238      resTypes.push_back(dispatch.getResults()[0].getType());239 240    mlir::Type funTy =241        mlir::FunctionType::get(rewriter.getContext(), argTypes, resTypes);242    mlir::Value funcPtr = fir::ConvertOp::create(rewriter, loc, funTy, address);243 244    // Make the call.245    llvm::SmallVector<mlir::Value> args{funcPtr};246    args.append(dispatch.getArgs().begin(), dispatch.getArgs().end());247    rewriter.replaceOpWithNewOp<fir::CallOp>(248        dispatch, resTypes, nullptr, args, dispatch.getArgAttrsAttr(),249        dispatch.getResAttrsAttr(), dispatch.getProcedureAttrsAttr(),250        /*inline_attr*/ fir::FortranInlineEnumAttr{},251        /*accessGroups*/ mlir::ArrayAttr{});252    return mlir::success();253  }254 255private:256  BindingTables bindingTables;257  std::optional<mlir::Type> typeDescriptorType;258};259 260/// Convert FIR structured control flow ops to CFG ops.261class PolymorphicOpConversion262    : public fir::impl::PolymorphicOpConversionBase<PolymorphicOpConversion> {263public:264  llvm::LogicalResult initialize(mlir::MLIRContext *ctx) override {265    return mlir::success();266  }267 268  void runOnOperation() override {269    auto *context = &getContext();270    mlir::ModuleOp mod = getOperation();271    mlir::RewritePatternSet patterns(context);272 273    BindingTables bindingTables;274    std::optional<mlir::Type> typeDescriptorType =275        buildBindingTables(bindingTables, mod);276 277    patterns.insert<SelectTypeConv>(context);278    patterns.insert<DispatchOpConv>(context, bindingTables, typeDescriptorType);279    mlir::ConversionTarget target(*context);280    target.addLegalDialect<mlir::affine::AffineDialect,281                           mlir::cf::ControlFlowDialect, FIROpsDialect,282                           mlir::func::FuncDialect>();283 284    // apply the patterns285    target.addIllegalOp<SelectTypeOp>();286    target.addIllegalOp<DispatchOp>();287    target.markUnknownOpDynamicallyLegal([](Operation *) { return true; });288    if (mlir::failed(mlir::applyPartialConversion(getOperation(), target,289                                                  std::move(patterns)))) {290      mlir::emitError(mlir::UnknownLoc::get(context),291                      "error in converting to CFG\n");292      signalPassFailure();293    }294  }295};296} // namespace297 298llvm::LogicalResult SelectTypeConv::matchAndRewrite(299    fir::SelectTypeOp selectType, OpAdaptor adaptor,300    mlir::ConversionPatternRewriter &rewriter) const {301  auto operands = adaptor.getOperands();302  auto typeGuards = selectType.getCases();303  unsigned typeGuardNum = typeGuards.size();304  auto selector = selectType.getSelector();305  auto loc = selectType.getLoc();306  auto mod = selectType.getOperation()->getParentOfType<mlir::ModuleOp>();307  fir::KindMapping kindMap = fir::getKindMapping(mod);308 309  // Order type guards so the condition and branches are done to respect the310  // Execution of SELECT TYPE construct as described in the Fortran 2018311  // standard 11.1.11.2 point 4.312  // 1. If a TYPE IS type guard statement matches the selector, the block313  //    following that statement is executed.314  // 2. Otherwise, if exactly one CLASS IS type guard statement matches the315  //    selector, the block following that statement is executed.316  // 3. Otherwise, if several CLASS IS type guard statements match the317  //    selector, one of these statements will inevitably specify a type that318  //    is an extension of all the types specified in the others; the block319  //    following that statement is executed.320  // 4. Otherwise, if there is a CLASS DEFAULT type guard statement, the block321  //    following that statement is executed.322  // 5. Otherwise, no block is executed.323 324  llvm::SmallVector<unsigned> orderedTypeGuards;325  llvm::SmallVector<unsigned> orderedClassIsGuards;326  unsigned defaultGuard = typeGuardNum - 1;327 328  // The following loop go through the type guards in the fir.select_type329  // operation and sort them into two lists.330  // - All the TYPE IS type guard are added in order to the orderedTypeGuards331  //   list. This list is used at the end to generate the if-then-else ladder.332  // - CLASS IS type guard are added in a separate list. If a CLASS IS type333  //   guard type extends a type already present, the type guard is inserted334  //   before in the list to respect point 3. above. Otherwise it is just335  //   added in order at the end.336  for (unsigned t = 0; t < typeGuardNum; ++t) {337    if (auto a = mlir::dyn_cast<fir::ExactTypeAttr>(typeGuards[t])) {338      orderedTypeGuards.push_back(t);339      continue;340    }341 342    if (auto a = mlir::dyn_cast<fir::SubclassAttr>(typeGuards[t])) {343      if (auto recTy = mlir::dyn_cast<fir::RecordType>(a.getType())) {344        auto dt = mod.lookupSymbol<fir::TypeInfoOp>(recTy.getName());345        assert(dt && "dispatch table not found");346        llvm::SmallSet<llvm::StringRef, 4> ancestors =347            collectAncestors(dt, mod);348        if (!ancestors.empty()) {349          auto it = orderedClassIsGuards.begin();350          while (it != orderedClassIsGuards.end()) {351            fir::SubclassAttr sAttr =352                mlir::dyn_cast<fir::SubclassAttr>(typeGuards[*it]);353            if (auto ty = mlir::dyn_cast<fir::RecordType>(sAttr.getType())) {354              if (ancestors.contains(ty.getName()))355                break;356            }357            ++it;358          }359          if (it != orderedClassIsGuards.end()) {360            // Parent type is present so place it before.361            orderedClassIsGuards.insert(it, t);362            continue;363          }364        }365      }366      orderedClassIsGuards.push_back(t);367    }368  }369  orderedTypeGuards.append(orderedClassIsGuards);370  orderedTypeGuards.push_back(defaultGuard);371  assert(orderedTypeGuards.size() == typeGuardNum &&372         "ordered type guard size doesn't match number of type guards");373 374  for (unsigned idx : orderedTypeGuards) {375    auto *dest = selectType.getSuccessor(idx);376    std::optional<mlir::ValueRange> destOps =377        selectType.getSuccessorOperands(operands, idx);378    if (mlir::dyn_cast<mlir::UnitAttr>(typeGuards[idx]))379      rewriter.replaceOpWithNewOp<mlir::cf::BranchOp>(380          selectType, dest, destOps.value_or(mlir::ValueRange{}));381    else if (mlir::failed(genTypeLadderStep(loc, selector, typeGuards[idx],382                                            dest, destOps, mod, rewriter,383                                            kindMap)))384      return mlir::failure();385  }386  return mlir::success();387}388 389llvm::LogicalResult SelectTypeConv::genTypeLadderStep(390    mlir::Location loc, mlir::Value selector, mlir::Attribute attr,391    mlir::Block *dest, std::optional<mlir::ValueRange> destOps,392    mlir::ModuleOp mod, mlir::PatternRewriter &rewriter,393    fir::KindMapping &kindMap) const {394  mlir::Value cmp;395  // TYPE IS type guard comparison are all done inlined.396  if (auto a = mlir::dyn_cast<fir::ExactTypeAttr>(attr)) {397    if (fir::isa_trivial(a.getType()) ||398        mlir::isa<fir::CharacterType>(a.getType())) {399      // For type guard statement with Intrinsic type spec the type code of400      // the descriptor is compared.401      int code = fir::getTypeCode(a.getType(), kindMap);402      if (code == 0)403        return mlir::emitError(loc)404               << "type code unavailable for " << a.getType();405      mlir::Value typeCode = mlir::arith::ConstantOp::create(406          rewriter, loc, rewriter.getI8IntegerAttr(code));407      mlir::Value selectorTypeCode = fir::BoxTypeCodeOp::create(408          rewriter, loc, rewriter.getI8Type(), selector);409      cmp = mlir::arith::CmpIOp::create(rewriter, loc,410                                        mlir::arith::CmpIPredicate::eq,411                                        selectorTypeCode, typeCode);412    } else {413      // Flang inline the kind parameter in the type descriptor so we can414      // directly check if the type descriptor addresses are identical for415      // the TYPE IS type guard statement.416      mlir::Value res =417          genTypeDescCompare(loc, selector, a.getType(), mod, rewriter);418      if (!res)419        return mlir::failure();420      cmp = res;421    }422    // CLASS IS type guard statement is done with a runtime call.423  } else if (auto a = mlir::dyn_cast<fir::SubclassAttr>(attr)) {424    // Retrieve the type descriptor from the type guard statement record type.425    assert(mlir::isa<fir::RecordType>(a.getType()) && "expect fir.record type");426    mlir::Value typeDescAddr = fir::TypeDescOp::create(427        rewriter, loc, mlir::TypeAttr::get(a.getType()));428    mlir::Type refNoneType = ReferenceType::get(rewriter.getNoneType());429    mlir::Value typeDesc =430        ConvertOp::create(rewriter, loc, refNoneType, typeDescAddr);431 432    // Prepare the selector descriptor for the runtime call.433    mlir::Type descNoneTy = fir::BoxType::get(rewriter.getNoneType());434    mlir::Value descSelector =435        ConvertOp::create(rewriter, loc, descNoneTy, selector);436 437    // Generate runtime call.438    llvm::StringRef fctName = RTNAME_STRING(ClassIs);439    mlir::func::FuncOp callee;440    {441      // Since conversion is done in parallel for each fir.select_type442      // operation, the runtime function insertion must be threadsafe.443      auto runtimeAttr =444          mlir::NamedAttribute(fir::FIROpsDialect::getFirRuntimeAttrName(),445                               mlir::UnitAttr::get(rewriter.getContext()));446      callee =447          fir::createFuncOp(rewriter.getUnknownLoc(), mod, fctName,448                            rewriter.getFunctionType({descNoneTy, refNoneType},449                                                     rewriter.getI1Type()),450                            {runtimeAttr});451    }452    cmp = fir::CallOp::create(rewriter, loc, callee,453                              mlir::ValueRange{descSelector, typeDesc})454              .getResult(0);455  }456 457  auto *thisBlock = rewriter.getInsertionBlock();458  auto *newBlock =459      rewriter.createBlock(dest->getParent(), mlir::Region::iterator(dest));460  rewriter.setInsertionPointToEnd(thisBlock);461  if (destOps.has_value())462    mlir::cf::CondBranchOp::create(rewriter, loc, cmp, dest, destOps.value(),463                                   newBlock, mlir::ValueRange{});464  else465    mlir::cf::CondBranchOp::create(rewriter, loc, cmp, dest, newBlock);466  rewriter.setInsertionPointToEnd(newBlock);467  return mlir::success();468}469 470// Generate comparison of type descriptor addresses.471mlir::Value472SelectTypeConv::genTypeDescCompare(mlir::Location loc, mlir::Value selector,473                                   mlir::Type ty, mlir::ModuleOp mod,474                                   mlir::PatternRewriter &rewriter) const {475  assert(mlir::isa<fir::RecordType>(ty) && "expect fir.record type");476  mlir::Value typeDescAddr =477      fir::TypeDescOp::create(rewriter, loc, mlir::TypeAttr::get(ty));478  mlir::Value selectorTdescAddr = fir::BoxTypeDescOp::create(479      rewriter, loc, typeDescAddr.getType(), selector);480  auto intPtrTy = rewriter.getIndexType();481  auto typeDescInt =482      fir::ConvertOp::create(rewriter, loc, intPtrTy, typeDescAddr);483  auto selectorTdescInt =484      fir::ConvertOp::create(rewriter, loc, intPtrTy, selectorTdescAddr);485  return mlir::arith::CmpIOp::create(rewriter, loc,486                                     mlir::arith::CmpIPredicate::eq,487                                     typeDescInt, selectorTdescInt);488}489 490llvm::SmallSet<llvm::StringRef, 4>491SelectTypeConv::collectAncestors(fir::TypeInfoOp dt, mlir::ModuleOp mod) const {492  llvm::SmallSet<llvm::StringRef, 4> ancestors;493  while (auto parentName = dt.getIfParentName()) {494    ancestors.insert(*parentName);495    dt = mod.lookupSymbol<fir::TypeInfoOp>(*parentName);496    assert(dt && "parent type info not generated");497  }498  return ancestors;499}500