xref: /llvm-project/mlir/lib/Target/LLVMIR/ModuleTranslation.cpp (revision 36c34ec967c28c77406fe85ef3237a167a243763)
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 
14 #include "mlir/Target/LLVMIR/ModuleTranslation.h"
15 
16 #include "AttrKindDetail.h"
17 #include "DebugTranslation.h"
18 #include "LoopAnnotationTranslation.h"
19 #include "mlir/Analysis/TopologicalSortUtils.h"
20 #include "mlir/Dialect/DLTI/DLTI.h"
21 #include "mlir/Dialect/LLVMIR/LLVMDialect.h"
22 #include "mlir/Dialect/LLVMIR/LLVMInterfaces.h"
23 #include "mlir/Dialect/LLVMIR/Transforms/DIExpressionLegalization.h"
24 #include "mlir/Dialect/LLVMIR/Transforms/LegalizeForExport.h"
25 #include "mlir/Dialect/OpenMP/OpenMPDialect.h"
26 #include "mlir/Dialect/OpenMP/OpenMPInterfaces.h"
27 #include "mlir/IR/AttrTypeSubElements.h"
28 #include "mlir/IR/Attributes.h"
29 #include "mlir/IR/BuiltinOps.h"
30 #include "mlir/IR/BuiltinTypes.h"
31 #include "mlir/IR/DialectResourceBlobManager.h"
32 #include "mlir/IR/RegionGraphTraits.h"
33 #include "mlir/Support/LLVM.h"
34 #include "mlir/Target/LLVMIR/LLVMTranslationInterface.h"
35 #include "mlir/Target/LLVMIR/TypeToLLVM.h"
36 
37 #include "llvm/ADT/PostOrderIterator.h"
38 #include "llvm/ADT/SetVector.h"
39 #include "llvm/ADT/StringExtras.h"
40 #include "llvm/ADT/TypeSwitch.h"
41 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
42 #include "llvm/IR/BasicBlock.h"
43 #include "llvm/IR/CFG.h"
44 #include "llvm/IR/Constants.h"
45 #include "llvm/IR/DerivedTypes.h"
46 #include "llvm/IR/IRBuilder.h"
47 #include "llvm/IR/InlineAsm.h"
48 #include "llvm/IR/IntrinsicsNVPTX.h"
49 #include "llvm/IR/LLVMContext.h"
50 #include "llvm/IR/MDBuilder.h"
51 #include "llvm/IR/Module.h"
52 #include "llvm/IR/Verifier.h"
53 #include "llvm/Support/Debug.h"
54 #include "llvm/Support/raw_ostream.h"
55 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
56 #include "llvm/Transforms/Utils/Cloning.h"
57 #include "llvm/Transforms/Utils/ModuleUtils.h"
58 #include <optional>
59 
60 #define DEBUG_TYPE "llvm-dialect-to-llvm-ir"
61 
62 using namespace mlir;
63 using namespace mlir::LLVM;
64 using namespace mlir::LLVM::detail;
65 
66 extern llvm::cl::opt<bool> UseNewDbgInfoFormat;
67 
68 #include "mlir/Dialect/LLVMIR/LLVMConversionEnumsToLLVM.inc"
69 
70 namespace {
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`.
91 class InstructionCapturingInserter : public llvm::IRBuilderCallbackInserter {
92 public:
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 
137 private:
138   /// List of captured instructions.
139   SmallVector<llvm::Instruction *> capturedInstructions;
140 
141   /// Whether the collection is enabled.
142   bool enabled = false;
143 };
144 
145 using CapturingIRBuilder =
146     llvm::IRBuilder<llvm::ConstantFolder, InstructionCapturingInserter>;
147 } // namespace
148 
149 InstructionCapturingInserter::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 
163 InstructionCapturingInserter::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.
179 static FailureOr<llvm::DataLayout>
180 translateDataLayout(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::kDataLayoutProgramMemorySpaceKey) {
201       auto value = cast<IntegerAttr>(entry.getValue());
202       uint64_t space = value.getValue().getZExtValue();
203       // Skip the default address space.
204       if (space == 0)
205         continue;
206       layoutStream << "-P" << space;
207       continue;
208     }
209     if (key.getValue() == DLTIDialect::kDataLayoutGlobalMemorySpaceKey) {
210       auto value = cast<IntegerAttr>(entry.getValue());
211       uint64_t space = value.getValue().getZExtValue();
212       // Skip the default address space.
213       if (space == 0)
214         continue;
215       layoutStream << "-G" << space;
216       continue;
217     }
218     if (key.getValue() == DLTIDialect::kDataLayoutAllocaMemorySpaceKey) {
219       auto value = cast<IntegerAttr>(entry.getValue());
220       uint64_t space = value.getValue().getZExtValue();
221       // Skip the default address space.
222       if (space == 0)
223         continue;
224       layoutStream << "-A" << space;
225       continue;
226     }
227     if (key.getValue() == DLTIDialect::kDataLayoutStackAlignmentKey) {
228       auto value = cast<IntegerAttr>(entry.getValue());
229       uint64_t alignment = value.getValue().getZExtValue();
230       // Skip the default stack alignment.
231       if (alignment == 0)
232         continue;
233       layoutStream << "-S" << alignment;
234       continue;
235     }
236     emitError(*loc) << "unsupported data layout key " << key;
237     return failure();
238   }
239 
240   // Go through the list of entries to check which types are explicitly
241   // specified in entries. Where possible, data layout queries are used instead
242   // of directly inspecting the entries.
243   for (DataLayoutEntryInterface entry : attribute.getEntries()) {
244     auto type = llvm::dyn_cast_if_present<Type>(entry.getKey());
245     if (!type)
246       continue;
247     // Data layout for the index type is irrelevant at this point.
248     if (isa<IndexType>(type))
249       continue;
250     layoutStream << "-";
251     LogicalResult result =
252         llvm::TypeSwitch<Type, LogicalResult>(type)
253             .Case<IntegerType, Float16Type, Float32Type, Float64Type,
254                   Float80Type, Float128Type>([&](Type type) -> LogicalResult {
255               if (auto intType = dyn_cast<IntegerType>(type)) {
256                 if (intType.getSignedness() != IntegerType::Signless)
257                   return emitError(*loc)
258                          << "unsupported data layout for non-signless integer "
259                          << intType;
260                 layoutStream << "i";
261               } else {
262                 layoutStream << "f";
263               }
264               uint64_t size = dataLayout.getTypeSizeInBits(type);
265               uint64_t abi = dataLayout.getTypeABIAlignment(type) * 8u;
266               uint64_t preferred =
267                   dataLayout.getTypePreferredAlignment(type) * 8u;
268               layoutStream << size << ":" << abi;
269               if (abi != preferred)
270                 layoutStream << ":" << preferred;
271               return success();
272             })
273             .Case([&](LLVMPointerType type) {
274               layoutStream << "p" << type.getAddressSpace() << ":";
275               uint64_t size = dataLayout.getTypeSizeInBits(type);
276               uint64_t abi = dataLayout.getTypeABIAlignment(type) * 8u;
277               uint64_t preferred =
278                   dataLayout.getTypePreferredAlignment(type) * 8u;
279               uint64_t index = *dataLayout.getTypeIndexBitwidth(type);
280               layoutStream << size << ":" << abi << ":" << preferred << ":"
281                            << index;
282               return success();
283             })
284             .Default([loc](Type type) {
285               return emitError(*loc)
286                      << "unsupported type in data layout: " << type;
287             });
288     if (failed(result))
289       return failure();
290   }
291   StringRef layoutSpec(llvmDataLayout);
292   if (layoutSpec.starts_with("-"))
293     layoutSpec = layoutSpec.drop_front();
294 
295   return llvm::DataLayout(layoutSpec);
296 }
297 
298 /// Builds a constant of a sequential LLVM type `type`, potentially containing
299 /// other sequential types recursively, from the individual constant values
300 /// provided in `constants`. `shape` contains the number of elements in nested
301 /// sequential types. Reports errors at `loc` and returns nullptr on error.
302 static llvm::Constant *
303 buildSequentialConstant(ArrayRef<llvm::Constant *> &constants,
304                         ArrayRef<int64_t> shape, llvm::Type *type,
305                         Location loc) {
306   if (shape.empty()) {
307     llvm::Constant *result = constants.front();
308     constants = constants.drop_front();
309     return result;
310   }
311 
312   llvm::Type *elementType;
313   if (auto *arrayTy = dyn_cast<llvm::ArrayType>(type)) {
314     elementType = arrayTy->getElementType();
315   } else if (auto *vectorTy = dyn_cast<llvm::VectorType>(type)) {
316     elementType = vectorTy->getElementType();
317   } else {
318     emitError(loc) << "expected sequential LLVM types wrapping a scalar";
319     return nullptr;
320   }
321 
322   SmallVector<llvm::Constant *, 8> nested;
323   nested.reserve(shape.front());
324   for (int64_t i = 0; i < shape.front(); ++i) {
325     nested.push_back(buildSequentialConstant(constants, shape.drop_front(),
326                                              elementType, loc));
327     if (!nested.back())
328       return nullptr;
329   }
330 
331   if (shape.size() == 1 && type->isVectorTy())
332     return llvm::ConstantVector::get(nested);
333   return llvm::ConstantArray::get(
334       llvm::ArrayType::get(elementType, shape.front()), nested);
335 }
336 
337 /// Returns the first non-sequential type nested in sequential types.
338 static llvm::Type *getInnermostElementType(llvm::Type *type) {
339   do {
340     if (auto *arrayTy = dyn_cast<llvm::ArrayType>(type)) {
341       type = arrayTy->getElementType();
342     } else if (auto *vectorTy = dyn_cast<llvm::VectorType>(type)) {
343       type = vectorTy->getElementType();
344     } else {
345       return type;
346     }
347   } while (true);
348 }
349 
350 /// Convert a dense elements attribute to an LLVM IR constant using its raw data
351 /// storage if possible. This supports elements attributes of tensor or vector
352 /// type and avoids constructing separate objects for individual values of the
353 /// innermost dimension. Constants for other dimensions are still constructed
354 /// recursively. Returns null if constructing from raw data is not supported for
355 /// this type, e.g., element type is not a power-of-two-sized primitive. Reports
356 /// other errors at `loc`.
357 static llvm::Constant *
358 convertDenseElementsAttr(Location loc, DenseElementsAttr denseElementsAttr,
359                          llvm::Type *llvmType,
360                          const ModuleTranslation &moduleTranslation) {
361   if (!denseElementsAttr)
362     return nullptr;
363 
364   llvm::Type *innermostLLVMType = getInnermostElementType(llvmType);
365   if (!llvm::ConstantDataSequential::isElementTypeCompatible(innermostLLVMType))
366     return nullptr;
367 
368   ShapedType type = denseElementsAttr.getType();
369   if (type.getNumElements() == 0)
370     return nullptr;
371 
372   // Check that the raw data size matches what is expected for the scalar size.
373   // TODO: in theory, we could repack the data here to keep constructing from
374   // raw data.
375   // TODO: we may also need to consider endianness when cross-compiling to an
376   // architecture where it is different.
377   int64_t elementByteSize = denseElementsAttr.getRawData().size() /
378                             denseElementsAttr.getNumElements();
379   if (8 * elementByteSize != innermostLLVMType->getScalarSizeInBits())
380     return nullptr;
381 
382   // Compute the shape of all dimensions but the innermost. Note that the
383   // innermost dimension may be that of the vector element type.
384   bool hasVectorElementType = isa<VectorType>(type.getElementType());
385   int64_t numAggregates =
386       denseElementsAttr.getNumElements() /
387       (hasVectorElementType ? 1
388                             : denseElementsAttr.getType().getShape().back());
389   ArrayRef<int64_t> outerShape = type.getShape();
390   if (!hasVectorElementType)
391     outerShape = outerShape.drop_back();
392 
393   // Handle the case of vector splat, LLVM has special support for it.
394   if (denseElementsAttr.isSplat() &&
395       (isa<VectorType>(type) || hasVectorElementType)) {
396     llvm::Constant *splatValue = LLVM::detail::getLLVMConstant(
397         innermostLLVMType, denseElementsAttr.getSplatValue<Attribute>(), loc,
398         moduleTranslation);
399     llvm::Constant *splatVector =
400         llvm::ConstantDataVector::getSplat(0, splatValue);
401     SmallVector<llvm::Constant *> constants(numAggregates, splatVector);
402     ArrayRef<llvm::Constant *> constantsRef = constants;
403     return buildSequentialConstant(constantsRef, outerShape, llvmType, loc);
404   }
405   if (denseElementsAttr.isSplat())
406     return nullptr;
407 
408   // In case of non-splat, create a constructor for the innermost constant from
409   // a piece of raw data.
410   std::function<llvm::Constant *(StringRef)> buildCstData;
411   if (isa<TensorType>(type)) {
412     auto vectorElementType = dyn_cast<VectorType>(type.getElementType());
413     if (vectorElementType && vectorElementType.getRank() == 1) {
414       buildCstData = [&](StringRef data) {
415         return llvm::ConstantDataVector::getRaw(
416             data, vectorElementType.getShape().back(), innermostLLVMType);
417       };
418     } else if (!vectorElementType) {
419       buildCstData = [&](StringRef data) {
420         return llvm::ConstantDataArray::getRaw(data, type.getShape().back(),
421                                                innermostLLVMType);
422       };
423     }
424   } else if (isa<VectorType>(type)) {
425     buildCstData = [&](StringRef data) {
426       return llvm::ConstantDataVector::getRaw(data, type.getShape().back(),
427                                               innermostLLVMType);
428     };
429   }
430   if (!buildCstData)
431     return nullptr;
432 
433   // Create innermost constants and defer to the default constant creation
434   // mechanism for other dimensions.
435   SmallVector<llvm::Constant *> constants;
436   int64_t aggregateSize = denseElementsAttr.getType().getShape().back() *
437                           (innermostLLVMType->getScalarSizeInBits() / 8);
438   constants.reserve(numAggregates);
439   for (unsigned i = 0; i < numAggregates; ++i) {
440     StringRef data(denseElementsAttr.getRawData().data() + i * aggregateSize,
441                    aggregateSize);
442     constants.push_back(buildCstData(data));
443   }
444 
445   ArrayRef<llvm::Constant *> constantsRef = constants;
446   return buildSequentialConstant(constantsRef, outerShape, llvmType, loc);
447 }
448 
449 /// Convert a dense resource elements attribute to an LLVM IR constant using its
450 /// raw data storage if possible. This supports elements attributes of tensor or
451 /// vector type and avoids constructing separate objects for individual values
452 /// of the innermost dimension. Constants for other dimensions are still
453 /// constructed recursively. Returns nullptr on failure and emits errors at
454 /// `loc`.
455 static llvm::Constant *convertDenseResourceElementsAttr(
456     Location loc, DenseResourceElementsAttr denseResourceAttr,
457     llvm::Type *llvmType, const ModuleTranslation &moduleTranslation) {
458   assert(denseResourceAttr && "expected non-null attribute");
459 
460   llvm::Type *innermostLLVMType = getInnermostElementType(llvmType);
461   if (!llvm::ConstantDataSequential::isElementTypeCompatible(
462           innermostLLVMType)) {
463     emitError(loc, "no known conversion for innermost element type");
464     return nullptr;
465   }
466 
467   ShapedType type = denseResourceAttr.getType();
468   assert(type.getNumElements() > 0 && "Expected non-empty elements attribute");
469 
470   AsmResourceBlob *blob = denseResourceAttr.getRawHandle().getBlob();
471   if (!blob) {
472     emitError(loc, "resource does not exist");
473     return nullptr;
474   }
475 
476   ArrayRef<char> rawData = blob->getData();
477 
478   // Check that the raw data size matches what is expected for the scalar size.
479   // TODO: in theory, we could repack the data here to keep constructing from
480   // raw data.
481   // TODO: we may also need to consider endianness when cross-compiling to an
482   // architecture where it is different.
483   int64_t numElements = denseResourceAttr.getType().getNumElements();
484   int64_t elementByteSize = rawData.size() / numElements;
485   if (8 * elementByteSize != innermostLLVMType->getScalarSizeInBits()) {
486     emitError(loc, "raw data size does not match element type size");
487     return nullptr;
488   }
489 
490   // Compute the shape of all dimensions but the innermost. Note that the
491   // innermost dimension may be that of the vector element type.
492   bool hasVectorElementType = isa<VectorType>(type.getElementType());
493   int64_t numAggregates =
494       numElements / (hasVectorElementType
495                          ? 1
496                          : denseResourceAttr.getType().getShape().back());
497   ArrayRef<int64_t> outerShape = type.getShape();
498   if (!hasVectorElementType)
499     outerShape = outerShape.drop_back();
500 
501   // Create a constructor for the innermost constant from a piece of raw data.
502   std::function<llvm::Constant *(StringRef)> buildCstData;
503   if (isa<TensorType>(type)) {
504     auto vectorElementType = dyn_cast<VectorType>(type.getElementType());
505     if (vectorElementType && vectorElementType.getRank() == 1) {
506       buildCstData = [&](StringRef data) {
507         return llvm::ConstantDataVector::getRaw(
508             data, vectorElementType.getShape().back(), innermostLLVMType);
509       };
510     } else if (!vectorElementType) {
511       buildCstData = [&](StringRef data) {
512         return llvm::ConstantDataArray::getRaw(data, type.getShape().back(),
513                                                innermostLLVMType);
514       };
515     }
516   } else if (isa<VectorType>(type)) {
517     buildCstData = [&](StringRef data) {
518       return llvm::ConstantDataVector::getRaw(data, type.getShape().back(),
519                                               innermostLLVMType);
520     };
521   }
522   if (!buildCstData) {
523     emitError(loc, "unsupported dense_resource type");
524     return nullptr;
525   }
526 
527   // Create innermost constants and defer to the default constant creation
528   // mechanism for other dimensions.
529   SmallVector<llvm::Constant *> constants;
530   int64_t aggregateSize = denseResourceAttr.getType().getShape().back() *
531                           (innermostLLVMType->getScalarSizeInBits() / 8);
532   constants.reserve(numAggregates);
533   for (unsigned i = 0; i < numAggregates; ++i) {
534     StringRef data(rawData.data() + i * aggregateSize, aggregateSize);
535     constants.push_back(buildCstData(data));
536   }
537 
538   ArrayRef<llvm::Constant *> constantsRef = constants;
539   return buildSequentialConstant(constantsRef, outerShape, llvmType, loc);
540 }
541 
542 /// Create an LLVM IR constant of `llvmType` from the MLIR attribute `attr`.
543 /// This currently supports integer, floating point, splat and dense element
544 /// attributes and combinations thereof. Also, an array attribute with two
545 /// elements is supported to represent a complex constant.  In case of error,
546 /// report it to `loc` and return nullptr.
547 llvm::Constant *mlir::LLVM::detail::getLLVMConstant(
548     llvm::Type *llvmType, Attribute attr, Location loc,
549     const ModuleTranslation &moduleTranslation) {
550   if (!attr)
551     return llvm::UndefValue::get(llvmType);
552   if (auto *structType = dyn_cast<::llvm::StructType>(llvmType)) {
553     auto arrayAttr = dyn_cast<ArrayAttr>(attr);
554     if (!arrayAttr) {
555       emitError(loc, "expected an array attribute for a struct constant");
556       return nullptr;
557     }
558     SmallVector<llvm::Constant *> structElements;
559     structElements.reserve(structType->getNumElements());
560     for (auto [elemType, elemAttr] :
561          zip_equal(structType->elements(), arrayAttr)) {
562       llvm::Constant *element =
563           getLLVMConstant(elemType, elemAttr, loc, moduleTranslation);
564       if (!element)
565         return nullptr;
566       structElements.push_back(element);
567     }
568     return llvm::ConstantStruct::get(structType, structElements);
569   }
570   // For integer types, we allow a mismatch in sizes as the index type in
571   // MLIR might have a different size than the index type in the LLVM module.
572   if (auto intAttr = dyn_cast<IntegerAttr>(attr))
573     return llvm::ConstantInt::get(
574         llvmType,
575         intAttr.getValue().sextOrTrunc(llvmType->getIntegerBitWidth()));
576   if (auto floatAttr = dyn_cast<FloatAttr>(attr)) {
577     const llvm::fltSemantics &sem = floatAttr.getValue().getSemantics();
578     // Special case for 8-bit floats, which are represented by integers due to
579     // the lack of native fp8 types in LLVM at the moment. Additionally, handle
580     // targets (like AMDGPU) that don't implement bfloat and convert all bfloats
581     // to i16.
582     unsigned floatWidth = APFloat::getSizeInBits(sem);
583     if (llvmType->isIntegerTy(floatWidth))
584       return llvm::ConstantInt::get(llvmType,
585                                     floatAttr.getValue().bitcastToAPInt());
586     if (llvmType !=
587         llvm::Type::getFloatingPointTy(llvmType->getContext(),
588                                        floatAttr.getValue().getSemantics())) {
589       emitError(loc, "FloatAttr does not match expected type of the constant");
590       return nullptr;
591     }
592     return llvm::ConstantFP::get(llvmType, floatAttr.getValue());
593   }
594   if (auto funcAttr = dyn_cast<FlatSymbolRefAttr>(attr))
595     return llvm::ConstantExpr::getBitCast(
596         moduleTranslation.lookupFunction(funcAttr.getValue()), llvmType);
597   if (auto splatAttr = dyn_cast<SplatElementsAttr>(attr)) {
598     llvm::Type *elementType;
599     uint64_t numElements;
600     bool isScalable = false;
601     if (auto *arrayTy = dyn_cast<llvm::ArrayType>(llvmType)) {
602       elementType = arrayTy->getElementType();
603       numElements = arrayTy->getNumElements();
604     } else if (auto *fVectorTy = dyn_cast<llvm::FixedVectorType>(llvmType)) {
605       elementType = fVectorTy->getElementType();
606       numElements = fVectorTy->getNumElements();
607     } else if (auto *sVectorTy = dyn_cast<llvm::ScalableVectorType>(llvmType)) {
608       elementType = sVectorTy->getElementType();
609       numElements = sVectorTy->getMinNumElements();
610       isScalable = true;
611     } else {
612       llvm_unreachable("unrecognized constant vector type");
613     }
614     // Splat value is a scalar. Extract it only if the element type is not
615     // another sequence type. The recursion terminates because each step removes
616     // one outer sequential type.
617     bool elementTypeSequential =
618         isa<llvm::ArrayType, llvm::VectorType>(elementType);
619     llvm::Constant *child = getLLVMConstant(
620         elementType,
621         elementTypeSequential ? splatAttr
622                               : splatAttr.getSplatValue<Attribute>(),
623         loc, moduleTranslation);
624     if (!child)
625       return nullptr;
626     if (llvmType->isVectorTy())
627       return llvm::ConstantVector::getSplat(
628           llvm::ElementCount::get(numElements, /*Scalable=*/isScalable), child);
629     if (llvmType->isArrayTy()) {
630       auto *arrayType = llvm::ArrayType::get(elementType, numElements);
631       if (child->isZeroValue()) {
632         return llvm::ConstantAggregateZero::get(arrayType);
633       } else {
634         if (llvm::ConstantDataSequential::isElementTypeCompatible(
635                 elementType)) {
636           // TODO: Handle all compatible types. This code only handles integer.
637           if (isa<llvm::IntegerType>(elementType)) {
638             if (llvm::ConstantInt *ci = dyn_cast<llvm::ConstantInt>(child)) {
639               if (ci->getBitWidth() == 8) {
640                 SmallVector<int8_t> constants(numElements, ci->getZExtValue());
641                 return llvm::ConstantDataArray::get(elementType->getContext(),
642                                                     constants);
643               }
644               if (ci->getBitWidth() == 16) {
645                 SmallVector<int16_t> constants(numElements, ci->getZExtValue());
646                 return llvm::ConstantDataArray::get(elementType->getContext(),
647                                                     constants);
648               }
649               if (ci->getBitWidth() == 32) {
650                 SmallVector<int32_t> constants(numElements, ci->getZExtValue());
651                 return llvm::ConstantDataArray::get(elementType->getContext(),
652                                                     constants);
653               }
654               if (ci->getBitWidth() == 64) {
655                 SmallVector<int64_t> constants(numElements, ci->getZExtValue());
656                 return llvm::ConstantDataArray::get(elementType->getContext(),
657                                                     constants);
658               }
659             }
660           }
661         }
662         // std::vector is used here to accomodate large number of elements that
663         // exceed SmallVector capacity.
664         std::vector<llvm::Constant *> constants(numElements, child);
665         return llvm::ConstantArray::get(arrayType, constants);
666       }
667     }
668   }
669 
670   // Try using raw elements data if possible.
671   if (llvm::Constant *result =
672           convertDenseElementsAttr(loc, dyn_cast<DenseElementsAttr>(attr),
673                                    llvmType, moduleTranslation)) {
674     return result;
675   }
676 
677   if (auto denseResourceAttr = dyn_cast<DenseResourceElementsAttr>(attr)) {
678     return convertDenseResourceElementsAttr(loc, denseResourceAttr, llvmType,
679                                             moduleTranslation);
680   }
681 
682   // Fall back to element-by-element construction otherwise.
683   if (auto elementsAttr = dyn_cast<ElementsAttr>(attr)) {
684     assert(elementsAttr.getShapedType().hasStaticShape());
685     assert(!elementsAttr.getShapedType().getShape().empty() &&
686            "unexpected empty elements attribute shape");
687 
688     SmallVector<llvm::Constant *, 8> constants;
689     constants.reserve(elementsAttr.getNumElements());
690     llvm::Type *innermostType = getInnermostElementType(llvmType);
691     for (auto n : elementsAttr.getValues<Attribute>()) {
692       constants.push_back(
693           getLLVMConstant(innermostType, n, loc, moduleTranslation));
694       if (!constants.back())
695         return nullptr;
696     }
697     ArrayRef<llvm::Constant *> constantsRef = constants;
698     llvm::Constant *result = buildSequentialConstant(
699         constantsRef, elementsAttr.getShapedType().getShape(), llvmType, loc);
700     assert(constantsRef.empty() && "did not consume all elemental constants");
701     return result;
702   }
703 
704   if (auto stringAttr = dyn_cast<StringAttr>(attr)) {
705     return llvm::ConstantDataArray::get(
706         moduleTranslation.getLLVMContext(),
707         ArrayRef<char>{stringAttr.getValue().data(),
708                        stringAttr.getValue().size()});
709   }
710   emitError(loc, "unsupported constant value");
711   return nullptr;
712 }
713 
714 ModuleTranslation::ModuleTranslation(Operation *module,
715                                      std::unique_ptr<llvm::Module> llvmModule)
716     : mlirModule(module), llvmModule(std::move(llvmModule)),
717       debugTranslation(
718           std::make_unique<DebugTranslation>(module, *this->llvmModule)),
719       loopAnnotationTranslation(std::make_unique<LoopAnnotationTranslation>(
720           *this, *this->llvmModule)),
721       typeTranslator(this->llvmModule->getContext()),
722       iface(module->getContext()) {
723   assert(satisfiesLLVMModule(mlirModule) &&
724          "mlirModule should honor LLVM's module semantics.");
725 }
726 
727 ModuleTranslation::~ModuleTranslation() {
728   if (ompBuilder)
729     ompBuilder->finalize();
730 }
731 
732 void ModuleTranslation::forgetMapping(Region &region) {
733   SmallVector<Region *> toProcess;
734   toProcess.push_back(&region);
735   while (!toProcess.empty()) {
736     Region *current = toProcess.pop_back_val();
737     for (Block &block : *current) {
738       blockMapping.erase(&block);
739       for (Value arg : block.getArguments())
740         valueMapping.erase(arg);
741       for (Operation &op : block) {
742         for (Value value : op.getResults())
743           valueMapping.erase(value);
744         if (op.hasSuccessors())
745           branchMapping.erase(&op);
746         if (isa<LLVM::GlobalOp>(op))
747           globalsMapping.erase(&op);
748         if (isa<LLVM::CallOp>(op))
749           callMapping.erase(&op);
750         llvm::append_range(
751             toProcess,
752             llvm::map_range(op.getRegions(), [](Region &r) { return &r; }));
753       }
754     }
755   }
756 }
757 
758 /// Get the SSA value passed to the current block from the terminator operation
759 /// of its predecessor.
760 static Value getPHISourceValue(Block *current, Block *pred,
761                                unsigned numArguments, unsigned index) {
762   Operation &terminator = *pred->getTerminator();
763   if (isa<LLVM::BrOp>(terminator))
764     return terminator.getOperand(index);
765 
766 #ifndef NDEBUG
767   llvm::SmallPtrSet<Block *, 4> seenSuccessors;
768   for (unsigned i = 0, e = terminator.getNumSuccessors(); i < e; ++i) {
769     Block *successor = terminator.getSuccessor(i);
770     auto branch = cast<BranchOpInterface>(terminator);
771     SuccessorOperands successorOperands = branch.getSuccessorOperands(i);
772     assert(
773         (!seenSuccessors.contains(successor) || successorOperands.empty()) &&
774         "successors with arguments in LLVM branches must be different blocks");
775     seenSuccessors.insert(successor);
776   }
777 #endif
778 
779   // For instructions that branch based on a condition value, we need to take
780   // the operands for the branch that was taken.
781   if (auto condBranchOp = dyn_cast<LLVM::CondBrOp>(terminator)) {
782     // For conditional branches, we take the operands from either the "true" or
783     // the "false" branch.
784     return condBranchOp.getSuccessor(0) == current
785                ? condBranchOp.getTrueDestOperands()[index]
786                : condBranchOp.getFalseDestOperands()[index];
787   }
788 
789   if (auto switchOp = dyn_cast<LLVM::SwitchOp>(terminator)) {
790     // For switches, we take the operands from either the default case, or from
791     // the case branch that was taken.
792     if (switchOp.getDefaultDestination() == current)
793       return switchOp.getDefaultOperands()[index];
794     for (const auto &i : llvm::enumerate(switchOp.getCaseDestinations()))
795       if (i.value() == current)
796         return switchOp.getCaseOperands(i.index())[index];
797   }
798 
799   if (auto invokeOp = dyn_cast<LLVM::InvokeOp>(terminator)) {
800     return invokeOp.getNormalDest() == current
801                ? invokeOp.getNormalDestOperands()[index]
802                : invokeOp.getUnwindDestOperands()[index];
803   }
804 
805   llvm_unreachable(
806       "only branch, switch or invoke operations can be terminators "
807       "of a block that has successors");
808 }
809 
810 /// Connect the PHI nodes to the results of preceding blocks.
811 void mlir::LLVM::detail::connectPHINodes(Region &region,
812                                          const ModuleTranslation &state) {
813   // Skip the first block, it cannot be branched to and its arguments correspond
814   // to the arguments of the LLVM function.
815   for (Block &bb : llvm::drop_begin(region)) {
816     llvm::BasicBlock *llvmBB = state.lookupBlock(&bb);
817     auto phis = llvmBB->phis();
818     auto numArguments = bb.getNumArguments();
819     assert(numArguments == std::distance(phis.begin(), phis.end()));
820     for (auto [index, phiNode] : llvm::enumerate(phis)) {
821       for (auto *pred : bb.getPredecessors()) {
822         // Find the LLVM IR block that contains the converted terminator
823         // instruction and use it in the PHI node. Note that this block is not
824         // necessarily the same as state.lookupBlock(pred), some operations
825         // (in particular, OpenMP operations using OpenMPIRBuilder) may have
826         // split the blocks.
827         llvm::Instruction *terminator =
828             state.lookupBranch(pred->getTerminator());
829         assert(terminator && "missing the mapping for a terminator");
830         phiNode.addIncoming(state.lookupValue(getPHISourceValue(
831                                 &bb, pred, numArguments, index)),
832                             terminator->getParent());
833       }
834     }
835   }
836 }
837 
838 llvm::CallInst *mlir::LLVM::detail::createIntrinsicCall(
839     llvm::IRBuilderBase &builder, llvm::Intrinsic::ID intrinsic,
840     ArrayRef<llvm::Value *> args, ArrayRef<llvm::Type *> tys) {
841   llvm::Module *module = builder.GetInsertBlock()->getModule();
842   llvm::Function *fn = llvm::Intrinsic::getDeclaration(module, intrinsic, tys);
843   return builder.CreateCall(fn, args);
844 }
845 
846 llvm::CallInst *mlir::LLVM::detail::createIntrinsicCall(
847     llvm::IRBuilderBase &builder, ModuleTranslation &moduleTranslation,
848     Operation *intrOp, llvm::Intrinsic::ID intrinsic, unsigned numResults,
849     ArrayRef<unsigned> overloadedResults, ArrayRef<unsigned> overloadedOperands,
850     ArrayRef<unsigned> immArgPositions,
851     ArrayRef<StringLiteral> immArgAttrNames) {
852   assert(immArgPositions.size() == immArgAttrNames.size() &&
853          "LLVM `immArgPositions` and MLIR `immArgAttrNames` should have equal "
854          "length");
855 
856   // Map operands and attributes to LLVM values.
857   auto operands = moduleTranslation.lookupValues(intrOp->getOperands());
858   SmallVector<llvm::Value *> args(immArgPositions.size() + operands.size());
859   for (auto [immArgPos, immArgName] :
860        llvm::zip(immArgPositions, immArgAttrNames)) {
861     auto attr = llvm::cast<TypedAttr>(intrOp->getAttr(immArgName));
862     assert(attr.getType().isIntOrFloat() && "expected int or float immarg");
863     auto *type = moduleTranslation.convertType(attr.getType());
864     args[immArgPos] = LLVM::detail::getLLVMConstant(
865         type, attr, intrOp->getLoc(), moduleTranslation);
866   }
867   unsigned opArg = 0;
868   for (auto &arg : args) {
869     if (!arg)
870       arg = operands[opArg++];
871   }
872 
873   // Resolve overloaded intrinsic declaration.
874   SmallVector<llvm::Type *> overloadedTypes;
875   for (unsigned overloadedResultIdx : overloadedResults) {
876     if (numResults > 1) {
877       // More than one result is mapped to an LLVM struct.
878       overloadedTypes.push_back(moduleTranslation.convertType(
879           llvm::cast<LLVM::LLVMStructType>(intrOp->getResult(0).getType())
880               .getBody()[overloadedResultIdx]));
881     } else {
882       overloadedTypes.push_back(
883           moduleTranslation.convertType(intrOp->getResult(0).getType()));
884     }
885   }
886   for (unsigned overloadedOperandIdx : overloadedOperands)
887     overloadedTypes.push_back(args[overloadedOperandIdx]->getType());
888   llvm::Module *module = builder.GetInsertBlock()->getModule();
889   llvm::Function *llvmIntr =
890       llvm::Intrinsic::getDeclaration(module, intrinsic, overloadedTypes);
891 
892   return builder.CreateCall(llvmIntr, args);
893 }
894 
895 /// Given a single MLIR operation, create the corresponding LLVM IR operation
896 /// using the `builder`.
897 LogicalResult ModuleTranslation::convertOperation(Operation &op,
898                                                   llvm::IRBuilderBase &builder,
899                                                   bool recordInsertions) {
900   const LLVMTranslationDialectInterface *opIface = iface.getInterfaceFor(&op);
901   if (!opIface)
902     return op.emitError("cannot be converted to LLVM IR: missing "
903                         "`LLVMTranslationDialectInterface` registration for "
904                         "dialect for op: ")
905            << op.getName();
906 
907   InstructionCapturingInserter::CollectionScope scope(builder,
908                                                       recordInsertions);
909   if (failed(opIface->convertOperation(&op, builder, *this)))
910     return op.emitError("LLVM Translation failed for operation: ")
911            << op.getName();
912 
913   return convertDialectAttributes(&op, scope.getCapturedInstructions());
914 }
915 
916 /// Convert block to LLVM IR.  Unless `ignoreArguments` is set, emit PHI nodes
917 /// to define values corresponding to the MLIR block arguments.  These nodes
918 /// are not connected to the source basic blocks, which may not exist yet.  Uses
919 /// `builder` to construct the LLVM IR. Expects the LLVM IR basic block to have
920 /// been created for `bb` and included in the block mapping.  Inserts new
921 /// instructions at the end of the block and leaves `builder` in a state
922 /// suitable for further insertion into the end of the block.
923 LogicalResult ModuleTranslation::convertBlockImpl(Block &bb,
924                                                   bool ignoreArguments,
925                                                   llvm::IRBuilderBase &builder,
926                                                   bool recordInsertions) {
927   builder.SetInsertPoint(lookupBlock(&bb));
928   auto *subprogram = builder.GetInsertBlock()->getParent()->getSubprogram();
929 
930   // Before traversing operations, make block arguments available through
931   // value remapping and PHI nodes, but do not add incoming edges for the PHI
932   // nodes just yet: those values may be defined by this or following blocks.
933   // This step is omitted if "ignoreArguments" is set.  The arguments of the
934   // first block have been already made available through the remapping of
935   // LLVM function arguments.
936   if (!ignoreArguments) {
937     auto predecessors = bb.getPredecessors();
938     unsigned numPredecessors =
939         std::distance(predecessors.begin(), predecessors.end());
940     for (auto arg : bb.getArguments()) {
941       auto wrappedType = arg.getType();
942       if (!isCompatibleType(wrappedType))
943         return emitError(bb.front().getLoc(),
944                          "block argument does not have an LLVM type");
945       builder.SetCurrentDebugLocation(
946           debugTranslation->translateLoc(arg.getLoc(), subprogram));
947       llvm::Type *type = convertType(wrappedType);
948       llvm::PHINode *phi = builder.CreatePHI(type, numPredecessors);
949       mapValue(arg, phi);
950     }
951   }
952 
953   // Traverse operations.
954   for (auto &op : bb) {
955     // Set the current debug location within the builder.
956     builder.SetCurrentDebugLocation(
957         debugTranslation->translateLoc(op.getLoc(), subprogram));
958 
959     if (failed(convertOperation(op, builder, recordInsertions)))
960       return failure();
961 
962     // Set the branch weight metadata on the translated instruction.
963     if (auto iface = dyn_cast<BranchWeightOpInterface>(op))
964       setBranchWeightsMetadata(iface);
965   }
966 
967   return success();
968 }
969 
970 /// A helper method to get the single Block in an operation honoring LLVM's
971 /// module requirements.
972 static Block &getModuleBody(Operation *module) {
973   return module->getRegion(0).front();
974 }
975 
976 /// A helper method to decide if a constant must not be set as a global variable
977 /// initializer. For an external linkage variable, the variable with an
978 /// initializer is considered externally visible and defined in this module, the
979 /// variable without an initializer is externally available and is defined
980 /// elsewhere.
981 static bool shouldDropGlobalInitializer(llvm::GlobalValue::LinkageTypes linkage,
982                                         llvm::Constant *cst) {
983   return (linkage == llvm::GlobalVariable::ExternalLinkage && !cst) ||
984          linkage == llvm::GlobalVariable::ExternalWeakLinkage;
985 }
986 
987 /// Sets the runtime preemption specifier of `gv` to dso_local if
988 /// `dsoLocalRequested` is true, otherwise it is left unchanged.
989 static void addRuntimePreemptionSpecifier(bool dsoLocalRequested,
990                                           llvm::GlobalValue *gv) {
991   if (dsoLocalRequested)
992     gv->setDSOLocal(true);
993 }
994 
995 /// Create named global variables that correspond to llvm.mlir.global
996 /// definitions. Convert llvm.global_ctors and global_dtors ops.
997 LogicalResult ModuleTranslation::convertGlobals() {
998   // Mapping from compile unit to its respective set of global variables.
999   DenseMap<llvm::DICompileUnit *, SmallVector<llvm::Metadata *>> allGVars;
1000 
1001   for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) {
1002     llvm::Type *type = convertType(op.getType());
1003     llvm::Constant *cst = nullptr;
1004     if (op.getValueOrNull()) {
1005       // String attributes are treated separately because they cannot appear as
1006       // in-function constants and are thus not supported by getLLVMConstant.
1007       if (auto strAttr = dyn_cast_or_null<StringAttr>(op.getValueOrNull())) {
1008         cst = llvm::ConstantDataArray::getString(
1009             llvmModule->getContext(), strAttr.getValue(), /*AddNull=*/false);
1010         type = cst->getType();
1011       } else if (!(cst = getLLVMConstant(type, op.getValueOrNull(), op.getLoc(),
1012                                          *this))) {
1013         return failure();
1014       }
1015     }
1016 
1017     auto linkage = convertLinkageToLLVM(op.getLinkage());
1018 
1019     // LLVM IR requires constant with linkage other than external or weak
1020     // external to have initializers. If MLIR does not provide an initializer,
1021     // default to undef.
1022     bool dropInitializer = shouldDropGlobalInitializer(linkage, cst);
1023     if (!dropInitializer && !cst)
1024       cst = llvm::UndefValue::get(type);
1025     else if (dropInitializer && cst)
1026       cst = nullptr;
1027 
1028     auto *var = new llvm::GlobalVariable(
1029         *llvmModule, type, op.getConstant(), linkage, cst, op.getSymName(),
1030         /*InsertBefore=*/nullptr,
1031         op.getThreadLocal_() ? llvm::GlobalValue::GeneralDynamicTLSModel
1032                              : llvm::GlobalValue::NotThreadLocal,
1033         op.getAddrSpace(), op.getExternallyInitialized());
1034 
1035     if (std::optional<mlir::SymbolRefAttr> comdat = op.getComdat()) {
1036       auto selectorOp = cast<ComdatSelectorOp>(
1037           SymbolTable::lookupNearestSymbolFrom(op, *comdat));
1038       var->setComdat(comdatMapping.lookup(selectorOp));
1039     }
1040 
1041     if (op.getUnnamedAddr().has_value())
1042       var->setUnnamedAddr(convertUnnamedAddrToLLVM(*op.getUnnamedAddr()));
1043 
1044     if (op.getSection().has_value())
1045       var->setSection(*op.getSection());
1046 
1047     addRuntimePreemptionSpecifier(op.getDsoLocal(), var);
1048 
1049     std::optional<uint64_t> alignment = op.getAlignment();
1050     if (alignment.has_value())
1051       var->setAlignment(llvm::MaybeAlign(alignment.value()));
1052 
1053     var->setVisibility(convertVisibilityToLLVM(op.getVisibility_()));
1054 
1055     globalsMapping.try_emplace(op, var);
1056 
1057     // Add debug information if present.
1058     if (op.getDbgExpr()) {
1059       llvm::DIGlobalVariableExpression *diGlobalExpr =
1060           debugTranslation->translateGlobalVariableExpression(op.getDbgExpr());
1061       llvm::DIGlobalVariable *diGlobalVar = diGlobalExpr->getVariable();
1062       var->addDebugInfo(diGlobalExpr);
1063 
1064       // There is no `globals` field in DICompileUnitAttr which can be directly
1065       // assigned to DICompileUnit. We have to build the list by looking at the
1066       // dbgExpr of all the GlobalOps. The scope of the variable is used to get
1067       // the DICompileUnit in which to add it.
1068       // But there are cases where the scope of a global does not
1069       // directly point to the DICompileUnit and we have to do a bit more work
1070       // to get to it. Some of those cases are:
1071       //
1072       // 1. For the languages that support modules, the scope hierarchy can be
1073       // variable -> DIModule -> DICompileUnit
1074       //
1075       // 2. For the Fortran common block variable, the scope hierarchy can be
1076       // variable -> DICommonBlock -> DISubprogram -> DICompileUnit
1077       //
1078       // 3. For entities like static local variables in C or variable with
1079       // SAVE attribute in Fortran, the scope hierarchy can be
1080       // variable -> DISubprogram -> DICompileUnit
1081       llvm::DIScope *scope = diGlobalVar->getScope();
1082       if (auto *mod = dyn_cast_if_present<llvm::DIModule>(scope))
1083         scope = mod->getScope();
1084       else if (auto *cb = dyn_cast_if_present<llvm::DICommonBlock>(scope)) {
1085         if (auto *sp = dyn_cast_if_present<llvm::DISubprogram>(cb->getScope()))
1086           scope = sp->getUnit();
1087       } else if (auto *sp = dyn_cast_if_present<llvm::DISubprogram>(scope))
1088         scope = sp->getUnit();
1089 
1090       // Get the compile unit (scope) of the the global variable.
1091       if (llvm::DICompileUnit *compileUnit =
1092               dyn_cast_if_present<llvm::DICompileUnit>(scope)) {
1093         // Update the compile unit with this incoming global variable expression
1094         // during the finalizing step later.
1095         allGVars[compileUnit].push_back(diGlobalExpr);
1096       }
1097     }
1098   }
1099 
1100   // Convert global variable bodies. This is done after all global variables
1101   // have been created in LLVM IR because a global body may refer to another
1102   // global or itself. So all global variables need to be mapped first.
1103   for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) {
1104     if (Block *initializer = op.getInitializerBlock()) {
1105       llvm::IRBuilder<> builder(llvmModule->getContext());
1106 
1107       [[maybe_unused]] int numConstantsHit = 0;
1108       [[maybe_unused]] int numConstantsErased = 0;
1109       DenseMap<llvm::ConstantAggregate *, int> constantAggregateUseMap;
1110 
1111       for (auto &op : initializer->without_terminator()) {
1112         if (failed(convertOperation(op, builder)))
1113           return emitError(op.getLoc(), "fail to convert global initializer");
1114         auto *cst = dyn_cast<llvm::Constant>(lookupValue(op.getResult(0)));
1115         if (!cst)
1116           return emitError(op.getLoc(), "unemittable constant value");
1117 
1118         // When emitting an LLVM constant, a new constant is created and the old
1119         // constant may become dangling and take space. We should remove the
1120         // dangling constants to avoid memory explosion especially for constant
1121         // arrays whose number of elements is large.
1122         // Because multiple operations may refer to the same constant, we need
1123         // to count the number of uses of each constant array and remove it only
1124         // when the count becomes zero.
1125         if (auto *agg = dyn_cast<llvm::ConstantAggregate>(cst)) {
1126           numConstantsHit++;
1127           Value result = op.getResult(0);
1128           int numUsers = std::distance(result.use_begin(), result.use_end());
1129           auto [iterator, inserted] =
1130               constantAggregateUseMap.try_emplace(agg, numUsers);
1131           if (!inserted) {
1132             // Key already exists, update the value
1133             iterator->second += numUsers;
1134           }
1135         }
1136         // Scan the operands of the operation to decrement the use count of
1137         // constants. Erase the constant if the use count becomes zero.
1138         for (Value v : op.getOperands()) {
1139           auto cst = dyn_cast<llvm::ConstantAggregate>(lookupValue(v));
1140           if (!cst)
1141             continue;
1142           auto iter = constantAggregateUseMap.find(cst);
1143           assert(iter != constantAggregateUseMap.end() && "constant not found");
1144           iter->second--;
1145           if (iter->second == 0) {
1146             // NOTE: cannot call removeDeadConstantUsers() here because it
1147             // may remove the constant which has uses not be converted yet.
1148             if (cst->user_empty()) {
1149               cst->destroyConstant();
1150               numConstantsErased++;
1151             }
1152             constantAggregateUseMap.erase(iter);
1153           }
1154         }
1155       }
1156 
1157       ReturnOp ret = cast<ReturnOp>(initializer->getTerminator());
1158       llvm::Constant *cst =
1159           cast<llvm::Constant>(lookupValue(ret.getOperand(0)));
1160       auto *global = cast<llvm::GlobalVariable>(lookupGlobal(op));
1161       if (!shouldDropGlobalInitializer(global->getLinkage(), cst))
1162         global->setInitializer(cst);
1163 
1164       // Try to remove the dangling constants again after all operations are
1165       // converted.
1166       for (auto it : constantAggregateUseMap) {
1167         auto cst = it.first;
1168         cst->removeDeadConstantUsers();
1169         if (cst->user_empty()) {
1170           cst->destroyConstant();
1171           numConstantsErased++;
1172         }
1173       }
1174 
1175       LLVM_DEBUG(llvm::dbgs()
1176                      << "Convert initializer for " << op.getName() << "\n";
1177                  llvm::dbgs() << numConstantsHit << " new constants hit\n";
1178                  llvm::dbgs()
1179                  << numConstantsErased << " dangling constants erased\n";);
1180     }
1181   }
1182 
1183   // Convert llvm.mlir.global_ctors and dtors.
1184   for (Operation &op : getModuleBody(mlirModule)) {
1185     auto ctorOp = dyn_cast<GlobalCtorsOp>(op);
1186     auto dtorOp = dyn_cast<GlobalDtorsOp>(op);
1187     if (!ctorOp && !dtorOp)
1188       continue;
1189     auto range = ctorOp ? llvm::zip(ctorOp.getCtors(), ctorOp.getPriorities())
1190                         : llvm::zip(dtorOp.getDtors(), dtorOp.getPriorities());
1191     auto appendGlobalFn =
1192         ctorOp ? llvm::appendToGlobalCtors : llvm::appendToGlobalDtors;
1193     for (auto symbolAndPriority : range) {
1194       llvm::Function *f = lookupFunction(
1195           cast<FlatSymbolRefAttr>(std::get<0>(symbolAndPriority)).getValue());
1196       appendGlobalFn(*llvmModule, f,
1197                      cast<IntegerAttr>(std::get<1>(symbolAndPriority)).getInt(),
1198                      /*Data=*/nullptr);
1199     }
1200   }
1201 
1202   for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>())
1203     if (failed(convertDialectAttributes(op, {})))
1204       return failure();
1205 
1206   // Finally, update the compile units their respective sets of global variables
1207   // created earlier.
1208   for (const auto &[compileUnit, globals] : allGVars) {
1209     compileUnit->replaceGlobalVariables(
1210         llvm::MDTuple::get(getLLVMContext(), globals));
1211   }
1212 
1213   return success();
1214 }
1215 
1216 /// Attempts to add an attribute identified by `key`, optionally with the given
1217 /// `value` to LLVM function `llvmFunc`. Reports errors at `loc` if any. If the
1218 /// attribute has a kind known to LLVM IR, create the attribute of this kind,
1219 /// otherwise keep it as a string attribute. Performs additional checks for
1220 /// attributes known to have or not have a value in order to avoid assertions
1221 /// inside LLVM upon construction.
1222 static LogicalResult checkedAddLLVMFnAttribute(Location loc,
1223                                                llvm::Function *llvmFunc,
1224                                                StringRef key,
1225                                                StringRef value = StringRef()) {
1226   auto kind = llvm::Attribute::getAttrKindFromName(key);
1227   if (kind == llvm::Attribute::None) {
1228     llvmFunc->addFnAttr(key, value);
1229     return success();
1230   }
1231 
1232   if (llvm::Attribute::isIntAttrKind(kind)) {
1233     if (value.empty())
1234       return emitError(loc) << "LLVM attribute '" << key << "' expects a value";
1235 
1236     int64_t result;
1237     if (!value.getAsInteger(/*Radix=*/0, result))
1238       llvmFunc->addFnAttr(
1239           llvm::Attribute::get(llvmFunc->getContext(), kind, result));
1240     else
1241       llvmFunc->addFnAttr(key, value);
1242     return success();
1243   }
1244 
1245   if (!value.empty())
1246     return emitError(loc) << "LLVM attribute '" << key
1247                           << "' does not expect a value, found '" << value
1248                           << "'";
1249 
1250   llvmFunc->addFnAttr(kind);
1251   return success();
1252 }
1253 
1254 /// Return a representation of `value` as metadata.
1255 static llvm::Metadata *convertIntegerToMetadata(llvm::LLVMContext &context,
1256                                                 const llvm::APInt &value) {
1257   llvm::Constant *constant = llvm::ConstantInt::get(context, value);
1258   return llvm::ConstantAsMetadata::get(constant);
1259 }
1260 
1261 /// Return a representation of `value` as an MDNode.
1262 static llvm::MDNode *convertIntegerToMDNode(llvm::LLVMContext &context,
1263                                             const llvm::APInt &value) {
1264   return llvm::MDNode::get(context, convertIntegerToMetadata(context, value));
1265 }
1266 
1267 /// Return an MDNode encoding `vec_type_hint` metadata.
1268 static llvm::MDNode *convertVecTypeHintToMDNode(llvm::LLVMContext &context,
1269                                                 llvm::Type *type,
1270                                                 bool isSigned) {
1271   llvm::Metadata *typeMD =
1272       llvm::ConstantAsMetadata::get(llvm::UndefValue::get(type));
1273   llvm::Metadata *isSignedMD =
1274       convertIntegerToMetadata(context, llvm::APInt(32, isSigned ? 1 : 0));
1275   return llvm::MDNode::get(context, {typeMD, isSignedMD});
1276 }
1277 
1278 /// Return an MDNode with a tuple given by the values in `values`.
1279 static llvm::MDNode *convertIntegerArrayToMDNode(llvm::LLVMContext &context,
1280                                                  ArrayRef<int32_t> values) {
1281   SmallVector<llvm::Metadata *> mdValues;
1282   llvm::transform(
1283       values, std::back_inserter(mdValues), [&context](int32_t value) {
1284         return convertIntegerToMetadata(context, llvm::APInt(32, value));
1285       });
1286   return llvm::MDNode::get(context, mdValues);
1287 }
1288 
1289 /// Attaches the attributes listed in the given array attribute to `llvmFunc`.
1290 /// Reports error to `loc` if any and returns immediately. Expects `attributes`
1291 /// to be an array attribute containing either string attributes, treated as
1292 /// value-less LLVM attributes, or array attributes containing two string
1293 /// attributes, with the first string being the name of the corresponding LLVM
1294 /// attribute and the second string beings its value. Note that even integer
1295 /// attributes are expected to have their values expressed as strings.
1296 static LogicalResult
1297 forwardPassthroughAttributes(Location loc, std::optional<ArrayAttr> attributes,
1298                              llvm::Function *llvmFunc) {
1299   if (!attributes)
1300     return success();
1301 
1302   for (Attribute attr : *attributes) {
1303     if (auto stringAttr = dyn_cast<StringAttr>(attr)) {
1304       if (failed(
1305               checkedAddLLVMFnAttribute(loc, llvmFunc, stringAttr.getValue())))
1306         return failure();
1307       continue;
1308     }
1309 
1310     auto arrayAttr = dyn_cast<ArrayAttr>(attr);
1311     if (!arrayAttr || arrayAttr.size() != 2)
1312       return emitError(loc)
1313              << "expected 'passthrough' to contain string or array attributes";
1314 
1315     auto keyAttr = dyn_cast<StringAttr>(arrayAttr[0]);
1316     auto valueAttr = dyn_cast<StringAttr>(arrayAttr[1]);
1317     if (!keyAttr || !valueAttr)
1318       return emitError(loc)
1319              << "expected arrays within 'passthrough' to contain two strings";
1320 
1321     if (failed(checkedAddLLVMFnAttribute(loc, llvmFunc, keyAttr.getValue(),
1322                                          valueAttr.getValue())))
1323       return failure();
1324   }
1325   return success();
1326 }
1327 
1328 LogicalResult ModuleTranslation::convertOneFunction(LLVMFuncOp func) {
1329   // Clear the block, branch value mappings, they are only relevant within one
1330   // function.
1331   blockMapping.clear();
1332   valueMapping.clear();
1333   branchMapping.clear();
1334   llvm::Function *llvmFunc = lookupFunction(func.getName());
1335 
1336   // Add function arguments to the value remapping table.
1337   for (auto [mlirArg, llvmArg] :
1338        llvm::zip(func.getArguments(), llvmFunc->args()))
1339     mapValue(mlirArg, &llvmArg);
1340 
1341   // Check the personality and set it.
1342   if (func.getPersonality()) {
1343     llvm::Type *ty = llvm::PointerType::getUnqual(llvmFunc->getContext());
1344     if (llvm::Constant *pfunc = getLLVMConstant(ty, func.getPersonalityAttr(),
1345                                                 func.getLoc(), *this))
1346       llvmFunc->setPersonalityFn(pfunc);
1347   }
1348 
1349   if (std::optional<StringRef> section = func.getSection())
1350     llvmFunc->setSection(*section);
1351 
1352   if (func.getArmStreaming())
1353     llvmFunc->addFnAttr("aarch64_pstate_sm_enabled");
1354   else if (func.getArmLocallyStreaming())
1355     llvmFunc->addFnAttr("aarch64_pstate_sm_body");
1356   else if (func.getArmStreamingCompatible())
1357     llvmFunc->addFnAttr("aarch64_pstate_sm_compatible");
1358 
1359   if (func.getArmNewZa())
1360     llvmFunc->addFnAttr("aarch64_new_za");
1361   else if (func.getArmInZa())
1362     llvmFunc->addFnAttr("aarch64_in_za");
1363   else if (func.getArmOutZa())
1364     llvmFunc->addFnAttr("aarch64_out_za");
1365   else if (func.getArmInoutZa())
1366     llvmFunc->addFnAttr("aarch64_inout_za");
1367   else if (func.getArmPreservesZa())
1368     llvmFunc->addFnAttr("aarch64_preserves_za");
1369 
1370   if (auto targetCpu = func.getTargetCpu())
1371     llvmFunc->addFnAttr("target-cpu", *targetCpu);
1372 
1373   if (auto tuneCpu = func.getTuneCpu())
1374     llvmFunc->addFnAttr("tune-cpu", *tuneCpu);
1375 
1376   if (auto targetFeatures = func.getTargetFeatures())
1377     llvmFunc->addFnAttr("target-features", targetFeatures->getFeaturesString());
1378 
1379   if (auto attr = func.getVscaleRange())
1380     llvmFunc->addFnAttr(llvm::Attribute::getWithVScaleRangeArgs(
1381         getLLVMContext(), attr->getMinRange().getInt(),
1382         attr->getMaxRange().getInt()));
1383 
1384   if (auto unsafeFpMath = func.getUnsafeFpMath())
1385     llvmFunc->addFnAttr("unsafe-fp-math", llvm::toStringRef(*unsafeFpMath));
1386 
1387   if (auto noInfsFpMath = func.getNoInfsFpMath())
1388     llvmFunc->addFnAttr("no-infs-fp-math", llvm::toStringRef(*noInfsFpMath));
1389 
1390   if (auto noNansFpMath = func.getNoNansFpMath())
1391     llvmFunc->addFnAttr("no-nans-fp-math", llvm::toStringRef(*noNansFpMath));
1392 
1393   if (auto approxFuncFpMath = func.getApproxFuncFpMath())
1394     llvmFunc->addFnAttr("approx-func-fp-math",
1395                         llvm::toStringRef(*approxFuncFpMath));
1396 
1397   if (auto noSignedZerosFpMath = func.getNoSignedZerosFpMath())
1398     llvmFunc->addFnAttr("no-signed-zeros-fp-math",
1399                         llvm::toStringRef(*noSignedZerosFpMath));
1400 
1401   if (auto denormalFpMath = func.getDenormalFpMath())
1402     llvmFunc->addFnAttr("denormal-fp-math", *denormalFpMath);
1403 
1404   if (auto denormalFpMathF32 = func.getDenormalFpMathF32())
1405     llvmFunc->addFnAttr("denormal-fp-math-f32", *denormalFpMathF32);
1406 
1407   if (auto fpContract = func.getFpContract())
1408     llvmFunc->addFnAttr("fp-contract", *fpContract);
1409 
1410   // Add function attribute frame-pointer, if found.
1411   if (FramePointerKindAttr attr = func.getFramePointerAttr())
1412     llvmFunc->addFnAttr("frame-pointer",
1413                         LLVM::framePointerKind::stringifyFramePointerKind(
1414                             (attr.getFramePointerKind())));
1415 
1416   // First, create all blocks so we can jump to them.
1417   llvm::LLVMContext &llvmContext = llvmFunc->getContext();
1418   for (auto &bb : func) {
1419     auto *llvmBB = llvm::BasicBlock::Create(llvmContext);
1420     llvmBB->insertInto(llvmFunc);
1421     mapBlock(&bb, llvmBB);
1422   }
1423 
1424   // Then, convert blocks one by one in topological order to ensure defs are
1425   // converted before uses.
1426   auto blocks = getBlocksSortedByDominance(func.getBody());
1427   for (Block *bb : blocks) {
1428     CapturingIRBuilder builder(llvmContext);
1429     if (failed(convertBlockImpl(*bb, bb->isEntryBlock(), builder,
1430                                 /*recordInsertions=*/true)))
1431       return failure();
1432   }
1433 
1434   // After all blocks have been traversed and values mapped, connect the PHI
1435   // nodes to the results of preceding blocks.
1436   detail::connectPHINodes(func.getBody(), *this);
1437 
1438   // Finally, convert dialect attributes attached to the function.
1439   return convertDialectAttributes(func, {});
1440 }
1441 
1442 LogicalResult ModuleTranslation::convertDialectAttributes(
1443     Operation *op, ArrayRef<llvm::Instruction *> instructions) {
1444   for (NamedAttribute attribute : op->getDialectAttrs())
1445     if (failed(iface.amendOperation(op, instructions, attribute, *this)))
1446       return failure();
1447   return success();
1448 }
1449 
1450 /// Converts memory effect attributes from `func` and attaches them to
1451 /// `llvmFunc`.
1452 static void convertFunctionMemoryAttributes(LLVMFuncOp func,
1453                                             llvm::Function *llvmFunc) {
1454   if (!func.getMemoryEffects())
1455     return;
1456 
1457   MemoryEffectsAttr memEffects = func.getMemoryEffectsAttr();
1458 
1459   // Add memory effects incrementally.
1460   llvm::MemoryEffects newMemEffects =
1461       llvm::MemoryEffects(llvm::MemoryEffects::Location::ArgMem,
1462                           convertModRefInfoToLLVM(memEffects.getArgMem()));
1463   newMemEffects |= llvm::MemoryEffects(
1464       llvm::MemoryEffects::Location::InaccessibleMem,
1465       convertModRefInfoToLLVM(memEffects.getInaccessibleMem()));
1466   newMemEffects |=
1467       llvm::MemoryEffects(llvm::MemoryEffects::Location::Other,
1468                           convertModRefInfoToLLVM(memEffects.getOther()));
1469   llvmFunc->setMemoryEffects(newMemEffects);
1470 }
1471 
1472 /// Converts function attributes from `func` and attaches them to `llvmFunc`.
1473 static void convertFunctionAttributes(LLVMFuncOp func,
1474                                       llvm::Function *llvmFunc) {
1475   if (func.getNoInlineAttr())
1476     llvmFunc->addFnAttr(llvm::Attribute::NoInline);
1477   if (func.getAlwaysInlineAttr())
1478     llvmFunc->addFnAttr(llvm::Attribute::AlwaysInline);
1479   if (func.getOptimizeNoneAttr())
1480     llvmFunc->addFnAttr(llvm::Attribute::OptimizeNone);
1481   if (func.getConvergentAttr())
1482     llvmFunc->addFnAttr(llvm::Attribute::Convergent);
1483   if (func.getNoUnwindAttr())
1484     llvmFunc->addFnAttr(llvm::Attribute::NoUnwind);
1485   if (func.getWillReturnAttr())
1486     llvmFunc->addFnAttr(llvm::Attribute::WillReturn);
1487   convertFunctionMemoryAttributes(func, llvmFunc);
1488 }
1489 
1490 /// Converts function attributes from `func` and attaches them to `llvmFunc`.
1491 static void convertFunctionKernelAttributes(LLVMFuncOp func,
1492                                             llvm::Function *llvmFunc,
1493                                             ModuleTranslation &translation) {
1494   llvm::LLVMContext &llvmContext = llvmFunc->getContext();
1495 
1496   if (VecTypeHintAttr vecTypeHint = func.getVecTypeHintAttr()) {
1497     Type type = vecTypeHint.getHint().getValue();
1498     llvm::Type *llvmType = translation.convertType(type);
1499     bool isSigned = vecTypeHint.getIsSigned();
1500     llvmFunc->setMetadata(
1501         func.getVecTypeHintAttrName(),
1502         convertVecTypeHintToMDNode(llvmContext, llvmType, isSigned));
1503   }
1504 
1505   if (std::optional<ArrayRef<int32_t>> workGroupSizeHint =
1506           func.getWorkGroupSizeHint()) {
1507     llvmFunc->setMetadata(
1508         func.getWorkGroupSizeHintAttrName(),
1509         convertIntegerArrayToMDNode(llvmContext, *workGroupSizeHint));
1510   }
1511 
1512   if (std::optional<ArrayRef<int32_t>> reqdWorkGroupSize =
1513           func.getReqdWorkGroupSize()) {
1514     llvmFunc->setMetadata(
1515         func.getReqdWorkGroupSizeAttrName(),
1516         convertIntegerArrayToMDNode(llvmContext, *reqdWorkGroupSize));
1517   }
1518 
1519   if (std::optional<uint32_t> intelReqdSubGroupSize =
1520           func.getIntelReqdSubGroupSize()) {
1521     llvmFunc->setMetadata(
1522         func.getIntelReqdSubGroupSizeAttrName(),
1523         convertIntegerToMDNode(llvmContext,
1524                                llvm::APInt(32, *intelReqdSubGroupSize)));
1525   }
1526 }
1527 
1528 FailureOr<llvm::AttrBuilder>
1529 ModuleTranslation::convertParameterAttrs(LLVMFuncOp func, int argIdx,
1530                                          DictionaryAttr paramAttrs) {
1531   llvm::AttrBuilder attrBuilder(llvmModule->getContext());
1532   auto attrNameToKindMapping = getAttrNameToKindMapping();
1533 
1534   for (auto namedAttr : paramAttrs) {
1535     auto it = attrNameToKindMapping.find(namedAttr.getName());
1536     if (it != attrNameToKindMapping.end()) {
1537       llvm::Attribute::AttrKind llvmKind = it->second;
1538 
1539       llvm::TypeSwitch<Attribute>(namedAttr.getValue())
1540           .Case<TypeAttr>([&](auto typeAttr) {
1541             attrBuilder.addTypeAttr(llvmKind, convertType(typeAttr.getValue()));
1542           })
1543           .Case<IntegerAttr>([&](auto intAttr) {
1544             attrBuilder.addRawIntAttr(llvmKind, intAttr.getInt());
1545           })
1546           .Case<UnitAttr>([&](auto) { attrBuilder.addAttribute(llvmKind); });
1547     } else if (namedAttr.getNameDialect()) {
1548       if (failed(iface.convertParameterAttr(func, argIdx, namedAttr, *this)))
1549         return failure();
1550     }
1551   }
1552 
1553   return attrBuilder;
1554 }
1555 
1556 LogicalResult ModuleTranslation::convertFunctionSignatures() {
1557   // Declare all functions first because there may be function calls that form a
1558   // call graph with cycles, or global initializers that reference functions.
1559   for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) {
1560     llvm::FunctionCallee llvmFuncCst = llvmModule->getOrInsertFunction(
1561         function.getName(),
1562         cast<llvm::FunctionType>(convertType(function.getFunctionType())));
1563     llvm::Function *llvmFunc = cast<llvm::Function>(llvmFuncCst.getCallee());
1564     llvmFunc->setLinkage(convertLinkageToLLVM(function.getLinkage()));
1565     llvmFunc->setCallingConv(convertCConvToLLVM(function.getCConv()));
1566     mapFunction(function.getName(), llvmFunc);
1567     addRuntimePreemptionSpecifier(function.getDsoLocal(), llvmFunc);
1568 
1569     // Convert function attributes.
1570     convertFunctionAttributes(function, llvmFunc);
1571 
1572     // Convert function kernel attributes to metadata.
1573     convertFunctionKernelAttributes(function, llvmFunc, *this);
1574 
1575     // Convert function_entry_count attribute to metadata.
1576     if (std::optional<uint64_t> entryCount = function.getFunctionEntryCount())
1577       llvmFunc->setEntryCount(entryCount.value());
1578 
1579     // Convert result attributes.
1580     if (ArrayAttr allResultAttrs = function.getAllResultAttrs()) {
1581       DictionaryAttr resultAttrs = cast<DictionaryAttr>(allResultAttrs[0]);
1582       FailureOr<llvm::AttrBuilder> attrBuilder =
1583           convertParameterAttrs(function, -1, resultAttrs);
1584       if (failed(attrBuilder))
1585         return failure();
1586       llvmFunc->addRetAttrs(*attrBuilder);
1587     }
1588 
1589     // Convert argument attributes.
1590     for (auto [argIdx, llvmArg] : llvm::enumerate(llvmFunc->args())) {
1591       if (DictionaryAttr argAttrs = function.getArgAttrDict(argIdx)) {
1592         FailureOr<llvm::AttrBuilder> attrBuilder =
1593             convertParameterAttrs(function, argIdx, argAttrs);
1594         if (failed(attrBuilder))
1595           return failure();
1596         llvmArg.addAttrs(*attrBuilder);
1597       }
1598     }
1599 
1600     // Forward the pass-through attributes to LLVM.
1601     if (failed(forwardPassthroughAttributes(
1602             function.getLoc(), function.getPassthrough(), llvmFunc)))
1603       return failure();
1604 
1605     // Convert visibility attribute.
1606     llvmFunc->setVisibility(convertVisibilityToLLVM(function.getVisibility_()));
1607 
1608     // Convert the comdat attribute.
1609     if (std::optional<mlir::SymbolRefAttr> comdat = function.getComdat()) {
1610       auto selectorOp = cast<ComdatSelectorOp>(
1611           SymbolTable::lookupNearestSymbolFrom(function, *comdat));
1612       llvmFunc->setComdat(comdatMapping.lookup(selectorOp));
1613     }
1614 
1615     if (auto gc = function.getGarbageCollector())
1616       llvmFunc->setGC(gc->str());
1617 
1618     if (auto unnamedAddr = function.getUnnamedAddr())
1619       llvmFunc->setUnnamedAddr(convertUnnamedAddrToLLVM(*unnamedAddr));
1620 
1621     if (auto alignment = function.getAlignment())
1622       llvmFunc->setAlignment(llvm::MaybeAlign(*alignment));
1623 
1624     // Translate the debug information for this function.
1625     debugTranslation->translate(function, *llvmFunc);
1626   }
1627 
1628   return success();
1629 }
1630 
1631 LogicalResult ModuleTranslation::convertFunctions() {
1632   // Convert functions.
1633   for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) {
1634     // Do not convert external functions, but do process dialect attributes
1635     // attached to them.
1636     if (function.isExternal()) {
1637       if (failed(convertDialectAttributes(function, {})))
1638         return failure();
1639       continue;
1640     }
1641 
1642     if (failed(convertOneFunction(function)))
1643       return failure();
1644   }
1645 
1646   return success();
1647 }
1648 
1649 LogicalResult ModuleTranslation::convertComdats() {
1650   for (auto comdatOp : getModuleBody(mlirModule).getOps<ComdatOp>()) {
1651     for (auto selectorOp : comdatOp.getOps<ComdatSelectorOp>()) {
1652       llvm::Module *module = getLLVMModule();
1653       if (module->getComdatSymbolTable().contains(selectorOp.getSymName()))
1654         return emitError(selectorOp.getLoc())
1655                << "comdat selection symbols must be unique even in different "
1656                   "comdat regions";
1657       llvm::Comdat *comdat = module->getOrInsertComdat(selectorOp.getSymName());
1658       comdat->setSelectionKind(convertComdatToLLVM(selectorOp.getComdat()));
1659       comdatMapping.try_emplace(selectorOp, comdat);
1660     }
1661   }
1662   return success();
1663 }
1664 
1665 void ModuleTranslation::setAccessGroupsMetadata(AccessGroupOpInterface op,
1666                                                 llvm::Instruction *inst) {
1667   if (llvm::MDNode *node = loopAnnotationTranslation->getAccessGroups(op))
1668     inst->setMetadata(llvm::LLVMContext::MD_access_group, node);
1669 }
1670 
1671 llvm::MDNode *
1672 ModuleTranslation::getOrCreateAliasScope(AliasScopeAttr aliasScopeAttr) {
1673   auto [scopeIt, scopeInserted] =
1674       aliasScopeMetadataMapping.try_emplace(aliasScopeAttr, nullptr);
1675   if (!scopeInserted)
1676     return scopeIt->second;
1677   llvm::LLVMContext &ctx = llvmModule->getContext();
1678   auto dummy = llvm::MDNode::getTemporary(ctx, std::nullopt);
1679   // Convert the domain metadata node if necessary.
1680   auto [domainIt, insertedDomain] = aliasDomainMetadataMapping.try_emplace(
1681       aliasScopeAttr.getDomain(), nullptr);
1682   if (insertedDomain) {
1683     llvm::SmallVector<llvm::Metadata *, 2> operands;
1684     // Placeholder for self-reference.
1685     operands.push_back(dummy.get());
1686     if (StringAttr description = aliasScopeAttr.getDomain().getDescription())
1687       operands.push_back(llvm::MDString::get(ctx, description));
1688     domainIt->second = llvm::MDNode::get(ctx, operands);
1689     // Self-reference for uniqueness.
1690     domainIt->second->replaceOperandWith(0, domainIt->second);
1691   }
1692   // Convert the scope metadata node.
1693   assert(domainIt->second && "Scope's domain should already be valid");
1694   llvm::SmallVector<llvm::Metadata *, 3> operands;
1695   // Placeholder for self-reference.
1696   operands.push_back(dummy.get());
1697   operands.push_back(domainIt->second);
1698   if (StringAttr description = aliasScopeAttr.getDescription())
1699     operands.push_back(llvm::MDString::get(ctx, description));
1700   scopeIt->second = llvm::MDNode::get(ctx, operands);
1701   // Self-reference for uniqueness.
1702   scopeIt->second->replaceOperandWith(0, scopeIt->second);
1703   return scopeIt->second;
1704 }
1705 
1706 llvm::MDNode *ModuleTranslation::getOrCreateAliasScopes(
1707     ArrayRef<AliasScopeAttr> aliasScopeAttrs) {
1708   SmallVector<llvm::Metadata *> nodes;
1709   nodes.reserve(aliasScopeAttrs.size());
1710   for (AliasScopeAttr aliasScopeAttr : aliasScopeAttrs)
1711     nodes.push_back(getOrCreateAliasScope(aliasScopeAttr));
1712   return llvm::MDNode::get(getLLVMContext(), nodes);
1713 }
1714 
1715 void ModuleTranslation::setAliasScopeMetadata(AliasAnalysisOpInterface op,
1716                                               llvm::Instruction *inst) {
1717   auto populateScopeMetadata = [&](ArrayAttr aliasScopeAttrs, unsigned kind) {
1718     if (!aliasScopeAttrs || aliasScopeAttrs.empty())
1719       return;
1720     llvm::MDNode *node = getOrCreateAliasScopes(
1721         llvm::to_vector(aliasScopeAttrs.getAsRange<AliasScopeAttr>()));
1722     inst->setMetadata(kind, node);
1723   };
1724 
1725   populateScopeMetadata(op.getAliasScopesOrNull(),
1726                         llvm::LLVMContext::MD_alias_scope);
1727   populateScopeMetadata(op.getNoAliasScopesOrNull(),
1728                         llvm::LLVMContext::MD_noalias);
1729 }
1730 
1731 llvm::MDNode *ModuleTranslation::getTBAANode(TBAATagAttr tbaaAttr) const {
1732   return tbaaMetadataMapping.lookup(tbaaAttr);
1733 }
1734 
1735 void ModuleTranslation::setTBAAMetadata(AliasAnalysisOpInterface op,
1736                                         llvm::Instruction *inst) {
1737   ArrayAttr tagRefs = op.getTBAATagsOrNull();
1738   if (!tagRefs || tagRefs.empty())
1739     return;
1740 
1741   // LLVM IR currently does not support attaching more than one TBAA access tag
1742   // to a memory accessing instruction. It may be useful to support this in
1743   // future, but for the time being just ignore the metadata if MLIR operation
1744   // has multiple access tags.
1745   if (tagRefs.size() > 1) {
1746     op.emitWarning() << "TBAA access tags were not translated, because LLVM "
1747                         "IR only supports a single tag per instruction";
1748     return;
1749   }
1750 
1751   llvm::MDNode *node = getTBAANode(cast<TBAATagAttr>(tagRefs[0]));
1752   inst->setMetadata(llvm::LLVMContext::MD_tbaa, node);
1753 }
1754 
1755 void ModuleTranslation::setBranchWeightsMetadata(BranchWeightOpInterface op) {
1756   DenseI32ArrayAttr weightsAttr = op.getBranchWeightsOrNull();
1757   if (!weightsAttr)
1758     return;
1759 
1760   llvm::Instruction *inst = isa<CallOp>(op) ? lookupCall(op) : lookupBranch(op);
1761   assert(inst && "expected the operation to have a mapping to an instruction");
1762   SmallVector<uint32_t> weights(weightsAttr.asArrayRef());
1763   inst->setMetadata(
1764       llvm::LLVMContext::MD_prof,
1765       llvm::MDBuilder(getLLVMContext()).createBranchWeights(weights));
1766 }
1767 
1768 LogicalResult ModuleTranslation::createTBAAMetadata() {
1769   llvm::LLVMContext &ctx = llvmModule->getContext();
1770   llvm::IntegerType *offsetTy = llvm::IntegerType::get(ctx, 64);
1771 
1772   // Walk the entire module and create all metadata nodes for the TBAA
1773   // attributes. The code below relies on two invariants of the
1774   // `AttrTypeWalker`:
1775   // 1. Attributes are visited in post-order: Since the attributes create a DAG,
1776   //    this ensures that any lookups into `tbaaMetadataMapping` for child
1777   //    attributes succeed.
1778   // 2. Attributes are only ever visited once: This way we don't leak any
1779   //    LLVM metadata instances.
1780   AttrTypeWalker walker;
1781   walker.addWalk([&](TBAARootAttr root) {
1782     tbaaMetadataMapping.insert(
1783         {root, llvm::MDNode::get(ctx, llvm::MDString::get(ctx, root.getId()))});
1784   });
1785 
1786   walker.addWalk([&](TBAATypeDescriptorAttr descriptor) {
1787     SmallVector<llvm::Metadata *> operands;
1788     operands.push_back(llvm::MDString::get(ctx, descriptor.getId()));
1789     for (TBAAMemberAttr member : descriptor.getMembers()) {
1790       operands.push_back(tbaaMetadataMapping.lookup(member.getTypeDesc()));
1791       operands.push_back(llvm::ConstantAsMetadata::get(
1792           llvm::ConstantInt::get(offsetTy, member.getOffset())));
1793     }
1794 
1795     tbaaMetadataMapping.insert({descriptor, llvm::MDNode::get(ctx, operands)});
1796   });
1797 
1798   walker.addWalk([&](TBAATagAttr tag) {
1799     SmallVector<llvm::Metadata *> operands;
1800 
1801     operands.push_back(tbaaMetadataMapping.lookup(tag.getBaseType()));
1802     operands.push_back(tbaaMetadataMapping.lookup(tag.getAccessType()));
1803 
1804     operands.push_back(llvm::ConstantAsMetadata::get(
1805         llvm::ConstantInt::get(offsetTy, tag.getOffset())));
1806     if (tag.getConstant())
1807       operands.push_back(
1808           llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(offsetTy, 1)));
1809 
1810     tbaaMetadataMapping.insert({tag, llvm::MDNode::get(ctx, operands)});
1811   });
1812 
1813   mlirModule->walk([&](AliasAnalysisOpInterface analysisOpInterface) {
1814     if (auto attr = analysisOpInterface.getTBAATagsOrNull())
1815       walker.walk(attr);
1816   });
1817 
1818   return success();
1819 }
1820 
1821 LogicalResult ModuleTranslation::createIdentMetadata() {
1822   if (auto attr = mlirModule->getAttrOfType<StringAttr>(
1823           LLVMDialect::getIdentAttrName())) {
1824     StringRef ident = attr;
1825     llvm::LLVMContext &ctx = llvmModule->getContext();
1826     llvm::NamedMDNode *namedMd =
1827         llvmModule->getOrInsertNamedMetadata(LLVMDialect::getIdentAttrName());
1828     llvm::MDNode *md = llvm::MDNode::get(ctx, llvm::MDString::get(ctx, ident));
1829     namedMd->addOperand(md);
1830   }
1831 
1832   return success();
1833 }
1834 
1835 void ModuleTranslation::setLoopMetadata(Operation *op,
1836                                         llvm::Instruction *inst) {
1837   LoopAnnotationAttr attr =
1838       TypeSwitch<Operation *, LoopAnnotationAttr>(op)
1839           .Case<LLVM::BrOp, LLVM::CondBrOp>(
1840               [](auto branchOp) { return branchOp.getLoopAnnotationAttr(); });
1841   if (!attr)
1842     return;
1843   llvm::MDNode *loopMD =
1844       loopAnnotationTranslation->translateLoopAnnotation(attr, op);
1845   inst->setMetadata(llvm::LLVMContext::MD_loop, loopMD);
1846 }
1847 
1848 llvm::Type *ModuleTranslation::convertType(Type type) {
1849   return typeTranslator.translateType(type);
1850 }
1851 
1852 /// A helper to look up remapped operands in the value remapping table.
1853 SmallVector<llvm::Value *> ModuleTranslation::lookupValues(ValueRange values) {
1854   SmallVector<llvm::Value *> remapped;
1855   remapped.reserve(values.size());
1856   for (Value v : values)
1857     remapped.push_back(lookupValue(v));
1858   return remapped;
1859 }
1860 
1861 llvm::OpenMPIRBuilder *ModuleTranslation::getOpenMPBuilder() {
1862   if (!ompBuilder) {
1863     ompBuilder = std::make_unique<llvm::OpenMPIRBuilder>(*llvmModule);
1864     ompBuilder->initialize();
1865 
1866     // Flags represented as top-level OpenMP dialect attributes are set in
1867     // `OpenMPDialectLLVMIRTranslationInterface::amendOperation()`. Here we set
1868     // the default configuration.
1869     ompBuilder->setConfig(llvm::OpenMPIRBuilderConfig(
1870         /* IsTargetDevice = */ false, /* IsGPU = */ false,
1871         /* OpenMPOffloadMandatory = */ false,
1872         /* HasRequiresReverseOffload = */ false,
1873         /* HasRequiresUnifiedAddress = */ false,
1874         /* HasRequiresUnifiedSharedMemory = */ false,
1875         /* HasRequiresDynamicAllocators = */ false));
1876   }
1877   return ompBuilder.get();
1878 }
1879 
1880 llvm::DILocation *ModuleTranslation::translateLoc(Location loc,
1881                                                   llvm::DILocalScope *scope) {
1882   return debugTranslation->translateLoc(loc, scope);
1883 }
1884 
1885 llvm::DIExpression *
1886 ModuleTranslation::translateExpression(LLVM::DIExpressionAttr attr) {
1887   return debugTranslation->translateExpression(attr);
1888 }
1889 
1890 llvm::DIGlobalVariableExpression *
1891 ModuleTranslation::translateGlobalVariableExpression(
1892     LLVM::DIGlobalVariableExpressionAttr attr) {
1893   return debugTranslation->translateGlobalVariableExpression(attr);
1894 }
1895 
1896 llvm::Metadata *ModuleTranslation::translateDebugInfo(LLVM::DINodeAttr attr) {
1897   return debugTranslation->translate(attr);
1898 }
1899 
1900 llvm::RoundingMode
1901 ModuleTranslation::translateRoundingMode(LLVM::RoundingMode rounding) {
1902   return convertRoundingModeToLLVM(rounding);
1903 }
1904 
1905 llvm::fp::ExceptionBehavior ModuleTranslation::translateFPExceptionBehavior(
1906     LLVM::FPExceptionBehavior exceptionBehavior) {
1907   return convertFPExceptionBehaviorToLLVM(exceptionBehavior);
1908 }
1909 
1910 llvm::NamedMDNode *
1911 ModuleTranslation::getOrInsertNamedModuleMetadata(StringRef name) {
1912   return llvmModule->getOrInsertNamedMetadata(name);
1913 }
1914 
1915 void ModuleTranslation::StackFrame::anchor() {}
1916 
1917 static std::unique_ptr<llvm::Module>
1918 prepareLLVMModule(Operation *m, llvm::LLVMContext &llvmContext,
1919                   StringRef name) {
1920   m->getContext()->getOrLoadDialect<LLVM::LLVMDialect>();
1921   auto llvmModule = std::make_unique<llvm::Module>(name, llvmContext);
1922   // ModuleTranslation can currently only construct modules in the old debug
1923   // info format, so set the flag accordingly.
1924   llvmModule->setNewDbgInfoFormatFlag(false);
1925   if (auto dataLayoutAttr =
1926           m->getDiscardableAttr(LLVM::LLVMDialect::getDataLayoutAttrName())) {
1927     llvmModule->setDataLayout(cast<StringAttr>(dataLayoutAttr).getValue());
1928   } else {
1929     FailureOr<llvm::DataLayout> llvmDataLayout(llvm::DataLayout(""));
1930     if (auto iface = dyn_cast<DataLayoutOpInterface>(m)) {
1931       if (DataLayoutSpecInterface spec = iface.getDataLayoutSpec()) {
1932         llvmDataLayout =
1933             translateDataLayout(spec, DataLayout(iface), m->getLoc());
1934       }
1935     } else if (auto mod = dyn_cast<ModuleOp>(m)) {
1936       if (DataLayoutSpecInterface spec = mod.getDataLayoutSpec()) {
1937         llvmDataLayout =
1938             translateDataLayout(spec, DataLayout(mod), m->getLoc());
1939       }
1940     }
1941     if (failed(llvmDataLayout))
1942       return nullptr;
1943     llvmModule->setDataLayout(*llvmDataLayout);
1944   }
1945   if (auto targetTripleAttr =
1946           m->getDiscardableAttr(LLVM::LLVMDialect::getTargetTripleAttrName()))
1947     llvmModule->setTargetTriple(cast<StringAttr>(targetTripleAttr).getValue());
1948 
1949   return llvmModule;
1950 }
1951 
1952 std::unique_ptr<llvm::Module>
1953 mlir::translateModuleToLLVMIR(Operation *module, llvm::LLVMContext &llvmContext,
1954                               StringRef name, bool disableVerification) {
1955   if (!satisfiesLLVMModule(module)) {
1956     module->emitOpError("can not be translated to an LLVMIR module");
1957     return nullptr;
1958   }
1959 
1960   std::unique_ptr<llvm::Module> llvmModule =
1961       prepareLLVMModule(module, llvmContext, name);
1962   if (!llvmModule)
1963     return nullptr;
1964 
1965   LLVM::ensureDistinctSuccessors(module);
1966   LLVM::legalizeDIExpressionsRecursively(module);
1967 
1968   ModuleTranslation translator(module, std::move(llvmModule));
1969   llvm::IRBuilder<> llvmBuilder(llvmContext);
1970 
1971   // Convert module before functions and operations inside, so dialect
1972   // attributes can be used to change dialect-specific global configurations via
1973   // `amendOperation()`. These configurations can then influence the translation
1974   // of operations afterwards.
1975   if (failed(translator.convertOperation(*module, llvmBuilder)))
1976     return nullptr;
1977 
1978   if (failed(translator.convertComdats()))
1979     return nullptr;
1980   if (failed(translator.convertFunctionSignatures()))
1981     return nullptr;
1982   if (failed(translator.convertGlobals()))
1983     return nullptr;
1984   if (failed(translator.createTBAAMetadata()))
1985     return nullptr;
1986   if (failed(translator.createIdentMetadata()))
1987     return nullptr;
1988 
1989   // Convert other top-level operations if possible.
1990   for (Operation &o : getModuleBody(module).getOperations()) {
1991     if (!isa<LLVM::LLVMFuncOp, LLVM::GlobalOp, LLVM::GlobalCtorsOp,
1992              LLVM::GlobalDtorsOp, LLVM::ComdatOp>(&o) &&
1993         !o.hasTrait<OpTrait::IsTerminator>() &&
1994         failed(translator.convertOperation(o, llvmBuilder))) {
1995       return nullptr;
1996     }
1997   }
1998 
1999   // Operations in function bodies with symbolic references must be converted
2000   // after the top-level operations they refer to are declared, so we do it
2001   // last.
2002   if (failed(translator.convertFunctions()))
2003     return nullptr;
2004 
2005   // Once we've finished constructing elements in the module, we should convert
2006   // it to use the debug info format desired by LLVM.
2007   // See https://llvm.org/docs/RemoveDIsDebugInfo.html
2008   translator.llvmModule->setIsNewDbgInfoFormat(UseNewDbgInfoFormat);
2009 
2010   if (!disableVerification &&
2011       llvm::verifyModule(*translator.llvmModule, &llvm::errs()))
2012     return nullptr;
2013 
2014   return std::move(translator.llvmModule);
2015 }
2016