clang 24.0.0git
LoweringHelpers.cpp
Go to the documentation of this file.
1//====- LoweringHelpers.cpp - Lowering helper functions -------------------===//
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// This file contains helper functions for lowering from CIR to LLVM or MLIR.
10//
11//===----------------------------------------------------------------------===//
12
14#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
15#include "mlir/Dialect/LLVMIR/LLVMTypes.h"
16#include "mlir/IR/BuiltinTypes.h"
17#include "mlir/IR/SymbolTable.h"
18#include "mlir/Interfaces/DataLayoutInterfaces.h"
20
21namespace {
22/// A _BitInt(N) whose padded storage integer iM has a larger alloc size than
23/// its M/8 store size is laid out by clang as a byte array, not a plain
24/// integer (e.g. _BitInt(129) -> i192 with alloc size 32 != store size 24).
25/// That "split" storage form is not yet implemented; lowerings must detect
26/// it and report errorNYI rather than emit the wrong-sized integer.
27bool isSplitStorageBitInt(cir::IntType ty, const mlir::DataLayout &dataLayout) {
28 if (!ty.isBitInt())
29 return false;
30 unsigned storageBits = ty.getStorageTypeWidth(dataLayout);
31 auto storageTy = mlir::IntegerType::get(ty.getContext(), storageBits);
32 uint64_t storeSize = storageBits / 8;
33 uint64_t allocSize =
34 llvm::alignTo(storeSize, dataLayout.getTypeABIAlignment(storageTy));
35 return allocSize != storeSize;
36}
37} // namespace
38
39mlir::Type convertTypeForMemory(const mlir::TypeConverter &converter,
40 mlir::DataLayout const &dataLayout,
41 mlir::Type type) {
42 // TODO(cir): Handle other types similarly to clang's codegen
43 // convertTypeForMemory
44 if (mlir::isa<cir::BoolType>(type)) {
45 return mlir::IntegerType::get(type.getContext(),
46 dataLayout.getTypeSizeInBits(type));
47 }
48
49 if (auto vecTy = mlir::dyn_cast<cir::VectorType>(type)) {
50 if (mlir::isa<cir::BoolType>(vecTy.getElementType())) {
52 // Pad to at least one byte.
53 uint64_t bytePadded = std::max<uint64_t>(vecTy.getSize(), 8);
54 return mlir::IntegerType::get(type.getContext(), bytePadded);
55 }
56 }
57
58 // _BitInt(N) keeps its literal width as a value but is stored in a padded
59 // integer iM in memory, the same way bool is i1 as a value and i8 in
60 // memory. The byte-array storage form for wide split widths is not
61 // implemented; a null return signals that, and op lowerings turn it into
62 // errorNYI.
63 if (auto intTy = mlir::dyn_cast<cir::IntType>(type);
64 intTy && intTy.isBitInt()) {
65 if (isSplitStorageBitInt(intTy, dataLayout))
66 return {};
67 return mlir::IntegerType::get(type.getContext(),
68 intTy.getStorageTypeWidth(dataLayout));
69 }
70
71 return converter.convertType(type);
72}
73
74static unsigned getIntOrBoolBitWidth(mlir::Type ty) {
75 if (auto intTy = mlir::dyn_cast<cir::IntType>(ty))
76 return intTy.getWidth();
77 assert(mlir::isa<cir::BoolType>(ty) &&
78 "expected CIR integer or bool element type");
79 return 1;
80}
81
82mlir::DenseElementsAttr
83convertStringAttrToDenseElementsAttr(cir::ConstArrayAttr attr,
84 mlir::Type type) {
85 const auto stringAttr = mlir::cast<mlir::StringAttr>(attr.getElts());
86 const auto arrayTy = mlir::cast<cir::ArrayType>(attr.getType());
87 const unsigned totalSize = arrayTy.getSize();
88 const unsigned trailingZeros = attr.getTrailingZerosNum();
89 assert(stringAttr.size() + trailingZeros == totalSize &&
90 "string const_array size must match explicit elements plus "
91 "trailing_zeros");
92
93 const unsigned bitWidth = getIntOrBoolBitWidth(arrayTy.getElementType());
95 values.reserve(totalSize);
96
97 // String bytes are raw values; interpret each as an unsigned byte so a
98 // high-bit char (>= 0x80) does not sign-extend to a value that overflows
99 // the element bit width when constructing the APInt.
100 for (const char element : stringAttr)
101 values.emplace_back(bitWidth, static_cast<unsigned char>(element));
102
103 values.insert(values.end(), trailingZeros, mlir::APInt::getZero(bitWidth));
104
105 return mlir::DenseElementsAttr::get(
106 mlir::RankedTensorType::get({totalSize}, type), llvm::ArrayRef(values));
107}
108
109template <> mlir::APInt getZeroInitFromType(mlir::Type ty) {
110 if (mlir::isa<cir::BoolType>(ty))
111 return mlir::APInt::getZero(1);
112 const auto intTy = mlir::cast<cir::IntType>(ty);
113 return mlir::APInt::getZero(intTy.getWidth());
114}
115
116template <> mlir::APFloat getZeroInitFromType(mlir::Type ty) {
117 auto fpTy = mlir::cast<cir::FPTypeInterface>(ty);
118 return mlir::APFloat::getZero(fpTy.getFloatSemantics());
119}
120
121/// \param attr the ConstArrayAttr to convert
122/// \param values the output parameter, the values array to fill
123/// \param currentDims the shpae of tensor we're going to convert to
124/// \param dimIndex the current dimension we're processing
125/// \param currentIndex the current index in the values array
126template <typename AttrTy, typename StorageTy>
128 cir::ConstArrayAttr attr, llvm::SmallVectorImpl<StorageTy> &values,
129 const llvm::SmallVectorImpl<int64_t> &currentDims, int64_t dimIndex,
130 int64_t currentIndex) {
131 if (auto stringAttr = mlir::dyn_cast<mlir::StringAttr>(attr.getElts())) {
132 if (auto arrayType = mlir::dyn_cast<cir::ArrayType>(attr.getType())) {
133 for (auto element : stringAttr) {
134 auto intAttr = cir::IntAttr::get(arrayType.getElementType(), element);
135 values[currentIndex++] = mlir::dyn_cast<AttrTy>(intAttr).getValue();
136 }
137 // Remaining slots are trailing zeros; values was zero-initialized.
138 currentIndex += attr.getTrailingZerosNum();
139 return;
140 }
141 }
142
143 dimIndex++;
144 std::size_t elementsSizeInCurrentDim = 1;
145 for (std::size_t i = dimIndex; i < currentDims.size(); i++)
146 elementsSizeInCurrentDim *= currentDims[i];
147
148 auto arrayAttr = mlir::cast<mlir::ArrayAttr>(attr.getElts());
149 for (auto eltAttr : arrayAttr) {
150 if constexpr (std::is_same_v<StorageTy, mlir::APInt>) {
151 if (auto boolAttr = mlir::dyn_cast<cir::BoolAttr>(eltAttr)) {
152 values[currentIndex++] =
153 llvm::APInt(1, static_cast<uint64_t>(boolAttr.getValue()));
154 continue;
155 }
156 }
157 if (auto valueAttr = mlir::dyn_cast<AttrTy>(eltAttr)) {
158 values[currentIndex++] = valueAttr.getValue();
159 continue;
160 }
161
162 if (auto subArrayAttr = mlir::dyn_cast<cir::ConstArrayAttr>(eltAttr)) {
163 convertToDenseElementsAttrImpl<AttrTy>(subArrayAttr, values, currentDims,
164 dimIndex, currentIndex);
165 currentIndex += elementsSizeInCurrentDim;
166 continue;
167 }
168
169 if (mlir::isa<cir::ZeroAttr, cir::UndefAttr>(eltAttr)) {
170 currentIndex += elementsSizeInCurrentDim;
171 continue;
172 }
173
174 llvm_unreachable("unknown element in ConstArrayAttr");
175 }
176}
177
178template <typename AttrTy, typename StorageTy>
179mlir::DenseElementsAttr convertToDenseElementsAttr(
180 cir::ConstArrayAttr attr, const llvm::SmallVectorImpl<int64_t> &dims,
181 mlir::Type elementType, mlir::Type convertedElementType) {
182 unsigned vectorSize = 1;
183 for (auto dim : dims)
184 vectorSize *= dim;
186 vectorSize, getZeroInitFromType<StorageTy>(elementType));
187 convertToDenseElementsAttrImpl<AttrTy>(attr, values, dims, /*currentDim=*/0,
188 /*initialIndex=*/0);
189 return mlir::DenseElementsAttr::get(
190 mlir::RankedTensorType::get(dims, convertedElementType),
191 llvm::ArrayRef(values));
192}
193
194/// Return true when \p gv can be lowered to a \c FlatSymbolRefAttr leaf without
195/// addrspacecast or bitcast (mirrors \c CIRAttrToValue::visitCirAttr).
196static bool
197globalViewMatchesPointerLeaf(cir::GlobalViewAttr gv, mlir::ModuleOp moduleOp,
198 mlir::SymbolTableCollection &symbolTables,
199 const mlir::TypeConverter *converter) {
200 if (gv.getIndices() || mlir::isa<cir::IntType, cir::VPtrType>(gv.getType()))
201 return false;
202
203 auto ptrTy = mlir::dyn_cast<cir::PointerType>(gv.getType());
204 if (!ptrTy)
205 return false;
206
207 unsigned sourceAddrSpace = 0;
208 mlir::Type sourceType;
209 auto sourceSymbol = symbolTables.lookupSymbolIn(moduleOp, gv.getSymbol());
210 if (auto llvmSymbol = mlir::dyn_cast<mlir::LLVM::GlobalOp>(sourceSymbol)) {
211 sourceType = llvmSymbol.getType();
212 sourceAddrSpace = llvmSymbol.getAddrSpace();
213 } else if (auto cirSymbol = mlir::dyn_cast<cir::GlobalOp>(sourceSymbol)) {
214 sourceType = converter->convertType(cirSymbol.getSymType());
215 if (auto targetAS = mlir::dyn_cast_if_present<cir::TargetAddressSpaceAttr>(
216 cirSymbol.getAddrSpaceAttr()))
217 sourceAddrSpace = targetAS.getValue();
218 } else {
219 // cir.func and other symbols not yet lowered to globals cannot be used as
220 // bulk constant leaves; those cases keep the insertvalue fallback.
221 return false;
222 }
223
224 auto llvmDstTy = converter->convertType<mlir::LLVM::LLVMPointerType>(ptrTy);
225 if (llvmDstTy.getAddressSpace() != sourceAddrSpace)
226 return false;
227
228 mlir::Type llvmEltTy = converter->convertType(ptrTy.getPointee());
229 if (llvmEltTy == sourceType)
230 return true;
231 if (auto arrTy = mlir::dyn_cast<mlir::LLVM::LLVMArrayType>(sourceType))
232 return llvmEltTy == arrTy.getElementType();
233 return false;
234}
235
236/// Lower a single pointer-element of a \c cir.const_array to an LLVM-dialect
237/// constant leaf suitable for a bulk \c llvm.mlir.constant. Only handles
238/// address-of-global without indices and null pointers; indexed global views
239/// must use the per-element \c llvm.insertvalue fallback.
240static std::optional<mlir::Attribute>
241lowerPointerElementAttr(mlir::Attribute elt, mlir::MLIRContext *ctx,
242 mlir::ModuleOp moduleOp,
243 mlir::SymbolTableCollection &symbolTables,
244 const mlir::TypeConverter *converter) {
245 if (auto gv = mlir::dyn_cast<cir::GlobalViewAttr>(elt)) {
246 if (!moduleOp ||
247 !globalViewMatchesPointerLeaf(gv, moduleOp, symbolTables, converter))
248 return std::nullopt;
249 return gv.getSymbol();
250 }
251 if (auto nullPtr = mlir::dyn_cast<cir::ConstPtrAttr>(elt)) {
252 if (nullPtr.isNullValue())
253 return mlir::LLVM::ZeroAttr::get(ctx);
254 return std::nullopt;
255 }
256 return std::nullopt;
257}
258
259static bool containsPoison(mlir::Attribute attr) {
260 if (mlir::isa<cir::PoisonAttr>(attr))
261 return true;
262 if (auto elts = mlir::dyn_cast<mlir::ArrayAttr>(attr))
263 return llvm::any_of(elts, containsPoison);
264 if (auto constArr = mlir::dyn_cast<cir::ConstArrayAttr>(attr)) {
265 if (mlir::isa<mlir::StringAttr>(constArr.getElts()))
266 return false;
267 if (auto elts = mlir::dyn_cast<mlir::ArrayAttr>(constArr.getElts()))
268 return llvm::any_of(elts, containsPoison);
269 }
270 return false;
271}
272
273/// Block-address attributes (address-of-label and label differences) are
274/// lowered to relocation expressions that cannot be materialized as part of a
275/// dense/aggregate constant attribute; they require the per-element
276/// insertvalue region lowering. Return true if \p attr contains any such
277/// element.
278static bool containsBlockAddress(mlir::Attribute attr) {
279 if (mlir::isa<cir::BlockAddrInfoAttr, cir::BlockAddrDiffAttr>(attr))
280 return true;
281 if (auto elts = mlir::dyn_cast<mlir::ArrayAttr>(attr))
282 return llvm::any_of(elts, containsBlockAddress);
283 if (auto constArr = mlir::dyn_cast<cir::ConstArrayAttr>(attr)) {
284 if (mlir::isa<mlir::StringAttr>(constArr.getElts()))
285 return false;
286 if (auto elts = mlir::dyn_cast<mlir::ArrayAttr>(constArr.getElts()))
287 return llvm::any_of(elts, containsBlockAddress);
288 }
289 return false;
290}
291
292static std::optional<mlir::Attribute> lowerConstRecordMemberAttr(
293 mlir::Attribute attr, mlir::SymbolTableCollection &symbolTables,
294 const mlir::TypeConverter *converter, mlir::ModuleOp moduleOp);
295
296std::optional<mlir::Attribute> lowerConstArrayAttr(
297 cir::ConstArrayAttr constArr, mlir::SymbolTableCollection &symbolTables,
298 const mlir::TypeConverter *converter, mlir::ModuleOp moduleOp) {
299 // Ensure ConstArrayAttr has a type.
300 const auto typedConstArr = mlir::cast<mlir::TypedAttr>(constArr);
301
302 // Ensure ConstArrayAttr type is a ArrayType.
303 const auto cirArrayType = mlir::cast<cir::ArrayType>(typedConstArr.getType());
304
305 // Is a ConstArrayAttr with an cir::ArrayType: fetch element type.
306 mlir::Type type = cirArrayType;
307 auto dims = llvm::SmallVector<int64_t, 2>{};
308 while (auto arrayType = mlir::dyn_cast<cir::ArrayType>(type)) {
309 dims.push_back(arrayType.getSize());
310 type = arrayType.getElementType();
311 }
312
313 if (containsPoison(constArr))
314 return std::nullopt;
315
316 // Block-address initializers cannot be represented as a dense/aggregate
317 // constant attribute; fall back to the per-element insertvalue lowering.
318 if (containsBlockAddress(constArr))
319 return std::nullopt;
320
321 if (mlir::isa<mlir::StringAttr>(constArr.getElts()))
323 converter->convertType(type));
324 if (mlir::isa<cir::IntType>(type)) {
325 // A _BitInt array element is stored in a padded integer in memory; the
326 // dense-attribute path here cannot express that widening, so fall back to
327 // the insertvalue region, which widens each element via emitToMemory.
328 if (mlir::cast<cir::IntType>(type).isBitInt())
329 return std::nullopt;
331 constArr, dims, type, converter->convertType(type));
332 }
333
334 if (mlir::isa<cir::BoolType>(type))
336 constArr, dims, type, converter->convertType(type));
337
338 if (mlir::isa<cir::FPTypeInterface>(type))
340 constArr, dims, type, converter->convertType(type));
341
342 if (mlir::isa<cir::PointerType>(type)) {
343 // FIXME: Pointer arrays with trailing_zeros (null-sentinel tables) fall
344 // through to the insertvalue path for now.
345 if (constArr.getTrailingZerosNum() > 0)
346 return std::nullopt;
347 auto eltsArr = mlir::dyn_cast<mlir::ArrayAttr>(constArr.getElts());
348 if (!eltsArr)
349 return std::nullopt;
351 lowered.reserve(eltsArr.size());
352 mlir::MLIRContext *ctx = constArr.getContext();
353 for (mlir::Attribute elt : eltsArr) {
354 std::optional<mlir::Attribute> llvmElt =
355 lowerPointerElementAttr(elt, ctx, moduleOp, symbolTables, converter);
356 if (!llvmElt)
357 return std::nullopt;
358 lowered.push_back(*llvmElt);
359 }
360 return mlir::ArrayAttr::get(ctx, lowered);
361 }
362
363 if (mlir::isa<cir::RecordType>(type)) {
364 // A record type is just an array of the element values.
365 auto eltsArr = mlir::dyn_cast<mlir::ArrayAttr>(constArr.getElts());
366 if (!eltsArr)
367 return std::nullopt;
368
370 loweredElts.reserve(cirArrayType.getSize());
371
372 for (mlir::Attribute elt : eltsArr) {
373 std::optional<mlir::Attribute> llvmElt =
374 lowerConstRecordMemberAttr(elt, symbolTables, converter, moduleOp);
375 if (!llvmElt)
376 return std::nullopt;
377 loweredElts.push_back(*llvmElt);
378 }
379
380 // Remaining elts are either going to be padding (and should be undef), or
381 // trailing-zeros. We can't really tell the difference as CIR lowering
382 // doesn't differentiate anyway, so just zero-fill them.
383 while (loweredElts.size() < cirArrayType.getSize())
384 loweredElts.push_back(mlir::LLVM::ZeroAttr::get(constArr.getContext()));
385 return mlir::ArrayAttr::get(constArr.getContext(), loweredElts);
386 }
387
388 return std::nullopt;
389}
390
391/// Lower a constant attribute that initializes a single member of a record (or
392/// a leaf of a nested aggregate) to an LLVM-dialect attribute that can be
393/// attached directly to an \c llvm.mlir.global, avoiding an insertvalue
394/// initializer region. Returns \c std::nullopt when the attribute cannot be
395/// represented as a single constant attribute (e.g. an indexed
396/// \c GlobalViewAttr), in which case the caller falls back to the region-based
397/// lowering.
398static std::optional<mlir::Attribute> lowerConstRecordMemberAttr(
399 mlir::Attribute attr, mlir::SymbolTableCollection &symbolTables,
400 const mlir::TypeConverter *converter, mlir::ModuleOp moduleOp) {
401 mlir::MLIRContext *ctx = attr.getContext();
402
403 if (auto arrayAttr = mlir::dyn_cast<cir::ConstArrayAttr>(attr))
404 return lowerConstArrayAttr(arrayAttr, symbolTables, converter, moduleOp);
405
406 if (auto recordAttr = mlir::dyn_cast<cir::ConstRecordAttr>(attr))
407 return lowerConstRecordAttr(recordAttr, symbolTables, converter, moduleOp);
408
409 if (mlir::isa<cir::ZeroAttr>(attr))
410 return mlir::LLVM::ZeroAttr::get(ctx);
411
412 if (mlir::isa<cir::UndefAttr>(attr))
413 return mlir::LLVM::UndefAttr::get(ctx);
414
415 if (auto intAttr = mlir::dyn_cast<cir::IntAttr>(attr)) {
416 // A _BitInt member is stored in a padded integer in memory; defer to the
417 // insertvalue region (CIRAttrToValue), which performs the extension.
418 if (mlir::cast<cir::IntType>(intAttr.getType()).isBitInt())
419 return std::nullopt;
420 return mlir::IntegerAttr::get(converter->convertType(intAttr.getType()),
421 intAttr.getValue());
422 }
423
424 if (auto boolAttr = mlir::dyn_cast<cir::BoolAttr>(attr))
425 return mlir::IntegerAttr::get(converter->convertType(boolAttr.getType()),
426 boolAttr.getValue() ? 1 : 0);
427
428 if (auto fpAttr = mlir::dyn_cast<cir::FPAttr>(attr))
429 return mlir::FloatAttr::get(converter->convertType(fpAttr.getType()),
430 fpAttr.getValue());
431
432 // Null pointers and simple address-of-global references can be represented
433 // as constant attributes; anything more complex uses the region fallback.
434 return lowerPointerElementAttr(attr, ctx, moduleOp, symbolTables, converter);
435}
436
437// Figure out if we want mark the new struct 'packed' if it isn't already. IF
438// it is already, we have to keep that behavior. We pack it with logic similar
439// to classic codegen, though will end up missing cases, since we don't want to
440// change the type other than the FAM.
441// We can do so if:
442// 1- Packing it won't change any of the field offsets.
443// 2- the non-padded struct would add padding beyond the
444// flexible array member. We don't pack if the flexible array member manages
445// to not cause trailing padding.
446static bool shouldPackFAMStruct(const mlir::DataLayout &dataLayout,
448 uint64_t maxAlign = 1;
449 uint64_t totalSize = 0;
450 for (mlir::Type member : members) {
451 uint64_t align = dataLayout.getTypeABIAlignment(member);
452 maxAlign = std::max(maxAlign, align);
453 uint64_t size = dataLayout.getTypeSize(member).getFixedValue();
454
455 if (llvm::alignTo(totalSize, align) != totalSize)
456 return false;
457
458 totalSize += size;
459 }
460 return llvm::alignTo(totalSize, maxAlign) != totalSize;
461}
462
463// CIR supports flexible-array-members in its struct types. That is, a
464// zero-length array as the last element, which can be initialized with an
465// arbitrary number of elements. A ConstRecordAttr can be created with one of
466// these, and our verifier allows it. However, the LLVM implementation does NOT
467// permit this. So we have to replace this type in LLVM with special struct for
468// this value.
469//
470// Additionally, the struct itself could contain a struct with a FAM or a union
471// that needed adjustment, so it recurses to check those. If no such type has
472// been found/no adjustment needed, this returns the type unchanged.
473//
474// Additionally, a union having an active member of not-the-largest
475// alignment can cause the need for a small padding array. We also capture the
476// original indices of the fields that had this padding prepended, so the
477// lowerConstRecordAttr can later put in a 'zero' init there.
479 mlir::LLVM::LLVMStructType structTy, cir::ConstRecordAttr constRecord,
480 const mlir::TypeConverter &converter, const mlir::DataLayout &dataLayout,
481 llvm::SmallVectorImpl<unsigned> &paddingAddedIndexes) {
482 assert(paddingAddedIndexes.empty() &&
483 "Not for accumulation, just single depth");
485 constRecord.getMembers().getValue();
486 llvm::SmallVector<mlir::Type> origBody{structTy.getBody()};
488 bool packed = structTy.isPacked();
489 uint64_t curOffset = 0;
490 bool changed = false;
491
492 // Recursively adjust each member. A member that is itself a union (or a
493 // struct containing one) lowers to a type that differs from its declared
494 // field type, and this struct has to adopt that adjusted type so the
495 // enclosing insertvalue chain type-checks.
496 for (auto [idx, member] : llvm::enumerate(initMembers)) {
497 if (idx >= origBody.size())
498 break;
499 mlir::Type adjusted =
500 adjustGlobalTypeForInit(origBody[idx], member, converter, dataLayout);
501 unsigned adjustedAlign = dataLayout.getTypeABIAlignment(adjusted);
502
503 if (adjusted != origBody[idx]) {
504 // We're always going to 'change' the layout if it has changed, but we
505 // need to see if there is new 'padding' that won't happen automatically
506 // here based on alignment.
507 unsigned origAlign = dataLayout.getTypeABIAlignment(origBody[idx]);
508
509 uint64_t origOffset =
510 packed ? curOffset : llvm::alignTo(curOffset, origAlign);
511 uint64_t adjustedOffset =
512 packed ? curOffset : llvm::alignTo(curOffset, adjustedAlign);
513
514 if (adjustedOffset != origOffset) {
515 // If the offset would change, we have to insert padding to make up for
516 // it. This should only happen since alignment will decrease with
517 // unions, so we should be able to assume adjusted-offset < origOffset?
518 assert(adjustedOffset < origOffset);
519 // Rather than just pad the difference between the offsets, we have to
520 // fill in since the end of the last field, else we leave room thanks to
521 // alignment between this field and the padding.
522 uint64_t difference = origOffset - curOffset;
523 newBody.push_back(mlir::LLVM::LLVMArrayType::get(
524 mlir::IntegerType::get(structTy.getContext(), 8), difference));
525 paddingAddedIndexes.push_back(idx);
526 curOffset = origOffset;
527 }
528 changed = true;
529 }
530 newBody.push_back(adjusted);
531
532 if (!packed)
533 curOffset = llvm::alignTo(curOffset, adjustedAlign);
534 curOffset += dataLayout.getTypeSize(adjusted).getFixedValue();
535 }
536
537 // CIR supports flexible-array-members in its struct types. That is, a
538 // zero-length array as the last element, which can be initialized with an
539 // arbitrary number of elements. A ConstRecordAttr can be created with one of
540 // these, and our verifier allows it. However, the LLVM implementation does
541 // NOT permit this, so we widen that trailing member to the initializer's
542 // array type (packing the struct if that changes the layout).
543 bool widenedFAM = false;
544 if (auto fam =
545 mlir::dyn_cast<mlir::LLVM::LLVMArrayType>(structTy.getBody().back());
546 fam && fam.getNumElements() == 0) {
547 mlir::Type lastInitType =
548 mlir::cast<mlir::TypedAttr>(initMembers.back()).getType();
549 if (mlir::cast<cir::ArrayType>(lastInitType).getSize() != 0) {
550 newBody.back() =
551 adjustGlobalTypeForInit(converter.convertType(lastInitType),
552 initMembers.back(), converter, dataLayout);
553 packed = packed || shouldPackFAMStruct(dataLayout, newBody);
554 widenedFAM = true;
555 changed = true;
556 }
557 }
558
559 if (!changed)
560 return structTy;
561
562 // We've likely reduced the alignment, so make sure we put padding 'behind'
563 // it. We can skip this in the FAM case, since a Flexible array member is not
564 // allowed to be initialized unless it is the 'last' element. So it doesn't
565 // need to be padded out.
566 if (!widenedFAM) {
567 uint64_t declaredSize = dataLayout.getTypeSize(structTy).getFixedValue();
568 assert(curOffset <= declaredSize && "body bigger than type?");
569 if (curOffset < declaredSize)
570 newBody.push_back(mlir::LLVM::LLVMArrayType::get(
571 mlir::IntegerType::get(structTy.getContext(), 8),
572 declaredSize - curOffset));
573 }
574
575 return mlir::LLVM::LLVMStructType::getLiteral(structTy.getContext(), newBody,
576 packed);
577}
578
579// A union constant only initializes its active member, but a union is lowered
580// to its most-aligned member (its 'storage' type), which need not be the
581// initialized one -- e.g. `union { char buf[16]; long cap; }` stores as `long`
582// (higher alignment) but may be initialized through `buf`. So the storage type
583// (and thus structTy) generally can't hold the active member's value. Rebuild
584// an anonymous struct `{ <active member>, [pad x i8] }` that holds the active
585// member followed by enough byte padding to span the union's full allocated
586// size, mirroring classic codegen.
588 mlir::LLVM::LLVMStructType structTy, cir::ConstRecordAttr constRecord,
589 const mlir::TypeConverter &converter, const mlir::DataLayout &dataLayout) {
590
591 auto unionTy = mlir::cast<cir::UnionType>(constRecord.getType());
592
593 // Unions can only initialize one field, so this has to be sizeof-one.
594 assert(constRecord.getMembers().size() == 1);
595 mlir::Attribute member = constRecord.getMembers()[0];
596 mlir::Type memberTy = convertTypeForMemory(
597 converter, dataLayout, mlir::cast<mlir::TypedAttr>(member).getType());
598
599 // The active member may itself need adjusting (e.g. it is a nested union, or
600 // a struct containing one), so recurse before using its type below.
601 memberTy = adjustGlobalTypeForInit(memberTy, member, converter, dataLayout);
602
603 // The converted union type is { storage, [padding] }, where storage is the
604 // union's most-aligned member. When the active member IS that storage type,
605 // the converted type already describes this initializer exactly (the pad we
606 // would compute equals the union's declared pad), so there is nothing to do.
607 if (memberTy == structTy.getBody().front())
608 return structTy;
609
610 uint64_t unionSize = dataLayout.getTypeSize(unionTy).getFixedValue();
611 uint64_t initSize = dataLayout.getTypeSize(memberTy).getFixedValue();
612 assert(initSize <= unionSize && "union initializer larger than the union");
613
615 newBody.push_back(memberTy);
616
617 // Fill the rest of the union's allocated size with byte padding.
618 if (initSize < unionSize)
619 newBody.push_back(mlir::LLVM::LLVMArrayType::get(
620 mlir::IntegerType::get(structTy.getContext(), 8),
621 unionSize - initSize));
622
623 return mlir::LLVM::LLVMStructType::getLiteral(structTy.getContext(), newBody,
624 unionTy.getPacked());
625}
626
627// Unions in an array can cause individual elements to be of different types.
628// This function adjusts the array type and replaces it with a struct type if
629// necessary, OR leaves it as a 'new' array type if necessary.
631 mlir::LLVM::LLVMArrayType arrayTy, cir::ConstArrayAttr arrayInit,
632 const mlir::TypeConverter &converter, const mlir::DataLayout &dataLayout) {
633 auto elts = mlir::dyn_cast<mlir::ArrayAttr>(arrayInit.getElts());
634
635 if (!elts)
636 return arrayTy;
637
638 mlir::Type origEltTy = arrayTy.getElementType();
639 llvm::SmallVector<mlir::Type> adjustedElts(arrayTy.getNumElements(),
640 origEltTy);
641 bool changed = false;
642
643 for (auto [idx, elt] : llvm::enumerate(elts)) {
644 mlir::Type adjusted =
645 adjustGlobalTypeForInit(origEltTy, elt, converter, dataLayout);
646
647 if (idx >= arrayTy.getNumElements()) {
648 adjustedElts.push_back(adjusted);
649 changed = true;
650 } else if (adjusted != origEltTy) {
651 adjustedElts[idx] = adjusted;
652 changed = true;
653 }
654 }
655
656 if (!changed)
657 return arrayTy;
658
659 if (llvm::all_equal(adjustedElts))
660 return mlir::LLVM::LLVMArrayType::get(adjustedElts.front(),
661 adjustedElts.size());
662
663 // Packed, because arrays shouldn't be subject to padding.
664 return mlir::LLVM::LLVMStructType::getLiteral(
665 arrayTy.getContext(), adjustedElts, /*isPacked=*/true);
666}
667
668// Apply various adjustments required for struct/union types.
669mlir::Type
670adjustGlobalTypeForInit(mlir::Type llvmType, mlir::Attribute init,
671 const mlir::TypeConverter &converter,
672 const mlir::DataLayout &dataLayout,
673 llvm::SmallVectorImpl<unsigned> &paddingAddedIndexes) {
674 if (auto arrayInit = mlir::dyn_cast_if_present<cir::ConstArrayAttr>(init)) {
675 auto arrayTy = mlir::dyn_cast<mlir::LLVM::LLVMArrayType>(llvmType);
676 if (!arrayTy)
677 return llvmType;
678 return adjustGlobalArrayTypeForInit(arrayTy, arrayInit, converter,
679 dataLayout);
680 }
681
682 // Conversions for both only happen if we have a record init.
683 auto constRecord = mlir::dyn_cast_if_present<cir::ConstRecordAttr>(init);
684 if (!constRecord)
685 return llvmType;
686
687 // If this isn't of struct-type, or doesn't have any members, there is nothing
688 // to do.
689 auto structTy = mlir::dyn_cast<mlir::LLVM::LLVMStructType>(llvmType);
690 if (!structTy || structTy.getBody().empty())
691 return llvmType;
692
693 // Structs can have a flexible array member, adjust that.
694 if (mlir::isa<cir::StructType>(constRecord.getType()))
695 return adjustGlobalStructTypeForInit(structTy, constRecord, converter,
696 dataLayout, paddingAddedIndexes);
697 if (mlir::isa<cir::UnionType>(constRecord.getType()))
698 return adjustGlobalUnionTypeForInit(structTy, constRecord, converter,
699 dataLayout);
700 return llvmType;
701}
702
703mlir::Type adjustGlobalTypeForInit(mlir::Type llvmType, mlir::Attribute init,
704 const mlir::TypeConverter &converter,
705 const mlir::DataLayout &dataLayout) {
706 llvm::SmallVector<unsigned> ignoredAddedIndexes;
707 return adjustGlobalTypeForInit(llvmType, init, converter, dataLayout,
708 ignoredAddedIndexes);
709}
710
711std::optional<mlir::Attribute> lowerConstRecordAttr(
712 cir::ConstRecordAttr constRecord, mlir::SymbolTableCollection &symbolTables,
713 const mlir::TypeConverter *converter, mlir::ModuleOp moduleOp) {
714
715 // Build one constant attribute per record member. The LLVM dialect global
716 // translation accepts an ArrayAttr (one element per struct field) and emits
717 // an llvm::ConstantStruct, so the whole initializer can be a single
718 // attribute on the global instead of an insertvalue region.
719 mlir::ArrayAttr memberAttrs = constRecord.getMembers();
721 loweredMembers.reserve(memberAttrs.size());
722 for (mlir::Attribute member : memberAttrs) {
723 std::optional<mlir::Attribute> lowered =
724 lowerConstRecordMemberAttr(member, symbolTables, converter, moduleOp);
725 if (!lowered)
726 return std::nullopt;
727 loweredMembers.push_back(*lowered);
728 }
729
730 // The lowered LLVM type may have more fields than the CIR record has members
731 // for a few reasons:
732 // 1- a union lowers to { active-member, [pad x i8]).
733 // 2- A struct that contains such a union can have its alignment changed too,
734 // so it needs tail padding to fill that in.
735 // 3- A struct containing a union whose initializer doesn't use the
736 // highest-aligned field will have to prepend a bit of padding, such as struct
737 // { i32, union { i64, i32 } }. Typically the union gets lowered to a struct
738 // { i64 } (as i64 has the greatest alignment), but if the init causes it to
739 // be the i32(or any such smaller field) we have to prepend it with padding:
740 // struct { i32, [4 x i8], struct { i32 }}
741 // instead of (with no init):
742 // struct { i32, struct { i64 }}
743 llvm::SmallVector<unsigned> paddingAddedIndexes;
744 mlir::Type adjustedTy = adjustGlobalTypeForInit(
745 converter->convertType(constRecord.getType()), constRecord, *converter,
746 mlir::DataLayout(moduleOp), paddingAddedIndexes);
747
748 // This handles #3 from above. adjustGlobalTypeForInit ensures the
749 // indexes are in increasing order, so we can insert 'backwards' without
750 // causing problems.
751 for (unsigned paddedElt : llvm::reverse(paddingAddedIndexes))
752 loweredMembers.insert(loweredMembers.begin() + paddedElt,
753 mlir::LLVM::ZeroAttr::get(constRecord.getContext()));
754
755 // Any remaining difference will be the union/struct padding case. We don't
756 // have a great handle/way to tell when to zero-vs-undef init, so always
757 // zero init, as it is always safe to do so.
758 if (auto structTy = mlir::dyn_cast<mlir::LLVM::LLVMStructType>(adjustedTy))
759 while (loweredMembers.size() < structTy.getBody().size())
760 loweredMembers.push_back(
761 mlir::LLVM::ZeroAttr::get(constRecord.getContext()));
762
763 return mlir::ArrayAttr::get(constRecord.getContext(), loweredMembers);
764}
765
766mlir::Value getConstAPInt(mlir::OpBuilder &bld, mlir::Location loc,
767 mlir::Type typ, const llvm::APInt &val) {
768 return mlir::LLVM::ConstantOp::create(bld, loc, typ, val);
769}
770
771mlir::Value getConst(mlir::OpBuilder &bld, mlir::Location loc, mlir::Type typ,
772 unsigned val) {
773 return mlir::LLVM::ConstantOp::create(bld, loc, typ, val);
774}
775
776mlir::Value createShL(mlir::OpBuilder &bld, mlir::Value lhs, unsigned rhs) {
777 if (!rhs)
778 return lhs;
779 mlir::Value rhsVal = getConst(bld, lhs.getLoc(), lhs.getType(), rhs);
780 return mlir::LLVM::ShlOp::create(bld, lhs.getLoc(), lhs, rhsVal);
781}
782
783mlir::Value createAShR(mlir::OpBuilder &bld, mlir::Value lhs, unsigned rhs) {
784 if (!rhs)
785 return lhs;
786 mlir::Value rhsVal = getConst(bld, lhs.getLoc(), lhs.getType(), rhs);
787 return mlir::LLVM::AShrOp::create(bld, lhs.getLoc(), lhs, rhsVal);
788}
789
790mlir::Value createAnd(mlir::OpBuilder &bld, mlir::Value lhs,
791 const llvm::APInt &rhs) {
792 mlir::Value rhsVal = getConstAPInt(bld, lhs.getLoc(), lhs.getType(), rhs);
793 return mlir::LLVM::AndOp::create(bld, lhs.getLoc(), lhs, rhsVal);
794}
795
796mlir::Value createLShR(mlir::OpBuilder &bld, mlir::Value lhs, unsigned rhs) {
797 if (!rhs)
798 return lhs;
799 mlir::Value rhsVal = getConst(bld, lhs.getLoc(), lhs.getType(), rhs);
800 return mlir::LLVM::LShrOp::create(bld, lhs.getLoc(), lhs, rhsVal);
801}
TokenType getType() const
Returns the token's type, e.g.
mlir::DenseElementsAttr convertStringAttrToDenseElementsAttr(cir::ConstArrayAttr attr, mlir::Type type)
mlir::Type convertTypeForMemory(const mlir::TypeConverter &converter, mlir::DataLayout const &dataLayout, mlir::Type type)
static bool globalViewMatchesPointerLeaf(cir::GlobalViewAttr gv, mlir::ModuleOp moduleOp, mlir::SymbolTableCollection &symbolTables, const mlir::TypeConverter *converter)
Return true when gv can be lowered to a FlatSymbolRefAttr leaf without addrspacecast or bitcast (mirr...
mlir::Value createLShR(mlir::OpBuilder &bld, mlir::Value lhs, unsigned rhs)
mlir::Value createShL(mlir::OpBuilder &bld, mlir::Value lhs, unsigned rhs)
mlir::Value getConst(mlir::OpBuilder &bld, mlir::Location loc, mlir::Type typ, unsigned val)
static mlir::Type adjustGlobalStructTypeForInit(mlir::LLVM::LLVMStructType structTy, cir::ConstRecordAttr constRecord, const mlir::TypeConverter &converter, const mlir::DataLayout &dataLayout, llvm::SmallVectorImpl< unsigned > &paddingAddedIndexes)
mlir::Value getConstAPInt(mlir::OpBuilder &bld, mlir::Location loc, mlir::Type typ, const llvm::APInt &val)
std::optional< mlir::Attribute > lowerConstArrayAttr(cir::ConstArrayAttr constArr, mlir::SymbolTableCollection &symbolTables, const mlir::TypeConverter *converter, mlir::ModuleOp moduleOp)
mlir::Type adjustGlobalTypeForInit(mlir::Type llvmType, mlir::Attribute init, const mlir::TypeConverter &converter, const mlir::DataLayout &dataLayout, llvm::SmallVectorImpl< unsigned > &paddingAddedIndexes)
void convertToDenseElementsAttrImpl(cir::ConstArrayAttr attr, llvm::SmallVectorImpl< StorageTy > &values, const llvm::SmallVectorImpl< int64_t > &currentDims, int64_t dimIndex, int64_t currentIndex)
static mlir::Type adjustGlobalArrayTypeForInit(mlir::LLVM::LLVMArrayType arrayTy, cir::ConstArrayAttr arrayInit, const mlir::TypeConverter &converter, const mlir::DataLayout &dataLayout)
static bool containsPoison(mlir::Attribute attr)
static std::optional< mlir::Attribute > lowerPointerElementAttr(mlir::Attribute elt, mlir::MLIRContext *ctx, mlir::ModuleOp moduleOp, mlir::SymbolTableCollection &symbolTables, const mlir::TypeConverter *converter)
Lower a single pointer-element of a cir.const_array to an LLVM-dialect constant leaf suitable for a b...
mlir::Value createAShR(mlir::OpBuilder &bld, mlir::Value lhs, unsigned rhs)
std::optional< mlir::Attribute > lowerConstRecordAttr(cir::ConstRecordAttr constRecord, mlir::SymbolTableCollection &symbolTables, const mlir::TypeConverter *converter, mlir::ModuleOp moduleOp)
static std::optional< mlir::Attribute > lowerConstRecordMemberAttr(mlir::Attribute attr, mlir::SymbolTableCollection &symbolTables, const mlir::TypeConverter *converter, mlir::ModuleOp moduleOp)
Lower a constant attribute that initializes a single member of a record (or a leaf of a nested aggreg...
mlir::Value createAnd(mlir::OpBuilder &bld, mlir::Value lhs, const llvm::APInt &rhs)
static bool shouldPackFAMStruct(const mlir::DataLayout &dataLayout, llvm::ArrayRef< mlir::Type > members)
mlir::DenseElementsAttr convertToDenseElementsAttr(cir::ConstArrayAttr attr, const llvm::SmallVectorImpl< int64_t > &dims, mlir::Type elementType, mlir::Type convertedElementType)
static bool containsBlockAddress(mlir::Attribute attr)
Block-address attributes (address-of-label and label differences) are lowered to relocation expressio...
static mlir::Type adjustGlobalUnionTypeForInit(mlir::LLVM::LLVMStructType structTy, cir::ConstRecordAttr constRecord, const mlir::TypeConverter &converter, const mlir::DataLayout &dataLayout)
mlir::APInt getZeroInitFromType(mlir::Type ty)
static unsigned getIntOrBoolBitWidth(mlir::Type ty)
StorageTy getZeroInitFromType(mlir::Type ty)