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"
17ea998709SAlex Zinenko #include "mlir/Dialect/DLTI/DLTI.h"
18ba0fa925SRiver Riddle #include "mlir/Dialect/LLVMIR/LLVMDialect.h"
19ce8f10d6SAlex Zinenko #include "mlir/Dialect/LLVMIR/Transforms/LegalizeForExport.h"
2092a295ebSKiran Chandramohan #include "mlir/Dialect/OpenMP/OpenMPDialect.h"
215d7231d8SStephan Herhut #include "mlir/IR/Attributes.h"
2265fcddffSRiver Riddle #include "mlir/IR/BuiltinOps.h"
2309f7a55fSRiver Riddle #include "mlir/IR/BuiltinTypes.h"
24d4568ed7SGeorge Mitenkov #include "mlir/IR/RegionGraphTraits.h"
255d7231d8SStephan Herhut #include "mlir/Support/LLVM.h"
26b77bac05SAlex Zinenko #include "mlir/Target/LLVMIR/LLVMTranslationInterface.h"
27929189a4SWilliam S. Moses #include "mlir/Target/LLVMIR/TypeToLLVM.h"
28ebf190fcSRiver Riddle #include "llvm/ADT/TypeSwitch.h"
295d7231d8SStephan Herhut 
30d4568ed7SGeorge Mitenkov #include "llvm/ADT/PostOrderIterator.h"
315d7231d8SStephan Herhut #include "llvm/ADT/SetVector.h"
3292a295ebSKiran Chandramohan #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
335d7231d8SStephan Herhut #include "llvm/IR/BasicBlock.h"
34d9067dcaSKiran Chandramohan #include "llvm/IR/CFG.h"
355d7231d8SStephan Herhut #include "llvm/IR/Constants.h"
365d7231d8SStephan Herhut #include "llvm/IR/DerivedTypes.h"
375d7231d8SStephan Herhut #include "llvm/IR/IRBuilder.h"
38047400edSNicolas Vasilache #include "llvm/IR/InlineAsm.h"
39875eb523SNavdeep Kumar #include "llvm/IR/IntrinsicsNVPTX.h"
405d7231d8SStephan Herhut #include "llvm/IR/LLVMContext.h"
4199d03f03SGeorge Mitenkov #include "llvm/IR/MDBuilder.h"
425d7231d8SStephan Herhut #include "llvm/IR/Module.h"
43ce8f10d6SAlex Zinenko #include "llvm/IR/Verifier.h"
44d9067dcaSKiran Chandramohan #include "llvm/Transforms/Utils/BasicBlockUtils.h"
455d7231d8SStephan Herhut #include "llvm/Transforms/Utils/Cloning.h"
4657b9b296SUday Bondhugula #include "llvm/Transforms/Utils/ModuleUtils.h"
475d7231d8SStephan Herhut 
482666b973SRiver Riddle using namespace mlir;
492666b973SRiver Riddle using namespace mlir::LLVM;
50c33d6970SRiver Riddle using namespace mlir::LLVM::detail;
515d7231d8SStephan Herhut 
52eb67bd78SAlex Zinenko #include "mlir/Dialect/LLVMIR/LLVMConversionEnumsToLLVM.inc"
53eb67bd78SAlex Zinenko 
54ea998709SAlex Zinenko /// Translates the given data layout spec attribute to the LLVM IR data layout.
55ea998709SAlex Zinenko /// Only integer, float and endianness entries are currently supported.
56ea998709SAlex Zinenko FailureOr<llvm::DataLayout>
translateDataLayout(DataLayoutSpecInterface attribute,const DataLayout & dataLayout,Optional<Location> loc=llvm::None)57ea998709SAlex Zinenko translateDataLayout(DataLayoutSpecInterface attribute,
58ea998709SAlex Zinenko                     const DataLayout &dataLayout,
59ea998709SAlex Zinenko                     Optional<Location> loc = llvm::None) {
60ea998709SAlex Zinenko   if (!loc)
61ea998709SAlex Zinenko     loc = UnknownLoc::get(attribute.getContext());
62ea998709SAlex Zinenko 
63ea998709SAlex Zinenko   // Translate the endianness attribute.
64ea998709SAlex Zinenko   std::string llvmDataLayout;
65ea998709SAlex Zinenko   llvm::raw_string_ostream layoutStream(llvmDataLayout);
66ea998709SAlex Zinenko   for (DataLayoutEntryInterface entry : attribute.getEntries()) {
67ea998709SAlex Zinenko     auto key = entry.getKey().dyn_cast<StringAttr>();
68ea998709SAlex Zinenko     if (!key)
69ea998709SAlex Zinenko       continue;
70ea998709SAlex Zinenko     if (key.getValue() == DLTIDialect::kDataLayoutEndiannessKey) {
71ea998709SAlex Zinenko       auto value = entry.getValue().cast<StringAttr>();
72ea998709SAlex Zinenko       bool isLittleEndian =
73ea998709SAlex Zinenko           value.getValue() == DLTIDialect::kDataLayoutEndiannessLittle;
74ea998709SAlex Zinenko       layoutStream << (isLittleEndian ? "e" : "E");
75ea998709SAlex Zinenko       layoutStream.flush();
76ea998709SAlex Zinenko       continue;
77ea998709SAlex Zinenko     }
78ea998709SAlex Zinenko     emitError(*loc) << "unsupported data layout key " << key;
79ea998709SAlex Zinenko     return failure();
80ea998709SAlex Zinenko   }
81ea998709SAlex Zinenko 
82ea998709SAlex Zinenko   // Go through the list of entries to check which types are explicitly
83ea998709SAlex Zinenko   // specified in entries. Don't use the entries directly though but query the
84ea998709SAlex Zinenko   // data from the layout.
85ea998709SAlex Zinenko   for (DataLayoutEntryInterface entry : attribute.getEntries()) {
86ea998709SAlex Zinenko     auto type = entry.getKey().dyn_cast<Type>();
87ea998709SAlex Zinenko     if (!type)
88ea998709SAlex Zinenko       continue;
89eb27da7dSAlex Zinenko     // Data layout for the index type is irrelevant at this point.
90eb27da7dSAlex Zinenko     if (type.isa<IndexType>())
91eb27da7dSAlex Zinenko       continue;
92ea998709SAlex Zinenko     FailureOr<std::string> prefix =
93ea998709SAlex Zinenko         llvm::TypeSwitch<Type, FailureOr<std::string>>(type)
94ea998709SAlex Zinenko             .Case<IntegerType>(
95ea998709SAlex Zinenko                 [loc](IntegerType integerType) -> FailureOr<std::string> {
96ea998709SAlex Zinenko                   if (integerType.getSignedness() == IntegerType::Signless)
97ea998709SAlex Zinenko                     return std::string("i");
98ea998709SAlex Zinenko                   emitError(*loc)
99ea998709SAlex Zinenko                       << "unsupported data layout for non-signless integer "
100ea998709SAlex Zinenko                       << integerType;
101ea998709SAlex Zinenko                   return failure();
102ea998709SAlex Zinenko                 })
103ea998709SAlex Zinenko             .Case<Float16Type, Float32Type, Float64Type, Float80Type,
104ea998709SAlex Zinenko                   Float128Type>([](Type) { return std::string("f"); })
105ea998709SAlex Zinenko             .Default([loc](Type type) -> FailureOr<std::string> {
106ea998709SAlex Zinenko               emitError(*loc) << "unsupported type in data layout: " << type;
107ea998709SAlex Zinenko               return failure();
108ea998709SAlex Zinenko             });
109ea998709SAlex Zinenko     if (failed(prefix))
110ea998709SAlex Zinenko       return failure();
111ea998709SAlex Zinenko 
112ea998709SAlex Zinenko     unsigned size = dataLayout.getTypeSizeInBits(type);
113ea998709SAlex Zinenko     unsigned abi = dataLayout.getTypeABIAlignment(type) * 8u;
114ea998709SAlex Zinenko     unsigned preferred = dataLayout.getTypePreferredAlignment(type) * 8u;
115ea998709SAlex Zinenko     layoutStream << "-" << *prefix << size << ":" << abi;
116ea998709SAlex Zinenko     if (abi != preferred)
117ea998709SAlex Zinenko       layoutStream << ":" << preferred;
118ea998709SAlex Zinenko   }
119ea998709SAlex Zinenko   layoutStream.flush();
120ea998709SAlex Zinenko   StringRef layoutSpec(llvmDataLayout);
121ea998709SAlex Zinenko   if (layoutSpec.startswith("-"))
122ea998709SAlex Zinenko     layoutSpec = layoutSpec.drop_front();
123ea998709SAlex Zinenko 
124ea998709SAlex Zinenko   return llvm::DataLayout(layoutSpec);
125ea998709SAlex Zinenko }
126ea998709SAlex Zinenko 
127a922e231SAlex Zinenko /// Builds a constant of a sequential LLVM type `type`, potentially containing
128a922e231SAlex Zinenko /// other sequential types recursively, from the individual constant values
129a922e231SAlex Zinenko /// provided in `constants`. `shape` contains the number of elements in nested
130a922e231SAlex Zinenko /// sequential types. Reports errors at `loc` and returns nullptr on error.
131a4a42160SAlex Zinenko static llvm::Constant *
buildSequentialConstant(ArrayRef<llvm::Constant * > & constants,ArrayRef<int64_t> shape,llvm::Type * type,Location loc)132a4a42160SAlex Zinenko buildSequentialConstant(ArrayRef<llvm::Constant *> &constants,
133a4a42160SAlex Zinenko                         ArrayRef<int64_t> shape, llvm::Type *type,
134a4a42160SAlex Zinenko                         Location loc) {
135a4a42160SAlex Zinenko   if (shape.empty()) {
136a4a42160SAlex Zinenko     llvm::Constant *result = constants.front();
137a4a42160SAlex Zinenko     constants = constants.drop_front();
138a4a42160SAlex Zinenko     return result;
139a4a42160SAlex Zinenko   }
140a4a42160SAlex Zinenko 
14168b03aeeSEli Friedman   llvm::Type *elementType;
14268b03aeeSEli Friedman   if (auto *arrayTy = dyn_cast<llvm::ArrayType>(type)) {
14368b03aeeSEli Friedman     elementType = arrayTy->getElementType();
14468b03aeeSEli Friedman   } else if (auto *vectorTy = dyn_cast<llvm::VectorType>(type)) {
14568b03aeeSEli Friedman     elementType = vectorTy->getElementType();
14668b03aeeSEli Friedman   } else {
147a4a42160SAlex Zinenko     emitError(loc) << "expected sequential LLVM types wrapping a scalar";
148a4a42160SAlex Zinenko     return nullptr;
149a4a42160SAlex Zinenko   }
150a4a42160SAlex Zinenko 
151a4a42160SAlex Zinenko   SmallVector<llvm::Constant *, 8> nested;
152a4a42160SAlex Zinenko   nested.reserve(shape.front());
153a4a42160SAlex Zinenko   for (int64_t i = 0; i < shape.front(); ++i) {
154a4a42160SAlex Zinenko     nested.push_back(buildSequentialConstant(constants, shape.drop_front(),
155a4a42160SAlex Zinenko                                              elementType, loc));
156a4a42160SAlex Zinenko     if (!nested.back())
157a4a42160SAlex Zinenko       return nullptr;
158a4a42160SAlex Zinenko   }
159a4a42160SAlex Zinenko 
160a4a42160SAlex Zinenko   if (shape.size() == 1 && type->isVectorTy())
161a4a42160SAlex Zinenko     return llvm::ConstantVector::get(nested);
162a4a42160SAlex Zinenko   return llvm::ConstantArray::get(
163a4a42160SAlex Zinenko       llvm::ArrayType::get(elementType, shape.front()), nested);
164a4a42160SAlex Zinenko }
165a4a42160SAlex Zinenko 
166fc817b09SKazuaki Ishizaki /// Returns the first non-sequential type nested in sequential types.
getInnermostElementType(llvm::Type * type)167a4a42160SAlex Zinenko static llvm::Type *getInnermostElementType(llvm::Type *type) {
16868b03aeeSEli Friedman   do {
16968b03aeeSEli Friedman     if (auto *arrayTy = dyn_cast<llvm::ArrayType>(type)) {
17068b03aeeSEli Friedman       type = arrayTy->getElementType();
17168b03aeeSEli Friedman     } else if (auto *vectorTy = dyn_cast<llvm::VectorType>(type)) {
17268b03aeeSEli Friedman       type = vectorTy->getElementType();
17368b03aeeSEli Friedman     } else {
174a4a42160SAlex Zinenko       return type;
175a4a42160SAlex Zinenko     }
1760881a4f1SAlex Zinenko   } while (true);
17768b03aeeSEli Friedman }
178a4a42160SAlex Zinenko 
179f9be7a7aSAlex Zinenko /// Convert a dense elements attribute to an LLVM IR constant using its raw data
180f9be7a7aSAlex Zinenko /// storage if possible. This supports elements attributes of tensor or vector
181f9be7a7aSAlex Zinenko /// type and avoids constructing separate objects for individual values of the
182f9be7a7aSAlex Zinenko /// innermost dimension. Constants for other dimensions are still constructed
183f9be7a7aSAlex Zinenko /// recursively. Returns null if constructing from raw data is not supported for
184f9be7a7aSAlex Zinenko /// this type, e.g., element type is not a power-of-two-sized primitive. Reports
185f9be7a7aSAlex Zinenko /// other errors at `loc`.
186f9be7a7aSAlex Zinenko static llvm::Constant *
convertDenseElementsAttr(Location loc,DenseElementsAttr denseElementsAttr,llvm::Type * llvmType,const ModuleTranslation & moduleTranslation)187f9be7a7aSAlex Zinenko convertDenseElementsAttr(Location loc, DenseElementsAttr denseElementsAttr,
188f9be7a7aSAlex Zinenko                          llvm::Type *llvmType,
189f9be7a7aSAlex Zinenko                          const ModuleTranslation &moduleTranslation) {
190f9be7a7aSAlex Zinenko   if (!denseElementsAttr)
191f9be7a7aSAlex Zinenko     return nullptr;
192f9be7a7aSAlex Zinenko 
193f9be7a7aSAlex Zinenko   llvm::Type *innermostLLVMType = getInnermostElementType(llvmType);
194f9be7a7aSAlex Zinenko   if (!llvm::ConstantDataSequential::isElementTypeCompatible(innermostLLVMType))
195f9be7a7aSAlex Zinenko     return nullptr;
196f9be7a7aSAlex Zinenko 
197898e8096SBenjamin Kramer   ShapedType type = denseElementsAttr.getType();
198898e8096SBenjamin Kramer   if (type.getNumElements() == 0)
199898e8096SBenjamin Kramer     return nullptr;
200898e8096SBenjamin Kramer 
201f9be7a7aSAlex Zinenko   // Compute the shape of all dimensions but the innermost. Note that the
202f9be7a7aSAlex Zinenko   // innermost dimension may be that of the vector element type.
203f9be7a7aSAlex Zinenko   bool hasVectorElementType = type.getElementType().isa<VectorType>();
204f9be7a7aSAlex Zinenko   unsigned numAggregates =
205f9be7a7aSAlex Zinenko       denseElementsAttr.getNumElements() /
206f9be7a7aSAlex Zinenko       (hasVectorElementType ? 1
207f9be7a7aSAlex Zinenko                             : denseElementsAttr.getType().getShape().back());
208f9be7a7aSAlex Zinenko   ArrayRef<int64_t> outerShape = type.getShape();
209f9be7a7aSAlex Zinenko   if (!hasVectorElementType)
210f9be7a7aSAlex Zinenko     outerShape = outerShape.drop_back();
211f9be7a7aSAlex Zinenko 
212f9be7a7aSAlex Zinenko   // Handle the case of vector splat, LLVM has special support for it.
213f9be7a7aSAlex Zinenko   if (denseElementsAttr.isSplat() &&
214f9be7a7aSAlex Zinenko       (type.isa<VectorType>() || hasVectorElementType)) {
215f9be7a7aSAlex Zinenko     llvm::Constant *splatValue = LLVM::detail::getLLVMConstant(
216937e40a8SRiver Riddle         innermostLLVMType, denseElementsAttr.getSplatValue<Attribute>(), loc,
21727dad996SBenjamin Kramer         moduleTranslation);
218f9be7a7aSAlex Zinenko     llvm::Constant *splatVector =
219f9be7a7aSAlex Zinenko         llvm::ConstantDataVector::getSplat(0, splatValue);
220f9be7a7aSAlex Zinenko     SmallVector<llvm::Constant *> constants(numAggregates, splatVector);
221f9be7a7aSAlex Zinenko     ArrayRef<llvm::Constant *> constantsRef = constants;
222f9be7a7aSAlex Zinenko     return buildSequentialConstant(constantsRef, outerShape, llvmType, loc);
223f9be7a7aSAlex Zinenko   }
224f9be7a7aSAlex Zinenko   if (denseElementsAttr.isSplat())
225f9be7a7aSAlex Zinenko     return nullptr;
226f9be7a7aSAlex Zinenko 
227f9be7a7aSAlex Zinenko   // In case of non-splat, create a constructor for the innermost constant from
228f9be7a7aSAlex Zinenko   // a piece of raw data.
229f9be7a7aSAlex Zinenko   std::function<llvm::Constant *(StringRef)> buildCstData;
230f9be7a7aSAlex Zinenko   if (type.isa<TensorType>()) {
231f9be7a7aSAlex Zinenko     auto vectorElementType = type.getElementType().dyn_cast<VectorType>();
232f9be7a7aSAlex Zinenko     if (vectorElementType && vectorElementType.getRank() == 1) {
233f9be7a7aSAlex Zinenko       buildCstData = [&](StringRef data) {
234f9be7a7aSAlex Zinenko         return llvm::ConstantDataVector::getRaw(
235f9be7a7aSAlex Zinenko             data, vectorElementType.getShape().back(), innermostLLVMType);
236f9be7a7aSAlex Zinenko       };
237f9be7a7aSAlex Zinenko     } else if (!vectorElementType) {
238f9be7a7aSAlex Zinenko       buildCstData = [&](StringRef data) {
239f9be7a7aSAlex Zinenko         return llvm::ConstantDataArray::getRaw(data, type.getShape().back(),
240f9be7a7aSAlex Zinenko                                                innermostLLVMType);
241f9be7a7aSAlex Zinenko       };
242f9be7a7aSAlex Zinenko     }
243f9be7a7aSAlex Zinenko   } else if (type.isa<VectorType>()) {
244f9be7a7aSAlex Zinenko     buildCstData = [&](StringRef data) {
245f9be7a7aSAlex Zinenko       return llvm::ConstantDataVector::getRaw(data, type.getShape().back(),
246f9be7a7aSAlex Zinenko                                               innermostLLVMType);
247f9be7a7aSAlex Zinenko     };
248f9be7a7aSAlex Zinenko   }
249f9be7a7aSAlex Zinenko   if (!buildCstData)
250f9be7a7aSAlex Zinenko     return nullptr;
251f9be7a7aSAlex Zinenko 
252f9be7a7aSAlex Zinenko   // Create innermost constants and defer to the default constant creation
253f9be7a7aSAlex Zinenko   // mechanism for other dimensions.
254f9be7a7aSAlex Zinenko   SmallVector<llvm::Constant *> constants;
255f9be7a7aSAlex Zinenko   unsigned aggregateSize = denseElementsAttr.getType().getShape().back() *
256f9be7a7aSAlex Zinenko                            (innermostLLVMType->getScalarSizeInBits() / 8);
257f9be7a7aSAlex Zinenko   constants.reserve(numAggregates);
258f9be7a7aSAlex Zinenko   for (unsigned i = 0; i < numAggregates; ++i) {
259f9be7a7aSAlex Zinenko     StringRef data(denseElementsAttr.getRawData().data() + i * aggregateSize,
260f9be7a7aSAlex Zinenko                    aggregateSize);
261f9be7a7aSAlex Zinenko     constants.push_back(buildCstData(data));
262f9be7a7aSAlex Zinenko   }
263f9be7a7aSAlex Zinenko 
264f9be7a7aSAlex Zinenko   ArrayRef<llvm::Constant *> constantsRef = constants;
265f9be7a7aSAlex Zinenko   return buildSequentialConstant(constantsRef, outerShape, llvmType, loc);
266f9be7a7aSAlex Zinenko }
267f9be7a7aSAlex Zinenko 
2682666b973SRiver Riddle /// Create an LLVM IR constant of `llvmType` from the MLIR attribute `attr`.
2692666b973SRiver Riddle /// This currently supports integer, floating point, splat and dense element
2705ef21506SAdrian Kuegel /// attributes and combinations thereof. Also, an array attribute with two
2715ef21506SAdrian Kuegel /// elements is supported to represent a complex constant.  In case of error,
2725ef21506SAdrian Kuegel /// report it to `loc` and return nullptr.
getLLVMConstant(llvm::Type * llvmType,Attribute attr,Location loc,const ModuleTranslation & moduleTranslation)273176379e0SAlex Zinenko llvm::Constant *mlir::LLVM::detail::getLLVMConstant(
274176379e0SAlex Zinenko     llvm::Type *llvmType, Attribute attr, Location loc,
27527dad996SBenjamin Kramer     const ModuleTranslation &moduleTranslation) {
27633a3a91bSChristian Sigg   if (!attr)
27733a3a91bSChristian Sigg     return llvm::UndefValue::get(llvmType);
2785ef21506SAdrian Kuegel   if (auto *structType = dyn_cast<::llvm::StructType>(llvmType)) {
27927dad996SBenjamin Kramer     auto arrayAttr = attr.dyn_cast<ArrayAttr>();
28027dad996SBenjamin Kramer     if (!arrayAttr || arrayAttr.size() != 2) {
28127dad996SBenjamin Kramer       emitError(loc, "expected struct type to be a complex number");
282a4a42160SAlex Zinenko       return nullptr;
283a4a42160SAlex Zinenko     }
2845ef21506SAdrian Kuegel     llvm::Type *elementType = structType->getElementType(0);
28527dad996SBenjamin Kramer     llvm::Constant *real =
28627dad996SBenjamin Kramer         getLLVMConstant(elementType, arrayAttr[0], loc, moduleTranslation);
2875ef21506SAdrian Kuegel     if (!real)
2885ef21506SAdrian Kuegel       return nullptr;
28927dad996SBenjamin Kramer     llvm::Constant *imag =
29027dad996SBenjamin Kramer         getLLVMConstant(elementType, arrayAttr[1], loc, moduleTranslation);
2915ef21506SAdrian Kuegel     if (!imag)
2925ef21506SAdrian Kuegel       return nullptr;
2935ef21506SAdrian Kuegel     return llvm::ConstantStruct::get(structType, {real, imag});
2945ef21506SAdrian Kuegel   }
295ac9d742bSStephan Herhut   // For integer types, we allow a mismatch in sizes as the index type in
296ac9d742bSStephan Herhut   // MLIR might have a different size than the index type in the LLVM module.
2975d7231d8SStephan Herhut   if (auto intAttr = attr.dyn_cast<IntegerAttr>())
298ac9d742bSStephan Herhut     return llvm::ConstantInt::get(
299ac9d742bSStephan Herhut         llvmType,
300ac9d742bSStephan Herhut         intAttr.getValue().sextOrTrunc(llvmType->getIntegerBitWidth()));
3015ef21506SAdrian Kuegel   if (auto floatAttr = attr.dyn_cast<FloatAttr>()) {
3025ef21506SAdrian Kuegel     if (llvmType !=
3035ef21506SAdrian Kuegel         llvm::Type::getFloatingPointTy(llvmType->getContext(),
3045ef21506SAdrian Kuegel                                        floatAttr.getValue().getSemantics())) {
3055ef21506SAdrian Kuegel       emitError(loc, "FloatAttr does not match expected type of the constant");
3065ef21506SAdrian Kuegel       return nullptr;
3075ef21506SAdrian Kuegel     }
3085d7231d8SStephan Herhut     return llvm::ConstantFP::get(llvmType, floatAttr.getValue());
3095ef21506SAdrian Kuegel   }
3109b9c647cSRiver Riddle   if (auto funcAttr = attr.dyn_cast<FlatSymbolRefAttr>())
311176379e0SAlex Zinenko     return llvm::ConstantExpr::getBitCast(
312176379e0SAlex Zinenko         moduleTranslation.lookupFunction(funcAttr.getValue()), llvmType);
3135d7231d8SStephan Herhut   if (auto splatAttr = attr.dyn_cast<SplatElementsAttr>()) {
31468b03aeeSEli Friedman     llvm::Type *elementType;
31568b03aeeSEli Friedman     uint64_t numElements;
3167c564586SJavier Setoain     bool isScalable = false;
31768b03aeeSEli Friedman     if (auto *arrayTy = dyn_cast<llvm::ArrayType>(llvmType)) {
31868b03aeeSEli Friedman       elementType = arrayTy->getElementType();
31968b03aeeSEli Friedman       numElements = arrayTy->getNumElements();
32002b6fb21SMehdi Amini     } else if (auto *fVectorTy = dyn_cast<llvm::FixedVectorType>(llvmType)) {
321a4830d14SJavier Setoain       elementType = fVectorTy->getElementType();
322a4830d14SJavier Setoain       numElements = fVectorTy->getNumElements();
32302b6fb21SMehdi Amini     } else if (auto *sVectorTy = dyn_cast<llvm::ScalableVectorType>(llvmType)) {
324a4830d14SJavier Setoain       elementType = sVectorTy->getElementType();
325a4830d14SJavier Setoain       numElements = sVectorTy->getMinNumElements();
3267c564586SJavier Setoain       isScalable = true;
32768b03aeeSEli Friedman     } else {
328a4830d14SJavier Setoain       llvm_unreachable("unrecognized constant vector type");
32968b03aeeSEli Friedman     }
330d6ea8ff0SAlex Zinenko     // Splat value is a scalar. Extract it only if the element type is not
331d6ea8ff0SAlex Zinenko     // another sequence type. The recursion terminates because each step removes
332d6ea8ff0SAlex Zinenko     // one outer sequential type.
33368b03aeeSEli Friedman     bool elementTypeSequential =
334d891d738SRahul Joshi         isa<llvm::ArrayType, llvm::VectorType>(elementType);
335d6ea8ff0SAlex Zinenko     llvm::Constant *child = getLLVMConstant(
336d6ea8ff0SAlex Zinenko         elementType,
337937e40a8SRiver Riddle         elementTypeSequential ? splatAttr
338937e40a8SRiver Riddle                               : splatAttr.getSplatValue<Attribute>(),
33927dad996SBenjamin Kramer         loc, moduleTranslation);
340a4a42160SAlex Zinenko     if (!child)
341a4a42160SAlex Zinenko       return nullptr;
3422f13df13SMLIR Team     if (llvmType->isVectorTy())
343396a42d9SRiver Riddle       return llvm::ConstantVector::getSplat(
3447c564586SJavier Setoain           llvm::ElementCount::get(numElements, /*Scalable=*/isScalable), child);
3452f13df13SMLIR Team     if (llvmType->isArrayTy()) {
346ac9d742bSStephan Herhut       auto *arrayType = llvm::ArrayType::get(elementType, numElements);
3472f13df13SMLIR Team       SmallVector<llvm::Constant *, 8> constants(numElements, child);
3482f13df13SMLIR Team       return llvm::ConstantArray::get(arrayType, constants);
3492f13df13SMLIR Team     }
3505d7231d8SStephan Herhut   }
351a4a42160SAlex Zinenko 
352f9be7a7aSAlex Zinenko   // Try using raw elements data if possible.
353f9be7a7aSAlex Zinenko   if (llvm::Constant *result =
354f9be7a7aSAlex Zinenko           convertDenseElementsAttr(loc, attr.dyn_cast<DenseElementsAttr>(),
355f9be7a7aSAlex Zinenko                                    llvmType, moduleTranslation)) {
356f9be7a7aSAlex Zinenko     return result;
357f9be7a7aSAlex Zinenko   }
358f9be7a7aSAlex Zinenko 
359f9be7a7aSAlex Zinenko   // Fall back to element-by-element construction otherwise.
360d906f84bSRiver Riddle   if (auto elementsAttr = attr.dyn_cast<ElementsAttr>()) {
361a4a42160SAlex Zinenko     assert(elementsAttr.getType().hasStaticShape());
362a4a42160SAlex Zinenko     assert(!elementsAttr.getType().getShape().empty() &&
363a4a42160SAlex Zinenko            "unexpected empty elements attribute shape");
364a4a42160SAlex Zinenko 
3655d7231d8SStephan Herhut     SmallVector<llvm::Constant *, 8> constants;
366a4a42160SAlex Zinenko     constants.reserve(elementsAttr.getNumElements());
367a4a42160SAlex Zinenko     llvm::Type *innermostType = getInnermostElementType(llvmType);
368d906f84bSRiver Riddle     for (auto n : elementsAttr.getValues<Attribute>()) {
369176379e0SAlex Zinenko       constants.push_back(
37027dad996SBenjamin Kramer           getLLVMConstant(innermostType, n, loc, moduleTranslation));
3715d7231d8SStephan Herhut       if (!constants.back())
3725d7231d8SStephan Herhut         return nullptr;
3735d7231d8SStephan Herhut     }
374a4a42160SAlex Zinenko     ArrayRef<llvm::Constant *> constantsRef = constants;
375a4a42160SAlex Zinenko     llvm::Constant *result = buildSequentialConstant(
376a4a42160SAlex Zinenko         constantsRef, elementsAttr.getType().getShape(), llvmType, loc);
377a4a42160SAlex Zinenko     assert(constantsRef.empty() && "did not consume all elemental constants");
378a4a42160SAlex Zinenko     return result;
3792f13df13SMLIR Team   }
380a4a42160SAlex Zinenko 
381cb348dffSStephan Herhut   if (auto stringAttr = attr.dyn_cast<StringAttr>()) {
382cb348dffSStephan Herhut     return llvm::ConstantDataArray::get(
383176379e0SAlex Zinenko         moduleTranslation.getLLVMContext(),
384176379e0SAlex Zinenko         ArrayRef<char>{stringAttr.getValue().data(),
385cb348dffSStephan Herhut                        stringAttr.getValue().size()});
386cb348dffSStephan Herhut   }
387a4c3a645SRiver Riddle   emitError(loc, "unsupported constant value");
3885d7231d8SStephan Herhut   return nullptr;
3895d7231d8SStephan Herhut }
3905d7231d8SStephan Herhut 
ModuleTranslation(Operation * module,std::unique_ptr<llvm::Module> llvmModule)391c33d6970SRiver Riddle ModuleTranslation::ModuleTranslation(Operation *module,
392c33d6970SRiver Riddle                                      std::unique_ptr<llvm::Module> llvmModule)
393c33d6970SRiver Riddle     : mlirModule(module), llvmModule(std::move(llvmModule)),
394c33d6970SRiver Riddle       debugTranslation(
39592a295ebSKiran Chandramohan           std::make_unique<DebugTranslation>(module, *this->llvmModule)),
396b77bac05SAlex Zinenko       typeTranslator(this->llvmModule->getContext()),
397b77bac05SAlex Zinenko       iface(module->getContext()) {
398c33d6970SRiver Riddle   assert(satisfiesLLVMModule(mlirModule) &&
399c33d6970SRiver Riddle          "mlirModule should honor LLVM's module semantics.");
400c33d6970SRiver Riddle }
~ModuleTranslation()401d9067dcaSKiran Chandramohan ModuleTranslation::~ModuleTranslation() {
402d9067dcaSKiran Chandramohan   if (ompBuilder)
403d9067dcaSKiran Chandramohan     ompBuilder->finalize();
404d9067dcaSKiran Chandramohan }
405d9067dcaSKiran Chandramohan 
forgetMapping(Region & region)4068647e4c3SAlex Zinenko void ModuleTranslation::forgetMapping(Region &region) {
4078647e4c3SAlex Zinenko   SmallVector<Region *> toProcess;
4088647e4c3SAlex Zinenko   toProcess.push_back(&region);
4098647e4c3SAlex Zinenko   while (!toProcess.empty()) {
4108647e4c3SAlex Zinenko     Region *current = toProcess.pop_back_val();
4118647e4c3SAlex Zinenko     for (Block &block : *current) {
4128647e4c3SAlex Zinenko       blockMapping.erase(&block);
4138647e4c3SAlex Zinenko       for (Value arg : block.getArguments())
4148647e4c3SAlex Zinenko         valueMapping.erase(arg);
4158647e4c3SAlex Zinenko       for (Operation &op : block) {
4168647e4c3SAlex Zinenko         for (Value value : op.getResults())
4178647e4c3SAlex Zinenko           valueMapping.erase(value);
4188647e4c3SAlex Zinenko         if (op.hasSuccessors())
4198647e4c3SAlex Zinenko           branchMapping.erase(&op);
4208647e4c3SAlex Zinenko         if (isa<LLVM::GlobalOp>(op))
4218647e4c3SAlex Zinenko           globalsMapping.erase(&op);
4228647e4c3SAlex Zinenko         accessGroupMetadataMapping.erase(&op);
4238647e4c3SAlex Zinenko         llvm::append_range(
4248647e4c3SAlex Zinenko             toProcess,
4258647e4c3SAlex Zinenko             llvm::map_range(op.getRegions(), [](Region &r) { return &r; }));
4268647e4c3SAlex Zinenko       }
4278647e4c3SAlex Zinenko     }
4288647e4c3SAlex Zinenko   }
4298647e4c3SAlex Zinenko }
4308647e4c3SAlex Zinenko 
431d9067dcaSKiran Chandramohan /// Get the SSA value passed to the current block from the terminator operation
432d9067dcaSKiran Chandramohan /// of its predecessor.
getPHISourceValue(Block * current,Block * pred,unsigned numArguments,unsigned index)433d9067dcaSKiran Chandramohan static Value getPHISourceValue(Block *current, Block *pred,
434d9067dcaSKiran Chandramohan                                unsigned numArguments, unsigned index) {
435d9067dcaSKiran Chandramohan   Operation &terminator = *pred->getTerminator();
436d9067dcaSKiran Chandramohan   if (isa<LLVM::BrOp>(terminator))
437d9067dcaSKiran Chandramohan     return terminator.getOperand(index);
438d9067dcaSKiran Chandramohan 
439bea16e72SAlex Zinenko #ifndef NDEBUG
440bea16e72SAlex Zinenko   llvm::SmallPtrSet<Block *, 4> seenSuccessors;
441bea16e72SAlex Zinenko   for (unsigned i = 0, e = terminator.getNumSuccessors(); i < e; ++i) {
442bea16e72SAlex Zinenko     Block *successor = terminator.getSuccessor(i);
443bea16e72SAlex Zinenko     auto branch = cast<BranchOpInterface>(terminator);
4440c789db5SMarkus Böck     SuccessorOperands successorOperands = branch.getSuccessorOperands(i);
445bea16e72SAlex Zinenko     assert(
4460c789db5SMarkus Böck         (!seenSuccessors.contains(successor) || successorOperands.empty()) &&
44714f24155SBrian Gesiak         "successors with arguments in LLVM branches must be different blocks");
448bea16e72SAlex Zinenko     seenSuccessors.insert(successor);
449bea16e72SAlex Zinenko   }
450bea16e72SAlex Zinenko #endif
451d9067dcaSKiran Chandramohan 
45214f24155SBrian Gesiak   // For instructions that branch based on a condition value, we need to take
45314f24155SBrian Gesiak   // the operands for the branch that was taken.
45414f24155SBrian Gesiak   if (auto condBranchOp = dyn_cast<LLVM::CondBrOp>(terminator)) {
45514f24155SBrian Gesiak     // For conditional branches, we take the operands from either the "true" or
45614f24155SBrian Gesiak     // the "false" branch.
457d9067dcaSKiran Chandramohan     return condBranchOp.getSuccessor(0) == current
458cfb72fd3SJacques Pienaar                ? condBranchOp.getTrueDestOperands()[index]
459cfb72fd3SJacques Pienaar                : condBranchOp.getFalseDestOperands()[index];
4600881a4f1SAlex Zinenko   }
4610881a4f1SAlex Zinenko 
4620881a4f1SAlex Zinenko   if (auto switchOp = dyn_cast<LLVM::SwitchOp>(terminator)) {
46314f24155SBrian Gesiak     // For switches, we take the operands from either the default case, or from
46414f24155SBrian Gesiak     // the case branch that was taken.
465dde96363SJacques Pienaar     if (switchOp.getDefaultDestination() == current)
466dde96363SJacques Pienaar       return switchOp.getDefaultOperands()[index];
467e4853be2SMehdi Amini     for (const auto &i : llvm::enumerate(switchOp.getCaseDestinations()))
46814f24155SBrian Gesiak       if (i.value() == current)
46914f24155SBrian Gesiak         return switchOp.getCaseOperands(i.index())[index];
47014f24155SBrian Gesiak   }
47114f24155SBrian Gesiak 
47256097205SMarkus Böck   if (auto invokeOp = dyn_cast<LLVM::InvokeOp>(terminator)) {
47356097205SMarkus Böck     return invokeOp.getNormalDest() == current
47456097205SMarkus Böck                ? invokeOp.getNormalDestOperands()[index]
47556097205SMarkus Böck                : invokeOp.getUnwindDestOperands()[index];
47656097205SMarkus Böck   }
47756097205SMarkus Böck 
47856097205SMarkus Böck   llvm_unreachable(
47956097205SMarkus Böck       "only branch, switch or invoke operations can be terminators "
48056097205SMarkus Böck       "of a block that has successors");
481d9067dcaSKiran Chandramohan }
482d9067dcaSKiran Chandramohan 
483d9067dcaSKiran Chandramohan /// Connect the PHI nodes to the results of preceding blocks.
connectPHINodes(Region & region,const ModuleTranslation & state)48466900b3eSAlex Zinenko void mlir::LLVM::detail::connectPHINodes(Region &region,
48566900b3eSAlex Zinenko                                          const ModuleTranslation &state) {
486d9067dcaSKiran Chandramohan   // Skip the first block, it cannot be branched to and its arguments correspond
487d9067dcaSKiran Chandramohan   // to the arguments of the LLVM function.
4885605a1eeSKazu Hirata   for (Block &bb : llvm::drop_begin(region)) {
4895605a1eeSKazu Hirata     llvm::BasicBlock *llvmBB = state.lookupBlock(&bb);
490d9067dcaSKiran Chandramohan     auto phis = llvmBB->phis();
4915605a1eeSKazu Hirata     auto numArguments = bb.getNumArguments();
492d9067dcaSKiran Chandramohan     assert(numArguments == std::distance(phis.begin(), phis.end()));
493d9067dcaSKiran Chandramohan     for (auto &numberedPhiNode : llvm::enumerate(phis)) {
494d9067dcaSKiran Chandramohan       auto &phiNode = numberedPhiNode.value();
495d9067dcaSKiran Chandramohan       unsigned index = numberedPhiNode.index();
4965605a1eeSKazu Hirata       for (auto *pred : bb.getPredecessors()) {
497db884dafSAlex Zinenko         // Find the LLVM IR block that contains the converted terminator
498db884dafSAlex Zinenko         // instruction and use it in the PHI node. Note that this block is not
4990881a4f1SAlex Zinenko         // necessarily the same as state.lookupBlock(pred), some operations
500db884dafSAlex Zinenko         // (in particular, OpenMP operations using OpenMPIRBuilder) may have
501db884dafSAlex Zinenko         // split the blocks.
502db884dafSAlex Zinenko         llvm::Instruction *terminator =
5030881a4f1SAlex Zinenko             state.lookupBranch(pred->getTerminator());
504db884dafSAlex Zinenko         assert(terminator && "missing the mapping for a terminator");
5055605a1eeSKazu Hirata         phiNode.addIncoming(state.lookupValue(getPHISourceValue(
5065605a1eeSKazu Hirata                                 &bb, pred, numArguments, index)),
507db884dafSAlex Zinenko                             terminator->getParent());
508d9067dcaSKiran Chandramohan       }
509d9067dcaSKiran Chandramohan     }
510d9067dcaSKiran Chandramohan   }
511d9067dcaSKiran Chandramohan }
512d9067dcaSKiran Chandramohan 
513d9067dcaSKiran Chandramohan /// Sort function blocks topologically.
5144efb7754SRiver Riddle SetVector<Block *>
getTopologicallySortedBlocks(Region & region)51566900b3eSAlex Zinenko mlir::LLVM::detail::getTopologicallySortedBlocks(Region &region) {
516d4568ed7SGeorge Mitenkov   // For each block that has not been visited yet (i.e. that has no
517d4568ed7SGeorge Mitenkov   // predecessors), add it to the list as well as its successors.
5184efb7754SRiver Riddle   SetVector<Block *> blocks;
51966900b3eSAlex Zinenko   for (Block &b : region) {
520d4568ed7SGeorge Mitenkov     if (blocks.count(&b) == 0) {
521d4568ed7SGeorge Mitenkov       llvm::ReversePostOrderTraversal<Block *> traversal(&b);
522d4568ed7SGeorge Mitenkov       blocks.insert(traversal.begin(), traversal.end());
523d4568ed7SGeorge Mitenkov     }
524d9067dcaSKiran Chandramohan   }
52566900b3eSAlex Zinenko   assert(blocks.size() == region.getBlocks().size() &&
52666900b3eSAlex Zinenko          "some blocks are not sorted");
527d9067dcaSKiran Chandramohan 
528d9067dcaSKiran Chandramohan   return blocks;
529d9067dcaSKiran Chandramohan }
530d9067dcaSKiran Chandramohan 
createIntrinsicCall(llvm::IRBuilderBase & builder,llvm::Intrinsic::ID intrinsic,ArrayRef<llvm::Value * > args,ArrayRef<llvm::Type * > tys)531176379e0SAlex Zinenko llvm::Value *mlir::LLVM::detail::createIntrinsicCall(
532176379e0SAlex Zinenko     llvm::IRBuilderBase &builder, llvm::Intrinsic::ID intrinsic,
533176379e0SAlex Zinenko     ArrayRef<llvm::Value *> args, ArrayRef<llvm::Type *> tys) {
534176379e0SAlex Zinenko   llvm::Module *module = builder.GetInsertBlock()->getModule();
535176379e0SAlex Zinenko   llvm::Function *fn = llvm::Intrinsic::getDeclaration(module, intrinsic, tys);
536176379e0SAlex Zinenko   return builder.CreateCall(fn, args);
537176379e0SAlex Zinenko }
538176379e0SAlex Zinenko 
5392666b973SRiver Riddle /// Given a single MLIR operation, create the corresponding LLVM IR operation
540176379e0SAlex Zinenko /// using the `builder`.
541ce8f10d6SAlex Zinenko LogicalResult
convertOperation(Operation & op,llvm::IRBuilderBase & builder)54238b106f6SMehdi Amini ModuleTranslation::convertOperation(Operation &op,
543ce8f10d6SAlex Zinenko                                     llvm::IRBuilderBase &builder) {
54438b106f6SMehdi Amini   const LLVMTranslationDialectInterface *opIface = iface.getInterfaceFor(&op);
54538b106f6SMehdi Amini   if (!opIface)
54638b106f6SMehdi Amini     return op.emitError("cannot be converted to LLVM IR: missing "
54738b106f6SMehdi Amini                         "`LLVMTranslationDialectInterface` registration for "
54838b106f6SMehdi Amini                         "dialect for op: ")
54938b106f6SMehdi Amini            << op.getName();
550176379e0SAlex Zinenko 
55138b106f6SMehdi Amini   if (failed(opIface->convertOperation(&op, builder, *this)))
55238b106f6SMehdi Amini     return op.emitError("LLVM Translation failed for operation: ")
55338b106f6SMehdi Amini            << op.getName();
55438b106f6SMehdi Amini 
55538b106f6SMehdi Amini   return convertDialectAttributes(&op);
5565d7231d8SStephan Herhut }
5575d7231d8SStephan Herhut 
5582666b973SRiver Riddle /// Convert block to LLVM IR.  Unless `ignoreArguments` is set, emit PHI nodes
5592666b973SRiver Riddle /// to define values corresponding to the MLIR block arguments.  These nodes
56010164a2eSAlex Zinenko /// are not connected to the source basic blocks, which may not exist yet.  Uses
56110164a2eSAlex Zinenko /// `builder` to construct the LLVM IR. Expects the LLVM IR basic block to have
56210164a2eSAlex Zinenko /// been created for `bb` and included in the block mapping.  Inserts new
56310164a2eSAlex Zinenko /// instructions at the end of the block and leaves `builder` in a state
56410164a2eSAlex Zinenko /// suitable for further insertion into the end of the block.
convertBlock(Block & bb,bool ignoreArguments,llvm::IRBuilderBase & builder)56510164a2eSAlex Zinenko LogicalResult ModuleTranslation::convertBlock(Block &bb, bool ignoreArguments,
566ce8f10d6SAlex Zinenko                                               llvm::IRBuilderBase &builder) {
5670881a4f1SAlex Zinenko   builder.SetInsertPoint(lookupBlock(&bb));
568c33d6970SRiver Riddle   auto *subprogram = builder.GetInsertBlock()->getParent()->getSubprogram();
5695d7231d8SStephan Herhut 
5705d7231d8SStephan Herhut   // Before traversing operations, make block arguments available through
5715d7231d8SStephan Herhut   // value remapping and PHI nodes, but do not add incoming edges for the PHI
5725d7231d8SStephan Herhut   // nodes just yet: those values may be defined by this or following blocks.
5735d7231d8SStephan Herhut   // This step is omitted if "ignoreArguments" is set.  The arguments of the
5745d7231d8SStephan Herhut   // first block have been already made available through the remapping of
5755d7231d8SStephan Herhut   // LLVM function arguments.
5765d7231d8SStephan Herhut   if (!ignoreArguments) {
5775d7231d8SStephan Herhut     auto predecessors = bb.getPredecessors();
5785d7231d8SStephan Herhut     unsigned numPredecessors =
5795d7231d8SStephan Herhut         std::distance(predecessors.begin(), predecessors.end());
58035807bc4SRiver Riddle     for (auto arg : bb.getArguments()) {
581c69c9e0fSAlex Zinenko       auto wrappedType = arg.getType();
582c69c9e0fSAlex Zinenko       if (!isCompatibleType(wrappedType))
583baa1ec22SAlex Zinenko         return emitError(bb.front().getLoc(),
584a4c3a645SRiver Riddle                          "block argument does not have an LLVM type");
585aec38c61SAlex Zinenko       llvm::Type *type = convertType(wrappedType);
5865d7231d8SStephan Herhut       llvm::PHINode *phi = builder.CreatePHI(type, numPredecessors);
5870881a4f1SAlex Zinenko       mapValue(arg, phi);
5885d7231d8SStephan Herhut     }
5895d7231d8SStephan Herhut   }
5905d7231d8SStephan Herhut 
5915d7231d8SStephan Herhut   // Traverse operations.
5925d7231d8SStephan Herhut   for (auto &op : bb) {
593c33d6970SRiver Riddle     // Set the current debug location within the builder.
594c33d6970SRiver Riddle     builder.SetCurrentDebugLocation(
595c33d6970SRiver Riddle         debugTranslation->translateLoc(op.getLoc(), subprogram));
596c33d6970SRiver Riddle 
597baa1ec22SAlex Zinenko     if (failed(convertOperation(op, builder)))
598baa1ec22SAlex Zinenko       return failure();
5995d7231d8SStephan Herhut   }
6005d7231d8SStephan Herhut 
601baa1ec22SAlex Zinenko   return success();
6025d7231d8SStephan Herhut }
6035d7231d8SStephan Herhut 
604ce8f10d6SAlex Zinenko /// A helper method to get the single Block in an operation honoring LLVM's
605ce8f10d6SAlex Zinenko /// module requirements.
getModuleBody(Operation * module)606ce8f10d6SAlex Zinenko static Block &getModuleBody(Operation *module) {
607ce8f10d6SAlex Zinenko   return module->getRegion(0).front();
608ce8f10d6SAlex Zinenko }
609ce8f10d6SAlex Zinenko 
610ffa455d4SJean Perier /// A helper method to decide if a constant must not be set as a global variable
611d4df3825SAlex Zinenko /// initializer. For an external linkage variable, the variable with an
612d4df3825SAlex Zinenko /// initializer is considered externally visible and defined in this module, the
613d4df3825SAlex Zinenko /// variable without an initializer is externally available and is defined
614d4df3825SAlex Zinenko /// elsewhere.
shouldDropGlobalInitializer(llvm::GlobalValue::LinkageTypes linkage,llvm::Constant * cst)615ffa455d4SJean Perier static bool shouldDropGlobalInitializer(llvm::GlobalValue::LinkageTypes linkage,
616ffa455d4SJean Perier                                         llvm::Constant *cst) {
617d4df3825SAlex Zinenko   return (linkage == llvm::GlobalVariable::ExternalLinkage && !cst) ||
618ffa455d4SJean Perier          linkage == llvm::GlobalVariable::ExternalWeakLinkage;
619ffa455d4SJean Perier }
620ffa455d4SJean Perier 
6218ca04b05SFelipe de Azevedo Piovezan /// Sets the runtime preemption specifier of `gv` to dso_local if
6228ca04b05SFelipe de Azevedo Piovezan /// `dsoLocalRequested` is true, otherwise it is left unchanged.
addRuntimePreemptionSpecifier(bool dsoLocalRequested,llvm::GlobalValue * gv)6238ca04b05SFelipe de Azevedo Piovezan static void addRuntimePreemptionSpecifier(bool dsoLocalRequested,
6248ca04b05SFelipe de Azevedo Piovezan                                           llvm::GlobalValue *gv) {
6258ca04b05SFelipe de Azevedo Piovezan   if (dsoLocalRequested)
6268ca04b05SFelipe de Azevedo Piovezan     gv->setDSOLocal(true);
6278ca04b05SFelipe de Azevedo Piovezan }
6288ca04b05SFelipe de Azevedo Piovezan 
6292666b973SRiver Riddle /// Create named global variables that correspond to llvm.mlir.global
63057b9b296SUday Bondhugula /// definitions. Convert llvm.global_ctors and global_dtors ops.
convertGlobals()631efa2d533SAlex Zinenko LogicalResult ModuleTranslation::convertGlobals() {
63244fc7d72STres Popp   for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) {
633aec38c61SAlex Zinenko     llvm::Type *type = convertType(op.getType());
634d4df3825SAlex Zinenko     llvm::Constant *cst = nullptr;
635250a11aeSJames Molloy     if (op.getValueOrNull()) {
63668451df2SAlex Zinenko       // String attributes are treated separately because they cannot appear as
63768451df2SAlex Zinenko       // in-function constants and are thus not supported by getLLVMConstant.
63833a3a91bSChristian Sigg       if (auto strAttr = op.getValueOrNull().dyn_cast_or_null<StringAttr>()) {
6392dd38b09SAlex Zinenko         cst = llvm::ConstantDataArray::getString(
64068451df2SAlex Zinenko             llvmModule->getContext(), strAttr.getValue(), /*AddNull=*/false);
6412dd38b09SAlex Zinenko         type = cst->getType();
642176379e0SAlex Zinenko       } else if (!(cst = getLLVMConstant(type, op.getValueOrNull(), op.getLoc(),
643176379e0SAlex Zinenko                                          *this))) {
644efa2d533SAlex Zinenko         return failure();
64568451df2SAlex Zinenko       }
646ffa455d4SJean Perier     }
647ffa455d4SJean Perier 
648cfb72fd3SJacques Pienaar     auto linkage = convertLinkageToLLVM(op.getLinkage());
649cfb72fd3SJacques Pienaar     auto addrSpace = op.getAddrSpace();
650d4df3825SAlex Zinenko 
651d4df3825SAlex Zinenko     // LLVM IR requires constant with linkage other than external or weak
652d4df3825SAlex Zinenko     // external to have initializers. If MLIR does not provide an initializer,
653d4df3825SAlex Zinenko     // default to undef.
654d4df3825SAlex Zinenko     bool dropInitializer = shouldDropGlobalInitializer(linkage, cst);
655d4df3825SAlex Zinenko     if (!dropInitializer && !cst)
656d4df3825SAlex Zinenko       cst = llvm::UndefValue::get(type);
657d4df3825SAlex Zinenko     else if (dropInitializer && cst)
658d4df3825SAlex Zinenko       cst = nullptr;
659d4df3825SAlex Zinenko 
660ffa455d4SJean Perier     auto *var = new llvm::GlobalVariable(
661cfb72fd3SJacques Pienaar         *llvmModule, type, op.getConstant(), linkage, cst, op.getSymName(),
662f0ba32d6SShraiysh Vaishay         /*InsertBefore=*/nullptr,
663f0ba32d6SShraiysh Vaishay         op.getThreadLocal_() ? llvm::GlobalValue::GeneralDynamicTLSModel
664f0ba32d6SShraiysh Vaishay                              : llvm::GlobalValue::NotThreadLocal,
665f0ba32d6SShraiysh Vaishay         addrSpace);
666ffa455d4SJean Perier 
667491d2701SKazu Hirata     if (op.getUnnamedAddr().has_value())
668cfb72fd3SJacques Pienaar       var->setUnnamedAddr(convertUnnamedAddrToLLVM(*op.getUnnamedAddr()));
669c46a8862Sclementval 
670491d2701SKazu Hirata     if (op.getSection().has_value())
671cfb72fd3SJacques Pienaar       var->setSection(*op.getSection());
672b65472d6SRanjith Kumar H 
673cfb72fd3SJacques Pienaar     addRuntimePreemptionSpecifier(op.getDsoLocal(), var);
6748ca04b05SFelipe de Azevedo Piovezan 
675cfb72fd3SJacques Pienaar     Optional<uint64_t> alignment = op.getAlignment();
676491d2701SKazu Hirata     if (alignment.has_value())
677c27d8152SKazu Hirata       var->setAlignment(llvm::MaybeAlign(alignment.value()));
6789a0ea599SDumitru Potop 
679ffa455d4SJean Perier     globalsMapping.try_emplace(op, var);
680ffa455d4SJean Perier   }
681ffa455d4SJean Perier 
682ffa455d4SJean Perier   // Convert global variable bodies. This is done after all global variables
683ffa455d4SJean Perier   // have been created in LLVM IR because a global body may refer to another
684ffa455d4SJean Perier   // global or itself. So all global variables need to be mapped first.
685ffa455d4SJean Perier   for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) {
686ffa455d4SJean Perier     if (Block *initializer = op.getInitializerBlock()) {
687250a11aeSJames Molloy       llvm::IRBuilder<> builder(llvmModule->getContext());
688250a11aeSJames Molloy       for (auto &op : initializer->without_terminator()) {
689250a11aeSJames Molloy         if (failed(convertOperation(op, builder)) ||
6900881a4f1SAlex Zinenko             !isa<llvm::Constant>(lookupValue(op.getResult(0))))
691efa2d533SAlex Zinenko           return emitError(op.getLoc(), "unemittable constant value");
692250a11aeSJames Molloy       }
693250a11aeSJames Molloy       ReturnOp ret = cast<ReturnOp>(initializer->getTerminator());
694ffa455d4SJean Perier       llvm::Constant *cst =
695ffa455d4SJean Perier           cast<llvm::Constant>(lookupValue(ret.getOperand(0)));
696ffa455d4SJean Perier       auto *global = cast<llvm::GlobalVariable>(lookupGlobal(op));
697ffa455d4SJean Perier       if (!shouldDropGlobalInitializer(global->getLinkage(), cst))
698ffa455d4SJean Perier         global->setInitializer(cst);
699250a11aeSJames Molloy     }
700b9ff2dd8SAlex Zinenko   }
701efa2d533SAlex Zinenko 
70257b9b296SUday Bondhugula   // Convert llvm.mlir.global_ctors and dtors.
70357b9b296SUday Bondhugula   for (Operation &op : getModuleBody(mlirModule)) {
70457b9b296SUday Bondhugula     auto ctorOp = dyn_cast<GlobalCtorsOp>(op);
70557b9b296SUday Bondhugula     auto dtorOp = dyn_cast<GlobalDtorsOp>(op);
70657b9b296SUday Bondhugula     if (!ctorOp && !dtorOp)
70757b9b296SUday Bondhugula       continue;
70862fea88bSJacques Pienaar     auto range = ctorOp ? llvm::zip(ctorOp.getCtors(), ctorOp.getPriorities())
70962fea88bSJacques Pienaar                         : llvm::zip(dtorOp.getDtors(), dtorOp.getPriorities());
71057b9b296SUday Bondhugula     auto appendGlobalFn =
71157b9b296SUday Bondhugula         ctorOp ? llvm::appendToGlobalCtors : llvm::appendToGlobalDtors;
71257b9b296SUday Bondhugula     for (auto symbolAndPriority : range) {
71357b9b296SUday Bondhugula       llvm::Function *f = lookupFunction(
71457b9b296SUday Bondhugula           std::get<0>(symbolAndPriority).cast<FlatSymbolRefAttr>().getValue());
71557b9b296SUday Bondhugula       appendGlobalFn(
71618eb6818SMehdi Amini           *llvmModule, f,
71757b9b296SUday Bondhugula           std::get<1>(symbolAndPriority).cast<IntegerAttr>().getInt(),
71857b9b296SUday Bondhugula           /*Data=*/nullptr);
71957b9b296SUday Bondhugula     }
72057b9b296SUday Bondhugula   }
72157b9b296SUday Bondhugula 
722efa2d533SAlex Zinenko   return success();
723b9ff2dd8SAlex Zinenko }
724b9ff2dd8SAlex Zinenko 
7250a2131b7SAlex Zinenko /// Attempts to add an attribute identified by `key`, optionally with the given
7260a2131b7SAlex Zinenko /// `value` to LLVM function `llvmFunc`. Reports errors at `loc` if any. If the
7270a2131b7SAlex Zinenko /// attribute has a kind known to LLVM IR, create the attribute of this kind,
7280a2131b7SAlex Zinenko /// otherwise keep it as a string attribute. Performs additional checks for
7290a2131b7SAlex Zinenko /// attributes known to have or not have a value in order to avoid assertions
7300a2131b7SAlex Zinenko /// inside LLVM upon construction.
checkedAddLLVMFnAttribute(Location loc,llvm::Function * llvmFunc,StringRef key,StringRef value=StringRef ())7310a2131b7SAlex Zinenko static LogicalResult checkedAddLLVMFnAttribute(Location loc,
7320a2131b7SAlex Zinenko                                                llvm::Function *llvmFunc,
7330a2131b7SAlex Zinenko                                                StringRef key,
7340a2131b7SAlex Zinenko                                                StringRef value = StringRef()) {
7350a2131b7SAlex Zinenko   auto kind = llvm::Attribute::getAttrKindFromName(key);
7360a2131b7SAlex Zinenko   if (kind == llvm::Attribute::None) {
7370a2131b7SAlex Zinenko     llvmFunc->addFnAttr(key, value);
7380a2131b7SAlex Zinenko     return success();
7390a2131b7SAlex Zinenko   }
7400a2131b7SAlex Zinenko 
7416ac32872SNikita Popov   if (llvm::Attribute::isIntAttrKind(kind)) {
7420a2131b7SAlex Zinenko     if (value.empty())
7430a2131b7SAlex Zinenko       return emitError(loc) << "LLVM attribute '" << key << "' expects a value";
7440a2131b7SAlex Zinenko 
7450a2131b7SAlex Zinenko     int result;
7460a2131b7SAlex Zinenko     if (!value.getAsInteger(/*Radix=*/0, result))
7470a2131b7SAlex Zinenko       llvmFunc->addFnAttr(
7480a2131b7SAlex Zinenko           llvm::Attribute::get(llvmFunc->getContext(), kind, result));
7490a2131b7SAlex Zinenko     else
7500a2131b7SAlex Zinenko       llvmFunc->addFnAttr(key, value);
7510a2131b7SAlex Zinenko     return success();
7520a2131b7SAlex Zinenko   }
7530a2131b7SAlex Zinenko 
7540a2131b7SAlex Zinenko   if (!value.empty())
7550a2131b7SAlex Zinenko     return emitError(loc) << "LLVM attribute '" << key
7560a2131b7SAlex Zinenko                           << "' does not expect a value, found '" << value
7570a2131b7SAlex Zinenko                           << "'";
7580a2131b7SAlex Zinenko 
7590a2131b7SAlex Zinenko   llvmFunc->addFnAttr(kind);
7600a2131b7SAlex Zinenko   return success();
7610a2131b7SAlex Zinenko }
7620a2131b7SAlex Zinenko 
7630a2131b7SAlex Zinenko /// Attaches the attributes listed in the given array attribute to `llvmFunc`.
7640a2131b7SAlex Zinenko /// Reports error to `loc` if any and returns immediately. Expects `attributes`
7650a2131b7SAlex Zinenko /// to be an array attribute containing either string attributes, treated as
7660a2131b7SAlex Zinenko /// value-less LLVM attributes, or array attributes containing two string
7670a2131b7SAlex Zinenko /// attributes, with the first string being the name of the corresponding LLVM
7680a2131b7SAlex Zinenko /// attribute and the second string beings its value. Note that even integer
7690a2131b7SAlex Zinenko /// attributes are expected to have their values expressed as strings.
7700a2131b7SAlex Zinenko static LogicalResult
forwardPassthroughAttributes(Location loc,Optional<ArrayAttr> attributes,llvm::Function * llvmFunc)7710a2131b7SAlex Zinenko forwardPassthroughAttributes(Location loc, Optional<ArrayAttr> attributes,
7720a2131b7SAlex Zinenko                              llvm::Function *llvmFunc) {
7730a2131b7SAlex Zinenko   if (!attributes)
7740a2131b7SAlex Zinenko     return success();
7750a2131b7SAlex Zinenko 
7760a2131b7SAlex Zinenko   for (Attribute attr : *attributes) {
7770a2131b7SAlex Zinenko     if (auto stringAttr = attr.dyn_cast<StringAttr>()) {
7780a2131b7SAlex Zinenko       if (failed(
7790a2131b7SAlex Zinenko               checkedAddLLVMFnAttribute(loc, llvmFunc, stringAttr.getValue())))
7800a2131b7SAlex Zinenko         return failure();
7810a2131b7SAlex Zinenko       continue;
7820a2131b7SAlex Zinenko     }
7830a2131b7SAlex Zinenko 
7840a2131b7SAlex Zinenko     auto arrayAttr = attr.dyn_cast<ArrayAttr>();
7850a2131b7SAlex Zinenko     if (!arrayAttr || arrayAttr.size() != 2)
7860a2131b7SAlex Zinenko       return emitError(loc)
7870a2131b7SAlex Zinenko              << "expected 'passthrough' to contain string or array attributes";
7880a2131b7SAlex Zinenko 
7890a2131b7SAlex Zinenko     auto keyAttr = arrayAttr[0].dyn_cast<StringAttr>();
7900a2131b7SAlex Zinenko     auto valueAttr = arrayAttr[1].dyn_cast<StringAttr>();
7910a2131b7SAlex Zinenko     if (!keyAttr || !valueAttr)
7920a2131b7SAlex Zinenko       return emitError(loc)
7930a2131b7SAlex Zinenko              << "expected arrays within 'passthrough' to contain two strings";
7940a2131b7SAlex Zinenko 
7950a2131b7SAlex Zinenko     if (failed(checkedAddLLVMFnAttribute(loc, llvmFunc, keyAttr.getValue(),
7960a2131b7SAlex Zinenko                                          valueAttr.getValue())))
7970a2131b7SAlex Zinenko       return failure();
7980a2131b7SAlex Zinenko   }
7990a2131b7SAlex Zinenko   return success();
8000a2131b7SAlex Zinenko }
8010a2131b7SAlex Zinenko 
convertOneFunction(LLVMFuncOp func)8025e7959a3SAlex Zinenko LogicalResult ModuleTranslation::convertOneFunction(LLVMFuncOp func) {
803db884dafSAlex Zinenko   // Clear the block, branch value mappings, they are only relevant within one
8045d7231d8SStephan Herhut   // function.
8055d7231d8SStephan Herhut   blockMapping.clear();
8065d7231d8SStephan Herhut   valueMapping.clear();
807db884dafSAlex Zinenko   branchMapping.clear();
8080881a4f1SAlex Zinenko   llvm::Function *llvmFunc = lookupFunction(func.getName());
809c33d6970SRiver Riddle 
810c33d6970SRiver Riddle   // Translate the debug information for this function.
811c33d6970SRiver Riddle   debugTranslation->translate(func, *llvmFunc);
812c33d6970SRiver Riddle 
8135d7231d8SStephan Herhut   // Add function arguments to the value remapping table.
8145d7231d8SStephan Herhut   // If there was noalias info then we decorate each argument accordingly.
8155d7231d8SStephan Herhut   unsigned int argIdx = 0;
816eeef50b1SFangrui Song   for (auto kvp : llvm::zip(func.getArguments(), llvmFunc->args())) {
8175d7231d8SStephan Herhut     llvm::Argument &llvmArg = std::get<1>(kvp);
818e62a6956SRiver Riddle     BlockArgument mlirArg = std::get<0>(kvp);
8195d7231d8SStephan Herhut 
8201c777ab4SUday Bondhugula     if (auto attr = func.getArgAttrOfType<UnitAttr>(
82167cc5cecSStephan Herhut             argIdx, LLVMDialect::getNoAliasAttrName())) {
8225d7231d8SStephan Herhut       // NB: Attribute already verified to be boolean, so check if we can indeed
8235d7231d8SStephan Herhut       // attach the attribute to this argument, based on its type.
824c69c9e0fSAlex Zinenko       auto argTy = mlirArg.getType();
8258de43b92SAlex Zinenko       if (!argTy.isa<LLVM::LLVMPointerType>())
826baa1ec22SAlex Zinenko         return func.emitError(
8275d7231d8SStephan Herhut             "llvm.noalias attribute attached to LLVM non-pointer argument");
8285d7231d8SStephan Herhut       llvmArg.addAttr(llvm::Attribute::AttrKind::NoAlias);
8295d7231d8SStephan Herhut     }
8302416e28cSStephan Herhut 
83167cc5cecSStephan Herhut     if (auto attr = func.getArgAttrOfType<IntegerAttr>(
83267cc5cecSStephan Herhut             argIdx, LLVMDialect::getAlignAttrName())) {
8332416e28cSStephan Herhut       // NB: Attribute already verified to be int, so check if we can indeed
8342416e28cSStephan Herhut       // attach the attribute to this argument, based on its type.
835c69c9e0fSAlex Zinenko       auto argTy = mlirArg.getType();
8368de43b92SAlex Zinenko       if (!argTy.isa<LLVM::LLVMPointerType>())
8372416e28cSStephan Herhut         return func.emitError(
8382416e28cSStephan Herhut             "llvm.align attribute attached to LLVM non-pointer argument");
839d50298ddSEric Schweitz       llvmArg.addAttrs(llvm::AttrBuilder(llvmArg.getContext())
840d50298ddSEric Schweitz                            .addAlignmentAttr(llvm::Align(attr.getInt())));
8412416e28cSStephan Herhut     }
8422416e28cSStephan Herhut 
84370b841acSEric Schweitz     if (auto attr = func.getArgAttrOfType<UnitAttr>(argIdx, "llvm.sret")) {
844a4ad79c5SNikita Popov       auto argTy = mlirArg.getType().dyn_cast<LLVM::LLVMPointerType>();
845a4ad79c5SNikita Popov       if (!argTy)
84670b841acSEric Schweitz         return func.emitError(
84770b841acSEric Schweitz             "llvm.sret attribute attached to LLVM non-pointer argument");
848a4ad79c5SNikita Popov       llvmArg.addAttrs(
849a4ad79c5SNikita Popov           llvm::AttrBuilder(llvmArg.getContext())
850a4ad79c5SNikita Popov               .addStructRetAttr(convertType(argTy.getElementType())));
85170b841acSEric Schweitz     }
85270b841acSEric Schweitz 
85370b841acSEric Schweitz     if (auto attr = func.getArgAttrOfType<UnitAttr>(argIdx, "llvm.byval")) {
854a4ad79c5SNikita Popov       auto argTy = mlirArg.getType().dyn_cast<LLVM::LLVMPointerType>();
855a4ad79c5SNikita Popov       if (!argTy)
85670b841acSEric Schweitz         return func.emitError(
85770b841acSEric Schweitz             "llvm.byval attribute attached to LLVM non-pointer argument");
858a4ad79c5SNikita Popov       llvmArg.addAttrs(llvm::AttrBuilder(llvmArg.getContext())
859a4ad79c5SNikita Popov                            .addByValAttr(convertType(argTy.getElementType())));
86070b841acSEric Schweitz     }
86170b841acSEric Schweitz 
8621c083e69SEric Schweitz     if (auto attr = func.getArgAttrOfType<UnitAttr>(argIdx, "llvm.nest")) {
8631c083e69SEric Schweitz       auto argTy = mlirArg.getType();
8641c083e69SEric Schweitz       if (!argTy.isa<LLVM::LLVMPointerType>())
8651c083e69SEric Schweitz         return func.emitError(
8661c083e69SEric Schweitz             "llvm.nest attribute attached to LLVM non-pointer argument");
8671c083e69SEric Schweitz       llvmArg.addAttrs(llvm::AttrBuilder(llvmArg.getContext())
8681c083e69SEric Schweitz                            .addAttribute(llvm::Attribute::Nest));
8691c083e69SEric Schweitz     }
8701c083e69SEric Schweitz 
8710881a4f1SAlex Zinenko     mapValue(mlirArg, &llvmArg);
8725d7231d8SStephan Herhut     argIdx++;
8735d7231d8SStephan Herhut   }
8745d7231d8SStephan Herhut 
875ff77397fSShraiysh Vaishay   // Check the personality and set it.
876037f0995SKazu Hirata   if (func.getPersonality()) {
877ff77397fSShraiysh Vaishay     llvm::Type *ty = llvm::Type::getInt8PtrTy(llvmFunc->getContext());
878dde96363SJacques Pienaar     if (llvm::Constant *pfunc = getLLVMConstant(ty, func.getPersonalityAttr(),
879dde96363SJacques Pienaar                                                 func.getLoc(), *this))
880ff77397fSShraiysh Vaishay       llvmFunc->setPersonalityFn(pfunc);
881ff77397fSShraiysh Vaishay   }
882ff77397fSShraiysh Vaishay 
8831bf79213SMarkus Böck   if (auto gc = func.getGarbageCollector())
8841bf79213SMarkus Böck     llvmFunc->setGC(gc->str());
8851bf79213SMarkus Böck 
8865d7231d8SStephan Herhut   // First, create all blocks so we can jump to them.
8875d7231d8SStephan Herhut   llvm::LLVMContext &llvmContext = llvmFunc->getContext();
8885d7231d8SStephan Herhut   for (auto &bb : func) {
8895d7231d8SStephan Herhut     auto *llvmBB = llvm::BasicBlock::Create(llvmContext);
8905d7231d8SStephan Herhut     llvmBB->insertInto(llvmFunc);
8910881a4f1SAlex Zinenko     mapBlock(&bb, llvmBB);
8925d7231d8SStephan Herhut   }
8935d7231d8SStephan Herhut 
8945d7231d8SStephan Herhut   // Then, convert blocks one by one in topological order to ensure defs are
8955d7231d8SStephan Herhut   // converted before uses.
89666900b3eSAlex Zinenko   auto blocks = detail::getTopologicallySortedBlocks(func.getBody());
89710164a2eSAlex Zinenko   for (Block *bb : blocks) {
89810164a2eSAlex Zinenko     llvm::IRBuilder<> builder(llvmContext);
89910164a2eSAlex Zinenko     if (failed(convertBlock(*bb, bb->isEntryBlock(), builder)))
900baa1ec22SAlex Zinenko       return failure();
9015d7231d8SStephan Herhut   }
9025d7231d8SStephan Herhut 
903176379e0SAlex Zinenko   // After all blocks have been traversed and values mapped, connect the PHI
904176379e0SAlex Zinenko   // nodes to the results of preceding blocks.
90566900b3eSAlex Zinenko   detail::connectPHINodes(func.getBody(), *this);
906176379e0SAlex Zinenko 
907176379e0SAlex Zinenko   // Finally, convert dialect attributes attached to the function.
908176379e0SAlex Zinenko   return convertDialectAttributes(func);
909176379e0SAlex Zinenko }
910176379e0SAlex Zinenko 
convertDialectAttributes(Operation * op)911176379e0SAlex Zinenko LogicalResult ModuleTranslation::convertDialectAttributes(Operation *op) {
912176379e0SAlex Zinenko   for (NamedAttribute attribute : op->getDialectAttrs())
913176379e0SAlex Zinenko     if (failed(iface.amendOperation(op, attribute, *this)))
914176379e0SAlex Zinenko       return failure();
915baa1ec22SAlex Zinenko   return success();
9165d7231d8SStephan Herhut }
9175d7231d8SStephan Herhut 
convertFunctionSignatures()918a084b94fSSean Silva LogicalResult ModuleTranslation::convertFunctionSignatures() {
9195d7231d8SStephan Herhut   // Declare all functions first because there may be function calls that form a
920a084b94fSSean Silva   // call graph with cycles, or global initializers that reference functions.
92144fc7d72STres Popp   for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) {
9225e7959a3SAlex Zinenko     llvm::FunctionCallee llvmFuncCst = llvmModule->getOrInsertFunction(
9235e7959a3SAlex Zinenko         function.getName(),
9244a3460a7SRiver Riddle         cast<llvm::FunctionType>(convertType(function.getFunctionType())));
9250a2131b7SAlex Zinenko     llvm::Function *llvmFunc = cast<llvm::Function>(llvmFuncCst.getCallee());
926dde96363SJacques Pienaar     llvmFunc->setLinkage(convertLinkageToLLVM(function.getLinkage()));
9270881a4f1SAlex Zinenko     mapFunction(function.getName(), llvmFunc);
928dde96363SJacques Pienaar     addRuntimePreemptionSpecifier(function.getDsoLocal(), llvmFunc);
9290a2131b7SAlex Zinenko 
9300a2131b7SAlex Zinenko     // Forward the pass-through attributes to LLVM.
931dde96363SJacques Pienaar     if (failed(forwardPassthroughAttributes(
932dde96363SJacques Pienaar             function.getLoc(), function.getPassthrough(), llvmFunc)))
9330a2131b7SAlex Zinenko       return failure();
9345d7231d8SStephan Herhut   }
9355d7231d8SStephan Herhut 
936a084b94fSSean Silva   return success();
937a084b94fSSean Silva }
938a084b94fSSean Silva 
convertFunctions()939a084b94fSSean Silva LogicalResult ModuleTranslation::convertFunctions() {
9405d7231d8SStephan Herhut   // Convert functions.
94144fc7d72STres Popp   for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) {
9425d7231d8SStephan Herhut     // Ignore external functions.
9435d7231d8SStephan Herhut     if (function.isExternal())
9445d7231d8SStephan Herhut       continue;
9455d7231d8SStephan Herhut 
946baa1ec22SAlex Zinenko     if (failed(convertOneFunction(function)))
947baa1ec22SAlex Zinenko       return failure();
9485d7231d8SStephan Herhut   }
9495d7231d8SStephan Herhut 
950baa1ec22SAlex Zinenko   return success();
9515d7231d8SStephan Herhut }
9525d7231d8SStephan Herhut 
9534a2930f4SArpith C. Jacob llvm::MDNode *
getAccessGroup(Operation & opInst,SymbolRefAttr accessGroupRef) const9544a2930f4SArpith C. Jacob ModuleTranslation::getAccessGroup(Operation &opInst,
9554a2930f4SArpith C. Jacob                                   SymbolRefAttr accessGroupRef) const {
9564a2930f4SArpith C. Jacob   auto metadataName = accessGroupRef.getRootReference();
9574a2930f4SArpith C. Jacob   auto accessGroupName = accessGroupRef.getLeafReference();
9584a2930f4SArpith C. Jacob   auto metadataOp = SymbolTable::lookupNearestSymbolFrom<LLVM::MetadataOp>(
9594a2930f4SArpith C. Jacob       opInst.getParentOp(), metadataName);
9604a2930f4SArpith C. Jacob   auto *accessGroupOp =
9614a2930f4SArpith C. Jacob       SymbolTable::lookupNearestSymbolFrom(metadataOp, accessGroupName);
9624a2930f4SArpith C. Jacob   return accessGroupMetadataMapping.lookup(accessGroupOp);
9634a2930f4SArpith C. Jacob }
9644a2930f4SArpith C. Jacob 
createAccessGroupMetadata()9654a2930f4SArpith C. Jacob LogicalResult ModuleTranslation::createAccessGroupMetadata() {
9664a2930f4SArpith C. Jacob   mlirModule->walk([&](LLVM::MetadataOp metadatas) {
9674a2930f4SArpith C. Jacob     metadatas.walk([&](LLVM::AccessGroupMetadataOp op) {
9684a2930f4SArpith C. Jacob       llvm::LLVMContext &ctx = llvmModule->getContext();
9694a2930f4SArpith C. Jacob       llvm::MDNode *accessGroup = llvm::MDNode::getDistinct(ctx, {});
9704a2930f4SArpith C. Jacob       accessGroupMetadataMapping.insert({op, accessGroup});
9714a2930f4SArpith C. Jacob     });
9724a2930f4SArpith C. Jacob   });
9734a2930f4SArpith C. Jacob   return success();
9744a2930f4SArpith C. Jacob }
9754a2930f4SArpith C. Jacob 
setAccessGroupsMetadata(Operation * op,llvm::Instruction * inst)9764e393350SArpith C. Jacob void ModuleTranslation::setAccessGroupsMetadata(Operation *op,
9774e393350SArpith C. Jacob                                                 llvm::Instruction *inst) {
9784e393350SArpith C. Jacob   auto accessGroups =
9794e393350SArpith C. Jacob       op->getAttrOfType<ArrayAttr>(LLVMDialect::getAccessGroupsAttrName());
9804e393350SArpith C. Jacob   if (accessGroups && !accessGroups.empty()) {
9814e393350SArpith C. Jacob     llvm::Module *module = inst->getModule();
9824e393350SArpith C. Jacob     SmallVector<llvm::Metadata *> metadatas;
9834e393350SArpith C. Jacob     for (SymbolRefAttr accessGroupRef :
9844e393350SArpith C. Jacob          accessGroups.getAsRange<SymbolRefAttr>())
9854e393350SArpith C. Jacob       metadatas.push_back(getAccessGroup(*op, accessGroupRef));
9864e393350SArpith C. Jacob 
9874e393350SArpith C. Jacob     llvm::MDNode *unionMD = nullptr;
9884e393350SArpith C. Jacob     if (metadatas.size() == 1)
9894e393350SArpith C. Jacob       unionMD = llvm::cast<llvm::MDNode>(metadatas.front());
9904e393350SArpith C. Jacob     else if (metadatas.size() >= 2)
9914e393350SArpith C. Jacob       unionMD = llvm::MDNode::get(module->getContext(), metadatas);
9924e393350SArpith C. Jacob 
9934e393350SArpith C. Jacob     inst->setMetadata(module->getMDKindID("llvm.access.group"), unionMD);
9944e393350SArpith C. Jacob   }
9954e393350SArpith C. Jacob }
9964e393350SArpith C. Jacob 
createAliasScopeMetadata()997d25e91d7STyler Augustine LogicalResult ModuleTranslation::createAliasScopeMetadata() {
998d25e91d7STyler Augustine   mlirModule->walk([&](LLVM::MetadataOp metadatas) {
999d25e91d7STyler Augustine     // Create the domains first, so they can be reference below in the scopes.
1000d25e91d7STyler Augustine     DenseMap<Operation *, llvm::MDNode *> aliasScopeDomainMetadataMapping;
1001d25e91d7STyler Augustine     metadatas.walk([&](LLVM::AliasScopeDomainMetadataOp op) {
1002d25e91d7STyler Augustine       llvm::LLVMContext &ctx = llvmModule->getContext();
1003d25e91d7STyler Augustine       llvm::SmallVector<llvm::Metadata *, 2> operands;
1004d25e91d7STyler Augustine       operands.push_back({}); // Placeholder for self-reference
1005cfb72fd3SJacques Pienaar       if (Optional<StringRef> description = op.getDescription())
10066d5fc1e3SKazu Hirata         operands.push_back(llvm::MDString::get(ctx, *description));
1007d25e91d7STyler Augustine       llvm::MDNode *domain = llvm::MDNode::get(ctx, operands);
1008d25e91d7STyler Augustine       domain->replaceOperandWith(0, domain); // Self-reference for uniqueness
1009d25e91d7STyler Augustine       aliasScopeDomainMetadataMapping.insert({op, domain});
1010d25e91d7STyler Augustine     });
1011d25e91d7STyler Augustine 
1012d25e91d7STyler Augustine     // Now create the scopes, referencing the domains created above.
1013d25e91d7STyler Augustine     metadatas.walk([&](LLVM::AliasScopeMetadataOp op) {
1014d25e91d7STyler Augustine       llvm::LLVMContext &ctx = llvmModule->getContext();
1015d25e91d7STyler Augustine       assert(isa<LLVM::MetadataOp>(op->getParentOp()));
1016d25e91d7STyler Augustine       auto metadataOp = dyn_cast<LLVM::MetadataOp>(op->getParentOp());
1017d25e91d7STyler Augustine       Operation *domainOp =
1018cfb72fd3SJacques Pienaar           SymbolTable::lookupNearestSymbolFrom(metadataOp, op.getDomainAttr());
1019d25e91d7STyler Augustine       llvm::MDNode *domain = aliasScopeDomainMetadataMapping.lookup(domainOp);
1020d25e91d7STyler Augustine       assert(domain && "Scope's domain should already be valid");
1021d25e91d7STyler Augustine       llvm::SmallVector<llvm::Metadata *, 3> operands;
1022d25e91d7STyler Augustine       operands.push_back({}); // Placeholder for self-reference
1023d25e91d7STyler Augustine       operands.push_back(domain);
1024cfb72fd3SJacques Pienaar       if (Optional<StringRef> description = op.getDescription())
10256d5fc1e3SKazu Hirata         operands.push_back(llvm::MDString::get(ctx, *description));
1026d25e91d7STyler Augustine       llvm::MDNode *scope = llvm::MDNode::get(ctx, operands);
1027d25e91d7STyler Augustine       scope->replaceOperandWith(0, scope); // Self-reference for uniqueness
1028d25e91d7STyler Augustine       aliasScopeMetadataMapping.insert({op, scope});
1029d25e91d7STyler Augustine     });
1030d25e91d7STyler Augustine   });
1031d25e91d7STyler Augustine   return success();
1032d25e91d7STyler Augustine }
1033d25e91d7STyler Augustine 
1034d25e91d7STyler Augustine llvm::MDNode *
getAliasScope(Operation & opInst,SymbolRefAttr aliasScopeRef) const1035d25e91d7STyler Augustine ModuleTranslation::getAliasScope(Operation &opInst,
1036d25e91d7STyler Augustine                                  SymbolRefAttr aliasScopeRef) const {
103741d4aa7dSChris Lattner   StringAttr metadataName = aliasScopeRef.getRootReference();
103841d4aa7dSChris Lattner   StringAttr scopeName = aliasScopeRef.getLeafReference();
1039d25e91d7STyler Augustine   auto metadataOp = SymbolTable::lookupNearestSymbolFrom<LLVM::MetadataOp>(
1040d25e91d7STyler Augustine       opInst.getParentOp(), metadataName);
1041d25e91d7STyler Augustine   Operation *aliasScopeOp =
1042d25e91d7STyler Augustine       SymbolTable::lookupNearestSymbolFrom(metadataOp, scopeName);
1043d25e91d7STyler Augustine   return aliasScopeMetadataMapping.lookup(aliasScopeOp);
1044d25e91d7STyler Augustine }
1045d25e91d7STyler Augustine 
setAliasScopeMetadata(Operation * op,llvm::Instruction * inst)1046d25e91d7STyler Augustine void ModuleTranslation::setAliasScopeMetadata(Operation *op,
1047d25e91d7STyler Augustine                                               llvm::Instruction *inst) {
1048d25e91d7STyler Augustine   auto populateScopeMetadata = [this, op, inst](StringRef attrName,
1049d25e91d7STyler Augustine                                                 StringRef llvmMetadataName) {
1050d25e91d7STyler Augustine     auto scopes = op->getAttrOfType<ArrayAttr>(attrName);
1051d25e91d7STyler Augustine     if (!scopes || scopes.empty())
1052d25e91d7STyler Augustine       return;
1053d25e91d7STyler Augustine     llvm::Module *module = inst->getModule();
1054d25e91d7STyler Augustine     SmallVector<llvm::Metadata *> scopeMDs;
1055d25e91d7STyler Augustine     for (SymbolRefAttr scopeRef : scopes.getAsRange<SymbolRefAttr>())
1056d25e91d7STyler Augustine       scopeMDs.push_back(getAliasScope(*op, scopeRef));
1057bdaf0382SAlex Zinenko     llvm::MDNode *unionMD = llvm::MDNode::get(module->getContext(), scopeMDs);
1058d25e91d7STyler Augustine     inst->setMetadata(module->getMDKindID(llvmMetadataName), unionMD);
1059d25e91d7STyler Augustine   };
1060d25e91d7STyler Augustine 
1061d25e91d7STyler Augustine   populateScopeMetadata(LLVMDialect::getAliasScopesAttrName(), "alias.scope");
1062d25e91d7STyler Augustine   populateScopeMetadata(LLVMDialect::getNoAliasScopesAttrName(), "noalias");
1063d25e91d7STyler Augustine }
1064d25e91d7STyler Augustine 
convertType(Type type)1065c69c9e0fSAlex Zinenko llvm::Type *ModuleTranslation::convertType(Type type) {
1066b2ab375dSAlex Zinenko   return typeTranslator.translateType(type);
1067aec38c61SAlex Zinenko }
1068aec38c61SAlex Zinenko 
10698647e4c3SAlex Zinenko /// A helper to look up remapped operands in the value remapping table.
lookupValues(ValueRange values)10708647e4c3SAlex Zinenko SmallVector<llvm::Value *> ModuleTranslation::lookupValues(ValueRange values) {
10718647e4c3SAlex Zinenko   SmallVector<llvm::Value *> remapped;
1072efadb6b8SAlex Zinenko   remapped.reserve(values.size());
10730881a4f1SAlex Zinenko   for (Value v : values)
10740881a4f1SAlex Zinenko     remapped.push_back(lookupValue(v));
1075efadb6b8SAlex Zinenko   return remapped;
1076efadb6b8SAlex Zinenko }
1077efadb6b8SAlex Zinenko 
107866900b3eSAlex Zinenko const llvm::DILocation *
translateLoc(Location loc,llvm::DILocalScope * scope)107966900b3eSAlex Zinenko ModuleTranslation::translateLoc(Location loc, llvm::DILocalScope *scope) {
108066900b3eSAlex Zinenko   return debugTranslation->translateLoc(loc, scope);
108166900b3eSAlex Zinenko }
108266900b3eSAlex Zinenko 
1083176379e0SAlex Zinenko llvm::NamedMDNode *
getOrInsertNamedModuleMetadata(StringRef name)1084176379e0SAlex Zinenko ModuleTranslation::getOrInsertNamedModuleMetadata(StringRef name) {
1085176379e0SAlex Zinenko   return llvmModule->getOrInsertNamedMetadata(name);
1086176379e0SAlex Zinenko }
1087176379e0SAlex Zinenko 
anchor()108872d013ddSAlex Zinenko void ModuleTranslation::StackFrame::anchor() {}
108972d013ddSAlex Zinenko 
1090ce8f10d6SAlex Zinenko static std::unique_ptr<llvm::Module>
prepareLLVMModule(Operation * m,llvm::LLVMContext & llvmContext,StringRef name)1091ce8f10d6SAlex Zinenko prepareLLVMModule(Operation *m, llvm::LLVMContext &llvmContext,
1092ce8f10d6SAlex Zinenko                   StringRef name) {
1093f9dc2b70SMehdi Amini   m->getContext()->getOrLoadDialect<LLVM::LLVMDialect>();
1094db1c197bSAlex Zinenko   auto llvmModule = std::make_unique<llvm::Module>(name, llvmContext);
1095168213f9SAlex Zinenko   if (auto dataLayoutAttr =
1096ea998709SAlex Zinenko           m->getAttr(LLVM::LLVMDialect::getDataLayoutAttrName())) {
1097168213f9SAlex Zinenko     llvmModule->setDataLayout(dataLayoutAttr.cast<StringAttr>().getValue());
1098ea998709SAlex Zinenko   } else {
1099ea998709SAlex Zinenko     FailureOr<llvm::DataLayout> llvmDataLayout(llvm::DataLayout(""));
1100ea998709SAlex Zinenko     if (auto iface = dyn_cast<DataLayoutOpInterface>(m)) {
1101ea998709SAlex Zinenko       if (DataLayoutSpecInterface spec = iface.getDataLayoutSpec()) {
1102ea998709SAlex Zinenko         llvmDataLayout =
1103ea998709SAlex Zinenko             translateDataLayout(spec, DataLayout(iface), m->getLoc());
1104ea998709SAlex Zinenko       }
1105ea998709SAlex Zinenko     } else if (auto mod = dyn_cast<ModuleOp>(m)) {
1106ea998709SAlex Zinenko       if (DataLayoutSpecInterface spec = mod.getDataLayoutSpec()) {
1107ea998709SAlex Zinenko         llvmDataLayout =
1108ea998709SAlex Zinenko             translateDataLayout(spec, DataLayout(mod), m->getLoc());
1109ea998709SAlex Zinenko       }
1110ea998709SAlex Zinenko     }
1111ea998709SAlex Zinenko     if (failed(llvmDataLayout))
1112ea998709SAlex Zinenko       return nullptr;
1113ea998709SAlex Zinenko     llvmModule->setDataLayout(*llvmDataLayout);
1114ea998709SAlex Zinenko   }
11155dd5a083SNicolas Vasilache   if (auto targetTripleAttr =
11165dd5a083SNicolas Vasilache           m->getAttr(LLVM::LLVMDialect::getTargetTripleAttrName()))
11175dd5a083SNicolas Vasilache     llvmModule->setTargetTriple(targetTripleAttr.cast<StringAttr>().getValue());
11185d7231d8SStephan Herhut 
1119*d04c2b2fSMehdi Amini   // Inject declarations for `malloc` and `free` functions that can be used in
1120*d04c2b2fSMehdi Amini   // memref allocation/deallocation coming from standard ops lowering.
1121db1c197bSAlex Zinenko   llvm::IRBuilder<> builder(llvmContext);
1122*d04c2b2fSMehdi Amini   llvmModule->getOrInsertFunction("malloc", builder.getInt8PtrTy(),
11235d7231d8SStephan Herhut                                   builder.getInt64Ty());
1124*d04c2b2fSMehdi Amini   llvmModule->getOrInsertFunction("free", builder.getVoidTy(),
11255d7231d8SStephan Herhut                                   builder.getInt8PtrTy());
11265d7231d8SStephan Herhut 
11275d7231d8SStephan Herhut   return llvmModule;
11285d7231d8SStephan Herhut }
1129ce8f10d6SAlex Zinenko 
1130ce8f10d6SAlex Zinenko std::unique_ptr<llvm::Module>
translateModuleToLLVMIR(Operation * module,llvm::LLVMContext & llvmContext,StringRef name)1131ce8f10d6SAlex Zinenko mlir::translateModuleToLLVMIR(Operation *module, llvm::LLVMContext &llvmContext,
1132ce8f10d6SAlex Zinenko                               StringRef name) {
1133ce8f10d6SAlex Zinenko   if (!satisfiesLLVMModule(module))
1134ce8f10d6SAlex Zinenko     return nullptr;
1135ea998709SAlex Zinenko 
1136ce8f10d6SAlex Zinenko   std::unique_ptr<llvm::Module> llvmModule =
1137ce8f10d6SAlex Zinenko       prepareLLVMModule(module, llvmContext, name);
1138ea998709SAlex Zinenko   if (!llvmModule)
1139ea998709SAlex Zinenko     return nullptr;
1140ce8f10d6SAlex Zinenko 
1141ce8f10d6SAlex Zinenko   LLVM::ensureDistinctSuccessors(module);
1142ce8f10d6SAlex Zinenko 
1143ce8f10d6SAlex Zinenko   ModuleTranslation translator(module, std::move(llvmModule));
1144ce8f10d6SAlex Zinenko   if (failed(translator.convertFunctionSignatures()))
1145ce8f10d6SAlex Zinenko     return nullptr;
1146ce8f10d6SAlex Zinenko   if (failed(translator.convertGlobals()))
1147ce8f10d6SAlex Zinenko     return nullptr;
11484a2930f4SArpith C. Jacob   if (failed(translator.createAccessGroupMetadata()))
11494a2930f4SArpith C. Jacob     return nullptr;
1150d25e91d7STyler Augustine   if (failed(translator.createAliasScopeMetadata()))
1151d25e91d7STyler Augustine     return nullptr;
1152ce8f10d6SAlex Zinenko   if (failed(translator.convertFunctions()))
1153ce8f10d6SAlex Zinenko     return nullptr;
11548647e4c3SAlex Zinenko 
11558647e4c3SAlex Zinenko   // Convert other top-level operations if possible.
11568647e4c3SAlex Zinenko   llvm::IRBuilder<> llvmBuilder(llvmContext);
11578647e4c3SAlex Zinenko   for (Operation &o : getModuleBody(module).getOperations()) {
115857b9b296SUday Bondhugula     if (!isa<LLVM::LLVMFuncOp, LLVM::GlobalOp, LLVM::GlobalCtorsOp,
115957b9b296SUday Bondhugula              LLVM::GlobalDtorsOp, LLVM::MetadataOp>(&o) &&
11608647e4c3SAlex Zinenko         !o.hasTrait<OpTrait::IsTerminator>() &&
11618647e4c3SAlex Zinenko         failed(translator.convertOperation(o, llvmBuilder))) {
11628647e4c3SAlex Zinenko       return nullptr;
11638647e4c3SAlex Zinenko     }
11648647e4c3SAlex Zinenko   }
11658647e4c3SAlex Zinenko 
1166ce8f10d6SAlex Zinenko   if (llvm::verifyModule(*translator.llvmModule, &llvm::errs()))
1167ce8f10d6SAlex Zinenko     return nullptr;
1168ce8f10d6SAlex Zinenko 
1169ce8f10d6SAlex Zinenko   return std::move(translator.llvmModule);
1170ce8f10d6SAlex Zinenko }
1171