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"
17*7ecee63eSKiran Kumar T P #include "mlir/ADT/TypeSwitch.h"
18ba0fa925SRiver Riddle #include "mlir/Dialect/LLVMIR/LLVMDialect.h"
1992a295ebSKiran Chandramohan #include "mlir/Dialect/OpenMP/OpenMPDialect.h"
205d7231d8SStephan Herhut #include "mlir/IR/Attributes.h"
215d7231d8SStephan Herhut #include "mlir/IR/Module.h"
22a4a42160SAlex Zinenko #include "mlir/IR/StandardTypes.h"
235d7231d8SStephan Herhut #include "mlir/Support/LLVM.h"
245d7231d8SStephan Herhut 
255d7231d8SStephan Herhut #include "llvm/ADT/SetVector.h"
2692a295ebSKiran Chandramohan #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
275d7231d8SStephan Herhut #include "llvm/IR/BasicBlock.h"
285d7231d8SStephan Herhut #include "llvm/IR/Constants.h"
295d7231d8SStephan Herhut #include "llvm/IR/DerivedTypes.h"
305d7231d8SStephan Herhut #include "llvm/IR/IRBuilder.h"
315d7231d8SStephan Herhut #include "llvm/IR/LLVMContext.h"
325d7231d8SStephan Herhut #include "llvm/IR/Module.h"
335d7231d8SStephan Herhut #include "llvm/Transforms/Utils/Cloning.h"
345d7231d8SStephan Herhut 
352666b973SRiver Riddle using namespace mlir;
362666b973SRiver Riddle using namespace mlir::LLVM;
37c33d6970SRiver Riddle using namespace mlir::LLVM::detail;
385d7231d8SStephan Herhut 
39eb67bd78SAlex Zinenko #include "mlir/Dialect/LLVMIR/LLVMConversionEnumsToLLVM.inc"
40eb67bd78SAlex Zinenko 
41a922e231SAlex Zinenko /// Builds a constant of a sequential LLVM type `type`, potentially containing
42a922e231SAlex Zinenko /// other sequential types recursively, from the individual constant values
43a922e231SAlex Zinenko /// provided in `constants`. `shape` contains the number of elements in nested
44a922e231SAlex Zinenko /// sequential types. Reports errors at `loc` and returns nullptr on error.
45a4a42160SAlex Zinenko static llvm::Constant *
46a4a42160SAlex Zinenko buildSequentialConstant(ArrayRef<llvm::Constant *> &constants,
47a4a42160SAlex Zinenko                         ArrayRef<int64_t> shape, llvm::Type *type,
48a4a42160SAlex Zinenko                         Location loc) {
49a4a42160SAlex Zinenko   if (shape.empty()) {
50a4a42160SAlex Zinenko     llvm::Constant *result = constants.front();
51a4a42160SAlex Zinenko     constants = constants.drop_front();
52a4a42160SAlex Zinenko     return result;
53a4a42160SAlex Zinenko   }
54a4a42160SAlex Zinenko 
5568b03aeeSEli Friedman   llvm::Type *elementType;
5668b03aeeSEli Friedman   if (auto *arrayTy = dyn_cast<llvm::ArrayType>(type)) {
5768b03aeeSEli Friedman     elementType = arrayTy->getElementType();
5868b03aeeSEli Friedman   } else if (auto *vectorTy = dyn_cast<llvm::VectorType>(type)) {
5968b03aeeSEli Friedman     elementType = vectorTy->getElementType();
6068b03aeeSEli Friedman   } else {
61a4a42160SAlex Zinenko     emitError(loc) << "expected sequential LLVM types wrapping a scalar";
62a4a42160SAlex Zinenko     return nullptr;
63a4a42160SAlex Zinenko   }
64a4a42160SAlex Zinenko 
65a4a42160SAlex Zinenko   SmallVector<llvm::Constant *, 8> nested;
66a4a42160SAlex Zinenko   nested.reserve(shape.front());
67a4a42160SAlex Zinenko   for (int64_t i = 0; i < shape.front(); ++i) {
68a4a42160SAlex Zinenko     nested.push_back(buildSequentialConstant(constants, shape.drop_front(),
69a4a42160SAlex Zinenko                                              elementType, loc));
70a4a42160SAlex Zinenko     if (!nested.back())
71a4a42160SAlex Zinenko       return nullptr;
72a4a42160SAlex Zinenko   }
73a4a42160SAlex Zinenko 
74a4a42160SAlex Zinenko   if (shape.size() == 1 && type->isVectorTy())
75a4a42160SAlex Zinenko     return llvm::ConstantVector::get(nested);
76a4a42160SAlex Zinenko   return llvm::ConstantArray::get(
77a4a42160SAlex Zinenko       llvm::ArrayType::get(elementType, shape.front()), nested);
78a4a42160SAlex Zinenko }
79a4a42160SAlex Zinenko 
80fc817b09SKazuaki Ishizaki /// Returns the first non-sequential type nested in sequential types.
81a4a42160SAlex Zinenko static llvm::Type *getInnermostElementType(llvm::Type *type) {
8268b03aeeSEli Friedman   do {
8368b03aeeSEli Friedman     if (auto *arrayTy = dyn_cast<llvm::ArrayType>(type)) {
8468b03aeeSEli Friedman       type = arrayTy->getElementType();
8568b03aeeSEli Friedman     } else if (auto *vectorTy = dyn_cast<llvm::VectorType>(type)) {
8668b03aeeSEli Friedman       type = vectorTy->getElementType();
8768b03aeeSEli Friedman     } else {
88a4a42160SAlex Zinenko       return type;
89a4a42160SAlex Zinenko     }
9068b03aeeSEli Friedman   } while (1);
9168b03aeeSEli Friedman }
92a4a42160SAlex Zinenko 
932666b973SRiver Riddle /// Create an LLVM IR constant of `llvmType` from the MLIR attribute `attr`.
942666b973SRiver Riddle /// This currently supports integer, floating point, splat and dense element
952666b973SRiver Riddle /// attributes and combinations thereof.  In case of error, report it to `loc`
962666b973SRiver Riddle /// and return nullptr.
975d7231d8SStephan Herhut llvm::Constant *ModuleTranslation::getLLVMConstant(llvm::Type *llvmType,
985d7231d8SStephan Herhut                                                    Attribute attr,
995d7231d8SStephan Herhut                                                    Location loc) {
10033a3a91bSChristian Sigg   if (!attr)
10133a3a91bSChristian Sigg     return llvm::UndefValue::get(llvmType);
102a4a42160SAlex Zinenko   if (llvmType->isStructTy()) {
103a4a42160SAlex Zinenko     emitError(loc, "struct types are not supported in constants");
104a4a42160SAlex Zinenko     return nullptr;
105a4a42160SAlex Zinenko   }
106ac9d742bSStephan Herhut   // For integer types, we allow a mismatch in sizes as the index type in
107ac9d742bSStephan Herhut   // MLIR might have a different size than the index type in the LLVM module.
1085d7231d8SStephan Herhut   if (auto intAttr = attr.dyn_cast<IntegerAttr>())
109ac9d742bSStephan Herhut     return llvm::ConstantInt::get(
110ac9d742bSStephan Herhut         llvmType,
111ac9d742bSStephan Herhut         intAttr.getValue().sextOrTrunc(llvmType->getIntegerBitWidth()));
11218fc42faSAhmed Taei   if (auto boolAttr = attr.dyn_cast<BoolAttr>())
11318fc42faSAhmed Taei     return llvm::ConstantInt::get(llvmType, boolAttr.getValue());
1145d7231d8SStephan Herhut   if (auto floatAttr = attr.dyn_cast<FloatAttr>())
1155d7231d8SStephan Herhut     return llvm::ConstantFP::get(llvmType, floatAttr.getValue());
1169b9c647cSRiver Riddle   if (auto funcAttr = attr.dyn_cast<FlatSymbolRefAttr>())
117ff77397fSShraiysh Vaishay     return llvm::ConstantExpr::getBitCast(
118ff77397fSShraiysh Vaishay         functionMapping.lookup(funcAttr.getValue()), llvmType);
1195d7231d8SStephan Herhut   if (auto splatAttr = attr.dyn_cast<SplatElementsAttr>()) {
12068b03aeeSEli Friedman     llvm::Type *elementType;
12168b03aeeSEli Friedman     uint64_t numElements;
12268b03aeeSEli Friedman     if (auto *arrayTy = dyn_cast<llvm::ArrayType>(llvmType)) {
12368b03aeeSEli Friedman       elementType = arrayTy->getElementType();
12468b03aeeSEli Friedman       numElements = arrayTy->getNumElements();
12568b03aeeSEli Friedman     } else {
12668b03aeeSEli Friedman       auto *vectorTy = cast<llvm::VectorType>(llvmType);
12768b03aeeSEli Friedman       elementType = vectorTy->getElementType();
12868b03aeeSEli Friedman       numElements = vectorTy->getNumElements();
12968b03aeeSEli Friedman     }
130d6ea8ff0SAlex Zinenko     // Splat value is a scalar. Extract it only if the element type is not
131d6ea8ff0SAlex Zinenko     // another sequence type. The recursion terminates because each step removes
132d6ea8ff0SAlex Zinenko     // one outer sequential type.
13368b03aeeSEli Friedman     bool elementTypeSequential =
13468b03aeeSEli Friedman         isa<llvm::ArrayType>(elementType) || isa<llvm::VectorType>(elementType);
135d6ea8ff0SAlex Zinenko     llvm::Constant *child = getLLVMConstant(
136d6ea8ff0SAlex Zinenko         elementType,
13768b03aeeSEli Friedman         elementTypeSequential ? splatAttr : splatAttr.getSplatValue(), loc);
138a4a42160SAlex Zinenko     if (!child)
139a4a42160SAlex Zinenko       return nullptr;
1402f13df13SMLIR Team     if (llvmType->isVectorTy())
141396a42d9SRiver Riddle       return llvm::ConstantVector::getSplat(
142396a42d9SRiver Riddle           llvm::ElementCount(numElements, /*Scalable=*/false), child);
1432f13df13SMLIR Team     if (llvmType->isArrayTy()) {
144ac9d742bSStephan Herhut       auto *arrayType = llvm::ArrayType::get(elementType, numElements);
1452f13df13SMLIR Team       SmallVector<llvm::Constant *, 8> constants(numElements, child);
1462f13df13SMLIR Team       return llvm::ConstantArray::get(arrayType, constants);
1472f13df13SMLIR Team     }
1485d7231d8SStephan Herhut   }
149a4a42160SAlex Zinenko 
150d906f84bSRiver Riddle   if (auto elementsAttr = attr.dyn_cast<ElementsAttr>()) {
151a4a42160SAlex Zinenko     assert(elementsAttr.getType().hasStaticShape());
152a4a42160SAlex Zinenko     assert(elementsAttr.getNumElements() != 0 &&
153a4a42160SAlex Zinenko            "unexpected empty elements attribute");
154a4a42160SAlex Zinenko     assert(!elementsAttr.getType().getShape().empty() &&
155a4a42160SAlex Zinenko            "unexpected empty elements attribute shape");
156a4a42160SAlex Zinenko 
1575d7231d8SStephan Herhut     SmallVector<llvm::Constant *, 8> constants;
158a4a42160SAlex Zinenko     constants.reserve(elementsAttr.getNumElements());
159a4a42160SAlex Zinenko     llvm::Type *innermostType = getInnermostElementType(llvmType);
160d906f84bSRiver Riddle     for (auto n : elementsAttr.getValues<Attribute>()) {
161a4a42160SAlex Zinenko       constants.push_back(getLLVMConstant(innermostType, n, loc));
1625d7231d8SStephan Herhut       if (!constants.back())
1635d7231d8SStephan Herhut         return nullptr;
1645d7231d8SStephan Herhut     }
165a4a42160SAlex Zinenko     ArrayRef<llvm::Constant *> constantsRef = constants;
166a4a42160SAlex Zinenko     llvm::Constant *result = buildSequentialConstant(
167a4a42160SAlex Zinenko         constantsRef, elementsAttr.getType().getShape(), llvmType, loc);
168a4a42160SAlex Zinenko     assert(constantsRef.empty() && "did not consume all elemental constants");
169a4a42160SAlex Zinenko     return result;
1702f13df13SMLIR Team   }
171a4a42160SAlex Zinenko 
172cb348dffSStephan Herhut   if (auto stringAttr = attr.dyn_cast<StringAttr>()) {
173cb348dffSStephan Herhut     return llvm::ConstantDataArray::get(
174cb348dffSStephan Herhut         llvmModule->getContext(), ArrayRef<char>{stringAttr.getValue().data(),
175cb348dffSStephan Herhut                                                  stringAttr.getValue().size()});
176cb348dffSStephan Herhut   }
177a4c3a645SRiver Riddle   emitError(loc, "unsupported constant value");
1785d7231d8SStephan Herhut   return nullptr;
1795d7231d8SStephan Herhut }
1805d7231d8SStephan Herhut 
1812666b973SRiver Riddle /// Convert MLIR integer comparison predicate to LLVM IR comparison predicate.
182ec82e1c9SAlex Zinenko static llvm::CmpInst::Predicate getLLVMCmpPredicate(ICmpPredicate p) {
1835d7231d8SStephan Herhut   switch (p) {
184ec82e1c9SAlex Zinenko   case LLVM::ICmpPredicate::eq:
1855d7231d8SStephan Herhut     return llvm::CmpInst::Predicate::ICMP_EQ;
186ec82e1c9SAlex Zinenko   case LLVM::ICmpPredicate::ne:
1875d7231d8SStephan Herhut     return llvm::CmpInst::Predicate::ICMP_NE;
188ec82e1c9SAlex Zinenko   case LLVM::ICmpPredicate::slt:
1895d7231d8SStephan Herhut     return llvm::CmpInst::Predicate::ICMP_SLT;
190ec82e1c9SAlex Zinenko   case LLVM::ICmpPredicate::sle:
1915d7231d8SStephan Herhut     return llvm::CmpInst::Predicate::ICMP_SLE;
192ec82e1c9SAlex Zinenko   case LLVM::ICmpPredicate::sgt:
1935d7231d8SStephan Herhut     return llvm::CmpInst::Predicate::ICMP_SGT;
194ec82e1c9SAlex Zinenko   case LLVM::ICmpPredicate::sge:
1955d7231d8SStephan Herhut     return llvm::CmpInst::Predicate::ICMP_SGE;
196ec82e1c9SAlex Zinenko   case LLVM::ICmpPredicate::ult:
1975d7231d8SStephan Herhut     return llvm::CmpInst::Predicate::ICMP_ULT;
198ec82e1c9SAlex Zinenko   case LLVM::ICmpPredicate::ule:
1995d7231d8SStephan Herhut     return llvm::CmpInst::Predicate::ICMP_ULE;
200ec82e1c9SAlex Zinenko   case LLVM::ICmpPredicate::ugt:
2015d7231d8SStephan Herhut     return llvm::CmpInst::Predicate::ICMP_UGT;
202ec82e1c9SAlex Zinenko   case LLVM::ICmpPredicate::uge:
2035d7231d8SStephan Herhut     return llvm::CmpInst::Predicate::ICMP_UGE;
2045d7231d8SStephan Herhut   }
205e6365f3dSJacques Pienaar   llvm_unreachable("incorrect comparison predicate");
2065d7231d8SStephan Herhut }
2075d7231d8SStephan Herhut 
20848fdc8d7SNagy Mostafa static llvm::CmpInst::Predicate getLLVMCmpPredicate(FCmpPredicate p) {
20948fdc8d7SNagy Mostafa   switch (p) {
21048fdc8d7SNagy Mostafa   case LLVM::FCmpPredicate::_false:
21148fdc8d7SNagy Mostafa     return llvm::CmpInst::Predicate::FCMP_FALSE;
21248fdc8d7SNagy Mostafa   case LLVM::FCmpPredicate::oeq:
21348fdc8d7SNagy Mostafa     return llvm::CmpInst::Predicate::FCMP_OEQ;
21448fdc8d7SNagy Mostafa   case LLVM::FCmpPredicate::ogt:
21548fdc8d7SNagy Mostafa     return llvm::CmpInst::Predicate::FCMP_OGT;
21648fdc8d7SNagy Mostafa   case LLVM::FCmpPredicate::oge:
21748fdc8d7SNagy Mostafa     return llvm::CmpInst::Predicate::FCMP_OGE;
21848fdc8d7SNagy Mostafa   case LLVM::FCmpPredicate::olt:
21948fdc8d7SNagy Mostafa     return llvm::CmpInst::Predicate::FCMP_OLT;
22048fdc8d7SNagy Mostafa   case LLVM::FCmpPredicate::ole:
22148fdc8d7SNagy Mostafa     return llvm::CmpInst::Predicate::FCMP_OLE;
22248fdc8d7SNagy Mostafa   case LLVM::FCmpPredicate::one:
22348fdc8d7SNagy Mostafa     return llvm::CmpInst::Predicate::FCMP_ONE;
22448fdc8d7SNagy Mostafa   case LLVM::FCmpPredicate::ord:
22548fdc8d7SNagy Mostafa     return llvm::CmpInst::Predicate::FCMP_ORD;
22648fdc8d7SNagy Mostafa   case LLVM::FCmpPredicate::ueq:
22748fdc8d7SNagy Mostafa     return llvm::CmpInst::Predicate::FCMP_UEQ;
22848fdc8d7SNagy Mostafa   case LLVM::FCmpPredicate::ugt:
22948fdc8d7SNagy Mostafa     return llvm::CmpInst::Predicate::FCMP_UGT;
23048fdc8d7SNagy Mostafa   case LLVM::FCmpPredicate::uge:
23148fdc8d7SNagy Mostafa     return llvm::CmpInst::Predicate::FCMP_UGE;
23248fdc8d7SNagy Mostafa   case LLVM::FCmpPredicate::ult:
23348fdc8d7SNagy Mostafa     return llvm::CmpInst::Predicate::FCMP_ULT;
23448fdc8d7SNagy Mostafa   case LLVM::FCmpPredicate::ule:
23548fdc8d7SNagy Mostafa     return llvm::CmpInst::Predicate::FCMP_ULE;
23648fdc8d7SNagy Mostafa   case LLVM::FCmpPredicate::une:
23748fdc8d7SNagy Mostafa     return llvm::CmpInst::Predicate::FCMP_UNE;
23848fdc8d7SNagy Mostafa   case LLVM::FCmpPredicate::uno:
23948fdc8d7SNagy Mostafa     return llvm::CmpInst::Predicate::FCMP_UNO;
24048fdc8d7SNagy Mostafa   case LLVM::FCmpPredicate::_true:
24148fdc8d7SNagy Mostafa     return llvm::CmpInst::Predicate::FCMP_TRUE;
24248fdc8d7SNagy Mostafa   }
243e6365f3dSJacques Pienaar   llvm_unreachable("incorrect comparison predicate");
24448fdc8d7SNagy Mostafa }
24548fdc8d7SNagy Mostafa 
24660a0c612SFrank Laub static llvm::AtomicRMWInst::BinOp getLLVMAtomicBinOp(AtomicBinOp op) {
24760a0c612SFrank Laub   switch (op) {
24860a0c612SFrank Laub   case LLVM::AtomicBinOp::xchg:
24960a0c612SFrank Laub     return llvm::AtomicRMWInst::BinOp::Xchg;
25060a0c612SFrank Laub   case LLVM::AtomicBinOp::add:
25160a0c612SFrank Laub     return llvm::AtomicRMWInst::BinOp::Add;
25260a0c612SFrank Laub   case LLVM::AtomicBinOp::sub:
25360a0c612SFrank Laub     return llvm::AtomicRMWInst::BinOp::Sub;
25460a0c612SFrank Laub   case LLVM::AtomicBinOp::_and:
25560a0c612SFrank Laub     return llvm::AtomicRMWInst::BinOp::And;
25660a0c612SFrank Laub   case LLVM::AtomicBinOp::nand:
25760a0c612SFrank Laub     return llvm::AtomicRMWInst::BinOp::Nand;
25860a0c612SFrank Laub   case LLVM::AtomicBinOp::_or:
25960a0c612SFrank Laub     return llvm::AtomicRMWInst::BinOp::Or;
26060a0c612SFrank Laub   case LLVM::AtomicBinOp::_xor:
26160a0c612SFrank Laub     return llvm::AtomicRMWInst::BinOp::Xor;
26260a0c612SFrank Laub   case LLVM::AtomicBinOp::max:
26360a0c612SFrank Laub     return llvm::AtomicRMWInst::BinOp::Max;
26460a0c612SFrank Laub   case LLVM::AtomicBinOp::min:
26560a0c612SFrank Laub     return llvm::AtomicRMWInst::BinOp::Min;
26660a0c612SFrank Laub   case LLVM::AtomicBinOp::umax:
26760a0c612SFrank Laub     return llvm::AtomicRMWInst::BinOp::UMax;
26860a0c612SFrank Laub   case LLVM::AtomicBinOp::umin:
26960a0c612SFrank Laub     return llvm::AtomicRMWInst::BinOp::UMin;
27060a0c612SFrank Laub   case LLVM::AtomicBinOp::fadd:
27160a0c612SFrank Laub     return llvm::AtomicRMWInst::BinOp::FAdd;
27260a0c612SFrank Laub   case LLVM::AtomicBinOp::fsub:
27360a0c612SFrank Laub     return llvm::AtomicRMWInst::BinOp::FSub;
27460a0c612SFrank Laub   }
27560a0c612SFrank Laub   llvm_unreachable("incorrect atomic binary operator");
27660a0c612SFrank Laub }
27760a0c612SFrank Laub 
27860a0c612SFrank Laub static llvm::AtomicOrdering getLLVMAtomicOrdering(AtomicOrdering ordering) {
27960a0c612SFrank Laub   switch (ordering) {
28060a0c612SFrank Laub   case LLVM::AtomicOrdering::not_atomic:
28160a0c612SFrank Laub     return llvm::AtomicOrdering::NotAtomic;
28260a0c612SFrank Laub   case LLVM::AtomicOrdering::unordered:
28360a0c612SFrank Laub     return llvm::AtomicOrdering::Unordered;
28460a0c612SFrank Laub   case LLVM::AtomicOrdering::monotonic:
28560a0c612SFrank Laub     return llvm::AtomicOrdering::Monotonic;
28660a0c612SFrank Laub   case LLVM::AtomicOrdering::acquire:
28760a0c612SFrank Laub     return llvm::AtomicOrdering::Acquire;
28860a0c612SFrank Laub   case LLVM::AtomicOrdering::release:
28960a0c612SFrank Laub     return llvm::AtomicOrdering::Release;
29060a0c612SFrank Laub   case LLVM::AtomicOrdering::acq_rel:
29160a0c612SFrank Laub     return llvm::AtomicOrdering::AcquireRelease;
29260a0c612SFrank Laub   case LLVM::AtomicOrdering::seq_cst:
29360a0c612SFrank Laub     return llvm::AtomicOrdering::SequentiallyConsistent;
29460a0c612SFrank Laub   }
29560a0c612SFrank Laub   llvm_unreachable("incorrect atomic ordering");
29660a0c612SFrank Laub }
29760a0c612SFrank Laub 
298c33d6970SRiver Riddle ModuleTranslation::ModuleTranslation(Operation *module,
299c33d6970SRiver Riddle                                      std::unique_ptr<llvm::Module> llvmModule)
300c33d6970SRiver Riddle     : mlirModule(module), llvmModule(std::move(llvmModule)),
301c33d6970SRiver Riddle       debugTranslation(
30292a295ebSKiran Chandramohan           std::make_unique<DebugTranslation>(module, *this->llvmModule)),
30392a295ebSKiran Chandramohan       ompDialect(
30492a295ebSKiran Chandramohan           module->getContext()->getRegisteredDialect<omp::OpenMPDialect>()) {
305c33d6970SRiver Riddle   assert(satisfiesLLVMModule(mlirModule) &&
306c33d6970SRiver Riddle          "mlirModule should honor LLVM's module semantics.");
307c33d6970SRiver Riddle }
308c33d6970SRiver Riddle ModuleTranslation::~ModuleTranslation() {}
309c33d6970SRiver Riddle 
310*7ecee63eSKiran Kumar T P /// Given an OpenMP MLIR operation, create the corresponding LLVM IR
311*7ecee63eSKiran Kumar T P /// (including OpenMP runtime calls).
312*7ecee63eSKiran Kumar T P LogicalResult
313*7ecee63eSKiran Kumar T P ModuleTranslation::convertOmpOperation(Operation &opInst,
314*7ecee63eSKiran Kumar T P                                        llvm::IRBuilder<> &builder) {
315*7ecee63eSKiran Kumar T P   if (!ompBuilder) {
316*7ecee63eSKiran Kumar T P     ompBuilder = std::make_unique<llvm::OpenMPIRBuilder>(*llvmModule);
317*7ecee63eSKiran Kumar T P     ompBuilder->initialize();
318*7ecee63eSKiran Kumar T P   }
319*7ecee63eSKiran Kumar T P   return mlir::TypeSwitch<Operation *, LogicalResult>(&opInst)
320*7ecee63eSKiran Kumar T P       .Case([&](omp::BarrierOp) {
321*7ecee63eSKiran Kumar T P         ompBuilder->CreateBarrier(builder.saveIP(), llvm::omp::OMPD_barrier);
322*7ecee63eSKiran Kumar T P         return success();
323*7ecee63eSKiran Kumar T P       })
324*7ecee63eSKiran Kumar T P       .Case([&](omp::TaskwaitOp) {
325*7ecee63eSKiran Kumar T P         ompBuilder->CreateTaskwait(builder.saveIP());
326*7ecee63eSKiran Kumar T P         return success();
327*7ecee63eSKiran Kumar T P       })
328*7ecee63eSKiran Kumar T P       .Case([&](omp::TaskyieldOp) {
329*7ecee63eSKiran Kumar T P         ompBuilder->CreateTaskyield(builder.saveIP());
330*7ecee63eSKiran Kumar T P         return success();
331*7ecee63eSKiran Kumar T P       })
332*7ecee63eSKiran Kumar T P       .Default([&](Operation *inst) {
333*7ecee63eSKiran Kumar T P         return inst->emitError("unsupported OpenMP operation: ")
334*7ecee63eSKiran Kumar T P                << inst->getName();
335*7ecee63eSKiran Kumar T P       });
336*7ecee63eSKiran Kumar T P }
337*7ecee63eSKiran Kumar T P 
3382666b973SRiver Riddle /// Given a single MLIR operation, create the corresponding LLVM IR operation
3392666b973SRiver Riddle /// using the `builder`.  LLVM IR Builder does not have a generic interface so
3402666b973SRiver Riddle /// this has to be a long chain of `if`s calling different functions with a
3412666b973SRiver Riddle /// different number of arguments.
342baa1ec22SAlex Zinenko LogicalResult ModuleTranslation::convertOperation(Operation &opInst,
3435d7231d8SStephan Herhut                                                   llvm::IRBuilder<> &builder) {
3445d7231d8SStephan Herhut   auto extractPosition = [](ArrayAttr attr) {
3455d7231d8SStephan Herhut     SmallVector<unsigned, 4> position;
3465d7231d8SStephan Herhut     position.reserve(attr.size());
3475d7231d8SStephan Herhut     for (Attribute v : attr)
3485d7231d8SStephan Herhut       position.push_back(v.cast<IntegerAttr>().getValue().getZExtValue());
3495d7231d8SStephan Herhut     return position;
3505d7231d8SStephan Herhut   };
3515d7231d8SStephan Herhut 
352ba0fa925SRiver Riddle #include "mlir/Dialect/LLVMIR/LLVMConversions.inc"
3535d7231d8SStephan Herhut 
3545d7231d8SStephan Herhut   // Emit function calls.  If the "callee" attribute is present, this is a
3555d7231d8SStephan Herhut   // direct function call and we also need to look up the remapped function
3565d7231d8SStephan Herhut   // itself.  Otherwise, this is an indirect call and the callee is the first
3575d7231d8SStephan Herhut   // operand, look it up as a normal value.  Return the llvm::Value representing
3585d7231d8SStephan Herhut   // the function result, which may be of llvm::VoidTy type.
3595d7231d8SStephan Herhut   auto convertCall = [this, &builder](Operation &op) -> llvm::Value * {
3605d7231d8SStephan Herhut     auto operands = lookupValues(op.getOperands());
3615d7231d8SStephan Herhut     ArrayRef<llvm::Value *> operandsRef(operands);
3629b9c647cSRiver Riddle     if (auto attr = op.getAttrOfType<FlatSymbolRefAttr>("callee")) {
3635d7231d8SStephan Herhut       return builder.CreateCall(functionMapping.lookup(attr.getValue()),
3645d7231d8SStephan Herhut                                 operandsRef);
3655d7231d8SStephan Herhut     } else {
366133049d0SEli Friedman       auto *calleePtrType =
367133049d0SEli Friedman           cast<llvm::PointerType>(operandsRef.front()->getType());
368133049d0SEli Friedman       auto *calleeType =
369133049d0SEli Friedman           cast<llvm::FunctionType>(calleePtrType->getElementType());
370133049d0SEli Friedman       return builder.CreateCall(calleeType, operandsRef.front(),
371133049d0SEli Friedman                                 operandsRef.drop_front());
3725d7231d8SStephan Herhut     }
3735d7231d8SStephan Herhut   };
3745d7231d8SStephan Herhut 
3755d7231d8SStephan Herhut   // Emit calls.  If the called function has a result, remap the corresponding
3765d7231d8SStephan Herhut   // value.  Note that LLVM IR dialect CallOp has either 0 or 1 result.
377d5b60ee8SRiver Riddle   if (isa<LLVM::CallOp>(opInst)) {
3785d7231d8SStephan Herhut     llvm::Value *result = convertCall(opInst);
3795d7231d8SStephan Herhut     if (opInst.getNumResults() != 0) {
3805d7231d8SStephan Herhut       valueMapping[opInst.getResult(0)] = result;
381baa1ec22SAlex Zinenko       return success();
3825d7231d8SStephan Herhut     }
3835d7231d8SStephan Herhut     // Check that LLVM call returns void for 0-result functions.
384baa1ec22SAlex Zinenko     return success(result->getType()->isVoidTy());
3855d7231d8SStephan Herhut   }
3865d7231d8SStephan Herhut 
387d242aa24SShraiysh Vaishay   if (auto invOp = dyn_cast<LLVM::InvokeOp>(opInst)) {
388d242aa24SShraiysh Vaishay     auto operands = lookupValues(opInst.getOperands());
389d242aa24SShraiysh Vaishay     ArrayRef<llvm::Value *> operandsRef(operands);
390133049d0SEli Friedman     if (auto attr = opInst.getAttrOfType<FlatSymbolRefAttr>("callee")) {
391d242aa24SShraiysh Vaishay       builder.CreateInvoke(functionMapping.lookup(attr.getValue()),
392d242aa24SShraiysh Vaishay                            blockMapping[invOp.getSuccessor(0)],
393d242aa24SShraiysh Vaishay                            blockMapping[invOp.getSuccessor(1)], operandsRef);
394133049d0SEli Friedman     } else {
395133049d0SEli Friedman       auto *calleePtrType =
396133049d0SEli Friedman           cast<llvm::PointerType>(operandsRef.front()->getType());
397133049d0SEli Friedman       auto *calleeType =
398133049d0SEli Friedman           cast<llvm::FunctionType>(calleePtrType->getElementType());
399d242aa24SShraiysh Vaishay       builder.CreateInvoke(
400133049d0SEli Friedman           calleeType, operandsRef.front(), blockMapping[invOp.getSuccessor(0)],
401d242aa24SShraiysh Vaishay           blockMapping[invOp.getSuccessor(1)], operandsRef.drop_front());
402133049d0SEli Friedman     }
403d242aa24SShraiysh Vaishay     return success();
404d242aa24SShraiysh Vaishay   }
405d242aa24SShraiysh Vaishay 
406d242aa24SShraiysh Vaishay   if (auto lpOp = dyn_cast<LLVM::LandingpadOp>(opInst)) {
407d242aa24SShraiysh Vaishay     llvm::Type *ty = lpOp.getType().dyn_cast<LLVMType>().getUnderlyingType();
408d242aa24SShraiysh Vaishay     llvm::LandingPadInst *lpi =
409d242aa24SShraiysh Vaishay         builder.CreateLandingPad(ty, lpOp.getNumOperands());
410d242aa24SShraiysh Vaishay 
411d242aa24SShraiysh Vaishay     // Add clauses
412d242aa24SShraiysh Vaishay     for (auto operand : lookupValues(lpOp.getOperands())) {
413d242aa24SShraiysh Vaishay       // All operands should be constant - checked by verifier
414d242aa24SShraiysh Vaishay       if (auto constOperand = dyn_cast<llvm::Constant>(operand))
415d242aa24SShraiysh Vaishay         lpi->addClause(constOperand);
416d242aa24SShraiysh Vaishay     }
417ff77397fSShraiysh Vaishay     valueMapping[lpOp.getResult()] = lpi;
418d242aa24SShraiysh Vaishay     return success();
419d242aa24SShraiysh Vaishay   }
420d242aa24SShraiysh Vaishay 
4215d7231d8SStephan Herhut   // Emit branches.  We need to look up the remapped blocks and ignore the block
4225d7231d8SStephan Herhut   // arguments that were transformed into PHI nodes.
423c5ecf991SRiver Riddle   if (auto brOp = dyn_cast<LLVM::BrOp>(opInst)) {
424c0fd5e65SRiver Riddle     builder.CreateBr(blockMapping[brOp.getSuccessor()]);
425baa1ec22SAlex Zinenko     return success();
4265d7231d8SStephan Herhut   }
427c5ecf991SRiver Riddle   if (auto condbrOp = dyn_cast<LLVM::CondBrOp>(opInst)) {
4285d7231d8SStephan Herhut     builder.CreateCondBr(valueMapping.lookup(condbrOp.getOperand(0)),
4295d7231d8SStephan Herhut                          blockMapping[condbrOp.getSuccessor(0)],
4305d7231d8SStephan Herhut                          blockMapping[condbrOp.getSuccessor(1)]);
431baa1ec22SAlex Zinenko     return success();
4325d7231d8SStephan Herhut   }
4335d7231d8SStephan Herhut 
4342dd38b09SAlex Zinenko   // Emit addressof.  We need to look up the global value referenced by the
4352dd38b09SAlex Zinenko   // operation and store it in the MLIR-to-LLVM value mapping.  This does not
4362dd38b09SAlex Zinenko   // emit any LLVM instruction.
4372dd38b09SAlex Zinenko   if (auto addressOfOp = dyn_cast<LLVM::AddressOfOp>(opInst)) {
4382dd38b09SAlex Zinenko     LLVM::GlobalOp global = addressOfOp.getGlobal();
4392dd38b09SAlex Zinenko     // The verifier should not have allowed this.
4402dd38b09SAlex Zinenko     assert(global && "referencing an undefined global");
4412dd38b09SAlex Zinenko 
4422dd38b09SAlex Zinenko     valueMapping[addressOfOp.getResult()] = globalsMapping.lookup(global);
4432dd38b09SAlex Zinenko     return success();
4442dd38b09SAlex Zinenko   }
4452dd38b09SAlex Zinenko 
44692a295ebSKiran Chandramohan   if (opInst.getDialect() == ompDialect) {
447*7ecee63eSKiran Kumar T P     return convertOmpOperation(opInst, builder);
44892a295ebSKiran Chandramohan   }
44992a295ebSKiran Chandramohan 
450baa1ec22SAlex Zinenko   return opInst.emitError("unsupported or non-LLVM operation: ")
451baa1ec22SAlex Zinenko          << opInst.getName();
4525d7231d8SStephan Herhut }
4535d7231d8SStephan Herhut 
4542666b973SRiver Riddle /// Convert block to LLVM IR.  Unless `ignoreArguments` is set, emit PHI nodes
4552666b973SRiver Riddle /// to define values corresponding to the MLIR block arguments.  These nodes
4562666b973SRiver Riddle /// are not connected to the source basic blocks, which may not exist yet.
457baa1ec22SAlex Zinenko LogicalResult ModuleTranslation::convertBlock(Block &bb, bool ignoreArguments) {
4585d7231d8SStephan Herhut   llvm::IRBuilder<> builder(blockMapping[&bb]);
459c33d6970SRiver Riddle   auto *subprogram = builder.GetInsertBlock()->getParent()->getSubprogram();
4605d7231d8SStephan Herhut 
4615d7231d8SStephan Herhut   // Before traversing operations, make block arguments available through
4625d7231d8SStephan Herhut   // value remapping and PHI nodes, but do not add incoming edges for the PHI
4635d7231d8SStephan Herhut   // nodes just yet: those values may be defined by this or following blocks.
4645d7231d8SStephan Herhut   // This step is omitted if "ignoreArguments" is set.  The arguments of the
4655d7231d8SStephan Herhut   // first block have been already made available through the remapping of
4665d7231d8SStephan Herhut   // LLVM function arguments.
4675d7231d8SStephan Herhut   if (!ignoreArguments) {
4685d7231d8SStephan Herhut     auto predecessors = bb.getPredecessors();
4695d7231d8SStephan Herhut     unsigned numPredecessors =
4705d7231d8SStephan Herhut         std::distance(predecessors.begin(), predecessors.end());
47135807bc4SRiver Riddle     for (auto arg : bb.getArguments()) {
4722bdf33ccSRiver Riddle       auto wrappedType = arg.getType().dyn_cast<LLVM::LLVMType>();
473baa1ec22SAlex Zinenko       if (!wrappedType)
474baa1ec22SAlex Zinenko         return emitError(bb.front().getLoc(),
475a4c3a645SRiver Riddle                          "block argument does not have an LLVM type");
4765d7231d8SStephan Herhut       llvm::Type *type = wrappedType.getUnderlyingType();
4775d7231d8SStephan Herhut       llvm::PHINode *phi = builder.CreatePHI(type, numPredecessors);
4785d7231d8SStephan Herhut       valueMapping[arg] = phi;
4795d7231d8SStephan Herhut     }
4805d7231d8SStephan Herhut   }
4815d7231d8SStephan Herhut 
4825d7231d8SStephan Herhut   // Traverse operations.
4835d7231d8SStephan Herhut   for (auto &op : bb) {
484c33d6970SRiver Riddle     // Set the current debug location within the builder.
485c33d6970SRiver Riddle     builder.SetCurrentDebugLocation(
486c33d6970SRiver Riddle         debugTranslation->translateLoc(op.getLoc(), subprogram));
487c33d6970SRiver Riddle 
488baa1ec22SAlex Zinenko     if (failed(convertOperation(op, builder)))
489baa1ec22SAlex Zinenko       return failure();
4905d7231d8SStephan Herhut   }
4915d7231d8SStephan Herhut 
492baa1ec22SAlex Zinenko   return success();
4935d7231d8SStephan Herhut }
4945d7231d8SStephan Herhut 
4952666b973SRiver Riddle /// Create named global variables that correspond to llvm.mlir.global
4962666b973SRiver Riddle /// definitions.
497efa2d533SAlex Zinenko LogicalResult ModuleTranslation::convertGlobals() {
49844fc7d72STres Popp   for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) {
499250a11aeSJames Molloy     llvm::Type *type = op.getType().getUnderlyingType();
500250a11aeSJames Molloy     llvm::Constant *cst = llvm::UndefValue::get(type);
501250a11aeSJames Molloy     if (op.getValueOrNull()) {
50268451df2SAlex Zinenko       // String attributes are treated separately because they cannot appear as
50368451df2SAlex Zinenko       // in-function constants and are thus not supported by getLLVMConstant.
50433a3a91bSChristian Sigg       if (auto strAttr = op.getValueOrNull().dyn_cast_or_null<StringAttr>()) {
5052dd38b09SAlex Zinenko         cst = llvm::ConstantDataArray::getString(
50668451df2SAlex Zinenko             llvmModule->getContext(), strAttr.getValue(), /*AddNull=*/false);
5072dd38b09SAlex Zinenko         type = cst->getType();
508efa2d533SAlex Zinenko       } else if (!(cst = getLLVMConstant(type, op.getValueOrNull(),
509efa2d533SAlex Zinenko                                          op.getLoc()))) {
510efa2d533SAlex Zinenko         return failure();
51168451df2SAlex Zinenko       }
512250a11aeSJames Molloy     } else if (Block *initializer = op.getInitializerBlock()) {
513250a11aeSJames Molloy       llvm::IRBuilder<> builder(llvmModule->getContext());
514250a11aeSJames Molloy       for (auto &op : initializer->without_terminator()) {
515250a11aeSJames Molloy         if (failed(convertOperation(op, builder)) ||
516efa2d533SAlex Zinenko             !isa<llvm::Constant>(valueMapping.lookup(op.getResult(0))))
517efa2d533SAlex Zinenko           return emitError(op.getLoc(), "unemittable constant value");
518250a11aeSJames Molloy       }
519250a11aeSJames Molloy       ReturnOp ret = cast<ReturnOp>(initializer->getTerminator());
520250a11aeSJames Molloy       cst = cast<llvm::Constant>(valueMapping.lookup(ret.getOperand(0)));
521250a11aeSJames Molloy     }
52268451df2SAlex Zinenko 
523eb67bd78SAlex Zinenko     auto linkage = convertLinkageToLLVM(op.linkage());
524d5e627f8SAlex Zinenko     bool anyExternalLinkage =
5257b5d4669SEric Schweitz         ((linkage == llvm::GlobalVariable::ExternalLinkage &&
5267b5d4669SEric Schweitz           isa<llvm::UndefValue>(cst)) ||
527d5e627f8SAlex Zinenko          linkage == llvm::GlobalVariable::ExternalWeakLinkage);
528e79bfefbSMLIR Team     auto addrSpace = op.addr_space().getLimitedValue();
529e79bfefbSMLIR Team     auto *var = new llvm::GlobalVariable(
530d5e627f8SAlex Zinenko         *llvmModule, type, op.constant(), linkage,
531d5e627f8SAlex Zinenko         anyExternalLinkage ? nullptr : cst, op.sym_name(),
532d5e627f8SAlex Zinenko         /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal, addrSpace);
533e79bfefbSMLIR Team 
5342dd38b09SAlex Zinenko     globalsMapping.try_emplace(op, var);
535b9ff2dd8SAlex Zinenko   }
536efa2d533SAlex Zinenko 
537efa2d533SAlex Zinenko   return success();
538b9ff2dd8SAlex Zinenko }
539b9ff2dd8SAlex Zinenko 
5402666b973SRiver Riddle /// Get the SSA value passed to the current block from the terminator operation
5412666b973SRiver Riddle /// of its predecessor.
542e62a6956SRiver Riddle static Value getPHISourceValue(Block *current, Block *pred,
5435d7231d8SStephan Herhut                                unsigned numArguments, unsigned index) {
5445d7231d8SStephan Herhut   auto &terminator = *pred->getTerminator();
545d5b60ee8SRiver Riddle   if (isa<LLVM::BrOp>(terminator)) {
5465d7231d8SStephan Herhut     return terminator.getOperand(index);
5475d7231d8SStephan Herhut   }
5485d7231d8SStephan Herhut 
5495d7231d8SStephan Herhut   // For conditional branches, we need to check if the current block is reached
5505d7231d8SStephan Herhut   // through the "true" or the "false" branch and take the relevant operands.
551c5ecf991SRiver Riddle   auto condBranchOp = dyn_cast<LLVM::CondBrOp>(terminator);
5525d7231d8SStephan Herhut   assert(condBranchOp &&
5535d7231d8SStephan Herhut          "only branch operations can be terminators of a block that "
5545d7231d8SStephan Herhut          "has successors");
5555d7231d8SStephan Herhut   assert((condBranchOp.getSuccessor(0) != condBranchOp.getSuccessor(1)) &&
5565d7231d8SStephan Herhut          "successors with arguments in LLVM conditional branches must be "
5575d7231d8SStephan Herhut          "different blocks");
5585d7231d8SStephan Herhut 
5595d7231d8SStephan Herhut   return condBranchOp.getSuccessor(0) == current
560988249a5SRiver Riddle              ? condBranchOp.trueDestOperands()[index]
561988249a5SRiver Riddle              : condBranchOp.falseDestOperands()[index];
5625d7231d8SStephan Herhut }
5635d7231d8SStephan Herhut 
5645e7959a3SAlex Zinenko void ModuleTranslation::connectPHINodes(LLVMFuncOp func) {
5655d7231d8SStephan Herhut   // Skip the first block, it cannot be branched to and its arguments correspond
5665d7231d8SStephan Herhut   // to the arguments of the LLVM function.
5675d7231d8SStephan Herhut   for (auto it = std::next(func.begin()), eit = func.end(); it != eit; ++it) {
5685d7231d8SStephan Herhut     Block *bb = &*it;
5695d7231d8SStephan Herhut     llvm::BasicBlock *llvmBB = blockMapping.lookup(bb);
5705d7231d8SStephan Herhut     auto phis = llvmBB->phis();
5715d7231d8SStephan Herhut     auto numArguments = bb->getNumArguments();
5725d7231d8SStephan Herhut     assert(numArguments == std::distance(phis.begin(), phis.end()));
5735d7231d8SStephan Herhut     for (auto &numberedPhiNode : llvm::enumerate(phis)) {
5745d7231d8SStephan Herhut       auto &phiNode = numberedPhiNode.value();
5755d7231d8SStephan Herhut       unsigned index = numberedPhiNode.index();
5765d7231d8SStephan Herhut       for (auto *pred : bb->getPredecessors()) {
5775d7231d8SStephan Herhut         phiNode.addIncoming(valueMapping.lookup(getPHISourceValue(
5785d7231d8SStephan Herhut                                 bb, pred, numArguments, index)),
5795d7231d8SStephan Herhut                             blockMapping.lookup(pred));
5805d7231d8SStephan Herhut       }
5815d7231d8SStephan Herhut     }
5825d7231d8SStephan Herhut   }
5835d7231d8SStephan Herhut }
5845d7231d8SStephan Herhut 
5855d7231d8SStephan Herhut // TODO(mlir-team): implement an iterative version
5865d7231d8SStephan Herhut static void topologicalSortImpl(llvm::SetVector<Block *> &blocks, Block *b) {
5875d7231d8SStephan Herhut   blocks.insert(b);
5885d7231d8SStephan Herhut   for (Block *bb : b->getSuccessors()) {
5895d7231d8SStephan Herhut     if (blocks.count(bb) == 0)
5905d7231d8SStephan Herhut       topologicalSortImpl(blocks, bb);
5915d7231d8SStephan Herhut   }
5925d7231d8SStephan Herhut }
5935d7231d8SStephan Herhut 
5942666b973SRiver Riddle /// Sort function blocks topologically.
5955e7959a3SAlex Zinenko static llvm::SetVector<Block *> topologicalSort(LLVMFuncOp f) {
5965d7231d8SStephan Herhut   // For each blocks that has not been visited yet (i.e. that has no
5975d7231d8SStephan Herhut   // predecessors), add it to the list and traverse its successors in DFS
5985d7231d8SStephan Herhut   // preorder.
5995d7231d8SStephan Herhut   llvm::SetVector<Block *> blocks;
6005d7231d8SStephan Herhut   for (Block &b : f.getBlocks()) {
6015d7231d8SStephan Herhut     if (blocks.count(&b) == 0)
6025d7231d8SStephan Herhut       topologicalSortImpl(blocks, &b);
6035d7231d8SStephan Herhut   }
6045d7231d8SStephan Herhut   assert(blocks.size() == f.getBlocks().size() && "some blocks are not sorted");
6055d7231d8SStephan Herhut 
6065d7231d8SStephan Herhut   return blocks;
6075d7231d8SStephan Herhut }
6085d7231d8SStephan Herhut 
6090a2131b7SAlex Zinenko /// Attempts to add an attribute identified by `key`, optionally with the given
6100a2131b7SAlex Zinenko /// `value` to LLVM function `llvmFunc`. Reports errors at `loc` if any. If the
6110a2131b7SAlex Zinenko /// attribute has a kind known to LLVM IR, create the attribute of this kind,
6120a2131b7SAlex Zinenko /// otherwise keep it as a string attribute. Performs additional checks for
6130a2131b7SAlex Zinenko /// attributes known to have or not have a value in order to avoid assertions
6140a2131b7SAlex Zinenko /// inside LLVM upon construction.
6150a2131b7SAlex Zinenko static LogicalResult checkedAddLLVMFnAttribute(Location loc,
6160a2131b7SAlex Zinenko                                                llvm::Function *llvmFunc,
6170a2131b7SAlex Zinenko                                                StringRef key,
6180a2131b7SAlex Zinenko                                                StringRef value = StringRef()) {
6190a2131b7SAlex Zinenko   auto kind = llvm::Attribute::getAttrKindFromName(key);
6200a2131b7SAlex Zinenko   if (kind == llvm::Attribute::None) {
6210a2131b7SAlex Zinenko     llvmFunc->addFnAttr(key, value);
6220a2131b7SAlex Zinenko     return success();
6230a2131b7SAlex Zinenko   }
6240a2131b7SAlex Zinenko 
6250a2131b7SAlex Zinenko   if (llvm::Attribute::doesAttrKindHaveArgument(kind)) {
6260a2131b7SAlex Zinenko     if (value.empty())
6270a2131b7SAlex Zinenko       return emitError(loc) << "LLVM attribute '" << key << "' expects a value";
6280a2131b7SAlex Zinenko 
6290a2131b7SAlex Zinenko     int result;
6300a2131b7SAlex Zinenko     if (!value.getAsInteger(/*Radix=*/0, result))
6310a2131b7SAlex Zinenko       llvmFunc->addFnAttr(
6320a2131b7SAlex Zinenko           llvm::Attribute::get(llvmFunc->getContext(), kind, result));
6330a2131b7SAlex Zinenko     else
6340a2131b7SAlex Zinenko       llvmFunc->addFnAttr(key, value);
6350a2131b7SAlex Zinenko     return success();
6360a2131b7SAlex Zinenko   }
6370a2131b7SAlex Zinenko 
6380a2131b7SAlex Zinenko   if (!value.empty())
6390a2131b7SAlex Zinenko     return emitError(loc) << "LLVM attribute '" << key
6400a2131b7SAlex Zinenko                           << "' does not expect a value, found '" << value
6410a2131b7SAlex Zinenko                           << "'";
6420a2131b7SAlex Zinenko 
6430a2131b7SAlex Zinenko   llvmFunc->addFnAttr(kind);
6440a2131b7SAlex Zinenko   return success();
6450a2131b7SAlex Zinenko }
6460a2131b7SAlex Zinenko 
6470a2131b7SAlex Zinenko /// Attaches the attributes listed in the given array attribute to `llvmFunc`.
6480a2131b7SAlex Zinenko /// Reports error to `loc` if any and returns immediately. Expects `attributes`
6490a2131b7SAlex Zinenko /// to be an array attribute containing either string attributes, treated as
6500a2131b7SAlex Zinenko /// value-less LLVM attributes, or array attributes containing two string
6510a2131b7SAlex Zinenko /// attributes, with the first string being the name of the corresponding LLVM
6520a2131b7SAlex Zinenko /// attribute and the second string beings its value. Note that even integer
6530a2131b7SAlex Zinenko /// attributes are expected to have their values expressed as strings.
6540a2131b7SAlex Zinenko static LogicalResult
6550a2131b7SAlex Zinenko forwardPassthroughAttributes(Location loc, Optional<ArrayAttr> attributes,
6560a2131b7SAlex Zinenko                              llvm::Function *llvmFunc) {
6570a2131b7SAlex Zinenko   if (!attributes)
6580a2131b7SAlex Zinenko     return success();
6590a2131b7SAlex Zinenko 
6600a2131b7SAlex Zinenko   for (Attribute attr : *attributes) {
6610a2131b7SAlex Zinenko     if (auto stringAttr = attr.dyn_cast<StringAttr>()) {
6620a2131b7SAlex Zinenko       if (failed(
6630a2131b7SAlex Zinenko               checkedAddLLVMFnAttribute(loc, llvmFunc, stringAttr.getValue())))
6640a2131b7SAlex Zinenko         return failure();
6650a2131b7SAlex Zinenko       continue;
6660a2131b7SAlex Zinenko     }
6670a2131b7SAlex Zinenko 
6680a2131b7SAlex Zinenko     auto arrayAttr = attr.dyn_cast<ArrayAttr>();
6690a2131b7SAlex Zinenko     if (!arrayAttr || arrayAttr.size() != 2)
6700a2131b7SAlex Zinenko       return emitError(loc)
6710a2131b7SAlex Zinenko              << "expected 'passthrough' to contain string or array attributes";
6720a2131b7SAlex Zinenko 
6730a2131b7SAlex Zinenko     auto keyAttr = arrayAttr[0].dyn_cast<StringAttr>();
6740a2131b7SAlex Zinenko     auto valueAttr = arrayAttr[1].dyn_cast<StringAttr>();
6750a2131b7SAlex Zinenko     if (!keyAttr || !valueAttr)
6760a2131b7SAlex Zinenko       return emitError(loc)
6770a2131b7SAlex Zinenko              << "expected arrays within 'passthrough' to contain two strings";
6780a2131b7SAlex Zinenko 
6790a2131b7SAlex Zinenko     if (failed(checkedAddLLVMFnAttribute(loc, llvmFunc, keyAttr.getValue(),
6800a2131b7SAlex Zinenko                                          valueAttr.getValue())))
6810a2131b7SAlex Zinenko       return failure();
6820a2131b7SAlex Zinenko   }
6830a2131b7SAlex Zinenko   return success();
6840a2131b7SAlex Zinenko }
6850a2131b7SAlex Zinenko 
6865e7959a3SAlex Zinenko LogicalResult ModuleTranslation::convertOneFunction(LLVMFuncOp func) {
6875d7231d8SStephan Herhut   // Clear the block and value mappings, they are only relevant within one
6885d7231d8SStephan Herhut   // function.
6895d7231d8SStephan Herhut   blockMapping.clear();
6905d7231d8SStephan Herhut   valueMapping.clear();
691c33862b0SRiver Riddle   llvm::Function *llvmFunc = functionMapping.lookup(func.getName());
692c33d6970SRiver Riddle 
693c33d6970SRiver Riddle   // Translate the debug information for this function.
694c33d6970SRiver Riddle   debugTranslation->translate(func, *llvmFunc);
695c33d6970SRiver Riddle 
6965d7231d8SStephan Herhut   // Add function arguments to the value remapping table.
6975d7231d8SStephan Herhut   // If there was noalias info then we decorate each argument accordingly.
6985d7231d8SStephan Herhut   unsigned int argIdx = 0;
699eeef50b1SFangrui Song   for (auto kvp : llvm::zip(func.getArguments(), llvmFunc->args())) {
7005d7231d8SStephan Herhut     llvm::Argument &llvmArg = std::get<1>(kvp);
701e62a6956SRiver Riddle     BlockArgument mlirArg = std::get<0>(kvp);
7025d7231d8SStephan Herhut 
7035d7231d8SStephan Herhut     if (auto attr = func.getArgAttrOfType<BoolAttr>(argIdx, "llvm.noalias")) {
7045d7231d8SStephan Herhut       // NB: Attribute already verified to be boolean, so check if we can indeed
7055d7231d8SStephan Herhut       // attach the attribute to this argument, based on its type.
7062bdf33ccSRiver Riddle       auto argTy = mlirArg.getType().dyn_cast<LLVM::LLVMType>();
707baa1ec22SAlex Zinenko       if (!argTy.getUnderlyingType()->isPointerTy())
708baa1ec22SAlex Zinenko         return func.emitError(
7095d7231d8SStephan Herhut             "llvm.noalias attribute attached to LLVM non-pointer argument");
7105d7231d8SStephan Herhut       if (attr.getValue())
7115d7231d8SStephan Herhut         llvmArg.addAttr(llvm::Attribute::AttrKind::NoAlias);
7125d7231d8SStephan Herhut     }
7135d7231d8SStephan Herhut     valueMapping[mlirArg] = &llvmArg;
7145d7231d8SStephan Herhut     argIdx++;
7155d7231d8SStephan Herhut   }
7165d7231d8SStephan Herhut 
717ff77397fSShraiysh Vaishay   // Check the personality and set it.
718ff77397fSShraiysh Vaishay   if (func.personality().hasValue()) {
719ff77397fSShraiysh Vaishay     llvm::Type *ty = llvm::Type::getInt8PtrTy(llvmFunc->getContext());
720ff77397fSShraiysh Vaishay     if (llvm::Constant *pfunc =
721ff77397fSShraiysh Vaishay             getLLVMConstant(ty, func.personalityAttr(), func.getLoc()))
722ff77397fSShraiysh Vaishay       llvmFunc->setPersonalityFn(pfunc);
723ff77397fSShraiysh Vaishay   }
724ff77397fSShraiysh Vaishay 
7255d7231d8SStephan Herhut   // First, create all blocks so we can jump to them.
7265d7231d8SStephan Herhut   llvm::LLVMContext &llvmContext = llvmFunc->getContext();
7275d7231d8SStephan Herhut   for (auto &bb : func) {
7285d7231d8SStephan Herhut     auto *llvmBB = llvm::BasicBlock::Create(llvmContext);
7295d7231d8SStephan Herhut     llvmBB->insertInto(llvmFunc);
7305d7231d8SStephan Herhut     blockMapping[&bb] = llvmBB;
7315d7231d8SStephan Herhut   }
7325d7231d8SStephan Herhut 
7335d7231d8SStephan Herhut   // Then, convert blocks one by one in topological order to ensure defs are
7345d7231d8SStephan Herhut   // converted before uses.
7355d7231d8SStephan Herhut   auto blocks = topologicalSort(func);
7365d7231d8SStephan Herhut   for (auto indexedBB : llvm::enumerate(blocks)) {
7375d7231d8SStephan Herhut     auto *bb = indexedBB.value();
738baa1ec22SAlex Zinenko     if (failed(convertBlock(*bb, /*ignoreArguments=*/indexedBB.index() == 0)))
739baa1ec22SAlex Zinenko       return failure();
7405d7231d8SStephan Herhut   }
7415d7231d8SStephan Herhut 
7425d7231d8SStephan Herhut   // Finally, after all blocks have been traversed and values mapped, connect
7435d7231d8SStephan Herhut   // the PHI nodes to the results of preceding blocks.
7445d7231d8SStephan Herhut   connectPHINodes(func);
745baa1ec22SAlex Zinenko   return success();
7465d7231d8SStephan Herhut }
7475d7231d8SStephan Herhut 
74844fc7d72STres Popp LogicalResult ModuleTranslation::checkSupportedModuleOps(Operation *m) {
74944fc7d72STres Popp   for (Operation &o : getModuleBody(m).getOperations())
7504dde19f0SAlex Zinenko     if (!isa<LLVM::LLVMFuncOp>(&o) && !isa<LLVM::GlobalOp>(&o) &&
75144fc7d72STres Popp         !o.isKnownTerminator())
7524dde19f0SAlex Zinenko       return o.emitOpError("unsupported module-level operation");
7534dde19f0SAlex Zinenko   return success();
7544dde19f0SAlex Zinenko }
7554dde19f0SAlex Zinenko 
756baa1ec22SAlex Zinenko LogicalResult ModuleTranslation::convertFunctions() {
7575d7231d8SStephan Herhut   // Declare all functions first because there may be function calls that form a
7585d7231d8SStephan Herhut   // call graph with cycles.
75944fc7d72STres Popp   for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) {
7605e7959a3SAlex Zinenko     llvm::FunctionCallee llvmFuncCst = llvmModule->getOrInsertFunction(
7615e7959a3SAlex Zinenko         function.getName(),
7624562e389SRiver Riddle         cast<llvm::FunctionType>(function.getType().getUnderlyingType()));
7630a2131b7SAlex Zinenko     llvm::Function *llvmFunc = cast<llvm::Function>(llvmFuncCst.getCallee());
7640a2131b7SAlex Zinenko     functionMapping[function.getName()] = llvmFunc;
7650a2131b7SAlex Zinenko 
7660a2131b7SAlex Zinenko     // Forward the pass-through attributes to LLVM.
7670a2131b7SAlex Zinenko     if (failed(forwardPassthroughAttributes(function.getLoc(),
7680a2131b7SAlex Zinenko                                             function.passthrough(), llvmFunc)))
7690a2131b7SAlex Zinenko       return failure();
7705d7231d8SStephan Herhut   }
7715d7231d8SStephan Herhut 
7725d7231d8SStephan Herhut   // Convert functions.
77344fc7d72STres Popp   for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) {
7745d7231d8SStephan Herhut     // Ignore external functions.
7755d7231d8SStephan Herhut     if (function.isExternal())
7765d7231d8SStephan Herhut       continue;
7775d7231d8SStephan Herhut 
778baa1ec22SAlex Zinenko     if (failed(convertOneFunction(function)))
779baa1ec22SAlex Zinenko       return failure();
7805d7231d8SStephan Herhut   }
7815d7231d8SStephan Herhut 
782baa1ec22SAlex Zinenko   return success();
7835d7231d8SStephan Herhut }
7845d7231d8SStephan Herhut 
785efadb6b8SAlex Zinenko /// A helper to look up remapped operands in the value remapping table.`
786efadb6b8SAlex Zinenko SmallVector<llvm::Value *, 8>
787efadb6b8SAlex Zinenko ModuleTranslation::lookupValues(ValueRange values) {
788efadb6b8SAlex Zinenko   SmallVector<llvm::Value *, 8> remapped;
789efadb6b8SAlex Zinenko   remapped.reserve(values.size());
790ff77397fSShraiysh Vaishay   for (Value v : values) {
791ff77397fSShraiysh Vaishay     assert(valueMapping.count(v) && "referencing undefined value");
792efadb6b8SAlex Zinenko     remapped.push_back(valueMapping.lookup(v));
793ff77397fSShraiysh Vaishay   }
794efadb6b8SAlex Zinenko   return remapped;
795efadb6b8SAlex Zinenko }
796efadb6b8SAlex Zinenko 
79744fc7d72STres Popp std::unique_ptr<llvm::Module>
79844fc7d72STres Popp ModuleTranslation::prepareLLVMModule(Operation *m) {
79944fc7d72STres Popp   auto *dialect = m->getContext()->getRegisteredDialect<LLVM::LLVMDialect>();
8005d7231d8SStephan Herhut   assert(dialect && "LLVM dialect must be registered");
8015d7231d8SStephan Herhut 
802bc5c7378SRiver Riddle   auto llvmModule = llvm::CloneModule(dialect->getLLVMModule());
8035d7231d8SStephan Herhut   if (!llvmModule)
8045d7231d8SStephan Herhut     return nullptr;
8055d7231d8SStephan Herhut 
8065d7231d8SStephan Herhut   llvm::LLVMContext &llvmContext = llvmModule->getContext();
8075d7231d8SStephan Herhut   llvm::IRBuilder<> builder(llvmContext);
8085d7231d8SStephan Herhut 
8095d7231d8SStephan Herhut   // Inject declarations for `malloc` and `free` functions that can be used in
8105d7231d8SStephan Herhut   // memref allocation/deallocation coming from standard ops lowering.
8115d7231d8SStephan Herhut   llvmModule->getOrInsertFunction("malloc", builder.getInt8PtrTy(),
8125d7231d8SStephan Herhut                                   builder.getInt64Ty());
8135d7231d8SStephan Herhut   llvmModule->getOrInsertFunction("free", builder.getVoidTy(),
8145d7231d8SStephan Herhut                                   builder.getInt8PtrTy());
8155d7231d8SStephan Herhut 
8165d7231d8SStephan Herhut   return llvmModule;
8175d7231d8SStephan Herhut }
818