Debian Codegraph @

flang/lib/Optimizer/CodeGen/TypeConverter.cpp

raw
1 //===-- TypeConverter.cpp -- type conversion --------------------*- C++ -*-===//
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 #define DEBUG_TYPE "flang-type-conversion"
14
15 #include "flang/Optimizer/CodeGen/TypeConverter.h"
16 #include "flang/Common/Fortran.h"
17 #include "flang/Optimizer/Builder/Todo.h" // remove when TODO's are done
18 #include "flang/Optimizer/CodeGen/DescriptorModel.h"
19 #include "flang/Optimizer/CodeGen/TBAABuilder.h"
20 #include "flang/Optimizer/CodeGen/Target.h"
21 #include "flang/Optimizer/Dialect/FIRType.h"
22 #include "flang/Optimizer/Dialect/Support/FIRContext.h"
23 #include "flang/Optimizer/Dialect/Support/KindMapping.h"
24 #include "flang/Optimizer/Support/InternalNames.h"
25 #include "mlir/Conversion/LLVMCommon/TypeConverter.h"
26 #include "llvm/ADT/ScopeExit.h"
27 #include "llvm/Support/Debug.h"
28
29 namespace fir {
30
31 LLVMTypeConverter::LLVMTypeConverter(mlir::ModuleOp module, bool applyTBAA,
32 bool forceUnifiedTBAATree,
33 const mlir::DataLayout &dl)
34 : mlir::LLVMTypeConverter(module.getContext()),
35 kindMapping(getKindMapping(module)),
36 specifics(CodeGenSpecifics::get(
37 module.getContext(), getTargetTriple(module), getKindMapping(module),
38 getTargetCPU(module), getTargetFeatures(module), dl,
39 getTuneCPU(module))),
40 tbaaBuilder(std::make_unique<TBAABuilder>(module->getContext(), applyTBAA,
41 forceUnifiedTBAATree)),
42 dataLayout{&dl} {
43 LLVM_DEBUG(llvm::dbgs() << "FIR type converter\n");
44
45 // Each conversion should return a value of type mlir::Type.
46 addConversion([&](BoxType box) { return convertBoxType(box); });
47 addConversion([&](BoxCharType boxchar) {
48 LLVM_DEBUG(llvm::dbgs() << "type convert: " << boxchar << '\n');
49 return convertType(specifics->boxcharMemoryType(boxchar.getEleTy()));
50 });
51 addConversion([&](BoxProcType boxproc) {
52 // TODO: Support for this type will be added later when the Fortran 2003
53 // procedure pointer feature is implemented.
54 return std::nullopt;
55 });
56 addConversion(
57 [&](fir::ClassType classTy) { return convertBoxType(classTy); });
58 addConversion(
59 [&](fir::CharacterType charTy) { return convertCharType(charTy); });
60 addConversion(
61 [&](fir::ComplexType cmplx) { return convertComplexType(cmplx); });
62 addConversion([&](fir::FieldType field) {
63 // Convert to i32 because of LLVM GEP indexing restriction.
64 return mlir::IntegerType::get(field.getContext(), 32);
65 });
66 addConversion([&](HeapType heap) { return convertPointerLike(heap); });
67 addConversion([&](fir::IntegerType intTy) {
68 return mlir::IntegerType::get(
69 &getContext(), kindMapping.getIntegerBitsize(intTy.getFKind()));
70 });
71 addConversion([&](fir::LenType field) {
72 // Get size of len paramter from the descriptor.
73 return getModel<Fortran::runtime::typeInfo::TypeParameterValue>()(
74 &getContext());
75 });
76 addConversion([&](fir::LogicalType boolTy) {
77 return mlir::IntegerType::get(
78 &getContext(), kindMapping.getLogicalBitsize(boolTy.getFKind()));
79 });
80 addConversion([&](fir::LLVMPointerType pointer) {
81 return convertPointerLike(pointer);
82 });
83 addConversion(
84 [&](fir::PointerType pointer) { return convertPointerLike(pointer); });
85 addConversion(
86 [&](fir::RecordType derived, llvm::SmallVectorImpl<mlir::Type> &results) {
87 return convertRecordType(derived, results);
88 });
89 addConversion(
90 [&](fir::RealType real) { return convertRealType(real.getFKind()); });
91 addConversion(
92 [&](fir::ReferenceType ref) { return convertPointerLike(ref); });
93 addConversion([&](fir::SequenceType sequence) {
94 return convertSequenceType(sequence);
95 });
96 addConversion([&](fir::TypeDescType tdesc) {
97 return convertTypeDescType(tdesc.getContext());
98 });
99 addConversion([&](fir::VectorType vecTy) {
100 return mlir::VectorType::get(llvm::ArrayRef<int64_t>(vecTy.getLen()),
101 convertType(vecTy.getEleTy()));
102 });
103 addConversion([&](mlir::TupleType tuple) {
104 LLVM_DEBUG(llvm::dbgs() << "type convert: " << tuple << '\n');
105 llvm::SmallVector<mlir::Type> members;
106 for (auto mem : tuple.getTypes()) {
107 // Prevent fir.box from degenerating to a pointer to a descriptor in the
108 // context of a tuple type.
109 if (auto box = mlir::dyn_cast<fir::BaseBoxType>(mem))
110 members.push_back(convertBoxTypeAsStruct(box));
111 else
112 members.push_back(mlir::cast<mlir::Type>(convertType(mem)));
113 }
114 return mlir::LLVM::LLVMStructType::getLiteral(&getContext(), members,
115 /*isPacked=*/false);
116 });
117 addConversion([&](mlir::NoneType none) {
118 return mlir::LLVM::LLVMStructType::getLiteral(
119 none.getContext(), std::nullopt, /*isPacked=*/false);
120 });
121 addConversion([&](fir::DummyScopeType dscope) {
122 // DummyScopeType values must not have any uses after PreCGRewrite.
123 // Convert it here to i1 just in case it survives.
124 return mlir::IntegerType::get(&getContext(), 1);
125 });
126 }
127
128 // i32 is used here because LLVM wants i32 constants when indexing into struct
129 // types. Indexing into other aggregate types is more flexible.
130 mlir::Type LLVMTypeConverter::offsetType() const {
131 return mlir::IntegerType::get(&getContext(), 32);
132 }
133
134 // i64 can be used to index into aggregates like arrays
135 mlir::Type LLVMTypeConverter::indexType() const {
136 return mlir::IntegerType::get(&getContext(), 64);
137 }
138
139 // fir.type<name(p : TY'...){f : TY...}> --> llvm<"%name = { ty... }">
140 std::optional<llvm::LogicalResult> LLVMTypeConverter::convertRecordType(
141 fir::RecordType derived, llvm::SmallVectorImpl<mlir::Type> &results) {
142 auto name = fir::NameUniquer::dropTypeConversionMarkers(derived.getName());
143 auto st = mlir::LLVM::LLVMStructType::getIdentified(&getContext(), name);
144
145 auto &callStack = getCurrentThreadRecursiveStack();
146 if (llvm::count(callStack, derived)) {
147 results.push_back(st);
148 return mlir::success();
149 }
150 callStack.push_back(derived);
151 auto popConversionCallStack =
152 llvm::make_scope_exit([&callStack]() { callStack.pop_back(); });
153
154 llvm::SmallVector<mlir::Type> members;
155 for (auto mem : derived.getTypeList()) {
156 // Prevent fir.box from degenerating to a pointer to a descriptor in the
157 // context of a record type.
158 if (auto box = mlir::dyn_cast<fir::BaseBoxType>(mem.second))
159 members.push_back(convertBoxTypeAsStruct(box));
160 else
161 members.push_back(mlir::cast<mlir::Type>(convertType(mem.second)));
162 }
163 if (mlir::failed(st.setBody(members, /*isPacked=*/false)))
164 return mlir::failure();
165 results.push_back(st);
166 return mlir::success();
167 }
168
169 // Is an extended descriptor needed given the element type of a fir.box type ?
170 // Extended descriptors are required for derived types.
171 bool LLVMTypeConverter::requiresExtendedDesc(mlir::Type boxElementType) const {
172 auto eleTy = fir::unwrapSequenceType(boxElementType);
173 return mlir::isa<fir::RecordType>(eleTy);
174 }
175
176 // This corresponds to the descriptor as defined in ISO_Fortran_binding.h and
177 // the addendum defined in descriptor.h.
178 mlir::Type LLVMTypeConverter::convertBoxTypeAsStruct(BaseBoxType box,
179 int rank) const {
180 // (base_addr*, elem_len, version, rank, type, attribute, f18Addendum, [dim]
181 llvm::SmallVector<mlir::Type> dataDescFields;
182 mlir::Type ele = box.getEleTy();
183 // remove fir.heap/fir.ref/fir.ptr
184 if (auto removeIndirection = fir::dyn_cast_ptrEleTy(ele))
185 ele = removeIndirection;
186 auto eleTy = convertType(ele);
187 // base_addr*
188 if (mlir::isa<SequenceType>(ele) &&
189 mlir::isa<mlir::LLVM::LLVMPointerType>(eleTy))
190 dataDescFields.push_back(eleTy);
191 else
192 dataDescFields.push_back(
193 mlir::LLVM::LLVMPointerType::get(eleTy.getContext()));
194 // elem_len
195 dataDescFields.push_back(
196 getDescFieldTypeModel<kElemLenPosInBox>()(&getContext()));
197 // version
198 dataDescFields.push_back(
199 getDescFieldTypeModel<kVersionPosInBox>()(&getContext()));
200 // rank
201 dataDescFields.push_back(
202 getDescFieldTypeModel<kRankPosInBox>()(&getContext()));
203 // type
204 dataDescFields.push_back(
205 getDescFieldTypeModel<kTypePosInBox>()(&getContext()));
206 // attribute
207 dataDescFields.push_back(
208 getDescFieldTypeModel<kAttributePosInBox>()(&getContext()));
209 // f18Addendum
210 dataDescFields.push_back(
211 getDescFieldTypeModel<kF18AddendumPosInBox>()(&getContext()));
212 // [dims]
213 if (rank == unknownRank()) {
214 if (auto seqTy = mlir::dyn_cast<SequenceType>(ele))
215 if (seqTy.hasUnknownShape())
216 rank = Fortran::common::maxRank;
217 else
218 rank = seqTy.getDimension();
219 else
220 rank = 0;
221 }
222 if (rank > 0) {
223 auto rowTy = getDescFieldTypeModel<kDimsPosInBox>()(&getContext());
224 dataDescFields.push_back(mlir::LLVM::LLVMArrayType::get(rowTy, rank));
225 }
226 // opt-type-ptr: i8* (see fir.tdesc)
227 if (requiresExtendedDesc(ele) || fir::isUnlimitedPolymorphicType(box)) {
228 dataDescFields.push_back(
229 getExtendedDescFieldTypeModel<kOptTypePtrPosInBox>()(&getContext()));
230 auto rowTy =
231 getExtendedDescFieldTypeModel<kOptRowTypePosInBox>()(&getContext());
232 dataDescFields.push_back(mlir::LLVM::LLVMArrayType::get(rowTy, 1));
233 if (auto recTy =
234 mlir::dyn_cast<fir::RecordType>(fir::unwrapSequenceType(ele)))
235 if (recTy.getNumLenParams() > 0) {
236 // The descriptor design needs to be clarified regarding the number of
237 // length parameters in the addendum. Since it can change for
238 // polymorphic allocatables, it seems all length parameters cannot
239 // always possibly be placed in the addendum.
240 TODO_NOLOC("extended descriptor derived with length parameters");
241 unsigned numLenParams = recTy.getNumLenParams();
242 dataDescFields.push_back(
243 mlir::LLVM::LLVMArrayType::get(rowTy, numLenParams));
244 }
245 }
246 return mlir::LLVM::LLVMStructType::getLiteral(&getContext(), dataDescFields,
247 /*isPacked=*/false);
248 }
249
250 /// Convert fir.box type to the corresponding llvm struct type instead of a
251 /// pointer to this struct type.
252 mlir::Type LLVMTypeConverter::convertBoxType(BaseBoxType box, int rank) const {
253 // TODO: send the box type and the converted LLVM structure layout
254 // to tbaaBuilder for proper creation of TBAATypeDescriptorOp.
255 return mlir::LLVM::LLVMPointerType::get(box.getContext());
256 }
257
258 // fir.boxproc<any> --> llvm<"{ any*, i8* }">
259 mlir::Type LLVMTypeConverter::convertBoxProcType(BoxProcType boxproc) const {
260 auto funcTy = convertType(boxproc.getEleTy());
261 auto voidPtrTy = mlir::LLVM::LLVMPointerType::get(boxproc.getContext());
262 llvm::SmallVector<mlir::Type, 2> tuple = {funcTy, voidPtrTy};
263 return mlir::LLVM::LLVMStructType::getLiteral(boxproc.getContext(), tuple,
264 /*isPacked=*/false);
265 }
266
267 unsigned LLVMTypeConverter::characterBitsize(fir::CharacterType charTy) const {
268 return kindMapping.getCharacterBitsize(charTy.getFKind());
269 }
270
271 // fir.char<k,?> --> llvm<"ix"> where ix is scaled by kind mapping
272 // fir.char<k,n> --> llvm.array<n x "ix">
273 mlir::Type LLVMTypeConverter::convertCharType(fir::CharacterType charTy) const {
274 auto iTy = mlir::IntegerType::get(&getContext(), characterBitsize(charTy));
275 if (charTy.getLen() == fir::CharacterType::unknownLen())
276 return iTy;
277 return mlir::LLVM::LLVMArrayType::get(iTy, charTy.getLen());
278 }
279
280 // convert a front-end kind value to either a std or LLVM IR dialect type
281 // fir.real<n> --> llvm.anyfloat where anyfloat is a kind mapping
282 mlir::Type LLVMTypeConverter::convertRealType(fir::KindTy kind) const {
283 return fir::fromRealTypeID(&getContext(), kindMapping.getRealTypeID(kind),
284 kind);
285 }
286
287 // fir.array<c ... :any> --> llvm<"[...[c x any]]">
288 mlir::Type LLVMTypeConverter::convertSequenceType(SequenceType seq) const {
289 auto baseTy = convertType(seq.getEleTy());
290 if (characterWithDynamicLen(seq.getEleTy()))
291 return baseTy;
292 auto shape = seq.getShape();
293 auto constRows = seq.getConstantRows();
294 if (constRows) {
295 decltype(constRows) i = constRows;
296 for (auto e : shape) {
297 baseTy = mlir::LLVM::LLVMArrayType::get(baseTy, e);
298 if (--i == 0)
299 break;
300 }
301 if (!seq.hasDynamicExtents())
302 return baseTy;
303 }
304 return baseTy;
305 }
306
307 // fir.tdesc<any> --> llvm<"i8*">
308 // TODO: For now use a void*, however pointer identity is not sufficient for
309 // the f18 object v. class distinction (F2003).
310 mlir::Type
311 LLVMTypeConverter::convertTypeDescType(mlir::MLIRContext *ctx) const {
312 return mlir::LLVM::LLVMPointerType::get(ctx);
313 }
314
315 // Relay TBAA tag attachment to TBAABuilder.
316 void LLVMTypeConverter::attachTBAATag(mlir::LLVM::AliasAnalysisOpInterface op,
317 mlir::Type baseFIRType,
318 mlir::Type accessFIRType,
319 mlir::LLVM::GEPOp gep) const {
320 tbaaBuilder->attachTBAATag(op, baseFIRType, accessFIRType, gep);
321 }
322
323 } // namespace fir