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"
26ec1f4e7cSAlex Zinenko #include "mlir/Target/LLVMIR/TypeTranslation.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"
385d7231d8SStephan Herhut #include "llvm/IR/LLVMContext.h"
3999d03f03SGeorge Mitenkov #include "llvm/IR/MDBuilder.h"
405d7231d8SStephan Herhut #include "llvm/IR/Module.h"
41ce8f10d6SAlex Zinenko #include "llvm/IR/Verifier.h"
42d9067dcaSKiran Chandramohan #include "llvm/Transforms/Utils/BasicBlockUtils.h"
435d7231d8SStephan Herhut #include "llvm/Transforms/Utils/Cloning.h"
445d7231d8SStephan Herhut 
452666b973SRiver Riddle using namespace mlir;
462666b973SRiver Riddle using namespace mlir::LLVM;
47c33d6970SRiver Riddle using namespace mlir::LLVM::detail;
485d7231d8SStephan Herhut 
49eb67bd78SAlex Zinenko #include "mlir/Dialect/LLVMIR/LLVMConversionEnumsToLLVM.inc"
50eb67bd78SAlex Zinenko 
51a922e231SAlex Zinenko /// Builds a constant of a sequential LLVM type `type`, potentially containing
52a922e231SAlex Zinenko /// other sequential types recursively, from the individual constant values
53a922e231SAlex Zinenko /// provided in `constants`. `shape` contains the number of elements in nested
54a922e231SAlex Zinenko /// sequential types. Reports errors at `loc` and returns nullptr on error.
55a4a42160SAlex Zinenko static llvm::Constant *
56a4a42160SAlex Zinenko buildSequentialConstant(ArrayRef<llvm::Constant *> &constants,
57a4a42160SAlex Zinenko                         ArrayRef<int64_t> shape, llvm::Type *type,
58a4a42160SAlex Zinenko                         Location loc) {
59a4a42160SAlex Zinenko   if (shape.empty()) {
60a4a42160SAlex Zinenko     llvm::Constant *result = constants.front();
61a4a42160SAlex Zinenko     constants = constants.drop_front();
62a4a42160SAlex Zinenko     return result;
63a4a42160SAlex Zinenko   }
64a4a42160SAlex Zinenko 
6568b03aeeSEli Friedman   llvm::Type *elementType;
6668b03aeeSEli Friedman   if (auto *arrayTy = dyn_cast<llvm::ArrayType>(type)) {
6768b03aeeSEli Friedman     elementType = arrayTy->getElementType();
6868b03aeeSEli Friedman   } else if (auto *vectorTy = dyn_cast<llvm::VectorType>(type)) {
6968b03aeeSEli Friedman     elementType = vectorTy->getElementType();
7068b03aeeSEli Friedman   } else {
71a4a42160SAlex Zinenko     emitError(loc) << "expected sequential LLVM types wrapping a scalar";
72a4a42160SAlex Zinenko     return nullptr;
73a4a42160SAlex Zinenko   }
74a4a42160SAlex Zinenko 
75a4a42160SAlex Zinenko   SmallVector<llvm::Constant *, 8> nested;
76a4a42160SAlex Zinenko   nested.reserve(shape.front());
77a4a42160SAlex Zinenko   for (int64_t i = 0; i < shape.front(); ++i) {
78a4a42160SAlex Zinenko     nested.push_back(buildSequentialConstant(constants, shape.drop_front(),
79a4a42160SAlex Zinenko                                              elementType, loc));
80a4a42160SAlex Zinenko     if (!nested.back())
81a4a42160SAlex Zinenko       return nullptr;
82a4a42160SAlex Zinenko   }
83a4a42160SAlex Zinenko 
84a4a42160SAlex Zinenko   if (shape.size() == 1 && type->isVectorTy())
85a4a42160SAlex Zinenko     return llvm::ConstantVector::get(nested);
86a4a42160SAlex Zinenko   return llvm::ConstantArray::get(
87a4a42160SAlex Zinenko       llvm::ArrayType::get(elementType, shape.front()), nested);
88a4a42160SAlex Zinenko }
89a4a42160SAlex Zinenko 
90fc817b09SKazuaki Ishizaki /// Returns the first non-sequential type nested in sequential types.
91a4a42160SAlex Zinenko static llvm::Type *getInnermostElementType(llvm::Type *type) {
9268b03aeeSEli Friedman   do {
9368b03aeeSEli Friedman     if (auto *arrayTy = dyn_cast<llvm::ArrayType>(type)) {
9468b03aeeSEli Friedman       type = arrayTy->getElementType();
9568b03aeeSEli Friedman     } else if (auto *vectorTy = dyn_cast<llvm::VectorType>(type)) {
9668b03aeeSEli Friedman       type = vectorTy->getElementType();
9768b03aeeSEli Friedman     } else {
98a4a42160SAlex Zinenko       return type;
99a4a42160SAlex Zinenko     }
1000881a4f1SAlex Zinenko   } while (true);
10168b03aeeSEli Friedman }
102a4a42160SAlex Zinenko 
1032666b973SRiver Riddle /// Create an LLVM IR constant of `llvmType` from the MLIR attribute `attr`.
1042666b973SRiver Riddle /// This currently supports integer, floating point, splat and dense element
1052666b973SRiver Riddle /// attributes and combinations thereof.  In case of error, report it to `loc`
1062666b973SRiver Riddle /// and return nullptr.
107176379e0SAlex Zinenko llvm::Constant *mlir::LLVM::detail::getLLVMConstant(
108176379e0SAlex Zinenko     llvm::Type *llvmType, Attribute attr, Location loc,
109176379e0SAlex Zinenko     const ModuleTranslation &moduleTranslation) {
11033a3a91bSChristian Sigg   if (!attr)
11133a3a91bSChristian Sigg     return llvm::UndefValue::get(llvmType);
112a4a42160SAlex Zinenko   if (llvmType->isStructTy()) {
113a4a42160SAlex Zinenko     emitError(loc, "struct types are not supported in constants");
114a4a42160SAlex Zinenko     return nullptr;
115a4a42160SAlex Zinenko   }
116ac9d742bSStephan Herhut   // For integer types, we allow a mismatch in sizes as the index type in
117ac9d742bSStephan Herhut   // MLIR might have a different size than the index type in the LLVM module.
1185d7231d8SStephan Herhut   if (auto intAttr = attr.dyn_cast<IntegerAttr>())
119ac9d742bSStephan Herhut     return llvm::ConstantInt::get(
120ac9d742bSStephan Herhut         llvmType,
121ac9d742bSStephan Herhut         intAttr.getValue().sextOrTrunc(llvmType->getIntegerBitWidth()));
1225d7231d8SStephan Herhut   if (auto floatAttr = attr.dyn_cast<FloatAttr>())
1235d7231d8SStephan Herhut     return llvm::ConstantFP::get(llvmType, floatAttr.getValue());
1249b9c647cSRiver Riddle   if (auto funcAttr = attr.dyn_cast<FlatSymbolRefAttr>())
125176379e0SAlex Zinenko     return llvm::ConstantExpr::getBitCast(
126176379e0SAlex Zinenko         moduleTranslation.lookupFunction(funcAttr.getValue()), llvmType);
1275d7231d8SStephan Herhut   if (auto splatAttr = attr.dyn_cast<SplatElementsAttr>()) {
12868b03aeeSEli Friedman     llvm::Type *elementType;
12968b03aeeSEli Friedman     uint64_t numElements;
13068b03aeeSEli Friedman     if (auto *arrayTy = dyn_cast<llvm::ArrayType>(llvmType)) {
13168b03aeeSEli Friedman       elementType = arrayTy->getElementType();
13268b03aeeSEli Friedman       numElements = arrayTy->getNumElements();
13368b03aeeSEli Friedman     } else {
1345cba1c63SChristopher Tetreault       auto *vectorTy = cast<llvm::FixedVectorType>(llvmType);
13568b03aeeSEli Friedman       elementType = vectorTy->getElementType();
13668b03aeeSEli Friedman       numElements = vectorTy->getNumElements();
13768b03aeeSEli Friedman     }
138d6ea8ff0SAlex Zinenko     // Splat value is a scalar. Extract it only if the element type is not
139d6ea8ff0SAlex Zinenko     // another sequence type. The recursion terminates because each step removes
140d6ea8ff0SAlex Zinenko     // one outer sequential type.
14168b03aeeSEli Friedman     bool elementTypeSequential =
142d891d738SRahul Joshi         isa<llvm::ArrayType, llvm::VectorType>(elementType);
143d6ea8ff0SAlex Zinenko     llvm::Constant *child = getLLVMConstant(
144d6ea8ff0SAlex Zinenko         elementType,
145176379e0SAlex Zinenko         elementTypeSequential ? splatAttr : splatAttr.getSplatValue(), loc,
146176379e0SAlex Zinenko         moduleTranslation);
147a4a42160SAlex Zinenko     if (!child)
148a4a42160SAlex Zinenko       return nullptr;
1492f13df13SMLIR Team     if (llvmType->isVectorTy())
150396a42d9SRiver Riddle       return llvm::ConstantVector::getSplat(
1510f95e731SAlex Zinenko           llvm::ElementCount::get(numElements, /*Scalable=*/false), child);
1522f13df13SMLIR Team     if (llvmType->isArrayTy()) {
153ac9d742bSStephan Herhut       auto *arrayType = llvm::ArrayType::get(elementType, numElements);
1542f13df13SMLIR Team       SmallVector<llvm::Constant *, 8> constants(numElements, child);
1552f13df13SMLIR Team       return llvm::ConstantArray::get(arrayType, constants);
1562f13df13SMLIR Team     }
1575d7231d8SStephan Herhut   }
158a4a42160SAlex Zinenko 
159d906f84bSRiver Riddle   if (auto elementsAttr = attr.dyn_cast<ElementsAttr>()) {
160a4a42160SAlex Zinenko     assert(elementsAttr.getType().hasStaticShape());
161a4a42160SAlex Zinenko     assert(elementsAttr.getNumElements() != 0 &&
162a4a42160SAlex Zinenko            "unexpected empty elements attribute");
163a4a42160SAlex Zinenko     assert(!elementsAttr.getType().getShape().empty() &&
164a4a42160SAlex Zinenko            "unexpected empty elements attribute shape");
165a4a42160SAlex Zinenko 
1665d7231d8SStephan Herhut     SmallVector<llvm::Constant *, 8> constants;
167a4a42160SAlex Zinenko     constants.reserve(elementsAttr.getNumElements());
168a4a42160SAlex Zinenko     llvm::Type *innermostType = getInnermostElementType(llvmType);
169d906f84bSRiver Riddle     for (auto n : elementsAttr.getValues<Attribute>()) {
170176379e0SAlex Zinenko       constants.push_back(
171176379e0SAlex Zinenko           getLLVMConstant(innermostType, n, loc, moduleTranslation));
1725d7231d8SStephan Herhut       if (!constants.back())
1735d7231d8SStephan Herhut         return nullptr;
1745d7231d8SStephan Herhut     }
175a4a42160SAlex Zinenko     ArrayRef<llvm::Constant *> constantsRef = constants;
176a4a42160SAlex Zinenko     llvm::Constant *result = buildSequentialConstant(
177a4a42160SAlex Zinenko         constantsRef, elementsAttr.getType().getShape(), llvmType, loc);
178a4a42160SAlex Zinenko     assert(constantsRef.empty() && "did not consume all elemental constants");
179a4a42160SAlex Zinenko     return result;
1802f13df13SMLIR Team   }
181a4a42160SAlex Zinenko 
182cb348dffSStephan Herhut   if (auto stringAttr = attr.dyn_cast<StringAttr>()) {
183cb348dffSStephan Herhut     return llvm::ConstantDataArray::get(
184176379e0SAlex Zinenko         moduleTranslation.getLLVMContext(),
185176379e0SAlex Zinenko         ArrayRef<char>{stringAttr.getValue().data(),
186cb348dffSStephan Herhut                        stringAttr.getValue().size()});
187cb348dffSStephan Herhut   }
188a4c3a645SRiver Riddle   emitError(loc, "unsupported constant value");
1895d7231d8SStephan Herhut   return nullptr;
1905d7231d8SStephan Herhut }
1915d7231d8SStephan Herhut 
192c33d6970SRiver Riddle ModuleTranslation::ModuleTranslation(Operation *module,
193c33d6970SRiver Riddle                                      std::unique_ptr<llvm::Module> llvmModule)
194c33d6970SRiver Riddle     : mlirModule(module), llvmModule(std::move(llvmModule)),
195c33d6970SRiver Riddle       debugTranslation(
19692a295ebSKiran Chandramohan           std::make_unique<DebugTranslation>(module, *this->llvmModule)),
197b77bac05SAlex Zinenko       typeTranslator(this->llvmModule->getContext()),
198b77bac05SAlex Zinenko       iface(module->getContext()) {
199c33d6970SRiver Riddle   assert(satisfiesLLVMModule(mlirModule) &&
200c33d6970SRiver Riddle          "mlirModule should honor LLVM's module semantics.");
201c33d6970SRiver Riddle }
202d9067dcaSKiran Chandramohan ModuleTranslation::~ModuleTranslation() {
203d9067dcaSKiran Chandramohan   if (ompBuilder)
204d9067dcaSKiran Chandramohan     ompBuilder->finalize();
205d9067dcaSKiran Chandramohan }
206d9067dcaSKiran Chandramohan 
207d9067dcaSKiran Chandramohan /// Get the SSA value passed to the current block from the terminator operation
208d9067dcaSKiran Chandramohan /// of its predecessor.
209d9067dcaSKiran Chandramohan static Value getPHISourceValue(Block *current, Block *pred,
210d9067dcaSKiran Chandramohan                                unsigned numArguments, unsigned index) {
211d9067dcaSKiran Chandramohan   Operation &terminator = *pred->getTerminator();
212d9067dcaSKiran Chandramohan   if (isa<LLVM::BrOp>(terminator))
213d9067dcaSKiran Chandramohan     return terminator.getOperand(index);
214d9067dcaSKiran Chandramohan 
21514f24155SBrian Gesiak   SuccessorRange successors = terminator.getSuccessors();
21614f24155SBrian Gesiak   assert(std::adjacent_find(successors.begin(), successors.end()) ==
21714f24155SBrian Gesiak              successors.end() &&
21814f24155SBrian Gesiak          "successors with arguments in LLVM branches must be different blocks");
21958f2b765SChristian Sigg   (void)successors;
220d9067dcaSKiran Chandramohan 
22114f24155SBrian Gesiak   // For instructions that branch based on a condition value, we need to take
22214f24155SBrian Gesiak   // the operands for the branch that was taken.
22314f24155SBrian Gesiak   if (auto condBranchOp = dyn_cast<LLVM::CondBrOp>(terminator)) {
22414f24155SBrian Gesiak     // For conditional branches, we take the operands from either the "true" or
22514f24155SBrian Gesiak     // the "false" branch.
226d9067dcaSKiran Chandramohan     return condBranchOp.getSuccessor(0) == current
227d9067dcaSKiran Chandramohan                ? condBranchOp.trueDestOperands()[index]
228d9067dcaSKiran Chandramohan                : condBranchOp.falseDestOperands()[index];
2290881a4f1SAlex Zinenko   }
2300881a4f1SAlex Zinenko 
2310881a4f1SAlex Zinenko   if (auto switchOp = dyn_cast<LLVM::SwitchOp>(terminator)) {
23214f24155SBrian Gesiak     // For switches, we take the operands from either the default case, or from
23314f24155SBrian Gesiak     // the case branch that was taken.
23414f24155SBrian Gesiak     if (switchOp.defaultDestination() == current)
23514f24155SBrian Gesiak       return switchOp.defaultOperands()[index];
23614f24155SBrian Gesiak     for (auto i : llvm::enumerate(switchOp.caseDestinations()))
23714f24155SBrian Gesiak       if (i.value() == current)
23814f24155SBrian Gesiak         return switchOp.getCaseOperands(i.index())[index];
23914f24155SBrian Gesiak   }
24014f24155SBrian Gesiak 
24114f24155SBrian Gesiak   llvm_unreachable("only branch or switch operations can be terminators of a "
24214f24155SBrian Gesiak                    "block that has successors");
243d9067dcaSKiran Chandramohan }
244d9067dcaSKiran Chandramohan 
245d9067dcaSKiran Chandramohan /// Connect the PHI nodes to the results of preceding blocks.
24666900b3eSAlex Zinenko void mlir::LLVM::detail::connectPHINodes(Region &region,
24766900b3eSAlex Zinenko                                          const ModuleTranslation &state) {
248d9067dcaSKiran Chandramohan   // Skip the first block, it cannot be branched to and its arguments correspond
249d9067dcaSKiran Chandramohan   // to the arguments of the LLVM function.
25066900b3eSAlex Zinenko   for (auto it = std::next(region.begin()), eit = region.end(); it != eit;
25166900b3eSAlex Zinenko        ++it) {
252d9067dcaSKiran Chandramohan     Block *bb = &*it;
2530881a4f1SAlex Zinenko     llvm::BasicBlock *llvmBB = state.lookupBlock(bb);
254d9067dcaSKiran Chandramohan     auto phis = llvmBB->phis();
255d9067dcaSKiran Chandramohan     auto numArguments = bb->getNumArguments();
256d9067dcaSKiran Chandramohan     assert(numArguments == std::distance(phis.begin(), phis.end()));
257d9067dcaSKiran Chandramohan     for (auto &numberedPhiNode : llvm::enumerate(phis)) {
258d9067dcaSKiran Chandramohan       auto &phiNode = numberedPhiNode.value();
259d9067dcaSKiran Chandramohan       unsigned index = numberedPhiNode.index();
260d9067dcaSKiran Chandramohan       for (auto *pred : bb->getPredecessors()) {
261db884dafSAlex Zinenko         // Find the LLVM IR block that contains the converted terminator
262db884dafSAlex Zinenko         // instruction and use it in the PHI node. Note that this block is not
2630881a4f1SAlex Zinenko         // necessarily the same as state.lookupBlock(pred), some operations
264db884dafSAlex Zinenko         // (in particular, OpenMP operations using OpenMPIRBuilder) may have
265db884dafSAlex Zinenko         // split the blocks.
266db884dafSAlex Zinenko         llvm::Instruction *terminator =
2670881a4f1SAlex Zinenko             state.lookupBranch(pred->getTerminator());
268db884dafSAlex Zinenko         assert(terminator && "missing the mapping for a terminator");
2690881a4f1SAlex Zinenko         phiNode.addIncoming(
2700881a4f1SAlex Zinenko             state.lookupValue(getPHISourceValue(bb, pred, numArguments, index)),
271db884dafSAlex Zinenko             terminator->getParent());
272d9067dcaSKiran Chandramohan       }
273d9067dcaSKiran Chandramohan     }
274d9067dcaSKiran Chandramohan   }
275d9067dcaSKiran Chandramohan }
276d9067dcaSKiran Chandramohan 
277d9067dcaSKiran Chandramohan /// Sort function blocks topologically.
278*4efb7754SRiver Riddle SetVector<Block *>
27966900b3eSAlex Zinenko mlir::LLVM::detail::getTopologicallySortedBlocks(Region &region) {
280d4568ed7SGeorge Mitenkov   // For each block that has not been visited yet (i.e. that has no
281d4568ed7SGeorge Mitenkov   // predecessors), add it to the list as well as its successors.
282*4efb7754SRiver Riddle   SetVector<Block *> blocks;
28366900b3eSAlex Zinenko   for (Block &b : region) {
284d4568ed7SGeorge Mitenkov     if (blocks.count(&b) == 0) {
285d4568ed7SGeorge Mitenkov       llvm::ReversePostOrderTraversal<Block *> traversal(&b);
286d4568ed7SGeorge Mitenkov       blocks.insert(traversal.begin(), traversal.end());
287d4568ed7SGeorge Mitenkov     }
288d9067dcaSKiran Chandramohan   }
28966900b3eSAlex Zinenko   assert(blocks.size() == region.getBlocks().size() &&
29066900b3eSAlex Zinenko          "some blocks are not sorted");
291d9067dcaSKiran Chandramohan 
292d9067dcaSKiran Chandramohan   return blocks;
293d9067dcaSKiran Chandramohan }
294d9067dcaSKiran Chandramohan 
295176379e0SAlex Zinenko llvm::Value *mlir::LLVM::detail::createIntrinsicCall(
296176379e0SAlex Zinenko     llvm::IRBuilderBase &builder, llvm::Intrinsic::ID intrinsic,
297176379e0SAlex Zinenko     ArrayRef<llvm::Value *> args, ArrayRef<llvm::Type *> tys) {
298176379e0SAlex Zinenko   llvm::Module *module = builder.GetInsertBlock()->getModule();
299176379e0SAlex Zinenko   llvm::Function *fn = llvm::Intrinsic::getDeclaration(module, intrinsic, tys);
300176379e0SAlex Zinenko   return builder.CreateCall(fn, args);
301176379e0SAlex Zinenko }
302176379e0SAlex Zinenko 
3032666b973SRiver Riddle /// Given a single MLIR operation, create the corresponding LLVM IR operation
304176379e0SAlex Zinenko /// using the `builder`.
305ce8f10d6SAlex Zinenko LogicalResult
30638b106f6SMehdi Amini ModuleTranslation::convertOperation(Operation &op,
307ce8f10d6SAlex Zinenko                                     llvm::IRBuilderBase &builder) {
30838b106f6SMehdi Amini   const LLVMTranslationDialectInterface *opIface = iface.getInterfaceFor(&op);
30938b106f6SMehdi Amini   if (!opIface)
31038b106f6SMehdi Amini     return op.emitError("cannot be converted to LLVM IR: missing "
31138b106f6SMehdi Amini                         "`LLVMTranslationDialectInterface` registration for "
31238b106f6SMehdi Amini                         "dialect for op: ")
31338b106f6SMehdi Amini            << op.getName();
314176379e0SAlex Zinenko 
31538b106f6SMehdi Amini   if (failed(opIface->convertOperation(&op, builder, *this)))
31638b106f6SMehdi Amini     return op.emitError("LLVM Translation failed for operation: ")
31738b106f6SMehdi Amini            << op.getName();
31838b106f6SMehdi Amini 
31938b106f6SMehdi Amini   return convertDialectAttributes(&op);
3205d7231d8SStephan Herhut }
3215d7231d8SStephan Herhut 
3222666b973SRiver Riddle /// Convert block to LLVM IR.  Unless `ignoreArguments` is set, emit PHI nodes
3232666b973SRiver Riddle /// to define values corresponding to the MLIR block arguments.  These nodes
32410164a2eSAlex Zinenko /// are not connected to the source basic blocks, which may not exist yet.  Uses
32510164a2eSAlex Zinenko /// `builder` to construct the LLVM IR. Expects the LLVM IR basic block to have
32610164a2eSAlex Zinenko /// been created for `bb` and included in the block mapping.  Inserts new
32710164a2eSAlex Zinenko /// instructions at the end of the block and leaves `builder` in a state
32810164a2eSAlex Zinenko /// suitable for further insertion into the end of the block.
32910164a2eSAlex Zinenko LogicalResult ModuleTranslation::convertBlock(Block &bb, bool ignoreArguments,
330ce8f10d6SAlex Zinenko                                               llvm::IRBuilderBase &builder) {
3310881a4f1SAlex Zinenko   builder.SetInsertPoint(lookupBlock(&bb));
332c33d6970SRiver Riddle   auto *subprogram = builder.GetInsertBlock()->getParent()->getSubprogram();
3335d7231d8SStephan Herhut 
3345d7231d8SStephan Herhut   // Before traversing operations, make block arguments available through
3355d7231d8SStephan Herhut   // value remapping and PHI nodes, but do not add incoming edges for the PHI
3365d7231d8SStephan Herhut   // nodes just yet: those values may be defined by this or following blocks.
3375d7231d8SStephan Herhut   // This step is omitted if "ignoreArguments" is set.  The arguments of the
3385d7231d8SStephan Herhut   // first block have been already made available through the remapping of
3395d7231d8SStephan Herhut   // LLVM function arguments.
3405d7231d8SStephan Herhut   if (!ignoreArguments) {
3415d7231d8SStephan Herhut     auto predecessors = bb.getPredecessors();
3425d7231d8SStephan Herhut     unsigned numPredecessors =
3435d7231d8SStephan Herhut         std::distance(predecessors.begin(), predecessors.end());
34435807bc4SRiver Riddle     for (auto arg : bb.getArguments()) {
345c69c9e0fSAlex Zinenko       auto wrappedType = arg.getType();
346c69c9e0fSAlex Zinenko       if (!isCompatibleType(wrappedType))
347baa1ec22SAlex Zinenko         return emitError(bb.front().getLoc(),
348a4c3a645SRiver Riddle                          "block argument does not have an LLVM type");
349aec38c61SAlex Zinenko       llvm::Type *type = convertType(wrappedType);
3505d7231d8SStephan Herhut       llvm::PHINode *phi = builder.CreatePHI(type, numPredecessors);
3510881a4f1SAlex Zinenko       mapValue(arg, phi);
3525d7231d8SStephan Herhut     }
3535d7231d8SStephan Herhut   }
3545d7231d8SStephan Herhut 
3555d7231d8SStephan Herhut   // Traverse operations.
3565d7231d8SStephan Herhut   for (auto &op : bb) {
357c33d6970SRiver Riddle     // Set the current debug location within the builder.
358c33d6970SRiver Riddle     builder.SetCurrentDebugLocation(
359c33d6970SRiver Riddle         debugTranslation->translateLoc(op.getLoc(), subprogram));
360c33d6970SRiver Riddle 
361baa1ec22SAlex Zinenko     if (failed(convertOperation(op, builder)))
362baa1ec22SAlex Zinenko       return failure();
3635d7231d8SStephan Herhut   }
3645d7231d8SStephan Herhut 
365baa1ec22SAlex Zinenko   return success();
3665d7231d8SStephan Herhut }
3675d7231d8SStephan Herhut 
368ce8f10d6SAlex Zinenko /// A helper method to get the single Block in an operation honoring LLVM's
369ce8f10d6SAlex Zinenko /// module requirements.
370ce8f10d6SAlex Zinenko static Block &getModuleBody(Operation *module) {
371ce8f10d6SAlex Zinenko   return module->getRegion(0).front();
372ce8f10d6SAlex Zinenko }
373ce8f10d6SAlex Zinenko 
374ffa455d4SJean Perier /// A helper method to decide if a constant must not be set as a global variable
375ffa455d4SJean Perier /// initializer.
376ffa455d4SJean Perier static bool shouldDropGlobalInitializer(llvm::GlobalValue::LinkageTypes linkage,
377ffa455d4SJean Perier                                         llvm::Constant *cst) {
378ffa455d4SJean Perier   return (linkage == llvm::GlobalVariable::ExternalLinkage &&
379ffa455d4SJean Perier           isa<llvm::UndefValue>(cst)) ||
380ffa455d4SJean Perier          linkage == llvm::GlobalVariable::ExternalWeakLinkage;
381ffa455d4SJean Perier }
382ffa455d4SJean Perier 
3832666b973SRiver Riddle /// Create named global variables that correspond to llvm.mlir.global
3842666b973SRiver Riddle /// definitions.
385efa2d533SAlex Zinenko LogicalResult ModuleTranslation::convertGlobals() {
38644fc7d72STres Popp   for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) {
387aec38c61SAlex Zinenko     llvm::Type *type = convertType(op.getType());
388250a11aeSJames Molloy     llvm::Constant *cst = llvm::UndefValue::get(type);
389250a11aeSJames Molloy     if (op.getValueOrNull()) {
39068451df2SAlex Zinenko       // String attributes are treated separately because they cannot appear as
39168451df2SAlex Zinenko       // in-function constants and are thus not supported by getLLVMConstant.
39233a3a91bSChristian Sigg       if (auto strAttr = op.getValueOrNull().dyn_cast_or_null<StringAttr>()) {
3932dd38b09SAlex Zinenko         cst = llvm::ConstantDataArray::getString(
39468451df2SAlex Zinenko             llvmModule->getContext(), strAttr.getValue(), /*AddNull=*/false);
3952dd38b09SAlex Zinenko         type = cst->getType();
396176379e0SAlex Zinenko       } else if (!(cst = getLLVMConstant(type, op.getValueOrNull(), op.getLoc(),
397176379e0SAlex Zinenko                                          *this))) {
398efa2d533SAlex Zinenko         return failure();
39968451df2SAlex Zinenko       }
400ffa455d4SJean Perier     }
401ffa455d4SJean Perier 
402ffa455d4SJean Perier     auto linkage = convertLinkageToLLVM(op.linkage());
403ffa455d4SJean Perier     auto addrSpace = op.addr_space();
404ffa455d4SJean Perier     auto *var = new llvm::GlobalVariable(
405ffa455d4SJean Perier         *llvmModule, type, op.constant(), linkage,
406ffa455d4SJean Perier         shouldDropGlobalInitializer(linkage, cst) ? nullptr : cst,
407ffa455d4SJean Perier         op.sym_name(),
408ffa455d4SJean Perier         /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal, addrSpace);
409ffa455d4SJean Perier 
410ffa455d4SJean Perier     globalsMapping.try_emplace(op, var);
411ffa455d4SJean Perier   }
412ffa455d4SJean Perier 
413ffa455d4SJean Perier   // Convert global variable bodies. This is done after all global variables
414ffa455d4SJean Perier   // have been created in LLVM IR because a global body may refer to another
415ffa455d4SJean Perier   // global or itself. So all global variables need to be mapped first.
416ffa455d4SJean Perier   for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) {
417ffa455d4SJean Perier     if (Block *initializer = op.getInitializerBlock()) {
418250a11aeSJames Molloy       llvm::IRBuilder<> builder(llvmModule->getContext());
419250a11aeSJames Molloy       for (auto &op : initializer->without_terminator()) {
420250a11aeSJames Molloy         if (failed(convertOperation(op, builder)) ||
4210881a4f1SAlex Zinenko             !isa<llvm::Constant>(lookupValue(op.getResult(0))))
422efa2d533SAlex Zinenko           return emitError(op.getLoc(), "unemittable constant value");
423250a11aeSJames Molloy       }
424250a11aeSJames Molloy       ReturnOp ret = cast<ReturnOp>(initializer->getTerminator());
425ffa455d4SJean Perier       llvm::Constant *cst =
426ffa455d4SJean Perier           cast<llvm::Constant>(lookupValue(ret.getOperand(0)));
427ffa455d4SJean Perier       auto *global = cast<llvm::GlobalVariable>(lookupGlobal(op));
428ffa455d4SJean Perier       if (!shouldDropGlobalInitializer(global->getLinkage(), cst))
429ffa455d4SJean Perier         global->setInitializer(cst);
430250a11aeSJames Molloy     }
431b9ff2dd8SAlex Zinenko   }
432efa2d533SAlex Zinenko 
433efa2d533SAlex Zinenko   return success();
434b9ff2dd8SAlex Zinenko }
435b9ff2dd8SAlex Zinenko 
4360a2131b7SAlex Zinenko /// Attempts to add an attribute identified by `key`, optionally with the given
4370a2131b7SAlex Zinenko /// `value` to LLVM function `llvmFunc`. Reports errors at `loc` if any. If the
4380a2131b7SAlex Zinenko /// attribute has a kind known to LLVM IR, create the attribute of this kind,
4390a2131b7SAlex Zinenko /// otherwise keep it as a string attribute. Performs additional checks for
4400a2131b7SAlex Zinenko /// attributes known to have or not have a value in order to avoid assertions
4410a2131b7SAlex Zinenko /// inside LLVM upon construction.
4420a2131b7SAlex Zinenko static LogicalResult checkedAddLLVMFnAttribute(Location loc,
4430a2131b7SAlex Zinenko                                                llvm::Function *llvmFunc,
4440a2131b7SAlex Zinenko                                                StringRef key,
4450a2131b7SAlex Zinenko                                                StringRef value = StringRef()) {
4460a2131b7SAlex Zinenko   auto kind = llvm::Attribute::getAttrKindFromName(key);
4470a2131b7SAlex Zinenko   if (kind == llvm::Attribute::None) {
4480a2131b7SAlex Zinenko     llvmFunc->addFnAttr(key, value);
4490a2131b7SAlex Zinenko     return success();
4500a2131b7SAlex Zinenko   }
4510a2131b7SAlex Zinenko 
4520a2131b7SAlex Zinenko   if (llvm::Attribute::doesAttrKindHaveArgument(kind)) {
4530a2131b7SAlex Zinenko     if (value.empty())
4540a2131b7SAlex Zinenko       return emitError(loc) << "LLVM attribute '" << key << "' expects a value";
4550a2131b7SAlex Zinenko 
4560a2131b7SAlex Zinenko     int result;
4570a2131b7SAlex Zinenko     if (!value.getAsInteger(/*Radix=*/0, result))
4580a2131b7SAlex Zinenko       llvmFunc->addFnAttr(
4590a2131b7SAlex Zinenko           llvm::Attribute::get(llvmFunc->getContext(), kind, result));
4600a2131b7SAlex Zinenko     else
4610a2131b7SAlex Zinenko       llvmFunc->addFnAttr(key, value);
4620a2131b7SAlex Zinenko     return success();
4630a2131b7SAlex Zinenko   }
4640a2131b7SAlex Zinenko 
4650a2131b7SAlex Zinenko   if (!value.empty())
4660a2131b7SAlex Zinenko     return emitError(loc) << "LLVM attribute '" << key
4670a2131b7SAlex Zinenko                           << "' does not expect a value, found '" << value
4680a2131b7SAlex Zinenko                           << "'";
4690a2131b7SAlex Zinenko 
4700a2131b7SAlex Zinenko   llvmFunc->addFnAttr(kind);
4710a2131b7SAlex Zinenko   return success();
4720a2131b7SAlex Zinenko }
4730a2131b7SAlex Zinenko 
4740a2131b7SAlex Zinenko /// Attaches the attributes listed in the given array attribute to `llvmFunc`.
4750a2131b7SAlex Zinenko /// Reports error to `loc` if any and returns immediately. Expects `attributes`
4760a2131b7SAlex Zinenko /// to be an array attribute containing either string attributes, treated as
4770a2131b7SAlex Zinenko /// value-less LLVM attributes, or array attributes containing two string
4780a2131b7SAlex Zinenko /// attributes, with the first string being the name of the corresponding LLVM
4790a2131b7SAlex Zinenko /// attribute and the second string beings its value. Note that even integer
4800a2131b7SAlex Zinenko /// attributes are expected to have their values expressed as strings.
4810a2131b7SAlex Zinenko static LogicalResult
4820a2131b7SAlex Zinenko forwardPassthroughAttributes(Location loc, Optional<ArrayAttr> attributes,
4830a2131b7SAlex Zinenko                              llvm::Function *llvmFunc) {
4840a2131b7SAlex Zinenko   if (!attributes)
4850a2131b7SAlex Zinenko     return success();
4860a2131b7SAlex Zinenko 
4870a2131b7SAlex Zinenko   for (Attribute attr : *attributes) {
4880a2131b7SAlex Zinenko     if (auto stringAttr = attr.dyn_cast<StringAttr>()) {
4890a2131b7SAlex Zinenko       if (failed(
4900a2131b7SAlex Zinenko               checkedAddLLVMFnAttribute(loc, llvmFunc, stringAttr.getValue())))
4910a2131b7SAlex Zinenko         return failure();
4920a2131b7SAlex Zinenko       continue;
4930a2131b7SAlex Zinenko     }
4940a2131b7SAlex Zinenko 
4950a2131b7SAlex Zinenko     auto arrayAttr = attr.dyn_cast<ArrayAttr>();
4960a2131b7SAlex Zinenko     if (!arrayAttr || arrayAttr.size() != 2)
4970a2131b7SAlex Zinenko       return emitError(loc)
4980a2131b7SAlex Zinenko              << "expected 'passthrough' to contain string or array attributes";
4990a2131b7SAlex Zinenko 
5000a2131b7SAlex Zinenko     auto keyAttr = arrayAttr[0].dyn_cast<StringAttr>();
5010a2131b7SAlex Zinenko     auto valueAttr = arrayAttr[1].dyn_cast<StringAttr>();
5020a2131b7SAlex Zinenko     if (!keyAttr || !valueAttr)
5030a2131b7SAlex Zinenko       return emitError(loc)
5040a2131b7SAlex Zinenko              << "expected arrays within 'passthrough' to contain two strings";
5050a2131b7SAlex Zinenko 
5060a2131b7SAlex Zinenko     if (failed(checkedAddLLVMFnAttribute(loc, llvmFunc, keyAttr.getValue(),
5070a2131b7SAlex Zinenko                                          valueAttr.getValue())))
5080a2131b7SAlex Zinenko       return failure();
5090a2131b7SAlex Zinenko   }
5100a2131b7SAlex Zinenko   return success();
5110a2131b7SAlex Zinenko }
5120a2131b7SAlex Zinenko 
5135e7959a3SAlex Zinenko LogicalResult ModuleTranslation::convertOneFunction(LLVMFuncOp func) {
514db884dafSAlex Zinenko   // Clear the block, branch value mappings, they are only relevant within one
5155d7231d8SStephan Herhut   // function.
5165d7231d8SStephan Herhut   blockMapping.clear();
5175d7231d8SStephan Herhut   valueMapping.clear();
518db884dafSAlex Zinenko   branchMapping.clear();
5190881a4f1SAlex Zinenko   llvm::Function *llvmFunc = lookupFunction(func.getName());
520c33d6970SRiver Riddle 
521c33d6970SRiver Riddle   // Translate the debug information for this function.
522c33d6970SRiver Riddle   debugTranslation->translate(func, *llvmFunc);
523c33d6970SRiver Riddle 
5245d7231d8SStephan Herhut   // Add function arguments to the value remapping table.
5255d7231d8SStephan Herhut   // If there was noalias info then we decorate each argument accordingly.
5265d7231d8SStephan Herhut   unsigned int argIdx = 0;
527eeef50b1SFangrui Song   for (auto kvp : llvm::zip(func.getArguments(), llvmFunc->args())) {
5285d7231d8SStephan Herhut     llvm::Argument &llvmArg = std::get<1>(kvp);
529e62a6956SRiver Riddle     BlockArgument mlirArg = std::get<0>(kvp);
5305d7231d8SStephan Herhut 
53167cc5cecSStephan Herhut     if (auto attr = func.getArgAttrOfType<BoolAttr>(
53267cc5cecSStephan Herhut             argIdx, LLVMDialect::getNoAliasAttrName())) {
5335d7231d8SStephan Herhut       // NB: Attribute already verified to be boolean, so check if we can indeed
5345d7231d8SStephan Herhut       // attach the attribute to this argument, based on its type.
535c69c9e0fSAlex Zinenko       auto argTy = mlirArg.getType();
5368de43b92SAlex Zinenko       if (!argTy.isa<LLVM::LLVMPointerType>())
537baa1ec22SAlex Zinenko         return func.emitError(
5385d7231d8SStephan Herhut             "llvm.noalias attribute attached to LLVM non-pointer argument");
5395d7231d8SStephan Herhut       if (attr.getValue())
5405d7231d8SStephan Herhut         llvmArg.addAttr(llvm::Attribute::AttrKind::NoAlias);
5415d7231d8SStephan Herhut     }
5422416e28cSStephan Herhut 
54367cc5cecSStephan Herhut     if (auto attr = func.getArgAttrOfType<IntegerAttr>(
54467cc5cecSStephan Herhut             argIdx, LLVMDialect::getAlignAttrName())) {
5452416e28cSStephan Herhut       // NB: Attribute already verified to be int, so check if we can indeed
5462416e28cSStephan Herhut       // attach the attribute to this argument, based on its type.
547c69c9e0fSAlex Zinenko       auto argTy = mlirArg.getType();
5488de43b92SAlex Zinenko       if (!argTy.isa<LLVM::LLVMPointerType>())
5492416e28cSStephan Herhut         return func.emitError(
5502416e28cSStephan Herhut             "llvm.align attribute attached to LLVM non-pointer argument");
5512416e28cSStephan Herhut       llvmArg.addAttrs(
5522416e28cSStephan Herhut           llvm::AttrBuilder().addAlignmentAttr(llvm::Align(attr.getInt())));
5532416e28cSStephan Herhut     }
5542416e28cSStephan Herhut 
55570b841acSEric Schweitz     if (auto attr = func.getArgAttrOfType<UnitAttr>(argIdx, "llvm.sret")) {
55670b841acSEric Schweitz       auto argTy = mlirArg.getType();
55770b841acSEric Schweitz       if (!argTy.isa<LLVM::LLVMPointerType>())
55870b841acSEric Schweitz         return func.emitError(
55970b841acSEric Schweitz             "llvm.sret attribute attached to LLVM non-pointer argument");
5601d6df1fcSEric Schweitz       llvmArg.addAttrs(llvm::AttrBuilder().addStructRetAttr(
5611d6df1fcSEric Schweitz           llvmArg.getType()->getPointerElementType()));
56270b841acSEric Schweitz     }
56370b841acSEric Schweitz 
56470b841acSEric Schweitz     if (auto attr = func.getArgAttrOfType<UnitAttr>(argIdx, "llvm.byval")) {
56570b841acSEric Schweitz       auto argTy = mlirArg.getType();
56670b841acSEric Schweitz       if (!argTy.isa<LLVM::LLVMPointerType>())
56770b841acSEric Schweitz         return func.emitError(
56870b841acSEric Schweitz             "llvm.byval attribute attached to LLVM non-pointer argument");
5691d6df1fcSEric Schweitz       llvmArg.addAttrs(llvm::AttrBuilder().addByValAttr(
5701d6df1fcSEric Schweitz           llvmArg.getType()->getPointerElementType()));
57170b841acSEric Schweitz     }
57270b841acSEric Schweitz 
5730881a4f1SAlex Zinenko     mapValue(mlirArg, &llvmArg);
5745d7231d8SStephan Herhut     argIdx++;
5755d7231d8SStephan Herhut   }
5765d7231d8SStephan Herhut 
577ff77397fSShraiysh Vaishay   // Check the personality and set it.
578ff77397fSShraiysh Vaishay   if (func.personality().hasValue()) {
579ff77397fSShraiysh Vaishay     llvm::Type *ty = llvm::Type::getInt8PtrTy(llvmFunc->getContext());
580ff77397fSShraiysh Vaishay     if (llvm::Constant *pfunc =
581176379e0SAlex Zinenko             getLLVMConstant(ty, func.personalityAttr(), func.getLoc(), *this))
582ff77397fSShraiysh Vaishay       llvmFunc->setPersonalityFn(pfunc);
583ff77397fSShraiysh Vaishay   }
584ff77397fSShraiysh Vaishay 
5855d7231d8SStephan Herhut   // First, create all blocks so we can jump to them.
5865d7231d8SStephan Herhut   llvm::LLVMContext &llvmContext = llvmFunc->getContext();
5875d7231d8SStephan Herhut   for (auto &bb : func) {
5885d7231d8SStephan Herhut     auto *llvmBB = llvm::BasicBlock::Create(llvmContext);
5895d7231d8SStephan Herhut     llvmBB->insertInto(llvmFunc);
5900881a4f1SAlex Zinenko     mapBlock(&bb, llvmBB);
5915d7231d8SStephan Herhut   }
5925d7231d8SStephan Herhut 
5935d7231d8SStephan Herhut   // Then, convert blocks one by one in topological order to ensure defs are
5945d7231d8SStephan Herhut   // converted before uses.
59566900b3eSAlex Zinenko   auto blocks = detail::getTopologicallySortedBlocks(func.getBody());
59610164a2eSAlex Zinenko   for (Block *bb : blocks) {
59710164a2eSAlex Zinenko     llvm::IRBuilder<> builder(llvmContext);
59810164a2eSAlex Zinenko     if (failed(convertBlock(*bb, bb->isEntryBlock(), builder)))
599baa1ec22SAlex Zinenko       return failure();
6005d7231d8SStephan Herhut   }
6015d7231d8SStephan Herhut 
602176379e0SAlex Zinenko   // After all blocks have been traversed and values mapped, connect the PHI
603176379e0SAlex Zinenko   // nodes to the results of preceding blocks.
60466900b3eSAlex Zinenko   detail::connectPHINodes(func.getBody(), *this);
605176379e0SAlex Zinenko 
606176379e0SAlex Zinenko   // Finally, convert dialect attributes attached to the function.
607176379e0SAlex Zinenko   return convertDialectAttributes(func);
608176379e0SAlex Zinenko }
609176379e0SAlex Zinenko 
610176379e0SAlex Zinenko LogicalResult ModuleTranslation::convertDialectAttributes(Operation *op) {
611176379e0SAlex Zinenko   for (NamedAttribute attribute : op->getDialectAttrs())
612176379e0SAlex Zinenko     if (failed(iface.amendOperation(op, attribute, *this)))
613176379e0SAlex Zinenko       return failure();
614baa1ec22SAlex Zinenko   return success();
6155d7231d8SStephan Herhut }
6165d7231d8SStephan Herhut 
617ce8f10d6SAlex Zinenko /// Check whether the module contains only supported ops directly in its body.
618ce8f10d6SAlex Zinenko static LogicalResult checkSupportedModuleOps(Operation *m) {
61944fc7d72STres Popp   for (Operation &o : getModuleBody(m).getOperations())
6204a2930f4SArpith C. Jacob     if (!isa<LLVM::LLVMFuncOp, LLVM::GlobalOp, LLVM::MetadataOp>(&o) &&
621fe7c0d90SRiver Riddle         !o.hasTrait<OpTrait::IsTerminator>())
6224dde19f0SAlex Zinenko       return o.emitOpError("unsupported module-level operation");
6234dde19f0SAlex Zinenko   return success();
6244dde19f0SAlex Zinenko }
6254dde19f0SAlex Zinenko 
626a084b94fSSean Silva LogicalResult ModuleTranslation::convertFunctionSignatures() {
6275d7231d8SStephan Herhut   // Declare all functions first because there may be function calls that form a
628a084b94fSSean Silva   // call graph with cycles, or global initializers that reference functions.
62944fc7d72STres Popp   for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) {
6305e7959a3SAlex Zinenko     llvm::FunctionCallee llvmFuncCst = llvmModule->getOrInsertFunction(
6315e7959a3SAlex Zinenko         function.getName(),
632aec38c61SAlex Zinenko         cast<llvm::FunctionType>(convertType(function.getType())));
6330a2131b7SAlex Zinenko     llvm::Function *llvmFunc = cast<llvm::Function>(llvmFuncCst.getCallee());
634ebbdecddSAlex Zinenko     llvmFunc->setLinkage(convertLinkageToLLVM(function.linkage()));
6350881a4f1SAlex Zinenko     mapFunction(function.getName(), llvmFunc);
6360a2131b7SAlex Zinenko 
6370a2131b7SAlex Zinenko     // Forward the pass-through attributes to LLVM.
6380a2131b7SAlex Zinenko     if (failed(forwardPassthroughAttributes(function.getLoc(),
6390a2131b7SAlex Zinenko                                             function.passthrough(), llvmFunc)))
6400a2131b7SAlex Zinenko       return failure();
6415d7231d8SStephan Herhut   }
6425d7231d8SStephan Herhut 
643a084b94fSSean Silva   return success();
644a084b94fSSean Silva }
645a084b94fSSean Silva 
646a084b94fSSean Silva LogicalResult ModuleTranslation::convertFunctions() {
6475d7231d8SStephan Herhut   // Convert functions.
64844fc7d72STres Popp   for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) {
6495d7231d8SStephan Herhut     // Ignore external functions.
6505d7231d8SStephan Herhut     if (function.isExternal())
6515d7231d8SStephan Herhut       continue;
6525d7231d8SStephan Herhut 
653baa1ec22SAlex Zinenko     if (failed(convertOneFunction(function)))
654baa1ec22SAlex Zinenko       return failure();
6555d7231d8SStephan Herhut   }
6565d7231d8SStephan Herhut 
657baa1ec22SAlex Zinenko   return success();
6585d7231d8SStephan Herhut }
6595d7231d8SStephan Herhut 
6604a2930f4SArpith C. Jacob llvm::MDNode *
6614a2930f4SArpith C. Jacob ModuleTranslation::getAccessGroup(Operation &opInst,
6624a2930f4SArpith C. Jacob                                   SymbolRefAttr accessGroupRef) const {
6634a2930f4SArpith C. Jacob   auto metadataName = accessGroupRef.getRootReference();
6644a2930f4SArpith C. Jacob   auto accessGroupName = accessGroupRef.getLeafReference();
6654a2930f4SArpith C. Jacob   auto metadataOp = SymbolTable::lookupNearestSymbolFrom<LLVM::MetadataOp>(
6664a2930f4SArpith C. Jacob       opInst.getParentOp(), metadataName);
6674a2930f4SArpith C. Jacob   auto *accessGroupOp =
6684a2930f4SArpith C. Jacob       SymbolTable::lookupNearestSymbolFrom(metadataOp, accessGroupName);
6694a2930f4SArpith C. Jacob   return accessGroupMetadataMapping.lookup(accessGroupOp);
6704a2930f4SArpith C. Jacob }
6714a2930f4SArpith C. Jacob 
6724a2930f4SArpith C. Jacob LogicalResult ModuleTranslation::createAccessGroupMetadata() {
6734a2930f4SArpith C. Jacob   mlirModule->walk([&](LLVM::MetadataOp metadatas) {
6744a2930f4SArpith C. Jacob     metadatas.walk([&](LLVM::AccessGroupMetadataOp op) {
6754a2930f4SArpith C. Jacob       llvm::LLVMContext &ctx = llvmModule->getContext();
6764a2930f4SArpith C. Jacob       llvm::MDNode *accessGroup = llvm::MDNode::getDistinct(ctx, {});
6774a2930f4SArpith C. Jacob       accessGroupMetadataMapping.insert({op, accessGroup});
6784a2930f4SArpith C. Jacob     });
6794a2930f4SArpith C. Jacob   });
6804a2930f4SArpith C. Jacob   return success();
6814a2930f4SArpith C. Jacob }
6824a2930f4SArpith C. Jacob 
6834e393350SArpith C. Jacob void ModuleTranslation::setAccessGroupsMetadata(Operation *op,
6844e393350SArpith C. Jacob                                                 llvm::Instruction *inst) {
6854e393350SArpith C. Jacob   auto accessGroups =
6864e393350SArpith C. Jacob       op->getAttrOfType<ArrayAttr>(LLVMDialect::getAccessGroupsAttrName());
6874e393350SArpith C. Jacob   if (accessGroups && !accessGroups.empty()) {
6884e393350SArpith C. Jacob     llvm::Module *module = inst->getModule();
6894e393350SArpith C. Jacob     SmallVector<llvm::Metadata *> metadatas;
6904e393350SArpith C. Jacob     for (SymbolRefAttr accessGroupRef :
6914e393350SArpith C. Jacob          accessGroups.getAsRange<SymbolRefAttr>())
6924e393350SArpith C. Jacob       metadatas.push_back(getAccessGroup(*op, accessGroupRef));
6934e393350SArpith C. Jacob 
6944e393350SArpith C. Jacob     llvm::MDNode *unionMD = nullptr;
6954e393350SArpith C. Jacob     if (metadatas.size() == 1)
6964e393350SArpith C. Jacob       unionMD = llvm::cast<llvm::MDNode>(metadatas.front());
6974e393350SArpith C. Jacob     else if (metadatas.size() >= 2)
6984e393350SArpith C. Jacob       unionMD = llvm::MDNode::get(module->getContext(), metadatas);
6994e393350SArpith C. Jacob 
7004e393350SArpith C. Jacob     inst->setMetadata(module->getMDKindID("llvm.access.group"), unionMD);
7014e393350SArpith C. Jacob   }
7024e393350SArpith C. Jacob }
7034e393350SArpith C. Jacob 
704c69c9e0fSAlex Zinenko llvm::Type *ModuleTranslation::convertType(Type type) {
705b2ab375dSAlex Zinenko   return typeTranslator.translateType(type);
706aec38c61SAlex Zinenko }
707aec38c61SAlex Zinenko 
708efadb6b8SAlex Zinenko /// A helper to look up remapped operands in the value remapping table.`
709efadb6b8SAlex Zinenko SmallVector<llvm::Value *, 8>
710efadb6b8SAlex Zinenko ModuleTranslation::lookupValues(ValueRange values) {
711efadb6b8SAlex Zinenko   SmallVector<llvm::Value *, 8> remapped;
712efadb6b8SAlex Zinenko   remapped.reserve(values.size());
7130881a4f1SAlex Zinenko   for (Value v : values)
7140881a4f1SAlex Zinenko     remapped.push_back(lookupValue(v));
715efadb6b8SAlex Zinenko   return remapped;
716efadb6b8SAlex Zinenko }
717efadb6b8SAlex Zinenko 
71866900b3eSAlex Zinenko const llvm::DILocation *
71966900b3eSAlex Zinenko ModuleTranslation::translateLoc(Location loc, llvm::DILocalScope *scope) {
72066900b3eSAlex Zinenko   return debugTranslation->translateLoc(loc, scope);
72166900b3eSAlex Zinenko }
72266900b3eSAlex Zinenko 
723176379e0SAlex Zinenko llvm::NamedMDNode *
724176379e0SAlex Zinenko ModuleTranslation::getOrInsertNamedModuleMetadata(StringRef name) {
725176379e0SAlex Zinenko   return llvmModule->getOrInsertNamedMetadata(name);
726176379e0SAlex Zinenko }
727176379e0SAlex Zinenko 
728ce8f10d6SAlex Zinenko static std::unique_ptr<llvm::Module>
729ce8f10d6SAlex Zinenko prepareLLVMModule(Operation *m, llvm::LLVMContext &llvmContext,
730ce8f10d6SAlex Zinenko                   StringRef name) {
731f9dc2b70SMehdi Amini   m->getContext()->getOrLoadDialect<LLVM::LLVMDialect>();
732db1c197bSAlex Zinenko   auto llvmModule = std::make_unique<llvm::Module>(name, llvmContext);
733168213f9SAlex Zinenko   if (auto dataLayoutAttr =
734168213f9SAlex Zinenko           m->getAttr(LLVM::LLVMDialect::getDataLayoutAttrName()))
735168213f9SAlex Zinenko     llvmModule->setDataLayout(dataLayoutAttr.cast<StringAttr>().getValue());
7365dd5a083SNicolas Vasilache   if (auto targetTripleAttr =
7375dd5a083SNicolas Vasilache           m->getAttr(LLVM::LLVMDialect::getTargetTripleAttrName()))
7385dd5a083SNicolas Vasilache     llvmModule->setTargetTriple(targetTripleAttr.cast<StringAttr>().getValue());
7395d7231d8SStephan Herhut 
7405d7231d8SStephan Herhut   // Inject declarations for `malloc` and `free` functions that can be used in
7415d7231d8SStephan Herhut   // memref allocation/deallocation coming from standard ops lowering.
742db1c197bSAlex Zinenko   llvm::IRBuilder<> builder(llvmContext);
7435d7231d8SStephan Herhut   llvmModule->getOrInsertFunction("malloc", builder.getInt8PtrTy(),
7445d7231d8SStephan Herhut                                   builder.getInt64Ty());
7455d7231d8SStephan Herhut   llvmModule->getOrInsertFunction("free", builder.getVoidTy(),
7465d7231d8SStephan Herhut                                   builder.getInt8PtrTy());
7475d7231d8SStephan Herhut 
7485d7231d8SStephan Herhut   return llvmModule;
7495d7231d8SStephan Herhut }
750ce8f10d6SAlex Zinenko 
751ce8f10d6SAlex Zinenko std::unique_ptr<llvm::Module>
752ce8f10d6SAlex Zinenko mlir::translateModuleToLLVMIR(Operation *module, llvm::LLVMContext &llvmContext,
753ce8f10d6SAlex Zinenko                               StringRef name) {
754ce8f10d6SAlex Zinenko   if (!satisfiesLLVMModule(module))
755ce8f10d6SAlex Zinenko     return nullptr;
756ce8f10d6SAlex Zinenko   if (failed(checkSupportedModuleOps(module)))
757ce8f10d6SAlex Zinenko     return nullptr;
758ce8f10d6SAlex Zinenko   std::unique_ptr<llvm::Module> llvmModule =
759ce8f10d6SAlex Zinenko       prepareLLVMModule(module, llvmContext, name);
760ce8f10d6SAlex Zinenko 
761ce8f10d6SAlex Zinenko   LLVM::ensureDistinctSuccessors(module);
762ce8f10d6SAlex Zinenko 
763ce8f10d6SAlex Zinenko   ModuleTranslation translator(module, std::move(llvmModule));
764ce8f10d6SAlex Zinenko   if (failed(translator.convertFunctionSignatures()))
765ce8f10d6SAlex Zinenko     return nullptr;
766ce8f10d6SAlex Zinenko   if (failed(translator.convertGlobals()))
767ce8f10d6SAlex Zinenko     return nullptr;
7684a2930f4SArpith C. Jacob   if (failed(translator.createAccessGroupMetadata()))
7694a2930f4SArpith C. Jacob     return nullptr;
770ce8f10d6SAlex Zinenko   if (failed(translator.convertFunctions()))
771ce8f10d6SAlex Zinenko     return nullptr;
772ce8f10d6SAlex Zinenko   if (llvm::verifyModule(*translator.llvmModule, &llvm::errs()))
773ce8f10d6SAlex Zinenko     return nullptr;
774ce8f10d6SAlex Zinenko 
775ce8f10d6SAlex Zinenko   return std::move(translator.llvmModule);
776ce8f10d6SAlex Zinenko }
777