FLANG
DirectivesCommon.h
1//===-- DirectivesCommon.h --------------------------------------*- 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//===----------------------------------------------------------------------===//
15//===----------------------------------------------------------------------===//
16
17#ifndef FORTRAN_OPTIMIZER_BUILDER_DIRECTIVESCOMMON_H_
18#define FORTRAN_OPTIMIZER_BUILDER_DIRECTIVESCOMMON_H_
19
20#include "BoxValue.h"
21#include "FIRBuilder.h"
22#include "flang/Optimizer/Builder/BoxValue.h"
23#include "flang/Optimizer/Builder/FIRBuilder.h"
24#include "flang/Optimizer/Builder/Todo.h"
25#include "flang/Optimizer/HLFIR/HLFIROps.h"
26
27namespace fir::factory {
28
31struct AddrAndBoundsInfo {
32 explicit AddrAndBoundsInfo() {}
33 explicit AddrAndBoundsInfo(mlir::Value addr, mlir::Value rawInput)
34 : addr(addr), rawInput(rawInput) {}
35 explicit AddrAndBoundsInfo(mlir::Value addr, mlir::Value rawInput,
36 mlir::Value isPresent)
37 : addr(addr), rawInput(rawInput), isPresent(isPresent) {}
38 explicit AddrAndBoundsInfo(mlir::Value addr, mlir::Value rawInput,
39 mlir::Value isPresent, mlir::Type boxType)
40 : addr(addr), rawInput(rawInput), isPresent(isPresent), boxType(boxType) {
41 }
42 mlir::Value addr = nullptr;
43 mlir::Value rawInput = nullptr;
44 mlir::Value isPresent = nullptr;
45 mlir::Type boxType = nullptr;
46 void dump(llvm::raw_ostream &os) {
47 os << "AddrAndBoundsInfo addr: " << addr << "\n";
48 os << "AddrAndBoundsInfo rawInput: " << rawInput << "\n";
49 os << "AddrAndBoundsInfo isPresent: " << isPresent << "\n";
50 os << "AddrAndBoundsInfo boxType: " << boxType << "\n";
51 }
52};
53
54inline AddrAndBoundsInfo getDataOperandBaseAddr(fir::FirOpBuilder &builder,
55 mlir::Value symAddr,
56 bool isOptional,
57 mlir::Location loc,
58 bool unwrapFirBox = true) {
59 mlir::Value rawInput = symAddr;
60 if (auto declareOp =
61 mlir::dyn_cast_or_null<hlfir::DeclareOp>(symAddr.getDefiningOp())) {
62 symAddr = declareOp.getResults()[0];
63 rawInput = declareOp.getResults()[1];
64 }
65
66 if (!symAddr)
67 llvm::report_fatal_error("could not retrieve symbol address");
68
69 mlir::Value isPresent;
70 if (isOptional)
71 isPresent =
72 fir::IsPresentOp::create(builder, loc, builder.getI1Type(), rawInput);
73
74 if (auto boxTy = mlir::dyn_cast<fir::BaseBoxType>(
75 fir::unwrapRefType(symAddr.getType()))) {
76 // In case of a box reference, load it here to get the box value.
77 // This is preferrable because then the same box value can then be used for
78 // all address/dimension retrievals. For Fortran optional though, leave
79 // the load generation for later so it can be done in the appropriate
80 // if branches.
81 if (unwrapFirBox && mlir::isa<fir::ReferenceType>(symAddr.getType()) &&
82 !isOptional) {
83 mlir::Value addr = fir::LoadOp::create(builder, loc, symAddr);
84 return AddrAndBoundsInfo(addr, rawInput, isPresent, boxTy);
85 }
86
87 return AddrAndBoundsInfo(symAddr, rawInput, isPresent, boxTy);
88 }
89 // For boxchar references, do the same as what is done above for box
90 // references - Load the boxchar so that it is easier to retrieve the length
91 // of the underlying character and the data pointer.
92 if (auto boxCharType = mlir::dyn_cast<fir::BoxCharType>(
93 fir::unwrapRefType((symAddr.getType())))) {
94 if (!isOptional && mlir::isa<fir::ReferenceType>(symAddr.getType())) {
95 mlir::Value boxChar = fir::LoadOp::create(builder, loc, symAddr);
96 return AddrAndBoundsInfo(boxChar, rawInput, isPresent);
97 }
98 }
99 return AddrAndBoundsInfo(symAddr, rawInput, isPresent);
100}
101
102template <typename BoundsOp, typename BoundsType>
103llvm::SmallVector<mlir::Value>
104gatherBoundsOrBoundValues(fir::FirOpBuilder &builder, mlir::Location loc,
105 fir::ExtendedValue dataExv, mlir::Value box,
106 bool collectValuesOnly = false) {
107 assert(box && "box must exist");
108 llvm::SmallVector<mlir::Value> values;
109 mlir::Value byteStride;
110 mlir::Type idxTy = builder.getIndexType();
111 mlir::Type boundTy = builder.getType<BoundsType>();
112 mlir::Value one = builder.createIntegerConstant(loc, idxTy, 1);
113 for (unsigned dim = 0; dim < dataExv.rank(); ++dim) {
114 mlir::Value d = builder.createIntegerConstant(loc, idxTy, dim);
115 mlir::Value baseLb =
116 fir::factory::readLowerBound(builder, loc, dataExv, dim, one);
117 auto dimInfo =
118 fir::BoxDimsOp::create(builder, loc, idxTy, idxTy, idxTy, box, d);
119 mlir::Value lb = builder.createIntegerConstant(loc, idxTy, 0);
120 mlir::Value ub =
121 mlir::arith::SubIOp::create(builder, loc, dimInfo.getExtent(), one);
122 if (dim == 0) // First stride is the element size.
123 byteStride = dimInfo.getByteStride();
124 if (collectValuesOnly) {
125 values.push_back(lb);
126 values.push_back(ub);
127 values.push_back(dimInfo.getExtent());
128 values.push_back(byteStride);
129 values.push_back(baseLb);
130 } else {
131 mlir::Value bound =
132 BoundsOp::create(builder, loc, boundTy, lb, ub, dimInfo.getExtent(),
133 byteStride, true, baseLb);
134 values.push_back(bound);
135 }
136 // Compute the stride for the next dimension.
137 byteStride = mlir::arith::MulIOp::create(builder, loc, byteStride,
138 dimInfo.getExtent());
139 }
140 return values;
141}
142template <typename BoundsOp, typename BoundsType>
143mlir::Value
144genBoundsOpFromBoxChar(fir::FirOpBuilder &builder, mlir::Location loc,
145 fir::ExtendedValue dataExv, AddrAndBoundsInfo &info) {
146
147 if (!mlir::isa<fir::BoxCharType>(fir::unwrapRefType(info.addr.getType())))
148 return mlir::Value{};
149
150 mlir::Type idxTy = builder.getIndexType();
151 mlir::Type lenType = builder.getCharacterLengthType();
152 mlir::Value zero = builder.createIntegerConstant(loc, idxTy, 0);
153 mlir::Value one = builder.createIntegerConstant(loc, idxTy, 1);
154 auto boxCharType =
155 mlir::cast<fir::BoxCharType>(fir::unwrapRefType(info.addr.getType()));
156 unsigned codeUnitBytes =
157 builder.getKindMap().getCharacterBitsize(boxCharType.getKind()) / 8;
158 // The extent counts character code units, but the stride is in bytes.
159 mlir::Value byteStride =
160 codeUnitBytes == 1
161 ? one
162 : builder.createIntegerConstant(loc, idxTy, codeUnitBytes);
163 using ExtentAndStride = std::tuple<mlir::Value, mlir::Value>;
164 auto [extent, stride] = [&]() -> ExtentAndStride {
165 if (info.isPresent) {
166 llvm::SmallVector<mlir::Type> resTypes = {idxTy, idxTy};
167 mlir::Operation::result_range ifRes =
168 builder
169 .genIfOp(loc, resTypes, info.isPresent, /*withElseRegion=*/true)
170 .genThen([&]() {
171 mlir::Value boxChar =
172 fir::isa_ref_type(info.addr.getType())
173 ? fir::LoadOp::create(builder, loc, info.addr)
174 : info.addr;
175 fir::BoxCharType boxCharType =
176 mlir::cast<fir::BoxCharType>(boxChar.getType());
177 mlir::Type refType = builder.getRefType(boxCharType.getEleTy());
178 auto unboxed = fir::UnboxCharOp::create(builder, loc, refType,
179 lenType, boxChar);
180 mlir::SmallVector<mlir::Value> results = {unboxed.getResult(1),
181 byteStride};
182 fir::ResultOp::create(builder, loc, results);
183 })
184 .genElse([&]() {
185 mlir::SmallVector<mlir::Value> results = {zero, zero};
186 fir::ResultOp::create(builder, loc, results);
187 })
188 .getResults();
189 return {ifRes[0], ifRes[1]};
190 }
191 // We have already established that info.addr.getType() is a boxchar
192 // or a boxchar address. If an address, load the boxchar.
193 mlir::Value boxChar = fir::isa_ref_type(info.addr.getType())
194 ? fir::LoadOp::create(builder, loc, info.addr)
195 : info.addr;
196 fir::BoxCharType boxCharType =
197 mlir::cast<fir::BoxCharType>(boxChar.getType());
198 mlir::Type refType = builder.getRefType(boxCharType.getEleTy());
199 auto unboxed =
200 fir::UnboxCharOp::create(builder, loc, refType, lenType, boxChar);
201 return {unboxed.getResult(1), byteStride};
202 }();
203
204 mlir::Value ub = mlir::arith::SubIOp::create(builder, loc, extent, one);
205 mlir::Type boundTy = builder.getType<BoundsType>();
206 return BoundsOp::create(builder, loc, boundTy,
207 /*lower_bound=*/zero,
208 /*upper_bound=*/ub,
209 /*extent=*/extent,
210 /*stride=*/stride,
211 /*stride_in_bytes=*/true,
212 /*start_idx=*/zero);
213}
214
216template <typename BoundsOp, typename BoundsType>
217llvm::SmallVector<mlir::Value>
218genBoundsOpsFromBox(fir::FirOpBuilder &builder, mlir::Location loc,
219 fir::ExtendedValue dataExv, AddrAndBoundsInfo &info) {
221 mlir::Type idxTy = builder.getIndexType();
222 mlir::Type boundTy = builder.getType<BoundsType>();
223
224 assert(mlir::isa<fir::BaseBoxType>(info.boxType) &&
225 "expect fir.box or fir.class");
226 assert(fir::unwrapRefType(info.addr.getType()) == info.boxType &&
227 "expected box type consistency");
228
229 if (info.isPresent) {
231 constexpr unsigned nbValuesPerBound = 5;
232 for (unsigned dim = 0; dim < dataExv.rank() * nbValuesPerBound; ++dim)
233 resTypes.push_back(idxTy);
234
235 mlir::Operation::result_range ifRes =
236 builder.genIfOp(loc, resTypes, info.isPresent, /*withElseRegion=*/true)
237 .genThen([&]() {
238 mlir::Value box =
239 !fir::isBoxAddress(info.addr.getType())
240 ? info.addr
241 : fir::LoadOp::create(builder, loc, info.addr);
243 gatherBoundsOrBoundValues<BoundsOp, BoundsType>(
244 builder, loc, dataExv, box,
245 /*collectValuesOnly=*/true);
246 fir::ResultOp::create(builder, loc, boundValues);
247 })
248 .genElse([&] {
249 // Box is not present. Populate bound values with default values.
251 mlir::Value zero = builder.createIntegerConstant(loc, idxTy, 0);
252 mlir::Value mOne = builder.createMinusOneInteger(loc, idxTy);
253 for (unsigned dim = 0; dim < dataExv.rank(); ++dim) {
254 boundValues.push_back(zero); // lb
255 boundValues.push_back(mOne); // ub
256 boundValues.push_back(zero); // extent
257 boundValues.push_back(zero); // byteStride
258 boundValues.push_back(zero); // baseLb
259 }
260 fir::ResultOp::create(builder, loc, boundValues);
261 })
262 .getResults();
263 // Create the bound operations outside the if-then-else with the if op
264 // results.
265 for (unsigned i = 0; i < ifRes.size(); i += nbValuesPerBound) {
266 mlir::Value bound =
267 BoundsOp::create(builder, loc, boundTy, ifRes[i], ifRes[i + 1],
268 ifRes[i + 2], ifRes[i + 3], true, ifRes[i + 4]);
269 bounds.push_back(bound);
270 }
271 } else {
272 mlir::Value box = !fir::isBoxAddress(info.addr.getType())
273 ? info.addr
274 : fir::LoadOp::create(builder, loc, info.addr);
275 bounds = gatherBoundsOrBoundValues<BoundsOp, BoundsType>(builder, loc,
276 dataExv, box);
277 }
278 return bounds;
279}
280
283template <typename BoundsOp, typename BoundsType>
285genBaseBoundsOps(fir::FirOpBuilder &builder, mlir::Location loc,
286 fir::ExtendedValue dataExv, bool isAssumedSize,
287 bool strideIncludeLowerExtent = false) {
288 mlir::Type idxTy = builder.getIndexType();
289 mlir::Type boundTy = builder.getType<BoundsType>();
291
292 if (dataExv.rank() == 0)
293 return bounds;
294
295 mlir::Value one = builder.createIntegerConstant(loc, idxTy, 1);
296 const unsigned rank = dataExv.rank();
297 mlir::Value cumulativeExtent = one;
298 for (unsigned dim = 0; dim < rank; ++dim) {
299 mlir::Value baseLb =
300 fir::factory::readLowerBound(builder, loc, dataExv, dim, one);
301 mlir::Value zero = builder.createIntegerConstant(loc, idxTy, 0);
302 mlir::Value ub;
303 mlir::Value lb = zero;
304 mlir::Value extent = fir::factory::readExtent(builder, loc, dataExv, dim);
305 if (isAssumedSize && dim + 1 == rank) {
306 extent = zero;
307 ub = lb;
308 } else {
309 // ub = extent - 1
310 ub = mlir::arith::SubIOp::create(builder, loc, extent, one);
311 }
312 mlir::Value stride = one;
313 if (strideIncludeLowerExtent) {
314 stride = cumulativeExtent;
315 cumulativeExtent = builder.createOrFold<mlir::arith::MulIOp>(
316 loc, cumulativeExtent, extent);
317 }
318
319 mlir::Value bound = BoundsOp::create(builder, loc, boundTy, lb, ub, extent,
320 stride, false, baseLb);
321 bounds.push_back(bound);
322 }
323 return bounds;
324}
325
328inline bool isOptionalArgument(mlir::Operation *op) {
329 if (auto declareOp = mlir::dyn_cast_or_null<hlfir::DeclareOp>(op))
330 if (declareOp.getFortranAttrs() &&
331 bitEnumContainsAny(*declareOp.getFortranAttrs(),
332 fir::FortranVariableFlagsEnum::optional))
333 return true;
334 return false;
335}
336
337template <typename BoundsOp, typename BoundsType>
339genImplicitBoundsOps(fir::FirOpBuilder &builder, AddrAndBoundsInfo &info,
340 fir::ExtendedValue dataExv, bool dataExvIsAssumedSize,
341 mlir::Location loc) {
343
344 mlir::Value baseOp = info.rawInput;
345 if (mlir::isa<fir::BaseBoxType>(fir::unwrapRefType(baseOp.getType())))
346 bounds =
347 genBoundsOpsFromBox<BoundsOp, BoundsType>(builder, loc, dataExv, info);
348 if (mlir::isa<fir::SequenceType>(fir::unwrapRefType(baseOp.getType()))) {
349 bounds = genBaseBoundsOps<BoundsOp, BoundsType>(builder, loc, dataExv,
350 dataExvIsAssumedSize);
351 }
352 if (characterWithDynamicLen(fir::unwrapRefType(baseOp.getType())) ||
353 mlir::isa<fir::BoxCharType>(fir::unwrapRefType(info.addr.getType()))) {
354 bounds = {genBoundsOpFromBoxChar<BoundsOp, BoundsType>(builder, loc,
355 dataExv, info)};
356 }
357 return bounds;
358}
359
360} // namespace fir::factory
361#endif // FORTRAN_OPTIMIZER_BUILDER_DIRECTIVESCOMMON_H_
Definition BoxValue.h:469
Definition FIRBuilder.h:66
IfBuilder genIfOp(mlir::Location loc, mlir::TypeRange results, mlir::Value cdt, bool withElseRegion)
Definition FIRBuilder.h:589
mlir::Type getCharacterLengthType()
Get character length type.
Definition FIRBuilder.h:174
const fir::KindMapping & getKindMap()
Get a reference to the kind map.
Definition FIRBuilder.h:133
mlir::Type getRefType(mlir::Type eleTy, bool isVolatile=false)
Safely create a reference type to the type eleTy.
Definition FIRBuilder.cpp:115
mlir::Value createMinusOneInteger(mlir::Location loc, mlir::Type integerType)
Definition FIRBuilder.h:215
mlir::Value createIntegerConstant(mlir::Location loc, mlir::Type integerType, std::int64_t i)
Definition FIRBuilder.cpp:151
Bitsize getCharacterBitsize(KindTy kind) const
Get the size in bits of !fir.char<kind>
Definition KindMapping.cpp:278
Definition OpenACC.h:20
Definition BoxValue.h:446
llvm::SmallVector< mlir::Value > genBaseBoundsOps(fir::FirOpBuilder &builder, mlir::Location loc, fir::ExtendedValue dataExv, bool isAssumedSize, bool strideIncludeLowerExtent=false)
Definition DirectivesCommon.h:285
llvm::SmallVector< mlir::Value > genBoundsOpsFromBox(fir::FirOpBuilder &builder, mlir::Location loc, fir::ExtendedValue dataExv, AddrAndBoundsInfo &info)
Generate the bounds operation from the descriptor information.
Definition DirectivesCommon.h:218
mlir::Value readLowerBound(fir::FirOpBuilder &builder, mlir::Location loc, const fir::ExtendedValue &box, unsigned dim, mlir::Value defaultValue)
Definition FIRBuilder.cpp:1079
mlir::Value readExtent(fir::FirOpBuilder &builder, mlir::Location loc, const fir::ExtendedValue &box, unsigned dim)
Read or get the extent in dimension dim of the array described by box.
Definition FIRBuilder.cpp:1048
bool isOptionalArgument(mlir::Operation *op)
Definition DirectivesCommon.h:328
bool isa_ref_type(mlir::Type t)
Is t a FIR dialect type that implies a memory (de)reference?
Definition FIRType.h:135
bool isBoxAddress(mlir::Type t)
Is t an address to fir.box or class type?
Definition FIRType.h:535
bool characterWithDynamicLen(mlir::Type t)
Returns true iff t is a fir.char type and has an unknown length.
Definition FIRType.h:263
Definition DirectivesCommon.h:31