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