Debian Codegraph @

llvm-project/flang/lib/Optimizer/HLFIR/Transforms/ConvertToFIR.cpp

raw
1 //===- ConvertToFIR.cpp - Convert HLFIR to FIR ----------------------------===//
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 // This file defines a pass to lower HLFIR to FIR
9 //===----------------------------------------------------------------------===//
10
11 #include "flang/Optimizer/Builder/Character.h"
12 #include "flang/Optimizer/Builder/FIRBuilder.h"
13 #include "flang/Optimizer/Builder/HLFIRTools.h"
14 #include "flang/Optimizer/Builder/MutableBox.h"
15 #include "flang/Optimizer/Builder/Runtime/Assign.h"
16 #include "flang/Optimizer/Builder/Todo.h"
17 #include "flang/Optimizer/Dialect/FIRDialect.h"
18 #include "flang/Optimizer/Dialect/FIROps.h"
19 #include "flang/Optimizer/Dialect/FIRType.h"
20 #include "flang/Optimizer/HLFIR/HLFIROps.h"
21 #include "flang/Optimizer/HLFIR/Passes.h"
22 #include "flang/Optimizer/Support/FIRContext.h"
23 #include "mlir/Transforms/DialectConversion.h"
24
25 namespace hlfir {
26 #define GEN_PASS_DEF_CONVERTHLFIRTOFIR
27 #include "flang/Optimizer/HLFIR/Passes.h.inc"
28 } // namespace hlfir
29
30 using namespace mlir;
31
32 namespace {
33 /// May \p lhs alias with \p rhs?
34 /// TODO: implement HLFIR alias analysis.
35 static bool mayAlias(hlfir::Entity lhs, hlfir::Entity rhs) { return true; }
36
37 class AssignOpConversion : public mlir::OpRewritePattern<hlfir::AssignOp> {
38 public:
39 explicit AssignOpConversion(mlir::MLIRContext *ctx) : OpRewritePattern{ctx} {}
40
41 mlir::LogicalResult
42 matchAndRewrite(hlfir::AssignOp assignOp,
43 mlir::PatternRewriter &rewriter) const override {
44 mlir::Location loc = assignOp->getLoc();
45 hlfir::Entity lhs(assignOp.getLhs());
46 hlfir::Entity rhs(assignOp.getRhs());
47 auto module = assignOp->getParentOfType<mlir::ModuleOp>();
48 fir::FirOpBuilder builder(rewriter, fir::getKindMapping(module));
49
50 if (rhs.getType().isa<hlfir::ExprType>()) {
51 mlir::emitError(loc, "hlfir must be bufferized with --bufferize-hlfir "
52 "pass before being converted to FIR");
53 return mlir::failure();
54 }
55 auto [rhsExv, rhsCleanUp] =
56 hlfir::translateToExtendedValue(loc, builder, rhs);
57 auto [lhsExv, lhsCleanUp] =
58 hlfir::translateToExtendedValue(loc, builder, lhs);
59 assert(!lhsCleanUp && !rhsCleanUp &&
60 "variable to fir::ExtendedValue must not require cleanup");
61
62 if (lhs.isArray()) {
63 // Use the runtime for simplicity. An optimization pass will be added to
64 // inline array assignment when profitable.
65 auto to = fir::getBase(builder.createBox(loc, lhsExv));
66 auto from = fir::getBase(builder.createBox(loc, rhsExv));
67 bool cleanUpTemp = false;
68 mlir::Type fromHeapType = fir::HeapType::get(
69 fir::unwrapRefType(from.getType().cast<fir::BoxType>().getEleTy()));
70 if (mayAlias(rhs, lhs)) {
71 /// Use the runtime to make a quick and dirty temp with the rhs value.
72 /// Overkill for scalar rhs that could be done in much more clever ways.
73 /// Note that temp descriptor must have the allocatable flag set so that
74 /// the runtime will allocate it with the shape and type parameters of
75 // the RHS.
76 mlir::Type fromBoxHeapType = fir::BoxType::get(fromHeapType);
77 auto fromMutableBox = builder.createTemporary(loc, fromBoxHeapType);
78 mlir::Value unallocatedBox = fir::factory::createUnallocatedBox(
79 builder, loc, fromBoxHeapType, {});
80 builder.create<fir::StoreOp>(loc, unallocatedBox, fromMutableBox);
81 fir::runtime::genAssign(builder, loc, fromMutableBox, from);
82 cleanUpTemp = true;
83 from = builder.create<fir::LoadOp>(loc, fromMutableBox);
84 }
85 auto toMutableBox = builder.createTemporary(loc, to.getType());
86 // As per 10.2.1.2 point 1 (1) polymorphic variables must be allocatable.
87 // It is assumed here that they have been reallocated with the dynamic
88 // type and that the mutableBox will not be modified.
89 builder.create<fir::StoreOp>(loc, to, toMutableBox);
90 fir::runtime::genAssign(builder, loc, toMutableBox, from);
91 if (cleanUpTemp) {
92 mlir::Value addr =
93 builder.create<fir::BoxAddrOp>(loc, fromHeapType, from);
94 builder.create<fir::FreeMemOp>(loc, addr);
95 }
96 } else {
97 // Assume overlap does not matter for scalar (dealt with memmove for
98 // characters).
99 // This is not true if this is a derived type with "recursive" allocatable
100 // components, in which case an overlap would matter because the LHS
101 // reallocation, if any, may modify the RHS component value before it is
102 // copied into the LHS.
103 if (fir::isRecordWithAllocatableMember(lhs.getFortranElementType()))
104 TODO(loc, "assignment with allocatable components");
105 fir::factory::genScalarAssignment(builder, loc, lhsExv, rhsExv);
106 }
107 rewriter.eraseOp(assignOp);
108 return mlir::success();
109 }
110 };
111
112 class DeclareOpConversion : public mlir::OpRewritePattern<hlfir::DeclareOp> {
113 public:
114 explicit DeclareOpConversion(mlir::MLIRContext *ctx)
115 : OpRewritePattern{ctx} {}
116
117 mlir::LogicalResult
118 matchAndRewrite(hlfir::DeclareOp declareOp,
119 mlir::PatternRewriter &rewriter) const override {
120 mlir::Location loc = declareOp->getLoc();
121 mlir::Value memref = declareOp.getMemref();
122 fir::FortranVariableFlagsAttr fortranAttrs;
123 if (auto attrs = declareOp.getFortranAttrs())
124 fortranAttrs =
125 fir::FortranVariableFlagsAttr::get(rewriter.getContext(), *attrs);
126 auto firBase = rewriter
127 .create<fir::DeclareOp>(
128 loc, memref.getType(), memref, declareOp.getShape(),
129 declareOp.getTypeparams(), declareOp.getUniqName(),
130 fortranAttrs)
131 .getResult();
132 mlir::Value hlfirBase;
133 mlir::Type hlfirBaseType = declareOp.getBase().getType();
134 if (hlfirBaseType.isa<fir::BaseBoxType>()) {
135 // Need to conditionally rebox/embox for optional.
136 if (mlir::cast<fir::FortranVariableOpInterface>(declareOp.getOperation())
137 .isOptional())
138 TODO(loc, "converting hlfir declare of optional box to fir");
139 if (!firBase.getType().isa<fir::BaseBoxType>()) {
140 llvm::SmallVector<mlir::Value> typeParams;
141 auto maybeCharType =
142 fir::unwrapSequenceType(fir::unwrapPassByRefType(hlfirBaseType))
143 .dyn_cast<fir::CharacterType>();
144 if (!maybeCharType || maybeCharType.hasDynamicLen())
145 typeParams.append(declareOp.getTypeparams().begin(),
146 declareOp.getTypeparams().end());
147 hlfirBase = rewriter.create<fir::EmboxOp>(
148 loc, hlfirBaseType, firBase, declareOp.getShape(),
149 /*slice=*/mlir::Value{}, typeParams);
150 } else {
151 // Rebox so that lower bounds are correct.
152 hlfirBase = rewriter.create<fir::ReboxOp>(loc, hlfirBaseType, firBase,
153 declareOp.getShape(),
154 /*slice=*/mlir::Value{});
155 }
156 } else if (hlfirBaseType.isa<fir::BoxCharType>()) {
157 assert(declareOp.getTypeparams().size() == 1 &&
158 "must contain character length");
159 hlfirBase = rewriter.create<fir::EmboxCharOp>(
160 loc, hlfirBaseType, firBase, declareOp.getTypeparams()[0]);
161 } else {
162 if (hlfirBaseType != firBase.getType()) {
163 declareOp.emitOpError()
164 << "unhandled HLFIR variable type '" << hlfirBaseType << "'\n";
165 return mlir::failure();
166 }
167 hlfirBase = firBase;
168 }
169 rewriter.replaceOp(declareOp, {hlfirBase, firBase});
170 return mlir::success();
171 }
172 };
173
174 class DesignateOpConversion
175 : public mlir::OpRewritePattern<hlfir::DesignateOp> {
176 public:
177 explicit DesignateOpConversion(mlir::MLIRContext *ctx)
178 : OpRewritePattern{ctx} {}
179
180 mlir::LogicalResult
181 matchAndRewrite(hlfir::DesignateOp designate,
182 mlir::PatternRewriter &rewriter) const override {
183 mlir::Location loc = designate.getLoc();
184 auto module = designate->getParentOfType<mlir::ModuleOp>();
185 fir::FirOpBuilder builder(rewriter, fir::getKindMapping(module));
186
187 if (designate.getComplexPart())
188 TODO(loc, "hlfir::designate with complex part");
189
190 hlfir::Entity baseEntity(designate.getMemref());
191
192 if (baseEntity.isMutableBox())
193 TODO(loc, "hlfir::designate load of pointer or allocatable");
194
195 mlir::Type designateResultType = designate.getResult().getType();
196 llvm::SmallVector<mlir::Value> firBaseTypeParameters;
197 auto [base, shape] = hlfir::genVariableFirBaseShapeAndParams(
198 loc, builder, baseEntity, firBaseTypeParameters);
199 mlir::Type baseEleTy = hlfir::getFortranElementType(base.getType());
200
201 mlir::Value fieldIndex;
202 if (designate.getComponent()) {
203 mlir::Type baseRecordType = baseEntity.getFortranElementType();
204 if (fir::isRecordWithTypeParameters(baseRecordType))
205 TODO(loc, "hlfir.designate with a parametrized derived type base");
206 fieldIndex = builder.create<fir::FieldIndexOp>(
207 loc, fir::FieldType::get(builder.getContext()),
208 designate.getComponent().value(), baseRecordType,
209 /*typeParams=*/mlir::ValueRange{});
210 if (baseEntity.isScalar()) {
211 // Component refs of scalar base right away:
212 // - scalar%scalar_component [substring|complex_part] or
213 // - scalar%static_size_array_comp
214 // - scalar%array(indices) [substring| complex part]
215 mlir::Type componentType = baseEleTy.cast<fir::RecordType>().getType(
216 designate.getComponent().value());
217 mlir::Type coorTy = fir::ReferenceType::get(componentType);
218 base = builder.create<fir::CoordinateOp>(loc, coorTy, base, fieldIndex);
219 if (componentType.isa<fir::BaseBoxType>()) {
220 auto variableInterface = mlir::cast<fir::FortranVariableOpInterface>(
221 designate.getOperation());
222 if (variableInterface.isAllocatable() ||
223 variableInterface.isPointer()) {
224 rewriter.replaceOp(designate, base);
225 return mlir::success();
226 }
227 TODO(loc,
228 "addressing parametrized derived type automatic components");
229 }
230 baseEleTy = hlfir::getFortranElementType(componentType);
231 shape = designate.getComponentShape();
232 } else {
233 // array%component[(indices) substring|complex part] cases.
234 // Component ref of array bases are dealt with below in embox/rebox.
235 assert(designateResultType.isa<fir::BaseBoxType>());
236 }
237 }
238
239 if (designateResultType.isa<fir::BaseBoxType>()) {
240 // Generate embox or rebox.
241 if (!fir::unwrapPassByRefType(designateResultType)
242 .isa<fir::SequenceType>())
243 TODO(loc, "addressing polymorphic arrays");
244 llvm::SmallVector<mlir::Value> triples;
245 llvm::SmallVector<mlir::Value> sliceFields;
246 mlir::Type idxTy = builder.getIndexType();
247 auto subscripts = designate.getIndices();
248 if (fieldIndex && baseEntity.isArray()) {
249 // array%scalar_comp or array%array_comp(indices)
250 // Generate triples for array(:, :, ...).
251 auto one = builder.createIntegerConstant(loc, idxTy, 1);
252 for (auto [lb, ub] : hlfir::genBounds(loc, builder, baseEntity)) {
253 triples.push_back(builder.createConvert(loc, idxTy, lb));
254 triples.push_back(builder.createConvert(loc, idxTy, ub));
255 triples.push_back(one);
256 }
257 sliceFields.push_back(fieldIndex);
258 // Add indices in the field path for "array%array_comp(indices)"
259 // case.
260 sliceFields.append(subscripts.begin(), subscripts.end());
261 } else {
262 // Otherwise, this is an array section with triplets.
263 auto undef = builder.create<fir::UndefOp>(loc, idxTy);
264 unsigned i = 0;
265 for (auto isTriplet : designate.getIsTriplet()) {
266 triples.push_back(subscripts[i++]);
267 if (isTriplet) {
268 triples.push_back(subscripts[i++]);
269 triples.push_back(subscripts[i++]);
270 } else {
271 triples.push_back(undef);
272 triples.push_back(undef);
273 }
274 }
275 }
276 llvm::SmallVector<mlir::Value, 2> substring;
277 if (!designate.getSubstring().empty()) {
278 substring.push_back(designate.getSubstring()[0]);
279 mlir::Type idxTy = builder.getIndexType();
280 // fir.slice op substring expects the zero based lower bound.
281 mlir::Value one = builder.createIntegerConstant(loc, idxTy, 1);
282 substring[0] = builder.createConvert(loc, idxTy, substring[0]);
283 substring[0] =
284 builder.create<mlir::arith::SubIOp>(loc, substring[0], one);
285 substring.push_back(designate.getTypeparams()[0]);
286 }
287
288 mlir::Value slice;
289 if (!triples.empty())
290 slice =
291 builder.create<fir::SliceOp>(loc, triples, sliceFields, substring);
292 else
293 assert(sliceFields.empty() && substring.empty());
294 llvm::SmallVector<mlir::Type> resultType{designateResultType};
295 mlir::Value resultBox;
296 if (base.getType().isa<fir::BaseBoxType>())
297 resultBox =
298 builder.create<fir::ReboxOp>(loc, resultType, base, shape, slice);
299 else
300 resultBox = builder.create<fir::EmboxOp>(loc, resultType, base, shape,
301 slice, firBaseTypeParameters);
302 rewriter.replaceOp(designate, resultBox);
303 return mlir::success();
304 }
305
306 // Otherwise, the result is the address of a scalar, or the address of the
307 // first element of a contiguous array section with compile time constant
308 // shape. The base may be an array, or a scalar.
309 mlir::Type resultAddressType = designateResultType;
310 if (auto boxCharType = designateResultType.dyn_cast<fir::BoxCharType>())
311 resultAddressType = fir::ReferenceType::get(boxCharType.getEleTy());
312
313 // Array element indexing.
314 if (!designate.getIndices().empty()) {
315 // - array(indices) [substring|complex_part] or
316 // - scalar%array_comp(indices) [substring|complex_part]
317 // This may be a ranked contiguous array section in which case
318 // The first element address is being computed.
319 llvm::SmallVector<mlir::Value> firstElementIndices;
320 auto indices = designate.getIndices();
321 int i = 0;
322 for (auto isTriplet : designate.getIsTripletAttr().asArrayRef()) {
323 // Coordinate of the first element are the index and triplets lower
324 // bounds
325 firstElementIndices.push_back(indices[i]);
326 i = i + (isTriplet ? 3 : 1);
327 }
328 mlir::Type arrayCoorType = fir::ReferenceType::get(baseEleTy);
329 base = builder.create<fir::ArrayCoorOp>(
330 loc, arrayCoorType, base, shape,
331 /*slice=*/mlir::Value{}, firstElementIndices, firBaseTypeParameters);
332 }
333
334 // Scalar substring (potentially on the previously built array element or
335 // component reference).
336 if (!designate.getSubstring().empty())
337 base = fir::factory::CharacterExprHelper{builder, loc}.genSubstringBase(
338 base, designate.getSubstring()[0], resultAddressType);
339
340 // Cast/embox the computed scalar address if needed.
341 if (designateResultType.isa<fir::BoxCharType>()) {
342 assert(designate.getTypeparams().size() == 1 &&
343 "must have character length");
344 auto emboxChar = builder.create<fir::EmboxCharOp>(
345 loc, designateResultType, base, designate.getTypeparams()[0]);
346 rewriter.replaceOp(designate, emboxChar.getResult());
347 } else {
348 base = builder.createConvert(loc, designateResultType, base);
349 rewriter.replaceOp(designate, base);
350 }
351 return mlir::success();
352 }
353 };
354
355 class NoReassocOpConversion
356 : public mlir::OpRewritePattern<hlfir::NoReassocOp> {
357 public:
358 explicit NoReassocOpConversion(mlir::MLIRContext *ctx)
359 : OpRewritePattern{ctx} {}
360
361 mlir::LogicalResult
362 matchAndRewrite(hlfir::NoReassocOp noreassoc,
363 mlir::PatternRewriter &rewriter) const override {
364 rewriter.replaceOpWithNewOp<fir::NoReassocOp>(noreassoc,
365 noreassoc.getVal());
366 return mlir::success();
367 }
368 };
369
370 class NullOpConversion : public mlir::OpRewritePattern<hlfir::NullOp> {
371 public:
372 explicit NullOpConversion(mlir::MLIRContext *ctx) : OpRewritePattern{ctx} {}
373
374 mlir::LogicalResult
375 matchAndRewrite(hlfir::NullOp nullop,
376 mlir::PatternRewriter &rewriter) const override {
377 rewriter.replaceOpWithNewOp<fir::ZeroOp>(nullop, nullop.getType());
378 return mlir::success();
379 }
380 };
381
382 class ConvertHLFIRtoFIR
383 : public hlfir::impl::ConvertHLFIRtoFIRBase<ConvertHLFIRtoFIR> {
384 public:
385 void runOnOperation() override {
386 // TODO: like "bufferize-hlfir" pass, runtime signature may be added
387 // by this pass. This requires the pass to run on the ModuleOp. It would
388 // probably be more optimal to have it run on FuncOp and find a way to
389 // generate the signatures in a thread safe way.
390 auto module = this->getOperation();
391 auto *context = &getContext();
392 mlir::RewritePatternSet patterns(context);
393 patterns
394 .insert<AssignOpConversion, DeclareOpConversion, DesignateOpConversion,
395 NoReassocOpConversion, NullOpConversion>(context);
396 mlir::ConversionTarget target(*context);
397 target.addIllegalDialect<hlfir::hlfirDialect>();
398 target.markUnknownOpDynamicallyLegal(
399 [](mlir::Operation *) { return true; });
400 if (mlir::failed(mlir::applyPartialConversion(module, target,
401 std::move(patterns)))) {
402 mlir::emitError(mlir::UnknownLoc::get(context),
403 "failure in HLFIR to FIR conversion pass");
404 signalPassFailure();
405 }
406 }
407 };
408 } // namespace
409
410 std::unique_ptr<mlir::Pass> hlfir::createConvertHLFIRtoFIRPass() {
411 return std::make_unique<ConvertHLFIRtoFIR>();
412 }