Debian Codegraph @

flang/lib/Optimizer/Dialect/FIRType.cpp

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