1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230
|
//===-- FIRType.cpp -------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// Coding style: https://mlir.llvm.org/getting_started/DeveloperGuide/
//
//===----------------------------------------------------------------------===//
#include "flang/Optimizer/Dialect/FIRType.h"
#include "flang/ISO_Fortran_binding.h"
#include "flang/Optimizer/Dialect/FIRDialect.h"
#include "flang/Optimizer/Dialect/Support/KindMapping.h"
#include "flang/Tools/PointerModels.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/BuiltinDialect.h"
#include "mlir/IR/Diagnostics.h"
#include "mlir/IR/DialectImplementation.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/ADT/TypeSwitch.h"
#include "llvm/Support/ErrorHandling.h"
#define GET_TYPEDEF_CLASSES
#include "flang/Optimizer/Dialect/FIROpsTypes.cpp.inc"
using namespace fir;
namespace {
template <typename TYPE>
TYPE parseIntSingleton(mlir::AsmParser &parser) {
int kind = 0;
if (parser.parseLess() || parser.parseInteger(kind) || parser.parseGreater())
return {};
return TYPE::get(parser.getContext(), kind);
}
template <typename TYPE>
TYPE parseKindSingleton(mlir::AsmParser &parser) {
return parseIntSingleton<TYPE>(parser);
}
template <typename TYPE>
TYPE parseRankSingleton(mlir::AsmParser &parser) {
return parseIntSingleton<TYPE>(parser);
}
template <typename TYPE>
TYPE parseTypeSingleton(mlir::AsmParser &parser) {
mlir::Type ty;
if (parser.parseLess() || parser.parseType(ty) || parser.parseGreater())
return {};
return TYPE::get(ty);
}
/// Is `ty` a standard or FIR integer type?
static bool isaIntegerType(mlir::Type ty) {
// TODO: why aren't we using isa_integer? investigatation required.
return ty.isa<mlir::IntegerType>() || ty.isa<fir::IntegerType>();
}
bool verifyRecordMemberType(mlir::Type ty) {
return !(ty.isa<BoxCharType>() || ty.isa<ShapeType>() ||
ty.isa<ShapeShiftType>() || ty.isa<ShiftType>() ||
ty.isa<SliceType>() || ty.isa<FieldType>() || ty.isa<LenType>() ||
ty.isa<ReferenceType>() || ty.isa<TypeDescType>());
}
bool verifySameLists(llvm::ArrayRef<RecordType::TypePair> a1,
llvm::ArrayRef<RecordType::TypePair> a2) {
// FIXME: do we need to allow for any variance here?
return a1 == a2;
}
RecordType verifyDerived(mlir::AsmParser &parser, RecordType derivedTy,
llvm::ArrayRef<RecordType::TypePair> lenPList,
llvm::ArrayRef<RecordType::TypePair> typeList) {
auto loc = parser.getNameLoc();
if (!verifySameLists(derivedTy.getLenParamList(), lenPList) ||
!verifySameLists(derivedTy.getTypeList(), typeList)) {
parser.emitError(loc, "cannot redefine record type members");
return {};
}
for (auto &p : lenPList)
if (!isaIntegerType(p.second)) {
parser.emitError(loc, "LEN parameter must be integral type");
return {};
}
for (auto &p : typeList)
if (!verifyRecordMemberType(p.second)) {
parser.emitError(loc, "field parameter has invalid type");
return {};
}
llvm::StringSet<> uniq;
for (auto &p : lenPList)
if (!uniq.insert(p.first).second) {
parser.emitError(loc, "LEN parameter cannot have duplicate name");
return {};
}
for (auto &p : typeList)
if (!uniq.insert(p.first).second) {
parser.emitError(loc, "field cannot have duplicate name");
return {};
}
return derivedTy;
}
} // namespace
// Implementation of the thin interface from dialect to type parser
mlir::Type fir::parseFirType(FIROpsDialect *dialect,
mlir::DialectAsmParser &parser) {
mlir::StringRef typeTag;
mlir::Type genType;
auto parseResult = generatedTypeParser(parser, &typeTag, genType);
if (parseResult.has_value())
return genType;
parser.emitError(parser.getNameLoc(), "unknown fir type: ") << typeTag;
return {};
}
namespace fir {
namespace detail {
// Type storage classes
/// Derived type storage
struct RecordTypeStorage : public mlir::TypeStorage {
using KeyTy = llvm::StringRef;
static unsigned hashKey(const KeyTy &key) {
return llvm::hash_combine(key.str());
}
bool operator==(const KeyTy &key) const { return key == getName(); }
static RecordTypeStorage *construct(mlir::TypeStorageAllocator &allocator,
const KeyTy &key) {
auto *storage = allocator.allocate<RecordTypeStorage>();
return new (storage) RecordTypeStorage{key};
}
llvm::StringRef getName() const { return name; }
void setLenParamList(llvm::ArrayRef<RecordType::TypePair> list) {
lens = list;
}
llvm::ArrayRef<RecordType::TypePair> getLenParamList() const { return lens; }
void setTypeList(llvm::ArrayRef<RecordType::TypePair> list) { types = list; }
llvm::ArrayRef<RecordType::TypePair> getTypeList() const { return types; }
bool isFinalized() const { return finalized; }
void finalize(llvm::ArrayRef<RecordType::TypePair> lenParamList,
llvm::ArrayRef<RecordType::TypePair> typeList) {
if (finalized)
return;
finalized = true;
setLenParamList(lenParamList);
setTypeList(typeList);
}
protected:
std::string name;
bool finalized;
std::vector<RecordType::TypePair> lens;
std::vector<RecordType::TypePair> types;
private:
RecordTypeStorage() = delete;
explicit RecordTypeStorage(llvm::StringRef name)
: name{name}, finalized{false} {}
};
} // namespace detail
template <typename A, typename B>
bool inbounds(A v, B lb, B ub) {
return v >= lb && v < ub;
}
bool isa_fir_type(mlir::Type t) {
return llvm::isa<FIROpsDialect>(t.getDialect());
}
bool isa_std_type(mlir::Type t) {
return llvm::isa<mlir::BuiltinDialect>(t.getDialect());
}
bool isa_fir_or_std_type(mlir::Type t) {
if (auto funcType = t.dyn_cast<mlir::FunctionType>())
return llvm::all_of(funcType.getInputs(), isa_fir_or_std_type) &&
llvm::all_of(funcType.getResults(), isa_fir_or_std_type);
return isa_fir_type(t) || isa_std_type(t);
}
mlir::Type getDerivedType(mlir::Type ty) {
return llvm::TypeSwitch<mlir::Type, mlir::Type>(ty)
.Case<fir::PointerType, fir::HeapType, fir::SequenceType>([](auto p) {
if (auto seq = p.getEleTy().template dyn_cast<fir::SequenceType>())
return seq.getEleTy();
return p.getEleTy();
})
.Default([](mlir::Type t) { return t; });
}
mlir::Type dyn_cast_ptrEleTy(mlir::Type t) {
return llvm::TypeSwitch<mlir::Type, mlir::Type>(t)
.Case<fir::ReferenceType, fir::PointerType, fir::HeapType,
fir::LLVMPointerType>([](auto p) { return p.getEleTy(); })
.Default([](mlir::Type) { return mlir::Type{}; });
}
mlir::Type dyn_cast_ptrOrBoxEleTy(mlir::Type t) {
return llvm::TypeSwitch<mlir::Type, mlir::Type>(t)
.Case<fir::ReferenceType, fir::PointerType, fir::HeapType,
fir::LLVMPointerType>([](auto p) { return p.getEleTy(); })
.Case<fir::BaseBoxType>(
[](auto p) { return unwrapRefType(p.getEleTy()); })
.Default([](mlir::Type) { return mlir::Type{}; });
}
static bool hasDynamicSize(fir::RecordType recTy) {
for (auto field : recTy.getTypeList()) {
if (auto arr = field.second.dyn_cast<fir::SequenceType>()) {
if (sequenceWithNonConstantShape(arr))
return true;
} else if (characterWithDynamicLen(field.second)) {
return true;
} else if (auto rec = field.second.dyn_cast<fir::RecordType>()) {
if (hasDynamicSize(rec))
return true;
}
}
return false;
}
bool hasDynamicSize(mlir::Type t) {
if (auto arr = t.dyn_cast<fir::SequenceType>()) {
if (sequenceWithNonConstantShape(arr))
return true;
t = arr.getEleTy();
}
if (characterWithDynamicLen(t))
return true;
if (auto rec = t.dyn_cast<fir::RecordType>())
return hasDynamicSize(rec);
return false;
}
bool isPointerType(mlir::Type ty) {
if (auto refTy = fir::dyn_cast_ptrEleTy(ty))
ty = refTy;
if (auto boxTy = ty.dyn_cast<fir::BaseBoxType>())
return boxTy.getEleTy().isa<fir::PointerType>();
return false;
}
bool isAllocatableType(mlir::Type ty) {
if (auto refTy = fir::dyn_cast_ptrEleTy(ty))
ty = refTy;
if (auto boxTy = ty.dyn_cast<fir::BaseBoxType>())
return boxTy.getEleTy().isa<fir::HeapType>();
return false;
}
bool isBoxNone(mlir::Type ty) {
if (auto box = ty.dyn_cast<fir::BoxType>())
return box.getEleTy().isa<mlir::NoneType>();
return false;
}
bool isBoxedRecordType(mlir::Type ty) {
if (auto refTy = fir::dyn_cast_ptrEleTy(ty))
ty = refTy;
if (auto boxTy = ty.dyn_cast<fir::BoxType>()) {
if (boxTy.getEleTy().isa<fir::RecordType>())
return true;
mlir::Type innerType = boxTy.unwrapInnerType();
return innerType && innerType.isa<fir::RecordType>();
}
return false;
}
bool isScalarBoxedRecordType(mlir::Type ty) {
if (auto refTy = fir::dyn_cast_ptrEleTy(ty))
ty = refTy;
if (auto boxTy = ty.dyn_cast<fir::BaseBoxType>()) {
if (boxTy.getEleTy().isa<fir::RecordType>())
return true;
if (auto heapTy = boxTy.getEleTy().dyn_cast<fir::HeapType>())
return heapTy.getEleTy().isa<fir::RecordType>();
if (auto ptrTy = boxTy.getEleTy().dyn_cast<fir::PointerType>())
return ptrTy.getEleTy().isa<fir::RecordType>();
}
return false;
}
bool isAssumedType(mlir::Type ty) {
if (auto boxTy = ty.dyn_cast<fir::BoxType>()) {
if (boxTy.getEleTy().isa<mlir::NoneType>())
return true;
if (auto seqTy = boxTy.getEleTy().dyn_cast<fir::SequenceType>())
return seqTy.getEleTy().isa<mlir::NoneType>();
}
return false;
}
bool isPolymorphicType(mlir::Type ty) {
if (auto refTy = fir::dyn_cast_ptrEleTy(ty))
ty = refTy;
// CLASS(*)
if (ty.isa<fir::ClassType>())
return true;
// assumed type are polymorphic.
return isAssumedType(ty);
}
bool isUnlimitedPolymorphicType(mlir::Type ty) {
if (auto refTy = fir::dyn_cast_ptrEleTy(ty))
ty = refTy;
// CLASS(*)
if (auto clTy = ty.dyn_cast<fir::ClassType>()) {
if (clTy.getEleTy().isa<mlir::NoneType>())
return true;
mlir::Type innerType = clTy.unwrapInnerType();
return innerType && innerType.isa<mlir::NoneType>();
}
// TYPE(*)
return isAssumedType(ty);
}
mlir::Type unwrapInnerType(mlir::Type ty) {
return llvm::TypeSwitch<mlir::Type, mlir::Type>(ty)
.Case<fir::PointerType, fir::HeapType, fir::SequenceType>([](auto t) {
mlir::Type eleTy = t.getEleTy();
if (auto seqTy = eleTy.dyn_cast<fir::SequenceType>())
return seqTy.getEleTy();
return eleTy;
})
.Case<fir::RecordType>([](auto t) { return t; })
.Default([](mlir::Type) { return mlir::Type{}; });
}
bool isRecordWithAllocatableMember(mlir::Type ty) {
if (auto recTy = ty.dyn_cast<fir::RecordType>())
for (auto [field, memTy] : recTy.getTypeList()) {
if (fir::isAllocatableType(memTy))
return true;
// A record type cannot recursively include itself as a direct member.
// There must be an intervening `ptr` type, so recursion is safe here.
if (memTy.isa<fir::RecordType>() && isRecordWithAllocatableMember(memTy))
return true;
}
return false;
}
mlir::Type unwrapAllRefAndSeqType(mlir::Type ty) {
while (true) {
mlir::Type nt = unwrapSequenceType(unwrapRefType(ty));
if (auto vecTy = nt.dyn_cast<fir::VectorType>())
nt = vecTy.getEleTy();
if (nt == ty)
return ty;
ty = nt;
}
}
mlir::Type unwrapSeqOrBoxedSeqType(mlir::Type ty) {
if (auto seqTy = ty.dyn_cast<fir::SequenceType>())
return seqTy.getEleTy();
if (auto boxTy = ty.dyn_cast<fir::BoxType>()) {
auto eleTy = unwrapRefType(boxTy.getEleTy());
if (auto seqTy = eleTy.dyn_cast<fir::SequenceType>())
return seqTy.getEleTy();
}
return ty;
}
unsigned getBoxRank(mlir::Type boxTy) {
auto eleTy = fir::dyn_cast_ptrOrBoxEleTy(boxTy);
if (auto seqTy = eleTy.dyn_cast<fir::SequenceType>())
return seqTy.getDimension();
return 0;
}
/// Return the ISO_C_BINDING intrinsic module value of type \p ty.
int getTypeCode(mlir::Type ty, const fir::KindMapping &kindMap) {
unsigned width = 0;
if (mlir::IntegerType intTy = ty.dyn_cast<mlir::IntegerType>()) {
switch (intTy.getWidth()) {
case 8:
return CFI_type_int8_t;
case 16:
return CFI_type_int16_t;
case 32:
return CFI_type_int32_t;
case 64:
return CFI_type_int64_t;
case 128:
return CFI_type_int128_t;
}
llvm_unreachable("unsupported integer type");
}
if (fir::LogicalType logicalTy = ty.dyn_cast<fir::LogicalType>()) {
switch (kindMap.getLogicalBitsize(logicalTy.getFKind())) {
case 8:
return CFI_type_Bool;
case 16:
return CFI_type_int_least16_t;
case 32:
return CFI_type_int_least32_t;
case 64:
return CFI_type_int_least64_t;
}
llvm_unreachable("unsupported logical type");
}
if (mlir::FloatType floatTy = ty.dyn_cast<mlir::FloatType>()) {
switch (floatTy.getWidth()) {
case 16:
return floatTy.isBF16() ? CFI_type_bfloat : CFI_type_half_float;
case 32:
return CFI_type_float;
case 64:
return CFI_type_double;
case 80:
return CFI_type_extended_double;
case 128:
return CFI_type_float128;
}
llvm_unreachable("unsupported real type");
}
if (fir::isa_complex(ty)) {
if (mlir::ComplexType complexTy = ty.dyn_cast<mlir::ComplexType>()) {
mlir::FloatType floatTy =
complexTy.getElementType().cast<mlir::FloatType>();
if (floatTy.isBF16())
return CFI_type_bfloat_Complex;
width = floatTy.getWidth();
} else if (fir::ComplexType complexTy = ty.dyn_cast<fir::ComplexType>()) {
auto FKind = complexTy.getFKind();
if (FKind == 3)
return CFI_type_bfloat_Complex;
width = kindMap.getRealBitsize(FKind);
}
switch (width) {
case 16:
return CFI_type_half_float_Complex;
case 32:
return CFI_type_float_Complex;
case 64:
return CFI_type_double_Complex;
case 80:
return CFI_type_extended_double_Complex;
case 128:
return CFI_type_float128_Complex;
}
llvm_unreachable("unsupported complex size");
}
if (fir::CharacterType charTy = ty.dyn_cast<fir::CharacterType>()) {
switch (kindMap.getCharacterBitsize(charTy.getFKind())) {
case 8:
return CFI_type_char;
case 16:
return CFI_type_char16_t;
case 32:
return CFI_type_char32_t;
}
llvm_unreachable("unsupported character type");
}
if (fir::isa_ref_type(ty))
return CFI_type_cptr;
if (ty.isa<fir::RecordType>())
return CFI_type_struct;
llvm_unreachable("unsupported type");
}
std::string getTypeAsString(mlir::Type ty, const fir::KindMapping &kindMap,
llvm::StringRef prefix) {
std::string buf;
llvm::raw_string_ostream name{buf};
name << prefix.str();
if (!prefix.empty())
name << "_";
while (ty) {
if (fir::isa_trivial(ty)) {
if (mlir::isa<mlir::IndexType>(ty)) {
name << "idx";
} else if (ty.isIntOrIndex()) {
name << 'i' << ty.getIntOrFloatBitWidth();
} else if (ty.isa<mlir::FloatType>()) {
name << 'f' << ty.getIntOrFloatBitWidth();
} else if (fir::isa_complex(ty)) {
name << 'z';
if (auto cplxTy = mlir::dyn_cast_or_null<mlir::ComplexType>(ty)) {
auto floatTy = cplxTy.getElementType().cast<mlir::FloatType>();
name << floatTy.getWidth();
} else if (auto cplxTy = mlir::dyn_cast_or_null<fir::ComplexType>(ty)) {
name << kindMap.getRealBitsize(cplxTy.getFKind());
}
} else if (auto logTy = mlir::dyn_cast_or_null<fir::LogicalType>(ty)) {
name << 'l' << kindMap.getLogicalBitsize(logTy.getFKind());
} else {
llvm::report_fatal_error("unsupported type");
}
break;
} else if (mlir::isa<mlir::NoneType>(ty)) {
name << "none";
break;
} else if (auto charTy = mlir::dyn_cast_or_null<fir::CharacterType>(ty)) {
name << 'c' << kindMap.getCharacterBitsize(charTy.getFKind());
if (charTy.getLen() != fir::CharacterType::singleton())
name << "x" << charTy.getLen();
break;
} else if (auto seqTy = mlir::dyn_cast_or_null<fir::SequenceType>(ty)) {
for (auto extent : seqTy.getShape()) {
if (extent == fir::SequenceType::getUnknownExtent())
name << "?x";
else
name << extent << 'x';
}
ty = seqTy.getEleTy();
} else if (auto refTy = mlir::dyn_cast_or_null<fir::ReferenceType>(ty)) {
name << "ref_";
ty = refTy.getEleTy();
} else if (auto ptrTy = mlir::dyn_cast_or_null<fir::PointerType>(ty)) {
name << "ptr_";
ty = ptrTy.getEleTy();
} else if (auto heapTy = mlir::dyn_cast_or_null<fir::HeapType>(ty)) {
name << "heap_";
ty = heapTy.getEleTy();
} else if (auto classTy = mlir::dyn_cast_or_null<fir::ClassType>(ty)) {
name << "class_";
ty = classTy.getEleTy();
} else if (auto boxTy = mlir::dyn_cast_or_null<fir::BoxType>(ty)) {
name << "box_";
ty = boxTy.getEleTy();
} else if (auto recTy = mlir::dyn_cast_or_null<fir::RecordType>(ty)) {
name << "rec_" << recTy.getName();
break;
} else {
llvm::report_fatal_error("unsupported type");
}
}
return name.str();
}
} // namespace fir
namespace {
static llvm::SmallPtrSet<detail::RecordTypeStorage const *, 4>
recordTypeVisited;
} // namespace
void fir::verifyIntegralType(mlir::Type type) {
if (isaIntegerType(type) || type.isa<mlir::IndexType>())
return;
llvm::report_fatal_error("expected integral type");
}
void fir::printFirType(FIROpsDialect *, mlir::Type ty,
mlir::DialectAsmPrinter &p) {
if (mlir::failed(generatedTypePrinter(ty, p)))
llvm::report_fatal_error("unknown type to print");
}
bool fir::isa_unknown_size_box(mlir::Type t) {
if (auto boxTy = t.dyn_cast<fir::BaseBoxType>()) {
auto valueType = fir::unwrapPassByRefType(boxTy);
if (auto seqTy = valueType.dyn_cast<fir::SequenceType>())
if (seqTy.hasUnknownShape())
return true;
}
return false;
}
//===----------------------------------------------------------------------===//
// BoxProcType
//===----------------------------------------------------------------------===//
// `boxproc` `<` return-type `>`
mlir::Type BoxProcType::parse(mlir::AsmParser &parser) {
mlir::Type ty;
if (parser.parseLess() || parser.parseType(ty) || parser.parseGreater())
return {};
return get(parser.getContext(), ty);
}
void fir::BoxProcType::print(mlir::AsmPrinter &printer) const {
printer << "<" << getEleTy() << '>';
}
mlir::LogicalResult
BoxProcType::verify(llvm::function_ref<mlir::InFlightDiagnostic()> emitError,
mlir::Type eleTy) {
if (eleTy.isa<mlir::FunctionType>())
return mlir::success();
if (auto refTy = eleTy.dyn_cast<ReferenceType>())
if (refTy.isa<mlir::FunctionType>())
return mlir::success();
return emitError() << "invalid type for boxproc" << eleTy << '\n';
}
static bool cannotBePointerOrHeapElementType(mlir::Type eleTy) {
return eleTy.isa<BoxType, BoxCharType, BoxProcType, ShapeType, ShapeShiftType,
SliceType, FieldType, LenType, HeapType, PointerType,
ReferenceType, TypeDescType>();
}
//===----------------------------------------------------------------------===//
// BoxType
//===----------------------------------------------------------------------===//
mlir::LogicalResult
fir::BoxType::verify(llvm::function_ref<mlir::InFlightDiagnostic()> emitError,
mlir::Type eleTy) {
if (eleTy.isa<fir::BaseBoxType>())
return emitError() << "invalid element type\n";
// TODO
return mlir::success();
}
//===----------------------------------------------------------------------===//
// BoxCharType
//===----------------------------------------------------------------------===//
mlir::Type fir::BoxCharType::parse(mlir::AsmParser &parser) {
return parseKindSingleton<fir::BoxCharType>(parser);
}
void fir::BoxCharType::print(mlir::AsmPrinter &printer) const {
printer << "<" << getKind() << ">";
}
CharacterType
fir::BoxCharType::getElementType(mlir::MLIRContext *context) const {
return CharacterType::getUnknownLen(context, getKind());
}
CharacterType fir::BoxCharType::getEleTy() const {
return getElementType(getContext());
}
//===----------------------------------------------------------------------===//
// CharacterType
//===----------------------------------------------------------------------===//
// `char` `<` kind [`,` `len`] `>`
mlir::Type fir::CharacterType::parse(mlir::AsmParser &parser) {
int kind = 0;
if (parser.parseLess() || parser.parseInteger(kind))
return {};
CharacterType::LenType len = 1;
if (mlir::succeeded(parser.parseOptionalComma())) {
if (mlir::succeeded(parser.parseOptionalQuestion())) {
len = fir::CharacterType::unknownLen();
} else if (!mlir::succeeded(parser.parseInteger(len))) {
return {};
}
}
if (parser.parseGreater())
return {};
return get(parser.getContext(), kind, len);
}
void fir::CharacterType::print(mlir::AsmPrinter &printer) const {
printer << "<" << getFKind();
auto len = getLen();
if (len != fir::CharacterType::singleton()) {
printer << ',';
if (len == fir::CharacterType::unknownLen())
printer << '?';
else
printer << len;
}
printer << '>';
}
//===----------------------------------------------------------------------===//
// ClassType
//===----------------------------------------------------------------------===//
mlir::LogicalResult
fir::ClassType::verify(llvm::function_ref<mlir::InFlightDiagnostic()> emitError,
mlir::Type eleTy) {
if (eleTy.isa<fir::RecordType, fir::SequenceType, fir::HeapType,
fir::PointerType, mlir::NoneType, mlir::IntegerType,
mlir::FloatType, fir::CharacterType, fir::LogicalType,
fir::ComplexType, mlir::ComplexType>())
return mlir::success();
return emitError() << "invalid element type\n";
}
//===----------------------------------------------------------------------===//
// ComplexType
//===----------------------------------------------------------------------===//
mlir::Type fir::ComplexType::parse(mlir::AsmParser &parser) {
return parseKindSingleton<fir::ComplexType>(parser);
}
void fir::ComplexType::print(mlir::AsmPrinter &printer) const {
printer << "<" << getFKind() << '>';
}
mlir::Type fir::ComplexType::getElementType() const {
return fir::RealType::get(getContext(), getFKind());
}
// Return the MLIR float type of the complex element type.
mlir::Type fir::ComplexType::getEleType(const fir::KindMapping &kindMap) const {
auto fkind = getFKind();
auto realTypeID = kindMap.getRealTypeID(fkind);
return fir::fromRealTypeID(getContext(), realTypeID, fkind);
}
//===----------------------------------------------------------------------===//
// HeapType
//===----------------------------------------------------------------------===//
// `heap` `<` type `>`
mlir::Type fir::HeapType::parse(mlir::AsmParser &parser) {
return parseTypeSingleton<HeapType>(parser);
}
void fir::HeapType::print(mlir::AsmPrinter &printer) const {
printer << "<" << getEleTy() << '>';
}
mlir::LogicalResult
fir::HeapType::verify(llvm::function_ref<mlir::InFlightDiagnostic()> emitError,
mlir::Type eleTy) {
if (cannotBePointerOrHeapElementType(eleTy))
return emitError() << "cannot build a heap pointer to type: " << eleTy
<< '\n';
return mlir::success();
}
//===----------------------------------------------------------------------===//
// IntegerType
//===----------------------------------------------------------------------===//
// `int` `<` kind `>`
mlir::Type fir::IntegerType::parse(mlir::AsmParser &parser) {
return parseKindSingleton<fir::IntegerType>(parser);
}
void fir::IntegerType::print(mlir::AsmPrinter &printer) const {
printer << "<" << getFKind() << '>';
}
//===----------------------------------------------------------------------===//
// LogicalType
//===----------------------------------------------------------------------===//
// `logical` `<` kind `>`
mlir::Type fir::LogicalType::parse(mlir::AsmParser &parser) {
return parseKindSingleton<fir::LogicalType>(parser);
}
void fir::LogicalType::print(mlir::AsmPrinter &printer) const {
printer << "<" << getFKind() << '>';
}
//===----------------------------------------------------------------------===//
// PointerType
//===----------------------------------------------------------------------===//
// `ptr` `<` type `>`
mlir::Type fir::PointerType::parse(mlir::AsmParser &parser) {
return parseTypeSingleton<fir::PointerType>(parser);
}
void fir::PointerType::print(mlir::AsmPrinter &printer) const {
printer << "<" << getEleTy() << '>';
}
mlir::LogicalResult fir::PointerType::verify(
llvm::function_ref<mlir::InFlightDiagnostic()> emitError,
mlir::Type eleTy) {
if (cannotBePointerOrHeapElementType(eleTy))
return emitError() << "cannot build a pointer to type: " << eleTy << '\n';
return mlir::success();
}
//===----------------------------------------------------------------------===//
// RealType
//===----------------------------------------------------------------------===//
// `real` `<` kind `>`
mlir::Type fir::RealType::parse(mlir::AsmParser &parser) {
return parseKindSingleton<fir::RealType>(parser);
}
void fir::RealType::print(mlir::AsmPrinter &printer) const {
printer << "<" << getFKind() << '>';
}
mlir::LogicalResult
fir::RealType::verify(llvm::function_ref<mlir::InFlightDiagnostic()> emitError,
KindTy fKind) {
// TODO
return mlir::success();
}
//===----------------------------------------------------------------------===//
// RecordType
//===----------------------------------------------------------------------===//
// Fortran derived type
// `type` `<` name
// (`(` id `:` type (`,` id `:` type)* `)`)?
// (`{` id `:` type (`,` id `:` type)* `}`)? '>'
mlir::Type fir::RecordType::parse(mlir::AsmParser &parser) {
llvm::StringRef name;
if (parser.parseLess() || parser.parseKeyword(&name))
return {};
RecordType result = RecordType::get(parser.getContext(), name);
RecordType::TypeList lenParamList;
if (!parser.parseOptionalLParen()) {
while (true) {
llvm::StringRef lenparam;
mlir::Type intTy;
if (parser.parseKeyword(&lenparam) || parser.parseColon() ||
parser.parseType(intTy)) {
parser.emitError(parser.getNameLoc(), "expected LEN parameter list");
return {};
}
lenParamList.emplace_back(lenparam, intTy);
if (parser.parseOptionalComma())
break;
}
if (parser.parseRParen())
return {};
}
RecordType::TypeList typeList;
if (!parser.parseOptionalLBrace()) {
while (true) {
llvm::StringRef field;
mlir::Type fldTy;
if (parser.parseKeyword(&field) || parser.parseColon() ||
parser.parseType(fldTy)) {
parser.emitError(parser.getNameLoc(), "expected field type list");
return {};
}
typeList.emplace_back(field, fldTy);
if (parser.parseOptionalComma())
break;
}
if (parser.parseRBrace())
return {};
}
if (parser.parseGreater())
return {};
if (lenParamList.empty() && typeList.empty())
return result;
result.finalize(lenParamList, typeList);
return verifyDerived(parser, result, lenParamList, typeList);
}
void fir::RecordType::print(mlir::AsmPrinter &printer) const {
printer << "<" << getName();
if (!recordTypeVisited.count(uniqueKey())) {
recordTypeVisited.insert(uniqueKey());
if (getLenParamList().size()) {
char ch = '(';
for (auto p : getLenParamList()) {
printer << ch << p.first << ':';
p.second.print(printer.getStream());
ch = ',';
}
printer << ')';
}
if (getTypeList().size()) {
char ch = '{';
for (auto p : getTypeList()) {
printer << ch << p.first << ':';
p.second.print(printer.getStream());
ch = ',';
}
printer << '}';
}
recordTypeVisited.erase(uniqueKey());
}
printer << '>';
}
void fir::RecordType::finalize(llvm::ArrayRef<TypePair> lenPList,
llvm::ArrayRef<TypePair> typeList) {
getImpl()->finalize(lenPList, typeList);
}
llvm::StringRef fir::RecordType::getName() const {
return getImpl()->getName();
}
RecordType::TypeList fir::RecordType::getTypeList() const {
return getImpl()->getTypeList();
}
RecordType::TypeList fir::RecordType::getLenParamList() const {
return getImpl()->getLenParamList();
}
bool fir::RecordType::isFinalized() const { return getImpl()->isFinalized(); }
detail::RecordTypeStorage const *fir::RecordType::uniqueKey() const {
return getImpl();
}
mlir::LogicalResult fir::RecordType::verify(
llvm::function_ref<mlir::InFlightDiagnostic()> emitError,
llvm::StringRef name) {
if (name.size() == 0)
return emitError() << "record types must have a name";
return mlir::success();
}
mlir::Type fir::RecordType::getType(llvm::StringRef ident) {
for (auto f : getTypeList())
if (ident == f.first)
return f.second;
return {};
}
unsigned fir::RecordType::getFieldIndex(llvm::StringRef ident) {
for (auto f : llvm::enumerate(getTypeList()))
if (ident == f.value().first)
return f.index();
return std::numeric_limits<unsigned>::max();
}
//===----------------------------------------------------------------------===//
// ReferenceType
//===----------------------------------------------------------------------===//
// `ref` `<` type `>`
mlir::Type fir::ReferenceType::parse(mlir::AsmParser &parser) {
return parseTypeSingleton<fir::ReferenceType>(parser);
}
void fir::ReferenceType::print(mlir::AsmPrinter &printer) const {
printer << "<" << getEleTy() << '>';
}
mlir::LogicalResult fir::ReferenceType::verify(
llvm::function_ref<mlir::InFlightDiagnostic()> emitError,
mlir::Type eleTy) {
if (eleTy.isa<ShapeType, ShapeShiftType, SliceType, FieldType, LenType,
ReferenceType, TypeDescType>())
return emitError() << "cannot build a reference to type: " << eleTy << '\n';
return mlir::success();
}
//===----------------------------------------------------------------------===//
// SequenceType
//===----------------------------------------------------------------------===//
// `array` `<` `*` | bounds (`x` bounds)* `:` type (',' affine-map)? `>`
// bounds ::= `?` | int-lit
mlir::Type fir::SequenceType::parse(mlir::AsmParser &parser) {
if (parser.parseLess())
return {};
SequenceType::Shape shape;
if (parser.parseOptionalStar()) {
if (parser.parseDimensionList(shape, /*allowDynamic=*/true))
return {};
} else if (parser.parseColon()) {
return {};
}
mlir::Type eleTy;
if (parser.parseType(eleTy))
return {};
mlir::AffineMapAttr map;
if (!parser.parseOptionalComma()) {
if (parser.parseAttribute(map)) {
parser.emitError(parser.getNameLoc(), "expecting affine map");
return {};
}
}
if (parser.parseGreater())
return {};
return SequenceType::get(parser.getContext(), shape, eleTy, map);
}
void fir::SequenceType::print(mlir::AsmPrinter &printer) const {
auto shape = getShape();
if (shape.size()) {
printer << '<';
for (const auto &b : shape) {
if (b >= 0)
printer << b << 'x';
else
printer << "?x";
}
} else {
printer << "<*:";
}
printer << getEleTy();
if (auto map = getLayoutMap()) {
printer << ", ";
map.print(printer.getStream());
}
printer << '>';
}
unsigned fir::SequenceType::getConstantRows() const {
if (hasDynamicSize(getEleTy()))
return 0;
auto shape = getShape();
unsigned count = 0;
for (auto d : shape) {
if (d == getUnknownExtent())
break;
++count;
}
return count;
}
mlir::LogicalResult fir::SequenceType::verify(
llvm::function_ref<mlir::InFlightDiagnostic()> emitError,
llvm::ArrayRef<int64_t> shape, mlir::Type eleTy,
mlir::AffineMapAttr layoutMap) {
// DIMENSION attribute can only be applied to an intrinsic or record type
if (eleTy.isa<BoxType, BoxCharType, BoxProcType, ShapeType, ShapeShiftType,
ShiftType, SliceType, FieldType, LenType, HeapType, PointerType,
ReferenceType, TypeDescType, SequenceType>())
return emitError() << "cannot build an array of this element type: "
<< eleTy << '\n';
return mlir::success();
}
//===----------------------------------------------------------------------===//
// ShapeType
//===----------------------------------------------------------------------===//
mlir::Type fir::ShapeType::parse(mlir::AsmParser &parser) {
return parseRankSingleton<fir::ShapeType>(parser);
}
void fir::ShapeType::print(mlir::AsmPrinter &printer) const {
printer << "<" << getImpl()->rank << ">";
}
//===----------------------------------------------------------------------===//
// ShapeShiftType
//===----------------------------------------------------------------------===//
mlir::Type fir::ShapeShiftType::parse(mlir::AsmParser &parser) {
return parseRankSingleton<fir::ShapeShiftType>(parser);
}
void fir::ShapeShiftType::print(mlir::AsmPrinter &printer) const {
printer << "<" << getRank() << ">";
}
//===----------------------------------------------------------------------===//
// ShiftType
//===----------------------------------------------------------------------===//
mlir::Type fir::ShiftType::parse(mlir::AsmParser &parser) {
return parseRankSingleton<fir::ShiftType>(parser);
}
void fir::ShiftType::print(mlir::AsmPrinter &printer) const {
printer << "<" << getRank() << ">";
}
//===----------------------------------------------------------------------===//
// SliceType
//===----------------------------------------------------------------------===//
// `slice` `<` rank `>`
mlir::Type fir::SliceType::parse(mlir::AsmParser &parser) {
return parseRankSingleton<fir::SliceType>(parser);
}
void fir::SliceType::print(mlir::AsmPrinter &printer) const {
printer << "<" << getRank() << '>';
}
//===----------------------------------------------------------------------===//
// TypeDescType
//===----------------------------------------------------------------------===//
// `tdesc` `<` type `>`
mlir::Type fir::TypeDescType::parse(mlir::AsmParser &parser) {
return parseTypeSingleton<fir::TypeDescType>(parser);
}
void fir::TypeDescType::print(mlir::AsmPrinter &printer) const {
printer << "<" << getOfTy() << '>';
}
mlir::LogicalResult fir::TypeDescType::verify(
llvm::function_ref<mlir::InFlightDiagnostic()> emitError,
mlir::Type eleTy) {
if (eleTy.isa<BoxType, BoxCharType, BoxProcType, ShapeType, ShapeShiftType,
ShiftType, SliceType, FieldType, LenType, ReferenceType,
TypeDescType>())
return emitError() << "cannot build a type descriptor of type: " << eleTy
<< '\n';
return mlir::success();
}
//===----------------------------------------------------------------------===//
// VectorType
//===----------------------------------------------------------------------===//
// `vector` `<` len `:` type `>`
mlir::Type fir::VectorType::parse(mlir::AsmParser &parser) {
int64_t len = 0;
mlir::Type eleTy;
if (parser.parseLess() || parser.parseInteger(len) || parser.parseColon() ||
parser.parseType(eleTy) || parser.parseGreater())
return {};
return fir::VectorType::get(len, eleTy);
}
void fir::VectorType::print(mlir::AsmPrinter &printer) const {
printer << "<" << getLen() << ':' << getEleTy() << '>';
}
mlir::LogicalResult fir::VectorType::verify(
llvm::function_ref<mlir::InFlightDiagnostic()> emitError, uint64_t len,
mlir::Type eleTy) {
if (!(fir::isa_real(eleTy) || fir::isa_integer(eleTy)))
return emitError() << "cannot build a vector of type " << eleTy << '\n';
return mlir::success();
}
bool fir::VectorType::isValidElementType(mlir::Type t) {
return isa_real(t) || isa_integer(t);
}
bool fir::isCharacterProcedureTuple(mlir::Type ty, bool acceptRawFunc) {
mlir::TupleType tuple = ty.dyn_cast<mlir::TupleType>();
return tuple && tuple.size() == 2 &&
(tuple.getType(0).isa<fir::BoxProcType>() ||
(acceptRawFunc && tuple.getType(0).isa<mlir::FunctionType>())) &&
fir::isa_integer(tuple.getType(1));
}
bool fir::hasAbstractResult(mlir::FunctionType ty) {
if (ty.getNumResults() == 0)
return false;
auto resultType = ty.getResult(0);
return resultType.isa<fir::SequenceType, fir::BaseBoxType, fir::RecordType>();
}
/// Convert llvm::Type::TypeID to mlir::Type. \p kind is provided for error
/// messages only.
mlir::Type fir::fromRealTypeID(mlir::MLIRContext *context,
llvm::Type::TypeID typeID, fir::KindTy kind) {
switch (typeID) {
case llvm::Type::TypeID::HalfTyID:
return mlir::FloatType::getF16(context);
case llvm::Type::TypeID::BFloatTyID:
return mlir::FloatType::getBF16(context);
case llvm::Type::TypeID::FloatTyID:
return mlir::FloatType::getF32(context);
case llvm::Type::TypeID::DoubleTyID:
return mlir::FloatType::getF64(context);
case llvm::Type::TypeID::X86_FP80TyID:
return mlir::FloatType::getF80(context);
case llvm::Type::TypeID::FP128TyID:
return mlir::FloatType::getF128(context);
default:
mlir::emitError(mlir::UnknownLoc::get(context))
<< "unsupported type: !fir.real<" << kind << ">";
return {};
}
}
//===----------------------------------------------------------------------===//
// BaseBoxType
//===----------------------------------------------------------------------===//
mlir::Type BaseBoxType::getEleTy() const {
return llvm::TypeSwitch<fir::BaseBoxType, mlir::Type>(*this)
.Case<fir::BoxType, fir::ClassType>(
[](auto type) { return type.getEleTy(); });
}
mlir::Type BaseBoxType::unwrapInnerType() const {
return fir::unwrapInnerType(getEleTy());
}
//===----------------------------------------------------------------------===//
// FIROpsDialect
//===----------------------------------------------------------------------===//
void FIROpsDialect::registerTypes() {
addTypes<BoxType, BoxCharType, BoxProcType, CharacterType, ClassType,
fir::ComplexType, FieldType, HeapType, fir::IntegerType, LenType,
LogicalType, LLVMPointerType, PointerType, RealType, RecordType,
ReferenceType, SequenceType, ShapeType, ShapeShiftType, ShiftType,
SliceType, TypeDescType, fir::VectorType>();
fir::ReferenceType::attachInterface<
OpenMPPointerLikeModel<fir::ReferenceType>>(*getContext());
fir::ReferenceType::attachInterface<
OpenACCPointerLikeModel<fir::ReferenceType>>(*getContext());
fir::PointerType::attachInterface<OpenMPPointerLikeModel<fir::PointerType>>(
*getContext());
fir::PointerType::attachInterface<OpenACCPointerLikeModel<fir::PointerType>>(
*getContext());
fir::HeapType::attachInterface<OpenMPPointerLikeModel<fir::HeapType>>(
*getContext());
fir::HeapType::attachInterface<OpenACCPointerLikeModel<fir::HeapType>>(
*getContext());
fir::LLVMPointerType::attachInterface<
OpenMPPointerLikeModel<fir::LLVMPointerType>>(*getContext());
fir::LLVMPointerType::attachInterface<
OpenACCPointerLikeModel<fir::LLVMPointerType>>(*getContext());
}
|