1cde4d5a6SJacques Pienaar //===- ModuleTranslation.cpp - MLIR to LLVM conversion --------------------===// 25d7231d8SStephan Herhut // 330857107SMehdi Amini // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 456222a06SMehdi Amini // See https://llvm.org/LICENSE.txt for license information. 556222a06SMehdi Amini // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 65d7231d8SStephan Herhut // 756222a06SMehdi Amini //===----------------------------------------------------------------------===// 85d7231d8SStephan Herhut // 95d7231d8SStephan Herhut // This file implements the translation between an MLIR LLVM dialect module and 105d7231d8SStephan Herhut // the corresponding LLVMIR module. It only handles core LLVM IR operations. 115d7231d8SStephan Herhut // 125d7231d8SStephan Herhut //===----------------------------------------------------------------------===// 135d7231d8SStephan Herhut 145d7231d8SStephan Herhut #include "mlir/Target/LLVMIR/ModuleTranslation.h" 155d7231d8SStephan Herhut 16c33d6970SRiver Riddle #include "DebugTranslation.h" 17ba0fa925SRiver Riddle #include "mlir/Dialect/LLVMIR/LLVMDialect.h" 18ce8f10d6SAlex Zinenko #include "mlir/Dialect/LLVMIR/Transforms/LegalizeForExport.h" 1992a295ebSKiran Chandramohan #include "mlir/Dialect/OpenMP/OpenMPDialect.h" 205d7231d8SStephan Herhut #include "mlir/IR/Attributes.h" 2165fcddffSRiver Riddle #include "mlir/IR/BuiltinOps.h" 2209f7a55fSRiver Riddle #include "mlir/IR/BuiltinTypes.h" 23d4568ed7SGeorge Mitenkov #include "mlir/IR/RegionGraphTraits.h" 245d7231d8SStephan Herhut #include "mlir/Support/LLVM.h" 25b77bac05SAlex Zinenko #include "mlir/Target/LLVMIR/LLVMTranslationInterface.h" 26929189a4SWilliam S. Moses #include "mlir/Target/LLVMIR/TypeToLLVM.h" 27ebf190fcSRiver Riddle #include "llvm/ADT/TypeSwitch.h" 285d7231d8SStephan Herhut 29d4568ed7SGeorge Mitenkov #include "llvm/ADT/PostOrderIterator.h" 305d7231d8SStephan Herhut #include "llvm/ADT/SetVector.h" 3192a295ebSKiran Chandramohan #include "llvm/Frontend/OpenMP/OMPIRBuilder.h" 325d7231d8SStephan Herhut #include "llvm/IR/BasicBlock.h" 33d9067dcaSKiran Chandramohan #include "llvm/IR/CFG.h" 345d7231d8SStephan Herhut #include "llvm/IR/Constants.h" 355d7231d8SStephan Herhut #include "llvm/IR/DerivedTypes.h" 365d7231d8SStephan Herhut #include "llvm/IR/IRBuilder.h" 37047400edSNicolas Vasilache #include "llvm/IR/InlineAsm.h" 38875eb523SNavdeep Kumar #include "llvm/IR/IntrinsicsNVPTX.h" 395d7231d8SStephan Herhut #include "llvm/IR/LLVMContext.h" 4099d03f03SGeorge Mitenkov #include "llvm/IR/MDBuilder.h" 415d7231d8SStephan Herhut #include "llvm/IR/Module.h" 42ce8f10d6SAlex Zinenko #include "llvm/IR/Verifier.h" 43d9067dcaSKiran Chandramohan #include "llvm/Transforms/Utils/BasicBlockUtils.h" 445d7231d8SStephan Herhut #include "llvm/Transforms/Utils/Cloning.h" 455d7231d8SStephan Herhut 462666b973SRiver Riddle using namespace mlir; 472666b973SRiver Riddle using namespace mlir::LLVM; 48c33d6970SRiver Riddle using namespace mlir::LLVM::detail; 495d7231d8SStephan Herhut 50eb67bd78SAlex Zinenko #include "mlir/Dialect/LLVMIR/LLVMConversionEnumsToLLVM.inc" 51eb67bd78SAlex Zinenko 52a922e231SAlex Zinenko /// Builds a constant of a sequential LLVM type `type`, potentially containing 53a922e231SAlex Zinenko /// other sequential types recursively, from the individual constant values 54a922e231SAlex Zinenko /// provided in `constants`. `shape` contains the number of elements in nested 55a922e231SAlex Zinenko /// sequential types. Reports errors at `loc` and returns nullptr on error. 56a4a42160SAlex Zinenko static llvm::Constant * 57a4a42160SAlex Zinenko buildSequentialConstant(ArrayRef<llvm::Constant *> &constants, 58a4a42160SAlex Zinenko ArrayRef<int64_t> shape, llvm::Type *type, 59a4a42160SAlex Zinenko Location loc) { 60a4a42160SAlex Zinenko if (shape.empty()) { 61a4a42160SAlex Zinenko llvm::Constant *result = constants.front(); 62a4a42160SAlex Zinenko constants = constants.drop_front(); 63a4a42160SAlex Zinenko return result; 64a4a42160SAlex Zinenko } 65a4a42160SAlex Zinenko 6668b03aeeSEli Friedman llvm::Type *elementType; 6768b03aeeSEli Friedman if (auto *arrayTy = dyn_cast<llvm::ArrayType>(type)) { 6868b03aeeSEli Friedman elementType = arrayTy->getElementType(); 6968b03aeeSEli Friedman } else if (auto *vectorTy = dyn_cast<llvm::VectorType>(type)) { 7068b03aeeSEli Friedman elementType = vectorTy->getElementType(); 7168b03aeeSEli Friedman } else { 72a4a42160SAlex Zinenko emitError(loc) << "expected sequential LLVM types wrapping a scalar"; 73a4a42160SAlex Zinenko return nullptr; 74a4a42160SAlex Zinenko } 75a4a42160SAlex Zinenko 76a4a42160SAlex Zinenko SmallVector<llvm::Constant *, 8> nested; 77a4a42160SAlex Zinenko nested.reserve(shape.front()); 78a4a42160SAlex Zinenko for (int64_t i = 0; i < shape.front(); ++i) { 79a4a42160SAlex Zinenko nested.push_back(buildSequentialConstant(constants, shape.drop_front(), 80a4a42160SAlex Zinenko elementType, loc)); 81a4a42160SAlex Zinenko if (!nested.back()) 82a4a42160SAlex Zinenko return nullptr; 83a4a42160SAlex Zinenko } 84a4a42160SAlex Zinenko 85a4a42160SAlex Zinenko if (shape.size() == 1 && type->isVectorTy()) 86a4a42160SAlex Zinenko return llvm::ConstantVector::get(nested); 87a4a42160SAlex Zinenko return llvm::ConstantArray::get( 88a4a42160SAlex Zinenko llvm::ArrayType::get(elementType, shape.front()), nested); 89a4a42160SAlex Zinenko } 90a4a42160SAlex Zinenko 91fc817b09SKazuaki Ishizaki /// Returns the first non-sequential type nested in sequential types. 92a4a42160SAlex Zinenko static llvm::Type *getInnermostElementType(llvm::Type *type) { 9368b03aeeSEli Friedman do { 9468b03aeeSEli Friedman if (auto *arrayTy = dyn_cast<llvm::ArrayType>(type)) { 9568b03aeeSEli Friedman type = arrayTy->getElementType(); 9668b03aeeSEli Friedman } else if (auto *vectorTy = dyn_cast<llvm::VectorType>(type)) { 9768b03aeeSEli Friedman type = vectorTy->getElementType(); 9868b03aeeSEli Friedman } else { 99a4a42160SAlex Zinenko return type; 100a4a42160SAlex Zinenko } 1010881a4f1SAlex Zinenko } while (true); 10268b03aeeSEli Friedman } 103a4a42160SAlex Zinenko 1042666b973SRiver Riddle /// Create an LLVM IR constant of `llvmType` from the MLIR attribute `attr`. 1052666b973SRiver Riddle /// This currently supports integer, floating point, splat and dense element 1065ef21506SAdrian Kuegel /// attributes and combinations thereof. Also, an array attribute with two 1075ef21506SAdrian Kuegel /// elements is supported to represent a complex constant. In case of error, 1085ef21506SAdrian Kuegel /// report it to `loc` and return nullptr. 109176379e0SAlex Zinenko llvm::Constant *mlir::LLVM::detail::getLLVMConstant( 110176379e0SAlex Zinenko llvm::Type *llvmType, Attribute attr, Location loc, 1115ef21506SAdrian Kuegel const ModuleTranslation &moduleTranslation, bool isTopLevel) { 11233a3a91bSChristian Sigg if (!attr) 11333a3a91bSChristian Sigg return llvm::UndefValue::get(llvmType); 1145ef21506SAdrian Kuegel if (auto *structType = dyn_cast<::llvm::StructType>(llvmType)) { 1155ef21506SAdrian Kuegel if (!isTopLevel) { 1165ef21506SAdrian Kuegel emitError(loc, "nested struct types are not supported in constants"); 117a4a42160SAlex Zinenko return nullptr; 118a4a42160SAlex Zinenko } 1195ef21506SAdrian Kuegel auto arrayAttr = attr.cast<ArrayAttr>(); 1205ef21506SAdrian Kuegel llvm::Type *elementType = structType->getElementType(0); 1215ef21506SAdrian Kuegel llvm::Constant *real = getLLVMConstant(elementType, arrayAttr[0], loc, 1225ef21506SAdrian Kuegel moduleTranslation, false); 1235ef21506SAdrian Kuegel if (!real) 1245ef21506SAdrian Kuegel return nullptr; 1255ef21506SAdrian Kuegel llvm::Constant *imag = getLLVMConstant(elementType, arrayAttr[1], loc, 1265ef21506SAdrian Kuegel moduleTranslation, false); 1275ef21506SAdrian Kuegel if (!imag) 1285ef21506SAdrian Kuegel return nullptr; 1295ef21506SAdrian Kuegel return llvm::ConstantStruct::get(structType, {real, imag}); 1305ef21506SAdrian Kuegel } 131ac9d742bSStephan Herhut // For integer types, we allow a mismatch in sizes as the index type in 132ac9d742bSStephan Herhut // MLIR might have a different size than the index type in the LLVM module. 1335d7231d8SStephan Herhut if (auto intAttr = attr.dyn_cast<IntegerAttr>()) 134ac9d742bSStephan Herhut return llvm::ConstantInt::get( 135ac9d742bSStephan Herhut llvmType, 136ac9d742bSStephan Herhut intAttr.getValue().sextOrTrunc(llvmType->getIntegerBitWidth())); 1375ef21506SAdrian Kuegel if (auto floatAttr = attr.dyn_cast<FloatAttr>()) { 1385ef21506SAdrian Kuegel if (llvmType != 1395ef21506SAdrian Kuegel llvm::Type::getFloatingPointTy(llvmType->getContext(), 1405ef21506SAdrian Kuegel floatAttr.getValue().getSemantics())) { 1415ef21506SAdrian Kuegel emitError(loc, "FloatAttr does not match expected type of the constant"); 1425ef21506SAdrian Kuegel return nullptr; 1435ef21506SAdrian Kuegel } 1445d7231d8SStephan Herhut return llvm::ConstantFP::get(llvmType, floatAttr.getValue()); 1455ef21506SAdrian Kuegel } 1469b9c647cSRiver Riddle if (auto funcAttr = attr.dyn_cast<FlatSymbolRefAttr>()) 147176379e0SAlex Zinenko return llvm::ConstantExpr::getBitCast( 148176379e0SAlex Zinenko moduleTranslation.lookupFunction(funcAttr.getValue()), llvmType); 1495d7231d8SStephan Herhut if (auto splatAttr = attr.dyn_cast<SplatElementsAttr>()) { 15068b03aeeSEli Friedman llvm::Type *elementType; 15168b03aeeSEli Friedman uint64_t numElements; 15268b03aeeSEli Friedman if (auto *arrayTy = dyn_cast<llvm::ArrayType>(llvmType)) { 15368b03aeeSEli Friedman elementType = arrayTy->getElementType(); 15468b03aeeSEli Friedman numElements = arrayTy->getNumElements(); 15568b03aeeSEli Friedman } else { 1565cba1c63SChristopher Tetreault auto *vectorTy = cast<llvm::FixedVectorType>(llvmType); 15768b03aeeSEli Friedman elementType = vectorTy->getElementType(); 15868b03aeeSEli Friedman numElements = vectorTy->getNumElements(); 15968b03aeeSEli Friedman } 160d6ea8ff0SAlex Zinenko // Splat value is a scalar. Extract it only if the element type is not 161d6ea8ff0SAlex Zinenko // another sequence type. The recursion terminates because each step removes 162d6ea8ff0SAlex Zinenko // one outer sequential type. 16368b03aeeSEli Friedman bool elementTypeSequential = 164d891d738SRahul Joshi isa<llvm::ArrayType, llvm::VectorType>(elementType); 165d6ea8ff0SAlex Zinenko llvm::Constant *child = getLLVMConstant( 166d6ea8ff0SAlex Zinenko elementType, 167176379e0SAlex Zinenko elementTypeSequential ? splatAttr : splatAttr.getSplatValue(), loc, 1685ef21506SAdrian Kuegel moduleTranslation, false); 169a4a42160SAlex Zinenko if (!child) 170a4a42160SAlex Zinenko return nullptr; 1712f13df13SMLIR Team if (llvmType->isVectorTy()) 172396a42d9SRiver Riddle return llvm::ConstantVector::getSplat( 1730f95e731SAlex Zinenko llvm::ElementCount::get(numElements, /*Scalable=*/false), child); 1742f13df13SMLIR Team if (llvmType->isArrayTy()) { 175ac9d742bSStephan Herhut auto *arrayType = llvm::ArrayType::get(elementType, numElements); 1762f13df13SMLIR Team SmallVector<llvm::Constant *, 8> constants(numElements, child); 1772f13df13SMLIR Team return llvm::ConstantArray::get(arrayType, constants); 1782f13df13SMLIR Team } 1795d7231d8SStephan Herhut } 180a4a42160SAlex Zinenko 181d906f84bSRiver Riddle if (auto elementsAttr = attr.dyn_cast<ElementsAttr>()) { 182a4a42160SAlex Zinenko assert(elementsAttr.getType().hasStaticShape()); 183a4a42160SAlex Zinenko assert(elementsAttr.getNumElements() != 0 && 184a4a42160SAlex Zinenko "unexpected empty elements attribute"); 185a4a42160SAlex Zinenko assert(!elementsAttr.getType().getShape().empty() && 186a4a42160SAlex Zinenko "unexpected empty elements attribute shape"); 187a4a42160SAlex Zinenko 1885d7231d8SStephan Herhut SmallVector<llvm::Constant *, 8> constants; 189a4a42160SAlex Zinenko constants.reserve(elementsAttr.getNumElements()); 190a4a42160SAlex Zinenko llvm::Type *innermostType = getInnermostElementType(llvmType); 191d906f84bSRiver Riddle for (auto n : elementsAttr.getValues<Attribute>()) { 192176379e0SAlex Zinenko constants.push_back( 1935ef21506SAdrian Kuegel getLLVMConstant(innermostType, n, loc, moduleTranslation, false)); 1945d7231d8SStephan Herhut if (!constants.back()) 1955d7231d8SStephan Herhut return nullptr; 1965d7231d8SStephan Herhut } 197a4a42160SAlex Zinenko ArrayRef<llvm::Constant *> constantsRef = constants; 198a4a42160SAlex Zinenko llvm::Constant *result = buildSequentialConstant( 199a4a42160SAlex Zinenko constantsRef, elementsAttr.getType().getShape(), llvmType, loc); 200a4a42160SAlex Zinenko assert(constantsRef.empty() && "did not consume all elemental constants"); 201a4a42160SAlex Zinenko return result; 2022f13df13SMLIR Team } 203a4a42160SAlex Zinenko 204cb348dffSStephan Herhut if (auto stringAttr = attr.dyn_cast<StringAttr>()) { 205cb348dffSStephan Herhut return llvm::ConstantDataArray::get( 206176379e0SAlex Zinenko moduleTranslation.getLLVMContext(), 207176379e0SAlex Zinenko ArrayRef<char>{stringAttr.getValue().data(), 208cb348dffSStephan Herhut stringAttr.getValue().size()}); 209cb348dffSStephan Herhut } 210a4c3a645SRiver Riddle emitError(loc, "unsupported constant value"); 2115d7231d8SStephan Herhut return nullptr; 2125d7231d8SStephan Herhut } 2135d7231d8SStephan Herhut 214c33d6970SRiver Riddle ModuleTranslation::ModuleTranslation(Operation *module, 215c33d6970SRiver Riddle std::unique_ptr<llvm::Module> llvmModule) 216c33d6970SRiver Riddle : mlirModule(module), llvmModule(std::move(llvmModule)), 217c33d6970SRiver Riddle debugTranslation( 21892a295ebSKiran Chandramohan std::make_unique<DebugTranslation>(module, *this->llvmModule)), 219b77bac05SAlex Zinenko typeTranslator(this->llvmModule->getContext()), 220b77bac05SAlex Zinenko iface(module->getContext()) { 221c33d6970SRiver Riddle assert(satisfiesLLVMModule(mlirModule) && 222c33d6970SRiver Riddle "mlirModule should honor LLVM's module semantics."); 223c33d6970SRiver Riddle } 224d9067dcaSKiran Chandramohan ModuleTranslation::~ModuleTranslation() { 225d9067dcaSKiran Chandramohan if (ompBuilder) 226d9067dcaSKiran Chandramohan ompBuilder->finalize(); 227d9067dcaSKiran Chandramohan } 228d9067dcaSKiran Chandramohan 229d9067dcaSKiran Chandramohan /// Get the SSA value passed to the current block from the terminator operation 230d9067dcaSKiran Chandramohan /// of its predecessor. 231d9067dcaSKiran Chandramohan static Value getPHISourceValue(Block *current, Block *pred, 232d9067dcaSKiran Chandramohan unsigned numArguments, unsigned index) { 233d9067dcaSKiran Chandramohan Operation &terminator = *pred->getTerminator(); 234d9067dcaSKiran Chandramohan if (isa<LLVM::BrOp>(terminator)) 235d9067dcaSKiran Chandramohan return terminator.getOperand(index); 236d9067dcaSKiran Chandramohan 23714f24155SBrian Gesiak SuccessorRange successors = terminator.getSuccessors(); 23814f24155SBrian Gesiak assert(std::adjacent_find(successors.begin(), successors.end()) == 23914f24155SBrian Gesiak successors.end() && 24014f24155SBrian Gesiak "successors with arguments in LLVM branches must be different blocks"); 24158f2b765SChristian Sigg (void)successors; 242d9067dcaSKiran Chandramohan 24314f24155SBrian Gesiak // For instructions that branch based on a condition value, we need to take 24414f24155SBrian Gesiak // the operands for the branch that was taken. 24514f24155SBrian Gesiak if (auto condBranchOp = dyn_cast<LLVM::CondBrOp>(terminator)) { 24614f24155SBrian Gesiak // For conditional branches, we take the operands from either the "true" or 24714f24155SBrian Gesiak // the "false" branch. 248d9067dcaSKiran Chandramohan return condBranchOp.getSuccessor(0) == current 249d9067dcaSKiran Chandramohan ? condBranchOp.trueDestOperands()[index] 250d9067dcaSKiran Chandramohan : condBranchOp.falseDestOperands()[index]; 2510881a4f1SAlex Zinenko } 2520881a4f1SAlex Zinenko 2530881a4f1SAlex Zinenko if (auto switchOp = dyn_cast<LLVM::SwitchOp>(terminator)) { 25414f24155SBrian Gesiak // For switches, we take the operands from either the default case, or from 25514f24155SBrian Gesiak // the case branch that was taken. 25614f24155SBrian Gesiak if (switchOp.defaultDestination() == current) 25714f24155SBrian Gesiak return switchOp.defaultOperands()[index]; 25814f24155SBrian Gesiak for (auto i : llvm::enumerate(switchOp.caseDestinations())) 25914f24155SBrian Gesiak if (i.value() == current) 26014f24155SBrian Gesiak return switchOp.getCaseOperands(i.index())[index]; 26114f24155SBrian Gesiak } 26214f24155SBrian Gesiak 26314f24155SBrian Gesiak llvm_unreachable("only branch or switch operations can be terminators of a " 26414f24155SBrian Gesiak "block that has successors"); 265d9067dcaSKiran Chandramohan } 266d9067dcaSKiran Chandramohan 267d9067dcaSKiran Chandramohan /// Connect the PHI nodes to the results of preceding blocks. 26866900b3eSAlex Zinenko void mlir::LLVM::detail::connectPHINodes(Region ®ion, 26966900b3eSAlex Zinenko const ModuleTranslation &state) { 270d9067dcaSKiran Chandramohan // Skip the first block, it cannot be branched to and its arguments correspond 271d9067dcaSKiran Chandramohan // to the arguments of the LLVM function. 27266900b3eSAlex Zinenko for (auto it = std::next(region.begin()), eit = region.end(); it != eit; 27366900b3eSAlex Zinenko ++it) { 274d9067dcaSKiran Chandramohan Block *bb = &*it; 2750881a4f1SAlex Zinenko llvm::BasicBlock *llvmBB = state.lookupBlock(bb); 276d9067dcaSKiran Chandramohan auto phis = llvmBB->phis(); 277d9067dcaSKiran Chandramohan auto numArguments = bb->getNumArguments(); 278d9067dcaSKiran Chandramohan assert(numArguments == std::distance(phis.begin(), phis.end())); 279d9067dcaSKiran Chandramohan for (auto &numberedPhiNode : llvm::enumerate(phis)) { 280d9067dcaSKiran Chandramohan auto &phiNode = numberedPhiNode.value(); 281d9067dcaSKiran Chandramohan unsigned index = numberedPhiNode.index(); 282d9067dcaSKiran Chandramohan for (auto *pred : bb->getPredecessors()) { 283db884dafSAlex Zinenko // Find the LLVM IR block that contains the converted terminator 284db884dafSAlex Zinenko // instruction and use it in the PHI node. Note that this block is not 2850881a4f1SAlex Zinenko // necessarily the same as state.lookupBlock(pred), some operations 286db884dafSAlex Zinenko // (in particular, OpenMP operations using OpenMPIRBuilder) may have 287db884dafSAlex Zinenko // split the blocks. 288db884dafSAlex Zinenko llvm::Instruction *terminator = 2890881a4f1SAlex Zinenko state.lookupBranch(pred->getTerminator()); 290db884dafSAlex Zinenko assert(terminator && "missing the mapping for a terminator"); 2910881a4f1SAlex Zinenko phiNode.addIncoming( 2920881a4f1SAlex Zinenko state.lookupValue(getPHISourceValue(bb, pred, numArguments, index)), 293db884dafSAlex Zinenko terminator->getParent()); 294d9067dcaSKiran Chandramohan } 295d9067dcaSKiran Chandramohan } 296d9067dcaSKiran Chandramohan } 297d9067dcaSKiran Chandramohan } 298d9067dcaSKiran Chandramohan 299d9067dcaSKiran Chandramohan /// Sort function blocks topologically. 3004efb7754SRiver Riddle SetVector<Block *> 30166900b3eSAlex Zinenko mlir::LLVM::detail::getTopologicallySortedBlocks(Region ®ion) { 302d4568ed7SGeorge Mitenkov // For each block that has not been visited yet (i.e. that has no 303d4568ed7SGeorge Mitenkov // predecessors), add it to the list as well as its successors. 3044efb7754SRiver Riddle SetVector<Block *> blocks; 30566900b3eSAlex Zinenko for (Block &b : region) { 306d4568ed7SGeorge Mitenkov if (blocks.count(&b) == 0) { 307d4568ed7SGeorge Mitenkov llvm::ReversePostOrderTraversal<Block *> traversal(&b); 308d4568ed7SGeorge Mitenkov blocks.insert(traversal.begin(), traversal.end()); 309d4568ed7SGeorge Mitenkov } 310d9067dcaSKiran Chandramohan } 31166900b3eSAlex Zinenko assert(blocks.size() == region.getBlocks().size() && 31266900b3eSAlex Zinenko "some blocks are not sorted"); 313d9067dcaSKiran Chandramohan 314d9067dcaSKiran Chandramohan return blocks; 315d9067dcaSKiran Chandramohan } 316d9067dcaSKiran Chandramohan 317176379e0SAlex Zinenko llvm::Value *mlir::LLVM::detail::createIntrinsicCall( 318176379e0SAlex Zinenko llvm::IRBuilderBase &builder, llvm::Intrinsic::ID intrinsic, 319176379e0SAlex Zinenko ArrayRef<llvm::Value *> args, ArrayRef<llvm::Type *> tys) { 320176379e0SAlex Zinenko llvm::Module *module = builder.GetInsertBlock()->getModule(); 321176379e0SAlex Zinenko llvm::Function *fn = llvm::Intrinsic::getDeclaration(module, intrinsic, tys); 322176379e0SAlex Zinenko return builder.CreateCall(fn, args); 323176379e0SAlex Zinenko } 324176379e0SAlex Zinenko 325875eb523SNavdeep Kumar llvm::Value * 326875eb523SNavdeep Kumar mlir::LLVM::detail::createNvvmIntrinsicCall(llvm::IRBuilderBase &builder, 327875eb523SNavdeep Kumar llvm::Intrinsic::ID intrinsic, 328875eb523SNavdeep Kumar ArrayRef<llvm::Value *> args) { 329875eb523SNavdeep Kumar llvm::Module *module = builder.GetInsertBlock()->getModule(); 330875eb523SNavdeep Kumar llvm::Function *fn; 331875eb523SNavdeep Kumar if (llvm::Intrinsic::isOverloaded(intrinsic)) { 332875eb523SNavdeep Kumar if (intrinsic != llvm::Intrinsic::nvvm_wmma_m16n16k16_mma_row_row_f16_f16 && 333875eb523SNavdeep Kumar intrinsic != llvm::Intrinsic::nvvm_wmma_m16n16k16_mma_row_row_f32_f32) { 334875eb523SNavdeep Kumar // NVVM load and store instrinsic names are overloaded on the 335875eb523SNavdeep Kumar // source/destination pointer type. Pointer is the first argument in the 336875eb523SNavdeep Kumar // corresponding NVVM Op. 337875eb523SNavdeep Kumar fn = llvm::Intrinsic::getDeclaration(module, intrinsic, 338875eb523SNavdeep Kumar {args[0]->getType()}); 339875eb523SNavdeep Kumar } else { 340875eb523SNavdeep Kumar fn = llvm::Intrinsic::getDeclaration(module, intrinsic, {}); 341875eb523SNavdeep Kumar } 342875eb523SNavdeep Kumar } else { 343875eb523SNavdeep Kumar fn = llvm::Intrinsic::getDeclaration(module, intrinsic); 344875eb523SNavdeep Kumar } 345875eb523SNavdeep Kumar return builder.CreateCall(fn, args); 346875eb523SNavdeep Kumar } 347875eb523SNavdeep Kumar 3482666b973SRiver Riddle /// Given a single MLIR operation, create the corresponding LLVM IR operation 349176379e0SAlex Zinenko /// using the `builder`. 350ce8f10d6SAlex Zinenko LogicalResult 35138b106f6SMehdi Amini ModuleTranslation::convertOperation(Operation &op, 352ce8f10d6SAlex Zinenko llvm::IRBuilderBase &builder) { 35338b106f6SMehdi Amini const LLVMTranslationDialectInterface *opIface = iface.getInterfaceFor(&op); 35438b106f6SMehdi Amini if (!opIface) 35538b106f6SMehdi Amini return op.emitError("cannot be converted to LLVM IR: missing " 35638b106f6SMehdi Amini "`LLVMTranslationDialectInterface` registration for " 35738b106f6SMehdi Amini "dialect for op: ") 35838b106f6SMehdi Amini << op.getName(); 359176379e0SAlex Zinenko 36038b106f6SMehdi Amini if (failed(opIface->convertOperation(&op, builder, *this))) 36138b106f6SMehdi Amini return op.emitError("LLVM Translation failed for operation: ") 36238b106f6SMehdi Amini << op.getName(); 36338b106f6SMehdi Amini 36438b106f6SMehdi Amini return convertDialectAttributes(&op); 3655d7231d8SStephan Herhut } 3665d7231d8SStephan Herhut 3672666b973SRiver Riddle /// Convert block to LLVM IR. Unless `ignoreArguments` is set, emit PHI nodes 3682666b973SRiver Riddle /// to define values corresponding to the MLIR block arguments. These nodes 36910164a2eSAlex Zinenko /// are not connected to the source basic blocks, which may not exist yet. Uses 37010164a2eSAlex Zinenko /// `builder` to construct the LLVM IR. Expects the LLVM IR basic block to have 37110164a2eSAlex Zinenko /// been created for `bb` and included in the block mapping. Inserts new 37210164a2eSAlex Zinenko /// instructions at the end of the block and leaves `builder` in a state 37310164a2eSAlex Zinenko /// suitable for further insertion into the end of the block. 37410164a2eSAlex Zinenko LogicalResult ModuleTranslation::convertBlock(Block &bb, bool ignoreArguments, 375ce8f10d6SAlex Zinenko llvm::IRBuilderBase &builder) { 3760881a4f1SAlex Zinenko builder.SetInsertPoint(lookupBlock(&bb)); 377c33d6970SRiver Riddle auto *subprogram = builder.GetInsertBlock()->getParent()->getSubprogram(); 3785d7231d8SStephan Herhut 3795d7231d8SStephan Herhut // Before traversing operations, make block arguments available through 3805d7231d8SStephan Herhut // value remapping and PHI nodes, but do not add incoming edges for the PHI 3815d7231d8SStephan Herhut // nodes just yet: those values may be defined by this or following blocks. 3825d7231d8SStephan Herhut // This step is omitted if "ignoreArguments" is set. The arguments of the 3835d7231d8SStephan Herhut // first block have been already made available through the remapping of 3845d7231d8SStephan Herhut // LLVM function arguments. 3855d7231d8SStephan Herhut if (!ignoreArguments) { 3865d7231d8SStephan Herhut auto predecessors = bb.getPredecessors(); 3875d7231d8SStephan Herhut unsigned numPredecessors = 3885d7231d8SStephan Herhut std::distance(predecessors.begin(), predecessors.end()); 38935807bc4SRiver Riddle for (auto arg : bb.getArguments()) { 390c69c9e0fSAlex Zinenko auto wrappedType = arg.getType(); 391c69c9e0fSAlex Zinenko if (!isCompatibleType(wrappedType)) 392baa1ec22SAlex Zinenko return emitError(bb.front().getLoc(), 393a4c3a645SRiver Riddle "block argument does not have an LLVM type"); 394aec38c61SAlex Zinenko llvm::Type *type = convertType(wrappedType); 3955d7231d8SStephan Herhut llvm::PHINode *phi = builder.CreatePHI(type, numPredecessors); 3960881a4f1SAlex Zinenko mapValue(arg, phi); 3975d7231d8SStephan Herhut } 3985d7231d8SStephan Herhut } 3995d7231d8SStephan Herhut 4005d7231d8SStephan Herhut // Traverse operations. 4015d7231d8SStephan Herhut for (auto &op : bb) { 402c33d6970SRiver Riddle // Set the current debug location within the builder. 403c33d6970SRiver Riddle builder.SetCurrentDebugLocation( 404c33d6970SRiver Riddle debugTranslation->translateLoc(op.getLoc(), subprogram)); 405c33d6970SRiver Riddle 406baa1ec22SAlex Zinenko if (failed(convertOperation(op, builder))) 407baa1ec22SAlex Zinenko return failure(); 4085d7231d8SStephan Herhut } 4095d7231d8SStephan Herhut 410baa1ec22SAlex Zinenko return success(); 4115d7231d8SStephan Herhut } 4125d7231d8SStephan Herhut 413ce8f10d6SAlex Zinenko /// A helper method to get the single Block in an operation honoring LLVM's 414ce8f10d6SAlex Zinenko /// module requirements. 415ce8f10d6SAlex Zinenko static Block &getModuleBody(Operation *module) { 416ce8f10d6SAlex Zinenko return module->getRegion(0).front(); 417ce8f10d6SAlex Zinenko } 418ce8f10d6SAlex Zinenko 419ffa455d4SJean Perier /// A helper method to decide if a constant must not be set as a global variable 420ffa455d4SJean Perier /// initializer. 421ffa455d4SJean Perier static bool shouldDropGlobalInitializer(llvm::GlobalValue::LinkageTypes linkage, 422ffa455d4SJean Perier llvm::Constant *cst) { 423ffa455d4SJean Perier return (linkage == llvm::GlobalVariable::ExternalLinkage && 424ffa455d4SJean Perier isa<llvm::UndefValue>(cst)) || 425ffa455d4SJean Perier linkage == llvm::GlobalVariable::ExternalWeakLinkage; 426ffa455d4SJean Perier } 427ffa455d4SJean Perier 428*8ca04b05SFelipe de Azevedo Piovezan /// Sets the runtime preemption specifier of `gv` to dso_local if 429*8ca04b05SFelipe de Azevedo Piovezan /// `dsoLocalRequested` is true, otherwise it is left unchanged. 430*8ca04b05SFelipe de Azevedo Piovezan static void addRuntimePreemptionSpecifier(bool dsoLocalRequested, 431*8ca04b05SFelipe de Azevedo Piovezan llvm::GlobalValue *gv) { 432*8ca04b05SFelipe de Azevedo Piovezan if (dsoLocalRequested) 433*8ca04b05SFelipe de Azevedo Piovezan gv->setDSOLocal(true); 434*8ca04b05SFelipe de Azevedo Piovezan } 435*8ca04b05SFelipe de Azevedo Piovezan 4362666b973SRiver Riddle /// Create named global variables that correspond to llvm.mlir.global 4372666b973SRiver Riddle /// definitions. 438efa2d533SAlex Zinenko LogicalResult ModuleTranslation::convertGlobals() { 43944fc7d72STres Popp for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) { 440aec38c61SAlex Zinenko llvm::Type *type = convertType(op.getType()); 441250a11aeSJames Molloy llvm::Constant *cst = llvm::UndefValue::get(type); 442250a11aeSJames Molloy if (op.getValueOrNull()) { 44368451df2SAlex Zinenko // String attributes are treated separately because they cannot appear as 44468451df2SAlex Zinenko // in-function constants and are thus not supported by getLLVMConstant. 44533a3a91bSChristian Sigg if (auto strAttr = op.getValueOrNull().dyn_cast_or_null<StringAttr>()) { 4462dd38b09SAlex Zinenko cst = llvm::ConstantDataArray::getString( 44768451df2SAlex Zinenko llvmModule->getContext(), strAttr.getValue(), /*AddNull=*/false); 4482dd38b09SAlex Zinenko type = cst->getType(); 449176379e0SAlex Zinenko } else if (!(cst = getLLVMConstant(type, op.getValueOrNull(), op.getLoc(), 450176379e0SAlex Zinenko *this))) { 451efa2d533SAlex Zinenko return failure(); 45268451df2SAlex Zinenko } 453ffa455d4SJean Perier } 454ffa455d4SJean Perier 455ffa455d4SJean Perier auto linkage = convertLinkageToLLVM(op.linkage()); 456ffa455d4SJean Perier auto addrSpace = op.addr_space(); 457ffa455d4SJean Perier auto *var = new llvm::GlobalVariable( 458ffa455d4SJean Perier *llvmModule, type, op.constant(), linkage, 459ffa455d4SJean Perier shouldDropGlobalInitializer(linkage, cst) ? nullptr : cst, 460ffa455d4SJean Perier op.sym_name(), 461ffa455d4SJean Perier /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal, addrSpace); 462ffa455d4SJean Perier 463c46a8862Sclementval if (op.unnamed_addr().hasValue()) 464c46a8862Sclementval var->setUnnamedAddr(convertUnnamedAddrToLLVM(*op.unnamed_addr())); 465c46a8862Sclementval 466b65472d6SRanjith Kumar H if (op.section().hasValue()) 467b65472d6SRanjith Kumar H var->setSection(*op.section()); 468b65472d6SRanjith Kumar H 469*8ca04b05SFelipe de Azevedo Piovezan addRuntimePreemptionSpecifier(op.dso_local(), var); 470*8ca04b05SFelipe de Azevedo Piovezan 4719a0ea599SDumitru Potop Optional<uint64_t> alignment = op.alignment(); 4729a0ea599SDumitru Potop if (alignment.hasValue()) 4739a0ea599SDumitru Potop var->setAlignment(llvm::MaybeAlign(alignment.getValue())); 4749a0ea599SDumitru Potop 475ffa455d4SJean Perier globalsMapping.try_emplace(op, var); 476ffa455d4SJean Perier } 477ffa455d4SJean Perier 478ffa455d4SJean Perier // Convert global variable bodies. This is done after all global variables 479ffa455d4SJean Perier // have been created in LLVM IR because a global body may refer to another 480ffa455d4SJean Perier // global or itself. So all global variables need to be mapped first. 481ffa455d4SJean Perier for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) { 482ffa455d4SJean Perier if (Block *initializer = op.getInitializerBlock()) { 483250a11aeSJames Molloy llvm::IRBuilder<> builder(llvmModule->getContext()); 484250a11aeSJames Molloy for (auto &op : initializer->without_terminator()) { 485250a11aeSJames Molloy if (failed(convertOperation(op, builder)) || 4860881a4f1SAlex Zinenko !isa<llvm::Constant>(lookupValue(op.getResult(0)))) 487efa2d533SAlex Zinenko return emitError(op.getLoc(), "unemittable constant value"); 488250a11aeSJames Molloy } 489250a11aeSJames Molloy ReturnOp ret = cast<ReturnOp>(initializer->getTerminator()); 490ffa455d4SJean Perier llvm::Constant *cst = 491ffa455d4SJean Perier cast<llvm::Constant>(lookupValue(ret.getOperand(0))); 492ffa455d4SJean Perier auto *global = cast<llvm::GlobalVariable>(lookupGlobal(op)); 493ffa455d4SJean Perier if (!shouldDropGlobalInitializer(global->getLinkage(), cst)) 494ffa455d4SJean Perier global->setInitializer(cst); 495250a11aeSJames Molloy } 496b9ff2dd8SAlex Zinenko } 497efa2d533SAlex Zinenko 498efa2d533SAlex Zinenko return success(); 499b9ff2dd8SAlex Zinenko } 500b9ff2dd8SAlex Zinenko 5010a2131b7SAlex Zinenko /// Attempts to add an attribute identified by `key`, optionally with the given 5020a2131b7SAlex Zinenko /// `value` to LLVM function `llvmFunc`. Reports errors at `loc` if any. If the 5030a2131b7SAlex Zinenko /// attribute has a kind known to LLVM IR, create the attribute of this kind, 5040a2131b7SAlex Zinenko /// otherwise keep it as a string attribute. Performs additional checks for 5050a2131b7SAlex Zinenko /// attributes known to have or not have a value in order to avoid assertions 5060a2131b7SAlex Zinenko /// inside LLVM upon construction. 5070a2131b7SAlex Zinenko static LogicalResult checkedAddLLVMFnAttribute(Location loc, 5080a2131b7SAlex Zinenko llvm::Function *llvmFunc, 5090a2131b7SAlex Zinenko StringRef key, 5100a2131b7SAlex Zinenko StringRef value = StringRef()) { 5110a2131b7SAlex Zinenko auto kind = llvm::Attribute::getAttrKindFromName(key); 5120a2131b7SAlex Zinenko if (kind == llvm::Attribute::None) { 5130a2131b7SAlex Zinenko llvmFunc->addFnAttr(key, value); 5140a2131b7SAlex Zinenko return success(); 5150a2131b7SAlex Zinenko } 5160a2131b7SAlex Zinenko 5170a2131b7SAlex Zinenko if (llvm::Attribute::doesAttrKindHaveArgument(kind)) { 5180a2131b7SAlex Zinenko if (value.empty()) 5190a2131b7SAlex Zinenko return emitError(loc) << "LLVM attribute '" << key << "' expects a value"; 5200a2131b7SAlex Zinenko 5210a2131b7SAlex Zinenko int result; 5220a2131b7SAlex Zinenko if (!value.getAsInteger(/*Radix=*/0, result)) 5230a2131b7SAlex Zinenko llvmFunc->addFnAttr( 5240a2131b7SAlex Zinenko llvm::Attribute::get(llvmFunc->getContext(), kind, result)); 5250a2131b7SAlex Zinenko else 5260a2131b7SAlex Zinenko llvmFunc->addFnAttr(key, value); 5270a2131b7SAlex Zinenko return success(); 5280a2131b7SAlex Zinenko } 5290a2131b7SAlex Zinenko 5300a2131b7SAlex Zinenko if (!value.empty()) 5310a2131b7SAlex Zinenko return emitError(loc) << "LLVM attribute '" << key 5320a2131b7SAlex Zinenko << "' does not expect a value, found '" << value 5330a2131b7SAlex Zinenko << "'"; 5340a2131b7SAlex Zinenko 5350a2131b7SAlex Zinenko llvmFunc->addFnAttr(kind); 5360a2131b7SAlex Zinenko return success(); 5370a2131b7SAlex Zinenko } 5380a2131b7SAlex Zinenko 5390a2131b7SAlex Zinenko /// Attaches the attributes listed in the given array attribute to `llvmFunc`. 5400a2131b7SAlex Zinenko /// Reports error to `loc` if any and returns immediately. Expects `attributes` 5410a2131b7SAlex Zinenko /// to be an array attribute containing either string attributes, treated as 5420a2131b7SAlex Zinenko /// value-less LLVM attributes, or array attributes containing two string 5430a2131b7SAlex Zinenko /// attributes, with the first string being the name of the corresponding LLVM 5440a2131b7SAlex Zinenko /// attribute and the second string beings its value. Note that even integer 5450a2131b7SAlex Zinenko /// attributes are expected to have their values expressed as strings. 5460a2131b7SAlex Zinenko static LogicalResult 5470a2131b7SAlex Zinenko forwardPassthroughAttributes(Location loc, Optional<ArrayAttr> attributes, 5480a2131b7SAlex Zinenko llvm::Function *llvmFunc) { 5490a2131b7SAlex Zinenko if (!attributes) 5500a2131b7SAlex Zinenko return success(); 5510a2131b7SAlex Zinenko 5520a2131b7SAlex Zinenko for (Attribute attr : *attributes) { 5530a2131b7SAlex Zinenko if (auto stringAttr = attr.dyn_cast<StringAttr>()) { 5540a2131b7SAlex Zinenko if (failed( 5550a2131b7SAlex Zinenko checkedAddLLVMFnAttribute(loc, llvmFunc, stringAttr.getValue()))) 5560a2131b7SAlex Zinenko return failure(); 5570a2131b7SAlex Zinenko continue; 5580a2131b7SAlex Zinenko } 5590a2131b7SAlex Zinenko 5600a2131b7SAlex Zinenko auto arrayAttr = attr.dyn_cast<ArrayAttr>(); 5610a2131b7SAlex Zinenko if (!arrayAttr || arrayAttr.size() != 2) 5620a2131b7SAlex Zinenko return emitError(loc) 5630a2131b7SAlex Zinenko << "expected 'passthrough' to contain string or array attributes"; 5640a2131b7SAlex Zinenko 5650a2131b7SAlex Zinenko auto keyAttr = arrayAttr[0].dyn_cast<StringAttr>(); 5660a2131b7SAlex Zinenko auto valueAttr = arrayAttr[1].dyn_cast<StringAttr>(); 5670a2131b7SAlex Zinenko if (!keyAttr || !valueAttr) 5680a2131b7SAlex Zinenko return emitError(loc) 5690a2131b7SAlex Zinenko << "expected arrays within 'passthrough' to contain two strings"; 5700a2131b7SAlex Zinenko 5710a2131b7SAlex Zinenko if (failed(checkedAddLLVMFnAttribute(loc, llvmFunc, keyAttr.getValue(), 5720a2131b7SAlex Zinenko valueAttr.getValue()))) 5730a2131b7SAlex Zinenko return failure(); 5740a2131b7SAlex Zinenko } 5750a2131b7SAlex Zinenko return success(); 5760a2131b7SAlex Zinenko } 5770a2131b7SAlex Zinenko 5785e7959a3SAlex Zinenko LogicalResult ModuleTranslation::convertOneFunction(LLVMFuncOp func) { 579db884dafSAlex Zinenko // Clear the block, branch value mappings, they are only relevant within one 5805d7231d8SStephan Herhut // function. 5815d7231d8SStephan Herhut blockMapping.clear(); 5825d7231d8SStephan Herhut valueMapping.clear(); 583db884dafSAlex Zinenko branchMapping.clear(); 5840881a4f1SAlex Zinenko llvm::Function *llvmFunc = lookupFunction(func.getName()); 585c33d6970SRiver Riddle 586c33d6970SRiver Riddle // Translate the debug information for this function. 587c33d6970SRiver Riddle debugTranslation->translate(func, *llvmFunc); 588c33d6970SRiver Riddle 5895d7231d8SStephan Herhut // Add function arguments to the value remapping table. 5905d7231d8SStephan Herhut // If there was noalias info then we decorate each argument accordingly. 5915d7231d8SStephan Herhut unsigned int argIdx = 0; 592eeef50b1SFangrui Song for (auto kvp : llvm::zip(func.getArguments(), llvmFunc->args())) { 5935d7231d8SStephan Herhut llvm::Argument &llvmArg = std::get<1>(kvp); 594e62a6956SRiver Riddle BlockArgument mlirArg = std::get<0>(kvp); 5955d7231d8SStephan Herhut 5961c777ab4SUday Bondhugula if (auto attr = func.getArgAttrOfType<UnitAttr>( 59767cc5cecSStephan Herhut argIdx, LLVMDialect::getNoAliasAttrName())) { 5985d7231d8SStephan Herhut // NB: Attribute already verified to be boolean, so check if we can indeed 5995d7231d8SStephan Herhut // attach the attribute to this argument, based on its type. 600c69c9e0fSAlex Zinenko auto argTy = mlirArg.getType(); 6018de43b92SAlex Zinenko if (!argTy.isa<LLVM::LLVMPointerType>()) 602baa1ec22SAlex Zinenko return func.emitError( 6035d7231d8SStephan Herhut "llvm.noalias attribute attached to LLVM non-pointer argument"); 6045d7231d8SStephan Herhut llvmArg.addAttr(llvm::Attribute::AttrKind::NoAlias); 6055d7231d8SStephan Herhut } 6062416e28cSStephan Herhut 60767cc5cecSStephan Herhut if (auto attr = func.getArgAttrOfType<IntegerAttr>( 60867cc5cecSStephan Herhut argIdx, LLVMDialect::getAlignAttrName())) { 6092416e28cSStephan Herhut // NB: Attribute already verified to be int, so check if we can indeed 6102416e28cSStephan Herhut // attach the attribute to this argument, based on its type. 611c69c9e0fSAlex Zinenko auto argTy = mlirArg.getType(); 6128de43b92SAlex Zinenko if (!argTy.isa<LLVM::LLVMPointerType>()) 6132416e28cSStephan Herhut return func.emitError( 6142416e28cSStephan Herhut "llvm.align attribute attached to LLVM non-pointer argument"); 6152416e28cSStephan Herhut llvmArg.addAttrs( 6162416e28cSStephan Herhut llvm::AttrBuilder().addAlignmentAttr(llvm::Align(attr.getInt()))); 6172416e28cSStephan Herhut } 6182416e28cSStephan Herhut 61970b841acSEric Schweitz if (auto attr = func.getArgAttrOfType<UnitAttr>(argIdx, "llvm.sret")) { 62070b841acSEric Schweitz auto argTy = mlirArg.getType(); 62170b841acSEric Schweitz if (!argTy.isa<LLVM::LLVMPointerType>()) 62270b841acSEric Schweitz return func.emitError( 62370b841acSEric Schweitz "llvm.sret attribute attached to LLVM non-pointer argument"); 6241d6df1fcSEric Schweitz llvmArg.addAttrs(llvm::AttrBuilder().addStructRetAttr( 6251d6df1fcSEric Schweitz llvmArg.getType()->getPointerElementType())); 62670b841acSEric Schweitz } 62770b841acSEric Schweitz 62870b841acSEric Schweitz if (auto attr = func.getArgAttrOfType<UnitAttr>(argIdx, "llvm.byval")) { 62970b841acSEric Schweitz auto argTy = mlirArg.getType(); 63070b841acSEric Schweitz if (!argTy.isa<LLVM::LLVMPointerType>()) 63170b841acSEric Schweitz return func.emitError( 63270b841acSEric Schweitz "llvm.byval attribute attached to LLVM non-pointer argument"); 6331d6df1fcSEric Schweitz llvmArg.addAttrs(llvm::AttrBuilder().addByValAttr( 6341d6df1fcSEric Schweitz llvmArg.getType()->getPointerElementType())); 63570b841acSEric Schweitz } 63670b841acSEric Schweitz 6370881a4f1SAlex Zinenko mapValue(mlirArg, &llvmArg); 6385d7231d8SStephan Herhut argIdx++; 6395d7231d8SStephan Herhut } 6405d7231d8SStephan Herhut 641ff77397fSShraiysh Vaishay // Check the personality and set it. 642ff77397fSShraiysh Vaishay if (func.personality().hasValue()) { 643ff77397fSShraiysh Vaishay llvm::Type *ty = llvm::Type::getInt8PtrTy(llvmFunc->getContext()); 644ff77397fSShraiysh Vaishay if (llvm::Constant *pfunc = 645176379e0SAlex Zinenko getLLVMConstant(ty, func.personalityAttr(), func.getLoc(), *this)) 646ff77397fSShraiysh Vaishay llvmFunc->setPersonalityFn(pfunc); 647ff77397fSShraiysh Vaishay } 648ff77397fSShraiysh Vaishay 6495d7231d8SStephan Herhut // First, create all blocks so we can jump to them. 6505d7231d8SStephan Herhut llvm::LLVMContext &llvmContext = llvmFunc->getContext(); 6515d7231d8SStephan Herhut for (auto &bb : func) { 6525d7231d8SStephan Herhut auto *llvmBB = llvm::BasicBlock::Create(llvmContext); 6535d7231d8SStephan Herhut llvmBB->insertInto(llvmFunc); 6540881a4f1SAlex Zinenko mapBlock(&bb, llvmBB); 6555d7231d8SStephan Herhut } 6565d7231d8SStephan Herhut 6575d7231d8SStephan Herhut // Then, convert blocks one by one in topological order to ensure defs are 6585d7231d8SStephan Herhut // converted before uses. 65966900b3eSAlex Zinenko auto blocks = detail::getTopologicallySortedBlocks(func.getBody()); 66010164a2eSAlex Zinenko for (Block *bb : blocks) { 66110164a2eSAlex Zinenko llvm::IRBuilder<> builder(llvmContext); 66210164a2eSAlex Zinenko if (failed(convertBlock(*bb, bb->isEntryBlock(), builder))) 663baa1ec22SAlex Zinenko return failure(); 6645d7231d8SStephan Herhut } 6655d7231d8SStephan Herhut 666176379e0SAlex Zinenko // After all blocks have been traversed and values mapped, connect the PHI 667176379e0SAlex Zinenko // nodes to the results of preceding blocks. 66866900b3eSAlex Zinenko detail::connectPHINodes(func.getBody(), *this); 669176379e0SAlex Zinenko 670176379e0SAlex Zinenko // Finally, convert dialect attributes attached to the function. 671176379e0SAlex Zinenko return convertDialectAttributes(func); 672176379e0SAlex Zinenko } 673176379e0SAlex Zinenko 674176379e0SAlex Zinenko LogicalResult ModuleTranslation::convertDialectAttributes(Operation *op) { 675176379e0SAlex Zinenko for (NamedAttribute attribute : op->getDialectAttrs()) 676176379e0SAlex Zinenko if (failed(iface.amendOperation(op, attribute, *this))) 677176379e0SAlex Zinenko return failure(); 678baa1ec22SAlex Zinenko return success(); 6795d7231d8SStephan Herhut } 6805d7231d8SStephan Herhut 681ce8f10d6SAlex Zinenko /// Check whether the module contains only supported ops directly in its body. 682ce8f10d6SAlex Zinenko static LogicalResult checkSupportedModuleOps(Operation *m) { 68344fc7d72STres Popp for (Operation &o : getModuleBody(m).getOperations()) 6844a2930f4SArpith C. Jacob if (!isa<LLVM::LLVMFuncOp, LLVM::GlobalOp, LLVM::MetadataOp>(&o) && 685fe7c0d90SRiver Riddle !o.hasTrait<OpTrait::IsTerminator>()) 6864dde19f0SAlex Zinenko return o.emitOpError("unsupported module-level operation"); 6874dde19f0SAlex Zinenko return success(); 6884dde19f0SAlex Zinenko } 6894dde19f0SAlex Zinenko 690a084b94fSSean Silva LogicalResult ModuleTranslation::convertFunctionSignatures() { 6915d7231d8SStephan Herhut // Declare all functions first because there may be function calls that form a 692a084b94fSSean Silva // call graph with cycles, or global initializers that reference functions. 69344fc7d72STres Popp for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) { 6945e7959a3SAlex Zinenko llvm::FunctionCallee llvmFuncCst = llvmModule->getOrInsertFunction( 6955e7959a3SAlex Zinenko function.getName(), 696aec38c61SAlex Zinenko cast<llvm::FunctionType>(convertType(function.getType()))); 6970a2131b7SAlex Zinenko llvm::Function *llvmFunc = cast<llvm::Function>(llvmFuncCst.getCallee()); 698ebbdecddSAlex Zinenko llvmFunc->setLinkage(convertLinkageToLLVM(function.linkage())); 6990881a4f1SAlex Zinenko mapFunction(function.getName(), llvmFunc); 700*8ca04b05SFelipe de Azevedo Piovezan addRuntimePreemptionSpecifier(function.dso_local(), llvmFunc); 7010a2131b7SAlex Zinenko 7020a2131b7SAlex Zinenko // Forward the pass-through attributes to LLVM. 7030a2131b7SAlex Zinenko if (failed(forwardPassthroughAttributes(function.getLoc(), 7040a2131b7SAlex Zinenko function.passthrough(), llvmFunc))) 7050a2131b7SAlex Zinenko return failure(); 7065d7231d8SStephan Herhut } 7075d7231d8SStephan Herhut 708a084b94fSSean Silva return success(); 709a084b94fSSean Silva } 710a084b94fSSean Silva 711a084b94fSSean Silva LogicalResult ModuleTranslation::convertFunctions() { 7125d7231d8SStephan Herhut // Convert functions. 71344fc7d72STres Popp for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) { 7145d7231d8SStephan Herhut // Ignore external functions. 7155d7231d8SStephan Herhut if (function.isExternal()) 7165d7231d8SStephan Herhut continue; 7175d7231d8SStephan Herhut 718baa1ec22SAlex Zinenko if (failed(convertOneFunction(function))) 719baa1ec22SAlex Zinenko return failure(); 7205d7231d8SStephan Herhut } 7215d7231d8SStephan Herhut 722baa1ec22SAlex Zinenko return success(); 7235d7231d8SStephan Herhut } 7245d7231d8SStephan Herhut 7254a2930f4SArpith C. Jacob llvm::MDNode * 7264a2930f4SArpith C. Jacob ModuleTranslation::getAccessGroup(Operation &opInst, 7274a2930f4SArpith C. Jacob SymbolRefAttr accessGroupRef) const { 7284a2930f4SArpith C. Jacob auto metadataName = accessGroupRef.getRootReference(); 7294a2930f4SArpith C. Jacob auto accessGroupName = accessGroupRef.getLeafReference(); 7304a2930f4SArpith C. Jacob auto metadataOp = SymbolTable::lookupNearestSymbolFrom<LLVM::MetadataOp>( 7314a2930f4SArpith C. Jacob opInst.getParentOp(), metadataName); 7324a2930f4SArpith C. Jacob auto *accessGroupOp = 7334a2930f4SArpith C. Jacob SymbolTable::lookupNearestSymbolFrom(metadataOp, accessGroupName); 7344a2930f4SArpith C. Jacob return accessGroupMetadataMapping.lookup(accessGroupOp); 7354a2930f4SArpith C. Jacob } 7364a2930f4SArpith C. Jacob 7374a2930f4SArpith C. Jacob LogicalResult ModuleTranslation::createAccessGroupMetadata() { 7384a2930f4SArpith C. Jacob mlirModule->walk([&](LLVM::MetadataOp metadatas) { 7394a2930f4SArpith C. Jacob metadatas.walk([&](LLVM::AccessGroupMetadataOp op) { 7404a2930f4SArpith C. Jacob llvm::LLVMContext &ctx = llvmModule->getContext(); 7414a2930f4SArpith C. Jacob llvm::MDNode *accessGroup = llvm::MDNode::getDistinct(ctx, {}); 7424a2930f4SArpith C. Jacob accessGroupMetadataMapping.insert({op, accessGroup}); 7434a2930f4SArpith C. Jacob }); 7444a2930f4SArpith C. Jacob }); 7454a2930f4SArpith C. Jacob return success(); 7464a2930f4SArpith C. Jacob } 7474a2930f4SArpith C. Jacob 7484e393350SArpith C. Jacob void ModuleTranslation::setAccessGroupsMetadata(Operation *op, 7494e393350SArpith C. Jacob llvm::Instruction *inst) { 7504e393350SArpith C. Jacob auto accessGroups = 7514e393350SArpith C. Jacob op->getAttrOfType<ArrayAttr>(LLVMDialect::getAccessGroupsAttrName()); 7524e393350SArpith C. Jacob if (accessGroups && !accessGroups.empty()) { 7534e393350SArpith C. Jacob llvm::Module *module = inst->getModule(); 7544e393350SArpith C. Jacob SmallVector<llvm::Metadata *> metadatas; 7554e393350SArpith C. Jacob for (SymbolRefAttr accessGroupRef : 7564e393350SArpith C. Jacob accessGroups.getAsRange<SymbolRefAttr>()) 7574e393350SArpith C. Jacob metadatas.push_back(getAccessGroup(*op, accessGroupRef)); 7584e393350SArpith C. Jacob 7594e393350SArpith C. Jacob llvm::MDNode *unionMD = nullptr; 7604e393350SArpith C. Jacob if (metadatas.size() == 1) 7614e393350SArpith C. Jacob unionMD = llvm::cast<llvm::MDNode>(metadatas.front()); 7624e393350SArpith C. Jacob else if (metadatas.size() >= 2) 7634e393350SArpith C. Jacob unionMD = llvm::MDNode::get(module->getContext(), metadatas); 7644e393350SArpith C. Jacob 7654e393350SArpith C. Jacob inst->setMetadata(module->getMDKindID("llvm.access.group"), unionMD); 7664e393350SArpith C. Jacob } 7674e393350SArpith C. Jacob } 7684e393350SArpith C. Jacob 769c69c9e0fSAlex Zinenko llvm::Type *ModuleTranslation::convertType(Type type) { 770b2ab375dSAlex Zinenko return typeTranslator.translateType(type); 771aec38c61SAlex Zinenko } 772aec38c61SAlex Zinenko 773efadb6b8SAlex Zinenko /// A helper to look up remapped operands in the value remapping table.` 774efadb6b8SAlex Zinenko SmallVector<llvm::Value *, 8> 775efadb6b8SAlex Zinenko ModuleTranslation::lookupValues(ValueRange values) { 776efadb6b8SAlex Zinenko SmallVector<llvm::Value *, 8> remapped; 777efadb6b8SAlex Zinenko remapped.reserve(values.size()); 7780881a4f1SAlex Zinenko for (Value v : values) 7790881a4f1SAlex Zinenko remapped.push_back(lookupValue(v)); 780efadb6b8SAlex Zinenko return remapped; 781efadb6b8SAlex Zinenko } 782efadb6b8SAlex Zinenko 78366900b3eSAlex Zinenko const llvm::DILocation * 78466900b3eSAlex Zinenko ModuleTranslation::translateLoc(Location loc, llvm::DILocalScope *scope) { 78566900b3eSAlex Zinenko return debugTranslation->translateLoc(loc, scope); 78666900b3eSAlex Zinenko } 78766900b3eSAlex Zinenko 788176379e0SAlex Zinenko llvm::NamedMDNode * 789176379e0SAlex Zinenko ModuleTranslation::getOrInsertNamedModuleMetadata(StringRef name) { 790176379e0SAlex Zinenko return llvmModule->getOrInsertNamedMetadata(name); 791176379e0SAlex Zinenko } 792176379e0SAlex Zinenko 79372d013ddSAlex Zinenko void ModuleTranslation::StackFrame::anchor() {} 79472d013ddSAlex Zinenko 795ce8f10d6SAlex Zinenko static std::unique_ptr<llvm::Module> 796ce8f10d6SAlex Zinenko prepareLLVMModule(Operation *m, llvm::LLVMContext &llvmContext, 797ce8f10d6SAlex Zinenko StringRef name) { 798f9dc2b70SMehdi Amini m->getContext()->getOrLoadDialect<LLVM::LLVMDialect>(); 799db1c197bSAlex Zinenko auto llvmModule = std::make_unique<llvm::Module>(name, llvmContext); 800168213f9SAlex Zinenko if (auto dataLayoutAttr = 801168213f9SAlex Zinenko m->getAttr(LLVM::LLVMDialect::getDataLayoutAttrName())) 802168213f9SAlex Zinenko llvmModule->setDataLayout(dataLayoutAttr.cast<StringAttr>().getValue()); 8035dd5a083SNicolas Vasilache if (auto targetTripleAttr = 8045dd5a083SNicolas Vasilache m->getAttr(LLVM::LLVMDialect::getTargetTripleAttrName())) 8055dd5a083SNicolas Vasilache llvmModule->setTargetTriple(targetTripleAttr.cast<StringAttr>().getValue()); 8065d7231d8SStephan Herhut 8075d7231d8SStephan Herhut // Inject declarations for `malloc` and `free` functions that can be used in 8085d7231d8SStephan Herhut // memref allocation/deallocation coming from standard ops lowering. 809db1c197bSAlex Zinenko llvm::IRBuilder<> builder(llvmContext); 8105d7231d8SStephan Herhut llvmModule->getOrInsertFunction("malloc", builder.getInt8PtrTy(), 8115d7231d8SStephan Herhut builder.getInt64Ty()); 8125d7231d8SStephan Herhut llvmModule->getOrInsertFunction("free", builder.getVoidTy(), 8135d7231d8SStephan Herhut builder.getInt8PtrTy()); 8145d7231d8SStephan Herhut 8155d7231d8SStephan Herhut return llvmModule; 8165d7231d8SStephan Herhut } 817ce8f10d6SAlex Zinenko 818ce8f10d6SAlex Zinenko std::unique_ptr<llvm::Module> 819ce8f10d6SAlex Zinenko mlir::translateModuleToLLVMIR(Operation *module, llvm::LLVMContext &llvmContext, 820ce8f10d6SAlex Zinenko StringRef name) { 821ce8f10d6SAlex Zinenko if (!satisfiesLLVMModule(module)) 822ce8f10d6SAlex Zinenko return nullptr; 823ce8f10d6SAlex Zinenko if (failed(checkSupportedModuleOps(module))) 824ce8f10d6SAlex Zinenko return nullptr; 825ce8f10d6SAlex Zinenko std::unique_ptr<llvm::Module> llvmModule = 826ce8f10d6SAlex Zinenko prepareLLVMModule(module, llvmContext, name); 827ce8f10d6SAlex Zinenko 828ce8f10d6SAlex Zinenko LLVM::ensureDistinctSuccessors(module); 829ce8f10d6SAlex Zinenko 830ce8f10d6SAlex Zinenko ModuleTranslation translator(module, std::move(llvmModule)); 831ce8f10d6SAlex Zinenko if (failed(translator.convertFunctionSignatures())) 832ce8f10d6SAlex Zinenko return nullptr; 833ce8f10d6SAlex Zinenko if (failed(translator.convertGlobals())) 834ce8f10d6SAlex Zinenko return nullptr; 8354a2930f4SArpith C. Jacob if (failed(translator.createAccessGroupMetadata())) 8364a2930f4SArpith C. Jacob return nullptr; 837ce8f10d6SAlex Zinenko if (failed(translator.convertFunctions())) 838ce8f10d6SAlex Zinenko return nullptr; 839ce8f10d6SAlex Zinenko if (llvm::verifyModule(*translator.llvmModule, &llvm::errs())) 840ce8f10d6SAlex Zinenko return nullptr; 841ce8f10d6SAlex Zinenko 842ce8f10d6SAlex Zinenko return std::move(translator.llvmModule); 843ce8f10d6SAlex Zinenko } 844