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 all 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
18 changes: 1 addition & 17 deletions clang/include/clang/CIR/FrontendAction/CIRGenAction.h
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,9 @@ class CIRGenAction : public clang::ASTFrontendAction {
public:
enum class OutputType {
EmitAssembly,
EmitCIR,
EmitCIRFlat,
EmitMLIR,
EmitLLVM,
EmitBC,
EmitMLIR,
EmitObj,
None
};
Expand Down Expand Up @@ -73,20 +71,6 @@ class CIRGenAction : public clang::ASTFrontendAction {
OutputType action;
};

class EmitCIRAction : public CIRGenAction {
virtual void anchor();

public:
EmitCIRAction(mlir::MLIRContext *mlirCtx = nullptr);
};

class EmitCIRFlatAction : public CIRGenAction {
virtual void anchor();

public:
EmitCIRFlatAction(mlir::MLIRContext *mlirCtx = nullptr);
};

class EmitCIROnlyAction : public CIRGenAction {
virtual void anchor();

Expand Down
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_
19 changes: 15 additions & 4 deletions clang/include/clang/Driver/Options.td
Original file line number Diff line number Diff line change
Expand Up @@ -3113,14 +3113,25 @@ defm clangir_call_conv_lowering : BoolFOption<"clangir-call-conv-lowering",
NegFlag<SetFalse, [], [ClangOption, CC1Option], "Ignore calling convetion during lowering">,
BothFlags<[], [ClangOption, CC1Option], "">>;

def emit_mlir : Flag<["-"], "emit-mlir">, Visibility<[ClangOption]>, Group<Action_Group>,
HelpText<"Build ASTs and then lower through ClangIR to MLIR (standard dialects "
"when `-fno-clangir-direct-lowering` is used or the LLVM dialect when "
"`-fclangir-direct-lowering` is used), emit the .mlir file.">;
def emit_mlir_EQ : Joined<["-"], "emit-mlir=">, Visibility<[ClangOption, CC1Option]>, Group<Action_Group>,
HelpText<"Build ASTs and then lower through ClangIR to the selected MLIR dialect, emit the .mlir file. "
"Allowed values are `core` for MLIR standard dialects and `llvm` for the LLVM dialect.">,
Values<"core,llvm,cir,cir-flat">,
NormalizedValuesScope<"frontend">,
NormalizedValues<["MLIR_CORE", "MLIR_LLVM", "MLIR_CIR", "MLIR_CIR_FLAT"]>,
MarshallingInfoEnum<FrontendOpts<"MLIRTargetDialect">, "MLIR_CORE">;
def emit_cir : Flag<["-"], "emit-cir">, Visibility<[ClangOption, CC1Option]>,
Group<Action_Group>, HelpText<"Build ASTs and then lower to ClangIR, emit the .cir file">;
Group<Action_Group>, Alias<emit_mlir_EQ>, AliasArgs<["cir"]>,
HelpText<"Build ASTs and then lower to ClangIR, emit the .cir file">;
def emit_cir_only : Flag<["-"], "emit-cir-only">,
HelpText<"Build ASTs and convert to CIR, discarding output">;
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">;
Group<Action_Group>, Alias<emit_mlir_EQ>, AliasArgs<["cir-flat"]>,
HelpText<"Similar to -emit-cir but also lowers structured CFG into basic blocks.">;
/// ClangIR-specific options - END

def flto : Flag<["-"], "flto">,
Expand Down
2 changes: 0 additions & 2 deletions clang/include/clang/Driver/Types.def
Original file line number Diff line number Diff line change
Expand Up @@ -99,8 +99,6 @@ TYPE("ir", LLVM_BC, INVALID, "bc", phases
TYPE("lto-ir", LTO_IR, INVALID, "s", phases::Compile, phases::Backend, phases::Assemble, phases::Link)
TYPE("lto-bc", LTO_BC, INVALID, "o", phases::Compile, phases::Backend, phases::Assemble, phases::Link)

TYPE("cir", CIR, INVALID, "cir", phases::Compile, phases::Backend, phases::Assemble, phases::Link)
TYPE("cir-flat", CIR_FLAT, INVALID, "cir", phases::Compile, phases::Backend, phases::Assemble, phases::Link)
TYPE("mlir", MLIR, INVALID, "mlir", phases::Compile, phases::Backend, phases::Assemble, phases::Link)

// Misc.
Expand Down
10 changes: 4 additions & 6 deletions clang/include/clang/Frontend/FrontendOptions.h
Original file line number Diff line number Diff line change
Expand Up @@ -65,12 +65,6 @@ enum ActionKind {
/// Translate input source into HTML.
EmitHTML,

/// Emit a .cir file
EmitCIR,

/// Emit a .cir file with flat ClangIR
EmitCIRFlat,

/// Generate CIR, bud don't emit anything.
EmitCIROnly,

Expand Down Expand Up @@ -160,6 +154,8 @@ enum ActionKind {
PrintDependencyDirectivesSourceMinimizerOutput
};

enum MLIRDialectKind { MLIR_CORE, MLIR_LLVM, MLIR_CIR, MLIR_CIR_FLAT };

} // namespace frontend

/// The kind of a file that we've been handed as an input.
Expand Down Expand Up @@ -530,6 +526,8 @@ class FrontendOptions {
std::string ClangIRIdiomRecognizerOpts;
std::string ClangIRLibOptOpts;

frontend::MLIRDialectKind MLIRTargetDialect;

/// The input kind, either specified via -x argument or deduced from the input
/// file name.
InputKind DashX;
Expand Down
4 changes: 2 additions & 2 deletions clang/lib/CIR/CodeGen/CIRPasses.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ mlir::LogicalResult runCIRToCIRPasses(
llvm::StringRef lifetimeOpts, bool enableIdiomRecognizer,
llvm::StringRef idiomRecognizerOpts, bool enableLibOpt,
llvm::StringRef libOptOpts, std::string &passOptParsingFailure,
bool enableCIRSimplify, bool flattenCIR, bool emitMLIR,
bool enableCIRSimplify, bool flattenCIR, bool emitCore,
bool enableCallConvLowering, bool enableMem2Reg) {

llvm::TimeTraceScope scope("CIR To CIR Passes");
Expand Down Expand Up @@ -81,7 +81,7 @@ mlir::LogicalResult runCIRToCIRPasses(
if (enableMem2Reg)
pm.addPass(mlir::createMem2Reg());

if (emitMLIR)
if (emitCore)
pm.addPass(mlir::createSCFPreparePass());

// FIXME: once CIRCodenAction fixes emission other than CIR we
Expand Down
75 changes: 42 additions & 33 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 @@ -201,8 +202,16 @@ class CIRGenConsumer : public clang::ASTConsumer {
if (feOptions.ClangIRLibOpt)
libOptOpts = sanitizePassOptions(feOptions.ClangIRLibOptOpts);

bool enableCCLowering = feOptions.ClangIRCallConvLowering &&
action != CIRGenAction::OutputType::EmitCIR;
bool enableCCLowering =
feOptions.ClangIRCallConvLowering &&
!(action == CIRGenAction::OutputType::EmitMLIR &&
feOptions.MLIRTargetDialect == frontend::MLIR_CIR);
bool flattenCIR =
action == CIRGenAction::OutputType::EmitMLIR &&
feOptions.MLIRTargetDialect == clang::frontend::MLIR_CIR_FLAT;

bool emitCore = action == CIRGenAction::OutputType::EmitMLIR &&
feOptions.MLIRTargetDialect == clang::frontend::MLIR_CORE;

// Setup and run CIR pipeline.
std::string passOptParsingFailure;
Expand All @@ -211,10 +220,8 @@ class CIRGenConsumer : public clang::ASTConsumer {
feOptions.ClangIRLifetimeCheck, lifetimeOpts,
feOptions.ClangIRIdiomRecognizer, idiomRecognizerOpts,
feOptions.ClangIRLibOpt, libOptOpts, passOptParsingFailure,
codeGenOptions.OptimizationLevel > 0,
action == CIRGenAction::OutputType::EmitCIRFlat,
action == CIRGenAction::OutputType::EmitMLIR, enableCCLowering,
feOptions.ClangIREnableMem2Reg)
codeGenOptions.OptimizationLevel > 0, flattenCIR, emitCore,
enableCCLowering, feOptions.ClangIREnableMem2Reg)
.failed()) {
if (!passOptParsingFailure.empty())
diagnosticsEngine.Report(diag::err_drv_cir_pass_opt_parsing)
Expand Down Expand Up @@ -260,25 +267,39 @@ class CIRGenConsumer : public clang::ASTConsumer {
}
}

switch (action) {
case CIRGenAction::OutputType::EmitCIR:
case CIRGenAction::OutputType::EmitCIRFlat:
if (outputStream && mlirMod) {
// FIXME: we cannot roundtrip prettyForm=true right now.
mlir::OpPrintingFlags flags;
flags.enableDebugInfo(/*enable=*/true, /*prettyForm=*/false);
if (feOptions.ClangIRDisableCIRVerifier)
flags.assumeVerified();
mlirMod->print(*outputStream, flags);
}
break;
case CIRGenAction::OutputType::EmitMLIR: {
auto loweredMlirModule = lowerFromCIRToMLIR(mlirMod, mlirCtx.get());
auto emitMLIR = [&](mlir::Operation *mlirMod, bool verify) {
assert(mlirMod &&
"MLIR module does not exist, but lowering did not fail?");
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);
if (!verify)
flags.assumeVerified();
mlirMod->print(*outputStream, flags);
};

switch (action) {
case CIRGenAction::OutputType::EmitMLIR: {
switch (feOptions.MLIRTargetDialect) {
case clang::frontend::MLIR_CORE:
// case for direct lowering is already checked in compiler invocation
// no need to check here
emitMLIR(lowerFromCIRToMLIR(mlirMod, mlirCtx.get()), false);
break;
case clang::frontend::MLIR_LLVM: {
mlir::ModuleOp loweredMLIRModule =
feOptions.ClangIRDirectLowering
? direct::lowerDirectlyFromCIRToLLVMDialect(mlirMod)
: lowerFromCIRToMLIRToLLVMDialect(mlirMod, mlirCtx.get());
emitMLIR(loweredMLIRModule, false);
break;
}
case clang::frontend::MLIR_CIR:
case clang::frontend::MLIR_CIR_FLAT:
emitMLIR(mlirMod, feOptions.ClangIRDisableCIRVerifier);
break;
}
break;
}
case CIRGenAction::OutputType::EmitLLVM:
Expand Down Expand Up @@ -356,10 +377,6 @@ getOutputStream(CompilerInstance &ci, StringRef inFile,
switch (action) {
case CIRGenAction::OutputType::EmitAssembly:
return ci.createDefaultOutputFile(false, inFile, "s");
case CIRGenAction::OutputType::EmitCIR:
return ci.createDefaultOutputFile(false, inFile, "cir");
case CIRGenAction::OutputType::EmitCIRFlat:
return ci.createDefaultOutputFile(false, inFile, "cir");
case CIRGenAction::OutputType::EmitMLIR:
return ci.createDefaultOutputFile(false, inFile, "mlir");
case CIRGenAction::OutputType::EmitLLVM:
Expand Down Expand Up @@ -456,14 +473,6 @@ void EmitAssemblyAction::anchor() {}
EmitAssemblyAction::EmitAssemblyAction(mlir::MLIRContext *_MLIRContext)
: CIRGenAction(OutputType::EmitAssembly, _MLIRContext) {}

void EmitCIRAction::anchor() {}
EmitCIRAction::EmitCIRAction(mlir::MLIRContext *_MLIRContext)
: CIRGenAction(OutputType::EmitCIR, _MLIRContext) {}

void EmitCIRFlatAction::anchor() {}
EmitCIRFlatAction::EmitCIRFlatAction(mlir::MLIRContext *_MLIRContext)
: CIRGenAction(OutputType::EmitCIRFlat, _MLIRContext) {}

void EmitCIROnlyAction::anchor() {}
EmitCIROnlyAction::EmitCIROnlyAction(mlir::MLIRContext *_MLIRContext)
: CIRGenAction(OutputType::None, _MLIRContext) {}
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
Loading
Loading