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 
395d7231d8SStephan Herhut namespace mlir {
405d7231d8SStephan Herhut namespace LLVM {
415d7231d8SStephan Herhut 
425d7231d8SStephan Herhut // Convert an MLIR function type to LLVM IR.  Arguments of the function must of
435d7231d8SStephan Herhut // MLIR LLVM IR dialect types.  Use `loc` as a location when reporting errors.
445d7231d8SStephan Herhut // Return nullptr on errors.
455d7231d8SStephan Herhut static llvm::FunctionType *convertFunctionType(llvm::LLVMContext &llvmContext,
465d7231d8SStephan Herhut                                                FunctionType type, Location loc,
475d7231d8SStephan Herhut                                                bool isVarArgs) {
485d7231d8SStephan Herhut   assert(type && "expected non-null type");
495d7231d8SStephan Herhut   if (type.getNumResults() > 1)
50a4c3a645SRiver Riddle     return emitError(loc, "LLVM functions can only have 0 or 1 result"),
515d7231d8SStephan Herhut            nullptr;
525d7231d8SStephan Herhut 
535d7231d8SStephan Herhut   SmallVector<llvm::Type *, 8> argTypes;
545d7231d8SStephan Herhut   argTypes.reserve(type.getNumInputs());
555d7231d8SStephan Herhut   for (auto t : type.getInputs()) {
565d7231d8SStephan Herhut     auto wrappedLLVMType = t.dyn_cast<LLVM::LLVMType>();
575d7231d8SStephan Herhut     if (!wrappedLLVMType)
58a4c3a645SRiver Riddle       return emitError(loc, "non-LLVM function argument type"), nullptr;
595d7231d8SStephan Herhut     argTypes.push_back(wrappedLLVMType.getUnderlyingType());
605d7231d8SStephan Herhut   }
615d7231d8SStephan Herhut 
625d7231d8SStephan Herhut   if (type.getNumResults() == 0)
635d7231d8SStephan Herhut     return llvm::FunctionType::get(llvm::Type::getVoidTy(llvmContext), argTypes,
645d7231d8SStephan Herhut                                    isVarArgs);
655d7231d8SStephan Herhut 
665d7231d8SStephan Herhut   auto wrappedResultType = type.getResult(0).dyn_cast<LLVM::LLVMType>();
675d7231d8SStephan Herhut   if (!wrappedResultType)
68a4c3a645SRiver Riddle     return emitError(loc, "non-LLVM function result"), nullptr;
695d7231d8SStephan Herhut 
705d7231d8SStephan Herhut   return llvm::FunctionType::get(wrappedResultType.getUnderlyingType(),
715d7231d8SStephan Herhut                                  argTypes, isVarArgs);
725d7231d8SStephan Herhut }
735d7231d8SStephan Herhut 
745d7231d8SStephan Herhut // Create an LLVM IR constant of `llvmType` from the MLIR attribute `attr`.
755d7231d8SStephan Herhut // This currently supports integer, floating point, splat and dense element
765d7231d8SStephan Herhut // attributes and combinations thereof.  In case of error, report it to `loc`
775d7231d8SStephan Herhut // and return nullptr.
785d7231d8SStephan Herhut llvm::Constant *ModuleTranslation::getLLVMConstant(llvm::Type *llvmType,
795d7231d8SStephan Herhut                                                    Attribute attr,
805d7231d8SStephan Herhut                                                    Location loc) {
815d7231d8SStephan Herhut   if (auto intAttr = attr.dyn_cast<IntegerAttr>())
825d7231d8SStephan Herhut     return llvm::ConstantInt::get(llvmType, intAttr.getValue());
835d7231d8SStephan Herhut   if (auto floatAttr = attr.dyn_cast<FloatAttr>())
845d7231d8SStephan Herhut     return llvm::ConstantFP::get(llvmType, floatAttr.getValue());
859dbef0bfSRiver Riddle   if (auto funcAttr = attr.dyn_cast<SymbolRefAttr>())
865d7231d8SStephan Herhut     return functionMapping.lookup(funcAttr.getValue());
875d7231d8SStephan Herhut   if (auto splatAttr = attr.dyn_cast<SplatElementsAttr>()) {
882f13df13SMLIR Team     auto *sequentialType = cast<llvm::SequentialType>(llvmType);
892f13df13SMLIR Team     auto elementType = sequentialType->getElementType();
902f13df13SMLIR Team     uint64_t numElements = sequentialType->getNumElements();
912f13df13SMLIR Team     auto *child = getLLVMConstant(elementType, splatAttr.getSplatValue(), loc);
922f13df13SMLIR Team     if (llvmType->isVectorTy())
932f13df13SMLIR Team       return llvm::ConstantVector::getSplat(numElements, child);
942f13df13SMLIR Team     if (llvmType->isArrayTy()) {
952f13df13SMLIR Team       auto arrayType = llvm::ArrayType::get(elementType, numElements);
962f13df13SMLIR Team       SmallVector<llvm::Constant *, 8> constants(numElements, child);
972f13df13SMLIR Team       return llvm::ConstantArray::get(arrayType, constants);
982f13df13SMLIR Team     }
995d7231d8SStephan Herhut   }
100d906f84bSRiver Riddle   if (auto elementsAttr = attr.dyn_cast<ElementsAttr>()) {
1012f13df13SMLIR Team     auto *sequentialType = cast<llvm::SequentialType>(llvmType);
1022f13df13SMLIR Team     auto elementType = sequentialType->getElementType();
1032f13df13SMLIR Team     uint64_t numElements = sequentialType->getNumElements();
1045d7231d8SStephan Herhut     SmallVector<llvm::Constant *, 8> constants;
1055d7231d8SStephan Herhut     constants.reserve(numElements);
106d906f84bSRiver Riddle     for (auto n : elementsAttr.getValues<Attribute>()) {
1072f13df13SMLIR Team       constants.push_back(getLLVMConstant(elementType, n, loc));
1085d7231d8SStephan Herhut       if (!constants.back())
1095d7231d8SStephan Herhut         return nullptr;
1105d7231d8SStephan Herhut     }
1112f13df13SMLIR Team     if (llvmType->isVectorTy())
1125d7231d8SStephan Herhut       return llvm::ConstantVector::get(constants);
1132f13df13SMLIR Team     if (llvmType->isArrayTy()) {
1142f13df13SMLIR Team       auto arrayType = llvm::ArrayType::get(elementType, numElements);
1152f13df13SMLIR Team       return llvm::ConstantArray::get(arrayType, constants);
1162f13df13SMLIR Team     }
1175d7231d8SStephan Herhut   }
118cb348dffSStephan Herhut   if (auto stringAttr = attr.dyn_cast<StringAttr>()) {
119cb348dffSStephan Herhut     return llvm::ConstantDataArray::get(
120cb348dffSStephan Herhut         llvmModule->getContext(), ArrayRef<char>{stringAttr.getValue().data(),
121cb348dffSStephan Herhut                                                  stringAttr.getValue().size()});
122cb348dffSStephan Herhut   }
123a4c3a645SRiver Riddle   emitError(loc, "unsupported constant value");
1245d7231d8SStephan Herhut   return nullptr;
1255d7231d8SStephan Herhut }
1265d7231d8SStephan Herhut 
1275d7231d8SStephan Herhut // Convert MLIR integer comparison predicate to LLVM IR comparison predicate.
128ec82e1c9SAlex Zinenko static llvm::CmpInst::Predicate getLLVMCmpPredicate(ICmpPredicate p) {
1295d7231d8SStephan Herhut   switch (p) {
130ec82e1c9SAlex Zinenko   case LLVM::ICmpPredicate::eq:
1315d7231d8SStephan Herhut     return llvm::CmpInst::Predicate::ICMP_EQ;
132ec82e1c9SAlex Zinenko   case LLVM::ICmpPredicate::ne:
1335d7231d8SStephan Herhut     return llvm::CmpInst::Predicate::ICMP_NE;
134ec82e1c9SAlex Zinenko   case LLVM::ICmpPredicate::slt:
1355d7231d8SStephan Herhut     return llvm::CmpInst::Predicate::ICMP_SLT;
136ec82e1c9SAlex Zinenko   case LLVM::ICmpPredicate::sle:
1375d7231d8SStephan Herhut     return llvm::CmpInst::Predicate::ICMP_SLE;
138ec82e1c9SAlex Zinenko   case LLVM::ICmpPredicate::sgt:
1395d7231d8SStephan Herhut     return llvm::CmpInst::Predicate::ICMP_SGT;
140ec82e1c9SAlex Zinenko   case LLVM::ICmpPredicate::sge:
1415d7231d8SStephan Herhut     return llvm::CmpInst::Predicate::ICMP_SGE;
142ec82e1c9SAlex Zinenko   case LLVM::ICmpPredicate::ult:
1435d7231d8SStephan Herhut     return llvm::CmpInst::Predicate::ICMP_ULT;
144ec82e1c9SAlex Zinenko   case LLVM::ICmpPredicate::ule:
1455d7231d8SStephan Herhut     return llvm::CmpInst::Predicate::ICMP_ULE;
146ec82e1c9SAlex Zinenko   case LLVM::ICmpPredicate::ugt:
1475d7231d8SStephan Herhut     return llvm::CmpInst::Predicate::ICMP_UGT;
148ec82e1c9SAlex Zinenko   case LLVM::ICmpPredicate::uge:
1495d7231d8SStephan Herhut     return llvm::CmpInst::Predicate::ICMP_UGE;
1505d7231d8SStephan Herhut   }
151e6365f3dSJacques Pienaar   llvm_unreachable("incorrect comparison predicate");
1525d7231d8SStephan Herhut }
1535d7231d8SStephan Herhut 
15448fdc8d7SNagy Mostafa static llvm::CmpInst::Predicate getLLVMCmpPredicate(FCmpPredicate p) {
15548fdc8d7SNagy Mostafa   switch (p) {
15648fdc8d7SNagy Mostafa   case LLVM::FCmpPredicate::_false:
15748fdc8d7SNagy Mostafa     return llvm::CmpInst::Predicate::FCMP_FALSE;
15848fdc8d7SNagy Mostafa   case LLVM::FCmpPredicate::oeq:
15948fdc8d7SNagy Mostafa     return llvm::CmpInst::Predicate::FCMP_OEQ;
16048fdc8d7SNagy Mostafa   case LLVM::FCmpPredicate::ogt:
16148fdc8d7SNagy Mostafa     return llvm::CmpInst::Predicate::FCMP_OGT;
16248fdc8d7SNagy Mostafa   case LLVM::FCmpPredicate::oge:
16348fdc8d7SNagy Mostafa     return llvm::CmpInst::Predicate::FCMP_OGE;
16448fdc8d7SNagy Mostafa   case LLVM::FCmpPredicate::olt:
16548fdc8d7SNagy Mostafa     return llvm::CmpInst::Predicate::FCMP_OLT;
16648fdc8d7SNagy Mostafa   case LLVM::FCmpPredicate::ole:
16748fdc8d7SNagy Mostafa     return llvm::CmpInst::Predicate::FCMP_OLE;
16848fdc8d7SNagy Mostafa   case LLVM::FCmpPredicate::one:
16948fdc8d7SNagy Mostafa     return llvm::CmpInst::Predicate::FCMP_ONE;
17048fdc8d7SNagy Mostafa   case LLVM::FCmpPredicate::ord:
17148fdc8d7SNagy Mostafa     return llvm::CmpInst::Predicate::FCMP_ORD;
17248fdc8d7SNagy Mostafa   case LLVM::FCmpPredicate::ueq:
17348fdc8d7SNagy Mostafa     return llvm::CmpInst::Predicate::FCMP_UEQ;
17448fdc8d7SNagy Mostafa   case LLVM::FCmpPredicate::ugt:
17548fdc8d7SNagy Mostafa     return llvm::CmpInst::Predicate::FCMP_UGT;
17648fdc8d7SNagy Mostafa   case LLVM::FCmpPredicate::uge:
17748fdc8d7SNagy Mostafa     return llvm::CmpInst::Predicate::FCMP_UGE;
17848fdc8d7SNagy Mostafa   case LLVM::FCmpPredicate::ult:
17948fdc8d7SNagy Mostafa     return llvm::CmpInst::Predicate::FCMP_ULT;
18048fdc8d7SNagy Mostafa   case LLVM::FCmpPredicate::ule:
18148fdc8d7SNagy Mostafa     return llvm::CmpInst::Predicate::FCMP_ULE;
18248fdc8d7SNagy Mostafa   case LLVM::FCmpPredicate::une:
18348fdc8d7SNagy Mostafa     return llvm::CmpInst::Predicate::FCMP_UNE;
18448fdc8d7SNagy Mostafa   case LLVM::FCmpPredicate::uno:
18548fdc8d7SNagy Mostafa     return llvm::CmpInst::Predicate::FCMP_UNO;
18648fdc8d7SNagy Mostafa   case LLVM::FCmpPredicate::_true:
18748fdc8d7SNagy Mostafa     return llvm::CmpInst::Predicate::FCMP_TRUE;
18848fdc8d7SNagy Mostafa   }
189e6365f3dSJacques Pienaar   llvm_unreachable("incorrect comparison predicate");
19048fdc8d7SNagy Mostafa }
19148fdc8d7SNagy Mostafa 
1925d7231d8SStephan Herhut // A helper to look up remapped operands in the value remapping table.
1935d7231d8SStephan Herhut template <typename Range>
1945d7231d8SStephan Herhut SmallVector<llvm::Value *, 8> ModuleTranslation::lookupValues(Range &&values) {
1955d7231d8SStephan Herhut   SmallVector<llvm::Value *, 8> remapped;
1965d7231d8SStephan Herhut   remapped.reserve(llvm::size(values));
1975d7231d8SStephan Herhut   for (Value *v : values) {
1985d7231d8SStephan Herhut     remapped.push_back(valueMapping.lookup(v));
1995d7231d8SStephan Herhut   }
2005d7231d8SStephan Herhut   return remapped;
2015d7231d8SStephan Herhut }
2025d7231d8SStephan Herhut 
2035d7231d8SStephan Herhut // Given a single MLIR operation, create the corresponding LLVM IR operation
2045d7231d8SStephan Herhut // using the `builder`.  LLVM IR Builder does not have a generic interface so
2055d7231d8SStephan Herhut // this has to be a long chain of `if`s calling different functions with a
2065d7231d8SStephan Herhut // different number of arguments.
207baa1ec22SAlex Zinenko LogicalResult ModuleTranslation::convertOperation(Operation &opInst,
2085d7231d8SStephan Herhut                                                   llvm::IRBuilder<> &builder) {
2095d7231d8SStephan Herhut   auto extractPosition = [](ArrayAttr attr) {
2105d7231d8SStephan Herhut     SmallVector<unsigned, 4> position;
2115d7231d8SStephan Herhut     position.reserve(attr.size());
2125d7231d8SStephan Herhut     for (Attribute v : attr)
2135d7231d8SStephan Herhut       position.push_back(v.cast<IntegerAttr>().getValue().getZExtValue());
2145d7231d8SStephan Herhut     return position;
2155d7231d8SStephan Herhut   };
2165d7231d8SStephan Herhut 
217ba0fa925SRiver Riddle #include "mlir/Dialect/LLVMIR/LLVMConversions.inc"
2185d7231d8SStephan Herhut 
2195d7231d8SStephan Herhut   // Emit function calls.  If the "callee" attribute is present, this is a
2205d7231d8SStephan Herhut   // direct function call and we also need to look up the remapped function
2215d7231d8SStephan Herhut   // itself.  Otherwise, this is an indirect call and the callee is the first
2225d7231d8SStephan Herhut   // operand, look it up as a normal value.  Return the llvm::Value representing
2235d7231d8SStephan Herhut   // the function result, which may be of llvm::VoidTy type.
2245d7231d8SStephan Herhut   auto convertCall = [this, &builder](Operation &op) -> llvm::Value * {
2255d7231d8SStephan Herhut     auto operands = lookupValues(op.getOperands());
2265d7231d8SStephan Herhut     ArrayRef<llvm::Value *> operandsRef(operands);
2279dbef0bfSRiver Riddle     if (auto attr = op.getAttrOfType<SymbolRefAttr>("callee")) {
2285d7231d8SStephan Herhut       return builder.CreateCall(functionMapping.lookup(attr.getValue()),
2295d7231d8SStephan Herhut                                 operandsRef);
2305d7231d8SStephan Herhut     } else {
2315d7231d8SStephan Herhut       return builder.CreateCall(operandsRef.front(), operandsRef.drop_front());
2325d7231d8SStephan Herhut     }
2335d7231d8SStephan Herhut   };
2345d7231d8SStephan Herhut 
2355d7231d8SStephan Herhut   // Emit calls.  If the called function has a result, remap the corresponding
2365d7231d8SStephan Herhut   // value.  Note that LLVM IR dialect CallOp has either 0 or 1 result.
237d5b60ee8SRiver Riddle   if (isa<LLVM::CallOp>(opInst)) {
2385d7231d8SStephan Herhut     llvm::Value *result = convertCall(opInst);
2395d7231d8SStephan Herhut     if (opInst.getNumResults() != 0) {
2405d7231d8SStephan Herhut       valueMapping[opInst.getResult(0)] = result;
241baa1ec22SAlex Zinenko       return success();
2425d7231d8SStephan Herhut     }
2435d7231d8SStephan Herhut     // Check that LLVM call returns void for 0-result functions.
244baa1ec22SAlex Zinenko     return success(result->getType()->isVoidTy());
2455d7231d8SStephan Herhut   }
2465d7231d8SStephan Herhut 
2475d7231d8SStephan Herhut   // Emit branches.  We need to look up the remapped blocks and ignore the block
2485d7231d8SStephan Herhut   // arguments that were transformed into PHI nodes.
249c5ecf991SRiver Riddle   if (auto brOp = dyn_cast<LLVM::BrOp>(opInst)) {
2505d7231d8SStephan Herhut     builder.CreateBr(blockMapping[brOp.getSuccessor(0)]);
251baa1ec22SAlex Zinenko     return success();
2525d7231d8SStephan Herhut   }
253c5ecf991SRiver Riddle   if (auto condbrOp = dyn_cast<LLVM::CondBrOp>(opInst)) {
2545d7231d8SStephan Herhut     builder.CreateCondBr(valueMapping.lookup(condbrOp.getOperand(0)),
2555d7231d8SStephan Herhut                          blockMapping[condbrOp.getSuccessor(0)],
2565d7231d8SStephan Herhut                          blockMapping[condbrOp.getSuccessor(1)]);
257baa1ec22SAlex Zinenko     return success();
2585d7231d8SStephan Herhut   }
2595d7231d8SStephan Herhut 
2602dd38b09SAlex Zinenko   // Emit addressof.  We need to look up the global value referenced by the
2612dd38b09SAlex Zinenko   // operation and store it in the MLIR-to-LLVM value mapping.  This does not
2622dd38b09SAlex Zinenko   // emit any LLVM instruction.
2632dd38b09SAlex Zinenko   if (auto addressOfOp = dyn_cast<LLVM::AddressOfOp>(opInst)) {
2642dd38b09SAlex Zinenko     LLVM::GlobalOp global = addressOfOp.getGlobal();
2652dd38b09SAlex Zinenko     // The verifier should not have allowed this.
2662dd38b09SAlex Zinenko     assert(global && "referencing an undefined global");
2672dd38b09SAlex Zinenko 
2682dd38b09SAlex Zinenko     valueMapping[addressOfOp.getResult()] = globalsMapping.lookup(global);
2692dd38b09SAlex Zinenko     return success();
2702dd38b09SAlex Zinenko   }
2712dd38b09SAlex Zinenko 
272baa1ec22SAlex Zinenko   return opInst.emitError("unsupported or non-LLVM operation: ")
273baa1ec22SAlex Zinenko          << opInst.getName();
2745d7231d8SStephan Herhut }
2755d7231d8SStephan Herhut 
2765d7231d8SStephan Herhut // Convert block to LLVM IR.  Unless `ignoreArguments` is set, emit PHI nodes
2775d7231d8SStephan Herhut // to define values corresponding to the MLIR block arguments.  These nodes
2785d7231d8SStephan Herhut // are not connected to the source basic blocks, which may not exist yet.
279baa1ec22SAlex Zinenko LogicalResult ModuleTranslation::convertBlock(Block &bb, bool ignoreArguments) {
2805d7231d8SStephan Herhut   llvm::IRBuilder<> builder(blockMapping[&bb]);
2815d7231d8SStephan Herhut 
2825d7231d8SStephan Herhut   // Before traversing operations, make block arguments available through
2835d7231d8SStephan Herhut   // value remapping and PHI nodes, but do not add incoming edges for the PHI
2845d7231d8SStephan Herhut   // nodes just yet: those values may be defined by this or following blocks.
2855d7231d8SStephan Herhut   // This step is omitted if "ignoreArguments" is set.  The arguments of the
2865d7231d8SStephan Herhut   // first block have been already made available through the remapping of
2875d7231d8SStephan Herhut   // LLVM function arguments.
2885d7231d8SStephan Herhut   if (!ignoreArguments) {
2895d7231d8SStephan Herhut     auto predecessors = bb.getPredecessors();
2905d7231d8SStephan Herhut     unsigned numPredecessors =
2915d7231d8SStephan Herhut         std::distance(predecessors.begin(), predecessors.end());
2925d7231d8SStephan Herhut     for (auto *arg : bb.getArguments()) {
2935d7231d8SStephan Herhut       auto wrappedType = arg->getType().dyn_cast<LLVM::LLVMType>();
294baa1ec22SAlex Zinenko       if (!wrappedType)
295baa1ec22SAlex Zinenko         return emitError(bb.front().getLoc(),
296a4c3a645SRiver Riddle                          "block argument does not have an LLVM type");
2975d7231d8SStephan Herhut       llvm::Type *type = wrappedType.getUnderlyingType();
2985d7231d8SStephan Herhut       llvm::PHINode *phi = builder.CreatePHI(type, numPredecessors);
2995d7231d8SStephan Herhut       valueMapping[arg] = phi;
3005d7231d8SStephan Herhut     }
3015d7231d8SStephan Herhut   }
3025d7231d8SStephan Herhut 
3035d7231d8SStephan Herhut   // Traverse operations.
3045d7231d8SStephan Herhut   for (auto &op : bb) {
305baa1ec22SAlex Zinenko     if (failed(convertOperation(op, builder)))
306baa1ec22SAlex Zinenko       return failure();
3075d7231d8SStephan Herhut   }
3085d7231d8SStephan Herhut 
309baa1ec22SAlex Zinenko   return success();
3105d7231d8SStephan Herhut }
3115d7231d8SStephan Herhut 
312c335d9d3SAlex Zinenko // Create named global variables that correspond to llvm.mlir.global
313c335d9d3SAlex Zinenko // definitions.
314b9ff2dd8SAlex Zinenko void ModuleTranslation::convertGlobals() {
315b9ff2dd8SAlex Zinenko   for (auto op : mlirModule.getOps<LLVM::GlobalOp>()) {
3162dd38b09SAlex Zinenko     llvm::Constant *cst;
3172dd38b09SAlex Zinenko     llvm::Type *type;
31868451df2SAlex Zinenko     // String attributes are treated separately because they cannot appear as
31968451df2SAlex Zinenko     // in-function constants and are thus not supported by getLLVMConstant.
32068451df2SAlex Zinenko     if (auto strAttr = op.value().dyn_cast<StringAttr>()) {
3212dd38b09SAlex Zinenko       cst = llvm::ConstantDataArray::getString(
32268451df2SAlex Zinenko           llvmModule->getContext(), strAttr.getValue(), /*AddNull=*/false);
3232dd38b09SAlex Zinenko       type = cst->getType();
3242dd38b09SAlex Zinenko     } else {
3252dd38b09SAlex Zinenko       type = op.getType().getUnderlyingType();
3262dd38b09SAlex Zinenko       cst = getLLVMConstant(type, op.value(), op.getLoc());
32768451df2SAlex Zinenko     }
32868451df2SAlex Zinenko 
329*e79bfefbSMLIR Team     auto addrSpace = op.addr_space().getLimitedValue();
330*e79bfefbSMLIR Team     auto *var = new llvm::GlobalVariable(
331*e79bfefbSMLIR Team         *llvmModule, type, op.constant(), llvm::GlobalValue::InternalLinkage,
332*e79bfefbSMLIR Team         cst, op.sym_name(), /*InsertBefore=*/nullptr,
333*e79bfefbSMLIR Team         llvm::GlobalValue::NotThreadLocal, addrSpace);
334*e79bfefbSMLIR Team 
3352dd38b09SAlex Zinenko     globalsMapping.try_emplace(op, var);
336b9ff2dd8SAlex Zinenko   }
337b9ff2dd8SAlex Zinenko }
338b9ff2dd8SAlex Zinenko 
3395d7231d8SStephan Herhut // Get the SSA value passed to the current block from the terminator operation
3405d7231d8SStephan Herhut // of its predecessor.
3415d7231d8SStephan Herhut static Value *getPHISourceValue(Block *current, Block *pred,
3425d7231d8SStephan Herhut                                 unsigned numArguments, unsigned index) {
3435d7231d8SStephan Herhut   auto &terminator = *pred->getTerminator();
344d5b60ee8SRiver Riddle   if (isa<LLVM::BrOp>(terminator)) {
3455d7231d8SStephan Herhut     return terminator.getOperand(index);
3465d7231d8SStephan Herhut   }
3475d7231d8SStephan Herhut 
3485d7231d8SStephan Herhut   // For conditional branches, we need to check if the current block is reached
3495d7231d8SStephan Herhut   // through the "true" or the "false" branch and take the relevant operands.
350c5ecf991SRiver Riddle   auto condBranchOp = dyn_cast<LLVM::CondBrOp>(terminator);
3515d7231d8SStephan Herhut   assert(condBranchOp &&
3525d7231d8SStephan Herhut          "only branch operations can be terminators of a block that "
3535d7231d8SStephan Herhut          "has successors");
3545d7231d8SStephan Herhut   assert((condBranchOp.getSuccessor(0) != condBranchOp.getSuccessor(1)) &&
3555d7231d8SStephan Herhut          "successors with arguments in LLVM conditional branches must be "
3565d7231d8SStephan Herhut          "different blocks");
3575d7231d8SStephan Herhut 
3585d7231d8SStephan Herhut   return condBranchOp.getSuccessor(0) == current
3595d7231d8SStephan Herhut              ? terminator.getSuccessorOperand(0, index)
3605d7231d8SStephan Herhut              : terminator.getSuccessorOperand(1, index);
3615d7231d8SStephan Herhut }
3625d7231d8SStephan Herhut 
3638c443678SRiver Riddle void ModuleTranslation::connectPHINodes(FuncOp func) {
3645d7231d8SStephan Herhut   // Skip the first block, it cannot be branched to and its arguments correspond
3655d7231d8SStephan Herhut   // to the arguments of the LLVM function.
3665d7231d8SStephan Herhut   for (auto it = std::next(func.begin()), eit = func.end(); it != eit; ++it) {
3675d7231d8SStephan Herhut     Block *bb = &*it;
3685d7231d8SStephan Herhut     llvm::BasicBlock *llvmBB = blockMapping.lookup(bb);
3695d7231d8SStephan Herhut     auto phis = llvmBB->phis();
3705d7231d8SStephan Herhut     auto numArguments = bb->getNumArguments();
3715d7231d8SStephan Herhut     assert(numArguments == std::distance(phis.begin(), phis.end()));
3725d7231d8SStephan Herhut     for (auto &numberedPhiNode : llvm::enumerate(phis)) {
3735d7231d8SStephan Herhut       auto &phiNode = numberedPhiNode.value();
3745d7231d8SStephan Herhut       unsigned index = numberedPhiNode.index();
3755d7231d8SStephan Herhut       for (auto *pred : bb->getPredecessors()) {
3765d7231d8SStephan Herhut         phiNode.addIncoming(valueMapping.lookup(getPHISourceValue(
3775d7231d8SStephan Herhut                                 bb, pred, numArguments, index)),
3785d7231d8SStephan Herhut                             blockMapping.lookup(pred));
3795d7231d8SStephan Herhut       }
3805d7231d8SStephan Herhut     }
3815d7231d8SStephan Herhut   }
3825d7231d8SStephan Herhut }
3835d7231d8SStephan Herhut 
3845d7231d8SStephan Herhut // TODO(mlir-team): implement an iterative version
3855d7231d8SStephan Herhut static void topologicalSortImpl(llvm::SetVector<Block *> &blocks, Block *b) {
3865d7231d8SStephan Herhut   blocks.insert(b);
3875d7231d8SStephan Herhut   for (Block *bb : b->getSuccessors()) {
3885d7231d8SStephan Herhut     if (blocks.count(bb) == 0)
3895d7231d8SStephan Herhut       topologicalSortImpl(blocks, bb);
3905d7231d8SStephan Herhut   }
3915d7231d8SStephan Herhut }
3925d7231d8SStephan Herhut 
3935d7231d8SStephan Herhut // Sort function blocks topologically.
3948c443678SRiver Riddle static llvm::SetVector<Block *> topologicalSort(FuncOp f) {
3955d7231d8SStephan Herhut   // For each blocks that has not been visited yet (i.e. that has no
3965d7231d8SStephan Herhut   // predecessors), add it to the list and traverse its successors in DFS
3975d7231d8SStephan Herhut   // preorder.
3985d7231d8SStephan Herhut   llvm::SetVector<Block *> blocks;
3995d7231d8SStephan Herhut   for (Block &b : f.getBlocks()) {
4005d7231d8SStephan Herhut     if (blocks.count(&b) == 0)
4015d7231d8SStephan Herhut       topologicalSortImpl(blocks, &b);
4025d7231d8SStephan Herhut   }
4035d7231d8SStephan Herhut   assert(blocks.size() == f.getBlocks().size() && "some blocks are not sorted");
4045d7231d8SStephan Herhut 
4055d7231d8SStephan Herhut   return blocks;
4065d7231d8SStephan Herhut }
4075d7231d8SStephan Herhut 
408baa1ec22SAlex Zinenko LogicalResult ModuleTranslation::convertOneFunction(FuncOp func) {
4095d7231d8SStephan Herhut   // Clear the block and value mappings, they are only relevant within one
4105d7231d8SStephan Herhut   // function.
4115d7231d8SStephan Herhut   blockMapping.clear();
4125d7231d8SStephan Herhut   valueMapping.clear();
413c33862b0SRiver Riddle   llvm::Function *llvmFunc = functionMapping.lookup(func.getName());
4145d7231d8SStephan Herhut   // Add function arguments to the value remapping table.
4155d7231d8SStephan Herhut   // If there was noalias info then we decorate each argument accordingly.
4165d7231d8SStephan Herhut   unsigned int argIdx = 0;
4175d7231d8SStephan Herhut   for (const auto &kvp : llvm::zip(func.getArguments(), llvmFunc->args())) {
4185d7231d8SStephan Herhut     llvm::Argument &llvmArg = std::get<1>(kvp);
4195d7231d8SStephan Herhut     BlockArgument *mlirArg = std::get<0>(kvp);
4205d7231d8SStephan Herhut 
4215d7231d8SStephan Herhut     if (auto attr = func.getArgAttrOfType<BoolAttr>(argIdx, "llvm.noalias")) {
4225d7231d8SStephan Herhut       // NB: Attribute already verified to be boolean, so check if we can indeed
4235d7231d8SStephan Herhut       // attach the attribute to this argument, based on its type.
4245d7231d8SStephan Herhut       auto argTy = mlirArg->getType().dyn_cast<LLVM::LLVMType>();
425baa1ec22SAlex Zinenko       if (!argTy.getUnderlyingType()->isPointerTy())
426baa1ec22SAlex Zinenko         return func.emitError(
4275d7231d8SStephan Herhut             "llvm.noalias attribute attached to LLVM non-pointer argument");
4285d7231d8SStephan Herhut       if (attr.getValue())
4295d7231d8SStephan Herhut         llvmArg.addAttr(llvm::Attribute::AttrKind::NoAlias);
4305d7231d8SStephan Herhut     }
4315d7231d8SStephan Herhut     valueMapping[mlirArg] = &llvmArg;
4325d7231d8SStephan Herhut     argIdx++;
4335d7231d8SStephan Herhut   }
4345d7231d8SStephan Herhut 
4355d7231d8SStephan Herhut   // First, create all blocks so we can jump to them.
4365d7231d8SStephan Herhut   llvm::LLVMContext &llvmContext = llvmFunc->getContext();
4375d7231d8SStephan Herhut   for (auto &bb : func) {
4385d7231d8SStephan Herhut     auto *llvmBB = llvm::BasicBlock::Create(llvmContext);
4395d7231d8SStephan Herhut     llvmBB->insertInto(llvmFunc);
4405d7231d8SStephan Herhut     blockMapping[&bb] = llvmBB;
4415d7231d8SStephan Herhut   }
4425d7231d8SStephan Herhut 
4435d7231d8SStephan Herhut   // Then, convert blocks one by one in topological order to ensure defs are
4445d7231d8SStephan Herhut   // converted before uses.
4455d7231d8SStephan Herhut   auto blocks = topologicalSort(func);
4465d7231d8SStephan Herhut   for (auto indexedBB : llvm::enumerate(blocks)) {
4475d7231d8SStephan Herhut     auto *bb = indexedBB.value();
448baa1ec22SAlex Zinenko     if (failed(convertBlock(*bb, /*ignoreArguments=*/indexedBB.index() == 0)))
449baa1ec22SAlex Zinenko       return failure();
4505d7231d8SStephan Herhut   }
4515d7231d8SStephan Herhut 
4525d7231d8SStephan Herhut   // Finally, after all blocks have been traversed and values mapped, connect
4535d7231d8SStephan Herhut   // the PHI nodes to the results of preceding blocks.
4545d7231d8SStephan Herhut   connectPHINodes(func);
455baa1ec22SAlex Zinenko   return success();
4565d7231d8SStephan Herhut }
4575d7231d8SStephan Herhut 
458baa1ec22SAlex Zinenko LogicalResult ModuleTranslation::convertFunctions() {
4595d7231d8SStephan Herhut   // Declare all functions first because there may be function calls that form a
4605d7231d8SStephan Herhut   // call graph with cycles.
4618c443678SRiver Riddle   for (FuncOp function : mlirModule.getOps<FuncOp>()) {
4625d7231d8SStephan Herhut     mlir::BoolAttr isVarArgsAttr =
4635d7231d8SStephan Herhut         function.getAttrOfType<BoolAttr>("std.varargs");
4645d7231d8SStephan Herhut     bool isVarArgs = isVarArgsAttr && isVarArgsAttr.getValue();
4655d7231d8SStephan Herhut     llvm::FunctionType *functionType =
4665d7231d8SStephan Herhut         convertFunctionType(llvmModule->getContext(), function.getType(),
4675d7231d8SStephan Herhut                             function.getLoc(), isVarArgs);
4685d7231d8SStephan Herhut     if (!functionType)
469baa1ec22SAlex Zinenko       return failure();
4705d7231d8SStephan Herhut     llvm::FunctionCallee llvmFuncCst =
4715d7231d8SStephan Herhut         llvmModule->getOrInsertFunction(function.getName(), functionType);
4725d7231d8SStephan Herhut     assert(isa<llvm::Function>(llvmFuncCst.getCallee()));
473c33862b0SRiver Riddle     functionMapping[function.getName()] =
4745d7231d8SStephan Herhut         cast<llvm::Function>(llvmFuncCst.getCallee());
4755d7231d8SStephan Herhut   }
4765d7231d8SStephan Herhut 
4775d7231d8SStephan Herhut   // Convert functions.
4788c443678SRiver Riddle   for (FuncOp function : mlirModule.getOps<FuncOp>()) {
4795d7231d8SStephan Herhut     // Ignore external functions.
4805d7231d8SStephan Herhut     if (function.isExternal())
4815d7231d8SStephan Herhut       continue;
4825d7231d8SStephan Herhut 
483baa1ec22SAlex Zinenko     if (failed(convertOneFunction(function)))
484baa1ec22SAlex Zinenko       return failure();
4855d7231d8SStephan Herhut   }
4865d7231d8SStephan Herhut 
487baa1ec22SAlex Zinenko   return success();
4885d7231d8SStephan Herhut }
4895d7231d8SStephan Herhut 
490fec20e59SRiver Riddle std::unique_ptr<llvm::Module> ModuleTranslation::prepareLLVMModule(ModuleOp m) {
491bc5c7378SRiver Riddle   auto *dialect = m.getContext()->getRegisteredDialect<LLVM::LLVMDialect>();
4925d7231d8SStephan Herhut   assert(dialect && "LLVM dialect must be registered");
4935d7231d8SStephan Herhut 
494bc5c7378SRiver Riddle   auto llvmModule = llvm::CloneModule(dialect->getLLVMModule());
4955d7231d8SStephan Herhut   if (!llvmModule)
4965d7231d8SStephan Herhut     return nullptr;
4975d7231d8SStephan Herhut 
4985d7231d8SStephan Herhut   llvm::LLVMContext &llvmContext = llvmModule->getContext();
4995d7231d8SStephan Herhut   llvm::IRBuilder<> builder(llvmContext);
5005d7231d8SStephan Herhut 
5015d7231d8SStephan Herhut   // Inject declarations for `malloc` and `free` functions that can be used in
5025d7231d8SStephan Herhut   // memref allocation/deallocation coming from standard ops lowering.
5035d7231d8SStephan Herhut   llvmModule->getOrInsertFunction("malloc", builder.getInt8PtrTy(),
5045d7231d8SStephan Herhut                                   builder.getInt64Ty());
5055d7231d8SStephan Herhut   llvmModule->getOrInsertFunction("free", builder.getVoidTy(),
5065d7231d8SStephan Herhut                                   builder.getInt8PtrTy());
5075d7231d8SStephan Herhut 
5085d7231d8SStephan Herhut   return llvmModule;
5095d7231d8SStephan Herhut }
5105d7231d8SStephan Herhut 
5115d7231d8SStephan Herhut } // namespace LLVM
5125d7231d8SStephan Herhut } // namespace mlir
513