1cde4d5a6SJacques Pienaar //===- ModuleTranslation.cpp - MLIR to LLVM conversion --------------------===// 25d7231d8SStephan Herhut // 330857107SMehdi Amini // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 456222a06SMehdi Amini // See https://llvm.org/LICENSE.txt for license information. 556222a06SMehdi Amini // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 65d7231d8SStephan Herhut // 756222a06SMehdi Amini //===----------------------------------------------------------------------===// 85d7231d8SStephan Herhut // 95d7231d8SStephan Herhut // This file implements the translation between an MLIR LLVM dialect module and 105d7231d8SStephan Herhut // the corresponding LLVMIR module. It only handles core LLVM IR operations. 115d7231d8SStephan Herhut // 125d7231d8SStephan Herhut //===----------------------------------------------------------------------===// 135d7231d8SStephan Herhut 145d7231d8SStephan Herhut #include "mlir/Target/LLVMIR/ModuleTranslation.h" 155d7231d8SStephan Herhut 16c33d6970SRiver Riddle #include "DebugTranslation.h" 17ba0fa925SRiver Riddle #include "mlir/Dialect/LLVMIR/LLVMDialect.h" 18ce8f10d6SAlex Zinenko #include "mlir/Dialect/LLVMIR/Transforms/LegalizeForExport.h" 1992a295ebSKiran Chandramohan #include "mlir/Dialect/OpenMP/OpenMPDialect.h" 205d7231d8SStephan Herhut #include "mlir/IR/Attributes.h" 2165fcddffSRiver Riddle #include "mlir/IR/BuiltinOps.h" 2209f7a55fSRiver Riddle #include "mlir/IR/BuiltinTypes.h" 23d4568ed7SGeorge Mitenkov #include "mlir/IR/RegionGraphTraits.h" 245d7231d8SStephan Herhut #include "mlir/Support/LLVM.h" 25b77bac05SAlex Zinenko #include "mlir/Target/LLVMIR/LLVMTranslationInterface.h" 26ec1f4e7cSAlex Zinenko #include "mlir/Target/LLVMIR/TypeTranslation.h" 27ebf190fcSRiver Riddle #include "llvm/ADT/TypeSwitch.h" 285d7231d8SStephan Herhut 29d4568ed7SGeorge Mitenkov #include "llvm/ADT/PostOrderIterator.h" 305d7231d8SStephan Herhut #include "llvm/ADT/SetVector.h" 3192a295ebSKiran Chandramohan #include "llvm/Frontend/OpenMP/OMPIRBuilder.h" 325d7231d8SStephan Herhut #include "llvm/IR/BasicBlock.h" 33d9067dcaSKiran Chandramohan #include "llvm/IR/CFG.h" 345d7231d8SStephan Herhut #include "llvm/IR/Constants.h" 355d7231d8SStephan Herhut #include "llvm/IR/DerivedTypes.h" 365d7231d8SStephan Herhut #include "llvm/IR/IRBuilder.h" 37047400edSNicolas Vasilache #include "llvm/IR/InlineAsm.h" 385d7231d8SStephan Herhut #include "llvm/IR/LLVMContext.h" 3999d03f03SGeorge Mitenkov #include "llvm/IR/MDBuilder.h" 405d7231d8SStephan Herhut #include "llvm/IR/Module.h" 41ce8f10d6SAlex Zinenko #include "llvm/IR/Verifier.h" 42d9067dcaSKiran Chandramohan #include "llvm/Transforms/Utils/BasicBlockUtils.h" 435d7231d8SStephan Herhut #include "llvm/Transforms/Utils/Cloning.h" 445d7231d8SStephan Herhut 452666b973SRiver Riddle using namespace mlir; 462666b973SRiver Riddle using namespace mlir::LLVM; 47c33d6970SRiver Riddle using namespace mlir::LLVM::detail; 485d7231d8SStephan Herhut 49eb67bd78SAlex Zinenko #include "mlir/Dialect/LLVMIR/LLVMConversionEnumsToLLVM.inc" 50eb67bd78SAlex Zinenko 51a922e231SAlex Zinenko /// Builds a constant of a sequential LLVM type `type`, potentially containing 52a922e231SAlex Zinenko /// other sequential types recursively, from the individual constant values 53a922e231SAlex Zinenko /// provided in `constants`. `shape` contains the number of elements in nested 54a922e231SAlex Zinenko /// sequential types. Reports errors at `loc` and returns nullptr on error. 55a4a42160SAlex Zinenko static llvm::Constant * 56a4a42160SAlex Zinenko buildSequentialConstant(ArrayRef<llvm::Constant *> &constants, 57a4a42160SAlex Zinenko ArrayRef<int64_t> shape, llvm::Type *type, 58a4a42160SAlex Zinenko Location loc) { 59a4a42160SAlex Zinenko if (shape.empty()) { 60a4a42160SAlex Zinenko llvm::Constant *result = constants.front(); 61a4a42160SAlex Zinenko constants = constants.drop_front(); 62a4a42160SAlex Zinenko return result; 63a4a42160SAlex Zinenko } 64a4a42160SAlex Zinenko 6568b03aeeSEli Friedman llvm::Type *elementType; 6668b03aeeSEli Friedman if (auto *arrayTy = dyn_cast<llvm::ArrayType>(type)) { 6768b03aeeSEli Friedman elementType = arrayTy->getElementType(); 6868b03aeeSEli Friedman } else if (auto *vectorTy = dyn_cast<llvm::VectorType>(type)) { 6968b03aeeSEli Friedman elementType = vectorTy->getElementType(); 7068b03aeeSEli Friedman } else { 71a4a42160SAlex Zinenko emitError(loc) << "expected sequential LLVM types wrapping a scalar"; 72a4a42160SAlex Zinenko return nullptr; 73a4a42160SAlex Zinenko } 74a4a42160SAlex Zinenko 75a4a42160SAlex Zinenko SmallVector<llvm::Constant *, 8> nested; 76a4a42160SAlex Zinenko nested.reserve(shape.front()); 77a4a42160SAlex Zinenko for (int64_t i = 0; i < shape.front(); ++i) { 78a4a42160SAlex Zinenko nested.push_back(buildSequentialConstant(constants, shape.drop_front(), 79a4a42160SAlex Zinenko elementType, loc)); 80a4a42160SAlex Zinenko if (!nested.back()) 81a4a42160SAlex Zinenko return nullptr; 82a4a42160SAlex Zinenko } 83a4a42160SAlex Zinenko 84a4a42160SAlex Zinenko if (shape.size() == 1 && type->isVectorTy()) 85a4a42160SAlex Zinenko return llvm::ConstantVector::get(nested); 86a4a42160SAlex Zinenko return llvm::ConstantArray::get( 87a4a42160SAlex Zinenko llvm::ArrayType::get(elementType, shape.front()), nested); 88a4a42160SAlex Zinenko } 89a4a42160SAlex Zinenko 90fc817b09SKazuaki Ishizaki /// Returns the first non-sequential type nested in sequential types. 91a4a42160SAlex Zinenko static llvm::Type *getInnermostElementType(llvm::Type *type) { 9268b03aeeSEli Friedman do { 9368b03aeeSEli Friedman if (auto *arrayTy = dyn_cast<llvm::ArrayType>(type)) { 9468b03aeeSEli Friedman type = arrayTy->getElementType(); 9568b03aeeSEli Friedman } else if (auto *vectorTy = dyn_cast<llvm::VectorType>(type)) { 9668b03aeeSEli Friedman type = vectorTy->getElementType(); 9768b03aeeSEli Friedman } else { 98a4a42160SAlex Zinenko return type; 99a4a42160SAlex Zinenko } 1000881a4f1SAlex Zinenko } while (true); 10168b03aeeSEli Friedman } 102a4a42160SAlex Zinenko 1032666b973SRiver Riddle /// Create an LLVM IR constant of `llvmType` from the MLIR attribute `attr`. 1042666b973SRiver Riddle /// This currently supports integer, floating point, splat and dense element 1052666b973SRiver Riddle /// attributes and combinations thereof. In case of error, report it to `loc` 1062666b973SRiver Riddle /// and return nullptr. 107176379e0SAlex Zinenko llvm::Constant *mlir::LLVM::detail::getLLVMConstant( 108176379e0SAlex Zinenko llvm::Type *llvmType, Attribute attr, Location loc, 109176379e0SAlex Zinenko const ModuleTranslation &moduleTranslation) { 11033a3a91bSChristian Sigg if (!attr) 11133a3a91bSChristian Sigg return llvm::UndefValue::get(llvmType); 112a4a42160SAlex Zinenko if (llvmType->isStructTy()) { 113a4a42160SAlex Zinenko emitError(loc, "struct types are not supported in constants"); 114a4a42160SAlex Zinenko return nullptr; 115a4a42160SAlex Zinenko } 116ac9d742bSStephan Herhut // For integer types, we allow a mismatch in sizes as the index type in 117ac9d742bSStephan Herhut // MLIR might have a different size than the index type in the LLVM module. 1185d7231d8SStephan Herhut if (auto intAttr = attr.dyn_cast<IntegerAttr>()) 119ac9d742bSStephan Herhut return llvm::ConstantInt::get( 120ac9d742bSStephan Herhut llvmType, 121ac9d742bSStephan Herhut intAttr.getValue().sextOrTrunc(llvmType->getIntegerBitWidth())); 1225d7231d8SStephan Herhut if (auto floatAttr = attr.dyn_cast<FloatAttr>()) 1235d7231d8SStephan Herhut return llvm::ConstantFP::get(llvmType, floatAttr.getValue()); 1249b9c647cSRiver Riddle if (auto funcAttr = attr.dyn_cast<FlatSymbolRefAttr>()) 125176379e0SAlex Zinenko return llvm::ConstantExpr::getBitCast( 126176379e0SAlex Zinenko moduleTranslation.lookupFunction(funcAttr.getValue()), llvmType); 1275d7231d8SStephan Herhut if (auto splatAttr = attr.dyn_cast<SplatElementsAttr>()) { 12868b03aeeSEli Friedman llvm::Type *elementType; 12968b03aeeSEli Friedman uint64_t numElements; 13068b03aeeSEli Friedman if (auto *arrayTy = dyn_cast<llvm::ArrayType>(llvmType)) { 13168b03aeeSEli Friedman elementType = arrayTy->getElementType(); 13268b03aeeSEli Friedman numElements = arrayTy->getNumElements(); 13368b03aeeSEli Friedman } else { 1345cba1c63SChristopher Tetreault auto *vectorTy = cast<llvm::FixedVectorType>(llvmType); 13568b03aeeSEli Friedman elementType = vectorTy->getElementType(); 13668b03aeeSEli Friedman numElements = vectorTy->getNumElements(); 13768b03aeeSEli Friedman } 138d6ea8ff0SAlex Zinenko // Splat value is a scalar. Extract it only if the element type is not 139d6ea8ff0SAlex Zinenko // another sequence type. The recursion terminates because each step removes 140d6ea8ff0SAlex Zinenko // one outer sequential type. 14168b03aeeSEli Friedman bool elementTypeSequential = 142d891d738SRahul Joshi isa<llvm::ArrayType, llvm::VectorType>(elementType); 143d6ea8ff0SAlex Zinenko llvm::Constant *child = getLLVMConstant( 144d6ea8ff0SAlex Zinenko elementType, 145176379e0SAlex Zinenko elementTypeSequential ? splatAttr : splatAttr.getSplatValue(), loc, 146176379e0SAlex Zinenko moduleTranslation); 147a4a42160SAlex Zinenko if (!child) 148a4a42160SAlex Zinenko return nullptr; 1492f13df13SMLIR Team if (llvmType->isVectorTy()) 150396a42d9SRiver Riddle return llvm::ConstantVector::getSplat( 1510f95e731SAlex Zinenko llvm::ElementCount::get(numElements, /*Scalable=*/false), child); 1522f13df13SMLIR Team if (llvmType->isArrayTy()) { 153ac9d742bSStephan Herhut auto *arrayType = llvm::ArrayType::get(elementType, numElements); 1542f13df13SMLIR Team SmallVector<llvm::Constant *, 8> constants(numElements, child); 1552f13df13SMLIR Team return llvm::ConstantArray::get(arrayType, constants); 1562f13df13SMLIR Team } 1575d7231d8SStephan Herhut } 158a4a42160SAlex Zinenko 159d906f84bSRiver Riddle if (auto elementsAttr = attr.dyn_cast<ElementsAttr>()) { 160a4a42160SAlex Zinenko assert(elementsAttr.getType().hasStaticShape()); 161a4a42160SAlex Zinenko assert(elementsAttr.getNumElements() != 0 && 162a4a42160SAlex Zinenko "unexpected empty elements attribute"); 163a4a42160SAlex Zinenko assert(!elementsAttr.getType().getShape().empty() && 164a4a42160SAlex Zinenko "unexpected empty elements attribute shape"); 165a4a42160SAlex Zinenko 1665d7231d8SStephan Herhut SmallVector<llvm::Constant *, 8> constants; 167a4a42160SAlex Zinenko constants.reserve(elementsAttr.getNumElements()); 168a4a42160SAlex Zinenko llvm::Type *innermostType = getInnermostElementType(llvmType); 169d906f84bSRiver Riddle for (auto n : elementsAttr.getValues<Attribute>()) { 170176379e0SAlex Zinenko constants.push_back( 171176379e0SAlex Zinenko getLLVMConstant(innermostType, n, loc, moduleTranslation)); 1725d7231d8SStephan Herhut if (!constants.back()) 1735d7231d8SStephan Herhut return nullptr; 1745d7231d8SStephan Herhut } 175a4a42160SAlex Zinenko ArrayRef<llvm::Constant *> constantsRef = constants; 176a4a42160SAlex Zinenko llvm::Constant *result = buildSequentialConstant( 177a4a42160SAlex Zinenko constantsRef, elementsAttr.getType().getShape(), llvmType, loc); 178a4a42160SAlex Zinenko assert(constantsRef.empty() && "did not consume all elemental constants"); 179a4a42160SAlex Zinenko return result; 1802f13df13SMLIR Team } 181a4a42160SAlex Zinenko 182cb348dffSStephan Herhut if (auto stringAttr = attr.dyn_cast<StringAttr>()) { 183cb348dffSStephan Herhut return llvm::ConstantDataArray::get( 184176379e0SAlex Zinenko moduleTranslation.getLLVMContext(), 185176379e0SAlex Zinenko ArrayRef<char>{stringAttr.getValue().data(), 186cb348dffSStephan Herhut stringAttr.getValue().size()}); 187cb348dffSStephan Herhut } 188a4c3a645SRiver Riddle emitError(loc, "unsupported constant value"); 1895d7231d8SStephan Herhut return nullptr; 1905d7231d8SStephan Herhut } 1915d7231d8SStephan Herhut 192c33d6970SRiver Riddle ModuleTranslation::ModuleTranslation(Operation *module, 193c33d6970SRiver Riddle std::unique_ptr<llvm::Module> llvmModule) 194c33d6970SRiver Riddle : mlirModule(module), llvmModule(std::move(llvmModule)), 195c33d6970SRiver Riddle debugTranslation( 19692a295ebSKiran Chandramohan std::make_unique<DebugTranslation>(module, *this->llvmModule)), 197b77bac05SAlex Zinenko typeTranslator(this->llvmModule->getContext()), 198b77bac05SAlex Zinenko iface(module->getContext()) { 199c33d6970SRiver Riddle assert(satisfiesLLVMModule(mlirModule) && 200c33d6970SRiver Riddle "mlirModule should honor LLVM's module semantics."); 201c33d6970SRiver Riddle } 202d9067dcaSKiran Chandramohan ModuleTranslation::~ModuleTranslation() { 203d9067dcaSKiran Chandramohan if (ompBuilder) 204d9067dcaSKiran Chandramohan ompBuilder->finalize(); 205d9067dcaSKiran Chandramohan } 206d9067dcaSKiran Chandramohan 207d9067dcaSKiran Chandramohan /// Get the SSA value passed to the current block from the terminator operation 208d9067dcaSKiran Chandramohan /// of its predecessor. 209d9067dcaSKiran Chandramohan static Value getPHISourceValue(Block *current, Block *pred, 210d9067dcaSKiran Chandramohan unsigned numArguments, unsigned index) { 211d9067dcaSKiran Chandramohan Operation &terminator = *pred->getTerminator(); 212d9067dcaSKiran Chandramohan if (isa<LLVM::BrOp>(terminator)) 213d9067dcaSKiran Chandramohan return terminator.getOperand(index); 214d9067dcaSKiran Chandramohan 21514f24155SBrian Gesiak SuccessorRange successors = terminator.getSuccessors(); 21614f24155SBrian Gesiak assert(std::adjacent_find(successors.begin(), successors.end()) == 21714f24155SBrian Gesiak successors.end() && 21814f24155SBrian Gesiak "successors with arguments in LLVM branches must be different blocks"); 21958f2b765SChristian Sigg (void)successors; 220d9067dcaSKiran Chandramohan 22114f24155SBrian Gesiak // For instructions that branch based on a condition value, we need to take 22214f24155SBrian Gesiak // the operands for the branch that was taken. 22314f24155SBrian Gesiak if (auto condBranchOp = dyn_cast<LLVM::CondBrOp>(terminator)) { 22414f24155SBrian Gesiak // For conditional branches, we take the operands from either the "true" or 22514f24155SBrian Gesiak // the "false" branch. 226d9067dcaSKiran Chandramohan return condBranchOp.getSuccessor(0) == current 227d9067dcaSKiran Chandramohan ? condBranchOp.trueDestOperands()[index] 228d9067dcaSKiran Chandramohan : condBranchOp.falseDestOperands()[index]; 2290881a4f1SAlex Zinenko } 2300881a4f1SAlex Zinenko 2310881a4f1SAlex Zinenko if (auto switchOp = dyn_cast<LLVM::SwitchOp>(terminator)) { 23214f24155SBrian Gesiak // For switches, we take the operands from either the default case, or from 23314f24155SBrian Gesiak // the case branch that was taken. 23414f24155SBrian Gesiak if (switchOp.defaultDestination() == current) 23514f24155SBrian Gesiak return switchOp.defaultOperands()[index]; 23614f24155SBrian Gesiak for (auto i : llvm::enumerate(switchOp.caseDestinations())) 23714f24155SBrian Gesiak if (i.value() == current) 23814f24155SBrian Gesiak return switchOp.getCaseOperands(i.index())[index]; 23914f24155SBrian Gesiak } 24014f24155SBrian Gesiak 24114f24155SBrian Gesiak llvm_unreachable("only branch or switch operations can be terminators of a " 24214f24155SBrian Gesiak "block that has successors"); 243d9067dcaSKiran Chandramohan } 244d9067dcaSKiran Chandramohan 245d9067dcaSKiran Chandramohan /// Connect the PHI nodes to the results of preceding blocks. 24666900b3eSAlex Zinenko void mlir::LLVM::detail::connectPHINodes(Region ®ion, 24766900b3eSAlex Zinenko const ModuleTranslation &state) { 248d9067dcaSKiran Chandramohan // Skip the first block, it cannot be branched to and its arguments correspond 249d9067dcaSKiran Chandramohan // to the arguments of the LLVM function. 25066900b3eSAlex Zinenko for (auto it = std::next(region.begin()), eit = region.end(); it != eit; 25166900b3eSAlex Zinenko ++it) { 252d9067dcaSKiran Chandramohan Block *bb = &*it; 2530881a4f1SAlex Zinenko llvm::BasicBlock *llvmBB = state.lookupBlock(bb); 254d9067dcaSKiran Chandramohan auto phis = llvmBB->phis(); 255d9067dcaSKiran Chandramohan auto numArguments = bb->getNumArguments(); 256d9067dcaSKiran Chandramohan assert(numArguments == std::distance(phis.begin(), phis.end())); 257d9067dcaSKiran Chandramohan for (auto &numberedPhiNode : llvm::enumerate(phis)) { 258d9067dcaSKiran Chandramohan auto &phiNode = numberedPhiNode.value(); 259d9067dcaSKiran Chandramohan unsigned index = numberedPhiNode.index(); 260d9067dcaSKiran Chandramohan for (auto *pred : bb->getPredecessors()) { 261db884dafSAlex Zinenko // Find the LLVM IR block that contains the converted terminator 262db884dafSAlex Zinenko // instruction and use it in the PHI node. Note that this block is not 2630881a4f1SAlex Zinenko // necessarily the same as state.lookupBlock(pred), some operations 264db884dafSAlex Zinenko // (in particular, OpenMP operations using OpenMPIRBuilder) may have 265db884dafSAlex Zinenko // split the blocks. 266db884dafSAlex Zinenko llvm::Instruction *terminator = 2670881a4f1SAlex Zinenko state.lookupBranch(pred->getTerminator()); 268db884dafSAlex Zinenko assert(terminator && "missing the mapping for a terminator"); 2690881a4f1SAlex Zinenko phiNode.addIncoming( 2700881a4f1SAlex Zinenko state.lookupValue(getPHISourceValue(bb, pred, numArguments, index)), 271db884dafSAlex Zinenko terminator->getParent()); 272d9067dcaSKiran Chandramohan } 273d9067dcaSKiran Chandramohan } 274d9067dcaSKiran Chandramohan } 275d9067dcaSKiran Chandramohan } 276d9067dcaSKiran Chandramohan 277d9067dcaSKiran Chandramohan /// Sort function blocks topologically. 27866900b3eSAlex Zinenko llvm::SetVector<Block *> 27966900b3eSAlex Zinenko mlir::LLVM::detail::getTopologicallySortedBlocks(Region ®ion) { 280d4568ed7SGeorge Mitenkov // For each block that has not been visited yet (i.e. that has no 281d4568ed7SGeorge Mitenkov // predecessors), add it to the list as well as its successors. 282d9067dcaSKiran Chandramohan llvm::SetVector<Block *> blocks; 28366900b3eSAlex Zinenko for (Block &b : region) { 284d4568ed7SGeorge Mitenkov if (blocks.count(&b) == 0) { 285d4568ed7SGeorge Mitenkov llvm::ReversePostOrderTraversal<Block *> traversal(&b); 286d4568ed7SGeorge Mitenkov blocks.insert(traversal.begin(), traversal.end()); 287d4568ed7SGeorge Mitenkov } 288d9067dcaSKiran Chandramohan } 28966900b3eSAlex Zinenko assert(blocks.size() == region.getBlocks().size() && 29066900b3eSAlex Zinenko "some blocks are not sorted"); 291d9067dcaSKiran Chandramohan 292d9067dcaSKiran Chandramohan return blocks; 293d9067dcaSKiran Chandramohan } 294d9067dcaSKiran Chandramohan 295176379e0SAlex Zinenko llvm::Value *mlir::LLVM::detail::createIntrinsicCall( 296176379e0SAlex Zinenko llvm::IRBuilderBase &builder, llvm::Intrinsic::ID intrinsic, 297176379e0SAlex Zinenko ArrayRef<llvm::Value *> args, ArrayRef<llvm::Type *> tys) { 298176379e0SAlex Zinenko llvm::Module *module = builder.GetInsertBlock()->getModule(); 299176379e0SAlex Zinenko llvm::Function *fn = llvm::Intrinsic::getDeclaration(module, intrinsic, tys); 300176379e0SAlex Zinenko return builder.CreateCall(fn, args); 301176379e0SAlex Zinenko } 302176379e0SAlex Zinenko 3032666b973SRiver Riddle /// Given a single MLIR operation, create the corresponding LLVM IR operation 304176379e0SAlex Zinenko /// using the `builder`. 305ce8f10d6SAlex Zinenko LogicalResult 306ce8f10d6SAlex Zinenko ModuleTranslation::convertOperation(Operation &opInst, 307ce8f10d6SAlex Zinenko llvm::IRBuilderBase &builder) { 308176379e0SAlex Zinenko if (failed(iface.convertOperation(&opInst, builder, *this))) 309baa1ec22SAlex Zinenko return opInst.emitError("unsupported or non-LLVM operation: ") 310baa1ec22SAlex Zinenko << opInst.getName(); 311176379e0SAlex Zinenko 312176379e0SAlex Zinenko return convertDialectAttributes(&opInst); 3135d7231d8SStephan Herhut } 3145d7231d8SStephan Herhut 3152666b973SRiver Riddle /// Convert block to LLVM IR. Unless `ignoreArguments` is set, emit PHI nodes 3162666b973SRiver Riddle /// to define values corresponding to the MLIR block arguments. These nodes 31710164a2eSAlex Zinenko /// are not connected to the source basic blocks, which may not exist yet. Uses 31810164a2eSAlex Zinenko /// `builder` to construct the LLVM IR. Expects the LLVM IR basic block to have 31910164a2eSAlex Zinenko /// been created for `bb` and included in the block mapping. Inserts new 32010164a2eSAlex Zinenko /// instructions at the end of the block and leaves `builder` in a state 32110164a2eSAlex Zinenko /// suitable for further insertion into the end of the block. 32210164a2eSAlex Zinenko LogicalResult ModuleTranslation::convertBlock(Block &bb, bool ignoreArguments, 323ce8f10d6SAlex Zinenko llvm::IRBuilderBase &builder) { 3240881a4f1SAlex Zinenko builder.SetInsertPoint(lookupBlock(&bb)); 325c33d6970SRiver Riddle auto *subprogram = builder.GetInsertBlock()->getParent()->getSubprogram(); 3265d7231d8SStephan Herhut 3275d7231d8SStephan Herhut // Before traversing operations, make block arguments available through 3285d7231d8SStephan Herhut // value remapping and PHI nodes, but do not add incoming edges for the PHI 3295d7231d8SStephan Herhut // nodes just yet: those values may be defined by this or following blocks. 3305d7231d8SStephan Herhut // This step is omitted if "ignoreArguments" is set. The arguments of the 3315d7231d8SStephan Herhut // first block have been already made available through the remapping of 3325d7231d8SStephan Herhut // LLVM function arguments. 3335d7231d8SStephan Herhut if (!ignoreArguments) { 3345d7231d8SStephan Herhut auto predecessors = bb.getPredecessors(); 3355d7231d8SStephan Herhut unsigned numPredecessors = 3365d7231d8SStephan Herhut std::distance(predecessors.begin(), predecessors.end()); 33735807bc4SRiver Riddle for (auto arg : bb.getArguments()) { 338c69c9e0fSAlex Zinenko auto wrappedType = arg.getType(); 339c69c9e0fSAlex Zinenko if (!isCompatibleType(wrappedType)) 340baa1ec22SAlex Zinenko return emitError(bb.front().getLoc(), 341a4c3a645SRiver Riddle "block argument does not have an LLVM type"); 342aec38c61SAlex Zinenko llvm::Type *type = convertType(wrappedType); 3435d7231d8SStephan Herhut llvm::PHINode *phi = builder.CreatePHI(type, numPredecessors); 3440881a4f1SAlex Zinenko mapValue(arg, phi); 3455d7231d8SStephan Herhut } 3465d7231d8SStephan Herhut } 3475d7231d8SStephan Herhut 3485d7231d8SStephan Herhut // Traverse operations. 3495d7231d8SStephan Herhut for (auto &op : bb) { 350c33d6970SRiver Riddle // Set the current debug location within the builder. 351c33d6970SRiver Riddle builder.SetCurrentDebugLocation( 352c33d6970SRiver Riddle debugTranslation->translateLoc(op.getLoc(), subprogram)); 353c33d6970SRiver Riddle 354baa1ec22SAlex Zinenko if (failed(convertOperation(op, builder))) 355baa1ec22SAlex Zinenko return failure(); 3565d7231d8SStephan Herhut } 3575d7231d8SStephan Herhut 358baa1ec22SAlex Zinenko return success(); 3595d7231d8SStephan Herhut } 3605d7231d8SStephan Herhut 361ce8f10d6SAlex Zinenko /// A helper method to get the single Block in an operation honoring LLVM's 362ce8f10d6SAlex Zinenko /// module requirements. 363ce8f10d6SAlex Zinenko static Block &getModuleBody(Operation *module) { 364ce8f10d6SAlex Zinenko return module->getRegion(0).front(); 365ce8f10d6SAlex Zinenko } 366ce8f10d6SAlex Zinenko 3672666b973SRiver Riddle /// Create named global variables that correspond to llvm.mlir.global 3682666b973SRiver Riddle /// definitions. 369efa2d533SAlex Zinenko LogicalResult ModuleTranslation::convertGlobals() { 37044fc7d72STres Popp for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) { 371aec38c61SAlex Zinenko llvm::Type *type = convertType(op.getType()); 372250a11aeSJames Molloy llvm::Constant *cst = llvm::UndefValue::get(type); 373250a11aeSJames Molloy if (op.getValueOrNull()) { 37468451df2SAlex Zinenko // String attributes are treated separately because they cannot appear as 37568451df2SAlex Zinenko // in-function constants and are thus not supported by getLLVMConstant. 37633a3a91bSChristian Sigg if (auto strAttr = op.getValueOrNull().dyn_cast_or_null<StringAttr>()) { 3772dd38b09SAlex Zinenko cst = llvm::ConstantDataArray::getString( 37868451df2SAlex Zinenko llvmModule->getContext(), strAttr.getValue(), /*AddNull=*/false); 3792dd38b09SAlex Zinenko type = cst->getType(); 380176379e0SAlex Zinenko } else if (!(cst = getLLVMConstant(type, op.getValueOrNull(), op.getLoc(), 381176379e0SAlex Zinenko *this))) { 382efa2d533SAlex Zinenko return failure(); 38368451df2SAlex Zinenko } 384250a11aeSJames Molloy } else if (Block *initializer = op.getInitializerBlock()) { 385250a11aeSJames Molloy llvm::IRBuilder<> builder(llvmModule->getContext()); 386250a11aeSJames Molloy for (auto &op : initializer->without_terminator()) { 387250a11aeSJames Molloy if (failed(convertOperation(op, builder)) || 3880881a4f1SAlex Zinenko !isa<llvm::Constant>(lookupValue(op.getResult(0)))) 389efa2d533SAlex Zinenko return emitError(op.getLoc(), "unemittable constant value"); 390250a11aeSJames Molloy } 391250a11aeSJames Molloy ReturnOp ret = cast<ReturnOp>(initializer->getTerminator()); 3920881a4f1SAlex Zinenko cst = cast<llvm::Constant>(lookupValue(ret.getOperand(0))); 393250a11aeSJames Molloy } 39468451df2SAlex Zinenko 395eb67bd78SAlex Zinenko auto linkage = convertLinkageToLLVM(op.linkage()); 396d5e627f8SAlex Zinenko bool anyExternalLinkage = 3977b5d4669SEric Schweitz ((linkage == llvm::GlobalVariable::ExternalLinkage && 3987b5d4669SEric Schweitz isa<llvm::UndefValue>(cst)) || 399d5e627f8SAlex Zinenko linkage == llvm::GlobalVariable::ExternalWeakLinkage); 400431bb8b3SRiver Riddle auto addrSpace = op.addr_space(); 401e79bfefbSMLIR Team auto *var = new llvm::GlobalVariable( 402d5e627f8SAlex Zinenko *llvmModule, type, op.constant(), linkage, 403d5e627f8SAlex Zinenko anyExternalLinkage ? nullptr : cst, op.sym_name(), 404d5e627f8SAlex Zinenko /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal, addrSpace); 405e79bfefbSMLIR Team 4062dd38b09SAlex Zinenko globalsMapping.try_emplace(op, var); 407b9ff2dd8SAlex Zinenko } 408efa2d533SAlex Zinenko 409efa2d533SAlex Zinenko return success(); 410b9ff2dd8SAlex Zinenko } 411b9ff2dd8SAlex Zinenko 4120a2131b7SAlex Zinenko /// Attempts to add an attribute identified by `key`, optionally with the given 4130a2131b7SAlex Zinenko /// `value` to LLVM function `llvmFunc`. Reports errors at `loc` if any. If the 4140a2131b7SAlex Zinenko /// attribute has a kind known to LLVM IR, create the attribute of this kind, 4150a2131b7SAlex Zinenko /// otherwise keep it as a string attribute. Performs additional checks for 4160a2131b7SAlex Zinenko /// attributes known to have or not have a value in order to avoid assertions 4170a2131b7SAlex Zinenko /// inside LLVM upon construction. 4180a2131b7SAlex Zinenko static LogicalResult checkedAddLLVMFnAttribute(Location loc, 4190a2131b7SAlex Zinenko llvm::Function *llvmFunc, 4200a2131b7SAlex Zinenko StringRef key, 4210a2131b7SAlex Zinenko StringRef value = StringRef()) { 4220a2131b7SAlex Zinenko auto kind = llvm::Attribute::getAttrKindFromName(key); 4230a2131b7SAlex Zinenko if (kind == llvm::Attribute::None) { 4240a2131b7SAlex Zinenko llvmFunc->addFnAttr(key, value); 4250a2131b7SAlex Zinenko return success(); 4260a2131b7SAlex Zinenko } 4270a2131b7SAlex Zinenko 4280a2131b7SAlex Zinenko if (llvm::Attribute::doesAttrKindHaveArgument(kind)) { 4290a2131b7SAlex Zinenko if (value.empty()) 4300a2131b7SAlex Zinenko return emitError(loc) << "LLVM attribute '" << key << "' expects a value"; 4310a2131b7SAlex Zinenko 4320a2131b7SAlex Zinenko int result; 4330a2131b7SAlex Zinenko if (!value.getAsInteger(/*Radix=*/0, result)) 4340a2131b7SAlex Zinenko llvmFunc->addFnAttr( 4350a2131b7SAlex Zinenko llvm::Attribute::get(llvmFunc->getContext(), kind, result)); 4360a2131b7SAlex Zinenko else 4370a2131b7SAlex Zinenko llvmFunc->addFnAttr(key, value); 4380a2131b7SAlex Zinenko return success(); 4390a2131b7SAlex Zinenko } 4400a2131b7SAlex Zinenko 4410a2131b7SAlex Zinenko if (!value.empty()) 4420a2131b7SAlex Zinenko return emitError(loc) << "LLVM attribute '" << key 4430a2131b7SAlex Zinenko << "' does not expect a value, found '" << value 4440a2131b7SAlex Zinenko << "'"; 4450a2131b7SAlex Zinenko 4460a2131b7SAlex Zinenko llvmFunc->addFnAttr(kind); 4470a2131b7SAlex Zinenko return success(); 4480a2131b7SAlex Zinenko } 4490a2131b7SAlex Zinenko 4500a2131b7SAlex Zinenko /// Attaches the attributes listed in the given array attribute to `llvmFunc`. 4510a2131b7SAlex Zinenko /// Reports error to `loc` if any and returns immediately. Expects `attributes` 4520a2131b7SAlex Zinenko /// to be an array attribute containing either string attributes, treated as 4530a2131b7SAlex Zinenko /// value-less LLVM attributes, or array attributes containing two string 4540a2131b7SAlex Zinenko /// attributes, with the first string being the name of the corresponding LLVM 4550a2131b7SAlex Zinenko /// attribute and the second string beings its value. Note that even integer 4560a2131b7SAlex Zinenko /// attributes are expected to have their values expressed as strings. 4570a2131b7SAlex Zinenko static LogicalResult 4580a2131b7SAlex Zinenko forwardPassthroughAttributes(Location loc, Optional<ArrayAttr> attributes, 4590a2131b7SAlex Zinenko llvm::Function *llvmFunc) { 4600a2131b7SAlex Zinenko if (!attributes) 4610a2131b7SAlex Zinenko return success(); 4620a2131b7SAlex Zinenko 4630a2131b7SAlex Zinenko for (Attribute attr : *attributes) { 4640a2131b7SAlex Zinenko if (auto stringAttr = attr.dyn_cast<StringAttr>()) { 4650a2131b7SAlex Zinenko if (failed( 4660a2131b7SAlex Zinenko checkedAddLLVMFnAttribute(loc, llvmFunc, stringAttr.getValue()))) 4670a2131b7SAlex Zinenko return failure(); 4680a2131b7SAlex Zinenko continue; 4690a2131b7SAlex Zinenko } 4700a2131b7SAlex Zinenko 4710a2131b7SAlex Zinenko auto arrayAttr = attr.dyn_cast<ArrayAttr>(); 4720a2131b7SAlex Zinenko if (!arrayAttr || arrayAttr.size() != 2) 4730a2131b7SAlex Zinenko return emitError(loc) 4740a2131b7SAlex Zinenko << "expected 'passthrough' to contain string or array attributes"; 4750a2131b7SAlex Zinenko 4760a2131b7SAlex Zinenko auto keyAttr = arrayAttr[0].dyn_cast<StringAttr>(); 4770a2131b7SAlex Zinenko auto valueAttr = arrayAttr[1].dyn_cast<StringAttr>(); 4780a2131b7SAlex Zinenko if (!keyAttr || !valueAttr) 4790a2131b7SAlex Zinenko return emitError(loc) 4800a2131b7SAlex Zinenko << "expected arrays within 'passthrough' to contain two strings"; 4810a2131b7SAlex Zinenko 4820a2131b7SAlex Zinenko if (failed(checkedAddLLVMFnAttribute(loc, llvmFunc, keyAttr.getValue(), 4830a2131b7SAlex Zinenko valueAttr.getValue()))) 4840a2131b7SAlex Zinenko return failure(); 4850a2131b7SAlex Zinenko } 4860a2131b7SAlex Zinenko return success(); 4870a2131b7SAlex Zinenko } 4880a2131b7SAlex Zinenko 4895e7959a3SAlex Zinenko LogicalResult ModuleTranslation::convertOneFunction(LLVMFuncOp func) { 490db884dafSAlex Zinenko // Clear the block, branch value mappings, they are only relevant within one 4915d7231d8SStephan Herhut // function. 4925d7231d8SStephan Herhut blockMapping.clear(); 4935d7231d8SStephan Herhut valueMapping.clear(); 494db884dafSAlex Zinenko branchMapping.clear(); 4950881a4f1SAlex Zinenko llvm::Function *llvmFunc = lookupFunction(func.getName()); 496c33d6970SRiver Riddle 497c33d6970SRiver Riddle // Translate the debug information for this function. 498c33d6970SRiver Riddle debugTranslation->translate(func, *llvmFunc); 499c33d6970SRiver Riddle 5005d7231d8SStephan Herhut // Add function arguments to the value remapping table. 5015d7231d8SStephan Herhut // If there was noalias info then we decorate each argument accordingly. 5025d7231d8SStephan Herhut unsigned int argIdx = 0; 503eeef50b1SFangrui Song for (auto kvp : llvm::zip(func.getArguments(), llvmFunc->args())) { 5045d7231d8SStephan Herhut llvm::Argument &llvmArg = std::get<1>(kvp); 505e62a6956SRiver Riddle BlockArgument mlirArg = std::get<0>(kvp); 5065d7231d8SStephan Herhut 50767cc5cecSStephan Herhut if (auto attr = func.getArgAttrOfType<BoolAttr>( 50867cc5cecSStephan Herhut argIdx, LLVMDialect::getNoAliasAttrName())) { 5095d7231d8SStephan Herhut // NB: Attribute already verified to be boolean, so check if we can indeed 5105d7231d8SStephan Herhut // attach the attribute to this argument, based on its type. 511c69c9e0fSAlex Zinenko auto argTy = mlirArg.getType(); 5128de43b92SAlex Zinenko if (!argTy.isa<LLVM::LLVMPointerType>()) 513baa1ec22SAlex Zinenko return func.emitError( 5145d7231d8SStephan Herhut "llvm.noalias attribute attached to LLVM non-pointer argument"); 5155d7231d8SStephan Herhut if (attr.getValue()) 5165d7231d8SStephan Herhut llvmArg.addAttr(llvm::Attribute::AttrKind::NoAlias); 5175d7231d8SStephan Herhut } 5182416e28cSStephan Herhut 51967cc5cecSStephan Herhut if (auto attr = func.getArgAttrOfType<IntegerAttr>( 52067cc5cecSStephan Herhut argIdx, LLVMDialect::getAlignAttrName())) { 5212416e28cSStephan Herhut // NB: Attribute already verified to be int, so check if we can indeed 5222416e28cSStephan Herhut // attach the attribute to this argument, based on its type. 523c69c9e0fSAlex Zinenko auto argTy = mlirArg.getType(); 5248de43b92SAlex Zinenko if (!argTy.isa<LLVM::LLVMPointerType>()) 5252416e28cSStephan Herhut return func.emitError( 5262416e28cSStephan Herhut "llvm.align attribute attached to LLVM non-pointer argument"); 5272416e28cSStephan Herhut llvmArg.addAttrs( 5282416e28cSStephan Herhut llvm::AttrBuilder().addAlignmentAttr(llvm::Align(attr.getInt()))); 5292416e28cSStephan Herhut } 5302416e28cSStephan Herhut 53170b841acSEric Schweitz if (auto attr = func.getArgAttrOfType<UnitAttr>(argIdx, "llvm.sret")) { 53270b841acSEric Schweitz auto argTy = mlirArg.getType(); 53370b841acSEric Schweitz if (!argTy.isa<LLVM::LLVMPointerType>()) 53470b841acSEric Schweitz return func.emitError( 53570b841acSEric Schweitz "llvm.sret attribute attached to LLVM non-pointer argument"); 5361d6df1fcSEric Schweitz llvmArg.addAttrs(llvm::AttrBuilder().addStructRetAttr( 5371d6df1fcSEric Schweitz llvmArg.getType()->getPointerElementType())); 53870b841acSEric Schweitz } 53970b841acSEric Schweitz 54070b841acSEric Schweitz if (auto attr = func.getArgAttrOfType<UnitAttr>(argIdx, "llvm.byval")) { 54170b841acSEric Schweitz auto argTy = mlirArg.getType(); 54270b841acSEric Schweitz if (!argTy.isa<LLVM::LLVMPointerType>()) 54370b841acSEric Schweitz return func.emitError( 54470b841acSEric Schweitz "llvm.byval attribute attached to LLVM non-pointer argument"); 5451d6df1fcSEric Schweitz llvmArg.addAttrs(llvm::AttrBuilder().addByValAttr( 5461d6df1fcSEric Schweitz llvmArg.getType()->getPointerElementType())); 54770b841acSEric Schweitz } 54870b841acSEric Schweitz 5490881a4f1SAlex Zinenko mapValue(mlirArg, &llvmArg); 5505d7231d8SStephan Herhut argIdx++; 5515d7231d8SStephan Herhut } 5525d7231d8SStephan Herhut 553ff77397fSShraiysh Vaishay // Check the personality and set it. 554ff77397fSShraiysh Vaishay if (func.personality().hasValue()) { 555ff77397fSShraiysh Vaishay llvm::Type *ty = llvm::Type::getInt8PtrTy(llvmFunc->getContext()); 556ff77397fSShraiysh Vaishay if (llvm::Constant *pfunc = 557176379e0SAlex Zinenko getLLVMConstant(ty, func.personalityAttr(), func.getLoc(), *this)) 558ff77397fSShraiysh Vaishay llvmFunc->setPersonalityFn(pfunc); 559ff77397fSShraiysh Vaishay } 560ff77397fSShraiysh Vaishay 5615d7231d8SStephan Herhut // First, create all blocks so we can jump to them. 5625d7231d8SStephan Herhut llvm::LLVMContext &llvmContext = llvmFunc->getContext(); 5635d7231d8SStephan Herhut for (auto &bb : func) { 5645d7231d8SStephan Herhut auto *llvmBB = llvm::BasicBlock::Create(llvmContext); 5655d7231d8SStephan Herhut llvmBB->insertInto(llvmFunc); 5660881a4f1SAlex Zinenko mapBlock(&bb, llvmBB); 5675d7231d8SStephan Herhut } 5685d7231d8SStephan Herhut 5695d7231d8SStephan Herhut // Then, convert blocks one by one in topological order to ensure defs are 5705d7231d8SStephan Herhut // converted before uses. 57166900b3eSAlex Zinenko auto blocks = detail::getTopologicallySortedBlocks(func.getBody()); 57210164a2eSAlex Zinenko for (Block *bb : blocks) { 57310164a2eSAlex Zinenko llvm::IRBuilder<> builder(llvmContext); 57410164a2eSAlex Zinenko if (failed(convertBlock(*bb, bb->isEntryBlock(), builder))) 575baa1ec22SAlex Zinenko return failure(); 5765d7231d8SStephan Herhut } 5775d7231d8SStephan Herhut 578176379e0SAlex Zinenko // After all blocks have been traversed and values mapped, connect the PHI 579176379e0SAlex Zinenko // nodes to the results of preceding blocks. 58066900b3eSAlex Zinenko detail::connectPHINodes(func.getBody(), *this); 581176379e0SAlex Zinenko 582176379e0SAlex Zinenko // Finally, convert dialect attributes attached to the function. 583176379e0SAlex Zinenko return convertDialectAttributes(func); 584176379e0SAlex Zinenko } 585176379e0SAlex Zinenko 586176379e0SAlex Zinenko LogicalResult ModuleTranslation::convertDialectAttributes(Operation *op) { 587176379e0SAlex Zinenko for (NamedAttribute attribute : op->getDialectAttrs()) 588176379e0SAlex Zinenko if (failed(iface.amendOperation(op, attribute, *this))) 589176379e0SAlex Zinenko return failure(); 590baa1ec22SAlex Zinenko return success(); 5915d7231d8SStephan Herhut } 5925d7231d8SStephan Herhut 593ce8f10d6SAlex Zinenko /// Check whether the module contains only supported ops directly in its body. 594ce8f10d6SAlex Zinenko static LogicalResult checkSupportedModuleOps(Operation *m) { 59544fc7d72STres Popp for (Operation &o : getModuleBody(m).getOperations()) 5964a2930f4SArpith C. Jacob if (!isa<LLVM::LLVMFuncOp, LLVM::GlobalOp, LLVM::MetadataOp>(&o) && 597fe7c0d90SRiver Riddle !o.hasTrait<OpTrait::IsTerminator>()) 5984dde19f0SAlex Zinenko return o.emitOpError("unsupported module-level operation"); 5994dde19f0SAlex Zinenko return success(); 6004dde19f0SAlex Zinenko } 6014dde19f0SAlex Zinenko 602a084b94fSSean Silva LogicalResult ModuleTranslation::convertFunctionSignatures() { 6035d7231d8SStephan Herhut // Declare all functions first because there may be function calls that form a 604a084b94fSSean Silva // call graph with cycles, or global initializers that reference functions. 60544fc7d72STres Popp for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) { 6065e7959a3SAlex Zinenko llvm::FunctionCallee llvmFuncCst = llvmModule->getOrInsertFunction( 6075e7959a3SAlex Zinenko function.getName(), 608aec38c61SAlex Zinenko cast<llvm::FunctionType>(convertType(function.getType()))); 6090a2131b7SAlex Zinenko llvm::Function *llvmFunc = cast<llvm::Function>(llvmFuncCst.getCallee()); 610ebbdecddSAlex Zinenko llvmFunc->setLinkage(convertLinkageToLLVM(function.linkage())); 6110881a4f1SAlex Zinenko mapFunction(function.getName(), llvmFunc); 6120a2131b7SAlex Zinenko 6130a2131b7SAlex Zinenko // Forward the pass-through attributes to LLVM. 6140a2131b7SAlex Zinenko if (failed(forwardPassthroughAttributes(function.getLoc(), 6150a2131b7SAlex Zinenko function.passthrough(), llvmFunc))) 6160a2131b7SAlex Zinenko return failure(); 6175d7231d8SStephan Herhut } 6185d7231d8SStephan Herhut 619a084b94fSSean Silva return success(); 620a084b94fSSean Silva } 621a084b94fSSean Silva 622a084b94fSSean Silva LogicalResult ModuleTranslation::convertFunctions() { 6235d7231d8SStephan Herhut // Convert functions. 62444fc7d72STres Popp for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) { 6255d7231d8SStephan Herhut // Ignore external functions. 6265d7231d8SStephan Herhut if (function.isExternal()) 6275d7231d8SStephan Herhut continue; 6285d7231d8SStephan Herhut 629baa1ec22SAlex Zinenko if (failed(convertOneFunction(function))) 630baa1ec22SAlex Zinenko return failure(); 6315d7231d8SStephan Herhut } 6325d7231d8SStephan Herhut 633baa1ec22SAlex Zinenko return success(); 6345d7231d8SStephan Herhut } 6355d7231d8SStephan Herhut 6364a2930f4SArpith C. Jacob llvm::MDNode * 6374a2930f4SArpith C. Jacob ModuleTranslation::getAccessGroup(Operation &opInst, 6384a2930f4SArpith C. Jacob SymbolRefAttr accessGroupRef) const { 6394a2930f4SArpith C. Jacob auto metadataName = accessGroupRef.getRootReference(); 6404a2930f4SArpith C. Jacob auto accessGroupName = accessGroupRef.getLeafReference(); 6414a2930f4SArpith C. Jacob auto metadataOp = SymbolTable::lookupNearestSymbolFrom<LLVM::MetadataOp>( 6424a2930f4SArpith C. Jacob opInst.getParentOp(), metadataName); 6434a2930f4SArpith C. Jacob auto *accessGroupOp = 6444a2930f4SArpith C. Jacob SymbolTable::lookupNearestSymbolFrom(metadataOp, accessGroupName); 6454a2930f4SArpith C. Jacob return accessGroupMetadataMapping.lookup(accessGroupOp); 6464a2930f4SArpith C. Jacob } 6474a2930f4SArpith C. Jacob 6484a2930f4SArpith C. Jacob LogicalResult ModuleTranslation::createAccessGroupMetadata() { 6494a2930f4SArpith C. Jacob mlirModule->walk([&](LLVM::MetadataOp metadatas) { 6504a2930f4SArpith C. Jacob metadatas.walk([&](LLVM::AccessGroupMetadataOp op) { 6514a2930f4SArpith C. Jacob llvm::LLVMContext &ctx = llvmModule->getContext(); 6524a2930f4SArpith C. Jacob llvm::MDNode *accessGroup = llvm::MDNode::getDistinct(ctx, {}); 6534a2930f4SArpith C. Jacob accessGroupMetadataMapping.insert({op, accessGroup}); 6544a2930f4SArpith C. Jacob }); 6554a2930f4SArpith C. Jacob }); 6564a2930f4SArpith C. Jacob return success(); 6574a2930f4SArpith C. Jacob } 6584a2930f4SArpith C. Jacob 659*4e393350SArpith C. Jacob void ModuleTranslation::setAccessGroupsMetadata(Operation *op, 660*4e393350SArpith C. Jacob llvm::Instruction *inst) { 661*4e393350SArpith C. Jacob auto accessGroups = 662*4e393350SArpith C. Jacob op->getAttrOfType<ArrayAttr>(LLVMDialect::getAccessGroupsAttrName()); 663*4e393350SArpith C. Jacob if (accessGroups && !accessGroups.empty()) { 664*4e393350SArpith C. Jacob llvm::Module *module = inst->getModule(); 665*4e393350SArpith C. Jacob SmallVector<llvm::Metadata *> metadatas; 666*4e393350SArpith C. Jacob for (SymbolRefAttr accessGroupRef : 667*4e393350SArpith C. Jacob accessGroups.getAsRange<SymbolRefAttr>()) 668*4e393350SArpith C. Jacob metadatas.push_back(getAccessGroup(*op, accessGroupRef)); 669*4e393350SArpith C. Jacob 670*4e393350SArpith C. Jacob llvm::MDNode *unionMD = nullptr; 671*4e393350SArpith C. Jacob if (metadatas.size() == 1) 672*4e393350SArpith C. Jacob unionMD = llvm::cast<llvm::MDNode>(metadatas.front()); 673*4e393350SArpith C. Jacob else if (metadatas.size() >= 2) 674*4e393350SArpith C. Jacob unionMD = llvm::MDNode::get(module->getContext(), metadatas); 675*4e393350SArpith C. Jacob 676*4e393350SArpith C. Jacob inst->setMetadata(module->getMDKindID("llvm.access.group"), unionMD); 677*4e393350SArpith C. Jacob } 678*4e393350SArpith C. Jacob } 679*4e393350SArpith C. Jacob 680c69c9e0fSAlex Zinenko llvm::Type *ModuleTranslation::convertType(Type type) { 681b2ab375dSAlex Zinenko return typeTranslator.translateType(type); 682aec38c61SAlex Zinenko } 683aec38c61SAlex Zinenko 684efadb6b8SAlex Zinenko /// A helper to look up remapped operands in the value remapping table.` 685efadb6b8SAlex Zinenko SmallVector<llvm::Value *, 8> 686efadb6b8SAlex Zinenko ModuleTranslation::lookupValues(ValueRange values) { 687efadb6b8SAlex Zinenko SmallVector<llvm::Value *, 8> remapped; 688efadb6b8SAlex Zinenko remapped.reserve(values.size()); 6890881a4f1SAlex Zinenko for (Value v : values) 6900881a4f1SAlex Zinenko remapped.push_back(lookupValue(v)); 691efadb6b8SAlex Zinenko return remapped; 692efadb6b8SAlex Zinenko } 693efadb6b8SAlex Zinenko 69466900b3eSAlex Zinenko const llvm::DILocation * 69566900b3eSAlex Zinenko ModuleTranslation::translateLoc(Location loc, llvm::DILocalScope *scope) { 69666900b3eSAlex Zinenko return debugTranslation->translateLoc(loc, scope); 69766900b3eSAlex Zinenko } 69866900b3eSAlex Zinenko 699176379e0SAlex Zinenko llvm::NamedMDNode * 700176379e0SAlex Zinenko ModuleTranslation::getOrInsertNamedModuleMetadata(StringRef name) { 701176379e0SAlex Zinenko return llvmModule->getOrInsertNamedMetadata(name); 702176379e0SAlex Zinenko } 703176379e0SAlex Zinenko 704ce8f10d6SAlex Zinenko static std::unique_ptr<llvm::Module> 705ce8f10d6SAlex Zinenko prepareLLVMModule(Operation *m, llvm::LLVMContext &llvmContext, 706ce8f10d6SAlex Zinenko StringRef name) { 707f9dc2b70SMehdi Amini m->getContext()->getOrLoadDialect<LLVM::LLVMDialect>(); 708db1c197bSAlex Zinenko auto llvmModule = std::make_unique<llvm::Module>(name, llvmContext); 709168213f9SAlex Zinenko if (auto dataLayoutAttr = 710168213f9SAlex Zinenko m->getAttr(LLVM::LLVMDialect::getDataLayoutAttrName())) 711168213f9SAlex Zinenko llvmModule->setDataLayout(dataLayoutAttr.cast<StringAttr>().getValue()); 7125dd5a083SNicolas Vasilache if (auto targetTripleAttr = 7135dd5a083SNicolas Vasilache m->getAttr(LLVM::LLVMDialect::getTargetTripleAttrName())) 7145dd5a083SNicolas Vasilache llvmModule->setTargetTriple(targetTripleAttr.cast<StringAttr>().getValue()); 7155d7231d8SStephan Herhut 7165d7231d8SStephan Herhut // Inject declarations for `malloc` and `free` functions that can be used in 7175d7231d8SStephan Herhut // memref allocation/deallocation coming from standard ops lowering. 718db1c197bSAlex Zinenko llvm::IRBuilder<> builder(llvmContext); 7195d7231d8SStephan Herhut llvmModule->getOrInsertFunction("malloc", builder.getInt8PtrTy(), 7205d7231d8SStephan Herhut builder.getInt64Ty()); 7215d7231d8SStephan Herhut llvmModule->getOrInsertFunction("free", builder.getVoidTy(), 7225d7231d8SStephan Herhut builder.getInt8PtrTy()); 7235d7231d8SStephan Herhut 7245d7231d8SStephan Herhut return llvmModule; 7255d7231d8SStephan Herhut } 726ce8f10d6SAlex Zinenko 727ce8f10d6SAlex Zinenko std::unique_ptr<llvm::Module> 728ce8f10d6SAlex Zinenko mlir::translateModuleToLLVMIR(Operation *module, llvm::LLVMContext &llvmContext, 729ce8f10d6SAlex Zinenko StringRef name) { 730ce8f10d6SAlex Zinenko if (!satisfiesLLVMModule(module)) 731ce8f10d6SAlex Zinenko return nullptr; 732ce8f10d6SAlex Zinenko if (failed(checkSupportedModuleOps(module))) 733ce8f10d6SAlex Zinenko return nullptr; 734ce8f10d6SAlex Zinenko std::unique_ptr<llvm::Module> llvmModule = 735ce8f10d6SAlex Zinenko prepareLLVMModule(module, llvmContext, name); 736ce8f10d6SAlex Zinenko 737ce8f10d6SAlex Zinenko LLVM::ensureDistinctSuccessors(module); 738ce8f10d6SAlex Zinenko 739ce8f10d6SAlex Zinenko ModuleTranslation translator(module, std::move(llvmModule)); 740ce8f10d6SAlex Zinenko if (failed(translator.convertFunctionSignatures())) 741ce8f10d6SAlex Zinenko return nullptr; 742ce8f10d6SAlex Zinenko if (failed(translator.convertGlobals())) 743ce8f10d6SAlex Zinenko return nullptr; 7444a2930f4SArpith C. Jacob if (failed(translator.createAccessGroupMetadata())) 7454a2930f4SArpith C. Jacob return nullptr; 746ce8f10d6SAlex Zinenko if (failed(translator.convertFunctions())) 747ce8f10d6SAlex Zinenko return nullptr; 748ce8f10d6SAlex Zinenko if (llvm::verifyModule(*translator.llvmModule, &llvm::errs())) 749ce8f10d6SAlex Zinenko return nullptr; 750ce8f10d6SAlex Zinenko 751ce8f10d6SAlex Zinenko return std::move(translator.llvmModule); 752ce8f10d6SAlex Zinenko } 753