1cde4d5a6SJacques Pienaar //===- ModuleTranslation.cpp - MLIR to LLVM conversion --------------------===//
25d7231d8SStephan Herhut //
330857107SMehdi Amini // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
456222a06SMehdi Amini // See https://llvm.org/LICENSE.txt for license information.
556222a06SMehdi Amini // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
65d7231d8SStephan Herhut //
756222a06SMehdi Amini //===----------------------------------------------------------------------===//
85d7231d8SStephan Herhut //
95d7231d8SStephan Herhut // This file implements the translation between an MLIR LLVM dialect module and
105d7231d8SStephan Herhut // the corresponding LLVMIR module. It only handles core LLVM IR operations.
115d7231d8SStephan Herhut //
125d7231d8SStephan Herhut //===----------------------------------------------------------------------===//
135d7231d8SStephan Herhut 
145d7231d8SStephan Herhut #include "mlir/Target/LLVMIR/ModuleTranslation.h"
155d7231d8SStephan Herhut 
16c33d6970SRiver Riddle #include "DebugTranslation.h"
17ba0fa925SRiver Riddle #include "mlir/Dialect/LLVMIR/LLVMDialect.h"
18ce8f10d6SAlex Zinenko #include "mlir/Dialect/LLVMIR/Transforms/LegalizeForExport.h"
1992a295ebSKiran Chandramohan #include "mlir/Dialect/OpenMP/OpenMPDialect.h"
205d7231d8SStephan Herhut #include "mlir/IR/Attributes.h"
2165fcddffSRiver Riddle #include "mlir/IR/BuiltinOps.h"
2209f7a55fSRiver Riddle #include "mlir/IR/BuiltinTypes.h"
23d4568ed7SGeorge Mitenkov #include "mlir/IR/RegionGraphTraits.h"
245d7231d8SStephan Herhut #include "mlir/Support/LLVM.h"
25b77bac05SAlex Zinenko #include "mlir/Target/LLVMIR/LLVMTranslationInterface.h"
26929189a4SWilliam S. Moses #include "mlir/Target/LLVMIR/TypeToLLVM.h"
27ebf190fcSRiver Riddle #include "llvm/ADT/TypeSwitch.h"
285d7231d8SStephan Herhut 
29d4568ed7SGeorge Mitenkov #include "llvm/ADT/PostOrderIterator.h"
305d7231d8SStephan Herhut #include "llvm/ADT/SetVector.h"
3192a295ebSKiran Chandramohan #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
325d7231d8SStephan Herhut #include "llvm/IR/BasicBlock.h"
33d9067dcaSKiran Chandramohan #include "llvm/IR/CFG.h"
345d7231d8SStephan Herhut #include "llvm/IR/Constants.h"
355d7231d8SStephan Herhut #include "llvm/IR/DerivedTypes.h"
365d7231d8SStephan Herhut #include "llvm/IR/IRBuilder.h"
37047400edSNicolas Vasilache #include "llvm/IR/InlineAsm.h"
38875eb523SNavdeep Kumar #include "llvm/IR/IntrinsicsNVPTX.h"
395d7231d8SStephan Herhut #include "llvm/IR/LLVMContext.h"
4099d03f03SGeorge Mitenkov #include "llvm/IR/MDBuilder.h"
415d7231d8SStephan Herhut #include "llvm/IR/Module.h"
42ce8f10d6SAlex Zinenko #include "llvm/IR/Verifier.h"
43d9067dcaSKiran Chandramohan #include "llvm/Transforms/Utils/BasicBlockUtils.h"
445d7231d8SStephan Herhut #include "llvm/Transforms/Utils/Cloning.h"
4557b9b296SUday Bondhugula #include "llvm/Transforms/Utils/ModuleUtils.h"
465d7231d8SStephan Herhut 
472666b973SRiver Riddle using namespace mlir;
482666b973SRiver Riddle using namespace mlir::LLVM;
49c33d6970SRiver Riddle using namespace mlir::LLVM::detail;
505d7231d8SStephan Herhut 
51eb67bd78SAlex Zinenko #include "mlir/Dialect/LLVMIR/LLVMConversionEnumsToLLVM.inc"
52eb67bd78SAlex Zinenko 
53a922e231SAlex Zinenko /// Builds a constant of a sequential LLVM type `type`, potentially containing
54a922e231SAlex Zinenko /// other sequential types recursively, from the individual constant values
55a922e231SAlex Zinenko /// provided in `constants`. `shape` contains the number of elements in nested
56a922e231SAlex Zinenko /// sequential types. Reports errors at `loc` and returns nullptr on error.
57a4a42160SAlex Zinenko static llvm::Constant *
58a4a42160SAlex Zinenko buildSequentialConstant(ArrayRef<llvm::Constant *> &constants,
59a4a42160SAlex Zinenko                         ArrayRef<int64_t> shape, llvm::Type *type,
60a4a42160SAlex Zinenko                         Location loc) {
61a4a42160SAlex Zinenko   if (shape.empty()) {
62a4a42160SAlex Zinenko     llvm::Constant *result = constants.front();
63a4a42160SAlex Zinenko     constants = constants.drop_front();
64a4a42160SAlex Zinenko     return result;
65a4a42160SAlex Zinenko   }
66a4a42160SAlex Zinenko 
6768b03aeeSEli Friedman   llvm::Type *elementType;
6868b03aeeSEli Friedman   if (auto *arrayTy = dyn_cast<llvm::ArrayType>(type)) {
6968b03aeeSEli Friedman     elementType = arrayTy->getElementType();
7068b03aeeSEli Friedman   } else if (auto *vectorTy = dyn_cast<llvm::VectorType>(type)) {
7168b03aeeSEli Friedman     elementType = vectorTy->getElementType();
7268b03aeeSEli Friedman   } else {
73a4a42160SAlex Zinenko     emitError(loc) << "expected sequential LLVM types wrapping a scalar";
74a4a42160SAlex Zinenko     return nullptr;
75a4a42160SAlex Zinenko   }
76a4a42160SAlex Zinenko 
77a4a42160SAlex Zinenko   SmallVector<llvm::Constant *, 8> nested;
78a4a42160SAlex Zinenko   nested.reserve(shape.front());
79a4a42160SAlex Zinenko   for (int64_t i = 0; i < shape.front(); ++i) {
80a4a42160SAlex Zinenko     nested.push_back(buildSequentialConstant(constants, shape.drop_front(),
81a4a42160SAlex Zinenko                                              elementType, loc));
82a4a42160SAlex Zinenko     if (!nested.back())
83a4a42160SAlex Zinenko       return nullptr;
84a4a42160SAlex Zinenko   }
85a4a42160SAlex Zinenko 
86a4a42160SAlex Zinenko   if (shape.size() == 1 && type->isVectorTy())
87a4a42160SAlex Zinenko     return llvm::ConstantVector::get(nested);
88a4a42160SAlex Zinenko   return llvm::ConstantArray::get(
89a4a42160SAlex Zinenko       llvm::ArrayType::get(elementType, shape.front()), nested);
90a4a42160SAlex Zinenko }
91a4a42160SAlex Zinenko 
92fc817b09SKazuaki Ishizaki /// Returns the first non-sequential type nested in sequential types.
93a4a42160SAlex Zinenko static llvm::Type *getInnermostElementType(llvm::Type *type) {
9468b03aeeSEli Friedman   do {
9568b03aeeSEli Friedman     if (auto *arrayTy = dyn_cast<llvm::ArrayType>(type)) {
9668b03aeeSEli Friedman       type = arrayTy->getElementType();
9768b03aeeSEli Friedman     } else if (auto *vectorTy = dyn_cast<llvm::VectorType>(type)) {
9868b03aeeSEli Friedman       type = vectorTy->getElementType();
9968b03aeeSEli Friedman     } else {
100a4a42160SAlex Zinenko       return type;
101a4a42160SAlex Zinenko     }
1020881a4f1SAlex Zinenko   } while (true);
10368b03aeeSEli Friedman }
104a4a42160SAlex Zinenko 
105f9be7a7aSAlex Zinenko /// Convert a dense elements attribute to an LLVM IR constant using its raw data
106f9be7a7aSAlex Zinenko /// storage if possible. This supports elements attributes of tensor or vector
107f9be7a7aSAlex Zinenko /// type and avoids constructing separate objects for individual values of the
108f9be7a7aSAlex Zinenko /// innermost dimension. Constants for other dimensions are still constructed
109f9be7a7aSAlex Zinenko /// recursively. Returns null if constructing from raw data is not supported for
110f9be7a7aSAlex Zinenko /// this type, e.g., element type is not a power-of-two-sized primitive. Reports
111f9be7a7aSAlex Zinenko /// other errors at `loc`.
112f9be7a7aSAlex Zinenko static llvm::Constant *
113f9be7a7aSAlex Zinenko convertDenseElementsAttr(Location loc, DenseElementsAttr denseElementsAttr,
114f9be7a7aSAlex Zinenko                          llvm::Type *llvmType,
115f9be7a7aSAlex Zinenko                          const ModuleTranslation &moduleTranslation) {
116f9be7a7aSAlex Zinenko   if (!denseElementsAttr)
117f9be7a7aSAlex Zinenko     return nullptr;
118f9be7a7aSAlex Zinenko 
119f9be7a7aSAlex Zinenko   llvm::Type *innermostLLVMType = getInnermostElementType(llvmType);
120f9be7a7aSAlex Zinenko   if (!llvm::ConstantDataSequential::isElementTypeCompatible(innermostLLVMType))
121f9be7a7aSAlex Zinenko     return nullptr;
122f9be7a7aSAlex Zinenko 
123898e8096SBenjamin Kramer   ShapedType type = denseElementsAttr.getType();
124898e8096SBenjamin Kramer   if (type.getNumElements() == 0)
125898e8096SBenjamin Kramer     return nullptr;
126898e8096SBenjamin Kramer 
127f9be7a7aSAlex Zinenko   // Compute the shape of all dimensions but the innermost. Note that the
128f9be7a7aSAlex Zinenko   // innermost dimension may be that of the vector element type.
129f9be7a7aSAlex Zinenko   bool hasVectorElementType = type.getElementType().isa<VectorType>();
130f9be7a7aSAlex Zinenko   unsigned numAggregates =
131f9be7a7aSAlex Zinenko       denseElementsAttr.getNumElements() /
132f9be7a7aSAlex Zinenko       (hasVectorElementType ? 1
133f9be7a7aSAlex Zinenko                             : denseElementsAttr.getType().getShape().back());
134f9be7a7aSAlex Zinenko   ArrayRef<int64_t> outerShape = type.getShape();
135f9be7a7aSAlex Zinenko   if (!hasVectorElementType)
136f9be7a7aSAlex Zinenko     outerShape = outerShape.drop_back();
137f9be7a7aSAlex Zinenko 
138f9be7a7aSAlex Zinenko   // Handle the case of vector splat, LLVM has special support for it.
139f9be7a7aSAlex Zinenko   if (denseElementsAttr.isSplat() &&
140f9be7a7aSAlex Zinenko       (type.isa<VectorType>() || hasVectorElementType)) {
141f9be7a7aSAlex Zinenko     llvm::Constant *splatValue = LLVM::detail::getLLVMConstant(
142937e40a8SRiver Riddle         innermostLLVMType, denseElementsAttr.getSplatValue<Attribute>(), loc,
143f9be7a7aSAlex Zinenko         moduleTranslation, /*isTopLevel=*/false);
144f9be7a7aSAlex Zinenko     llvm::Constant *splatVector =
145f9be7a7aSAlex Zinenko         llvm::ConstantDataVector::getSplat(0, splatValue);
146f9be7a7aSAlex Zinenko     SmallVector<llvm::Constant *> constants(numAggregates, splatVector);
147f9be7a7aSAlex Zinenko     ArrayRef<llvm::Constant *> constantsRef = constants;
148f9be7a7aSAlex Zinenko     return buildSequentialConstant(constantsRef, outerShape, llvmType, loc);
149f9be7a7aSAlex Zinenko   }
150f9be7a7aSAlex Zinenko   if (denseElementsAttr.isSplat())
151f9be7a7aSAlex Zinenko     return nullptr;
152f9be7a7aSAlex Zinenko 
153f9be7a7aSAlex Zinenko   // In case of non-splat, create a constructor for the innermost constant from
154f9be7a7aSAlex Zinenko   // a piece of raw data.
155f9be7a7aSAlex Zinenko   std::function<llvm::Constant *(StringRef)> buildCstData;
156f9be7a7aSAlex Zinenko   if (type.isa<TensorType>()) {
157f9be7a7aSAlex Zinenko     auto vectorElementType = type.getElementType().dyn_cast<VectorType>();
158f9be7a7aSAlex Zinenko     if (vectorElementType && vectorElementType.getRank() == 1) {
159f9be7a7aSAlex Zinenko       buildCstData = [&](StringRef data) {
160f9be7a7aSAlex Zinenko         return llvm::ConstantDataVector::getRaw(
161f9be7a7aSAlex Zinenko             data, vectorElementType.getShape().back(), innermostLLVMType);
162f9be7a7aSAlex Zinenko       };
163f9be7a7aSAlex Zinenko     } else if (!vectorElementType) {
164f9be7a7aSAlex Zinenko       buildCstData = [&](StringRef data) {
165f9be7a7aSAlex Zinenko         return llvm::ConstantDataArray::getRaw(data, type.getShape().back(),
166f9be7a7aSAlex Zinenko                                                innermostLLVMType);
167f9be7a7aSAlex Zinenko       };
168f9be7a7aSAlex Zinenko     }
169f9be7a7aSAlex Zinenko   } else if (type.isa<VectorType>()) {
170f9be7a7aSAlex Zinenko     buildCstData = [&](StringRef data) {
171f9be7a7aSAlex Zinenko       return llvm::ConstantDataVector::getRaw(data, type.getShape().back(),
172f9be7a7aSAlex Zinenko                                               innermostLLVMType);
173f9be7a7aSAlex Zinenko     };
174f9be7a7aSAlex Zinenko   }
175f9be7a7aSAlex Zinenko   if (!buildCstData)
176f9be7a7aSAlex Zinenko     return nullptr;
177f9be7a7aSAlex Zinenko 
178f9be7a7aSAlex Zinenko   // Create innermost constants and defer to the default constant creation
179f9be7a7aSAlex Zinenko   // mechanism for other dimensions.
180f9be7a7aSAlex Zinenko   SmallVector<llvm::Constant *> constants;
181f9be7a7aSAlex Zinenko   unsigned aggregateSize = denseElementsAttr.getType().getShape().back() *
182f9be7a7aSAlex Zinenko                            (innermostLLVMType->getScalarSizeInBits() / 8);
183f9be7a7aSAlex Zinenko   constants.reserve(numAggregates);
184f9be7a7aSAlex Zinenko   for (unsigned i = 0; i < numAggregates; ++i) {
185f9be7a7aSAlex Zinenko     StringRef data(denseElementsAttr.getRawData().data() + i * aggregateSize,
186f9be7a7aSAlex Zinenko                    aggregateSize);
187f9be7a7aSAlex Zinenko     constants.push_back(buildCstData(data));
188f9be7a7aSAlex Zinenko   }
189f9be7a7aSAlex Zinenko 
190f9be7a7aSAlex Zinenko   ArrayRef<llvm::Constant *> constantsRef = constants;
191f9be7a7aSAlex Zinenko   return buildSequentialConstant(constantsRef, outerShape, llvmType, loc);
192f9be7a7aSAlex Zinenko }
193f9be7a7aSAlex Zinenko 
1942666b973SRiver Riddle /// Create an LLVM IR constant of `llvmType` from the MLIR attribute `attr`.
1952666b973SRiver Riddle /// This currently supports integer, floating point, splat and dense element
1965ef21506SAdrian Kuegel /// attributes and combinations thereof. Also, an array attribute with two
1975ef21506SAdrian Kuegel /// elements is supported to represent a complex constant.  In case of error,
1985ef21506SAdrian Kuegel /// report it to `loc` and return nullptr.
199176379e0SAlex Zinenko llvm::Constant *mlir::LLVM::detail::getLLVMConstant(
200176379e0SAlex Zinenko     llvm::Type *llvmType, Attribute attr, Location loc,
2015ef21506SAdrian Kuegel     const ModuleTranslation &moduleTranslation, bool isTopLevel) {
20233a3a91bSChristian Sigg   if (!attr)
20333a3a91bSChristian Sigg     return llvm::UndefValue::get(llvmType);
2045ef21506SAdrian Kuegel   if (auto *structType = dyn_cast<::llvm::StructType>(llvmType)) {
2055ef21506SAdrian Kuegel     if (!isTopLevel) {
2065ef21506SAdrian Kuegel       emitError(loc, "nested struct types are not supported in constants");
207a4a42160SAlex Zinenko       return nullptr;
208a4a42160SAlex Zinenko     }
2095ef21506SAdrian Kuegel     auto arrayAttr = attr.cast<ArrayAttr>();
2105ef21506SAdrian Kuegel     llvm::Type *elementType = structType->getElementType(0);
2115ef21506SAdrian Kuegel     llvm::Constant *real = getLLVMConstant(elementType, arrayAttr[0], loc,
2125ef21506SAdrian Kuegel                                            moduleTranslation, false);
2135ef21506SAdrian Kuegel     if (!real)
2145ef21506SAdrian Kuegel       return nullptr;
2155ef21506SAdrian Kuegel     llvm::Constant *imag = getLLVMConstant(elementType, arrayAttr[1], loc,
2165ef21506SAdrian Kuegel                                            moduleTranslation, false);
2175ef21506SAdrian Kuegel     if (!imag)
2185ef21506SAdrian Kuegel       return nullptr;
2195ef21506SAdrian Kuegel     return llvm::ConstantStruct::get(structType, {real, imag});
2205ef21506SAdrian Kuegel   }
221ac9d742bSStephan Herhut   // For integer types, we allow a mismatch in sizes as the index type in
222ac9d742bSStephan Herhut   // MLIR might have a different size than the index type in the LLVM module.
2235d7231d8SStephan Herhut   if (auto intAttr = attr.dyn_cast<IntegerAttr>())
224ac9d742bSStephan Herhut     return llvm::ConstantInt::get(
225ac9d742bSStephan Herhut         llvmType,
226ac9d742bSStephan Herhut         intAttr.getValue().sextOrTrunc(llvmType->getIntegerBitWidth()));
2275ef21506SAdrian Kuegel   if (auto floatAttr = attr.dyn_cast<FloatAttr>()) {
2285ef21506SAdrian Kuegel     if (llvmType !=
2295ef21506SAdrian Kuegel         llvm::Type::getFloatingPointTy(llvmType->getContext(),
2305ef21506SAdrian Kuegel                                        floatAttr.getValue().getSemantics())) {
2315ef21506SAdrian Kuegel       emitError(loc, "FloatAttr does not match expected type of the constant");
2325ef21506SAdrian Kuegel       return nullptr;
2335ef21506SAdrian Kuegel     }
2345d7231d8SStephan Herhut     return llvm::ConstantFP::get(llvmType, floatAttr.getValue());
2355ef21506SAdrian Kuegel   }
2369b9c647cSRiver Riddle   if (auto funcAttr = attr.dyn_cast<FlatSymbolRefAttr>())
237176379e0SAlex Zinenko     return llvm::ConstantExpr::getBitCast(
238176379e0SAlex Zinenko         moduleTranslation.lookupFunction(funcAttr.getValue()), llvmType);
2395d7231d8SStephan Herhut   if (auto splatAttr = attr.dyn_cast<SplatElementsAttr>()) {
24068b03aeeSEli Friedman     llvm::Type *elementType;
24168b03aeeSEli Friedman     uint64_t numElements;
2427c564586SJavier Setoain     bool isScalable = false;
24368b03aeeSEli Friedman     if (auto *arrayTy = dyn_cast<llvm::ArrayType>(llvmType)) {
24468b03aeeSEli Friedman       elementType = arrayTy->getElementType();
24568b03aeeSEli Friedman       numElements = arrayTy->getNumElements();
24602b6fb21SMehdi Amini     } else if (auto *fVectorTy = dyn_cast<llvm::FixedVectorType>(llvmType)) {
247a4830d14SJavier Setoain       elementType = fVectorTy->getElementType();
248a4830d14SJavier Setoain       numElements = fVectorTy->getNumElements();
24902b6fb21SMehdi Amini     } else if (auto *sVectorTy = dyn_cast<llvm::ScalableVectorType>(llvmType)) {
250a4830d14SJavier Setoain       elementType = sVectorTy->getElementType();
251a4830d14SJavier Setoain       numElements = sVectorTy->getMinNumElements();
2527c564586SJavier Setoain       isScalable = true;
25368b03aeeSEli Friedman     } else {
254a4830d14SJavier Setoain       llvm_unreachable("unrecognized constant vector type");
25568b03aeeSEli Friedman     }
256d6ea8ff0SAlex Zinenko     // Splat value is a scalar. Extract it only if the element type is not
257d6ea8ff0SAlex Zinenko     // another sequence type. The recursion terminates because each step removes
258d6ea8ff0SAlex Zinenko     // one outer sequential type.
25968b03aeeSEli Friedman     bool elementTypeSequential =
260d891d738SRahul Joshi         isa<llvm::ArrayType, llvm::VectorType>(elementType);
261d6ea8ff0SAlex Zinenko     llvm::Constant *child = getLLVMConstant(
262d6ea8ff0SAlex Zinenko         elementType,
263937e40a8SRiver Riddle         elementTypeSequential ? splatAttr
264937e40a8SRiver Riddle                               : splatAttr.getSplatValue<Attribute>(),
265937e40a8SRiver Riddle         loc, moduleTranslation, false);
266a4a42160SAlex Zinenko     if (!child)
267a4a42160SAlex Zinenko       return nullptr;
2682f13df13SMLIR Team     if (llvmType->isVectorTy())
269396a42d9SRiver Riddle       return llvm::ConstantVector::getSplat(
2707c564586SJavier Setoain           llvm::ElementCount::get(numElements, /*Scalable=*/isScalable), child);
2712f13df13SMLIR Team     if (llvmType->isArrayTy()) {
272ac9d742bSStephan Herhut       auto *arrayType = llvm::ArrayType::get(elementType, numElements);
2732f13df13SMLIR Team       SmallVector<llvm::Constant *, 8> constants(numElements, child);
2742f13df13SMLIR Team       return llvm::ConstantArray::get(arrayType, constants);
2752f13df13SMLIR Team     }
2765d7231d8SStephan Herhut   }
277a4a42160SAlex Zinenko 
278f9be7a7aSAlex Zinenko   // Try using raw elements data if possible.
279f9be7a7aSAlex Zinenko   if (llvm::Constant *result =
280f9be7a7aSAlex Zinenko           convertDenseElementsAttr(loc, attr.dyn_cast<DenseElementsAttr>(),
281f9be7a7aSAlex Zinenko                                    llvmType, moduleTranslation)) {
282f9be7a7aSAlex Zinenko     return result;
283f9be7a7aSAlex Zinenko   }
284f9be7a7aSAlex Zinenko 
285f9be7a7aSAlex Zinenko   // Fall back to element-by-element construction otherwise.
286d906f84bSRiver Riddle   if (auto elementsAttr = attr.dyn_cast<ElementsAttr>()) {
287a4a42160SAlex Zinenko     assert(elementsAttr.getType().hasStaticShape());
288a4a42160SAlex Zinenko     assert(!elementsAttr.getType().getShape().empty() &&
289a4a42160SAlex Zinenko            "unexpected empty elements attribute shape");
290a4a42160SAlex Zinenko 
2915d7231d8SStephan Herhut     SmallVector<llvm::Constant *, 8> constants;
292a4a42160SAlex Zinenko     constants.reserve(elementsAttr.getNumElements());
293a4a42160SAlex Zinenko     llvm::Type *innermostType = getInnermostElementType(llvmType);
294d906f84bSRiver Riddle     for (auto n : elementsAttr.getValues<Attribute>()) {
295176379e0SAlex Zinenko       constants.push_back(
2965ef21506SAdrian Kuegel           getLLVMConstant(innermostType, n, loc, moduleTranslation, false));
2975d7231d8SStephan Herhut       if (!constants.back())
2985d7231d8SStephan Herhut         return nullptr;
2995d7231d8SStephan Herhut     }
300a4a42160SAlex Zinenko     ArrayRef<llvm::Constant *> constantsRef = constants;
301a4a42160SAlex Zinenko     llvm::Constant *result = buildSequentialConstant(
302a4a42160SAlex Zinenko         constantsRef, elementsAttr.getType().getShape(), llvmType, loc);
303a4a42160SAlex Zinenko     assert(constantsRef.empty() && "did not consume all elemental constants");
304a4a42160SAlex Zinenko     return result;
3052f13df13SMLIR Team   }
306a4a42160SAlex Zinenko 
307cb348dffSStephan Herhut   if (auto stringAttr = attr.dyn_cast<StringAttr>()) {
308cb348dffSStephan Herhut     return llvm::ConstantDataArray::get(
309176379e0SAlex Zinenko         moduleTranslation.getLLVMContext(),
310176379e0SAlex Zinenko         ArrayRef<char>{stringAttr.getValue().data(),
311cb348dffSStephan Herhut                        stringAttr.getValue().size()});
312cb348dffSStephan Herhut   }
313a4c3a645SRiver Riddle   emitError(loc, "unsupported constant value");
3145d7231d8SStephan Herhut   return nullptr;
3155d7231d8SStephan Herhut }
3165d7231d8SStephan Herhut 
317c33d6970SRiver Riddle ModuleTranslation::ModuleTranslation(Operation *module,
318c33d6970SRiver Riddle                                      std::unique_ptr<llvm::Module> llvmModule)
319c33d6970SRiver Riddle     : mlirModule(module), llvmModule(std::move(llvmModule)),
320c33d6970SRiver Riddle       debugTranslation(
32192a295ebSKiran Chandramohan           std::make_unique<DebugTranslation>(module, *this->llvmModule)),
322b77bac05SAlex Zinenko       typeTranslator(this->llvmModule->getContext()),
323b77bac05SAlex Zinenko       iface(module->getContext()) {
324c33d6970SRiver Riddle   assert(satisfiesLLVMModule(mlirModule) &&
325c33d6970SRiver Riddle          "mlirModule should honor LLVM's module semantics.");
326c33d6970SRiver Riddle }
327d9067dcaSKiran Chandramohan ModuleTranslation::~ModuleTranslation() {
328d9067dcaSKiran Chandramohan   if (ompBuilder)
329d9067dcaSKiran Chandramohan     ompBuilder->finalize();
330d9067dcaSKiran Chandramohan }
331d9067dcaSKiran Chandramohan 
3328647e4c3SAlex Zinenko void ModuleTranslation::forgetMapping(Region &region) {
3338647e4c3SAlex Zinenko   SmallVector<Region *> toProcess;
3348647e4c3SAlex Zinenko   toProcess.push_back(&region);
3358647e4c3SAlex Zinenko   while (!toProcess.empty()) {
3368647e4c3SAlex Zinenko     Region *current = toProcess.pop_back_val();
3378647e4c3SAlex Zinenko     for (Block &block : *current) {
3388647e4c3SAlex Zinenko       blockMapping.erase(&block);
3398647e4c3SAlex Zinenko       for (Value arg : block.getArguments())
3408647e4c3SAlex Zinenko         valueMapping.erase(arg);
3418647e4c3SAlex Zinenko       for (Operation &op : block) {
3428647e4c3SAlex Zinenko         for (Value value : op.getResults())
3438647e4c3SAlex Zinenko           valueMapping.erase(value);
3448647e4c3SAlex Zinenko         if (op.hasSuccessors())
3458647e4c3SAlex Zinenko           branchMapping.erase(&op);
3468647e4c3SAlex Zinenko         if (isa<LLVM::GlobalOp>(op))
3478647e4c3SAlex Zinenko           globalsMapping.erase(&op);
3488647e4c3SAlex Zinenko         accessGroupMetadataMapping.erase(&op);
3498647e4c3SAlex Zinenko         llvm::append_range(
3508647e4c3SAlex Zinenko             toProcess,
3518647e4c3SAlex Zinenko             llvm::map_range(op.getRegions(), [](Region &r) { return &r; }));
3528647e4c3SAlex Zinenko       }
3538647e4c3SAlex Zinenko     }
3548647e4c3SAlex Zinenko   }
3558647e4c3SAlex Zinenko }
3568647e4c3SAlex Zinenko 
357d9067dcaSKiran Chandramohan /// Get the SSA value passed to the current block from the terminator operation
358d9067dcaSKiran Chandramohan /// of its predecessor.
359d9067dcaSKiran Chandramohan static Value getPHISourceValue(Block *current, Block *pred,
360d9067dcaSKiran Chandramohan                                unsigned numArguments, unsigned index) {
361d9067dcaSKiran Chandramohan   Operation &terminator = *pred->getTerminator();
362d9067dcaSKiran Chandramohan   if (isa<LLVM::BrOp>(terminator))
363d9067dcaSKiran Chandramohan     return terminator.getOperand(index);
364d9067dcaSKiran Chandramohan 
365*bea16e72SAlex Zinenko #ifndef NDEBUG
366*bea16e72SAlex Zinenko   llvm::SmallPtrSet<Block *, 4> seenSuccessors;
367*bea16e72SAlex Zinenko   for (unsigned i = 0, e = terminator.getNumSuccessors(); i < e; ++i) {
368*bea16e72SAlex Zinenko     Block *successor = terminator.getSuccessor(i);
369*bea16e72SAlex Zinenko     auto branch = cast<BranchOpInterface>(terminator);
370*bea16e72SAlex Zinenko     Optional<OperandRange> successorOperands = branch.getSuccessorOperands(i);
371*bea16e72SAlex Zinenko     assert(
372*bea16e72SAlex Zinenko         (!seenSuccessors.contains(successor) ||
373*bea16e72SAlex Zinenko          (successorOperands && successorOperands->empty())) &&
37414f24155SBrian Gesiak         "successors with arguments in LLVM branches must be different blocks");
375*bea16e72SAlex Zinenko     seenSuccessors.insert(successor);
376*bea16e72SAlex Zinenko   }
377*bea16e72SAlex Zinenko #endif
378d9067dcaSKiran Chandramohan 
37914f24155SBrian Gesiak   // For instructions that branch based on a condition value, we need to take
38014f24155SBrian Gesiak   // the operands for the branch that was taken.
38114f24155SBrian Gesiak   if (auto condBranchOp = dyn_cast<LLVM::CondBrOp>(terminator)) {
38214f24155SBrian Gesiak     // For conditional branches, we take the operands from either the "true" or
38314f24155SBrian Gesiak     // the "false" branch.
384d9067dcaSKiran Chandramohan     return condBranchOp.getSuccessor(0) == current
385cfb72fd3SJacques Pienaar                ? condBranchOp.getTrueDestOperands()[index]
386cfb72fd3SJacques Pienaar                : condBranchOp.getFalseDestOperands()[index];
3870881a4f1SAlex Zinenko   }
3880881a4f1SAlex Zinenko 
3890881a4f1SAlex Zinenko   if (auto switchOp = dyn_cast<LLVM::SwitchOp>(terminator)) {
39014f24155SBrian Gesiak     // For switches, we take the operands from either the default case, or from
39114f24155SBrian Gesiak     // the case branch that was taken.
392dde96363SJacques Pienaar     if (switchOp.getDefaultDestination() == current)
393dde96363SJacques Pienaar       return switchOp.getDefaultOperands()[index];
394e4853be2SMehdi Amini     for (const auto &i : llvm::enumerate(switchOp.getCaseDestinations()))
39514f24155SBrian Gesiak       if (i.value() == current)
39614f24155SBrian Gesiak         return switchOp.getCaseOperands(i.index())[index];
39714f24155SBrian Gesiak   }
39814f24155SBrian Gesiak 
39956097205SMarkus Böck   if (auto invokeOp = dyn_cast<LLVM::InvokeOp>(terminator)) {
40056097205SMarkus Böck     return invokeOp.getNormalDest() == current
40156097205SMarkus Böck                ? invokeOp.getNormalDestOperands()[index]
40256097205SMarkus Böck                : invokeOp.getUnwindDestOperands()[index];
40356097205SMarkus Böck   }
40456097205SMarkus Böck 
40556097205SMarkus Böck   llvm_unreachable(
40656097205SMarkus Böck       "only branch, switch or invoke operations can be terminators "
40756097205SMarkus Böck       "of a block that has successors");
408d9067dcaSKiran Chandramohan }
409d9067dcaSKiran Chandramohan 
410d9067dcaSKiran Chandramohan /// Connect the PHI nodes to the results of preceding blocks.
41166900b3eSAlex Zinenko void mlir::LLVM::detail::connectPHINodes(Region &region,
41266900b3eSAlex Zinenko                                          const ModuleTranslation &state) {
413d9067dcaSKiran Chandramohan   // Skip the first block, it cannot be branched to and its arguments correspond
414d9067dcaSKiran Chandramohan   // to the arguments of the LLVM function.
41566900b3eSAlex Zinenko   for (auto it = std::next(region.begin()), eit = region.end(); it != eit;
41666900b3eSAlex Zinenko        ++it) {
417d9067dcaSKiran Chandramohan     Block *bb = &*it;
4180881a4f1SAlex Zinenko     llvm::BasicBlock *llvmBB = state.lookupBlock(bb);
419d9067dcaSKiran Chandramohan     auto phis = llvmBB->phis();
420d9067dcaSKiran Chandramohan     auto numArguments = bb->getNumArguments();
421d9067dcaSKiran Chandramohan     assert(numArguments == std::distance(phis.begin(), phis.end()));
422d9067dcaSKiran Chandramohan     for (auto &numberedPhiNode : llvm::enumerate(phis)) {
423d9067dcaSKiran Chandramohan       auto &phiNode = numberedPhiNode.value();
424d9067dcaSKiran Chandramohan       unsigned index = numberedPhiNode.index();
425d9067dcaSKiran Chandramohan       for (auto *pred : bb->getPredecessors()) {
426db884dafSAlex Zinenko         // Find the LLVM IR block that contains the converted terminator
427db884dafSAlex Zinenko         // instruction and use it in the PHI node. Note that this block is not
4280881a4f1SAlex Zinenko         // necessarily the same as state.lookupBlock(pred), some operations
429db884dafSAlex Zinenko         // (in particular, OpenMP operations using OpenMPIRBuilder) may have
430db884dafSAlex Zinenko         // split the blocks.
431db884dafSAlex Zinenko         llvm::Instruction *terminator =
4320881a4f1SAlex Zinenko             state.lookupBranch(pred->getTerminator());
433db884dafSAlex Zinenko         assert(terminator && "missing the mapping for a terminator");
4340881a4f1SAlex Zinenko         phiNode.addIncoming(
4350881a4f1SAlex Zinenko             state.lookupValue(getPHISourceValue(bb, pred, numArguments, index)),
436db884dafSAlex Zinenko             terminator->getParent());
437d9067dcaSKiran Chandramohan       }
438d9067dcaSKiran Chandramohan     }
439d9067dcaSKiran Chandramohan   }
440d9067dcaSKiran Chandramohan }
441d9067dcaSKiran Chandramohan 
442d9067dcaSKiran Chandramohan /// Sort function blocks topologically.
4434efb7754SRiver Riddle SetVector<Block *>
44466900b3eSAlex Zinenko mlir::LLVM::detail::getTopologicallySortedBlocks(Region &region) {
445d4568ed7SGeorge Mitenkov   // For each block that has not been visited yet (i.e. that has no
446d4568ed7SGeorge Mitenkov   // predecessors), add it to the list as well as its successors.
4474efb7754SRiver Riddle   SetVector<Block *> blocks;
44866900b3eSAlex Zinenko   for (Block &b : region) {
449d4568ed7SGeorge Mitenkov     if (blocks.count(&b) == 0) {
450d4568ed7SGeorge Mitenkov       llvm::ReversePostOrderTraversal<Block *> traversal(&b);
451d4568ed7SGeorge Mitenkov       blocks.insert(traversal.begin(), traversal.end());
452d4568ed7SGeorge Mitenkov     }
453d9067dcaSKiran Chandramohan   }
45466900b3eSAlex Zinenko   assert(blocks.size() == region.getBlocks().size() &&
45566900b3eSAlex Zinenko          "some blocks are not sorted");
456d9067dcaSKiran Chandramohan 
457d9067dcaSKiran Chandramohan   return blocks;
458d9067dcaSKiran Chandramohan }
459d9067dcaSKiran Chandramohan 
460176379e0SAlex Zinenko llvm::Value *mlir::LLVM::detail::createIntrinsicCall(
461176379e0SAlex Zinenko     llvm::IRBuilderBase &builder, llvm::Intrinsic::ID intrinsic,
462176379e0SAlex Zinenko     ArrayRef<llvm::Value *> args, ArrayRef<llvm::Type *> tys) {
463176379e0SAlex Zinenko   llvm::Module *module = builder.GetInsertBlock()->getModule();
464176379e0SAlex Zinenko   llvm::Function *fn = llvm::Intrinsic::getDeclaration(module, intrinsic, tys);
465176379e0SAlex Zinenko   return builder.CreateCall(fn, args);
466176379e0SAlex Zinenko }
467176379e0SAlex Zinenko 
4682666b973SRiver Riddle /// Given a single MLIR operation, create the corresponding LLVM IR operation
469176379e0SAlex Zinenko /// using the `builder`.
470ce8f10d6SAlex Zinenko LogicalResult
47138b106f6SMehdi Amini ModuleTranslation::convertOperation(Operation &op,
472ce8f10d6SAlex Zinenko                                     llvm::IRBuilderBase &builder) {
47338b106f6SMehdi Amini   const LLVMTranslationDialectInterface *opIface = iface.getInterfaceFor(&op);
47438b106f6SMehdi Amini   if (!opIface)
47538b106f6SMehdi Amini     return op.emitError("cannot be converted to LLVM IR: missing "
47638b106f6SMehdi Amini                         "`LLVMTranslationDialectInterface` registration for "
47738b106f6SMehdi Amini                         "dialect for op: ")
47838b106f6SMehdi Amini            << op.getName();
479176379e0SAlex Zinenko 
48038b106f6SMehdi Amini   if (failed(opIface->convertOperation(&op, builder, *this)))
48138b106f6SMehdi Amini     return op.emitError("LLVM Translation failed for operation: ")
48238b106f6SMehdi Amini            << op.getName();
48338b106f6SMehdi Amini 
48438b106f6SMehdi Amini   return convertDialectAttributes(&op);
4855d7231d8SStephan Herhut }
4865d7231d8SStephan Herhut 
4872666b973SRiver Riddle /// Convert block to LLVM IR.  Unless `ignoreArguments` is set, emit PHI nodes
4882666b973SRiver Riddle /// to define values corresponding to the MLIR block arguments.  These nodes
48910164a2eSAlex Zinenko /// are not connected to the source basic blocks, which may not exist yet.  Uses
49010164a2eSAlex Zinenko /// `builder` to construct the LLVM IR. Expects the LLVM IR basic block to have
49110164a2eSAlex Zinenko /// been created for `bb` and included in the block mapping.  Inserts new
49210164a2eSAlex Zinenko /// instructions at the end of the block and leaves `builder` in a state
49310164a2eSAlex Zinenko /// suitable for further insertion into the end of the block.
49410164a2eSAlex Zinenko LogicalResult ModuleTranslation::convertBlock(Block &bb, bool ignoreArguments,
495ce8f10d6SAlex Zinenko                                               llvm::IRBuilderBase &builder) {
4960881a4f1SAlex Zinenko   builder.SetInsertPoint(lookupBlock(&bb));
497c33d6970SRiver Riddle   auto *subprogram = builder.GetInsertBlock()->getParent()->getSubprogram();
4985d7231d8SStephan Herhut 
4995d7231d8SStephan Herhut   // Before traversing operations, make block arguments available through
5005d7231d8SStephan Herhut   // value remapping and PHI nodes, but do not add incoming edges for the PHI
5015d7231d8SStephan Herhut   // nodes just yet: those values may be defined by this or following blocks.
5025d7231d8SStephan Herhut   // This step is omitted if "ignoreArguments" is set.  The arguments of the
5035d7231d8SStephan Herhut   // first block have been already made available through the remapping of
5045d7231d8SStephan Herhut   // LLVM function arguments.
5055d7231d8SStephan Herhut   if (!ignoreArguments) {
5065d7231d8SStephan Herhut     auto predecessors = bb.getPredecessors();
5075d7231d8SStephan Herhut     unsigned numPredecessors =
5085d7231d8SStephan Herhut         std::distance(predecessors.begin(), predecessors.end());
50935807bc4SRiver Riddle     for (auto arg : bb.getArguments()) {
510c69c9e0fSAlex Zinenko       auto wrappedType = arg.getType();
511c69c9e0fSAlex Zinenko       if (!isCompatibleType(wrappedType))
512baa1ec22SAlex Zinenko         return emitError(bb.front().getLoc(),
513a4c3a645SRiver Riddle                          "block argument does not have an LLVM type");
514aec38c61SAlex Zinenko       llvm::Type *type = convertType(wrappedType);
5155d7231d8SStephan Herhut       llvm::PHINode *phi = builder.CreatePHI(type, numPredecessors);
5160881a4f1SAlex Zinenko       mapValue(arg, phi);
5175d7231d8SStephan Herhut     }
5185d7231d8SStephan Herhut   }
5195d7231d8SStephan Herhut 
5205d7231d8SStephan Herhut   // Traverse operations.
5215d7231d8SStephan Herhut   for (auto &op : bb) {
522c33d6970SRiver Riddle     // Set the current debug location within the builder.
523c33d6970SRiver Riddle     builder.SetCurrentDebugLocation(
524c33d6970SRiver Riddle         debugTranslation->translateLoc(op.getLoc(), subprogram));
525c33d6970SRiver Riddle 
526baa1ec22SAlex Zinenko     if (failed(convertOperation(op, builder)))
527baa1ec22SAlex Zinenko       return failure();
5285d7231d8SStephan Herhut   }
5295d7231d8SStephan Herhut 
530baa1ec22SAlex Zinenko   return success();
5315d7231d8SStephan Herhut }
5325d7231d8SStephan Herhut 
533ce8f10d6SAlex Zinenko /// A helper method to get the single Block in an operation honoring LLVM's
534ce8f10d6SAlex Zinenko /// module requirements.
535ce8f10d6SAlex Zinenko static Block &getModuleBody(Operation *module) {
536ce8f10d6SAlex Zinenko   return module->getRegion(0).front();
537ce8f10d6SAlex Zinenko }
538ce8f10d6SAlex Zinenko 
539ffa455d4SJean Perier /// A helper method to decide if a constant must not be set as a global variable
540d4df3825SAlex Zinenko /// initializer. For an external linkage variable, the variable with an
541d4df3825SAlex Zinenko /// initializer is considered externally visible and defined in this module, the
542d4df3825SAlex Zinenko /// variable without an initializer is externally available and is defined
543d4df3825SAlex Zinenko /// elsewhere.
544ffa455d4SJean Perier static bool shouldDropGlobalInitializer(llvm::GlobalValue::LinkageTypes linkage,
545ffa455d4SJean Perier                                         llvm::Constant *cst) {
546d4df3825SAlex Zinenko   return (linkage == llvm::GlobalVariable::ExternalLinkage && !cst) ||
547ffa455d4SJean Perier          linkage == llvm::GlobalVariable::ExternalWeakLinkage;
548ffa455d4SJean Perier }
549ffa455d4SJean Perier 
5508ca04b05SFelipe de Azevedo Piovezan /// Sets the runtime preemption specifier of `gv` to dso_local if
5518ca04b05SFelipe de Azevedo Piovezan /// `dsoLocalRequested` is true, otherwise it is left unchanged.
5528ca04b05SFelipe de Azevedo Piovezan static void addRuntimePreemptionSpecifier(bool dsoLocalRequested,
5538ca04b05SFelipe de Azevedo Piovezan                                           llvm::GlobalValue *gv) {
5548ca04b05SFelipe de Azevedo Piovezan   if (dsoLocalRequested)
5558ca04b05SFelipe de Azevedo Piovezan     gv->setDSOLocal(true);
5568ca04b05SFelipe de Azevedo Piovezan }
5578ca04b05SFelipe de Azevedo Piovezan 
5582666b973SRiver Riddle /// Create named global variables that correspond to llvm.mlir.global
55957b9b296SUday Bondhugula /// definitions. Convert llvm.global_ctors and global_dtors ops.
560efa2d533SAlex Zinenko LogicalResult ModuleTranslation::convertGlobals() {
56144fc7d72STres Popp   for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) {
562aec38c61SAlex Zinenko     llvm::Type *type = convertType(op.getType());
563d4df3825SAlex Zinenko     llvm::Constant *cst = nullptr;
564250a11aeSJames Molloy     if (op.getValueOrNull()) {
56568451df2SAlex Zinenko       // String attributes are treated separately because they cannot appear as
56668451df2SAlex Zinenko       // in-function constants and are thus not supported by getLLVMConstant.
56733a3a91bSChristian Sigg       if (auto strAttr = op.getValueOrNull().dyn_cast_or_null<StringAttr>()) {
5682dd38b09SAlex Zinenko         cst = llvm::ConstantDataArray::getString(
56968451df2SAlex Zinenko             llvmModule->getContext(), strAttr.getValue(), /*AddNull=*/false);
5702dd38b09SAlex Zinenko         type = cst->getType();
571176379e0SAlex Zinenko       } else if (!(cst = getLLVMConstant(type, op.getValueOrNull(), op.getLoc(),
572176379e0SAlex Zinenko                                          *this))) {
573efa2d533SAlex Zinenko         return failure();
57468451df2SAlex Zinenko       }
575ffa455d4SJean Perier     }
576ffa455d4SJean Perier 
577cfb72fd3SJacques Pienaar     auto linkage = convertLinkageToLLVM(op.getLinkage());
578cfb72fd3SJacques Pienaar     auto addrSpace = op.getAddrSpace();
579d4df3825SAlex Zinenko 
580d4df3825SAlex Zinenko     // LLVM IR requires constant with linkage other than external or weak
581d4df3825SAlex Zinenko     // external to have initializers. If MLIR does not provide an initializer,
582d4df3825SAlex Zinenko     // default to undef.
583d4df3825SAlex Zinenko     bool dropInitializer = shouldDropGlobalInitializer(linkage, cst);
584d4df3825SAlex Zinenko     if (!dropInitializer && !cst)
585d4df3825SAlex Zinenko       cst = llvm::UndefValue::get(type);
586d4df3825SAlex Zinenko     else if (dropInitializer && cst)
587d4df3825SAlex Zinenko       cst = nullptr;
588d4df3825SAlex Zinenko 
589ffa455d4SJean Perier     auto *var = new llvm::GlobalVariable(
590cfb72fd3SJacques Pienaar         *llvmModule, type, op.getConstant(), linkage, cst, op.getSymName(),
591ffa455d4SJean Perier         /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal, addrSpace);
592ffa455d4SJean Perier 
593cfb72fd3SJacques Pienaar     if (op.getUnnamedAddr().hasValue())
594cfb72fd3SJacques Pienaar       var->setUnnamedAddr(convertUnnamedAddrToLLVM(*op.getUnnamedAddr()));
595c46a8862Sclementval 
596cfb72fd3SJacques Pienaar     if (op.getSection().hasValue())
597cfb72fd3SJacques Pienaar       var->setSection(*op.getSection());
598b65472d6SRanjith Kumar H 
599cfb72fd3SJacques Pienaar     addRuntimePreemptionSpecifier(op.getDsoLocal(), var);
6008ca04b05SFelipe de Azevedo Piovezan 
601cfb72fd3SJacques Pienaar     Optional<uint64_t> alignment = op.getAlignment();
6029a0ea599SDumitru Potop     if (alignment.hasValue())
6039a0ea599SDumitru Potop       var->setAlignment(llvm::MaybeAlign(alignment.getValue()));
6049a0ea599SDumitru Potop 
605ffa455d4SJean Perier     globalsMapping.try_emplace(op, var);
606ffa455d4SJean Perier   }
607ffa455d4SJean Perier 
608ffa455d4SJean Perier   // Convert global variable bodies. This is done after all global variables
609ffa455d4SJean Perier   // have been created in LLVM IR because a global body may refer to another
610ffa455d4SJean Perier   // global or itself. So all global variables need to be mapped first.
611ffa455d4SJean Perier   for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) {
612ffa455d4SJean Perier     if (Block *initializer = op.getInitializerBlock()) {
613250a11aeSJames Molloy       llvm::IRBuilder<> builder(llvmModule->getContext());
614250a11aeSJames Molloy       for (auto &op : initializer->without_terminator()) {
615250a11aeSJames Molloy         if (failed(convertOperation(op, builder)) ||
6160881a4f1SAlex Zinenko             !isa<llvm::Constant>(lookupValue(op.getResult(0))))
617efa2d533SAlex Zinenko           return emitError(op.getLoc(), "unemittable constant value");
618250a11aeSJames Molloy       }
619250a11aeSJames Molloy       ReturnOp ret = cast<ReturnOp>(initializer->getTerminator());
620ffa455d4SJean Perier       llvm::Constant *cst =
621ffa455d4SJean Perier           cast<llvm::Constant>(lookupValue(ret.getOperand(0)));
622ffa455d4SJean Perier       auto *global = cast<llvm::GlobalVariable>(lookupGlobal(op));
623ffa455d4SJean Perier       if (!shouldDropGlobalInitializer(global->getLinkage(), cst))
624ffa455d4SJean Perier         global->setInitializer(cst);
625250a11aeSJames Molloy     }
626b9ff2dd8SAlex Zinenko   }
627efa2d533SAlex Zinenko 
62857b9b296SUday Bondhugula   // Convert llvm.mlir.global_ctors and dtors.
62957b9b296SUday Bondhugula   for (Operation &op : getModuleBody(mlirModule)) {
63057b9b296SUday Bondhugula     auto ctorOp = dyn_cast<GlobalCtorsOp>(op);
63157b9b296SUday Bondhugula     auto dtorOp = dyn_cast<GlobalDtorsOp>(op);
63257b9b296SUday Bondhugula     if (!ctorOp && !dtorOp)
63357b9b296SUday Bondhugula       continue;
63462fea88bSJacques Pienaar     auto range = ctorOp ? llvm::zip(ctorOp.getCtors(), ctorOp.getPriorities())
63562fea88bSJacques Pienaar                         : llvm::zip(dtorOp.getDtors(), dtorOp.getPriorities());
63657b9b296SUday Bondhugula     auto appendGlobalFn =
63757b9b296SUday Bondhugula         ctorOp ? llvm::appendToGlobalCtors : llvm::appendToGlobalDtors;
63857b9b296SUday Bondhugula     for (auto symbolAndPriority : range) {
63957b9b296SUday Bondhugula       llvm::Function *f = lookupFunction(
64057b9b296SUday Bondhugula           std::get<0>(symbolAndPriority).cast<FlatSymbolRefAttr>().getValue());
64157b9b296SUday Bondhugula       appendGlobalFn(
64218eb6818SMehdi Amini           *llvmModule, f,
64357b9b296SUday Bondhugula           std::get<1>(symbolAndPriority).cast<IntegerAttr>().getInt(),
64457b9b296SUday Bondhugula           /*Data=*/nullptr);
64557b9b296SUday Bondhugula     }
64657b9b296SUday Bondhugula   }
64757b9b296SUday Bondhugula 
648efa2d533SAlex Zinenko   return success();
649b9ff2dd8SAlex Zinenko }
650b9ff2dd8SAlex Zinenko 
6510a2131b7SAlex Zinenko /// Attempts to add an attribute identified by `key`, optionally with the given
6520a2131b7SAlex Zinenko /// `value` to LLVM function `llvmFunc`. Reports errors at `loc` if any. If the
6530a2131b7SAlex Zinenko /// attribute has a kind known to LLVM IR, create the attribute of this kind,
6540a2131b7SAlex Zinenko /// otherwise keep it as a string attribute. Performs additional checks for
6550a2131b7SAlex Zinenko /// attributes known to have or not have a value in order to avoid assertions
6560a2131b7SAlex Zinenko /// inside LLVM upon construction.
6570a2131b7SAlex Zinenko static LogicalResult checkedAddLLVMFnAttribute(Location loc,
6580a2131b7SAlex Zinenko                                                llvm::Function *llvmFunc,
6590a2131b7SAlex Zinenko                                                StringRef key,
6600a2131b7SAlex Zinenko                                                StringRef value = StringRef()) {
6610a2131b7SAlex Zinenko   auto kind = llvm::Attribute::getAttrKindFromName(key);
6620a2131b7SAlex Zinenko   if (kind == llvm::Attribute::None) {
6630a2131b7SAlex Zinenko     llvmFunc->addFnAttr(key, value);
6640a2131b7SAlex Zinenko     return success();
6650a2131b7SAlex Zinenko   }
6660a2131b7SAlex Zinenko 
6676ac32872SNikita Popov   if (llvm::Attribute::isIntAttrKind(kind)) {
6680a2131b7SAlex Zinenko     if (value.empty())
6690a2131b7SAlex Zinenko       return emitError(loc) << "LLVM attribute '" << key << "' expects a value";
6700a2131b7SAlex Zinenko 
6710a2131b7SAlex Zinenko     int result;
6720a2131b7SAlex Zinenko     if (!value.getAsInteger(/*Radix=*/0, result))
6730a2131b7SAlex Zinenko       llvmFunc->addFnAttr(
6740a2131b7SAlex Zinenko           llvm::Attribute::get(llvmFunc->getContext(), kind, result));
6750a2131b7SAlex Zinenko     else
6760a2131b7SAlex Zinenko       llvmFunc->addFnAttr(key, value);
6770a2131b7SAlex Zinenko     return success();
6780a2131b7SAlex Zinenko   }
6790a2131b7SAlex Zinenko 
6800a2131b7SAlex Zinenko   if (!value.empty())
6810a2131b7SAlex Zinenko     return emitError(loc) << "LLVM attribute '" << key
6820a2131b7SAlex Zinenko                           << "' does not expect a value, found '" << value
6830a2131b7SAlex Zinenko                           << "'";
6840a2131b7SAlex Zinenko 
6850a2131b7SAlex Zinenko   llvmFunc->addFnAttr(kind);
6860a2131b7SAlex Zinenko   return success();
6870a2131b7SAlex Zinenko }
6880a2131b7SAlex Zinenko 
6890a2131b7SAlex Zinenko /// Attaches the attributes listed in the given array attribute to `llvmFunc`.
6900a2131b7SAlex Zinenko /// Reports error to `loc` if any and returns immediately. Expects `attributes`
6910a2131b7SAlex Zinenko /// to be an array attribute containing either string attributes, treated as
6920a2131b7SAlex Zinenko /// value-less LLVM attributes, or array attributes containing two string
6930a2131b7SAlex Zinenko /// attributes, with the first string being the name of the corresponding LLVM
6940a2131b7SAlex Zinenko /// attribute and the second string beings its value. Note that even integer
6950a2131b7SAlex Zinenko /// attributes are expected to have their values expressed as strings.
6960a2131b7SAlex Zinenko static LogicalResult
6970a2131b7SAlex Zinenko forwardPassthroughAttributes(Location loc, Optional<ArrayAttr> attributes,
6980a2131b7SAlex Zinenko                              llvm::Function *llvmFunc) {
6990a2131b7SAlex Zinenko   if (!attributes)
7000a2131b7SAlex Zinenko     return success();
7010a2131b7SAlex Zinenko 
7020a2131b7SAlex Zinenko   for (Attribute attr : *attributes) {
7030a2131b7SAlex Zinenko     if (auto stringAttr = attr.dyn_cast<StringAttr>()) {
7040a2131b7SAlex Zinenko       if (failed(
7050a2131b7SAlex Zinenko               checkedAddLLVMFnAttribute(loc, llvmFunc, stringAttr.getValue())))
7060a2131b7SAlex Zinenko         return failure();
7070a2131b7SAlex Zinenko       continue;
7080a2131b7SAlex Zinenko     }
7090a2131b7SAlex Zinenko 
7100a2131b7SAlex Zinenko     auto arrayAttr = attr.dyn_cast<ArrayAttr>();
7110a2131b7SAlex Zinenko     if (!arrayAttr || arrayAttr.size() != 2)
7120a2131b7SAlex Zinenko       return emitError(loc)
7130a2131b7SAlex Zinenko              << "expected 'passthrough' to contain string or array attributes";
7140a2131b7SAlex Zinenko 
7150a2131b7SAlex Zinenko     auto keyAttr = arrayAttr[0].dyn_cast<StringAttr>();
7160a2131b7SAlex Zinenko     auto valueAttr = arrayAttr[1].dyn_cast<StringAttr>();
7170a2131b7SAlex Zinenko     if (!keyAttr || !valueAttr)
7180a2131b7SAlex Zinenko       return emitError(loc)
7190a2131b7SAlex Zinenko              << "expected arrays within 'passthrough' to contain two strings";
7200a2131b7SAlex Zinenko 
7210a2131b7SAlex Zinenko     if (failed(checkedAddLLVMFnAttribute(loc, llvmFunc, keyAttr.getValue(),
7220a2131b7SAlex Zinenko                                          valueAttr.getValue())))
7230a2131b7SAlex Zinenko       return failure();
7240a2131b7SAlex Zinenko   }
7250a2131b7SAlex Zinenko   return success();
7260a2131b7SAlex Zinenko }
7270a2131b7SAlex Zinenko 
7285e7959a3SAlex Zinenko LogicalResult ModuleTranslation::convertOneFunction(LLVMFuncOp func) {
729db884dafSAlex Zinenko   // Clear the block, branch value mappings, they are only relevant within one
7305d7231d8SStephan Herhut   // function.
7315d7231d8SStephan Herhut   blockMapping.clear();
7325d7231d8SStephan Herhut   valueMapping.clear();
733db884dafSAlex Zinenko   branchMapping.clear();
7340881a4f1SAlex Zinenko   llvm::Function *llvmFunc = lookupFunction(func.getName());
735c33d6970SRiver Riddle 
736c33d6970SRiver Riddle   // Translate the debug information for this function.
737c33d6970SRiver Riddle   debugTranslation->translate(func, *llvmFunc);
738c33d6970SRiver Riddle 
7395d7231d8SStephan Herhut   // Add function arguments to the value remapping table.
7405d7231d8SStephan Herhut   // If there was noalias info then we decorate each argument accordingly.
7415d7231d8SStephan Herhut   unsigned int argIdx = 0;
742eeef50b1SFangrui Song   for (auto kvp : llvm::zip(func.getArguments(), llvmFunc->args())) {
7435d7231d8SStephan Herhut     llvm::Argument &llvmArg = std::get<1>(kvp);
744e62a6956SRiver Riddle     BlockArgument mlirArg = std::get<0>(kvp);
7455d7231d8SStephan Herhut 
7461c777ab4SUday Bondhugula     if (auto attr = func.getArgAttrOfType<UnitAttr>(
74767cc5cecSStephan Herhut             argIdx, LLVMDialect::getNoAliasAttrName())) {
7485d7231d8SStephan Herhut       // NB: Attribute already verified to be boolean, so check if we can indeed
7495d7231d8SStephan Herhut       // attach the attribute to this argument, based on its type.
750c69c9e0fSAlex Zinenko       auto argTy = mlirArg.getType();
7518de43b92SAlex Zinenko       if (!argTy.isa<LLVM::LLVMPointerType>())
752baa1ec22SAlex Zinenko         return func.emitError(
7535d7231d8SStephan Herhut             "llvm.noalias attribute attached to LLVM non-pointer argument");
7545d7231d8SStephan Herhut       llvmArg.addAttr(llvm::Attribute::AttrKind::NoAlias);
7555d7231d8SStephan Herhut     }
7562416e28cSStephan Herhut 
75767cc5cecSStephan Herhut     if (auto attr = func.getArgAttrOfType<IntegerAttr>(
75867cc5cecSStephan Herhut             argIdx, LLVMDialect::getAlignAttrName())) {
7592416e28cSStephan Herhut       // NB: Attribute already verified to be int, so check if we can indeed
7602416e28cSStephan Herhut       // attach the attribute to this argument, based on its type.
761c69c9e0fSAlex Zinenko       auto argTy = mlirArg.getType();
7628de43b92SAlex Zinenko       if (!argTy.isa<LLVM::LLVMPointerType>())
7632416e28cSStephan Herhut         return func.emitError(
7642416e28cSStephan Herhut             "llvm.align attribute attached to LLVM non-pointer argument");
7652416e28cSStephan Herhut       llvmArg.addAttrs(
766d2cc6c2dSSerge Guelton           llvm::AttrBuilder(llvmArg.getContext()).addAlignmentAttr(llvm::Align(attr.getInt())));
7672416e28cSStephan Herhut     }
7682416e28cSStephan Herhut 
76970b841acSEric Schweitz     if (auto attr = func.getArgAttrOfType<UnitAttr>(argIdx, "llvm.sret")) {
77070b841acSEric Schweitz       auto argTy = mlirArg.getType();
77170b841acSEric Schweitz       if (!argTy.isa<LLVM::LLVMPointerType>())
77270b841acSEric Schweitz         return func.emitError(
77370b841acSEric Schweitz             "llvm.sret attribute attached to LLVM non-pointer argument");
774d2cc6c2dSSerge Guelton       llvmArg.addAttrs(llvm::AttrBuilder(llvmArg.getContext()).addStructRetAttr(
7751d6df1fcSEric Schweitz           llvmArg.getType()->getPointerElementType()));
77670b841acSEric Schweitz     }
77770b841acSEric Schweitz 
77870b841acSEric Schweitz     if (auto attr = func.getArgAttrOfType<UnitAttr>(argIdx, "llvm.byval")) {
77970b841acSEric Schweitz       auto argTy = mlirArg.getType();
78070b841acSEric Schweitz       if (!argTy.isa<LLVM::LLVMPointerType>())
78170b841acSEric Schweitz         return func.emitError(
78270b841acSEric Schweitz             "llvm.byval attribute attached to LLVM non-pointer argument");
783d2cc6c2dSSerge Guelton       llvmArg.addAttrs(llvm::AttrBuilder(llvmArg.getContext()).addByValAttr(
7841d6df1fcSEric Schweitz           llvmArg.getType()->getPointerElementType()));
78570b841acSEric Schweitz     }
78670b841acSEric Schweitz 
7870881a4f1SAlex Zinenko     mapValue(mlirArg, &llvmArg);
7885d7231d8SStephan Herhut     argIdx++;
7895d7231d8SStephan Herhut   }
7905d7231d8SStephan Herhut 
791ff77397fSShraiysh Vaishay   // Check the personality and set it.
792dde96363SJacques Pienaar   if (func.getPersonality().hasValue()) {
793ff77397fSShraiysh Vaishay     llvm::Type *ty = llvm::Type::getInt8PtrTy(llvmFunc->getContext());
794dde96363SJacques Pienaar     if (llvm::Constant *pfunc = getLLVMConstant(ty, func.getPersonalityAttr(),
795dde96363SJacques Pienaar                                                 func.getLoc(), *this))
796ff77397fSShraiysh Vaishay       llvmFunc->setPersonalityFn(pfunc);
797ff77397fSShraiysh Vaishay   }
798ff77397fSShraiysh Vaishay 
7995d7231d8SStephan Herhut   // First, create all blocks so we can jump to them.
8005d7231d8SStephan Herhut   llvm::LLVMContext &llvmContext = llvmFunc->getContext();
8015d7231d8SStephan Herhut   for (auto &bb : func) {
8025d7231d8SStephan Herhut     auto *llvmBB = llvm::BasicBlock::Create(llvmContext);
8035d7231d8SStephan Herhut     llvmBB->insertInto(llvmFunc);
8040881a4f1SAlex Zinenko     mapBlock(&bb, llvmBB);
8055d7231d8SStephan Herhut   }
8065d7231d8SStephan Herhut 
8075d7231d8SStephan Herhut   // Then, convert blocks one by one in topological order to ensure defs are
8085d7231d8SStephan Herhut   // converted before uses.
80966900b3eSAlex Zinenko   auto blocks = detail::getTopologicallySortedBlocks(func.getBody());
81010164a2eSAlex Zinenko   for (Block *bb : blocks) {
81110164a2eSAlex Zinenko     llvm::IRBuilder<> builder(llvmContext);
81210164a2eSAlex Zinenko     if (failed(convertBlock(*bb, bb->isEntryBlock(), builder)))
813baa1ec22SAlex Zinenko       return failure();
8145d7231d8SStephan Herhut   }
8155d7231d8SStephan Herhut 
816176379e0SAlex Zinenko   // After all blocks have been traversed and values mapped, connect the PHI
817176379e0SAlex Zinenko   // nodes to the results of preceding blocks.
81866900b3eSAlex Zinenko   detail::connectPHINodes(func.getBody(), *this);
819176379e0SAlex Zinenko 
820176379e0SAlex Zinenko   // Finally, convert dialect attributes attached to the function.
821176379e0SAlex Zinenko   return convertDialectAttributes(func);
822176379e0SAlex Zinenko }
823176379e0SAlex Zinenko 
824176379e0SAlex Zinenko LogicalResult ModuleTranslation::convertDialectAttributes(Operation *op) {
825176379e0SAlex Zinenko   for (NamedAttribute attribute : op->getDialectAttrs())
826176379e0SAlex Zinenko     if (failed(iface.amendOperation(op, attribute, *this)))
827176379e0SAlex Zinenko       return failure();
828baa1ec22SAlex Zinenko   return success();
8295d7231d8SStephan Herhut }
8305d7231d8SStephan Herhut 
831a084b94fSSean Silva LogicalResult ModuleTranslation::convertFunctionSignatures() {
8325d7231d8SStephan Herhut   // Declare all functions first because there may be function calls that form a
833a084b94fSSean Silva   // call graph with cycles, or global initializers that reference functions.
83444fc7d72STres Popp   for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) {
8355e7959a3SAlex Zinenko     llvm::FunctionCallee llvmFuncCst = llvmModule->getOrInsertFunction(
8365e7959a3SAlex Zinenko         function.getName(),
837aec38c61SAlex Zinenko         cast<llvm::FunctionType>(convertType(function.getType())));
8380a2131b7SAlex Zinenko     llvm::Function *llvmFunc = cast<llvm::Function>(llvmFuncCst.getCallee());
839dde96363SJacques Pienaar     llvmFunc->setLinkage(convertLinkageToLLVM(function.getLinkage()));
8400881a4f1SAlex Zinenko     mapFunction(function.getName(), llvmFunc);
841dde96363SJacques Pienaar     addRuntimePreemptionSpecifier(function.getDsoLocal(), llvmFunc);
8420a2131b7SAlex Zinenko 
8430a2131b7SAlex Zinenko     // Forward the pass-through attributes to LLVM.
844dde96363SJacques Pienaar     if (failed(forwardPassthroughAttributes(
845dde96363SJacques Pienaar             function.getLoc(), function.getPassthrough(), llvmFunc)))
8460a2131b7SAlex Zinenko       return failure();
8475d7231d8SStephan Herhut   }
8485d7231d8SStephan Herhut 
849a084b94fSSean Silva   return success();
850a084b94fSSean Silva }
851a084b94fSSean Silva 
852a084b94fSSean Silva LogicalResult ModuleTranslation::convertFunctions() {
8535d7231d8SStephan Herhut   // Convert functions.
85444fc7d72STres Popp   for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) {
8555d7231d8SStephan Herhut     // Ignore external functions.
8565d7231d8SStephan Herhut     if (function.isExternal())
8575d7231d8SStephan Herhut       continue;
8585d7231d8SStephan Herhut 
859baa1ec22SAlex Zinenko     if (failed(convertOneFunction(function)))
860baa1ec22SAlex Zinenko       return failure();
8615d7231d8SStephan Herhut   }
8625d7231d8SStephan Herhut 
863baa1ec22SAlex Zinenko   return success();
8645d7231d8SStephan Herhut }
8655d7231d8SStephan Herhut 
8664a2930f4SArpith C. Jacob llvm::MDNode *
8674a2930f4SArpith C. Jacob ModuleTranslation::getAccessGroup(Operation &opInst,
8684a2930f4SArpith C. Jacob                                   SymbolRefAttr accessGroupRef) const {
8694a2930f4SArpith C. Jacob   auto metadataName = accessGroupRef.getRootReference();
8704a2930f4SArpith C. Jacob   auto accessGroupName = accessGroupRef.getLeafReference();
8714a2930f4SArpith C. Jacob   auto metadataOp = SymbolTable::lookupNearestSymbolFrom<LLVM::MetadataOp>(
8724a2930f4SArpith C. Jacob       opInst.getParentOp(), metadataName);
8734a2930f4SArpith C. Jacob   auto *accessGroupOp =
8744a2930f4SArpith C. Jacob       SymbolTable::lookupNearestSymbolFrom(metadataOp, accessGroupName);
8754a2930f4SArpith C. Jacob   return accessGroupMetadataMapping.lookup(accessGroupOp);
8764a2930f4SArpith C. Jacob }
8774a2930f4SArpith C. Jacob 
8784a2930f4SArpith C. Jacob LogicalResult ModuleTranslation::createAccessGroupMetadata() {
8794a2930f4SArpith C. Jacob   mlirModule->walk([&](LLVM::MetadataOp metadatas) {
8804a2930f4SArpith C. Jacob     metadatas.walk([&](LLVM::AccessGroupMetadataOp op) {
8814a2930f4SArpith C. Jacob       llvm::LLVMContext &ctx = llvmModule->getContext();
8824a2930f4SArpith C. Jacob       llvm::MDNode *accessGroup = llvm::MDNode::getDistinct(ctx, {});
8834a2930f4SArpith C. Jacob       accessGroupMetadataMapping.insert({op, accessGroup});
8844a2930f4SArpith C. Jacob     });
8854a2930f4SArpith C. Jacob   });
8864a2930f4SArpith C. Jacob   return success();
8874a2930f4SArpith C. Jacob }
8884a2930f4SArpith C. Jacob 
8894e393350SArpith C. Jacob void ModuleTranslation::setAccessGroupsMetadata(Operation *op,
8904e393350SArpith C. Jacob                                                 llvm::Instruction *inst) {
8914e393350SArpith C. Jacob   auto accessGroups =
8924e393350SArpith C. Jacob       op->getAttrOfType<ArrayAttr>(LLVMDialect::getAccessGroupsAttrName());
8934e393350SArpith C. Jacob   if (accessGroups && !accessGroups.empty()) {
8944e393350SArpith C. Jacob     llvm::Module *module = inst->getModule();
8954e393350SArpith C. Jacob     SmallVector<llvm::Metadata *> metadatas;
8964e393350SArpith C. Jacob     for (SymbolRefAttr accessGroupRef :
8974e393350SArpith C. Jacob          accessGroups.getAsRange<SymbolRefAttr>())
8984e393350SArpith C. Jacob       metadatas.push_back(getAccessGroup(*op, accessGroupRef));
8994e393350SArpith C. Jacob 
9004e393350SArpith C. Jacob     llvm::MDNode *unionMD = nullptr;
9014e393350SArpith C. Jacob     if (metadatas.size() == 1)
9024e393350SArpith C. Jacob       unionMD = llvm::cast<llvm::MDNode>(metadatas.front());
9034e393350SArpith C. Jacob     else if (metadatas.size() >= 2)
9044e393350SArpith C. Jacob       unionMD = llvm::MDNode::get(module->getContext(), metadatas);
9054e393350SArpith C. Jacob 
9064e393350SArpith C. Jacob     inst->setMetadata(module->getMDKindID("llvm.access.group"), unionMD);
9074e393350SArpith C. Jacob   }
9084e393350SArpith C. Jacob }
9094e393350SArpith C. Jacob 
910d25e91d7STyler Augustine LogicalResult ModuleTranslation::createAliasScopeMetadata() {
911d25e91d7STyler Augustine   mlirModule->walk([&](LLVM::MetadataOp metadatas) {
912d25e91d7STyler Augustine     // Create the domains first, so they can be reference below in the scopes.
913d25e91d7STyler Augustine     DenseMap<Operation *, llvm::MDNode *> aliasScopeDomainMetadataMapping;
914d25e91d7STyler Augustine     metadatas.walk([&](LLVM::AliasScopeDomainMetadataOp op) {
915d25e91d7STyler Augustine       llvm::LLVMContext &ctx = llvmModule->getContext();
916d25e91d7STyler Augustine       llvm::SmallVector<llvm::Metadata *, 2> operands;
917d25e91d7STyler Augustine       operands.push_back({}); // Placeholder for self-reference
918cfb72fd3SJacques Pienaar       if (Optional<StringRef> description = op.getDescription())
919d25e91d7STyler Augustine         operands.push_back(llvm::MDString::get(ctx, description.getValue()));
920d25e91d7STyler Augustine       llvm::MDNode *domain = llvm::MDNode::get(ctx, operands);
921d25e91d7STyler Augustine       domain->replaceOperandWith(0, domain); // Self-reference for uniqueness
922d25e91d7STyler Augustine       aliasScopeDomainMetadataMapping.insert({op, domain});
923d25e91d7STyler Augustine     });
924d25e91d7STyler Augustine 
925d25e91d7STyler Augustine     // Now create the scopes, referencing the domains created above.
926d25e91d7STyler Augustine     metadatas.walk([&](LLVM::AliasScopeMetadataOp op) {
927d25e91d7STyler Augustine       llvm::LLVMContext &ctx = llvmModule->getContext();
928d25e91d7STyler Augustine       assert(isa<LLVM::MetadataOp>(op->getParentOp()));
929d25e91d7STyler Augustine       auto metadataOp = dyn_cast<LLVM::MetadataOp>(op->getParentOp());
930d25e91d7STyler Augustine       Operation *domainOp =
931cfb72fd3SJacques Pienaar           SymbolTable::lookupNearestSymbolFrom(metadataOp, op.getDomainAttr());
932d25e91d7STyler Augustine       llvm::MDNode *domain = aliasScopeDomainMetadataMapping.lookup(domainOp);
933d25e91d7STyler Augustine       assert(domain && "Scope's domain should already be valid");
934d25e91d7STyler Augustine       llvm::SmallVector<llvm::Metadata *, 3> operands;
935d25e91d7STyler Augustine       operands.push_back({}); // Placeholder for self-reference
936d25e91d7STyler Augustine       operands.push_back(domain);
937cfb72fd3SJacques Pienaar       if (Optional<StringRef> description = op.getDescription())
938d25e91d7STyler Augustine         operands.push_back(llvm::MDString::get(ctx, description.getValue()));
939d25e91d7STyler Augustine       llvm::MDNode *scope = llvm::MDNode::get(ctx, operands);
940d25e91d7STyler Augustine       scope->replaceOperandWith(0, scope); // Self-reference for uniqueness
941d25e91d7STyler Augustine       aliasScopeMetadataMapping.insert({op, scope});
942d25e91d7STyler Augustine     });
943d25e91d7STyler Augustine   });
944d25e91d7STyler Augustine   return success();
945d25e91d7STyler Augustine }
946d25e91d7STyler Augustine 
947d25e91d7STyler Augustine llvm::MDNode *
948d25e91d7STyler Augustine ModuleTranslation::getAliasScope(Operation &opInst,
949d25e91d7STyler Augustine                                  SymbolRefAttr aliasScopeRef) const {
95041d4aa7dSChris Lattner   StringAttr metadataName = aliasScopeRef.getRootReference();
95141d4aa7dSChris Lattner   StringAttr scopeName = aliasScopeRef.getLeafReference();
952d25e91d7STyler Augustine   auto metadataOp = SymbolTable::lookupNearestSymbolFrom<LLVM::MetadataOp>(
953d25e91d7STyler Augustine       opInst.getParentOp(), metadataName);
954d25e91d7STyler Augustine   Operation *aliasScopeOp =
955d25e91d7STyler Augustine       SymbolTable::lookupNearestSymbolFrom(metadataOp, scopeName);
956d25e91d7STyler Augustine   return aliasScopeMetadataMapping.lookup(aliasScopeOp);
957d25e91d7STyler Augustine }
958d25e91d7STyler Augustine 
959d25e91d7STyler Augustine void ModuleTranslation::setAliasScopeMetadata(Operation *op,
960d25e91d7STyler Augustine                                               llvm::Instruction *inst) {
961d25e91d7STyler Augustine   auto populateScopeMetadata = [this, op, inst](StringRef attrName,
962d25e91d7STyler Augustine                                                 StringRef llvmMetadataName) {
963d25e91d7STyler Augustine     auto scopes = op->getAttrOfType<ArrayAttr>(attrName);
964d25e91d7STyler Augustine     if (!scopes || scopes.empty())
965d25e91d7STyler Augustine       return;
966d25e91d7STyler Augustine     llvm::Module *module = inst->getModule();
967d25e91d7STyler Augustine     SmallVector<llvm::Metadata *> scopeMDs;
968d25e91d7STyler Augustine     for (SymbolRefAttr scopeRef : scopes.getAsRange<SymbolRefAttr>())
969d25e91d7STyler Augustine       scopeMDs.push_back(getAliasScope(*op, scopeRef));
970bdaf0382SAlex Zinenko     llvm::MDNode *unionMD = llvm::MDNode::get(module->getContext(), scopeMDs);
971d25e91d7STyler Augustine     inst->setMetadata(module->getMDKindID(llvmMetadataName), unionMD);
972d25e91d7STyler Augustine   };
973d25e91d7STyler Augustine 
974d25e91d7STyler Augustine   populateScopeMetadata(LLVMDialect::getAliasScopesAttrName(), "alias.scope");
975d25e91d7STyler Augustine   populateScopeMetadata(LLVMDialect::getNoAliasScopesAttrName(), "noalias");
976d25e91d7STyler Augustine }
977d25e91d7STyler Augustine 
978c69c9e0fSAlex Zinenko llvm::Type *ModuleTranslation::convertType(Type type) {
979b2ab375dSAlex Zinenko   return typeTranslator.translateType(type);
980aec38c61SAlex Zinenko }
981aec38c61SAlex Zinenko 
9828647e4c3SAlex Zinenko /// A helper to look up remapped operands in the value remapping table.
9838647e4c3SAlex Zinenko SmallVector<llvm::Value *> ModuleTranslation::lookupValues(ValueRange values) {
9848647e4c3SAlex Zinenko   SmallVector<llvm::Value *> remapped;
985efadb6b8SAlex Zinenko   remapped.reserve(values.size());
9860881a4f1SAlex Zinenko   for (Value v : values)
9870881a4f1SAlex Zinenko     remapped.push_back(lookupValue(v));
988efadb6b8SAlex Zinenko   return remapped;
989efadb6b8SAlex Zinenko }
990efadb6b8SAlex Zinenko 
99166900b3eSAlex Zinenko const llvm::DILocation *
99266900b3eSAlex Zinenko ModuleTranslation::translateLoc(Location loc, llvm::DILocalScope *scope) {
99366900b3eSAlex Zinenko   return debugTranslation->translateLoc(loc, scope);
99466900b3eSAlex Zinenko }
99566900b3eSAlex Zinenko 
996176379e0SAlex Zinenko llvm::NamedMDNode *
997176379e0SAlex Zinenko ModuleTranslation::getOrInsertNamedModuleMetadata(StringRef name) {
998176379e0SAlex Zinenko   return llvmModule->getOrInsertNamedMetadata(name);
999176379e0SAlex Zinenko }
1000176379e0SAlex Zinenko 
100172d013ddSAlex Zinenko void ModuleTranslation::StackFrame::anchor() {}
100272d013ddSAlex Zinenko 
1003ce8f10d6SAlex Zinenko static std::unique_ptr<llvm::Module>
1004ce8f10d6SAlex Zinenko prepareLLVMModule(Operation *m, llvm::LLVMContext &llvmContext,
1005ce8f10d6SAlex Zinenko                   StringRef name) {
1006f9dc2b70SMehdi Amini   m->getContext()->getOrLoadDialect<LLVM::LLVMDialect>();
1007db1c197bSAlex Zinenko   auto llvmModule = std::make_unique<llvm::Module>(name, llvmContext);
1008168213f9SAlex Zinenko   if (auto dataLayoutAttr =
1009168213f9SAlex Zinenko           m->getAttr(LLVM::LLVMDialect::getDataLayoutAttrName()))
1010168213f9SAlex Zinenko     llvmModule->setDataLayout(dataLayoutAttr.cast<StringAttr>().getValue());
10115dd5a083SNicolas Vasilache   if (auto targetTripleAttr =
10125dd5a083SNicolas Vasilache           m->getAttr(LLVM::LLVMDialect::getTargetTripleAttrName()))
10135dd5a083SNicolas Vasilache     llvmModule->setTargetTriple(targetTripleAttr.cast<StringAttr>().getValue());
10145d7231d8SStephan Herhut 
10155d7231d8SStephan Herhut   // Inject declarations for `malloc` and `free` functions that can be used in
10165d7231d8SStephan Herhut   // memref allocation/deallocation coming from standard ops lowering.
1017db1c197bSAlex Zinenko   llvm::IRBuilder<> builder(llvmContext);
10185d7231d8SStephan Herhut   llvmModule->getOrInsertFunction("malloc", builder.getInt8PtrTy(),
10195d7231d8SStephan Herhut                                   builder.getInt64Ty());
10205d7231d8SStephan Herhut   llvmModule->getOrInsertFunction("free", builder.getVoidTy(),
10215d7231d8SStephan Herhut                                   builder.getInt8PtrTy());
10225d7231d8SStephan Herhut 
10235d7231d8SStephan Herhut   return llvmModule;
10245d7231d8SStephan Herhut }
1025ce8f10d6SAlex Zinenko 
1026ce8f10d6SAlex Zinenko std::unique_ptr<llvm::Module>
1027ce8f10d6SAlex Zinenko mlir::translateModuleToLLVMIR(Operation *module, llvm::LLVMContext &llvmContext,
1028ce8f10d6SAlex Zinenko                               StringRef name) {
1029ce8f10d6SAlex Zinenko   if (!satisfiesLLVMModule(module))
1030ce8f10d6SAlex Zinenko     return nullptr;
1031ce8f10d6SAlex Zinenko   std::unique_ptr<llvm::Module> llvmModule =
1032ce8f10d6SAlex Zinenko       prepareLLVMModule(module, llvmContext, name);
1033ce8f10d6SAlex Zinenko 
1034ce8f10d6SAlex Zinenko   LLVM::ensureDistinctSuccessors(module);
1035ce8f10d6SAlex Zinenko 
1036ce8f10d6SAlex Zinenko   ModuleTranslation translator(module, std::move(llvmModule));
1037ce8f10d6SAlex Zinenko   if (failed(translator.convertFunctionSignatures()))
1038ce8f10d6SAlex Zinenko     return nullptr;
1039ce8f10d6SAlex Zinenko   if (failed(translator.convertGlobals()))
1040ce8f10d6SAlex Zinenko     return nullptr;
10414a2930f4SArpith C. Jacob   if (failed(translator.createAccessGroupMetadata()))
10424a2930f4SArpith C. Jacob     return nullptr;
1043d25e91d7STyler Augustine   if (failed(translator.createAliasScopeMetadata()))
1044d25e91d7STyler Augustine     return nullptr;
1045ce8f10d6SAlex Zinenko   if (failed(translator.convertFunctions()))
1046ce8f10d6SAlex Zinenko     return nullptr;
10478647e4c3SAlex Zinenko 
10488647e4c3SAlex Zinenko   // Convert other top-level operations if possible.
10498647e4c3SAlex Zinenko   llvm::IRBuilder<> llvmBuilder(llvmContext);
10508647e4c3SAlex Zinenko   for (Operation &o : getModuleBody(module).getOperations()) {
105157b9b296SUday Bondhugula     if (!isa<LLVM::LLVMFuncOp, LLVM::GlobalOp, LLVM::GlobalCtorsOp,
105257b9b296SUday Bondhugula              LLVM::GlobalDtorsOp, LLVM::MetadataOp>(&o) &&
10538647e4c3SAlex Zinenko         !o.hasTrait<OpTrait::IsTerminator>() &&
10548647e4c3SAlex Zinenko         failed(translator.convertOperation(o, llvmBuilder))) {
10558647e4c3SAlex Zinenko       return nullptr;
10568647e4c3SAlex Zinenko     }
10578647e4c3SAlex Zinenko   }
10588647e4c3SAlex Zinenko 
1059ce8f10d6SAlex Zinenko   if (llvm::verifyModule(*translator.llvmModule, &llvm::errs()))
1060ce8f10d6SAlex Zinenko     return nullptr;
1061ce8f10d6SAlex Zinenko 
1062ce8f10d6SAlex Zinenko   return std::move(translator.llvmModule);
1063ce8f10d6SAlex Zinenko }
1064