1 //===- ConvertToLLVMIR.cpp - MLIR to LLVM IR conversion -------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements a translation between the MLIR LLVM dialect and LLVM IR.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "mlir/Target/LLVMIR.h"
14 
15 #include "mlir/Dialect/OpenMP/OpenMPDialect.h"
16 #include "mlir/Target/LLVMIR/Dialect/LLVMIR/LLVMToLLVMIRTranslation.h"
17 #include "mlir/Target/LLVMIR/ModuleTranslation.h"
18 #include "mlir/Translation.h"
19 
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/IR/Verifier.h"
23 #include "llvm/Support/ToolOutputFile.h"
24 
25 using namespace mlir;
26 
27 std::unique_ptr<llvm::Module>
28 mlir::translateModuleToLLVMIR(ModuleOp m, llvm::LLVMContext &llvmContext,
29                               StringRef name) {
30   auto llvmModule =
31       LLVM::ModuleTranslation::translateModule<>(m, llvmContext, name);
32   if (!llvmModule)
33     emitError(m.getLoc(), "Fail to convert MLIR to LLVM IR");
34   else if (verifyModule(*llvmModule))
35     emitError(m.getLoc(), "LLVM IR fails to verify");
36   return llvmModule;
37 }
38 
39 void mlir::registerLLVMDialectTranslation(DialectRegistry &registry) {
40   registry.insert<LLVM::LLVMDialect>();
41   registry.addDialectInterface<LLVM::LLVMDialect,
42                                LLVMDialectLLVMIRTranslationInterface>();
43 }
44 
45 void mlir::registerLLVMDialectTranslation(MLIRContext &context) {
46   auto *dialect = context.getLoadedDialect<LLVM::LLVMDialect>();
47   if (!dialect || dialect->getRegisteredInterface<
48                       LLVMDialectLLVMIRTranslationInterface>() == nullptr) {
49     DialectRegistry registry;
50     registry.insert<LLVM::LLVMDialect>();
51     registry.addDialectInterface<LLVM::LLVMDialect,
52                                  LLVMDialectLLVMIRTranslationInterface>();
53     context.appendDialectRegistry(registry);
54   }
55 }
56 
57 namespace mlir {
58 void registerToLLVMIRTranslation() {
59   TranslateFromMLIRRegistration registration(
60       "mlir-to-llvmir",
61       [](ModuleOp module, raw_ostream &output) {
62         llvm::LLVMContext llvmContext;
63         auto llvmModule = LLVM::ModuleTranslation::translateModule<>(
64             module, llvmContext, "LLVMDialectModule");
65         if (!llvmModule)
66           return failure();
67 
68         llvmModule->print(output, nullptr);
69         return success();
70       },
71       [](DialectRegistry &registry) {
72         registry.insert<omp::OpenMPDialect>();
73         registerLLVMDialectTranslation(registry);
74       });
75 }
76 } // namespace mlir
77