1cde4d5a6SJacques Pienaar //===- ModuleTranslation.cpp - MLIR to LLVM conversion --------------------===// 25d7231d8SStephan Herhut // 35d7231d8SStephan Herhut // Copyright 2019 The MLIR Authors. 45d7231d8SStephan Herhut // 55d7231d8SStephan Herhut // Licensed under the Apache License, Version 2.0 (the "License"); 65d7231d8SStephan Herhut // you may not use this file except in compliance with the License. 75d7231d8SStephan Herhut // You may obtain a copy of the License at 85d7231d8SStephan Herhut // 95d7231d8SStephan Herhut // http://www.apache.org/licenses/LICENSE-2.0 105d7231d8SStephan Herhut // 115d7231d8SStephan Herhut // Unless required by applicable law or agreed to in writing, software 125d7231d8SStephan Herhut // distributed under the License is distributed on an "AS IS" BASIS, 135d7231d8SStephan Herhut // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 145d7231d8SStephan Herhut // See the License for the specific language governing permissions and 155d7231d8SStephan Herhut // limitations under the License. 165d7231d8SStephan Herhut // ============================================================================= 175d7231d8SStephan Herhut // 185d7231d8SStephan Herhut // This file implements the translation between an MLIR LLVM dialect module and 195d7231d8SStephan Herhut // the corresponding LLVMIR module. It only handles core LLVM IR operations. 205d7231d8SStephan Herhut // 215d7231d8SStephan Herhut //===----------------------------------------------------------------------===// 225d7231d8SStephan Herhut 235d7231d8SStephan Herhut #include "mlir/Target/LLVMIR/ModuleTranslation.h" 245d7231d8SStephan Herhut 25ba0fa925SRiver Riddle #include "mlir/Dialect/LLVMIR/LLVMDialect.h" 265d7231d8SStephan Herhut #include "mlir/IR/Attributes.h" 275d7231d8SStephan Herhut #include "mlir/IR/Module.h" 285d7231d8SStephan Herhut #include "mlir/Support/LLVM.h" 295d7231d8SStephan Herhut 305d7231d8SStephan Herhut #include "llvm/ADT/SetVector.h" 315d7231d8SStephan Herhut #include "llvm/IR/BasicBlock.h" 325d7231d8SStephan Herhut #include "llvm/IR/Constants.h" 335d7231d8SStephan Herhut #include "llvm/IR/DerivedTypes.h" 345d7231d8SStephan Herhut #include "llvm/IR/IRBuilder.h" 355d7231d8SStephan Herhut #include "llvm/IR/LLVMContext.h" 365d7231d8SStephan Herhut #include "llvm/IR/Module.h" 375d7231d8SStephan Herhut #include "llvm/Transforms/Utils/Cloning.h" 385d7231d8SStephan Herhut 392666b973SRiver Riddle using namespace mlir; 402666b973SRiver Riddle using namespace mlir::LLVM; 415d7231d8SStephan Herhut 422666b973SRiver Riddle /// Create an LLVM IR constant of `llvmType` from the MLIR attribute `attr`. 432666b973SRiver Riddle /// This currently supports integer, floating point, splat and dense element 442666b973SRiver Riddle /// attributes and combinations thereof. In case of error, report it to `loc` 452666b973SRiver Riddle /// and return nullptr. 465d7231d8SStephan Herhut llvm::Constant *ModuleTranslation::getLLVMConstant(llvm::Type *llvmType, 475d7231d8SStephan Herhut Attribute attr, 485d7231d8SStephan Herhut Location loc) { 4933a3a91bSChristian Sigg if (!attr) 5033a3a91bSChristian Sigg return llvm::UndefValue::get(llvmType); 515d7231d8SStephan Herhut if (auto intAttr = attr.dyn_cast<IntegerAttr>()) 525d7231d8SStephan Herhut return llvm::ConstantInt::get(llvmType, intAttr.getValue()); 535d7231d8SStephan Herhut if (auto floatAttr = attr.dyn_cast<FloatAttr>()) 545d7231d8SStephan Herhut return llvm::ConstantFP::get(llvmType, floatAttr.getValue()); 559b9c647cSRiver Riddle if (auto funcAttr = attr.dyn_cast<FlatSymbolRefAttr>()) 565d7231d8SStephan Herhut return functionMapping.lookup(funcAttr.getValue()); 575d7231d8SStephan Herhut if (auto splatAttr = attr.dyn_cast<SplatElementsAttr>()) { 582f13df13SMLIR Team auto *sequentialType = cast<llvm::SequentialType>(llvmType); 592f13df13SMLIR Team auto elementType = sequentialType->getElementType(); 602f13df13SMLIR Team uint64_t numElements = sequentialType->getNumElements(); 612f13df13SMLIR Team auto *child = getLLVMConstant(elementType, splatAttr.getSplatValue(), loc); 622f13df13SMLIR Team if (llvmType->isVectorTy()) 632f13df13SMLIR Team return llvm::ConstantVector::getSplat(numElements, child); 642f13df13SMLIR Team if (llvmType->isArrayTy()) { 652f13df13SMLIR Team auto arrayType = llvm::ArrayType::get(elementType, numElements); 662f13df13SMLIR Team SmallVector<llvm::Constant *, 8> constants(numElements, child); 672f13df13SMLIR Team return llvm::ConstantArray::get(arrayType, constants); 682f13df13SMLIR Team } 695d7231d8SStephan Herhut } 70d906f84bSRiver Riddle if (auto elementsAttr = attr.dyn_cast<ElementsAttr>()) { 712f13df13SMLIR Team auto *sequentialType = cast<llvm::SequentialType>(llvmType); 722f13df13SMLIR Team auto elementType = sequentialType->getElementType(); 732f13df13SMLIR Team uint64_t numElements = sequentialType->getNumElements(); 745d7231d8SStephan Herhut SmallVector<llvm::Constant *, 8> constants; 755d7231d8SStephan Herhut constants.reserve(numElements); 76d906f84bSRiver Riddle for (auto n : elementsAttr.getValues<Attribute>()) { 772f13df13SMLIR Team constants.push_back(getLLVMConstant(elementType, n, loc)); 785d7231d8SStephan Herhut if (!constants.back()) 795d7231d8SStephan Herhut return nullptr; 805d7231d8SStephan Herhut } 812f13df13SMLIR Team if (llvmType->isVectorTy()) 825d7231d8SStephan Herhut return llvm::ConstantVector::get(constants); 832f13df13SMLIR Team if (llvmType->isArrayTy()) { 842f13df13SMLIR Team auto arrayType = llvm::ArrayType::get(elementType, numElements); 852f13df13SMLIR Team return llvm::ConstantArray::get(arrayType, constants); 862f13df13SMLIR Team } 875d7231d8SStephan Herhut } 88cb348dffSStephan Herhut if (auto stringAttr = attr.dyn_cast<StringAttr>()) { 89cb348dffSStephan Herhut return llvm::ConstantDataArray::get( 90cb348dffSStephan Herhut llvmModule->getContext(), ArrayRef<char>{stringAttr.getValue().data(), 91cb348dffSStephan Herhut stringAttr.getValue().size()}); 92cb348dffSStephan Herhut } 93a4c3a645SRiver Riddle emitError(loc, "unsupported constant value"); 945d7231d8SStephan Herhut return nullptr; 955d7231d8SStephan Herhut } 965d7231d8SStephan Herhut 972666b973SRiver Riddle /// Convert MLIR integer comparison predicate to LLVM IR comparison predicate. 98ec82e1c9SAlex Zinenko static llvm::CmpInst::Predicate getLLVMCmpPredicate(ICmpPredicate p) { 995d7231d8SStephan Herhut switch (p) { 100ec82e1c9SAlex Zinenko case LLVM::ICmpPredicate::eq: 1015d7231d8SStephan Herhut return llvm::CmpInst::Predicate::ICMP_EQ; 102ec82e1c9SAlex Zinenko case LLVM::ICmpPredicate::ne: 1035d7231d8SStephan Herhut return llvm::CmpInst::Predicate::ICMP_NE; 104ec82e1c9SAlex Zinenko case LLVM::ICmpPredicate::slt: 1055d7231d8SStephan Herhut return llvm::CmpInst::Predicate::ICMP_SLT; 106ec82e1c9SAlex Zinenko case LLVM::ICmpPredicate::sle: 1075d7231d8SStephan Herhut return llvm::CmpInst::Predicate::ICMP_SLE; 108ec82e1c9SAlex Zinenko case LLVM::ICmpPredicate::sgt: 1095d7231d8SStephan Herhut return llvm::CmpInst::Predicate::ICMP_SGT; 110ec82e1c9SAlex Zinenko case LLVM::ICmpPredicate::sge: 1115d7231d8SStephan Herhut return llvm::CmpInst::Predicate::ICMP_SGE; 112ec82e1c9SAlex Zinenko case LLVM::ICmpPredicate::ult: 1135d7231d8SStephan Herhut return llvm::CmpInst::Predicate::ICMP_ULT; 114ec82e1c9SAlex Zinenko case LLVM::ICmpPredicate::ule: 1155d7231d8SStephan Herhut return llvm::CmpInst::Predicate::ICMP_ULE; 116ec82e1c9SAlex Zinenko case LLVM::ICmpPredicate::ugt: 1175d7231d8SStephan Herhut return llvm::CmpInst::Predicate::ICMP_UGT; 118ec82e1c9SAlex Zinenko case LLVM::ICmpPredicate::uge: 1195d7231d8SStephan Herhut return llvm::CmpInst::Predicate::ICMP_UGE; 1205d7231d8SStephan Herhut } 121e6365f3dSJacques Pienaar llvm_unreachable("incorrect comparison predicate"); 1225d7231d8SStephan Herhut } 1235d7231d8SStephan Herhut 12448fdc8d7SNagy Mostafa static llvm::CmpInst::Predicate getLLVMCmpPredicate(FCmpPredicate p) { 12548fdc8d7SNagy Mostafa switch (p) { 12648fdc8d7SNagy Mostafa case LLVM::FCmpPredicate::_false: 12748fdc8d7SNagy Mostafa return llvm::CmpInst::Predicate::FCMP_FALSE; 12848fdc8d7SNagy Mostafa case LLVM::FCmpPredicate::oeq: 12948fdc8d7SNagy Mostafa return llvm::CmpInst::Predicate::FCMP_OEQ; 13048fdc8d7SNagy Mostafa case LLVM::FCmpPredicate::ogt: 13148fdc8d7SNagy Mostafa return llvm::CmpInst::Predicate::FCMP_OGT; 13248fdc8d7SNagy Mostafa case LLVM::FCmpPredicate::oge: 13348fdc8d7SNagy Mostafa return llvm::CmpInst::Predicate::FCMP_OGE; 13448fdc8d7SNagy Mostafa case LLVM::FCmpPredicate::olt: 13548fdc8d7SNagy Mostafa return llvm::CmpInst::Predicate::FCMP_OLT; 13648fdc8d7SNagy Mostafa case LLVM::FCmpPredicate::ole: 13748fdc8d7SNagy Mostafa return llvm::CmpInst::Predicate::FCMP_OLE; 13848fdc8d7SNagy Mostafa case LLVM::FCmpPredicate::one: 13948fdc8d7SNagy Mostafa return llvm::CmpInst::Predicate::FCMP_ONE; 14048fdc8d7SNagy Mostafa case LLVM::FCmpPredicate::ord: 14148fdc8d7SNagy Mostafa return llvm::CmpInst::Predicate::FCMP_ORD; 14248fdc8d7SNagy Mostafa case LLVM::FCmpPredicate::ueq: 14348fdc8d7SNagy Mostafa return llvm::CmpInst::Predicate::FCMP_UEQ; 14448fdc8d7SNagy Mostafa case LLVM::FCmpPredicate::ugt: 14548fdc8d7SNagy Mostafa return llvm::CmpInst::Predicate::FCMP_UGT; 14648fdc8d7SNagy Mostafa case LLVM::FCmpPredicate::uge: 14748fdc8d7SNagy Mostafa return llvm::CmpInst::Predicate::FCMP_UGE; 14848fdc8d7SNagy Mostafa case LLVM::FCmpPredicate::ult: 14948fdc8d7SNagy Mostafa return llvm::CmpInst::Predicate::FCMP_ULT; 15048fdc8d7SNagy Mostafa case LLVM::FCmpPredicate::ule: 15148fdc8d7SNagy Mostafa return llvm::CmpInst::Predicate::FCMP_ULE; 15248fdc8d7SNagy Mostafa case LLVM::FCmpPredicate::une: 15348fdc8d7SNagy Mostafa return llvm::CmpInst::Predicate::FCMP_UNE; 15448fdc8d7SNagy Mostafa case LLVM::FCmpPredicate::uno: 15548fdc8d7SNagy Mostafa return llvm::CmpInst::Predicate::FCMP_UNO; 15648fdc8d7SNagy Mostafa case LLVM::FCmpPredicate::_true: 15748fdc8d7SNagy Mostafa return llvm::CmpInst::Predicate::FCMP_TRUE; 15848fdc8d7SNagy Mostafa } 159e6365f3dSJacques Pienaar llvm_unreachable("incorrect comparison predicate"); 16048fdc8d7SNagy Mostafa } 16148fdc8d7SNagy Mostafa 1622666b973SRiver Riddle /// Given a single MLIR operation, create the corresponding LLVM IR operation 1632666b973SRiver Riddle /// using the `builder`. LLVM IR Builder does not have a generic interface so 1642666b973SRiver Riddle /// this has to be a long chain of `if`s calling different functions with a 1652666b973SRiver Riddle /// different number of arguments. 166baa1ec22SAlex Zinenko LogicalResult ModuleTranslation::convertOperation(Operation &opInst, 1675d7231d8SStephan Herhut llvm::IRBuilder<> &builder) { 1685d7231d8SStephan Herhut auto extractPosition = [](ArrayAttr attr) { 1695d7231d8SStephan Herhut SmallVector<unsigned, 4> position; 1705d7231d8SStephan Herhut position.reserve(attr.size()); 1715d7231d8SStephan Herhut for (Attribute v : attr) 1725d7231d8SStephan Herhut position.push_back(v.cast<IntegerAttr>().getValue().getZExtValue()); 1735d7231d8SStephan Herhut return position; 1745d7231d8SStephan Herhut }; 1755d7231d8SStephan Herhut 176ba0fa925SRiver Riddle #include "mlir/Dialect/LLVMIR/LLVMConversions.inc" 1775d7231d8SStephan Herhut 1785d7231d8SStephan Herhut // Emit function calls. If the "callee" attribute is present, this is a 1795d7231d8SStephan Herhut // direct function call and we also need to look up the remapped function 1805d7231d8SStephan Herhut // itself. Otherwise, this is an indirect call and the callee is the first 1815d7231d8SStephan Herhut // operand, look it up as a normal value. Return the llvm::Value representing 1825d7231d8SStephan Herhut // the function result, which may be of llvm::VoidTy type. 1835d7231d8SStephan Herhut auto convertCall = [this, &builder](Operation &op) -> llvm::Value * { 1845d7231d8SStephan Herhut auto operands = lookupValues(op.getOperands()); 1855d7231d8SStephan Herhut ArrayRef<llvm::Value *> operandsRef(operands); 1869b9c647cSRiver Riddle if (auto attr = op.getAttrOfType<FlatSymbolRefAttr>("callee")) { 1875d7231d8SStephan Herhut return builder.CreateCall(functionMapping.lookup(attr.getValue()), 1885d7231d8SStephan Herhut operandsRef); 1895d7231d8SStephan Herhut } else { 1905d7231d8SStephan Herhut return builder.CreateCall(operandsRef.front(), operandsRef.drop_front()); 1915d7231d8SStephan Herhut } 1925d7231d8SStephan Herhut }; 1935d7231d8SStephan Herhut 1945d7231d8SStephan Herhut // Emit calls. If the called function has a result, remap the corresponding 1955d7231d8SStephan Herhut // value. Note that LLVM IR dialect CallOp has either 0 or 1 result. 196d5b60ee8SRiver Riddle if (isa<LLVM::CallOp>(opInst)) { 1975d7231d8SStephan Herhut llvm::Value *result = convertCall(opInst); 1985d7231d8SStephan Herhut if (opInst.getNumResults() != 0) { 1995d7231d8SStephan Herhut valueMapping[opInst.getResult(0)] = result; 200baa1ec22SAlex Zinenko return success(); 2015d7231d8SStephan Herhut } 2025d7231d8SStephan Herhut // Check that LLVM call returns void for 0-result functions. 203baa1ec22SAlex Zinenko return success(result->getType()->isVoidTy()); 2045d7231d8SStephan Herhut } 2055d7231d8SStephan Herhut 2065d7231d8SStephan Herhut // Emit branches. We need to look up the remapped blocks and ignore the block 2075d7231d8SStephan Herhut // arguments that were transformed into PHI nodes. 208c5ecf991SRiver Riddle if (auto brOp = dyn_cast<LLVM::BrOp>(opInst)) { 2095d7231d8SStephan Herhut builder.CreateBr(blockMapping[brOp.getSuccessor(0)]); 210baa1ec22SAlex Zinenko return success(); 2115d7231d8SStephan Herhut } 212c5ecf991SRiver Riddle if (auto condbrOp = dyn_cast<LLVM::CondBrOp>(opInst)) { 2135d7231d8SStephan Herhut builder.CreateCondBr(valueMapping.lookup(condbrOp.getOperand(0)), 2145d7231d8SStephan Herhut blockMapping[condbrOp.getSuccessor(0)], 2155d7231d8SStephan Herhut blockMapping[condbrOp.getSuccessor(1)]); 216baa1ec22SAlex Zinenko return success(); 2175d7231d8SStephan Herhut } 2185d7231d8SStephan Herhut 2192dd38b09SAlex Zinenko // Emit addressof. We need to look up the global value referenced by the 2202dd38b09SAlex Zinenko // operation and store it in the MLIR-to-LLVM value mapping. This does not 2212dd38b09SAlex Zinenko // emit any LLVM instruction. 2222dd38b09SAlex Zinenko if (auto addressOfOp = dyn_cast<LLVM::AddressOfOp>(opInst)) { 2232dd38b09SAlex Zinenko LLVM::GlobalOp global = addressOfOp.getGlobal(); 2242dd38b09SAlex Zinenko // The verifier should not have allowed this. 2252dd38b09SAlex Zinenko assert(global && "referencing an undefined global"); 2262dd38b09SAlex Zinenko 2272dd38b09SAlex Zinenko valueMapping[addressOfOp.getResult()] = globalsMapping.lookup(global); 2282dd38b09SAlex Zinenko return success(); 2292dd38b09SAlex Zinenko } 2302dd38b09SAlex Zinenko 231baa1ec22SAlex Zinenko return opInst.emitError("unsupported or non-LLVM operation: ") 232baa1ec22SAlex Zinenko << opInst.getName(); 2335d7231d8SStephan Herhut } 2345d7231d8SStephan Herhut 2352666b973SRiver Riddle /// Convert block to LLVM IR. Unless `ignoreArguments` is set, emit PHI nodes 2362666b973SRiver Riddle /// to define values corresponding to the MLIR block arguments. These nodes 2372666b973SRiver Riddle /// are not connected to the source basic blocks, which may not exist yet. 238baa1ec22SAlex Zinenko LogicalResult ModuleTranslation::convertBlock(Block &bb, bool ignoreArguments) { 2395d7231d8SStephan Herhut llvm::IRBuilder<> builder(blockMapping[&bb]); 2405d7231d8SStephan Herhut 2415d7231d8SStephan Herhut // Before traversing operations, make block arguments available through 2425d7231d8SStephan Herhut // value remapping and PHI nodes, but do not add incoming edges for the PHI 2435d7231d8SStephan Herhut // nodes just yet: those values may be defined by this or following blocks. 2445d7231d8SStephan Herhut // This step is omitted if "ignoreArguments" is set. The arguments of the 2455d7231d8SStephan Herhut // first block have been already made available through the remapping of 2465d7231d8SStephan Herhut // LLVM function arguments. 2475d7231d8SStephan Herhut if (!ignoreArguments) { 2485d7231d8SStephan Herhut auto predecessors = bb.getPredecessors(); 2495d7231d8SStephan Herhut unsigned numPredecessors = 2505d7231d8SStephan Herhut std::distance(predecessors.begin(), predecessors.end()); 251*35807bc4SRiver Riddle for (auto arg : bb.getArguments()) { 2525d7231d8SStephan Herhut auto wrappedType = arg->getType().dyn_cast<LLVM::LLVMType>(); 253baa1ec22SAlex Zinenko if (!wrappedType) 254baa1ec22SAlex Zinenko return emitError(bb.front().getLoc(), 255a4c3a645SRiver Riddle "block argument does not have an LLVM type"); 2565d7231d8SStephan Herhut llvm::Type *type = wrappedType.getUnderlyingType(); 2575d7231d8SStephan Herhut llvm::PHINode *phi = builder.CreatePHI(type, numPredecessors); 2585d7231d8SStephan Herhut valueMapping[arg] = phi; 2595d7231d8SStephan Herhut } 2605d7231d8SStephan Herhut } 2615d7231d8SStephan Herhut 2625d7231d8SStephan Herhut // Traverse operations. 2635d7231d8SStephan Herhut for (auto &op : bb) { 264baa1ec22SAlex Zinenko if (failed(convertOperation(op, builder))) 265baa1ec22SAlex Zinenko return failure(); 2665d7231d8SStephan Herhut } 2675d7231d8SStephan Herhut 268baa1ec22SAlex Zinenko return success(); 2695d7231d8SStephan Herhut } 2705d7231d8SStephan Herhut 2712666b973SRiver Riddle /// Convert the LLVM dialect linkage type to LLVM IR linkage type. 272d5e627f8SAlex Zinenko llvm::GlobalVariable::LinkageTypes convertLinkageType(LLVM::Linkage linkage) { 273d5e627f8SAlex Zinenko switch (linkage) { 274d5e627f8SAlex Zinenko case LLVM::Linkage::Private: 275d5e627f8SAlex Zinenko return llvm::GlobalValue::PrivateLinkage; 276d5e627f8SAlex Zinenko case LLVM::Linkage::Internal: 277d5e627f8SAlex Zinenko return llvm::GlobalValue::InternalLinkage; 278d5e627f8SAlex Zinenko case LLVM::Linkage::AvailableExternally: 279d5e627f8SAlex Zinenko return llvm::GlobalValue::AvailableExternallyLinkage; 280d5e627f8SAlex Zinenko case LLVM::Linkage::Linkonce: 281d5e627f8SAlex Zinenko return llvm::GlobalValue::LinkOnceAnyLinkage; 282d5e627f8SAlex Zinenko case LLVM::Linkage::Weak: 283d5e627f8SAlex Zinenko return llvm::GlobalValue::WeakAnyLinkage; 284d5e627f8SAlex Zinenko case LLVM::Linkage::Common: 285d5e627f8SAlex Zinenko return llvm::GlobalValue::CommonLinkage; 286d5e627f8SAlex Zinenko case LLVM::Linkage::Appending: 287d5e627f8SAlex Zinenko return llvm::GlobalValue::AppendingLinkage; 288d5e627f8SAlex Zinenko case LLVM::Linkage::ExternWeak: 289d5e627f8SAlex Zinenko return llvm::GlobalValue::ExternalWeakLinkage; 290d5e627f8SAlex Zinenko case LLVM::Linkage::LinkonceODR: 291d5e627f8SAlex Zinenko return llvm::GlobalValue::LinkOnceODRLinkage; 292d5e627f8SAlex Zinenko case LLVM::Linkage::WeakODR: 293d5e627f8SAlex Zinenko return llvm::GlobalValue::WeakODRLinkage; 294d5e627f8SAlex Zinenko case LLVM::Linkage::External: 295d5e627f8SAlex Zinenko return llvm::GlobalValue::ExternalLinkage; 296d5e627f8SAlex Zinenko } 297d5e627f8SAlex Zinenko llvm_unreachable("unknown linkage type"); 298d5e627f8SAlex Zinenko } 299d5e627f8SAlex Zinenko 3002666b973SRiver Riddle /// Create named global variables that correspond to llvm.mlir.global 3012666b973SRiver Riddle /// definitions. 302b9ff2dd8SAlex Zinenko void ModuleTranslation::convertGlobals() { 30344fc7d72STres Popp for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) { 304250a11aeSJames Molloy llvm::Type *type = op.getType().getUnderlyingType(); 305250a11aeSJames Molloy llvm::Constant *cst = llvm::UndefValue::get(type); 306250a11aeSJames Molloy if (op.getValueOrNull()) { 30768451df2SAlex Zinenko // String attributes are treated separately because they cannot appear as 30868451df2SAlex Zinenko // in-function constants and are thus not supported by getLLVMConstant. 30933a3a91bSChristian Sigg if (auto strAttr = op.getValueOrNull().dyn_cast_or_null<StringAttr>()) { 3102dd38b09SAlex Zinenko cst = llvm::ConstantDataArray::getString( 31168451df2SAlex Zinenko llvmModule->getContext(), strAttr.getValue(), /*AddNull=*/false); 3122dd38b09SAlex Zinenko type = cst->getType(); 3132dd38b09SAlex Zinenko } else { 31433a3a91bSChristian Sigg cst = getLLVMConstant(type, op.getValueOrNull(), op.getLoc()); 31568451df2SAlex Zinenko } 316250a11aeSJames Molloy } else if (Block *initializer = op.getInitializerBlock()) { 317250a11aeSJames Molloy llvm::IRBuilder<> builder(llvmModule->getContext()); 318250a11aeSJames Molloy for (auto &op : initializer->without_terminator()) { 319250a11aeSJames Molloy if (failed(convertOperation(op, builder)) || 320250a11aeSJames Molloy !isa<llvm::Constant>(valueMapping.lookup(op.getResult(0)))) { 321250a11aeSJames Molloy emitError(op.getLoc(), "unemittable constant value"); 322250a11aeSJames Molloy return; 323250a11aeSJames Molloy } 324250a11aeSJames Molloy } 325250a11aeSJames Molloy ReturnOp ret = cast<ReturnOp>(initializer->getTerminator()); 326250a11aeSJames Molloy cst = cast<llvm::Constant>(valueMapping.lookup(ret.getOperand(0))); 327250a11aeSJames Molloy } 32868451df2SAlex Zinenko 329d5e627f8SAlex Zinenko auto linkage = convertLinkageType(op.linkage()); 330d5e627f8SAlex Zinenko bool anyExternalLinkage = 331d5e627f8SAlex Zinenko (linkage == llvm::GlobalVariable::ExternalLinkage || 332d5e627f8SAlex Zinenko linkage == llvm::GlobalVariable::ExternalWeakLinkage); 333e79bfefbSMLIR Team auto addrSpace = op.addr_space().getLimitedValue(); 334e79bfefbSMLIR Team auto *var = new llvm::GlobalVariable( 335d5e627f8SAlex Zinenko *llvmModule, type, op.constant(), linkage, 336d5e627f8SAlex Zinenko anyExternalLinkage ? nullptr : cst, op.sym_name(), 337d5e627f8SAlex Zinenko /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal, addrSpace); 338e79bfefbSMLIR Team 3392dd38b09SAlex Zinenko globalsMapping.try_emplace(op, var); 340b9ff2dd8SAlex Zinenko } 341b9ff2dd8SAlex Zinenko } 342b9ff2dd8SAlex Zinenko 3432666b973SRiver Riddle /// Get the SSA value passed to the current block from the terminator operation 3442666b973SRiver Riddle /// of its predecessor. 345*35807bc4SRiver Riddle static ValuePtr getPHISourceValue(Block *current, Block *pred, 3465d7231d8SStephan Herhut unsigned numArguments, unsigned index) { 3475d7231d8SStephan Herhut auto &terminator = *pred->getTerminator(); 348d5b60ee8SRiver Riddle if (isa<LLVM::BrOp>(terminator)) { 3495d7231d8SStephan Herhut return terminator.getOperand(index); 3505d7231d8SStephan Herhut } 3515d7231d8SStephan Herhut 3525d7231d8SStephan Herhut // For conditional branches, we need to check if the current block is reached 3535d7231d8SStephan Herhut // through the "true" or the "false" branch and take the relevant operands. 354c5ecf991SRiver Riddle auto condBranchOp = dyn_cast<LLVM::CondBrOp>(terminator); 3555d7231d8SStephan Herhut assert(condBranchOp && 3565d7231d8SStephan Herhut "only branch operations can be terminators of a block that " 3575d7231d8SStephan Herhut "has successors"); 3585d7231d8SStephan Herhut assert((condBranchOp.getSuccessor(0) != condBranchOp.getSuccessor(1)) && 3595d7231d8SStephan Herhut "successors with arguments in LLVM conditional branches must be " 3605d7231d8SStephan Herhut "different blocks"); 3615d7231d8SStephan Herhut 3625d7231d8SStephan Herhut return condBranchOp.getSuccessor(0) == current 3635d7231d8SStephan Herhut ? terminator.getSuccessorOperand(0, index) 3645d7231d8SStephan Herhut : terminator.getSuccessorOperand(1, index); 3655d7231d8SStephan Herhut } 3665d7231d8SStephan Herhut 3675e7959a3SAlex Zinenko void ModuleTranslation::connectPHINodes(LLVMFuncOp func) { 3685d7231d8SStephan Herhut // Skip the first block, it cannot be branched to and its arguments correspond 3695d7231d8SStephan Herhut // to the arguments of the LLVM function. 3705d7231d8SStephan Herhut for (auto it = std::next(func.begin()), eit = func.end(); it != eit; ++it) { 3715d7231d8SStephan Herhut Block *bb = &*it; 3725d7231d8SStephan Herhut llvm::BasicBlock *llvmBB = blockMapping.lookup(bb); 3735d7231d8SStephan Herhut auto phis = llvmBB->phis(); 3745d7231d8SStephan Herhut auto numArguments = bb->getNumArguments(); 3755d7231d8SStephan Herhut assert(numArguments == std::distance(phis.begin(), phis.end())); 3765d7231d8SStephan Herhut for (auto &numberedPhiNode : llvm::enumerate(phis)) { 3775d7231d8SStephan Herhut auto &phiNode = numberedPhiNode.value(); 3785d7231d8SStephan Herhut unsigned index = numberedPhiNode.index(); 3795d7231d8SStephan Herhut for (auto *pred : bb->getPredecessors()) { 3805d7231d8SStephan Herhut phiNode.addIncoming(valueMapping.lookup(getPHISourceValue( 3815d7231d8SStephan Herhut bb, pred, numArguments, index)), 3825d7231d8SStephan Herhut blockMapping.lookup(pred)); 3835d7231d8SStephan Herhut } 3845d7231d8SStephan Herhut } 3855d7231d8SStephan Herhut } 3865d7231d8SStephan Herhut } 3875d7231d8SStephan Herhut 3885d7231d8SStephan Herhut // TODO(mlir-team): implement an iterative version 3895d7231d8SStephan Herhut static void topologicalSortImpl(llvm::SetVector<Block *> &blocks, Block *b) { 3905d7231d8SStephan Herhut blocks.insert(b); 3915d7231d8SStephan Herhut for (Block *bb : b->getSuccessors()) { 3925d7231d8SStephan Herhut if (blocks.count(bb) == 0) 3935d7231d8SStephan Herhut topologicalSortImpl(blocks, bb); 3945d7231d8SStephan Herhut } 3955d7231d8SStephan Herhut } 3965d7231d8SStephan Herhut 3972666b973SRiver Riddle /// Sort function blocks topologically. 3985e7959a3SAlex Zinenko static llvm::SetVector<Block *> topologicalSort(LLVMFuncOp f) { 3995d7231d8SStephan Herhut // For each blocks that has not been visited yet (i.e. that has no 4005d7231d8SStephan Herhut // predecessors), add it to the list and traverse its successors in DFS 4015d7231d8SStephan Herhut // preorder. 4025d7231d8SStephan Herhut llvm::SetVector<Block *> blocks; 4035d7231d8SStephan Herhut for (Block &b : f.getBlocks()) { 4045d7231d8SStephan Herhut if (blocks.count(&b) == 0) 4055d7231d8SStephan Herhut topologicalSortImpl(blocks, &b); 4065d7231d8SStephan Herhut } 4075d7231d8SStephan Herhut assert(blocks.size() == f.getBlocks().size() && "some blocks are not sorted"); 4085d7231d8SStephan Herhut 4095d7231d8SStephan Herhut return blocks; 4105d7231d8SStephan Herhut } 4115d7231d8SStephan Herhut 4125e7959a3SAlex Zinenko LogicalResult ModuleTranslation::convertOneFunction(LLVMFuncOp func) { 4135d7231d8SStephan Herhut // Clear the block and value mappings, they are only relevant within one 4145d7231d8SStephan Herhut // function. 4155d7231d8SStephan Herhut blockMapping.clear(); 4165d7231d8SStephan Herhut valueMapping.clear(); 417c33862b0SRiver Riddle llvm::Function *llvmFunc = functionMapping.lookup(func.getName()); 4185d7231d8SStephan Herhut // Add function arguments to the value remapping table. 4195d7231d8SStephan Herhut // If there was noalias info then we decorate each argument accordingly. 4205d7231d8SStephan Herhut unsigned int argIdx = 0; 4215d7231d8SStephan Herhut for (const auto &kvp : llvm::zip(func.getArguments(), llvmFunc->args())) { 4225d7231d8SStephan Herhut llvm::Argument &llvmArg = std::get<1>(kvp); 423*35807bc4SRiver Riddle BlockArgumentPtr mlirArg = std::get<0>(kvp); 4245d7231d8SStephan Herhut 4255d7231d8SStephan Herhut if (auto attr = func.getArgAttrOfType<BoolAttr>(argIdx, "llvm.noalias")) { 4265d7231d8SStephan Herhut // NB: Attribute already verified to be boolean, so check if we can indeed 4275d7231d8SStephan Herhut // attach the attribute to this argument, based on its type. 4285d7231d8SStephan Herhut auto argTy = mlirArg->getType().dyn_cast<LLVM::LLVMType>(); 429baa1ec22SAlex Zinenko if (!argTy.getUnderlyingType()->isPointerTy()) 430baa1ec22SAlex Zinenko return func.emitError( 4315d7231d8SStephan Herhut "llvm.noalias attribute attached to LLVM non-pointer argument"); 4325d7231d8SStephan Herhut if (attr.getValue()) 4335d7231d8SStephan Herhut llvmArg.addAttr(llvm::Attribute::AttrKind::NoAlias); 4345d7231d8SStephan Herhut } 4355d7231d8SStephan Herhut valueMapping[mlirArg] = &llvmArg; 4365d7231d8SStephan Herhut argIdx++; 4375d7231d8SStephan Herhut } 4385d7231d8SStephan Herhut 4395d7231d8SStephan Herhut // First, create all blocks so we can jump to them. 4405d7231d8SStephan Herhut llvm::LLVMContext &llvmContext = llvmFunc->getContext(); 4415d7231d8SStephan Herhut for (auto &bb : func) { 4425d7231d8SStephan Herhut auto *llvmBB = llvm::BasicBlock::Create(llvmContext); 4435d7231d8SStephan Herhut llvmBB->insertInto(llvmFunc); 4445d7231d8SStephan Herhut blockMapping[&bb] = llvmBB; 4455d7231d8SStephan Herhut } 4465d7231d8SStephan Herhut 4475d7231d8SStephan Herhut // Then, convert blocks one by one in topological order to ensure defs are 4485d7231d8SStephan Herhut // converted before uses. 4495d7231d8SStephan Herhut auto blocks = topologicalSort(func); 4505d7231d8SStephan Herhut for (auto indexedBB : llvm::enumerate(blocks)) { 4515d7231d8SStephan Herhut auto *bb = indexedBB.value(); 452baa1ec22SAlex Zinenko if (failed(convertBlock(*bb, /*ignoreArguments=*/indexedBB.index() == 0))) 453baa1ec22SAlex Zinenko return failure(); 4545d7231d8SStephan Herhut } 4555d7231d8SStephan Herhut 4565d7231d8SStephan Herhut // Finally, after all blocks have been traversed and values mapped, connect 4575d7231d8SStephan Herhut // the PHI nodes to the results of preceding blocks. 4585d7231d8SStephan Herhut connectPHINodes(func); 459baa1ec22SAlex Zinenko return success(); 4605d7231d8SStephan Herhut } 4615d7231d8SStephan Herhut 46244fc7d72STres Popp LogicalResult ModuleTranslation::checkSupportedModuleOps(Operation *m) { 46344fc7d72STres Popp for (Operation &o : getModuleBody(m).getOperations()) 4644dde19f0SAlex Zinenko if (!isa<LLVM::LLVMFuncOp>(&o) && !isa<LLVM::GlobalOp>(&o) && 46544fc7d72STres Popp !o.isKnownTerminator()) 4664dde19f0SAlex Zinenko return o.emitOpError("unsupported module-level operation"); 4674dde19f0SAlex Zinenko return success(); 4684dde19f0SAlex Zinenko } 4694dde19f0SAlex Zinenko 470baa1ec22SAlex Zinenko LogicalResult ModuleTranslation::convertFunctions() { 4715d7231d8SStephan Herhut // Declare all functions first because there may be function calls that form a 4725d7231d8SStephan Herhut // call graph with cycles. 47344fc7d72STres Popp for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) { 4745e7959a3SAlex Zinenko llvm::FunctionCallee llvmFuncCst = llvmModule->getOrInsertFunction( 4755e7959a3SAlex Zinenko function.getName(), 4764562e389SRiver Riddle cast<llvm::FunctionType>(function.getType().getUnderlyingType())); 4775d7231d8SStephan Herhut assert(isa<llvm::Function>(llvmFuncCst.getCallee())); 478c33862b0SRiver Riddle functionMapping[function.getName()] = 4795d7231d8SStephan Herhut cast<llvm::Function>(llvmFuncCst.getCallee()); 4805d7231d8SStephan Herhut } 4815d7231d8SStephan Herhut 4825d7231d8SStephan Herhut // Convert functions. 48344fc7d72STres Popp for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) { 4845d7231d8SStephan Herhut // Ignore external functions. 4855d7231d8SStephan Herhut if (function.isExternal()) 4865d7231d8SStephan Herhut continue; 4875d7231d8SStephan Herhut 488baa1ec22SAlex Zinenko if (failed(convertOneFunction(function))) 489baa1ec22SAlex Zinenko return failure(); 4905d7231d8SStephan Herhut } 4915d7231d8SStephan Herhut 492baa1ec22SAlex Zinenko return success(); 4935d7231d8SStephan Herhut } 4945d7231d8SStephan Herhut 495efadb6b8SAlex Zinenko /// A helper to look up remapped operands in the value remapping table.` 496efadb6b8SAlex Zinenko SmallVector<llvm::Value *, 8> 497efadb6b8SAlex Zinenko ModuleTranslation::lookupValues(ValueRange values) { 498efadb6b8SAlex Zinenko SmallVector<llvm::Value *, 8> remapped; 499efadb6b8SAlex Zinenko remapped.reserve(values.size()); 500*35807bc4SRiver Riddle for (ValuePtr v : values) 501efadb6b8SAlex Zinenko remapped.push_back(valueMapping.lookup(v)); 502efadb6b8SAlex Zinenko return remapped; 503efadb6b8SAlex Zinenko } 504efadb6b8SAlex Zinenko 50544fc7d72STres Popp std::unique_ptr<llvm::Module> 50644fc7d72STres Popp ModuleTranslation::prepareLLVMModule(Operation *m) { 50744fc7d72STres Popp auto *dialect = m->getContext()->getRegisteredDialect<LLVM::LLVMDialect>(); 5085d7231d8SStephan Herhut assert(dialect && "LLVM dialect must be registered"); 5095d7231d8SStephan Herhut 510bc5c7378SRiver Riddle auto llvmModule = llvm::CloneModule(dialect->getLLVMModule()); 5115d7231d8SStephan Herhut if (!llvmModule) 5125d7231d8SStephan Herhut return nullptr; 5135d7231d8SStephan Herhut 5145d7231d8SStephan Herhut llvm::LLVMContext &llvmContext = llvmModule->getContext(); 5155d7231d8SStephan Herhut llvm::IRBuilder<> builder(llvmContext); 5165d7231d8SStephan Herhut 5175d7231d8SStephan Herhut // Inject declarations for `malloc` and `free` functions that can be used in 5185d7231d8SStephan Herhut // memref allocation/deallocation coming from standard ops lowering. 5195d7231d8SStephan Herhut llvmModule->getOrInsertFunction("malloc", builder.getInt8PtrTy(), 5205d7231d8SStephan Herhut builder.getInt64Ty()); 5215d7231d8SStephan Herhut llvmModule->getOrInsertFunction("free", builder.getVoidTy(), 5225d7231d8SStephan Herhut builder.getInt8PtrTy()); 5235d7231d8SStephan Herhut 5245d7231d8SStephan Herhut return llvmModule; 5255d7231d8SStephan Herhut } 526