| 1 | //===--- CIRGenAction.cpp - LLVM Code generation Frontend Action ---------===// |
| 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 | #include "clang/CIR/FrontendAction/CIRGenAction.h" |
| 10 | #include "CIRDiagnosticHandler.h" |
| 11 | #include "mlir/Bytecode/BytecodeWriter.h" |
| 12 | #include "mlir/IR/BuiltinOps.h" |
| 13 | #include "mlir/IR/MLIRContext.h" |
| 14 | #include "mlir/IR/OwningOpRef.h" |
| 15 | #include "mlir/Parser/Parser.h" |
| 16 | #include "clang/AST/ASTContext.h" |
| 17 | #include "clang/Basic/DiagnosticCodeGen.h" |
| 18 | #include "clang/Basic/DiagnosticFrontend.h" |
| 19 | #include "clang/CIR/CIRGenerator.h" |
| 20 | #include "clang/CIR/CIRToCIRPasses.h" |
| 21 | #include "clang/CIR/Dialect/IR/CIRDialect.h" |
| 22 | #include "clang/CIR/InitAllDialects.h" |
| 23 | #include "clang/CIR/LowerToLLVM.h" |
| 24 | #include "clang/CodeGen/BackendUtil.h" |
| 25 | #include "clang/CodeGen/ModuleLinker.h" |
| 26 | #include "clang/CodeGenUtils/BackendDiagnosticHandler.h" |
| 27 | #include "clang/Frontend/CompilerInstance.h" |
| 28 | #include "llvm/ADT/STLFunctionalExtras.h" |
| 29 | #include "llvm/ADT/ScopeExit.h" |
| 30 | #include "llvm/ADT/SmallString.h" |
| 31 | #include "llvm/Frontend/Offloading/OffloadWrapper.h" |
| 32 | #include "llvm/IR/DiagnosticHandler.h" |
| 33 | #include "llvm/IR/Function.h" |
| 34 | #include "llvm/IR/GlobalValue.h" |
| 35 | #include "llvm/IR/LLVMContext.h" |
| 36 | #include "llvm/IR/Module.h" |
| 37 | #include "llvm/Support/LibraryOptionsContext.h" |
| 38 | #include "llvm/Support/MemoryBuffer.h" |
| 39 | #include "llvm/Support/Path.h" |
| 40 | #include "llvm/Support/raw_ostream.h" |
| 41 | |
| 42 | using namespace cir; |
| 43 | using namespace clang; |
| 44 | |
| 45 | namespace cir { |
| 46 | |
| 47 | static BackendAction |
| 48 | getBackendActionFromOutputType(CIRGenAction::OutputType Action) { |
| 49 | switch (Action) { |
| 50 | case CIRGenAction::OutputType::EmitCIR: |
| 51 | case CIRGenAction::OutputType::EmitCIRBC: |
| 52 | assert(false && |
| 53 | "Unsupported output type for getBackendActionFromOutputType!" ); |
| 54 | break; // Unreachable, but fall through to report that |
| 55 | case CIRGenAction::OutputType::EmitAssembly: |
| 56 | return BackendAction::Backend_EmitAssembly; |
| 57 | case CIRGenAction::OutputType::EmitBC: |
| 58 | return BackendAction::Backend_EmitBC; |
| 59 | case CIRGenAction::OutputType::EmitLLVM: |
| 60 | return BackendAction::Backend_EmitLL; |
| 61 | case CIRGenAction::OutputType::EmitObj: |
| 62 | return BackendAction::Backend_EmitObj; |
| 63 | } |
| 64 | // We should only get here if a non-enum value is passed in or we went through |
| 65 | // the assert(false) case above |
| 66 | llvm_unreachable("Unsupported output type!" ); |
| 67 | } |
| 68 | |
| 69 | static std::unique_ptr<llvm::Module> lowerFromCIRToLLVMIR( |
| 70 | mlir::ModuleOp MLIRModule, llvm::LLVMContext &LLVMCtx, bool EnableOpenMP, |
| 71 | llvm::StringRef mlirSaveTempsOutFile = {}, |
| 72 | llvm::vfs::FileSystem *fs = nullptr, bool enableOptimizations = false) { |
| 73 | return direct::lowerDirectlyFromCIRToLLVMIR(mlirModule: MLIRModule, llvmCtx&: LLVMCtx, enableOpenMP: EnableOpenMP, |
| 74 | mlirSaveTempsOutFile, fs, |
| 75 | enableOptimizations); |
| 76 | } |
| 77 | |
| 78 | // Print \p MLIRModule the way -emit-cir does, so that CIR emitted from source |
| 79 | // and CIR printed back from ClangIR input use the same form. |
| 80 | static void printCIRModule(mlir::ModuleOp MLIRModule, raw_ostream &OS) { |
| 81 | mlir::OpPrintingFlags Flags; |
| 82 | Flags.enableDebugInfo(/*enable=*/true, /*prettyForm=*/false); |
| 83 | MLIRModule->print(os&: OS, flags: Flags); |
| 84 | } |
| 85 | |
| 86 | // Reads the device binary named by -foffload-include-binary and embeds it |
| 87 | // into the host module. wrapSYCLBinaries also appends the registration ctor |
| 88 | // at priority 101 when no registration-function out-param is supplied. |
| 89 | static void embedSYCLDeviceBinary(CompilerInstance &CI, llvm::Module &M) { |
| 90 | StringRef fileName = CI.getCodeGenOpts().OffloadBinaryToEmbedFile; |
| 91 | auto bufferOrErr = CI.getVirtualFileSystem().getBufferForFile(Name: fileName); |
| 92 | if (std::error_code ec = bufferOrErr.getError()) { |
| 93 | CI.getDiagnostics().Report(DiagID: diag::err_cannot_open_file) |
| 94 | << fileName << ec.message(); |
| 95 | return; |
| 96 | } |
| 97 | std::unique_ptr<llvm::MemoryBuffer> buffer = std::move(bufferOrErr.get()); |
| 98 | if (llvm::Error err = llvm::offloading::wrapSYCLBinaries( |
| 99 | M, Buffer: ArrayRef<char>(buffer->getBufferStart(), buffer->getBufferSize()), |
| 100 | Options: llvm::offloading::SYCLJITOptions(), /*IsFinalizedImage=*/true)) { |
| 101 | CI.getDiagnostics().Report(DiagID: diag::err_fe_error_backend) |
| 102 | << llvm::toString(E: std::move(err)); |
| 103 | return; |
| 104 | } |
| 105 | } |
| 106 | |
| 107 | // Runs the CIR-to-CIR pipeline on \p MlirModule unless -clangir-disable-passes |
| 108 | // is given. |
| 109 | static mlir::LogicalResult runCIRPipeline(const FrontendOptions &FEOpts, |
| 110 | const CodeGenOptions &CGO, |
| 111 | mlir::ModuleOp MlirModule, |
| 112 | mlir::MLIRContext &MlirCtx) { |
| 113 | if (FEOpts.ClangIRDisablePasses) |
| 114 | return mlir::success(); |
| 115 | const bool EnableLibOpt = |
| 116 | FEOpts.ClangIRLibOptEnabled && (CGO.OptimizationLevel > 0); |
| 117 | return runCIRToCIRPasses( |
| 118 | theModule: MlirModule, mlirCtx&: MlirCtx, enableVerifier: !FEOpts.ClangIRDisableCIRVerifier, |
| 119 | enableIdiomRecognizer: FEOpts.ClangIREnableIdiomRecognizer, enableCIRSimplify: CGO.OptimizationLevel > 0, |
| 120 | enableLibOpt: EnableLibOpt, libOptOptions: FEOpts.ClangIRLibOptOptions, |
| 121 | enableCallConvLowering: FEOpts.ClangIRCallConvLowering); |
| 122 | } |
| 123 | |
| 124 | // Emits the output requested by \p Action for \p MlirModule, a CIR module that |
| 125 | // has been through the CIR-to-CIR pipeline. Language facts are read from the |
| 126 | // module's #cir.lowering_options and target facts from \p CI, so this |
| 127 | // does not need an ASTContext and can also run on CIR loaded from a file. |
| 128 | // \p AddFunctionSourceLocations, if set, runs on the lowered LLVM module |
| 129 | // before linking. |
| 130 | static void emitCIRModuleOutput( |
| 131 | CIRGenAction::OutputType Action, CompilerInstance &CI, |
| 132 | mlir::ModuleOp MlirModule, llvm::LLVMContext &LLVMCtx, |
| 133 | SmallVectorImpl<::clang::LinkModule> &LinkModules, |
| 134 | BackendDiagnosticConsumer &DiagConsumer, |
| 135 | std::unique_ptr<raw_pwrite_stream> OutputStream, |
| 136 | llvm::function_ref<void(llvm::Module &)> AddFunctionSourceLocations = {}) { |
| 137 | CodeGenOptions &CGO = CI.getCodeGenOpts(); |
| 138 | switch (Action) { |
| 139 | case CIRGenAction::OutputType::EmitCIR: |
| 140 | if (OutputStream && MlirModule) |
| 141 | printCIRModule(MLIRModule: MlirModule, OS&: *OutputStream); |
| 142 | break; |
| 143 | case CIRGenAction::OutputType::EmitCIRBC: |
| 144 | if (OutputStream && MlirModule && |
| 145 | failed(Result: mlir::writeBytecodeToFile(op: MlirModule, os&: *OutputStream)) && |
| 146 | !CI.getDiagnostics().hasErrorOccurred()) |
| 147 | CI.getDiagnostics().Report(DiagID: diag::err_cir_bc_write_failed); |
| 148 | break; |
| 149 | case CIRGenAction::OutputType::EmitLLVM: |
| 150 | case CIRGenAction::OutputType::EmitBC: |
| 151 | case CIRGenAction::OutputType::EmitObj: |
| 152 | case CIRGenAction::OutputType::EmitAssembly: { |
| 153 | StringRef saveTempsPrefix = CGO.SaveTempsFilePrefix; |
| 154 | std::string cirSaveTempsOutFile, mlirSaveTempsOutFile; |
| 155 | if (!saveTempsPrefix.empty()) { |
| 156 | SmallString<128> stem(saveTempsPrefix); |
| 157 | llvm::sys::path::replace_extension(path&: stem, extension: "cir" ); |
| 158 | cirSaveTempsOutFile = std::string(stem); |
| 159 | llvm::sys::path::replace_extension(path&: stem, extension: "mlir" ); |
| 160 | mlirSaveTempsOutFile = std::string(stem); |
| 161 | } |
| 162 | |
| 163 | if (!cirSaveTempsOutFile.empty()) { |
| 164 | std::error_code ec; |
| 165 | llvm::raw_fd_ostream out(cirSaveTempsOutFile, ec); |
| 166 | if (!ec) |
| 167 | MlirModule->print(os&: out); |
| 168 | } |
| 169 | |
| 170 | // If errors occurred during codegen, stop before running the backend. |
| 171 | if (CI.getDiagnostics().hasErrorOccurred()) |
| 172 | return; |
| 173 | |
| 174 | // Read the lowering facts before lowering rewrites the module. Without the |
| 175 | // attribute (e.g. hand-written CIR) every fact defaults to off. |
| 176 | auto LangOptsAttr = MlirModule->getAttrOfType<cir::LoweringOptionsAttr>( |
| 177 | name: cir::CIRDialect::getLoweringOptionsAttrName()); |
| 178 | const bool EnableOpenMP = LangOptsAttr && LangOptsAttr.getOpenmp(); |
| 179 | |
| 180 | // Route LLVM backend diagnostics (optimization remarks, unsupported |
| 181 | // features, inline-asm errors, etc.) through clang diagnostics for |
| 182 | // the remainder of the LLVM-emitting pipeline. |
| 183 | std::unique_ptr<llvm::DiagnosticHandler> OldDiagnosticHandler = |
| 184 | LLVMCtx.getDiagnosticHandler(); |
| 185 | llvm::scope_exit RestoreDiagnosticHandler([&]() { |
| 186 | LLVMCtx.setDiagnosticHandler(DH: std::move(OldDiagnosticHandler)); |
| 187 | }); |
| 188 | LLVMCtx.setDiagnosticHandler(DH: DiagConsumer.createDiagnosticHandler()); |
| 189 | |
| 190 | // Backend components (e.g. the inline-asm parser) reach the filesystem |
| 191 | // through the context's VFS, which must be set to stay within the IO |
| 192 | // sandbox. |
| 193 | LLVMCtx.setVirtualFileSystem(CI.getVirtualFileSystemPtr()); |
| 194 | |
| 195 | // Enable the llvm-simplify-cfg pass when optimizations are on |
| 196 | // (-O1 and up); at -O0 the lowered IR keeps its raw shape. |
| 197 | std::unique_ptr<llvm::Module> LLVMModule = |
| 198 | lowerFromCIRToLLVMIR(MLIRModule: MlirModule, LLVMCtx, EnableOpenMP, |
| 199 | mlirSaveTempsOutFile, fs: &CI.getVirtualFileSystem(), |
| 200 | /*enableOptimizations=*/CGO.OptimizationLevel > 0); |
| 201 | if (!LLVMModule) { |
| 202 | // Lowering errors are already routed through the MLIR diagnostic |
| 203 | // handler. Only emit the generic error if nothing was reported. |
| 204 | if (!CI.getDiagnostics().hasErrorOccurred()) |
| 205 | CI.getDiagnostics().Report(DiagID: diag::err_cir_to_llvm_lowering_failed); |
| 206 | return; |
| 207 | } |
| 208 | |
| 209 | LLVMModule->setDataLayout(CI.getTarget().getDataLayoutString()); |
| 210 | |
| 211 | if (AddFunctionSourceLocations) |
| 212 | AddFunctionSourceLocations(*LLVMModule); |
| 213 | |
| 214 | if (linkInModules(M&: *LLVMModule, LinkModules, CodeGenOpts: CGO, LangOpts: CI.getLangOpts(), |
| 215 | TargetOpts: CI.getTargetOpts(), DiagConsumer)) |
| 216 | return; |
| 217 | |
| 218 | const LangOptions &LangOpts = CI.getLangOpts(); |
| 219 | |
| 220 | // Embed the offloaded SYCL device binary into the host module. |
| 221 | if (LangOpts.SYCLIsHost && !CGO.OffloadBinaryToEmbedFile.empty()) |
| 222 | embedSYCLDeviceBinary(CI, M&: *LLVMModule); |
| 223 | |
| 224 | // CUDA, HIP and OpenMP offloading rely on host-side offload entries that |
| 225 | // are not emitted on the ClangIR path yet, so embedding their device |
| 226 | // objects would produce a host object that cannot be registered. |
| 227 | // LangOptions::CUDA is also set for HIP. |
| 228 | if (!CGO.OffloadObjects.empty() && |
| 229 | (LangOpts.CUDA || !LangOpts.OMPTargetTriples.empty())) { |
| 230 | DiagnosticsEngine &Diags = CI.getDiagnostics(); |
| 231 | Diags.Report(DiagID: Diags.getCustomDiagID( |
| 232 | L: DiagnosticsEngine::Error, |
| 233 | FormatString: "ClangIR code gen Not Yet Implemented: embedding offload objects " |
| 234 | "for CUDA, HIP or OpenMP offloading" )); |
| 235 | return; |
| 236 | } |
| 237 | |
| 238 | // If there is device offloading code embed it in the host now. |
| 239 | EmbedObject(M: LLVMModule.get(), CGOpts: CGO, VFS&: CI.getVirtualFileSystem(), |
| 240 | Diags&: CI.getDiagnostics()); |
| 241 | |
| 242 | EmbedBitcode(M: LLVMModule.get(), CGOpts: CGO, Buf: llvm::MemoryBufferRef()); |
| 243 | |
| 244 | BackendAction BEAction = getBackendActionFromOutputType(Action); |
| 245 | emitBackendOutput(CI, CGOpts&: CGO, M: LLVMModule.get(), Action: BEAction, |
| 246 | VFS: CI.getVirtualFileSystemPtr(), OS: std::move(OutputStream)); |
| 247 | break; |
| 248 | } |
| 249 | } |
| 250 | } |
| 251 | |
| 252 | class CIRGenConsumer : public clang::ASTConsumer { |
| 253 | |
| 254 | virtual void anchor(); |
| 255 | |
| 256 | CIRGenAction::OutputType Action; |
| 257 | |
| 258 | CompilerInstance &CI; |
| 259 | |
| 260 | std::unique_ptr<raw_pwrite_stream> OutputStream; |
| 261 | |
| 262 | ASTContext *Context{nullptr}; |
| 263 | IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS; |
| 264 | std::unique_ptr<CIRGenerator> Gen; |
| 265 | const FrontendOptions &FEOptions; |
| 266 | CodeGenOptions &CGO; |
| 267 | |
| 268 | llvm::LLVMContext &LLVMCtx; |
| 269 | SmallVectorImpl<::clang::LinkModule> &LinkModules; |
| 270 | |
| 271 | std::optional<CIRDiagnosticHandler> MLIRDiagHandler; |
| 272 | |
| 273 | // Translates LLVM backend diagnostics (raised while lowering CIR to LLVM |
| 274 | // IR and while running emitBackendOutput) into clang diagnostics; shared |
| 275 | // with classic CodeGen's BackendConsumer. |
| 276 | BackendDiagnosticConsumer DiagConsumer; |
| 277 | |
| 278 | public: |
| 279 | CIRGenConsumer(CIRGenAction::OutputType Action, CompilerInstance &CI, |
| 280 | CodeGenOptions &CGO, std::unique_ptr<raw_pwrite_stream> OS, |
| 281 | llvm::LLVMContext &LLVMCtx, |
| 282 | SmallVectorImpl<::clang::LinkModule> &LinkModules) |
| 283 | : Action(Action), CI(CI), OutputStream(std::move(OS)), |
| 284 | FS(&CI.getVirtualFileSystem()), |
| 285 | Gen(std::make_unique<CIRGenerator>(args&: CI.getDiagnostics(), args: std::move(FS), |
| 286 | args&: CI.getCodeGenOpts())), |
| 287 | FEOptions(CI.getFrontendOpts()), CGO(CGO), LLVMCtx(LLVMCtx), |
| 288 | LinkModules(LinkModules), |
| 289 | DiagConsumer(CI.getDiagnostics(), CI.getCodeGenOpts()) {} |
| 290 | |
| 291 | void Initialize(ASTContext &Ctx) override { |
| 292 | assert(!Context && "initialized multiple times" ); |
| 293 | Context = &Ctx; |
| 294 | DiagConsumer.setSourceManager(&Ctx.getSourceManager()); |
| 295 | Gen->Initialize(astContext&: Ctx); |
| 296 | // Install the MLIR diagnostic handler now that CIRGenerator owns its |
| 297 | // MLIRContext. Lifetime is tied to this consumer, which spans CIRGen, |
| 298 | // CIR-to-CIR passes, and CIR-to-LLVM lowering. |
| 299 | MLIRDiagHandler.emplace(args: &Gen->getMLIRContext(), args&: CI.getDiagnostics(), |
| 300 | args&: CI.getSourceManager(), args&: CI.getFileManager()); |
| 301 | } |
| 302 | |
| 303 | bool HandleTopLevelDecl(DeclGroupRef D) override { |
| 304 | Gen->HandleTopLevelDecl(group: D); |
| 305 | return true; |
| 306 | } |
| 307 | |
| 308 | void HandleCXXStaticMemberVarInstantiation(clang::VarDecl *VD) override { |
| 309 | Gen->HandleCXXStaticMemberVarInstantiation(D: VD); |
| 310 | } |
| 311 | |
| 312 | void HandleOpenACCRoutineReference(const FunctionDecl *FD, |
| 313 | const OpenACCRoutineDecl *RD) override { |
| 314 | Gen->HandleOpenACCRoutineReference(FD, RD); |
| 315 | } |
| 316 | |
| 317 | void HandleInlineFunctionDefinition(FunctionDecl *D) override { |
| 318 | Gen->HandleInlineFunctionDefinition(d: D); |
| 319 | } |
| 320 | |
| 321 | void HandleTranslationUnit(ASTContext &C) override { |
| 322 | Gen->HandleTranslationUnit(astContext&: C); |
| 323 | |
| 324 | if (!FEOptions.ClangIRDisableCIRVerifier) { |
| 325 | if (!Gen->verifyModule()) { |
| 326 | // Verifier output already routed through ClangIRDiagnosticHandler. |
| 327 | // Only emit the generic fatal if nothing more specific was reported. |
| 328 | if (!CI.getDiagnostics().hasErrorOccurred()) |
| 329 | CI.getDiagnostics().Report( |
| 330 | DiagID: diag::err_cir_verification_failed_pre_passes); |
| 331 | llvm::report_fatal_error( |
| 332 | reason: "CIR codegen: module verification error before running CIR passes" ); |
| 333 | return; |
| 334 | } |
| 335 | } |
| 336 | |
| 337 | mlir::ModuleOp MlirModule = Gen->getModule(); |
| 338 | mlir::MLIRContext &MlirCtx = Gen->getMLIRContext(); |
| 339 | |
| 340 | if (runCIRPipeline(FEOpts: FEOptions, CGO, MlirModule, MlirCtx).failed()) { |
| 341 | // Pass-side errors already routed through ClangIRDiagnosticHandler. |
| 342 | // Skip the generic catch-all if a specific diagnostic was emitted. |
| 343 | if (!CI.getDiagnostics().hasErrorOccurred()) |
| 344 | CI.getDiagnostics().Report(DiagID: diag::err_cir_to_cir_transform_failed); |
| 345 | return; |
| 346 | } |
| 347 | |
| 348 | // CIRGen-only step: map the emitted LLVM functions back to their source |
| 349 | // declarations so backend diagnostics point at the original source. |
| 350 | auto AddFunctionSourceLocations = [&](llvm::Module &LLVMModule) { |
| 351 | for (llvm::Function &F : LLVMModule.functions()) |
| 352 | if (const Decl *FD = Gen->getDeclForMangledName(mangledName: F.getName())) |
| 353 | DiagConsumer.addFunctionSourceLocation( |
| 354 | MangledName: F.getName(), Loc: FD->getASTContext().getFullLoc(Loc: FD->getLocation())); |
| 355 | }; |
| 356 | emitCIRModuleOutput(Action, CI, MlirModule, LLVMCtx, LinkModules, |
| 357 | DiagConsumer, OutputStream: std::move(OutputStream), |
| 358 | AddFunctionSourceLocations); |
| 359 | } |
| 360 | |
| 361 | void HandleTagDeclDefinition(TagDecl *D) override { |
| 362 | PrettyStackTraceDecl CrashInfo(D, SourceLocation(), |
| 363 | Context->getSourceManager(), |
| 364 | "CIR generation of declaration" ); |
| 365 | Gen->HandleTagDeclDefinition(d: D); |
| 366 | } |
| 367 | |
| 368 | void HandleTagDeclRequiredDefinition(const TagDecl *D) override { |
| 369 | Gen->HandleTagDeclRequiredDefinition(D); |
| 370 | } |
| 371 | |
| 372 | void CompleteTentativeDefinition(VarDecl *D) override { |
| 373 | Gen->CompleteTentativeDefinition(d: D); |
| 374 | } |
| 375 | |
| 376 | void HandleVTable(CXXRecordDecl *RD) override { Gen->HandleVTable(rd: RD); } |
| 377 | }; |
| 378 | } // namespace cir |
| 379 | |
| 380 | void CIRGenConsumer::anchor() {} |
| 381 | |
| 382 | CIRGenAction::CIRGenAction(OutputType Act) |
| 383 | : Ctx(std::make_unique<llvm::LLVMContext>()), Action(Act) {} |
| 384 | |
| 385 | CIRGenAction::~CIRGenAction() { MLIRMod.release(); } |
| 386 | |
| 387 | bool CIRGenAction::BeginSourceFileAction(CompilerInstance &CI) { |
| 388 | Ctx->getLibraryOptions().assign(Other: CI.getLibraryOptions()); |
| 389 | Ctx->setVirtualFileSystem(CI.getVirtualFileSystemPtr()); |
| 390 | if (clang::loadLinkModules(CI, Ctx&: *Ctx, LinkModules, |
| 391 | /*OnlyInternalized=*/false)) |
| 392 | return false; |
| 393 | return ASTFrontendAction::BeginSourceFileAction(CI); |
| 394 | } |
| 395 | |
| 396 | static std::unique_ptr<raw_pwrite_stream> |
| 397 | getOutputStream(CompilerInstance &CI, StringRef InFile, |
| 398 | CIRGenAction::OutputType Action); |
| 399 | |
| 400 | void CIRGenAction::ExecuteAction() { |
| 401 | if (getCurrentFileKind().getLanguage() != Language::CIR) { |
| 402 | ASTFrontendAction::ExecuteAction(); |
| 403 | return; |
| 404 | } |
| 405 | |
| 406 | CompilerInstance &CI = getCompilerInstance(); |
| 407 | DiagnosticsEngine &Diags = CI.getDiagnostics(); |
| 408 | SourceManager &SM = CI.getSourceManager(); |
| 409 | |
| 410 | std::unique_ptr<raw_pwrite_stream> OS = CI.takeOutputStream(); |
| 411 | if (!OS) |
| 412 | OS = getOutputStream(CI, InFile: getCurrentFileOrBufferName(), Action); |
| 413 | if (!OS) |
| 414 | return; |
| 415 | |
| 416 | std::optional<llvm::MemoryBufferRef> MainFile = |
| 417 | SM.getBufferOrNone(FID: SM.getMainFileID()); |
| 418 | if (!MainFile) |
| 419 | return; |
| 420 | |
| 421 | mlir::MLIRContext MLIRContext; |
| 422 | cir::registerAllDialects(context&: MLIRContext); |
| 423 | |
| 424 | // Route parser and verifier errors through clang's diagnostics. Parse |
| 425 | // errors point into the .cir input. Verifier errors use the location of |
| 426 | // the failing op, which for CIR emitted by CIRGen is a location in the |
| 427 | // original source file; that file is not loaded in the SourceManager, so |
| 428 | // the handler reports such errors with the original location as text. |
| 429 | // TODO: Decide where errors in CIRGen-produced input should point: at the |
| 430 | // .cir text, or at the original source. |
| 431 | CIRDiagnosticHandler DiagHandler(&MLIRContext, Diags, SM, |
| 432 | CI.getFileManager()); |
| 433 | |
| 434 | mlir::OwningOpRef<mlir::ModuleOp> Module = |
| 435 | mlir::parseSourceString<mlir::ModuleOp>(sourceStr: MainFile->getBuffer(), |
| 436 | config: mlir::ParserConfig(&MLIRContext), |
| 437 | sourceName: MainFile->getBufferIdentifier()); |
| 438 | if (!Module) { |
| 439 | if (!Diags.hasErrorOccurred()) |
| 440 | Diags.Report(DiagID: diag::err_invalid_cir); |
| 441 | return; |
| 442 | } |
| 443 | |
| 444 | // CIR is lowered for the target ABI of its own triple, so a module emitted |
| 445 | // for a different target cannot be retargeted by overriding its triple. |
| 446 | auto ModuleTriple = mlir::dyn_cast_if_present<mlir::StringAttr>( |
| 447 | Val: (*Module)->getAttr(name: cir::CIRDialect::getTripleAttrName())); |
| 448 | if (!ModuleTriple) { |
| 449 | Diags.Report(DiagID: diag::err_cir_input_missing_triple); |
| 450 | return; |
| 451 | } |
| 452 | const std::string &TargetTriple = CI.getTarget().getTriple().str(); |
| 453 | if (ModuleTriple.getValue() != TargetTriple) { |
| 454 | Diags.Report(DiagID: diag::err_cir_input_triple_mismatch) |
| 455 | << ModuleTriple.getValue() << TargetTriple; |
| 456 | return; |
| 457 | } |
| 458 | |
| 459 | // ClangIR input may already have been through the pipeline in an earlier |
| 460 | // invocation (e.g. -emit-cir). Its passes are safe to rerun, so run it whole. |
| 461 | if (runCIRPipeline(FEOpts: CI.getFrontendOpts(), CGO: CI.getCodeGenOpts(), MlirModule: *Module, |
| 462 | MlirCtx&: MLIRContext) |
| 463 | .failed()) { |
| 464 | if (!Diags.hasErrorOccurred()) |
| 465 | Diags.Report(DiagID: diag::err_cir_to_cir_transform_failed); |
| 466 | return; |
| 467 | } |
| 468 | BackendDiagnosticConsumer DiagConsumer(Diags, CI.getCodeGenOpts()); |
| 469 | DiagConsumer.setSourceManager(&SM); |
| 470 | emitCIRModuleOutput(Action, CI, MlirModule: *Module, LLVMCtx&: *Ctx, LinkModules, DiagConsumer, |
| 471 | OutputStream: std::move(OS)); |
| 472 | } |
| 473 | |
| 474 | static std::unique_ptr<raw_pwrite_stream> |
| 475 | getOutputStream(CompilerInstance &CI, StringRef InFile, |
| 476 | CIRGenAction::OutputType Action) { |
| 477 | switch (Action) { |
| 478 | case CIRGenAction::OutputType::EmitAssembly: |
| 479 | return CI.createDefaultOutputFile(Binary: false, BaseInput: InFile, Extension: "s" ); |
| 480 | case CIRGenAction::OutputType::EmitCIR: |
| 481 | return CI.createDefaultOutputFile(Binary: false, BaseInput: InFile, Extension: "cir" ); |
| 482 | case CIRGenAction::OutputType::EmitCIRBC: |
| 483 | return CI.createDefaultOutputFile(Binary: true, BaseInput: InFile, Extension: "cirbc" ); |
| 484 | case CIRGenAction::OutputType::EmitLLVM: |
| 485 | return CI.createDefaultOutputFile(Binary: false, BaseInput: InFile, Extension: "ll" ); |
| 486 | case CIRGenAction::OutputType::EmitBC: |
| 487 | return CI.createDefaultOutputFile(Binary: true, BaseInput: InFile, Extension: "bc" ); |
| 488 | case CIRGenAction::OutputType::EmitObj: |
| 489 | return CI.createDefaultOutputFile(Binary: true, BaseInput: InFile, Extension: "o" ); |
| 490 | } |
| 491 | llvm_unreachable("Invalid CIRGenAction::OutputType" ); |
| 492 | } |
| 493 | |
| 494 | std::unique_ptr<ASTConsumer> |
| 495 | CIRGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { |
| 496 | std::unique_ptr<llvm::raw_pwrite_stream> Out = CI.takeOutputStream(); |
| 497 | |
| 498 | if (!Out) |
| 499 | Out = getOutputStream(CI, InFile, Action); |
| 500 | |
| 501 | auto Result = std::make_unique<cir::CIRGenConsumer>( |
| 502 | args&: Action, args&: CI, args&: CI.getCodeGenOpts(), args: std::move(Out), args&: *Ctx, args&: LinkModules); |
| 503 | |
| 504 | return Result; |
| 505 | } |
| 506 | |
| 507 | void EmitAssemblyAction::anchor() {} |
| 508 | EmitAssemblyAction::EmitAssemblyAction() |
| 509 | : CIRGenAction(OutputType::EmitAssembly) {} |
| 510 | |
| 511 | void EmitCIRAction::anchor() {} |
| 512 | EmitCIRAction::EmitCIRAction() : CIRGenAction(OutputType::EmitCIR) {} |
| 513 | |
| 514 | void EmitCIRBCAction::anchor() {} |
| 515 | EmitCIRBCAction::EmitCIRBCAction() : CIRGenAction(OutputType::EmitCIRBC) {} |
| 516 | |
| 517 | void EmitLLVMAction::anchor() {} |
| 518 | EmitLLVMAction::EmitLLVMAction() : CIRGenAction(OutputType::EmitLLVM) {} |
| 519 | |
| 520 | void EmitBCAction::anchor() {} |
| 521 | EmitBCAction::EmitBCAction() : CIRGenAction(OutputType::EmitBC) {} |
| 522 | |
| 523 | void EmitObjAction::anchor() {} |
| 524 | EmitObjAction::EmitObjAction() : CIRGenAction(OutputType::EmitObj) {} |
| 525 | |