1//===----------------------------------------------------------------------===//
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// Converts CIR directly to LLVM IR, similar to mlir-translate or LLVM llc.
10//
11//===----------------------------------------------------------------------===//
12
13#include "mlir/Dialect/DLTI/DLTI.h"
14#include "mlir/Dialect/Func/IR/FuncOps.h"
15#include "mlir/Dialect/LLVMIR/LLVMDialectDecl.h"
16#include "mlir/Dialect/OpenMP/OpenMPDialect.h"
17#include "mlir/Dialect/OpenMP/Utils/Utils.h"
18#include "mlir/IR/BuiltinOps.h"
19#include "mlir/IR/MLIRContext.h"
20#include "mlir/Support/LogicalResult.h"
21#include "mlir/Target/LLVMIR/Dialect/Builtin/BuiltinToLLVMIRTranslation.h"
22#include "mlir/Target/LLVMIR/Dialect/LLVMIR/LLVMToLLVMIRTranslation.h"
23#include "mlir/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.h"
24#include "mlir/Target/LLVMIR/Export.h"
25#include "mlir/Tools/mlir-translate/MlirTranslateMain.h"
26#include "mlir/Tools/mlir-translate/Translation.h"
27
28#include "llvm/IR/DataLayout.h"
29#include "llvm/IR/Module.h"
30#include "llvm/TargetParser/Host.h"
31
32#include "clang/Basic/Diagnostic.h"
33#include "clang/Basic/DiagnosticIDs.h"
34#include "clang/Basic/DiagnosticOptions.h"
35#include "clang/Basic/TargetInfo.h"
36#include "clang/CIR/CIRDataLayoutSpec.h"
37#include "clang/CIR/Dialect/IR/CIRDialect.h"
38#include "clang/CIR/Dialect/Passes.h"
39#include "clang/CIR/InitAllDialects.h"
40#include "clang/CIR/LowerToLLVM.h"
41#include "clang/CIR/MissingFeatures.h"
42
43namespace cir {
44namespace direct {
45extern void registerCIRDialectTranslation(mlir::DialectRegistry &registry);
46} // namespace direct
47
48namespace {
49
50/// The goal of this option is to ensure that the triple and data layout specs
51/// are always available in the ClangIR module. With this requirement met, the
52/// behavior of this option is designed to be as intuitive as possible, as shown
53/// in the table below:
54///
55/// +--------+--------+-------------+-----------------+-----------------------+
56/// | Option | Triple | Data Layout | Behavior Triple | Behavior Data Layout |
57/// +========+========+=============+=================+=======================+
58/// | T | T | T | Overwrite | Derive from triple |
59/// | T | T | F | Overwrite | Derive from triple |
60/// | T | F | T | Overwrite | Derive from triple |
61/// | T | F | F | Overwrite | Derive from triple |
62/// | F | T | T | | |
63/// | F | T | F | | Derive from triple |
64/// | F | F | T | Set default | Derive from triple |
65/// | F | F | F | Set default | Derive from triple |
66/// +--------+--------+-------------+-----------------+-----------------------+
67llvm::cl::opt<std::string>
68 targetTripleOption("target",
69 llvm::cl::desc("Specify a default target triple when "
70 "it's not available in the module"),
71 llvm::cl::init(Val: ""));
72
73std::string prepareCIRModuleTriple(mlir::ModuleOp mod) {
74 std::string triple = targetTripleOption;
75
76 // Treat "" as the default target machine.
77 if (triple.empty()) {
78 triple = llvm::sys::getDefaultTargetTriple();
79
80 mod.emitWarning() << "no target triple provided, assuming " << triple;
81 }
82
83 mod->setAttr(name: cir::CIRDialect::getTripleAttrName(),
84 value: mlir::StringAttr::get(context: mod.getContext(), bytes: triple));
85 return triple;
86}
87
88llvm::LogicalResult prepareCIRModuleDataLayout(mlir::ModuleOp mod,
89 llvm::StringRef rawTriple) {
90 auto *context = mod.getContext();
91
92 // Data layout is fully determined by the target triple. Here we only pass the
93 // triple to get the data layout.
94 llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs> diagID(
95 new clang::DiagnosticIDs);
96 clang::DiagnosticOptions diagOpts;
97 llvm::IntrusiveRefCntPtr<clang::DiagnosticsEngine> diagnostics =
98 new clang::DiagnosticsEngine(diagID, diagOpts,
99 new clang::IgnoringDiagConsumer());
100 // TODO: Need to set various target options later to populate
101 // 'TargetInfo' properly.
102 clang::TargetOptions targetOptions;
103 targetOptions.Triple = rawTriple;
104 llvm::IntrusiveRefCntPtr<clang::TargetInfo> targetInfo =
105 clang::TargetInfo::CreateTargetInfo(Diags&: *diagnostics, Opts&: targetOptions);
106 if (!targetInfo) {
107 mod.emitError() << "error: invalid target triple '" << rawTriple << "'\n";
108 return llvm::failure();
109 }
110 std::string layoutString = targetInfo->getDataLayoutString();
111
112 // Registered dialects may not be loaded yet, ensure they are.
113 context->loadDialect<mlir::DLTIDialect, mlir::LLVM::LLVMDialect,
114 mlir::omp::OpenMPDialect>();
115
116 cir::setMLIRDataLayout(mod, dl: llvm::DataLayout(layoutString),
117 bitIntMaxAlign: targetInfo->getBitIntMaxAlign(),
118 maxVectorAlign: targetInfo->getMaxVectorAlign());
119
120 return llvm::success();
121}
122
123/// Prepare requirements like cir.triple and data layout.
124llvm::LogicalResult prepareCIRModuleForTranslation(mlir::ModuleOp mod) {
125 auto modTriple = mod->getAttrOfType<mlir::StringAttr>(
126 name: cir::CIRDialect::getTripleAttrName());
127 auto modDataLayout = mod->getAttr(name: mlir::DLTIDialect::kDataLayoutAttrName);
128 bool hasTargetOption = targetTripleOption.getNumOccurrences() > 0;
129
130 // Skip the situation where nothing should be done.
131 if (!hasTargetOption && modTriple && modDataLayout)
132 return llvm::success();
133
134 std::string triple;
135
136 if (!hasTargetOption && modTriple) {
137 // Do nothing if it's already set.
138 triple = modTriple.getValue();
139 } else {
140 // Otherwise, overwrite or set default.
141 triple = prepareCIRModuleTriple(mod);
142 }
143
144 // If the data layout is not set, derive it from the triple.
145 return prepareCIRModuleDataLayout(mod, rawTriple: triple);
146}
147} // namespace
148} // namespace cir
149
150static void registerLLVMIRTranslations(mlir::DialectRegistry &registry) {
151 mlir::registerBuiltinDialectTranslation(registry);
152 mlir::registerLLVMDialectTranslation(registry);
153 mlir::registerOpenMPDialectTranslation(registry);
154}
155
156void registerToLLVMTranslation() {
157 static llvm::cl::opt<bool> disableCCLowering(
158 "disable-cc-lowering",
159 llvm::cl::desc("Disable calling convention lowering pass"),
160 llvm::cl::init(Val: false));
161
162 mlir::TranslateFromMLIRRegistration registration(
163 "cir-to-llvmir", "Translate CIR to LLVMIR",
164 [](mlir::Operation *op, mlir::raw_ostream &output) {
165 auto cirModule = llvm::dyn_cast<mlir::ModuleOp>(Val: op);
166
167 if (mlir::failed(Result: cir::prepareCIRModuleForTranslation(mod: cirModule)))
168 return mlir::failure();
169
170 llvm::LLVMContext llvmContext;
171 const bool enableOpenMP = mlir::omp::isOpenMPModule(module: cirModule);
172 std::unique_ptr<llvm::Module> llvmModule =
173 cir::direct::lowerDirectlyFromCIRToLLVMIR(mlirModule: cirModule, llvmCtx&: llvmContext,
174 enableOpenMP);
175 if (!llvmModule)
176 return mlir::failure();
177 llvmModule->renumberMetadataForAssembly();
178 llvmModule->print(OS&: output, AAW: nullptr);
179 return mlir::success();
180 },
181 [](mlir::DialectRegistry &registry) {
182 cir::registerAllDialects(registry);
183 registry.insert<mlir::func::FuncDialect>();
184 registerLLVMIRTranslations(registry);
185 cir::direct::registerCIRDialectTranslation(registry);
186 });
187}
188
189// Mirrors mlir::registerToLLVMIRTranslation, restricted to the dialects CIR
190// lowers to so that the ClangIR tests need not depend on mlir-translate, which
191// links every MLIR dialect.
192static void registerMLIRToLLVMIRTranslation() {
193 mlir::TranslateFromMLIRRegistration registration(
194 "mlir-to-llvmir", "Translate MLIR to LLVMIR",
195 [](mlir::Operation *op, mlir::raw_ostream &output) {
196 llvm::LLVMContext llvmContext;
197 std::unique_ptr<llvm::Module> llvmModule =
198 mlir::translateModuleToLLVMIR(module: op, llvmContext);
199 if (!llvmModule)
200 return mlir::failure();
201 llvmModule->renumberMetadataForAssembly();
202 llvmModule->print(OS&: output, AAW: nullptr);
203 return mlir::success();
204 },
205 [](mlir::DialectRegistry &registry) {
206 registry.insert<mlir::DLTIDialect, mlir::func::FuncDialect>();
207 registerLLVMIRTranslations(registry);
208 });
209}
210
211int main(int argc, char **argv) {
212 registerToLLVMTranslation();
213 registerMLIRToLLVMIRTranslation();
214 return failed(Result: mlir::mlirTranslateMain(argc, argv, toolName: "CIR Translation Tool"));
215}
216