Skip to content

[CIR] Add option to emit MLIR in LLVM dialect. #1316

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Mar 5, 2025
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions clang/include/clang/CIR/LowerToLLVM.h
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,19 @@ class ModuleOp;
namespace cir {

namespace direct {
mlir::ModuleOp lowerDirectlyFromCIRToLLVMDialect(mlir::ModuleOp theModule,
bool disableVerifier = false,
bool disableCCLowering = false,
bool disableDebugInfo = false);

// Lower directly from pristine CIR to LLVMIR.
std::unique_ptr<llvm::Module> lowerDirectlyFromCIRToLLVMIR(
mlir::ModuleOp theModule, llvm::LLVMContext &llvmCtx,
bool disableVerifier = false, bool disableCCLowering = false,
bool disableDebugInfo = false);
}

// Lower directly from pristine CIR to LLVMIR.
} // namespace direct

std::unique_ptr<llvm::Module>
lowerFromCIRToMLIRToLLVMIR(mlir::ModuleOp theModule,
std::unique_ptr<mlir::MLIRContext> mlirCtx,
Expand Down
6 changes: 6 additions & 0 deletions clang/include/clang/CIR/LowerToMLIR.h
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,16 @@
#ifndef CLANG_CIR_LOWERTOMLIR_H
#define CLANG_CIR_LOWERTOMLIR_H

#include "mlir/Transforms/DialectConversion.h"

namespace cir {

void populateCIRLoopToSCFConversionPatterns(mlir::RewritePatternSet &patterns,
mlir::TypeConverter &converter);

mlir::ModuleOp
lowerFromCIRToMLIRToLLVMDialect(mlir::ModuleOp theModule,
mlir::MLIRContext *mlirCtx = nullptr);
} // namespace cir

#endif // CLANG_CIR_LOWERTOMLIR_H_
11 changes: 10 additions & 1 deletion clang/include/clang/Driver/Options.td
Original file line number Diff line number Diff line change
Expand Up @@ -3120,7 +3120,16 @@ def emit_cir_only : Flag<["-"], "emit-cir-only">,
def emit_cir_flat : Flag<["-"], "emit-cir-flat">, Visibility<[ClangOption, CC1Option]>,
Group<Action_Group>, HelpText<"Similar to -emit-cir but also lowers structured CFG into basic blocks.">;
def emit_mlir : Flag<["-"], "emit-mlir">, Visibility<[CC1Option]>, Group<Action_Group>,
HelpText<"Build ASTs and then lower through ClangIR to MLIR, emit the .milr file">;
HelpText<"Build ASTs and then lower through ClangIR to MLIR (standard dialects "
"or the LLVM dialect), emit the .mlir file.">;
def emit_mlir_EQ : Joined<["-"], "emit-mlir=">, Visibility<[CC1Option]>, Group<Action_Group>,
HelpText<"Build ASTs and then lower through ClangIR to the selected MLIR dialect, emit the .mlir file. "
"Allowed values are `std` for MLIR standard dialects "
"`llvm` for the LLVM dialect and `cir` for the ClangIR dialect.">,
Values<"std,llvm,cir">,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's confusing to have CIR here, better remove it. Should be std or LLVM (we already have -emit-cir and this PR is not unifying any of the existing handling either).

NormalizedValuesScope<"FrontendOptions">,
NormalizedValues<["MLIR_STD", "MLIR_LLVM", "MLIR_CIR"]>,
MarshallingInfoEnum<FrontendOpts<"MLIRTargetDialect">, "MLIR_Default">;
/// ClangIR-specific options - END

def flto : Flag<["-"], "flto">,
Expand Down
7 changes: 7 additions & 0 deletions clang/include/clang/Frontend/FrontendOptions.h
Original file line number Diff line number Diff line change
Expand Up @@ -530,6 +530,13 @@ class FrontendOptions {
std::string ClangIRIdiomRecognizerOpts;
std::string ClangIRLibOptOpts;

enum {
MLIR_Default,
MLIR_STD,
MLIR_LLVM,
MLIR_CIR
} MLIRTargetDialect = MLIR_Default;

/// The input kind, either specified via -x argument or deduced from the input
/// file name.
InputKind DashX;
Expand Down
48 changes: 39 additions & 9 deletions clang/lib/CIR/FrontendAction/CIRGenAction.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
#include "clang/CIR/CIRToCIRPasses.h"
#include "clang/CIR/Dialect/IR/CIRDialect.h"
#include "clang/CIR/LowerToLLVM.h"
#include "clang/CIR/LowerToMLIR.h"
#include "clang/CIR/Passes.h"
#include "clang/CodeGen/BackendUtil.h"
#include "clang/CodeGen/ModuleBuilder.h"
Expand Down Expand Up @@ -260,9 +261,7 @@ class CIRGenConsumer : public clang::ASTConsumer {
}
}

switch (action) {
case CIRGenAction::OutputType::EmitCIR:
case CIRGenAction::OutputType::EmitCIRFlat:
auto emitCIR = [&]() {
if (outputStream && mlirMod) {
// FIXME: we cannot roundtrip prettyForm=true right now.
mlir::OpPrintingFlags flags;
Expand All @@ -271,14 +270,45 @@ class CIRGenConsumer : public clang::ASTConsumer {
flags.assumeVerified();
mlirMod->print(*outputStream, flags);
}
};

switch (action) {
case CIRGenAction::OutputType::EmitCIR:
case CIRGenAction::OutputType::EmitCIRFlat:
emitCIR();
break;
case CIRGenAction::OutputType::EmitMLIR: {
auto loweredMlirModule = lowerFromCIRToMLIR(mlirMod, mlirCtx.get());
assert(outputStream && "Why are we here without an output stream?");
// FIXME: we cannot roundtrip prettyForm=true right now.
mlir::OpPrintingFlags flags;
flags.enableDebugInfo(/*enable=*/true, /*prettyForm=*/false);
loweredMlirModule->print(*outputStream, flags);
mlir::ModuleOp loweredMlirModule;
switch (feOptions.MLIRTargetDialect) {
case clang::FrontendOptions::MLIR_Default:
loweredMlirModule =
feOptions.ClangIRDirectLowering
? direct::lowerDirectlyFromCIRToLLVMDialect(mlirMod)
: lowerFromCIRToMLIR(mlirMod, mlirCtx.get());

break;
case clang::FrontendOptions::MLIR_STD:
// Attempting to emit std with direct lowering is already checked by
// Compiler Invocation
loweredMlirModule = lowerFromCIRToMLIR(mlirMod, mlirCtx.get());
break;
case clang::FrontendOptions::MLIR_LLVM:
loweredMlirModule =
feOptions.ClangIRDirectLowering
? direct::lowerDirectlyFromCIRToLLVMDialect(mlirMod)
: lowerFromCIRToMLIRToLLVMDialect(mlirMod, mlirCtx.get());
break;
case clang::FrontendOptions::MLIR_CIR:
emitCIR();
break;
}
if (loweredMlirModule) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What happens if this if is not taken?

assert(outputStream && "Why are we here without an output stream?");
// FIXME: we cannot roundtrip prettyForm=true right now.
mlir::OpPrintingFlags flags;
flags.enableDebugInfo(/*enable=*/true, /*prettyForm=*/false);
loweredMlirModule->print(*outputStream, flags);
}
break;
}
case CIRGenAction::OutputType::EmitLLVM:
Expand Down
24 changes: 19 additions & 5 deletions clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4689,11 +4689,11 @@ void populateCIRToLLVMPasses(mlir::OpPassManager &pm, bool useCCLowering) {

extern void registerCIRDialectTranslation(mlir::MLIRContext &context);

std::unique_ptr<llvm::Module>
lowerDirectlyFromCIRToLLVMIR(mlir::ModuleOp theModule, LLVMContext &llvmCtx,
bool disableVerifier, bool disableCCLowering,
bool disableDebugInfo) {
llvm::TimeTraceScope scope("lower from CIR to LLVM directly");
mlir::ModuleOp lowerDirectlyFromCIRToLLVMDialect(mlir::ModuleOp theModule,
bool disableVerifier,
bool disableCCLowering,
bool disableDebugInfo) {
llvm::TimeTraceScope scope("lower from CIR to LLVM Dialect");

mlir::MLIRContext *mlirCtx = theModule.getContext();
mlir::PassManager pm(mlirCtx);
Expand Down Expand Up @@ -4722,6 +4722,20 @@ lowerDirectlyFromCIRToLLVMIR(mlir::ModuleOp theModule, LLVMContext &llvmCtx,
if (theModule.verify().failed())
report_fatal_error("Verification of the final LLVMIR dialect failed!");

return theModule;
}

std::unique_ptr<llvm::Module>
lowerDirectlyFromCIRToLLVMIR(mlir::ModuleOp theModule, LLVMContext &llvmCtx,
bool disableVerifier, bool disableCCLowering,
bool disableDebugInfo) {
llvm::TimeTraceScope scope("lower from CIR to LLVM directly");

lowerDirectlyFromCIRToLLVMDialect(theModule, disableVerifier,
disableCCLowering, disableDebugInfo);

mlir::MLIRContext *mlirCtx = theModule.getContext();

mlir::registerBuiltinDialectTranslation(*mlirCtx);
mlir::registerLLVMDialectTranslation(*mlirCtx);
mlir::registerOpenMPDialectTranslation(*mlirCtx);
Expand Down
25 changes: 19 additions & 6 deletions clang/lib/CIR/Lowering/ThroughMLIR/LowerCIRToMLIR.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
#include "mlir/Transforms/DialectConversion.h"
#include "clang/CIR/Dialect/IR/CIRDialect.h"
#include "clang/CIR/Dialect/IR/CIRTypes.h"
#include "clang/CIR/LowerToLLVM.h"
#include "clang/CIR/LowerToMLIR.h"
#include "clang/CIR/LoweringHelpers.h"
#include "clang/CIR/Passes.h"
Expand Down Expand Up @@ -1458,13 +1459,14 @@ void ConvertCIRToMLIRPass::runOnOperation() {
signalPassFailure();
}

std::unique_ptr<llvm::Module>
lowerFromCIRToMLIRToLLVMIR(mlir::ModuleOp theModule,
std::unique_ptr<mlir::MLIRContext> mlirCtx,
LLVMContext &llvmCtx) {
llvm::TimeTraceScope scope("Lower from CIR to MLIR To LLVM");
mlir::ModuleOp lowerFromCIRToMLIRToLLVMDialect(mlir::ModuleOp theModule,
mlir::MLIRContext *mlirCtx) {
llvm::TimeTraceScope scope("Lower from CIR to MLIR To LLVM Dialect");
if (!mlirCtx) {
mlirCtx = theModule.getContext();
}

mlir::PassManager pm(mlirCtx.get());
mlir::PassManager pm(mlirCtx);

pm.addPass(createConvertCIRToMLIRPass());
pm.addPass(createConvertMLIRToLLVMPass());
Expand All @@ -1478,6 +1480,17 @@ lowerFromCIRToMLIRToLLVMIR(mlir::ModuleOp theModule,
if (theModule.verify().failed())
report_fatal_error("Verification of the final LLVMIR dialect failed!");

return theModule;
}

std::unique_ptr<llvm::Module>
lowerFromCIRToMLIRToLLVMIR(mlir::ModuleOp theModule,
std::unique_ptr<mlir::MLIRContext> mlirCtx,
LLVMContext &llvmCtx) {
llvm::TimeTraceScope scope("Lower from CIR to MLIR To LLVM");

lowerFromCIRToMLIRToLLVMDialect(theModule, mlirCtx.get());

mlir::registerBuiltinDialectTranslation(*mlirCtx);
mlir::registerLLVMDialectTranslation(*mlirCtx);
mlir::registerOpenMPDialectTranslation(*mlirCtx);
Expand Down
8 changes: 8 additions & 0 deletions clang/lib/Frontend/CompilerInvocation.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2738,6 +2738,7 @@ static const auto &getFrontendActionTable() {
{frontend::EmitCIRFlat, OPT_emit_cir_flat},
{frontend::EmitCIROnly, OPT_emit_cir_only},
{frontend::EmitMLIR, OPT_emit_mlir},
{frontend::EmitMLIR, OPT_emit_mlir_EQ},
{frontend::EmitHTML, OPT_emit_html},
{frontend::EmitLLVM, OPT_emit_llvm},
{frontend::EmitLLVMOnly, OPT_emit_llvm_only},
Expand Down Expand Up @@ -2849,6 +2850,13 @@ static void GenerateFrontendArgs(const FrontendOptions &Opts,
};
}

if (Opts.ProgramAction == frontend::EmitMLIR) {
GenerateProgramAction = [&]() {
if (Opts.MLIRTargetDialect == FrontendOptions::MLIR_Default)
GenerateArg(Consumer, OPT_emit_mlir);
};
}

if (Opts.ProgramAction == frontend::FixIt && !Opts.FixItSuffix.empty()) {
GenerateProgramAction = [&]() {
GenerateArg(Consumer, OPT_fixit_EQ, Opts.FixItSuffix);
Expand Down
7 changes: 4 additions & 3 deletions clang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,10 @@ CreateFrontendBaseAction(CompilerInstance &CI) {
llvm::report_fatal_error(
"-emit-cir and -emit-cir-only only valid when using -fclangir");

if (CI.getFrontendOpts().ClangIRDirectLowering && Act == EmitMLIR)
llvm::report_fatal_error(
"ClangIR direct lowering is incompatible with -emit-mlir");
if (Act == EmitMLIR && CI.getFrontendOpts().ClangIRDirectLowering &&
CI.getFrontendOpts().MLIRTargetDialect == FrontendOptions::MLIR_STD)
llvm::report_fatal_error("ClangIR direct lowering is incompatible with "
"emitting of MLIR standard dialects");

switch (CI.getFrontendOpts().ProgramAction) {
case ASTDeclList: return std::make_unique<ASTDeclListAction>();
Expand Down