MLIR 24.0.0git
ModuleTranslation.cpp
Go to the documentation of this file.
1//===- ModuleTranslation.cpp - MLIR to LLVM conversion --------------------===//
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 implements the translation between an MLIR LLVM dialect module and
10// the corresponding LLVMIR module. It only handles core LLVM IR operations.
11//
12//===----------------------------------------------------------------------===//
13
15
16#include "AttrKindDetail.h"
17#include "DebugTranslation.h"
26#include "mlir/IR/Attributes.h"
27#include "mlir/IR/BuiltinOps.h"
30#include "mlir/Support/LLVM.h"
33
34#include "llvm/ADT/DenseSet.h"
35#include "llvm/ADT/STLExtras.h"
36#include "llvm/ADT/StringExtras.h"
37#include "llvm/ADT/TypeSwitch.h"
38#include "llvm/Analysis/TargetFolder.h"
39#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
40#include "llvm/IR/BasicBlock.h"
41#include "llvm/IR/CFG.h"
42#include "llvm/IR/Constants.h"
43#include "llvm/IR/DerivedTypes.h"
44#include "llvm/IR/IRBuilder.h"
45#include "llvm/IR/InlineAsm.h"
46#include "llvm/IR/LLVMContext.h"
47#include "llvm/IR/MDBuilder.h"
48#include "llvm/IR/Module.h"
49#include "llvm/IR/Verifier.h"
50#include "llvm/Support/Debug.h"
51#include "llvm/Support/ErrorHandling.h"
52#include "llvm/Support/VirtualFileSystem.h"
53#include "llvm/Support/raw_ostream.h"
54#include "llvm/Transforms/Utils/BasicBlockUtils.h"
55#include "llvm/Transforms/Utils/Cloning.h"
56#include "llvm/Transforms/Utils/ModuleUtils.h"
57#include <numeric>
58#include <optional>
59
60#define DEBUG_TYPE "llvm-dialect-to-llvm-ir"
61
62using namespace mlir;
63using namespace mlir::LLVM;
64using namespace mlir::LLVM::detail;
65
66#include "mlir/Dialect/LLVMIR/LLVMConversionEnumsToLLVM.inc"
67
68namespace {
69/// A customized inserter for LLVM's IRBuilder that captures all LLVM IR
70/// instructions that are created for future reference.
71///
72/// This is intended to be used with the `CollectionScope` RAII object:
73///
74/// llvm::IRBuilder<..., InstructionCapturingInserter> builder;
75/// {
76/// InstructionCapturingInserter::CollectionScope scope(builder);
77/// // Call IRBuilder methods as usual.
78///
79/// // This will return a list of all instructions created by the builder,
80/// // in order of creation.
81/// builder.getInserter().getCapturedInstructions();
82/// }
83/// // This will return an empty list.
84/// builder.getInserter().getCapturedInstructions();
85///
86/// The capturing functionality is _disabled_ by default for performance
87/// consideration. It needs to be explicitly enabled, which is achieved by
88/// creating a `CollectionScope`.
89class InstructionCapturingInserter : public llvm::IRBuilderCallbackInserter {
90public:
91 /// Constructs the inserter.
92 InstructionCapturingInserter()
93 : llvm::IRBuilderCallbackInserter([this](llvm::Instruction *instruction) {
94 if (LLVM_LIKELY(enabled))
95 capturedInstructions.push_back(instruction);
96 }) {}
97
98 /// Returns the list of LLVM IR instructions captured since the last cleanup.
99 ArrayRef<llvm::Instruction *> getCapturedInstructions() const {
100 return capturedInstructions;
101 }
102
103 /// Clears the list of captured LLVM IR instructions.
104 void clearCapturedInstructions() { capturedInstructions.clear(); }
105
106 /// RAII object enabling the capture of created LLVM IR instructions.
107 class CollectionScope {
108 public:
109 /// Creates the scope for the given inserter.
110 CollectionScope(llvm::IRBuilderBase &irBuilder, bool isBuilderCapturing);
111
112 /// Ends the scope.
113 ~CollectionScope();
114
115 ArrayRef<llvm::Instruction *> getCapturedInstructions() {
116 if (!inserter)
117 return {};
118 return inserter->getCapturedInstructions();
119 }
120
121 private:
122 /// Back reference to the inserter.
123 InstructionCapturingInserter *inserter = nullptr;
124
125 /// List of instructions in the inserter prior to this scope.
126 SmallVector<llvm::Instruction *> previouslyCollectedInstructions;
127
128 /// Whether the inserter was enabled prior to this scope.
129 bool wasEnabled;
130 };
131
132 /// Enable or disable the capturing mechanism.
133 void setEnabled(bool enabled = true) { this->enabled = enabled; }
134
135private:
136 /// List of captured instructions.
137 SmallVector<llvm::Instruction *> capturedInstructions;
138
139 /// Whether the collection is enabled.
140 bool enabled = false;
141};
142
143using CapturingIRBuilder =
144 llvm::IRBuilder<llvm::TargetFolder, InstructionCapturingInserter>;
145} // namespace
146
147InstructionCapturingInserter::CollectionScope::CollectionScope(
148 llvm::IRBuilderBase &irBuilder, bool isBuilderCapturing) {
149
150 if (!isBuilderCapturing)
151 return;
152
153 auto &capturingIRBuilder = static_cast<CapturingIRBuilder &>(irBuilder);
154 inserter = &capturingIRBuilder.getInserter();
155 wasEnabled = inserter->enabled;
156 if (wasEnabled)
157 previouslyCollectedInstructions.swap(inserter->capturedInstructions);
158 inserter->setEnabled(true);
159}
160
161InstructionCapturingInserter::CollectionScope::~CollectionScope() {
162 if (!inserter)
163 return;
164
165 previouslyCollectedInstructions.swap(inserter->capturedInstructions);
166 // If collection was enabled (likely in another, surrounding scope), keep
167 // the instructions collected in this scope.
168 if (wasEnabled) {
169 llvm::append_range(inserter->capturedInstructions,
170 previouslyCollectedInstructions);
171 }
172 inserter->setEnabled(wasEnabled);
173}
174
175/// Translates the given data layout spec attribute to the LLVM IR data layout.
176/// Only integer, float, pointer and endianness entries are currently supported.
177static FailureOr<llvm::DataLayout>
178translateDataLayout(DataLayoutSpecInterface attribute,
179 const DataLayout &dataLayout,
180 std::optional<Location> loc = std::nullopt) {
181 if (!loc)
182 loc = UnknownLoc::get(attribute.getContext());
183
184 // Translate the endianness attribute.
185 std::string llvmDataLayout;
186 llvm::raw_string_ostream layoutStream(llvmDataLayout);
187 for (DataLayoutEntryInterface entry : attribute.getEntries()) {
188 auto key = llvm::dyn_cast_if_present<StringAttr>(entry.getKey());
189 if (!key)
190 continue;
191 if (key.getValue() == DLTIDialect::kDataLayoutEndiannessKey) {
192 auto value = cast<StringAttr>(entry.getValue());
193 bool isLittleEndian =
194 value.getValue() == DLTIDialect::kDataLayoutEndiannessLittle;
195 layoutStream << "-" << (isLittleEndian ? "e" : "E");
196 continue;
197 }
198 if (key.getValue() == DLTIDialect::kDataLayoutManglingModeKey) {
199 auto value = cast<StringAttr>(entry.getValue());
200 layoutStream << "-m:" << value.getValue();
201 continue;
202 }
203 if (key.getValue() == DLTIDialect::kDataLayoutProgramMemorySpaceKey) {
204 auto value = cast<IntegerAttr>(entry.getValue());
205 uint64_t space = value.getValue().getZExtValue();
206 // Skip the default address space.
207 if (space == 0)
208 continue;
209 layoutStream << "-P" << space;
210 continue;
211 }
212 if (key.getValue() == DLTIDialect::kDataLayoutGlobalMemorySpaceKey) {
213 auto value = cast<IntegerAttr>(entry.getValue());
214 uint64_t space = value.getValue().getZExtValue();
215 // Skip the default address space.
216 if (space == 0)
217 continue;
218 layoutStream << "-G" << space;
219 continue;
220 }
221 if (key.getValue() == DLTIDialect::kDataLayoutAllocaMemorySpaceKey) {
222 auto value = cast<IntegerAttr>(entry.getValue());
223 uint64_t space = value.getValue().getZExtValue();
224 // Skip the default address space.
225 if (space == 0)
226 continue;
227 layoutStream << "-A" << space;
228 continue;
229 }
230 if (key.getValue() == DLTIDialect::kDataLayoutStackAlignmentKey) {
231 auto value = cast<IntegerAttr>(entry.getValue());
232 uint64_t alignment = value.getValue().getZExtValue();
233 // Skip the default stack alignment.
234 if (alignment == 0)
235 continue;
236 layoutStream << "-S" << alignment;
237 continue;
238 }
239 if (key.getValue() == DLTIDialect::kDataLayoutFunctionPointerAlignmentKey) {
240 auto value = cast<FunctionPointerAlignmentAttr>(entry.getValue());
241 uint64_t alignment = value.getAlignment();
242 // Skip the default function pointer alignment.
243 if (alignment == 0)
244 continue;
245 layoutStream << "-F" << (value.getFunctionDependent() ? "n" : "i")
246 << alignment;
247 continue;
248 }
249 if (key.getValue() == DLTIDialect::kDataLayoutLegalIntWidthsKey) {
250 layoutStream << "-n";
251 llvm::interleave(
252 cast<DenseI32ArrayAttr>(entry.getValue()).asArrayRef(), layoutStream,
253 [&](int32_t val) { layoutStream << val; }, ":");
254 continue;
255 }
256 emitError(*loc) << "unsupported data layout key " << key;
257 return failure();
258 }
259
260 // Go through the list of entries to check which types are explicitly
261 // specified in entries. Where possible, data layout queries are used instead
262 // of directly inspecting the entries.
263 for (DataLayoutEntryInterface entry : attribute.getEntries()) {
264 auto type = llvm::dyn_cast_if_present<Type>(entry.getKey());
265 if (!type)
266 continue;
267 // Data layout for the index type is irrelevant at this point.
268 if (isa<IndexType>(type))
269 continue;
270 layoutStream << "-";
271 LogicalResult result =
273 .Case<IntegerType, Float16Type, Float32Type, Float64Type,
274 Float80Type, Float128Type>([&](Type type) -> LogicalResult {
275 if (auto intType = dyn_cast<IntegerType>(type)) {
276 if (intType.getSignedness() != IntegerType::Signless)
277 return emitError(*loc)
278 << "unsupported data layout for non-signless integer "
279 << intType;
280 layoutStream << "i";
281 } else {
282 layoutStream << "f";
283 }
284 uint64_t size = dataLayout.getTypeSizeInBits(type);
285 uint64_t abi = dataLayout.getTypeABIAlignment(type) * 8u;
286 uint64_t preferred =
287 dataLayout.getTypePreferredAlignment(type) * 8u;
288 layoutStream << size << ":" << abi;
289 if (abi != preferred)
290 layoutStream << ":" << preferred;
291 return success();
292 })
293 .Case([&](LLVMPointerType type) {
294 layoutStream << "p" << type.getAddressSpace() << ":";
295 uint64_t size = dataLayout.getTypeSizeInBits(type);
296 uint64_t abi = dataLayout.getTypeABIAlignment(type) * 8u;
297 uint64_t preferred =
298 dataLayout.getTypePreferredAlignment(type) * 8u;
299 uint64_t index = *dataLayout.getTypeIndexBitwidth(type);
300 layoutStream << size << ":" << abi << ":" << preferred << ":"
301 << index;
302 return success();
303 })
304 .Default([loc](Type type) {
305 return emitError(*loc)
306 << "unsupported type in data layout: " << type;
307 });
308 if (failed(result))
309 return failure();
310 }
311 StringRef layoutSpec(llvmDataLayout);
312 layoutSpec.consume_front("-");
313
314 return llvm::DataLayout(layoutSpec);
315}
316
317/// Builds a constant of a sequential LLVM type `type`, potentially containing
318/// other sequential types recursively, from the individual constant values
319/// provided in `constants`. `shape` contains the number of elements in nested
320/// sequential types. Reports errors at `loc` and returns nullptr on error.
321static llvm::Constant *
323 ArrayRef<int64_t> shape, llvm::Type *type,
324 Location loc) {
325 if (shape.empty()) {
326 llvm::Constant *result = constants.front();
327 constants = constants.drop_front();
328 return result;
329 }
330
331 llvm::Type *elementType;
332 if (auto *arrayTy = dyn_cast<llvm::ArrayType>(type)) {
333 elementType = arrayTy->getElementType();
334 } else if (auto *vectorTy = dyn_cast<llvm::VectorType>(type)) {
335 elementType = vectorTy->getElementType();
336 } else {
337 emitError(loc) << "expected sequential LLVM types wrapping a scalar";
338 return nullptr;
339 }
340
342 nested.reserve(shape.front());
343 for (int64_t i = 0; i < shape.front(); ++i) {
344 nested.push_back(buildSequentialConstant(constants, shape.drop_front(),
345 elementType, loc));
346 if (!nested.back())
347 return nullptr;
348 }
349
350 if (shape.size() == 1 && type->isVectorTy())
351 return llvm::ConstantVector::get(nested);
352 return llvm::ConstantArray::get(
353 llvm::ArrayType::get(elementType, shape.front()), nested);
354}
355
356/// Returns the first non-sequential type nested in sequential types.
357static llvm::Type *getInnermostElementType(llvm::Type *type) {
358 do {
359 if (auto *arrayTy = dyn_cast<llvm::ArrayType>(type)) {
360 type = arrayTy->getElementType();
361 } else if (auto *vectorTy = dyn_cast<llvm::VectorType>(type)) {
362 type = vectorTy->getElementType();
363 } else {
364 return type;
365 }
366 } while (true);
367}
368
369/// Convert a dense elements attribute to an LLVM IR constant using its raw data
370/// storage if possible. This supports elements attributes of tensor or vector
371/// type and avoids constructing separate objects for individual values of the
372/// innermost dimension. Constants for other dimensions are still constructed
373/// recursively. Returns null if constructing from raw data is not supported for
374/// this type, e.g., element type is not a power-of-two-sized primitive. Reports
375/// other errors at `loc`.
376static llvm::Constant *
378 llvm::Type *llvmType,
379 const ModuleTranslation &moduleTranslation) {
380 if (!denseElementsAttr)
381 return nullptr;
382
383 llvm::Type *innermostLLVMType = getInnermostElementType(llvmType);
384 if (!llvm::ConstantDataSequential::isElementTypeCompatible(innermostLLVMType))
385 return nullptr;
386
387 ShapedType type = denseElementsAttr.getType();
388 if (type.getNumElements() == 0)
389 return nullptr;
390
391 // Check that the raw data size matches what is expected for the scalar size.
392 // TODO: in theory, we could repack the data here to keep constructing from
393 // raw data.
394 // TODO: we may also need to consider endianness when cross-compiling to an
395 // architecture where it is different.
396 int64_t elementByteSize = denseElementsAttr.getRawData().size() /
397 denseElementsAttr.getNumElements();
398 if (8 * elementByteSize != innermostLLVMType->getScalarSizeInBits())
399 return nullptr;
400
401 // Compute the shape of all dimensions but the innermost. Note that the
402 // innermost dimension may be that of the vector element type.
403 bool hasVectorElementType = isa<VectorType>(type.getElementType());
404 int64_t numAggregates =
405 denseElementsAttr.getNumElements() /
406 (hasVectorElementType ? 1
407 : denseElementsAttr.getType().getShape().back());
408 ArrayRef<int64_t> outerShape = type.getShape();
409 if (!hasVectorElementType)
410 outerShape = outerShape.drop_back();
411
412 // Handle the case of vector splat, LLVM has special support for it.
413 if (denseElementsAttr.isSplat() &&
414 (isa<VectorType>(type) || hasVectorElementType)) {
415 llvm::Constant *splatValue = LLVM::detail::getLLVMConstant(
416 innermostLLVMType, denseElementsAttr.getSplatValue<Attribute>(), loc,
417 moduleTranslation);
418 llvm::Constant *splatVector =
419 llvm::ConstantDataVector::getSplat(0, splatValue);
420 SmallVector<llvm::Constant *> constants(numAggregates, splatVector);
421 ArrayRef<llvm::Constant *> constantsRef = constants;
422 return buildSequentialConstant(constantsRef, outerShape, llvmType, loc);
423 }
424 if (denseElementsAttr.isSplat())
425 return nullptr;
426
427 // In case of non-splat, create a constructor for the innermost constant from
428 // a piece of raw data.
429 std::function<llvm::Constant *(StringRef)> buildCstData;
430 if (isa<TensorType>(type)) {
431 auto vectorElementType = dyn_cast<VectorType>(type.getElementType());
432 if (vectorElementType && vectorElementType.getRank() == 1) {
433 buildCstData = [&](StringRef data) {
434 return llvm::ConstantDataVector::getRaw(
435 data, vectorElementType.getShape().back(), innermostLLVMType);
436 };
437 } else if (!vectorElementType) {
438 buildCstData = [&](StringRef data) {
439 return llvm::ConstantDataArray::getRaw(data, type.getShape().back(),
440 innermostLLVMType);
441 };
442 }
443 } else if (isa<VectorType>(type)) {
444 buildCstData = [&](StringRef data) {
445 return llvm::ConstantDataVector::getRaw(data, type.getShape().back(),
446 innermostLLVMType);
447 };
448 }
449 if (!buildCstData)
450 return nullptr;
451
452 // Create innermost constants and defer to the default constant creation
453 // mechanism for other dimensions.
455 int64_t aggregateSize = denseElementsAttr.getType().getShape().back() *
456 (innermostLLVMType->getScalarSizeInBits() / 8);
457 constants.reserve(numAggregates);
458 for (unsigned i = 0; i < numAggregates; ++i) {
459 StringRef data(denseElementsAttr.getRawData().data() + i * aggregateSize,
460 aggregateSize);
461 constants.push_back(buildCstData(data));
462 }
463
464 ArrayRef<llvm::Constant *> constantsRef = constants;
465 return buildSequentialConstant(constantsRef, outerShape, llvmType, loc);
466}
467
468/// Convert a dense resource elements attribute to an LLVM IR constant using its
469/// raw data storage if possible. This supports elements attributes of tensor or
470/// vector type and avoids constructing separate objects for individual values
471/// of the innermost dimension. Constants for other dimensions are still
472/// constructed recursively. Returns nullptr on failure and emits errors at
473/// `loc`.
474static llvm::Constant *convertDenseResourceElementsAttr(
475 Location loc, DenseResourceElementsAttr denseResourceAttr,
476 llvm::Type *llvmType, const ModuleTranslation &moduleTranslation) {
477 assert(denseResourceAttr && "expected non-null attribute");
478
479 llvm::Type *innermostLLVMType = getInnermostElementType(llvmType);
480 if (!llvm::ConstantDataSequential::isElementTypeCompatible(
481 innermostLLVMType)) {
482 emitError(loc, "no known conversion for innermost element type");
483 return nullptr;
484 }
485
486 ShapedType type = denseResourceAttr.getType();
487 assert(type.getNumElements() > 0 && "Expected non-empty elements attribute");
488
489 AsmResourceBlob *blob = denseResourceAttr.getRawHandle().getBlob();
490 if (!blob) {
491 emitError(loc, "resource does not exist");
492 return nullptr;
493 }
494
495 ArrayRef<char> rawData = blob->getData();
496
497 // Check that the raw data size matches what is expected for the scalar size.
498 // TODO: in theory, we could repack the data here to keep constructing from
499 // raw data.
500 // TODO: we may also need to consider endianness when cross-compiling to an
501 // architecture where it is different.
502 int64_t numElements = denseResourceAttr.getType().getNumElements();
503 int64_t elementByteSize = rawData.size() / numElements;
504 if (8 * elementByteSize != innermostLLVMType->getScalarSizeInBits()) {
505 emitError(loc, "raw data size does not match element type size");
506 return nullptr;
507 }
508
509 // Compute the shape of all dimensions but the innermost. Note that the
510 // innermost dimension may be that of the vector element type.
511 bool hasVectorElementType = isa<VectorType>(type.getElementType());
512 int64_t numAggregates =
513 numElements / (hasVectorElementType
514 ? 1
515 : denseResourceAttr.getType().getShape().back());
516 ArrayRef<int64_t> outerShape = type.getShape();
517 if (!hasVectorElementType)
518 outerShape = outerShape.drop_back();
519
520 // Create a constructor for the innermost constant from a piece of raw data.
521 std::function<llvm::Constant *(StringRef)> buildCstData;
522 if (isa<TensorType>(type)) {
523 auto vectorElementType = dyn_cast<VectorType>(type.getElementType());
524 if (vectorElementType && vectorElementType.getRank() == 1) {
525 buildCstData = [&](StringRef data) {
526 return llvm::ConstantDataVector::getRaw(
527 data, vectorElementType.getShape().back(), innermostLLVMType);
528 };
529 } else if (!vectorElementType) {
530 buildCstData = [&](StringRef data) {
531 return llvm::ConstantDataArray::getRaw(data, type.getShape().back(),
532 innermostLLVMType);
533 };
534 }
535 } else if (isa<VectorType>(type)) {
536 buildCstData = [&](StringRef data) {
537 return llvm::ConstantDataVector::getRaw(data, type.getShape().back(),
538 innermostLLVMType);
539 };
540 }
541 if (!buildCstData) {
542 emitError(loc, "unsupported dense_resource type");
543 return nullptr;
544 }
545
546 // Create innermost constants and defer to the default constant creation
547 // mechanism for other dimensions.
549 int64_t aggregateSize = denseResourceAttr.getType().getShape().back() *
550 (innermostLLVMType->getScalarSizeInBits() / 8);
551 constants.reserve(numAggregates);
552 for (unsigned i = 0; i < numAggregates; ++i) {
553 StringRef data(rawData.data() + i * aggregateSize, aggregateSize);
554 constants.push_back(buildCstData(data));
555 }
556
557 ArrayRef<llvm::Constant *> constantsRef = constants;
558 return buildSequentialConstant(constantsRef, outerShape, llvmType, loc);
559}
560
561/// Create an LLVM IR constant of `llvmType` from the MLIR attribute `attr`.
562/// This currently supports integer, floating point, splat and dense element
563/// attributes and combinations thereof. Also, an array attribute with two
564/// elements is supported to represent a complex constant. In case of error,
565/// report it to `loc` and return nullptr.
567 llvm::Type *llvmType, Attribute attr, Location loc,
568 const ModuleTranslation &moduleTranslation) {
569 if (!attr || isa<UndefAttr>(attr))
570 return llvm::UndefValue::get(llvmType);
571 if (isa<ZeroAttr>(attr))
572 return llvm::Constant::getNullValue(llvmType);
573 if (auto *structType = dyn_cast<::llvm::StructType>(llvmType)) {
574 auto arrayAttr = dyn_cast<ArrayAttr>(attr);
575 if (!arrayAttr) {
576 emitError(loc, "expected an array attribute for a struct constant");
577 return nullptr;
579 SmallVector<llvm::Constant *> structElements;
580 structElements.reserve(structType->getNumElements());
581 for (auto [elemType, elemAttr] :
582 zip_equal(structType->elements(), arrayAttr)) {
583 llvm::Constant *element =
584 getLLVMConstant(elemType, elemAttr, loc, moduleTranslation);
585 if (!element)
586 return nullptr;
587 structElements.push_back(element);
588 }
589 return llvm::ConstantStruct::get(structType, structElements);
590 }
591 // For integer types, we allow a mismatch in sizes as the index type in
592 // MLIR might have a different size than the index type in the LLVM module.
593 if (auto intAttr = dyn_cast<IntegerAttr>(attr)) {
594 // If the attribute is an unsigned integer or a 1-bit integer, zero-extend
595 // the value to the bit width of the LLVM type. Otherwise, sign-extend.
596 auto intTy = dyn_cast<IntegerType>(intAttr.getType());
597 APInt value;
598 if (intTy && (intTy.isUnsigned() || intTy.getWidth() == 1))
599 value = intAttr.getValue().zextOrTrunc(llvmType->getIntegerBitWidth());
600 else
601 value = intAttr.getValue().sextOrTrunc(llvmType->getIntegerBitWidth());
602 return llvm::ConstantInt::get(llvmType, value);
603 }
604 if (auto floatAttr = dyn_cast<FloatAttr>(attr)) {
605 const llvm::fltSemantics &sem = floatAttr.getValue().getSemantics();
606 // Special case for 8-bit floats, which are represented by integers due to
607 // the lack of native fp8 types in LLVM at the moment. Additionally, handle
608 // targets (like AMDGPU) that don't implement bfloat and convert all bfloats
609 // to i16.
610 unsigned floatWidth = APFloat::getSizeInBits(sem);
611 if (llvmType->isIntegerTy(floatWidth))
612 return llvm::ConstantInt::get(llvmType,
613 floatAttr.getValue().bitcastToAPInt());
614 if (llvmType !=
615 llvm::Type::getFloatingPointTy(llvmType->getContext(),
616 floatAttr.getValue().getSemantics())) {
617 emitError(loc, "FloatAttr does not match expected type of the constant");
618 return nullptr;
619 }
620 return llvm::ConstantFP::get(llvmType, floatAttr.getValue());
621 }
622 if (auto symAttr = dyn_cast<FlatSymbolRefAttr>(attr)) {
623 StringRef name = symAttr.getValue();
624 if (llvm::Function *func = moduleTranslation.lookupFunction(name))
625 return llvm::ConstantExpr::getBitCast(func, llvmType);
626 if (llvm::GlobalValue *global = moduleTranslation.lookupGlobal(name))
627 return llvm::ConstantExpr::getBitCast(global, llvmType);
628 emitError(loc, "unknown symbol reference '") << name << "' in constant";
629 return nullptr;
630 }
631 if (auto splatAttr = dyn_cast<SplatElementsAttr>(attr)) {
632 llvm::Type *elementType;
633 uint64_t numElements;
634 bool isScalable = false;
635 if (auto *arrayTy = dyn_cast<llvm::ArrayType>(llvmType)) {
636 elementType = arrayTy->getElementType();
637 numElements = arrayTy->getNumElements();
638 } else if (auto *fVectorTy = dyn_cast<llvm::FixedVectorType>(llvmType)) {
639 elementType = fVectorTy->getElementType();
640 numElements = fVectorTy->getNumElements();
641 } else if (auto *sVectorTy = dyn_cast<llvm::ScalableVectorType>(llvmType)) {
642 elementType = sVectorTy->getElementType();
643 numElements = sVectorTy->getMinNumElements();
644 isScalable = true;
645 } else {
646 llvm_unreachable("unrecognized constant vector type");
647 }
648 // Splat value is a scalar. Extract it only if the element type is not
649 // another sequence type. The recursion terminates because each step removes
650 // one outer sequential type.
651 bool elementTypeSequential =
652 isa<llvm::ArrayType, llvm::VectorType>(elementType);
653 llvm::Constant *child = getLLVMConstant(
654 elementType,
655 elementTypeSequential ? splatAttr
656 : splatAttr.getSplatValue<Attribute>(),
657 loc, moduleTranslation);
658 if (!child)
659 return nullptr;
660 if (llvmType->isVectorTy())
661 return llvm::ConstantVector::getSplat(
662 llvm::ElementCount::get(numElements, /*Scalable=*/isScalable), child);
663 if (llvmType->isArrayTy()) {
664 auto *arrayType = llvm::ArrayType::get(elementType, numElements);
665 if (child->isNullValue() && !elementType->isFPOrFPVectorTy()) {
666 return llvm::ConstantAggregateZero::get(arrayType);
667 }
668 if (llvm::ConstantDataSequential::isElementTypeCompatible(elementType)) {
669 if (isa<llvm::IntegerType>(elementType)) {
670 if (llvm::ConstantInt *ci = dyn_cast<llvm::ConstantInt>(child)) {
671 if (ci->getBitWidth() == 8) {
672 SmallVector<int8_t> constants(numElements, ci->getZExtValue());
673 return llvm::ConstantDataArray::get(elementType->getContext(),
674 constants);
675 }
676 if (ci->getBitWidth() == 16) {
677 SmallVector<int16_t> constants(numElements, ci->getZExtValue());
678 return llvm::ConstantDataArray::get(elementType->getContext(),
679 constants);
680 }
681 if (ci->getBitWidth() == 32) {
682 SmallVector<int32_t> constants(numElements, ci->getZExtValue());
683 return llvm::ConstantDataArray::get(elementType->getContext(),
684 constants);
685 }
686 if (ci->getBitWidth() == 64) {
687 SmallVector<int64_t> constants(numElements, ci->getZExtValue());
688 return llvm::ConstantDataArray::get(elementType->getContext(),
689 constants);
690 }
691 }
692 }
693 if (elementType->isFloatingPointTy()) {
694 if (llvm::ConstantFP *cfp = dyn_cast<llvm::ConstantFP>(child)) {
695 APInt bitPattern = cfp->getValueAPF().bitcastToAPInt();
696 uint64_t value = bitPattern.getZExtValue();
697 // TODO: This code only handles 16, 32, and 64 bit floats. Handle
698 // all compatible types, fp8, fp4, etc.
699 if (bitPattern.getBitWidth() == 16) {
700 SmallVector<uint16_t> constants(numElements, value);
701 return llvm::ConstantDataArray::getFP(elementType, constants);
702 }
703 if (bitPattern.getBitWidth() == 32) {
704 SmallVector<uint32_t> constants(numElements, value);
705 return llvm::ConstantDataArray::getFP(elementType, constants);
706 }
707 if (bitPattern.getBitWidth() == 64) {
708 SmallVector<uint64_t> constants(numElements, value);
709 return llvm::ConstantDataArray::getFP(elementType, constants);
710 }
711 }
712 }
713 }
714 // std::vector is used here to accomodate large number of elements that
715 // exceed SmallVector capacity.
716 std::vector<llvm::Constant *> constants(numElements, child);
717 return llvm::ConstantArray::get(arrayType, constants);
718 }
719 }
720
721 // Try using raw elements data if possible.
722 if (llvm::Constant *result =
723 convertDenseElementsAttr(loc, dyn_cast<DenseElementsAttr>(attr),
724 llvmType, moduleTranslation)) {
725 return result;
726 }
727
728 if (auto denseResourceAttr = dyn_cast<DenseResourceElementsAttr>(attr)) {
729 return convertDenseResourceElementsAttr(loc, denseResourceAttr, llvmType,
730 moduleTranslation);
731 }
732
733 // Fall back to element-by-element construction otherwise.
734 if (auto elementsAttr = dyn_cast<ElementsAttr>(attr)) {
735 assert(elementsAttr.getShapedType().hasStaticShape());
736 assert(!elementsAttr.getShapedType().getShape().empty() &&
737 "unexpected empty elements attribute shape");
738
739 SmallVector<llvm::Constant *, 8> constants;
740 constants.reserve(elementsAttr.getNumElements());
741 llvm::Type *innermostType = getInnermostElementType(llvmType);
742 for (auto n : elementsAttr.getValues<Attribute>()) {
743 constants.push_back(
744 getLLVMConstant(innermostType, n, loc, moduleTranslation));
745 if (!constants.back())
746 return nullptr;
747 }
748 ArrayRef<llvm::Constant *> constantsRef = constants;
749 llvm::Constant *result = buildSequentialConstant(
750 constantsRef, elementsAttr.getShapedType().getShape(), llvmType, loc);
751 assert(constantsRef.empty() && "did not consume all elemental constants");
752 return result;
753 }
754
755 if (auto stringAttr = dyn_cast<StringAttr>(attr)) {
756 return llvm::ConstantDataArray::get(moduleTranslation.getLLVMContext(),
757 ArrayRef<char>{stringAttr.getValue()});
758 }
759
760 // Handle arrays of structs that cannot be represented as DenseElementsAttr
761 // in MLIR.
762 if (auto arrayAttr = dyn_cast<ArrayAttr>(attr)) {
763 if (auto *arrayTy = dyn_cast<llvm::ArrayType>(llvmType)) {
764 llvm::Type *elementType = arrayTy->getElementType();
765 Attribute previousElementAttr;
766 llvm::Constant *elementCst = nullptr;
767 SmallVector<llvm::Constant *> constants;
768 constants.reserve(arrayTy->getNumElements());
769 for (Attribute elementAttr : arrayAttr) {
770 // Arrays with a single value or with repeating values are quite common.
771 // Short-circuit the translation when the element value is the same as
772 // the previous one.
773 if (!previousElementAttr || previousElementAttr != elementAttr) {
774 previousElementAttr = elementAttr;
775 elementCst =
776 getLLVMConstant(elementType, elementAttr, loc, moduleTranslation);
777 if (!elementCst)
778 return nullptr;
779 }
780 constants.push_back(elementCst);
781 }
782 return llvm::ConstantArray::get(arrayTy, constants);
783 }
784 }
785
786 emitError(loc, "unsupported constant value");
787 return nullptr;
788}
789
790ModuleTranslation::ModuleTranslation(Operation *module,
791 std::unique_ptr<llvm::Module> llvmModule,
792 llvm::vfs::FileSystem *fs)
793 : mlirModule(module), llvmModule(std::move(llvmModule)),
794 debugTranslation(
795 std::make_unique<DebugTranslation>(module, *this->llvmModule)),
796 loopAnnotationTranslation(std::make_unique<LoopAnnotationTranslation>(
797 *this, *this->llvmModule)),
798 fileSystem(fs), typeTranslator(this->llvmModule->getContext()),
799 iface(module->getContext()) {
800 assert(satisfiesLLVMModule(mlirModule) &&
801 "mlirModule should honor LLVM's module semantics.");
802}
803
804ModuleTranslation::~ModuleTranslation() {
805 if (ompBuilder && !ompBuilder->isFinalized())
806 ompBuilder->finalize();
807}
808
810 SmallVector<Region *> toProcess;
811 toProcess.push_back(&region);
812 while (!toProcess.empty()) {
813 Region *current = toProcess.pop_back_val();
814 for (Block &block : *current) {
815 blockMapping.erase(&block);
816 for (Value arg : block.getArguments())
817 valueMapping.erase(arg);
818 for (Operation &op : block) {
819 for (Value value : op.getResults())
820 valueMapping.erase(value);
821 if (op.hasSuccessors())
822 branchMapping.erase(&op);
823 if (isa<LLVM::GlobalOp>(op))
824 globalsMapping.erase(&op);
825 if (isa<LLVM::AliasOp>(op))
826 aliasesMapping.erase(&op);
827 if (isa<LLVM::IFuncOp>(op))
828 ifuncMapping.erase(&op);
829 if (isa<LLVM::CallOp>(op))
830 callMapping.erase(&op);
831 llvm::append_range(
832 toProcess,
833 llvm::map_range(op.getRegions(), [](Region &r) { return &r; }));
834 }
835 }
836 }
837}
838
839/// Get the SSA value passed to the current block from the terminator operation
840/// of its predecessor.
841static Value getPHISourceValue(Block *current, Block *pred,
842 unsigned numArguments, unsigned index) {
843 Operation &terminator = *pred->getTerminator();
844 if (isa<LLVM::BrOp>(terminator))
845 return terminator.getOperand(index);
846
847#ifndef NDEBUG
848 llvm::SmallPtrSet<Block *, 4> seenSuccessors;
849 for (unsigned i = 0, e = terminator.getNumSuccessors(); i < e; ++i) {
850 Block *successor = terminator.getSuccessor(i);
851 auto branch = cast<BranchOpInterface>(terminator);
852 SuccessorOperands successorOperands = branch.getSuccessorOperands(i);
853 assert(
854 (!seenSuccessors.contains(successor) || successorOperands.empty()) &&
855 "successors with arguments in LLVM branches must be different blocks");
856 seenSuccessors.insert(successor);
857 }
858#endif
859
860 // For instructions that branch based on a condition value, we need to take
861 // the operands for the branch that was taken.
862 if (auto condBranchOp = dyn_cast<LLVM::CondBrOp>(terminator)) {
863 // For conditional branches, we take the operands from either the "true" or
864 // the "false" branch.
865 return condBranchOp.getSuccessor(0) == current
866 ? condBranchOp.getTrueDestOperands()[index]
867 : condBranchOp.getFalseDestOperands()[index];
868 }
869
870 if (auto switchOp = dyn_cast<LLVM::SwitchOp>(terminator)) {
871 // For switches, we take the operands from either the default case, or from
872 // the case branch that was taken.
873 if (switchOp.getDefaultDestination() == current)
874 return switchOp.getDefaultOperands()[index];
875 for (const auto &i : llvm::enumerate(switchOp.getCaseDestinations()))
876 if (i.value() == current)
877 return switchOp.getCaseOperands(i.index())[index];
878 }
879
880 if (auto indBrOp = dyn_cast<LLVM::IndirectBrOp>(terminator)) {
881 // For indirect branches we take operands for each successor.
882 for (const auto &i : llvm::enumerate(indBrOp->getSuccessors())) {
883 if (indBrOp->getSuccessor(i.index()) == current)
884 return indBrOp.getSuccessorOperands(i.index())[index];
885 }
886 }
887
888 if (auto invokeOp = dyn_cast<LLVM::InvokeOp>(terminator)) {
889 return invokeOp.getNormalDest() == current
890 ? invokeOp.getNormalDestOperands()[index]
891 : invokeOp.getUnwindDestOperands()[index];
892 }
893
894 llvm_unreachable(
895 "only branch, switch or invoke operations can be terminators "
896 "of a block that has successors");
897}
898
899/// Connect the PHI nodes to the results of preceding blocks.
901 const ModuleTranslation &state) {
902 // Skip the first block, it cannot be branched to and its arguments correspond
903 // to the arguments of the LLVM function.
904 for (Block &bb : llvm::drop_begin(region)) {
905 llvm::BasicBlock *llvmBB = state.lookupBlock(&bb);
906 auto phis = llvmBB->phis();
907 auto numArguments = bb.getNumArguments();
908 assert(numArguments == std::distance(phis.begin(), phis.end()));
909 for (auto [index, phiNode] : llvm::enumerate(phis)) {
910 for (auto *pred : bb.getPredecessors()) {
911 // Find the LLVM IR block that contains the converted terminator
912 // instruction and use it in the PHI node. Note that this block is not
913 // necessarily the same as state.lookupBlock(pred), some operations
914 // (in particular, OpenMP operations using OpenMPIRBuilder) may have
915 // split the blocks.
916 llvm::Instruction *terminator =
917 state.lookupBranch(pred->getTerminator());
918 assert(terminator && "missing the mapping for a terminator");
919 phiNode.addIncoming(state.lookupValue(getPHISourceValue(
920 &bb, pred, numArguments, index)),
921 terminator->getParent());
922 }
923 }
924 }
925}
926
928 llvm::IRBuilderBase &builder, llvm::Intrinsic::ID intrinsic,
930 return builder.CreateIntrinsicWithoutFolding(intrinsic, tys, args);
931}
932
934 llvm::IRBuilderBase &builder, llvm::Intrinsic::ID intrinsic,
935 llvm::Type *retTy, ArrayRef<llvm::Value *> args) {
936 return builder.CreateIntrinsicWithoutFolding(retTy, intrinsic, args);
937}
938
940 llvm::IRBuilderBase &builder, ModuleTranslation &moduleTranslation,
941 Operation *intrOp, llvm::Intrinsic::ID intrinsic, unsigned numResults,
942 ArrayRef<unsigned> overloadedResults, ArrayRef<unsigned> overloadedOperands,
943 ArrayRef<unsigned> immArgPositions,
944 ArrayRef<StringLiteral> immArgAttrNames) {
945 assert(immArgPositions.size() == immArgAttrNames.size() &&
946 "LLVM `immArgPositions` and MLIR `immArgAttrNames` should have equal "
947 "length");
948
950 size_t numOpBundleOperands = 0;
951 auto opBundleSizesAttr = cast_if_present<DenseI32ArrayAttr>(
952 intrOp->getAttr(LLVMDialect::getOpBundleSizesAttrName()));
953 auto opBundleTagsAttr = cast_if_present<ArrayAttr>(
954 intrOp->getAttr(LLVMDialect::getOpBundleTagsAttrName()));
955
956 if (opBundleSizesAttr && opBundleTagsAttr) {
957 ArrayRef<int> opBundleSizes = opBundleSizesAttr.asArrayRef();
958 assert(opBundleSizes.size() == opBundleTagsAttr.size() &&
959 "operand bundles and tags do not match");
960
961 numOpBundleOperands = llvm::sum_of(opBundleSizes);
962 assert(numOpBundleOperands <= intrOp->getNumOperands() &&
963 "operand bundle operands is more than the number of operands");
964
965 ValueRange operands = intrOp->getOperands().take_back(numOpBundleOperands);
966 size_t nextOperandIdx = 0;
967 opBundles.reserve(opBundleSizesAttr.size());
968
969 for (auto [opBundleTagAttr, bundleSize] :
970 llvm::zip(opBundleTagsAttr, opBundleSizes)) {
971 auto bundleTag = cast<StringAttr>(opBundleTagAttr).str();
972 auto bundleOperands = moduleTranslation.lookupValues(
973 operands.slice(nextOperandIdx, bundleSize));
974 opBundles.emplace_back(std::move(bundleTag), std::move(bundleOperands));
975 nextOperandIdx += bundleSize;
976 }
977 }
978
979 // Map operands and attributes to LLVM values.
980 auto opOperands = intrOp->getOperands().drop_back(numOpBundleOperands);
981 auto operands = moduleTranslation.lookupValues(opOperands);
982 SmallVector<llvm::Value *> args(immArgPositions.size() + operands.size());
983 for (auto [immArgPos, immArgName] :
984 llvm::zip(immArgPositions, immArgAttrNames)) {
985 Attribute attr = intrOp->getAttr(immArgName);
986 if (auto intrinsicIntegerAttr =
987 dyn_cast<LLVM::IntrinsicIntegerAttrInterface>(attr))
988 attr = intrinsicIntegerAttr.getIntegerAttr();
989 auto typedAttr = llvm::cast<TypedAttr>(attr);
990 assert(typedAttr.getType().isIntOrFloat() &&
991 "expected int or float immarg");
992 auto *type = moduleTranslation.convertType(typedAttr.getType());
993 args[immArgPos] = LLVM::detail::getLLVMConstant(
994 type, typedAttr, intrOp->getLoc(), moduleTranslation);
995 }
996 unsigned opArg = 0;
997 for (auto &arg : args) {
998 if (!arg)
999 arg = operands[opArg++];
1000 }
1001
1002 // Resolve overloaded intrinsic declaration.
1003 SmallVector<llvm::Type *> overloadedTypes;
1004 for (unsigned overloadedResultIdx : overloadedResults) {
1005 if (numResults > 1) {
1006 // More than one result is mapped to an LLVM struct.
1007 overloadedTypes.push_back(moduleTranslation.convertType(
1008 llvm::cast<LLVM::LLVMStructType>(intrOp->getResult(0).getType())
1009 .getBody()[overloadedResultIdx]));
1010 } else {
1011 overloadedTypes.push_back(
1012 moduleTranslation.convertType(intrOp->getResult(0).getType()));
1013 }
1014 }
1015 for (unsigned overloadedOperandIdx : overloadedOperands)
1016 overloadedTypes.push_back(args[overloadedOperandIdx]->getType());
1017 llvm::Module *module = builder.GetInsertBlock()->getModule();
1018 llvm::Function *llvmIntr = llvm::Intrinsic::getOrInsertDeclaration(
1019 module, intrinsic, overloadedTypes);
1020
1021 return builder.CreateCall(llvmIntr, args, opBundles);
1022}
1023
1024/// Given a single MLIR operation, create the corresponding LLVM IR operation
1025/// using the `builder`.
1026LogicalResult ModuleTranslation::convertOperationImpl(
1027 Operation &op, llvm::IRBuilderBase &builder, bool recordInsertions) {
1028 const LLVMTranslationDialectInterface *opIface = iface.getInterfaceFor(&op);
1029 if (!opIface)
1030 return op.emitError("cannot be converted to LLVM IR: missing "
1031 "`LLVMTranslationDialectInterface` registration for "
1032 "dialect for op: ")
1033 << op.getName();
1034
1035 InstructionCapturingInserter::CollectionScope scope(builder,
1036 recordInsertions);
1037 if (failed(opIface->convertOperation(&op, builder, *this)))
1038 return op.emitError("LLVM Translation failed for operation: ")
1039 << op.getName();
1040
1041 return convertDialectAttributes(&op, scope.getCapturedInstructions());
1042}
1043
1044/// Convert block to LLVM IR. Unless `ignoreArguments` is set, emit PHI nodes
1045/// to define values corresponding to the MLIR block arguments. These nodes
1046/// are not connected to the source basic blocks, which may not exist yet. Uses
1047/// `builder` to construct the LLVM IR. Expects the LLVM IR basic block to have
1048/// been created for `bb` and included in the block mapping. Inserts new
1049/// instructions at the end of the block and leaves `builder` in a state
1050/// suitable for further insertion into the end of the block.
1051LogicalResult ModuleTranslation::convertBlockImpl(Block &bb,
1052 bool ignoreArguments,
1053 llvm::IRBuilderBase &builder,
1054 bool recordInsertions) {
1055 builder.SetInsertPoint(lookupBlock(&bb));
1056 auto *subprogram = builder.GetInsertBlock()->getParent()->getSubprogram();
1057
1058 // Before traversing operations, make block arguments available through
1059 // value remapping and PHI nodes, but do not add incoming edges for the PHI
1060 // nodes just yet: those values may be defined by this or following blocks.
1061 // This step is omitted if "ignoreArguments" is set. The arguments of the
1062 // first block have been already made available through the remapping of
1063 // LLVM function arguments.
1064 if (!ignoreArguments) {
1065 auto predecessors = bb.getPredecessors();
1066 unsigned numPredecessors =
1067 std::distance(predecessors.begin(), predecessors.end());
1068 for (auto arg : bb.getArguments()) {
1069 auto wrappedType = arg.getType();
1070 if (!isCompatibleType(wrappedType))
1071 return emitError(bb.front().getLoc(),
1072 "block argument does not have an LLVM type");
1073 builder.SetCurrentDebugLocation(
1074 debugTranslation->translateLoc(arg.getLoc(), subprogram));
1075 llvm::Type *type = convertType(wrappedType);
1076 llvm::PHINode *phi = builder.CreatePHI(type, numPredecessors);
1077 mapValue(arg, phi);
1078 }
1079 }
1080
1081 // Traverse operations.
1082 for (auto &op : bb) {
1083 // Set the current debug location within the builder.
1084 builder.SetCurrentDebugLocation(
1085 debugTranslation->translateLoc(op.getLoc(), subprogram));
1086
1087 if (failed(convertOperationImpl(op, builder, recordInsertions)))
1088 return failure();
1089
1090 // Set the branch weight metadata on the translated instruction.
1091 if (auto iface = dyn_cast<WeightedBranchOpInterface>(op))
1093 }
1094
1095 return success();
1096}
1097
1098/// A helper method to get the single Block in an operation honoring LLVM's
1099/// module requirements.
1101 return module->getRegion(0).front();
1102}
1103
1104/// A helper method to decide if a constant must not be set as a global variable
1105/// initializer. For an external linkage variable, the variable with an
1106/// initializer is considered externally visible and defined in this module, the
1107/// variable without an initializer is externally available and is defined
1108/// elsewhere.
1109static bool shouldDropGlobalInitializer(llvm::GlobalValue::LinkageTypes linkage,
1110 llvm::Constant *cst) {
1111 return (linkage == llvm::GlobalVariable::ExternalLinkage && !cst) ||
1112 linkage == llvm::GlobalVariable::ExternalWeakLinkage;
1113}
1114
1115/// Sets the runtime preemption specifier of `gv` to dso_local if
1116/// `dsoLocalRequested` is true, otherwise it is left unchanged.
1117static void addRuntimePreemptionSpecifier(bool dsoLocalRequested,
1118 llvm::GlobalValue *gv) {
1119 if (dsoLocalRequested)
1120 gv->setDSOLocal(true);
1121}
1122
1123/// Attempts to translate an MLIR attribute identified by `key`, optionally with
1124/// the given `value`, into an LLVM IR attribute. Reports errors at `loc` if
1125/// any. If the attribute name corresponds to a known LLVM IR attribute kind,
1126/// creates the LLVM attribute of that kind; otherwise, keeps it as a string
1127/// attribute. Performs additional checks for attributes known to have or not
1128/// have a value in order to avoid assertions inside LLVM upon construction.
1129static FailureOr<llvm::Attribute>
1130convertMLIRAttributeToLLVM(Location loc, llvm::LLVMContext &ctx, StringRef key,
1131 StringRef value = StringRef()) {
1132 auto kind = llvm::Attribute::getAttrKindFromName(key);
1133 if (kind == llvm::Attribute::None)
1134 return llvm::Attribute::get(ctx, key, value);
1135
1136 if (llvm::Attribute::isIntAttrKind(kind)) {
1137 if (value.empty())
1138 return emitError(loc) << "LLVM attribute '" << key << "' expects a value";
1139
1141 if (!value.getAsInteger(/*Radix=*/0, result))
1142 return llvm::Attribute::get(ctx, kind, result);
1143 return llvm::Attribute::get(ctx, key, value);
1144 }
1145
1146 if (!value.empty())
1147 return emitError(loc) << "LLVM attribute '" << key
1148 << "' does not expect a value, found '" << value
1149 << "'";
1150
1151 return llvm::Attribute::get(ctx, kind);
1152}
1153
1154/// Converts the MLIR attributes listed in the given array attribute into LLVM
1155/// attributes. Returns an `AttrBuilder` containing the converted attributes.
1156/// Reports error to `loc` if any and returns immediately. Expects `arrayAttr`
1157/// to contain either string attributes, treated as value-less LLVM attributes,
1158/// or array attributes containing two string attributes, with the first string
1159/// being the name of the corresponding LLVM attribute and the second string
1160/// beings its value. Note that even integer attributes are expected to have
1161/// their values expressed as strings.
1162static FailureOr<llvm::AttrBuilder>
1163convertMLIRAttributesToLLVM(Location loc, llvm::LLVMContext &ctx,
1164 ArrayAttr arrayAttr, StringRef arrayAttrName) {
1165 llvm::AttrBuilder attrBuilder(ctx);
1166 if (!arrayAttr)
1167 return attrBuilder;
1168
1169 for (Attribute attr : arrayAttr) {
1170 if (auto stringAttr = dyn_cast<StringAttr>(attr)) {
1171 FailureOr<llvm::Attribute> llvmAttr =
1172 convertMLIRAttributeToLLVM(loc, ctx, stringAttr.getValue());
1173 if (failed(llvmAttr))
1174 return failure();
1175 attrBuilder.addAttribute(*llvmAttr);
1176 continue;
1177 }
1178
1179 auto arrayAttr = dyn_cast<ArrayAttr>(attr);
1180 if (!arrayAttr || arrayAttr.size() != 2)
1181 return emitError(loc) << "expected '" << arrayAttrName
1182 << "' to contain string or array attributes";
1183
1184 auto keyAttr = dyn_cast<StringAttr>(arrayAttr[0]);
1185 auto valueAttr = dyn_cast<StringAttr>(arrayAttr[1]);
1186 if (!keyAttr || !valueAttr)
1187 return emitError(loc) << "expected arrays within '" << arrayAttrName
1188 << "' to contain two strings";
1189
1190 FailureOr<llvm::Attribute> llvmAttr = convertMLIRAttributeToLLVM(
1191 loc, ctx, keyAttr.getValue(), valueAttr.getValue());
1192 if (failed(llvmAttr))
1193 return failure();
1194 attrBuilder.addAttribute(*llvmAttr);
1195 }
1196
1197 return attrBuilder;
1198}
1199
1200LogicalResult ModuleTranslation::convertGlobalsAndAliases() {
1201 // Mapping from compile unit to its respective set of global variables.
1203 // Mapping from subprogram to its respective set of static local variables.
1205
1206 // First, create all global variables and global aliases in LLVM IR. A global
1207 // or alias body may refer to another global/alias or itself, so all the
1208 // mapping needs to happen prior to body conversion.
1209
1210 // Create all llvm::GlobalVariable
1211 for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) {
1212 llvm::Type *type = convertType(op.getType());
1213 llvm::Constant *cst = nullptr;
1214 const bool deferValueAttrToPass2 = op.getValueOrNull() &&
1215 !op.getInitializerBlock() &&
1216 !isa<StringAttr>(op.getValueOrNull());
1217 if (op.getValueOrNull() && !deferValueAttrToPass2) {
1218 // String attributes are treated separately because they cannot appear as
1219 // in-function constants and are thus not supported by getLLVMConstant.
1220 if (auto strAttr = dyn_cast_or_null<StringAttr>(op.getValueOrNull())) {
1221 cst = llvm::ConstantDataArray::getString(
1222 llvmModule->getContext(), strAttr.getValue(), /*AddNull=*/false);
1223 type = cst->getType();
1224 }
1225 }
1226
1227 auto linkage = convertLinkageToLLVM(op.getLinkage());
1228
1229 // LLVM IR requires constant with linkage other than external or weak
1230 // external to have initializers. If MLIR does not provide an initializer,
1231 // default to undef.
1232 bool dropInitializer = shouldDropGlobalInitializer(linkage, cst);
1233 if (!deferValueAttrToPass2) {
1234 if (!dropInitializer && !cst)
1235 cst = llvm::UndefValue::get(type);
1236 else if (dropInitializer && cst)
1237 cst = nullptr;
1238 } else {
1239 cst = nullptr;
1240 }
1241
1242 auto *var = new llvm::GlobalVariable(
1243 *llvmModule, type, op.getConstant(), linkage, cst, op.getSymName(),
1244 /*InsertBefore=*/nullptr,
1245 op.getThreadLocal_() ? llvm::GlobalValue::GeneralDynamicTLSModel
1246 : llvm::GlobalValue::NotThreadLocal,
1247 op.getAddrSpace(), op.getExternallyInitialized());
1248
1249 if (std::optional<mlir::SymbolRefAttr> comdat = op.getComdat()) {
1250 auto selectorOp = cast<ComdatSelectorOp>(
1252 var->setComdat(comdatMapping.lookup(selectorOp));
1253 }
1254
1255 if (op.getUnnamedAddr().has_value())
1256 var->setUnnamedAddr(convertUnnamedAddrToLLVM(*op.getUnnamedAddr()));
1257
1258 if (op.getSection().has_value())
1259 var->setSection(*op.getSection());
1260
1261 addRuntimePreemptionSpecifier(op.getDsoLocal(), var);
1262
1263 std::optional<uint64_t> alignment = op.getAlignment();
1264 if (alignment.has_value())
1265 var->setAlignment(llvm::MaybeAlign(alignment.value()));
1266
1267 var->setVisibility(convertVisibilityToLLVM(op.getVisibility_()));
1268
1269 globalsMapping.try_emplace(op, var);
1270 globalsByNameMapping.try_emplace(op.getSymName(), var);
1271
1272 // Add debug information if present.
1273 if (op.getDbgExprs()) {
1274 for (auto exprAttr :
1275 op.getDbgExprs()->getAsRange<DIGlobalVariableExpressionAttr>()) {
1276 llvm::DIGlobalVariableExpression *diGlobalExpr =
1277 debugTranslation->translateGlobalVariableExpression(exprAttr);
1278 llvm::DIGlobalVariable *diGlobalVar = diGlobalExpr->getVariable();
1279 var->addDebugInfo(diGlobalExpr);
1280
1281 // There is no `globals` field in DICompileUnitAttr which can be
1282 // directly assigned to DICompileUnit. We have to build the list by
1283 // looking at the dbgExpr of all the GlobalOps. The scope of the
1284 // variable is used to get the DICompileUnit in which to add it. But
1285 // there are cases where the scope of a global does not directly point
1286 // to the DICompileUnit and we have to do a bit more work to get to
1287 // it. Some of those cases are:
1288 //
1289 // 1. For the languages that support modules, the scope hierarchy can
1290 // be variable -> DIModule -> DICompileUnit
1291 //
1292 // 2. For the Fortran common block variable, the scope hierarchy can
1293 // be variable -> DICommonBlock -> DISubprogram -> DICompileUnit
1294 //
1295 // 3. For entities like static local variables in C or variable with
1296 // SAVE attribute in Fortran, the scope hierarchy can be
1297 // variable (-> DILocalScope)* -> DISubprogram
1298 llvm::DIScope *scope = diGlobalVar->getScope();
1299 if (auto *mod = dyn_cast_if_present<llvm::DIModule>(scope))
1300 scope = mod->getScope();
1301 else if (auto *cb = dyn_cast_if_present<llvm::DICommonBlock>(scope)) {
1302 if (auto *sp =
1303 dyn_cast_if_present<llvm::DISubprogram>(cb->getScope()))
1304 scope = sp->getUnit();
1305 } else if (auto *lbb =
1306 dyn_cast_if_present<llvm::DILexicalBlockBase>(scope)) {
1307 scope = lbb->getSubprogram();
1308 }
1309
1310 // Get the compile unit (scope) of the the global variable, or the
1311 // subprogram of the static local variable.
1312 if (llvm::DICompileUnit *compileUnit =
1313 dyn_cast_if_present<llvm::DICompileUnit>(scope)) {
1314 // Update the compile unit with this incoming global variable
1315 // expression during the finalizing step later.
1316 globalGVars[compileUnit].push_back(diGlobalExpr);
1317 } else if (llvm::DISubprogram *sp =
1318 dyn_cast_if_present<llvm::DISubprogram>(scope)) {
1319 // Update the subprogram with this incoming static local variable
1320 // expression during the finalizing step later.
1321 staticLocals[sp].push_back(diGlobalExpr);
1322 }
1323 }
1324 }
1325
1326 // Forward the target-specific attributes to LLVM.
1327 FailureOr<llvm::AttrBuilder> convertedTargetSpecificAttrs =
1329 op.getTargetSpecificAttrsAttr(),
1330 op.getTargetSpecificAttrsAttrName());
1331 if (failed(convertedTargetSpecificAttrs))
1332 return failure();
1333 var->addAttributes(*convertedTargetSpecificAttrs);
1334 }
1335
1336 // Value-attribute initializers may reference other globals by symbol name.
1337 // Register every global above before materializing those constants.
1338 for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) {
1339 if (!op.getValueOrNull() || op.getInitializerBlock() ||
1340 isa<StringAttr>(op.getValueOrNull()))
1341 continue;
1342
1343 llvm::Type *type = convertType(op.getType());
1344 llvm::Constant *cst =
1345 getLLVMConstant(type, op.getValueOrNull(), op.getLoc(), *this);
1346 if (!cst)
1347 return failure();
1348
1349 auto linkage = convertLinkageToLLVM(op.getLinkage());
1350 bool dropInitializer = shouldDropGlobalInitializer(linkage, cst);
1351 auto *var = cast<llvm::GlobalVariable>(lookupGlobal(op));
1352 if (dropInitializer)
1353 var->setInitializer(nullptr);
1354 else
1355 var->setInitializer(cst);
1356 }
1357
1358 // Create all llvm::GlobalAlias
1359 for (auto op : getModuleBody(mlirModule).getOps<LLVM::AliasOp>()) {
1360 llvm::Type *type = convertType(op.getType());
1361 llvm::Constant *cst = nullptr;
1362 llvm::GlobalValue::LinkageTypes linkage =
1363 convertLinkageToLLVM(op.getLinkage());
1364 llvm::Module &llvmMod = *llvmModule;
1365
1366 // Note address space and aliasee info isn't set just yet.
1367 llvm::GlobalAlias *var = llvm::GlobalAlias::create(
1368 type, op.getAddrSpace(), linkage, op.getSymName(), /*placeholder*/ cst,
1369 &llvmMod);
1370
1371 var->setThreadLocalMode(op.getThreadLocal_()
1372 ? llvm::GlobalAlias::GeneralDynamicTLSModel
1373 : llvm::GlobalAlias::NotThreadLocal);
1374
1375 // Note there is no need to setup the comdat because GlobalAlias calls into
1376 // the aliasee comdat information automatically.
1377
1378 if (op.getUnnamedAddr().has_value())
1379 var->setUnnamedAddr(convertUnnamedAddrToLLVM(*op.getUnnamedAddr()));
1380
1381 var->setVisibility(convertVisibilityToLLVM(op.getVisibility_()));
1382
1383 aliasesMapping.try_emplace(op, var);
1384 }
1385
1386 // Convert global variable bodies.
1387 for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) {
1388 if (Block *initializer = op.getInitializerBlock()) {
1389 llvm::IRBuilder<llvm::TargetFolder> builder(
1390 llvmModule->getContext(),
1391 llvm::TargetFolder(llvmModule->getDataLayout()));
1392
1393 [[maybe_unused]] int numConstantsHit = 0;
1394 [[maybe_unused]] int numConstantsErased = 0;
1395 DenseMap<llvm::ConstantAggregate *, int> constantAggregateUseMap;
1396
1397 for (auto &op : initializer->without_terminator()) {
1398 if (failed(convertOperation(op, builder)))
1399 return emitError(op.getLoc(), "fail to convert global initializer");
1400 auto *cst = dyn_cast<llvm::Constant>(lookupValue(op.getResult(0)));
1401 if (!cst)
1402 return emitError(op.getLoc(), "unemittable constant value");
1403
1404 // When emitting an LLVM constant, a new constant is created and the old
1405 // constant may become dangling and take space. We should remove the
1406 // dangling constants to avoid memory explosion especially for constant
1407 // arrays whose number of elements is large.
1408 // Because multiple operations may refer to the same constant, we need
1409 // to count the number of uses of each constant array and remove it only
1410 // when the count becomes zero.
1411 if (auto *agg = dyn_cast<llvm::ConstantAggregate>(cst)) {
1412 numConstantsHit++;
1413 Value result = op.getResult(0);
1414 int numUsers = std::distance(result.use_begin(), result.use_end());
1415 auto [iterator, inserted] =
1416 constantAggregateUseMap.try_emplace(agg, numUsers);
1417 if (!inserted) {
1418 // Key already exists, update the value
1419 iterator->second += numUsers;
1420 }
1421 }
1422 // Scan the operands of the operation to decrement the use count of
1423 // constants. Erase the constant if the use count becomes zero.
1424 for (Value v : op.getOperands()) {
1425 auto *cst = dyn_cast<llvm::ConstantAggregate>(lookupValue(v));
1426 if (!cst)
1427 continue;
1428 auto iter = constantAggregateUseMap.find(cst);
1429 assert(iter != constantAggregateUseMap.end() && "constant not found");
1430 iter->second--;
1431 if (iter->second == 0) {
1432 // NOTE: cannot call removeDeadConstantUsers() here because it
1433 // may remove the constant which has uses not be converted yet.
1434 if (cst->user_empty()) {
1435 cst->destroyConstant();
1436 numConstantsErased++;
1437 }
1438 constantAggregateUseMap.erase(iter);
1439 }
1440 }
1441 }
1442
1443 ReturnOp ret = cast<ReturnOp>(initializer->getTerminator());
1444 llvm::Constant *cst =
1445 cast<llvm::Constant>(lookupValue(ret.getOperand(0)));
1446 auto *global = cast<llvm::GlobalVariable>(lookupGlobal(op));
1447 if (!shouldDropGlobalInitializer(global->getLinkage(), cst))
1448 global->setInitializer(cst);
1449
1450 // Try to remove the dangling constants again after all operations are
1451 // converted.
1452 for (auto it : constantAggregateUseMap) {
1453 auto *cst = it.first;
1454 cst->removeDeadConstantUsers();
1455 if (cst->user_empty()) {
1456 cst->destroyConstant();
1457 numConstantsErased++;
1458 }
1459 }
1460
1461 LLVM_DEBUG(llvm::dbgs()
1462 << "Convert initializer for " << op.getName() << "\n";
1463 llvm::dbgs() << numConstantsHit << " new constants hit\n";
1464 llvm::dbgs()
1465 << numConstantsErased << " dangling constants erased\n";);
1466 }
1467 }
1468
1469 // Convert llvm.mlir.global_ctors and dtors.
1470 for (Operation &op : getModuleBody(mlirModule)) {
1471 auto ctorOp = dyn_cast<GlobalCtorsOp>(op);
1472 auto dtorOp = dyn_cast<GlobalDtorsOp>(op);
1473 if (!ctorOp && !dtorOp)
1474 continue;
1475
1476 // The empty / zero initialized version of llvm.global_(c|d)tors cannot be
1477 // handled by appendGlobalFn logic below, which just ignores empty (c|d)tor
1478 // lists. Make sure it gets emitted.
1479 if ((ctorOp && ctorOp.getCtors().empty()) ||
1480 (dtorOp && dtorOp.getDtors().empty())) {
1481 llvm::IRBuilder<llvm::TargetFolder> builder(
1482 llvmModule->getContext(),
1483 llvm::TargetFolder(llvmModule->getDataLayout()));
1484 llvm::Type *eltTy = llvm::StructType::get(
1485 builder.getInt32Ty(), builder.getPtrTy(), builder.getPtrTy());
1486 llvm::ArrayType *at = llvm::ArrayType::get(eltTy, 0);
1487 llvm::Constant *zeroInit = llvm::Constant::getNullValue(at);
1488 (void)new llvm::GlobalVariable(
1489 *llvmModule, zeroInit->getType(), false,
1490 llvm::GlobalValue::AppendingLinkage, zeroInit,
1491 ctorOp ? "llvm.global_ctors" : "llvm.global_dtors");
1492 } else {
1493 auto range = ctorOp
1494 ? llvm::zip(ctorOp.getCtors(), ctorOp.getPriorities())
1495 : llvm::zip(dtorOp.getDtors(), dtorOp.getPriorities());
1496 auto appendGlobalFn =
1497 ctorOp ? llvm::appendToGlobalCtors : llvm::appendToGlobalDtors;
1498 for (const auto &[sym, prio] : range) {
1499 llvm::Function *f =
1500 lookupFunction(cast<FlatSymbolRefAttr>(sym).getValue());
1501 appendGlobalFn(*llvmModule, f, cast<IntegerAttr>(prio).getInt(),
1502 /*Data=*/nullptr);
1503 }
1504 }
1505 }
1506
1507 for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>())
1508 if (failed(convertDialectAttributes(op, {})))
1509 return failure();
1510
1511 // Finally, update the compile units their respective sets of global variables
1512 // created earlier.
1513 for (const auto &[compileUnit, globals] : globalGVars)
1514 compileUnit->replaceGlobalVariables(
1515 llvm::MDTuple::get(getLLVMContext(), globals));
1516
1517 // And update the subprograms with their respective sets of static local
1518 // variables.
1519 for (const auto &[sp, globals] : staticLocals)
1520 sp->retainNodes(globals.begin(), globals.end());
1521
1522 // Convert global alias bodies.
1523 for (auto op : getModuleBody(mlirModule).getOps<LLVM::AliasOp>()) {
1524 Block &initializer = op.getInitializerBlock();
1525 llvm::IRBuilder<llvm::TargetFolder> builder(
1526 llvmModule->getContext(),
1527 llvm::TargetFolder(llvmModule->getDataLayout()));
1528
1529 for (mlir::Operation &op : initializer.without_terminator()) {
1530 if (failed(convertOperation(op, builder)))
1531 return emitError(op.getLoc(), "fail to convert alias initializer");
1532 if (!isa<llvm::Constant>(lookupValue(op.getResult(0))))
1533 return emitError(op.getLoc(), "unemittable constant value");
1534 }
1535
1536 auto ret = cast<ReturnOp>(initializer.getTerminator());
1537 auto *cst = cast<llvm::Constant>(lookupValue(ret.getOperand(0)));
1538 assert(aliasesMapping.count(op));
1539 auto *alias = cast<llvm::GlobalAlias>(aliasesMapping[op]);
1540 alias->setAliasee(cst);
1541 }
1542
1543 for (auto op : getModuleBody(mlirModule).getOps<LLVM::AliasOp>())
1544 if (failed(convertDialectAttributes(op, {})))
1545 return failure();
1546
1547 return success();
1548}
1549
1550/// Return a representation of `value` as metadata.
1551static llvm::Metadata *convertIntegerToMetadata(llvm::LLVMContext &context,
1552 const llvm::APInt &value) {
1553 llvm::Constant *constant = llvm::ConstantInt::get(context, value);
1554 return llvm::ConstantAsMetadata::get(constant);
1555}
1556
1557/// Return a representation of `value` as an MDNode.
1558static llvm::MDNode *convertIntegerToMDNode(llvm::LLVMContext &context,
1559 const llvm::APInt &value) {
1560 return llvm::MDNode::get(context, convertIntegerToMetadata(context, value));
1561}
1562
1563/// Return an MDNode encoding `vec_type_hint` metadata.
1564static llvm::MDNode *convertVecTypeHintToMDNode(llvm::LLVMContext &context,
1565 llvm::Type *type,
1566 bool isSigned) {
1567 llvm::Metadata *typeMD =
1568 llvm::ConstantAsMetadata::get(llvm::UndefValue::get(type));
1569 llvm::Metadata *isSignedMD =
1570 convertIntegerToMetadata(context, llvm::APInt(32, isSigned ? 1 : 0));
1571 return llvm::MDNode::get(context, {typeMD, isSignedMD});
1572}
1573
1574/// Return an MDNode with a tuple given by the values in `values`.
1575static llvm::MDNode *convertIntegerArrayToMDNode(llvm::LLVMContext &context,
1576 ArrayRef<int32_t> values) {
1578 llvm::transform(
1579 values, std::back_inserter(mdValues), [&context](int32_t value) {
1580 return convertIntegerToMetadata(context, llvm::APInt(32, value));
1581 });
1582 return llvm::MDNode::get(context, mdValues);
1583}
1584
1585FailureOr<llvm::Metadata *> ModuleTranslation::convertMetadataAttr(
1587 llvm::LLVMContext &llvmContext = getLLVMContext();
1588
1590 .Case([&](MDStringAttr a) -> FailureOr<llvm::Metadata *> {
1591 return llvm::MDString::get(llvmContext, a.getValue().getValue());
1592 })
1593 .Case([&](MDConstantAttr a) -> FailureOr<llvm::Metadata *> {
1594 IntegerAttr intAttr = llvm::dyn_cast<IntegerAttr>(a.getValue());
1595 if (!intAttr) {
1596 return emitError()
1597 << "expected integer attribute in metadata constant";
1598 }
1599 return llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1600 llvm::Type::getIntNTy(llvmContext,
1601 intAttr.getType().getIntOrFloatBitWidth()),
1602 intAttr.getValue()));
1603 })
1604 .Case([&](MDGlobalValueAttr a) -> FailureOr<llvm::Metadata *> {
1605 if (llvm::Function *fn = lookupFunction(a.getName().getValue()))
1606 return llvm::ValueAsMetadata::get(fn);
1607 if (llvm::GlobalValue *global = lookupGlobal(a.getName().getValue()))
1608 return llvm::ValueAsMetadata::get(global);
1609 Operation *symbol =
1610 symbolTable().lookupSymbolIn(mlirModule, a.getName());
1611 if (auto alias = dyn_cast_if_present<LLVM::AliasOp>(symbol)) {
1612 if (llvm::GlobalValue *global = lookupAlias(alias))
1613 return llvm::ValueAsMetadata::get(global);
1614 }
1615 if (auto ifunc = dyn_cast_if_present<LLVM::IFuncOp>(symbol)) {
1616 if (llvm::GlobalValue *global = lookupIFunc(ifunc))
1617 return llvm::ValueAsMetadata::get(global);
1618 }
1619 return emitError() << "could not resolve metadata reference '"
1620 << a.getName() << "'";
1621 })
1622 .Case([&](MDNodeAttr a) -> FailureOr<llvm::Metadata *> {
1624 for (Attribute operand : a.getOperands()) {
1625 FailureOr<llvm::Metadata *> md =
1627 if (failed(md))
1628 return failure();
1629 operands.push_back(*md);
1630 }
1631 return llvm::MDNode::get(llvmContext, operands);
1632 })
1633 .Default([&](Attribute attr) -> FailureOr<llvm::Metadata *> {
1634 return emitError() << "unsupported LLVM metadata attribute " << attr;
1635 });
1636}
1637
1638LogicalResult ModuleTranslation::convertOneFunction(LLVMFuncOp func) {
1639 // Clear the block, branch value mappings, they are only relevant within one
1640 // function.
1641 blockMapping.clear();
1642 valueMapping.clear();
1643 branchMapping.clear();
1644 llvm::Function *llvmFunc = lookupFunction(func.getName());
1645 llvm::LLVMContext &llvmContext = llvmFunc->getContext();
1646
1647 // Add function arguments to the value remapping table.
1648 for (auto [mlirArg, llvmArg] :
1649 llvm::zip(func.getArguments(), llvmFunc->args()))
1650 mapValue(mlirArg, &llvmArg);
1651
1652 // Check the personality and set it.
1653 if (func.getPersonality()) {
1654 llvm::Type *ty = llvm::PointerType::getUnqual(llvmFunc->getContext());
1655 if (llvm::Constant *pfunc = getLLVMConstant(ty, func.getPersonalityAttr(),
1656 func.getLoc(), *this))
1657 llvmFunc->setPersonalityFn(pfunc);
1658 }
1659
1660 if (std::optional<StringRef> section = func.getSection())
1661 llvmFunc->setSection(*section);
1662
1663 if (func.getArmStreaming())
1664 llvmFunc->addFnAttr("aarch64_pstate_sm_enabled");
1665 else if (func.getArmLocallyStreaming())
1666 llvmFunc->addFnAttr("aarch64_pstate_sm_body");
1667 else if (func.getArmStreamingCompatible())
1668 llvmFunc->addFnAttr("aarch64_pstate_sm_compatible");
1669
1670 if (func.getArmNewZa())
1671 llvmFunc->addFnAttr("aarch64_new_za");
1672 else if (func.getArmInZa())
1673 llvmFunc->addFnAttr("aarch64_in_za");
1674 else if (func.getArmOutZa())
1675 llvmFunc->addFnAttr("aarch64_out_za");
1676 else if (func.getArmInoutZa())
1677 llvmFunc->addFnAttr("aarch64_inout_za");
1678 else if (func.getArmPreservesZa())
1679 llvmFunc->addFnAttr("aarch64_preserves_za");
1680
1681 if (auto targetCpu = func.getTargetCpu())
1682 llvmFunc->addFnAttr("target-cpu", *targetCpu);
1683
1684 if (auto tuneCpu = func.getTuneCpu())
1685 llvmFunc->addFnAttr("tune-cpu", *tuneCpu);
1686
1687 if (auto reciprocalEstimates = func.getReciprocalEstimates())
1688 llvmFunc->addFnAttr("reciprocal-estimates", *reciprocalEstimates);
1689
1690 if (auto preferVectorWidth = func.getPreferVectorWidth())
1691 llvmFunc->addFnAttr("prefer-vector-width", *preferVectorWidth);
1692
1693 if (func.getUseSampleProfile())
1694 llvmFunc->addFnAttr("use-sample-profile");
1695
1696 if (auto attr = func.getVscaleRange())
1697 llvmFunc->addFnAttr(llvm::Attribute::getWithVScaleRangeArgs(
1698 getLLVMContext(), attr->getMinRange().getInt(),
1699 attr->getMaxRange().getInt()));
1700
1701 if (auto noSignedZerosFpMath = func.getNoSignedZerosFpMath())
1702 llvmFunc->addFnAttr("no-signed-zeros-fp-math",
1703 llvm::toStringRef(*noSignedZerosFpMath));
1704
1705 if (auto fpContract = func.getFpContract())
1706 llvmFunc->addFnAttr("fp-contract", *fpContract);
1707
1708 if (auto instrumentFunctionEntry = func.getInstrumentFunctionEntry())
1709 llvmFunc->addFnAttr("instrument-function-entry", *instrumentFunctionEntry);
1710
1711 if (auto instrumentFunctionExit = func.getInstrumentFunctionExit())
1712 llvmFunc->addFnAttr("instrument-function-exit", *instrumentFunctionExit);
1713
1714 // First, create all blocks so we can jump to them.
1715 for (auto &bb : func) {
1716 auto *llvmBB = llvm::BasicBlock::Create(llvmContext);
1717 llvmBB->insertInto(llvmFunc);
1718 mapBlock(&bb, llvmBB);
1719 }
1720
1721 // Then, convert blocks one by one in topological order to ensure defs are
1722 // converted before uses.
1723 auto blocks = getBlocksSortedByDominance(func.getBody());
1724 for (Block *bb : blocks) {
1725 CapturingIRBuilder builder(llvmContext,
1726 llvm::TargetFolder(llvmModule->getDataLayout()));
1727 if (failed(convertBlockImpl(*bb, bb->isEntryBlock(), builder,
1728 /*recordInsertions=*/true)))
1729 return failure();
1730 }
1731
1732 // After all blocks have been traversed and values mapped, connect the PHI
1733 // nodes to the results of preceding blocks.
1734 detail::connectPHINodes(func.getBody(), *this);
1735
1736 // Finally, convert dialect attributes attached to the function.
1737 return convertDialectAttributes(func, {});
1738}
1739
1740LogicalResult ModuleTranslation::convertDialectAttributes(
1741 Operation *op, ArrayRef<llvm::Instruction *> instructions) {
1742 for (NamedAttribute attribute : op->getDialectAttrs())
1743 if (failed(iface.amendOperation(op, instructions, attribute, *this)))
1744 return failure();
1745 return success();
1746}
1747
1748/// Converts memory effect attributes from `func` and attaches them to
1749/// `llvmFunc`.
1751 llvm::Function *llvmFunc) {
1752 if (!func.getMemoryEffects())
1753 return;
1754
1755 MemoryEffectsAttr memEffects = func.getMemoryEffectsAttr();
1756
1757 // Add memory effects incrementally.
1758 llvm::MemoryEffects newMemEffects =
1759 llvm::MemoryEffects(llvm::MemoryEffects::Location::ArgMem,
1760 convertModRefInfoToLLVM(memEffects.getArgMem()));
1761 newMemEffects |= llvm::MemoryEffects(
1762 llvm::MemoryEffects::Location::InaccessibleMem,
1763 convertModRefInfoToLLVM(memEffects.getInaccessibleMem()));
1764 newMemEffects |=
1765 llvm::MemoryEffects(llvm::MemoryEffects::Location::Other,
1766 convertModRefInfoToLLVM(memEffects.getOther()));
1767 newMemEffects |=
1768 llvm::MemoryEffects(llvm::MemoryEffects::Location::ErrnoMem,
1769 convertModRefInfoToLLVM(memEffects.getErrnoMem()));
1770 newMemEffects |=
1771 llvm::MemoryEffects(llvm::MemoryEffects::Location::TargetMem0,
1772 convertModRefInfoToLLVM(memEffects.getTargetMem0()));
1773 newMemEffects |=
1774 llvm::MemoryEffects(llvm::MemoryEffects::Location::TargetMem1,
1775 convertModRefInfoToLLVM(memEffects.getTargetMem1()));
1776 llvmFunc->setMemoryEffects(newMemEffects);
1777}
1778
1779llvm::Attribute
1781 if (!allocSizeAttr || allocSizeAttr.empty())
1782 return llvm::Attribute{};
1783
1784 unsigned elemSize = static_cast<unsigned>(allocSizeAttr[0]);
1785 std::optional<unsigned> numElems;
1786 if (allocSizeAttr.size() > 1)
1787 numElems = static_cast<unsigned>(allocSizeAttr[1]);
1788
1789 return llvm::Attribute::getWithAllocSizeArgs(getLLVMContext(), elemSize,
1790 numElems);
1791}
1793 llvm::AttrBuilder &Attrs) {
1794 std::optional<DenormalFPEnvAttr> denormalFpEnv = func.getDenormalFpenv();
1795 if (!denormalFpEnv)
1796 return;
1797
1798 llvm::DenormalMode DefaultMode(
1799 convertDenormalModeKindToLLVM(denormalFpEnv->getDefaultOutputMode()),
1800 convertDenormalModeKindToLLVM(denormalFpEnv->getDefaultInputMode()));
1801 llvm::DenormalMode FloatMode(
1802 convertDenormalModeKindToLLVM(denormalFpEnv->getFloatOutputMode()),
1803 convertDenormalModeKindToLLVM(denormalFpEnv->getFloatInputMode()));
1804
1805 llvm::DenormalFPEnv FPEnv(DefaultMode, FloatMode);
1806 Attrs.addDenormalFPEnvAttr(FPEnv);
1807}
1808
1809/// Converts function attributes from `func` and attaches them to `llvmFunc`.
1811 llvm::Function *llvmFunc) {
1812 // FIXME: Use AttrBuilder far all cases
1813 llvm::AttrBuilder AttrBuilder(llvmFunc->getContext());
1814
1815 if (func.getNoInlineAttr())
1816 llvmFunc->addFnAttr(llvm::Attribute::NoInline);
1817 if (func.getAlwaysInlineAttr())
1818 llvmFunc->addFnAttr(llvm::Attribute::AlwaysInline);
1819 if (func.getInlineHintAttr())
1820 llvmFunc->addFnAttr(llvm::Attribute::InlineHint);
1821 if (func.getOptimizeNoneAttr())
1822 llvmFunc->addFnAttr(llvm::Attribute::OptimizeNone);
1823 if (func.getReturnsTwiceAttr())
1824 llvmFunc->addFnAttr(llvm::Attribute::ReturnsTwice);
1825 if (func.getColdAttr())
1826 llvmFunc->addFnAttr(llvm::Attribute::Cold);
1827 if (func.getHotAttr())
1828 llvmFunc->addFnAttr(llvm::Attribute::Hot);
1829 if (func.getNoduplicateAttr())
1830 llvmFunc->addFnAttr(llvm::Attribute::NoDuplicate);
1831 if (func.getConvergentAttr())
1832 llvmFunc->addFnAttr(llvm::Attribute::Convergent);
1833 if (func.getNoUnwindAttr())
1834 llvmFunc->addFnAttr(llvm::Attribute::NoUnwind);
1835 if (func.getWillReturnAttr())
1836 llvmFunc->addFnAttr(llvm::Attribute::WillReturn);
1837 if (func.getNoreturnAttr())
1838 llvmFunc->addFnAttr(llvm::Attribute::NoReturn);
1839 if (func.getOptsizeAttr())
1840 llvmFunc->addFnAttr(llvm::Attribute::OptimizeForSize);
1841 if (func.getMinsizeAttr())
1842 llvmFunc->addFnAttr(llvm::Attribute::MinSize);
1843 if (func.getSaveRegParamsAttr())
1844 llvmFunc->addFnAttr("save-reg-params");
1845 if (func.getNoCallerSavedRegistersAttr())
1846 llvmFunc->addFnAttr("no_caller_saved_registers");
1847 if (func.getNocallbackAttr())
1848 llvmFunc->addFnAttr(llvm::Attribute::NoCallback);
1849 if (StringAttr modFormat = func.getModularFormatAttr())
1850 llvmFunc->addFnAttr("modular-format", modFormat.getValue());
1851 if (TargetFeaturesAttr targetFeatAttr = func.getTargetFeaturesAttr())
1852 llvmFunc->addFnAttr("target-features", targetFeatAttr.getFeaturesString());
1853 if (FramePointerKindAttr fpAttr = func.getFramePointerAttr())
1854 llvmFunc->addFnAttr("frame-pointer", stringifyFramePointerKind(
1855 fpAttr.getFramePointerKind()));
1856 if (UWTableKindAttr uwTableKindAttr = func.getUwtableKindAttr())
1857 llvmFunc->setUWTableKind(
1858 convertUWTableKindToLLVM(uwTableKindAttr.getUwtableKind()));
1859 if (StringAttr zcsr = func.getZeroCallUsedRegsAttr())
1860 llvmFunc->addFnAttr("zero-call-used-regs", zcsr.getValue());
1861
1862 if (ArrayAttr noBuiltins = func.getNobuiltinsAttr()) {
1863 if (noBuiltins.empty())
1864 llvmFunc->addFnAttr("no-builtins");
1865
1866 mod.convertFunctionAttrCollection(noBuiltins, llvmFunc,
1868 }
1869
1870 mod.convertFunctionAttrCollection(func.getDefaultFuncAttrsAttr(), llvmFunc,
1872
1873 if (llvm::Attribute attr = mod.convertAllocsizeAttr(func.getAllocsizeAttr());
1874 attr.isValid())
1875 llvmFunc->addFnAttr(attr);
1876
1878
1879 convertDenormalFPEnvAttribute(func, AttrBuilder);
1880 llvmFunc->addFnAttrs(AttrBuilder);
1881}
1882
1883/// Converts function attributes from `func` and attaches them to `llvmFunc`.
1885 llvm::Function *llvmFunc,
1886 ModuleTranslation &translation) {
1887 llvm::LLVMContext &llvmContext = llvmFunc->getContext();
1888
1889 if (VecTypeHintAttr vecTypeHint = func.getVecTypeHintAttr()) {
1890 Type type = vecTypeHint.getHint().getValue();
1891 llvm::Type *llvmType = translation.convertType(type);
1892 bool isSigned = vecTypeHint.getIsSigned();
1893 llvmFunc->setMetadata(
1894 func.getVecTypeHintAttrName(),
1895 convertVecTypeHintToMDNode(llvmContext, llvmType, isSigned));
1896 }
1897
1898 if (std::optional<ArrayRef<int32_t>> workGroupSizeHint =
1899 func.getWorkGroupSizeHint()) {
1900 llvmFunc->setMetadata(
1901 func.getWorkGroupSizeHintAttrName(),
1902 convertIntegerArrayToMDNode(llvmContext, *workGroupSizeHint));
1903 }
1904
1905 if (std::optional<ArrayRef<int32_t>> reqdWorkGroupSize =
1906 func.getReqdWorkGroupSize()) {
1907 llvmFunc->setMetadata(
1908 func.getReqdWorkGroupSizeAttrName(),
1909 convertIntegerArrayToMDNode(llvmContext, *reqdWorkGroupSize));
1910 }
1911
1912 if (std::optional<uint32_t> intelReqdSubGroupSize =
1913 func.getIntelReqdSubGroupSize()) {
1914 llvmFunc->setMetadata(
1915 func.getIntelReqdSubGroupSizeAttrName(),
1916 convertIntegerToMDNode(llvmContext,
1917 llvm::APInt(32, *intelReqdSubGroupSize)));
1918 }
1919}
1920
1921static LogicalResult convertParameterAttr(llvm::AttrBuilder &attrBuilder,
1922 llvm::Attribute::AttrKind llvmKind,
1923 NamedAttribute namedAttr,
1924 ModuleTranslation &moduleTranslation,
1925 Location loc) {
1927 .Case([&](TypeAttr typeAttr) {
1928 attrBuilder.addTypeAttr(
1929 llvmKind, moduleTranslation.convertType(typeAttr.getValue()));
1930 return success();
1931 })
1932 .Case([&](IntegerAttr intAttr) {
1933 attrBuilder.addRawIntAttr(llvmKind, intAttr.getInt());
1934 return success();
1935 })
1936 .Case([&](UnitAttr) {
1937 attrBuilder.addAttribute(llvmKind);
1938 return success();
1939 })
1940 .Case([&](LLVM::ConstantRangeAttr rangeAttr) {
1941 attrBuilder.addConstantRangeAttr(
1942 llvmKind,
1943 llvm::ConstantRange(rangeAttr.getLower(), rangeAttr.getUpper()));
1944 return success();
1945 })
1946 .Default([loc](auto) {
1947 return emitError(loc, "unsupported parameter attribute type");
1948 });
1949}
1950
1951FailureOr<llvm::AttrBuilder>
1952ModuleTranslation::convertParameterAttrs(LLVMFuncOp func, int argIdx,
1953 DictionaryAttr paramAttrs) {
1954 llvm::AttrBuilder attrBuilder(llvmModule->getContext());
1955 auto attrNameToKindMapping = getAttrNameToKindMapping();
1956 Location loc = func.getLoc();
1957
1958 for (auto namedAttr : paramAttrs) {
1959 auto it = attrNameToKindMapping.find(namedAttr.getName());
1960 if (it != attrNameToKindMapping.end()) {
1961 llvm::Attribute::AttrKind llvmKind = it->second;
1962 if (failed(convertParameterAttr(attrBuilder, llvmKind, namedAttr, *this,
1963 loc)))
1964 return failure();
1965 } else if (namedAttr.getNameDialect()) {
1966 if (failed(iface.convertParameterAttr(func, argIdx, namedAttr, *this)))
1967 return failure();
1968 }
1969 }
1970
1971 return attrBuilder;
1972}
1973
1975 ArgAndResultAttrsOpInterface attrsOp, llvm::CallBase *call,
1976 ArrayRef<unsigned> immArgPositions) {
1977 // Convert the argument attributes.
1978 if (ArrayAttr argAttrsArray = attrsOp.getArgAttrsAttr()) {
1979 unsigned argAttrIdx = 0;
1980 llvm::SmallDenseSet<unsigned> immArgPositionsSet(immArgPositions.begin(),
1981 immArgPositions.end());
1982 for (unsigned argIdx : llvm::seq<unsigned>(call->arg_size())) {
1983 if (argAttrIdx >= argAttrsArray.size())
1984 break;
1985 // Skip immediate arguments (they have no entries in argAttrsArray).
1986 if (immArgPositionsSet.contains(argIdx))
1987 continue;
1988 // Skip empty argument attributes.
1989 auto argAttrs = cast<DictionaryAttr>(argAttrsArray[argAttrIdx++]);
1990 if (argAttrs.empty())
1991 continue;
1992 // Convert and add attributes to the call instruction.
1993 FailureOr<llvm::AttrBuilder> attrBuilder =
1994 convertParameterAttrs(attrsOp->getLoc(), argAttrs);
1995 if (failed(attrBuilder))
1996 return failure();
1997 call->addParamAttrs(argIdx, *attrBuilder);
1998 }
1999 }
2000
2001 // Convert the result attributes.
2002 if (ArrayAttr resAttrsArray = attrsOp.getResAttrsAttr()) {
2003 if (!resAttrsArray.empty()) {
2004 auto resAttrs = cast<DictionaryAttr>(resAttrsArray[0]);
2005 FailureOr<llvm::AttrBuilder> attrBuilder =
2006 convertParameterAttrs(attrsOp->getLoc(), resAttrs);
2007 if (failed(attrBuilder))
2008 return failure();
2009 call->addRetAttrs(*attrBuilder);
2010 }
2011 }
2012
2013 return success();
2014}
2015
2016std::optional<llvm::Attribute>
2018 if (auto str = dyn_cast<StringAttr>(a))
2019 return llvm::Attribute::get(ctx, ("no-builtin-" + str.getValue()).str());
2020 return std::nullopt;
2021}
2022
2023std::optional<llvm::Attribute>
2025 mlir::NamedAttribute namedAttr) {
2026 StringAttr name = namedAttr.getName();
2027 Attribute value = namedAttr.getValue();
2028
2029 if (auto strVal = dyn_cast<StringAttr>(value))
2030 return llvm::Attribute::get(ctx, name.getValue(), strVal.getValue());
2031 if (mlir::isa<UnitAttr>(value))
2032 return llvm::Attribute::get(ctx, name.getValue());
2033 return std::nullopt;
2034}
2035
2036FailureOr<llvm::AttrBuilder>
2037ModuleTranslation::convertParameterAttrs(Location loc,
2038 DictionaryAttr paramAttrs) {
2039 llvm::AttrBuilder attrBuilder(llvmModule->getContext());
2040 auto attrNameToKindMapping = getAttrNameToKindMapping();
2041
2042 for (auto namedAttr : paramAttrs) {
2043 auto it = attrNameToKindMapping.find(namedAttr.getName());
2044 if (it != attrNameToKindMapping.end()) {
2045 llvm::Attribute::AttrKind llvmKind = it->second;
2046 if (failed(convertParameterAttr(attrBuilder, llvmKind, namedAttr, *this,
2047 loc)))
2048 return failure();
2049 }
2050 }
2051
2052 return attrBuilder;
2053}
2054
2055LogicalResult ModuleTranslation::convertFunctionSignatures() {
2056 // Declare all functions first because there may be function calls that form a
2057 // call graph with cycles, or global initializers that reference functions.
2058 for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) {
2059 llvm::FunctionCallee llvmFuncCst = llvmModule->getOrInsertFunction(
2060 function.getName(),
2061 cast<llvm::FunctionType>(convertType(function.getFunctionType())));
2062 llvm::Function *llvmFunc = cast<llvm::Function>(llvmFuncCst.getCallee());
2063 llvmFunc->setLinkage(convertLinkageToLLVM(function.getLinkage()));
2064 llvmFunc->setCallingConv(convertCConvToLLVM(function.getCConv()));
2065 mapFunction(function.getName(), llvmFunc);
2066 addRuntimePreemptionSpecifier(function.getDsoLocal(), llvmFunc);
2067
2068 // Convert function attributes.
2069 convertFunctionAttributes(*this, function, llvmFunc);
2070
2071 // Convert function kernel attributes to metadata.
2072 convertFunctionKernelAttributes(function, llvmFunc, *this);
2073
2074 // Convert function_entry_count attribute to metadata.
2075 if (auto entryCount = function.getFunctionEntryCountAttr()) {
2076 ArrayRef<uint64_t> imports = entryCount.getImports();
2077 llvm::DenseSet<llvm::GlobalValue::GUID> importGUIDs;
2078 if (!imports.empty())
2079 importGUIDs.insert(imports.begin(), imports.end());
2080 llvm::MDBuilder metadataBuilder(llvmFunc->getContext());
2081 llvmFunc->setMetadata(
2082 llvm::LLVMContext::MD_prof,
2083 metadataBuilder.createFunctionEntryCount(
2084 entryCount.getEntryCount(),
2085 entryCount.getCountType() == ProfileCountType::Synthetic,
2086 imports.empty() ? nullptr : &importGUIDs));
2087 }
2088
2089 // Convert result attributes.
2090 if (ArrayAttr allResultAttrs = function.getAllResultAttrs()) {
2091 DictionaryAttr resultAttrs = cast<DictionaryAttr>(allResultAttrs[0]);
2092 FailureOr<llvm::AttrBuilder> attrBuilder =
2093 convertParameterAttrs(function, -1, resultAttrs);
2094 if (failed(attrBuilder))
2095 return failure();
2096 llvmFunc->addRetAttrs(*attrBuilder);
2097 }
2098
2099 // Convert argument attributes.
2100 for (auto [argIdx, llvmArg] : llvm::enumerate(llvmFunc->args())) {
2101 if (DictionaryAttr argAttrs = function.getArgAttrDict(argIdx)) {
2102 FailureOr<llvm::AttrBuilder> attrBuilder =
2103 convertParameterAttrs(function, argIdx, argAttrs);
2104 if (failed(attrBuilder))
2105 return failure();
2106 llvmArg.addAttrs(*attrBuilder);
2107 }
2108 }
2109
2110 // Forward the pass-through attributes to LLVM.
2111 FailureOr<llvm::AttrBuilder> convertedPassthroughAttrs =
2112 convertMLIRAttributesToLLVM(function.getLoc(), llvmFunc->getContext(),
2113 function.getPassthroughAttr(),
2114 function.getPassthroughAttrName());
2115 if (failed(convertedPassthroughAttrs))
2116 return failure();
2117 llvmFunc->addFnAttrs(*convertedPassthroughAttrs);
2118
2119 // Convert visibility attribute.
2120 llvmFunc->setVisibility(convertVisibilityToLLVM(function.getVisibility_()));
2121
2122 // Convert the comdat attribute.
2123 if (std::optional<mlir::SymbolRefAttr> comdat = function.getComdat()) {
2124 auto selectorOp = cast<ComdatSelectorOp>(
2125 SymbolTable::lookupNearestSymbolFrom(function, *comdat));
2126 llvmFunc->setComdat(comdatMapping.lookup(selectorOp));
2127 }
2128
2129 if (auto gc = function.getGarbageCollector())
2130 llvmFunc->setGC(gc->str());
2131
2132 if (auto unnamedAddr = function.getUnnamedAddr())
2133 llvmFunc->setUnnamedAddr(convertUnnamedAddrToLLVM(*unnamedAddr));
2134
2135 if (auto alignment = function.getAlignment())
2136 llvmFunc->setAlignment(llvm::MaybeAlign(*alignment));
2137
2138 // Translate the debug information for this function.
2139 debugTranslation->translate(function, *llvmFunc);
2140 }
2141
2142 return success();
2143}
2144
2145LogicalResult ModuleTranslation::convertFunctions() {
2146 // Convert functions.
2147 for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) {
2148 // Do not convert external functions, but do process dialect attributes
2149 // attached to them.
2150 if (function.isExternal()) {
2151 if (failed(convertDialectAttributes(function, {})))
2152 return failure();
2153 continue;
2154 }
2155
2156 if (failed(convertOneFunction(function)))
2157 return failure();
2158 }
2159
2160 return success();
2161}
2162
2163LogicalResult ModuleTranslation::convertIFuncs() {
2164 for (auto op : getModuleBody(mlirModule).getOps<IFuncOp>()) {
2165 llvm::Type *type = convertType(op.getIFuncType());
2166 llvm::GlobalValue::LinkageTypes linkage =
2167 convertLinkageToLLVM(op.getLinkage());
2168 llvm::Constant *resolver;
2169 if (auto *resolverFn = lookupFunction(op.getResolver())) {
2170 resolver = cast<llvm::Constant>(resolverFn);
2171 } else {
2172 Operation *aliasOp = symbolTable().lookupSymbolIn(parentLLVMModule(op),
2173 op.getResolverAttr());
2174 resolver = cast<llvm::Constant>(lookupAlias(aliasOp));
2175 }
2176
2177 auto *ifunc =
2178 llvm::GlobalIFunc::create(type, op.getAddressSpace(), linkage,
2179 op.getSymName(), resolver, llvmModule.get());
2180 addRuntimePreemptionSpecifier(op.getDsoLocal(), ifunc);
2181 ifunc->setUnnamedAddr(convertUnnamedAddrToLLVM(op.getUnnamedAddr()));
2182 ifunc->setVisibility(convertVisibilityToLLVM(op.getVisibility_()));
2183
2184 ifuncMapping.try_emplace(op, ifunc);
2185 }
2186
2187 return success();
2188}
2189
2190LogicalResult ModuleTranslation::convertComdats() {
2191 for (auto comdatOp : getModuleBody(mlirModule).getOps<ComdatOp>()) {
2192 for (auto selectorOp : comdatOp.getOps<ComdatSelectorOp>()) {
2193 llvm::Module *module = getLLVMModule();
2194 if (module->getComdatSymbolTable().contains(selectorOp.getSymName()))
2195 return emitError(selectorOp.getLoc())
2196 << "comdat selection symbols must be unique even in different "
2197 "comdat regions";
2198 llvm::Comdat *comdat = module->getOrInsertComdat(selectorOp.getSymName());
2199 comdat->setSelectionKind(convertComdatToLLVM(selectorOp.getComdat()));
2200 comdatMapping.try_emplace(selectorOp, comdat);
2201 }
2202 }
2203 return success();
2204}
2205
2206LogicalResult ModuleTranslation::convertUnresolvedBlockAddress() {
2207 for (auto &[blockAddressOp, llvmCst] : unresolvedBlockAddressMapping) {
2208 BlockAddressAttr blockAddressAttr = blockAddressOp.getBlockAddr();
2209 llvm::BasicBlock *llvmBlock = lookupBlockAddress(blockAddressAttr);
2210 assert(llvmBlock && "expected LLVM blocks to be already translated");
2211
2212 // Update mapping with new block address constant.
2213 auto *llvmBlockAddr = llvm::BlockAddress::get(
2214 lookupFunction(blockAddressAttr.getFunction().getValue()), llvmBlock);
2215 llvmCst->replaceAllUsesWith(llvmBlockAddr);
2216 assert(llvmCst->use_empty() && "expected all uses to be replaced");
2217 cast<llvm::GlobalVariable>(llvmCst)->eraseFromParent();
2218 }
2219 unresolvedBlockAddressMapping.clear();
2220 return success();
2221}
2222
2223void ModuleTranslation::setAccessGroupsMetadata(AccessGroupOpInterface op,
2224 llvm::Instruction *inst) {
2225 if (llvm::MDNode *node = loopAnnotationTranslation->getAccessGroups(op))
2226 inst->setMetadata(llvm::LLVMContext::MD_access_group, node);
2227}
2228
2229llvm::MDNode *
2230ModuleTranslation::getOrCreateAliasScope(AliasScopeAttr aliasScopeAttr) {
2231 auto [scopeIt, scopeInserted] =
2232 aliasScopeMetadataMapping.try_emplace(aliasScopeAttr, nullptr);
2233 if (!scopeInserted)
2234 return scopeIt->second;
2235 llvm::LLVMContext &ctx = llvmModule->getContext();
2236 auto dummy = llvm::MDNode::getTemporary(ctx, {});
2237 // Convert the domain metadata node if necessary.
2238 auto [domainIt, insertedDomain] = aliasDomainMetadataMapping.try_emplace(
2239 aliasScopeAttr.getDomain(), nullptr);
2240 if (insertedDomain) {
2242 // Placeholder for potential self-reference.
2243 operands.push_back(dummy.get());
2244 if (StringAttr description = aliasScopeAttr.getDomain().getDescription())
2245 operands.push_back(llvm::MDString::get(ctx, description));
2246 domainIt->second = llvm::MDNode::get(ctx, operands);
2247 // Self-reference for uniqueness.
2248 llvm::Metadata *replacement;
2249 if (auto stringAttr =
2250 dyn_cast<StringAttr>(aliasScopeAttr.getDomain().getId()))
2251 replacement = llvm::MDString::get(ctx, stringAttr.getValue());
2252 else
2253 replacement = domainIt->second;
2254 domainIt->second->replaceOperandWith(0, replacement);
2255 }
2256 // Convert the scope metadata node.
2257 assert(domainIt->second && "Scope's domain should already be valid");
2259 // Placeholder for potential self-reference.
2260 operands.push_back(dummy.get());
2261 operands.push_back(domainIt->second);
2262 if (StringAttr description = aliasScopeAttr.getDescription())
2263 operands.push_back(llvm::MDString::get(ctx, description));
2264 scopeIt->second = llvm::MDNode::get(ctx, operands);
2265 // Self-reference for uniqueness.
2266 llvm::Metadata *replacement;
2267 if (auto stringAttr = dyn_cast<StringAttr>(aliasScopeAttr.getId()))
2268 replacement = llvm::MDString::get(ctx, stringAttr.getValue());
2269 else
2270 replacement = scopeIt->second;
2271 scopeIt->second->replaceOperandWith(0, replacement);
2272 return scopeIt->second;
2273}
2274
2276 ArrayRef<AliasScopeAttr> aliasScopeAttrs) {
2278 nodes.reserve(aliasScopeAttrs.size());
2279 for (AliasScopeAttr aliasScopeAttr : aliasScopeAttrs)
2280 nodes.push_back(getOrCreateAliasScope(aliasScopeAttr));
2281 return llvm::MDNode::get(getLLVMContext(), nodes);
2282}
2283
2284void ModuleTranslation::setAliasScopeMetadata(AliasAnalysisOpInterface op,
2285 llvm::Instruction *inst) {
2286 auto populateScopeMetadata = [&](ArrayAttr aliasScopeAttrs, unsigned kind) {
2287 if (!aliasScopeAttrs || aliasScopeAttrs.empty())
2288 return;
2289 llvm::MDNode *node = getOrCreateAliasScopes(
2290 llvm::to_vector(aliasScopeAttrs.getAsRange<AliasScopeAttr>()));
2291 inst->setMetadata(kind, node);
2292 };
2293
2294 populateScopeMetadata(op.getAliasScopesOrNull(),
2295 llvm::LLVMContext::MD_alias_scope);
2296 populateScopeMetadata(op.getNoAliasScopesOrNull(),
2297 llvm::LLVMContext::MD_noalias);
2298}
2299
2300llvm::MDNode *ModuleTranslation::getTBAANode(TBAATagAttr tbaaAttr) const {
2301 return tbaaMetadataMapping.lookup(tbaaAttr);
2302}
2303
2304void ModuleTranslation::setTBAAMetadata(AliasAnalysisOpInterface op,
2305 llvm::Instruction *inst) {
2306 ArrayAttr tagRefs = op.getTBAATagsOrNull();
2307 if (!tagRefs || tagRefs.empty())
2308 return;
2309
2310 // LLVM IR currently does not support attaching more than one TBAA access tag
2311 // to a memory accessing instruction. It may be useful to support this in
2312 // future, but for the time being just ignore the metadata if MLIR operation
2313 // has multiple access tags.
2314 if (tagRefs.size() > 1) {
2315 op.emitWarning() << "TBAA access tags were not translated, because LLVM "
2316 "IR only supports a single tag per instruction";
2317 return;
2318 }
2319
2320 llvm::MDNode *node = getTBAANode(cast<TBAATagAttr>(tagRefs[0]));
2321 inst->setMetadata(llvm::LLVMContext::MD_tbaa, node);
2322}
2323
2325 DereferenceableOpInterface op, llvm::Instruction *inst) {
2326 DereferenceableAttr derefAttr = op.getDereferenceableOrNull();
2327 if (!derefAttr)
2328 return;
2329
2330 llvm::MDNode *derefSizeNode = llvm::MDNode::get(
2332 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
2333 llvm::IntegerType::get(getLLVMContext(), 64), derefAttr.getBytes())));
2334 unsigned kindId = derefAttr.getMayBeNull()
2335 ? llvm::LLVMContext::MD_dereferenceable_or_null
2336 : llvm::LLVMContext::MD_dereferenceable;
2337 inst->setMetadata(kindId, derefSizeNode);
2338}
2339
2340void ModuleTranslation::setBranchWeightsMetadata(WeightedBranchOpInterface op) {
2341 SmallVector<uint32_t> weights;
2342 llvm::transform(op.getWeights(), std::back_inserter(weights),
2343 [](int32_t value) { return static_cast<uint32_t>(value); });
2344 if (weights.empty())
2345 return;
2346
2347 llvm::Instruction *inst = isa<CallOp>(op) ? lookupCall(op) : lookupBranch(op);
2348 assert(inst && "expected the operation to have a mapping to an instruction");
2349 inst->setMetadata(
2350 llvm::LLVMContext::MD_prof,
2351 llvm::MDBuilder(getLLVMContext()).createBranchWeights(weights));
2352}
2353
2354LogicalResult ModuleTranslation::createTBAAMetadata() {
2355 llvm::LLVMContext &ctx = llvmModule->getContext();
2356 llvm::IntegerType *offsetTy = llvm::IntegerType::get(ctx, 64);
2357
2358 // Walk the entire module and create all metadata nodes for the TBAA
2359 // attributes. The code below relies on two invariants of the
2360 // `AttrTypeWalker`:
2361 // 1. Attributes are visited in post-order: Since the attributes create a DAG,
2362 // this ensures that any lookups into `tbaaMetadataMapping` for child
2363 // attributes succeed.
2364 // 2. Attributes are only ever visited once: This way we don't leak any
2365 // LLVM metadata instances.
2366 AttrTypeWalker walker;
2367 walker.addWalk([&](TBAARootAttr root) {
2368 llvm::MDNode *node;
2369 if (StringAttr id = root.getId()) {
2370 node = llvm::MDNode::get(ctx, llvm::MDString::get(ctx, id));
2371 } else {
2372 // Anonymous root nodes are self-referencing.
2373 auto selfRef = llvm::MDNode::getTemporary(ctx, {});
2374 node = llvm::MDNode::get(ctx, {selfRef.get()});
2375 node->replaceOperandWith(0, node);
2376 }
2377 tbaaMetadataMapping.insert({root, node});
2378 });
2379
2380 walker.addWalk([&](TBAATypeDescriptorAttr descriptor) {
2381 SmallVector<llvm::Metadata *> operands;
2382 operands.push_back(llvm::MDString::get(ctx, descriptor.getId()));
2383 for (TBAAMemberAttr member : descriptor.getMembers()) {
2384 operands.push_back(tbaaMetadataMapping.lookup(member.getTypeDesc()));
2385 operands.push_back(llvm::ConstantAsMetadata::get(
2386 llvm::ConstantInt::get(offsetTy, member.getOffset())));
2387 }
2388
2389 tbaaMetadataMapping.insert({descriptor, llvm::MDNode::get(ctx, operands)});
2390 });
2391
2392 walker.addWalk([&](TBAATagAttr tag) {
2393 SmallVector<llvm::Metadata *> operands;
2394
2395 operands.push_back(tbaaMetadataMapping.lookup(tag.getBaseType()));
2396 operands.push_back(tbaaMetadataMapping.lookup(tag.getAccessType()));
2397
2398 operands.push_back(llvm::ConstantAsMetadata::get(
2399 llvm::ConstantInt::get(offsetTy, tag.getOffset())));
2400 if (tag.getConstant())
2401 operands.push_back(
2402 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(offsetTy, 1)));
2403
2404 tbaaMetadataMapping.insert({tag, llvm::MDNode::get(ctx, operands)});
2405 });
2406
2407 mlirModule->walk([&](AliasAnalysisOpInterface analysisOpInterface) {
2408 if (auto attr = analysisOpInterface.getTBAATagsOrNull())
2409 walker.walk(attr);
2410 });
2411
2412 return success();
2413}
2414
2415LogicalResult ModuleTranslation::createIdentMetadata() {
2416 if (auto attr = mlirModule->getAttrOfType<StringAttr>(
2417 LLVMDialect::getIdentAttrName())) {
2418 StringRef ident = attr;
2419 llvm::LLVMContext &ctx = llvmModule->getContext();
2420 llvm::NamedMDNode *namedMd =
2421 llvmModule->getOrInsertNamedMetadata(LLVMDialect::getIdentAttrName());
2422 llvm::MDNode *md = llvm::MDNode::get(ctx, llvm::MDString::get(ctx, ident));
2423 namedMd->addOperand(md);
2424 }
2425
2426 return success();
2427}
2428
2429LogicalResult ModuleTranslation::createCommandlineMetadata() {
2430 if (auto attr = mlirModule->getAttrOfType<StringAttr>(
2431 LLVMDialect::getCommandlineAttrName())) {
2432 StringRef cmdLine = attr;
2433 llvm::LLVMContext &ctx = llvmModule->getContext();
2434 llvm::NamedMDNode *nmd = llvmModule->getOrInsertNamedMetadata(
2435 LLVMDialect::getCommandlineAttrName());
2436 llvm::MDNode *md =
2437 llvm::MDNode::get(ctx, llvm::MDString::get(ctx, cmdLine));
2438 nmd->addOperand(md);
2439 }
2440
2441 return success();
2442}
2443
2444LogicalResult ModuleTranslation::createDependentLibrariesMetadata() {
2445 if (auto dependentLibrariesAttr = mlirModule->getDiscardableAttr(
2446 LLVM::LLVMDialect::getDependentLibrariesAttrName())) {
2447 auto *nmd =
2448 llvmModule->getOrInsertNamedMetadata("llvm.dependent-libraries");
2449 llvm::LLVMContext &ctx = llvmModule->getContext();
2450 for (auto libAttr :
2451 cast<ArrayAttr>(dependentLibrariesAttr).getAsRange<StringAttr>()) {
2452 auto *md =
2453 llvm::MDNode::get(ctx, llvm::MDString::get(ctx, libAttr.getValue()));
2454 nmd->addOperand(md);
2455 }
2456 }
2457 return success();
2458}
2459
2461 llvm::Instruction *inst) {
2462 LoopAnnotationAttr attr =
2464 .Case<LLVM::BrOp, LLVM::CondBrOp>(
2465 [](auto branchOp) { return branchOp.getLoopAnnotationAttr(); });
2466 if (!attr)
2467 return;
2468 llvm::MDNode *loopMD =
2469 loopAnnotationTranslation->translateLoopAnnotation(attr, op);
2470 inst->setMetadata(llvm::LLVMContext::MD_loop, loopMD);
2471}
2472
2473void ModuleTranslation::setDisjointFlag(Operation *op, llvm::Value *value) {
2474 auto iface = cast<DisjointFlagInterface>(op);
2475 // We do a dyn_cast here in case the value got folded into a constant.
2476 if (auto *disjointInst = dyn_cast<llvm::PossiblyDisjointInst>(value))
2477 disjointInst->setIsDisjoint(iface.getIsDisjoint());
2478}
2479
2481 return typeTranslator.translateType(type);
2482}
2483
2484/// A helper to look up remapped operands in the value remapping table.
2487 remapped.reserve(values.size());
2488 for (Value v : values)
2489 remapped.push_back(lookupValue(v));
2490 return remapped;
2491}
2492
2493llvm::OpenMPIRBuilder *ModuleTranslation::getOpenMPBuilder() {
2494 if (!ompBuilder) {
2495 ompBuilder = std::make_unique<llvm::OpenMPIRBuilder>(*llvmModule);
2496
2497 // Flags represented as top-level OpenMP dialect attributes are set in
2498 // `OpenMPDialectLLVMIRTranslationInterface::amendOperation()`. Here we set
2499 // the default configuration.
2500 llvm::OpenMPIRBuilderConfig config(
2501 /* IsTargetDevice = */ false, /* IsGPU = */ false,
2502 /* OpenMPOffloadMandatory = */ false,
2503 /* HasRequiresReverseOffload = */ false,
2504 /* HasRequiresUnifiedAddress = */ false,
2505 /* HasRequiresUnifiedSharedMemory = */ false,
2506 /* HasRequiresDynamicAllocators = */ false);
2507 unsigned int defaultAS =
2508 llvmModule->getDataLayout().getProgramAddressSpace();
2509 config.setDefaultTargetAS(defaultAS);
2510 config.setRuntimeCC(llvmModule->getTargetTriple().isSPIRV()
2511 ? llvm::CallingConv::SPIR_FUNC
2512 : llvm::CallingConv::C);
2513 ompBuilder->setConfig(std::move(config));
2514 ompBuilder->initialize();
2515 }
2516 return ompBuilder.get();
2517}
2518
2519llvm::vfs::FileSystem &ModuleTranslation::getFileSystem() {
2520 if (fileSystem)
2521 return *fileSystem;
2522 return *llvm::vfs::getRealFileSystem();
2523}
2524
2526 llvm::DILocalScope *scope) {
2527 return debugTranslation->translateLoc(loc, scope);
2528}
2529
2530llvm::DIExpression *
2531ModuleTranslation::translateExpression(LLVM::DIExpressionAttr attr) {
2532 return debugTranslation->translateExpression(attr);
2533}
2534
2535llvm::DIGlobalVariableExpression *
2537 LLVM::DIGlobalVariableExpressionAttr attr) {
2538 return debugTranslation->translateGlobalVariableExpression(attr);
2539}
2540
2542 return debugTranslation->translate(attr);
2543}
2544
2545llvm::RoundingMode
2546ModuleTranslation::translateRoundingMode(LLVM::RoundingMode rounding) {
2547 return convertRoundingModeToLLVM(rounding);
2548}
2549
2551 LLVM::FPExceptionBehavior exceptionBehavior) {
2552 return convertFPExceptionBehaviorToLLVM(exceptionBehavior);
2553}
2554
2555llvm::NamedMDNode *
2557 return llvmModule->getOrInsertNamedMetadata(name);
2558}
2559
2560static std::unique_ptr<llvm::Module>
2561prepareLLVMModule(Operation *m, llvm::LLVMContext &llvmContext,
2562 StringRef name) {
2563 m->getContext()->getOrLoadDialect<LLVM::LLVMDialect>();
2564 auto llvmModule = std::make_unique<llvm::Module>(name, llvmContext);
2565 if (auto dataLayoutAttr =
2566 m->getDiscardableAttr(LLVM::LLVMDialect::getDataLayoutAttrName())) {
2567 llvmModule->setDataLayout(cast<StringAttr>(dataLayoutAttr).getValue());
2568 } else {
2569 FailureOr<llvm::DataLayout> llvmDataLayout(llvm::DataLayout(""));
2570 if (auto iface = dyn_cast<DataLayoutOpInterface>(m)) {
2571 if (DataLayoutSpecInterface spec = iface.getDataLayoutSpec()) {
2572 llvmDataLayout =
2573 translateDataLayout(spec, DataLayout(iface), m->getLoc());
2574 }
2575 } else if (auto mod = dyn_cast<ModuleOp>(m)) {
2576 if (DataLayoutSpecInterface spec = mod.getDataLayoutSpec()) {
2577 llvmDataLayout =
2578 translateDataLayout(spec, DataLayout(mod), m->getLoc());
2579 }
2580 }
2581 if (failed(llvmDataLayout))
2582 return nullptr;
2583 llvmModule->setDataLayout(*llvmDataLayout);
2584 }
2585 if (auto targetTripleAttr =
2586 m->getDiscardableAttr(LLVM::LLVMDialect::getTargetTripleAttrName()))
2587 llvmModule->setTargetTriple(
2588 llvm::Triple(cast<StringAttr>(targetTripleAttr).getValue()));
2589
2590 if (auto asmAttr = m->getDiscardableAttr(
2591 LLVM::LLVMDialect::getModuleLevelAsmAttrName())) {
2592 auto asmArrayAttr = dyn_cast<ArrayAttr>(asmAttr);
2593 if (!asmArrayAttr) {
2594 m->emitError("expected an array attribute for a module level asm");
2595 return nullptr;
2596 }
2597
2598 for (Attribute elt : asmArrayAttr) {
2599 auto asmStrAttr = dyn_cast<StringAttr>(elt);
2600 if (!asmStrAttr) {
2601 m->emitError(
2602 "expected a string attribute for each entry of a module level asm");
2603 return nullptr;
2604 }
2605 llvmModule->appendModuleInlineAsm(asmStrAttr.getValue());
2606 }
2607 }
2608
2609 return llvmModule;
2610}
2611
2612std::unique_ptr<llvm::Module>
2613mlir::translateModuleToLLVMIR(Operation *module, llvm::LLVMContext &llvmContext,
2614 StringRef name, bool disableVerification,
2615 llvm::vfs::FileSystem *fs) {
2616 if (!satisfiesLLVMModule(module)) {
2617 module->emitOpError("can not be translated to an LLVMIR module");
2618 return nullptr;
2619 }
2620
2621 std::unique_ptr<llvm::Module> llvmModule =
2622 prepareLLVMModule(module, llvmContext, name);
2623 if (!llvmModule)
2624 return nullptr;
2625
2628
2629 ModuleTranslation translator(module, std::move(llvmModule), fs);
2630 llvm::IRBuilder<llvm::TargetFolder> llvmBuilder(
2631 llvmContext,
2632 llvm::TargetFolder(translator.getLLVMModule()->getDataLayout()));
2633
2634 // Convert module before functions and operations inside, so dialect
2635 // attributes can be used to change dialect-specific global configurations via
2636 // `amendOperation()`. These configurations can then influence the translation
2637 // of operations afterwards.
2638 if (failed(translator.convertOperation(*module, llvmBuilder)))
2639 return nullptr;
2640
2641 if (failed(translator.convertComdats()))
2642 return nullptr;
2643 if (failed(translator.convertFunctionSignatures()))
2644 return nullptr;
2645 if (failed(translator.convertGlobalsAndAliases()))
2646 return nullptr;
2647 if (failed(translator.convertIFuncs()))
2648 return nullptr;
2649 if (failed(translator.createTBAAMetadata()))
2650 return nullptr;
2651 if (failed(translator.createIdentMetadata()))
2652 return nullptr;
2653 if (failed(translator.createCommandlineMetadata()))
2654 return nullptr;
2655 if (failed(translator.createDependentLibrariesMetadata()))
2656 return nullptr;
2657
2658 // Convert other top-level operations if possible.
2659 for (Operation &o : getModuleBody(module).getOperations()) {
2660 if (!isa<LLVM::LLVMFuncOp, LLVM::AliasOp, LLVM::GlobalOp,
2661 LLVM::GlobalCtorsOp, LLVM::GlobalDtorsOp, LLVM::ComdatOp,
2662 LLVM::IFuncOp>(&o) &&
2663 !o.hasTrait<OpTrait::IsTerminator>() &&
2664 failed(translator.convertOperation(o, llvmBuilder))) {
2665 return nullptr;
2666 }
2667 }
2668
2669 // Operations in function bodies with symbolic references must be converted
2670 // after the top-level operations they refer to are declared, so we do it
2671 // last.
2672 if (failed(translator.convertFunctions()))
2673 return nullptr;
2674
2675 // Now that all MLIR blocks are resolved into LLVM ones, patch block address
2676 // constants to point to the correct blocks.
2677 if (failed(translator.convertUnresolvedBlockAddress()))
2678 return nullptr;
2679
2680 // Add the necessary debug info module flags, if they were not encoded in MLIR
2681 // beforehand.
2682 translator.debugTranslation->addModuleFlagsIfNotPresent();
2683
2684 // Call the OpenMP IR Builder callbacks prior to verifying the module
2685 if (auto *ompBuilder = translator.getOpenMPBuilder())
2686 ompBuilder->finalize();
2687
2688 if (!disableVerification &&
2689 llvm::verifyModule(*translator.llvmModule, &llvm::errs()))
2690 return nullptr;
2691
2692 return std::move(translator.llvmModule);
2693}
return success()
ArrayAttr()
b getContext())
*if copies could not be generated due to yet unimplemented cases *copyInPlacementStart and copyOutPlacementStart in copyPlacementBlock *specify the insertion points where the incoming copies and outgoing should be inserted(the insertion happens right before the *insertion point). Since `begin` can itself be invalidated due to the memref *rewriting done from this method
*if copies could not be generated due to yet unimplemented cases *copyInPlacementStart and copyOutPlacementStart in copyPlacementBlock *specify the insertion points where the incoming copies and outgoing should be the output argument nBegin is set to its * replacement(set to `begin` if no invalidation happens). Since outgoing *copies could have been inserted at `end`
static Value getPHISourceValue(Block *current, Block *pred, unsigned numArguments, unsigned index)
Get the SSA value passed to the current block from the terminator operation of its predecessor.
static llvm::Type * getInnermostElementType(llvm::Type *type)
Returns the first non-sequential type nested in sequential types.
static void addRuntimePreemptionSpecifier(bool dsoLocalRequested, llvm::GlobalValue *gv)
Sets the runtime preemption specifier of gv to dso_local if dsoLocalRequested is true,...
static Block & getModuleBody(Operation *module)
A helper method to get the single Block in an operation honoring LLVM's module requirements.
static llvm::MDNode * convertIntegerArrayToMDNode(llvm::LLVMContext &context, ArrayRef< int32_t > values)
Return an MDNode with a tuple given by the values in values.
static void convertDenormalFPEnvAttribute(LLVMFuncOp func, llvm::AttrBuilder &Attrs)
static bool shouldDropGlobalInitializer(llvm::GlobalValue::LinkageTypes linkage, llvm::Constant *cst)
A helper method to decide if a constant must not be set as a global variable initializer.
static llvm::MDNode * convertIntegerToMDNode(llvm::LLVMContext &context, const llvm::APInt &value)
Return a representation of value as an MDNode.
static llvm::Metadata * convertIntegerToMetadata(llvm::LLVMContext &context, const llvm::APInt &value)
Return a representation of value as metadata.
static FailureOr< llvm::Attribute > convertMLIRAttributeToLLVM(Location loc, llvm::LLVMContext &ctx, StringRef key, StringRef value=StringRef())
Attempts to translate an MLIR attribute identified by key, optionally with the given value,...
static void convertFunctionKernelAttributes(LLVMFuncOp func, llvm::Function *llvmFunc, ModuleTranslation &translation)
Converts function attributes from func and attaches them to llvmFunc.
static LogicalResult convertParameterAttr(llvm::AttrBuilder &attrBuilder, llvm::Attribute::AttrKind llvmKind, NamedAttribute namedAttr, ModuleTranslation &moduleTranslation, Location loc)
static llvm::Constant * buildSequentialConstant(ArrayRef< llvm::Constant * > &constants, ArrayRef< int64_t > shape, llvm::Type *type, Location loc)
Builds a constant of a sequential LLVM type type, potentially containing other sequential types recur...
static FailureOr< llvm::AttrBuilder > convertMLIRAttributesToLLVM(Location loc, llvm::LLVMContext &ctx, ArrayAttr arrayAttr, StringRef arrayAttrName)
Converts the MLIR attributes listed in the given array attribute into LLVM attributes.
static void convertFunctionMemoryAttributes(LLVMFuncOp func, llvm::Function *llvmFunc)
Converts memory effect attributes from func and attaches them to llvmFunc.
static void convertFunctionAttributes(ModuleTranslation &mod, LLVMFuncOp func, llvm::Function *llvmFunc)
Converts function attributes from func and attaches them to llvmFunc.
static llvm::Constant * convertDenseResourceElementsAttr(Location loc, DenseResourceElementsAttr denseResourceAttr, llvm::Type *llvmType, const ModuleTranslation &moduleTranslation)
Convert a dense resource elements attribute to an LLVM IR constant using its raw data storage if poss...
static llvm::MDNode * convertVecTypeHintToMDNode(llvm::LLVMContext &context, llvm::Type *type, bool isSigned)
Return an MDNode encoding vec_type_hint metadata.
static llvm::Constant * convertDenseElementsAttr(Location loc, DenseElementsAttr denseElementsAttr, llvm::Type *llvmType, const ModuleTranslation &moduleTranslation)
Convert a dense elements attribute to an LLVM IR constant using its raw data storage if possible.
static std::unique_ptr< llvm::Module > prepareLLVMModule(Operation *m, llvm::LLVMContext &llvmContext, StringRef name)
static ArrayRef< int64_t > getShape(Type type)
Returns the shape of the given type.
Definition Traits.cpp:117
This class represents a processed binary blob of data.
Definition AsmState.h:91
ArrayRef< char > getData() const
Return the raw underlying data of this blob.
Definition AsmState.h:145
void addWalk(WalkFn< Attribute > &&fn)
Register a walk function for a given attribute or type.
WalkResult walk(T element)
Walk the given attribute/type, and recursively walk any sub elements.
Attributes are known-constant values of operations.
Definition Attributes.h:25
MLIRContext * getContext() const
Return the context this attribute belongs to.
Block represents an ordered list of Operations.
Definition Block.h:33
iterator_range< pred_iterator > getPredecessors()
Definition Block.h:264
Operation & front()
Definition Block.h:177
Operation * getTerminator()
Get the terminator operation of this block.
Definition Block.cpp:249
BlockArgListType getArguments()
Definition Block.h:111
iterator_range< iterator > without_terminator()
Return an iterator range over the operation within this block excluding the terminator operation at t...
Definition Block.h:236
The main mechanism for performing data layout queries.
std::optional< uint64_t > getTypeIndexBitwidth(Type t) const
Returns the bitwidth that should be used when performing index computations for the given pointer-lik...
uint64_t getTypePreferredAlignment(Type t) const
Returns the preferred of the given type in the current scope.
uint64_t getTypeABIAlignment(Type t) const
Returns the required alignment of the given type in the current scope.
llvm::TypeSize getTypeSizeInBits(Type t) const
Returns the size in bits of the given type in the current scope.
An attribute that represents a reference to a dense vector or tensor object.
int64_t getNumElements() const
Returns the number of elements held by this attribute.
std::enable_if_t<!std::is_base_of< Attribute, T >::value||std::is_same< Attribute, T >::value, T > getSplatValue() const
Return the splat value for this attribute.
bool isSplat() const
Returns true if this attribute corresponds to a splat, i.e.
ArrayRef< char > getRawData() const
Return the raw storage data held by this attribute.
ShapedType getType() const
Return the type of this ElementsAttr, guaranteed to be a vector or tensor with static shape.
const InterfaceType * getInterfaceFor(Object *obj) const
Get the interface for a given object, or null if one is not registered.
This class represents a diagnostic that is inflight and set to be reported.
This class represents the base attribute for all debug info attributes.
Definition LLVMAttrs.h:29
Implementation class for module translation.
llvm::fp::ExceptionBehavior translateFPExceptionBehavior(LLVM::FPExceptionBehavior exceptionBehavior)
Translates the given LLVM FP exception behavior metadata.
llvm::CallInst * lookupCall(Operation *op) const
Finds an LLVM call instruction that corresponds to the given MLIR call operation.
llvm::BasicBlock * lookupBlock(Block *block) const
Finds an LLVM IR basic block that corresponds to the given MLIR block.
llvm::DIGlobalVariableExpression * translateGlobalVariableExpression(LLVM::DIGlobalVariableExpressionAttr attr)
Translates the given LLVM global variable expression metadata.
llvm::Attribute convertAllocsizeAttr(DenseI32ArrayAttr allocsizeAttr)
llvm::NamedMDNode * getOrInsertNamedModuleMetadata(StringRef name)
Gets the named metadata in the LLVM IR module being constructed, creating it if it does not exist.
SmallVector< llvm::Value * > lookupValues(ValueRange values)
Looks up remapped a list of remapped values.
void mapFunction(StringRef name, llvm::Function *func)
Stores the mapping between a function name and its LLVM IR representation.
void convertFunctionAttrCollection(AttrsTy attrs, Operation *op, const Converter &conv)
A template that takes a collection-like attribute, and converts it via a user provided callback,...
llvm::DILocation * translateLoc(Location loc, llvm::DILocalScope *scope)
Translates the given location.
void setDereferenceableMetadata(DereferenceableOpInterface op, llvm::Instruction *inst)
Sets LLVM dereferenceable metadata for operations that have dereferenceable attributes.
void setBranchWeightsMetadata(WeightedBranchOpInterface op)
Sets LLVM profiling metadata for operations that have branch weights.
llvm::Instruction * lookupBranch(Operation *op) const
Finds an LLVM IR instruction that corresponds to the given MLIR operation with successors.
llvm::Value * lookupValue(Value value) const
Finds an LLVM IR value corresponding to the given MLIR value.
LogicalResult convertArgAndResultAttrs(ArgAndResultAttrsOpInterface attrsOp, llvm::CallBase *call, ArrayRef< unsigned > immArgPositions={})
Converts argument and result attributes from attrsOp to LLVM IR attributes on the call instruction.
static std::optional< llvm::Attribute > convertNoBuiltin(llvm::LLVMContext &ctx, mlir::Attribute a)
SymbolTableCollection & symbolTable()
llvm::Type * convertType(Type type)
Converts the type from MLIR LLVM dialect to LLVM.
llvm::RoundingMode translateRoundingMode(LLVM::RoundingMode rounding)
Translates the given LLVM rounding mode metadata.
void setTBAAMetadata(AliasAnalysisOpInterface op, llvm::Instruction *inst)
Sets LLVM TBAA metadata for memory operations that have TBAA attributes.
llvm::DIExpression * translateExpression(LLVM::DIExpressionAttr attr)
Translates the given LLVM DWARF expression metadata.
llvm::OpenMPIRBuilder * getOpenMPBuilder()
Returns the OpenMP IR builder associated with the LLVM IR module being constructed.
llvm::vfs::FileSystem & getFileSystem()
Returns the virtual filesystem to use for file operations.
llvm::GlobalValue * lookupGlobal(Operation *op)
Finds an LLVM IR global value that corresponds to the given MLIR operation defining a global value.
FailureOr< llvm::Metadata * > convertMetadataAttr(Attribute attr, function_ref< InFlightDiagnostic()> emitError)
Converts an LLVM dialect metadata attribute to LLVM IR metadata.
llvm::BasicBlock * lookupBlockAddress(BlockAddressAttr attr) const
Finds the LLVM basic block that corresponds to the given BlockAddressAttr.
llvm::GlobalValue * lookupIFunc(Operation *op)
Finds an LLVM IR global value that corresponds to the given MLIR operation defining an IFunc.
llvm::Metadata * translateDebugInfo(LLVM::DINodeAttr attr)
Translates the given LLVM debug info metadata.
void setDisjointFlag(Operation *op, llvm::Value *value)
Sets the disjoint flag attribute for the exported instruction value given the original operation op.
llvm::GlobalValue * lookupAlias(Operation *op)
Finds an LLVM IR global value that corresponds to the given MLIR operation defining a global alias va...
LogicalResult convertOperation(Operation &op, llvm::IRBuilderBase &builder)
Converts the given MLIR operation into LLVM IR using this translator.
llvm::Function * lookupFunction(StringRef name) const
Finds an LLVM IR function by its name.
llvm::MDNode * getOrCreateAliasScopes(ArrayRef< AliasScopeAttr > aliasScopeAttrs)
Returns the LLVM metadata corresponding to an array of mlir LLVM dialect alias scope attributes.
void mapBlock(Block *mlir, llvm::BasicBlock *llvm)
Stores the mapping between an MLIR block and LLVM IR basic block.
llvm::MDNode * getOrCreateAliasScope(AliasScopeAttr aliasScopeAttr)
Returns the LLVM metadata corresponding to a mlir LLVM dialect alias scope attribute.
llvm::Module * getLLVMModule()
Returns the LLVM module in which the IR is being constructed.
static std::optional< llvm::Attribute > convertDefaultFuncAttr(llvm::LLVMContext &ctx, mlir::NamedAttribute namedAttr)
void forgetMapping(Region &region)
Removes the mapping for blocks contained in the region and values defined in these blocks.
void setAliasScopeMetadata(AliasAnalysisOpInterface op, llvm::Instruction *inst)
void setAccessGroupsMetadata(AccessGroupOpInterface op, llvm::Instruction *inst)
void mapValue(Value mlir, llvm::Value *llvm)
Stores the mapping between an MLIR value and its LLVM IR counterpart.
llvm::LLVMContext & getLLVMContext() const
Returns the LLVM context in which the IR is being constructed.
void setLoopMetadata(Operation *op, llvm::Instruction *inst)
Sets LLVM loop metadata for branch operations that have a loop annotation attribute.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
T * getOrLoadDialect()
Get (or create) a dialect for the given derived dialect type.
NamedAttribute represents a combination of a name and an Attribute value.
Definition Attributes.h:164
StringAttr getName() const
Return the name of the attribute.
Attribute getValue() const
Return the value of the attribute.
Definition Attributes.h:179
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
Attribute getDiscardableAttr(StringRef name)
Access a discardable attribute by name, returns a null Attribute if the discardable attribute does no...
Definition Operation.h:478
Value getOperand(unsigned idx)
Definition Operation.h:375
Attribute getAttr(StringAttr name)
Return the specified attribute if present, null otherwise.
Definition Operation.h:559
unsigned getNumSuccessors()
Definition Operation.h:731
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Definition Operation.h:432
Location getLoc()
The source location the operation was defined or derived from.
Definition Operation.h:240
InFlightDiagnostic emitError(const Twine &message={})
Emit an error about fatal conditions with this operation, reporting up to any diagnostic handlers tha...
OperationName getName()
The name of an operation is the key identifier for it.
Definition Operation.h:115
dialect_attr_range getDialectAttrs()
Return a range corresponding to the dialect attributes for this operation.
Definition Operation.h:662
operand_range getOperands()
Returns an iterator on the underlying Value's.
Definition Operation.h:403
Block * getSuccessor(unsigned index)
Definition Operation.h:733
MLIRContext * getContext()
Return the context this operation is associated with.
Definition Operation.h:233
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition Region.h:26
This class models how operands are forwarded to block arguments in control flow.
bool empty() const
Returns true if there are no successor operands.
virtual Operation * lookupSymbolIn(Operation *symbolTableOp, StringAttr symbol)
Look up a symbol with the specified name within the specified symbol table operation,...
static Operation * lookupNearestSymbolFrom(Operation *from, StringAttr symbol)
Returns the operation registered with the given symbol name within the closest parent operation of,...
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
This class provides an abstraction over the different types of ranges over Values.
Definition ValueRange.h:389
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
Type getType() const
Return the type of this value.
Definition Value.h:105
void connectPHINodes(Region &region, const ModuleTranslation &state)
For all blocks in the region that were converted to LLVM IR using the given ModuleTranslation,...
llvm::CallInst * createIntrinsicCall(llvm::IRBuilderBase &builder, llvm::Intrinsic::ID intrinsic, ArrayRef< llvm::Value * > args={}, ArrayRef< llvm::Type * > tys={})
Creates a call to an LLVM IR intrinsic function with the given arguments.
static llvm::DenseMap< llvm::StringRef, llvm::Attribute::AttrKind > getAttrNameToKindMapping()
Returns a dense map from LLVM attribute name to their kind in LLVM IR dialect.
llvm::Constant * getLLVMConstant(llvm::Type *llvmType, Attribute attr, Location loc, const ModuleTranslation &moduleTranslation)
Create an LLVM IR constant of llvmType from the MLIR attribute attr.
Operation * parentLLVMModule(Operation *op)
Lookup parent Module satisfying LLVM conditions on the Module Operation.
bool satisfiesLLVMModule(Operation *op)
LLVM requires some operations to be inside of a Module operation.
void legalizeDIExpressionsRecursively(Operation *op)
Register all known legalization patterns declared here and apply them to all ops in op.
bool isCompatibleType(Type type)
Returns true if the given type is compatible with the LLVM dialect.
void ensureDistinctSuccessors(Operation *op)
Make argument-taking successors of each block distinct.
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:717
Include the generated interface declarations.
SetVector< Block * > getBlocksSortedByDominance(Region &region)
Gets a list of blocks that is sorted according to dominance.
DataLayoutSpecInterface translateDataLayout(const llvm::DataLayout &dataLayout, MLIRContext *context)
Translate the given LLVM data layout into an MLIR equivalent using the DLTI dialect.
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
Definition Utils.cpp:307
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
detail::DenseArrayAttrImpl< int32_t > DenseI32ArrayAttr
llvm::TypeSwitch< T, ResultT > TypeSwitch
Definition LLVM.h:139
std::unique_ptr< llvm::Module > translateModuleToLLVMIR(Operation *module, llvm::LLVMContext &llvmContext, llvm::StringRef name="LLVMDialectModule", bool disableVerification=false, llvm::vfs::FileSystem *fs=nullptr)
Translates a given LLVM dialect module into an LLVM IR module living in the given context.
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
Definition LLVM.h:120
llvm::function_ref< Fn > function_ref
Definition LLVM.h:147