1//===--- CodeGenAction.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/CodeGen/CodeGenAction.h"
10#include "BackendConsumer.h"
11#include "CGCall.h"
12#include "CGDebugInfo.h"
13#include "CodeGenModule.h"
14#include "CoverageMappingGen.h"
15#include "MacroPPCallbacks.h"
16#include "clang/AST/ASTConsumer.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/DeclCXX.h"
19#include "clang/AST/DeclGroup.h"
20#include "clang/Basic/DiagnosticFrontend.h"
21#include "clang/Basic/FileManager.h"
22#include "clang/Basic/LangStandard.h"
23#include "clang/Basic/SourceManager.h"
24#include "clang/Basic/TargetInfo.h"
25#include "clang/CodeGen/BackendUtil.h"
26#include "clang/CodeGen/ModuleBuilder.h"
27#include "clang/Driver/DriverDiagnostic.h"
28#include "clang/Frontend/CompilerInstance.h"
29#include "clang/Frontend/MultiplexConsumer.h"
30#include "clang/Lex/Preprocessor.h"
31#include "clang/Serialization/ASTWriter.h"
32#include "llvm/ADT/ScopeExit.h"
33#include "llvm/Bitcode/BitcodeReader.h"
34#include "llvm/IR/DebugInfo.h"
35#include "llvm/IR/DiagnosticInfo.h"
36#include "llvm/IR/GlobalValue.h"
37#include "llvm/IR/LLVMContext.h"
38#include "llvm/IR/LLVMRemarkStreamer.h"
39#include "llvm/IR/Module.h"
40#include "llvm/IR/PassTimingInfo.h"
41#include "llvm/IR/Verifier.h"
42#include "llvm/IRReader/IRReader.h"
43#include "llvm/LTO/LTOBackend.h"
44#include "llvm/Pass.h"
45#include "llvm/Support/LibraryOptionsContext.h"
46#include "llvm/Support/ManagedStatic.h"
47#include "llvm/Support/MemoryBuffer.h"
48#include "llvm/Support/Mutex.h"
49#include "llvm/Support/SourceMgr.h"
50#include "llvm/Support/TimeProfiler.h"
51#include "llvm/Support/Timer.h"
52#include "llvm/Support/ToolOutputFile.h"
53#include "llvm/Transforms/Utils/Cloning.h"
54
55#include <optional>
56using namespace clang;
57using namespace llvm;
58
59#define DEBUG_TYPE "codegenaction"
60
61namespace {
62llvm::ManagedStatic<llvm::sys::SmartMutex<true>> TimePassesMutex;
63}
64
65namespace clang {
66
67static void reportOptRecordError(Error E, DiagnosticsEngine &Diags,
68 const CodeGenOptions &CodeGenOpts) {
69 handleAllErrors(
70 E: std::move(E),
71 Handlers: [&](const LLVMRemarkSetupFileError &E) {
72 Diags.Report(DiagID: diag::err_cannot_open_file)
73 << CodeGenOpts.OptRecordFile << E.message();
74 },
75 Handlers: [&](const LLVMRemarkSetupPatternError &E) {
76 Diags.Report(DiagID: diag::err_drv_optimization_remark_pattern)
77 << E.message() << CodeGenOpts.OptRecordPasses;
78 },
79 Handlers: [&](const LLVMRemarkSetupFormatError &E) {
80 Diags.Report(DiagID: diag::err_drv_optimization_remark_format)
81 << CodeGenOpts.OptRecordFormat;
82 });
83}
84
85BackendConsumer::BackendConsumer(CompilerInstance &CI, BackendAction Action,
86 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
87 LLVMContext &C,
88 SmallVector<LinkModule, 4> LinkModules,
89 StringRef InFile,
90 std::unique_ptr<raw_pwrite_stream> OS,
91 CoverageSourceInfo *CoverageInfo,
92 llvm::Module *CurLinkModule)
93 : CI(CI), Diags(CI.getDiagnostics()), CodeGenOpts(CI.getCodeGenOpts()),
94 TargetOpts(CI.getTargetOpts()), LangOpts(CI.getLangOpts()),
95 AsmOutStream(std::move(OS)), FS(VFS), Action(Action),
96 Gen(CreateLLVMCodeGen(CI, ModuleName: InFile, C, CoverageInfo)),
97 LinkModules(std::move(LinkModules)), DiagConsumer(Diags, CodeGenOpts) {
98 DiagConsumer.setCurLinkModule(CurLinkModule);
99 TimerIsEnabled = CodeGenOpts.TimePasses;
100 {
101 llvm::sys::SmartScopedLock<true> Lock(*TimePassesMutex);
102 llvm::TimePassesIsEnabled = CodeGenOpts.TimePasses;
103 llvm::TimePassesPerRun = CodeGenOpts.TimePassesPerRun;
104 }
105 if (CodeGenOpts.TimePasses)
106 LLVMIRGeneration.init(TimerName: "irgen", TimerDescription: "LLVM IR generation", tg&: CI.getTimerGroup());
107}
108
109llvm::Module* BackendConsumer::getModule() const {
110 return Gen->GetModule();
111}
112
113std::unique_ptr<llvm::Module> BackendConsumer::takeModule() {
114 return std::unique_ptr<llvm::Module>(Gen->ReleaseModule());
115}
116
117CodeGenerator* BackendConsumer::getCodeGenerator() {
118 return Gen.get();
119}
120
121void BackendConsumer::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
122 Gen->HandleCXXStaticMemberVarInstantiation(D: VD);
123}
124
125void BackendConsumer::Initialize(ASTContext &Ctx) {
126 assert(!Context && "initialized multiple times");
127
128 Context = &Ctx;
129 DiagConsumer.setSourceManager(&Ctx.getSourceManager());
130
131 if (TimerIsEnabled)
132 LLVMIRGeneration.startTimer();
133
134 Gen->Initialize(Context&: Ctx);
135
136 if (TimerIsEnabled)
137 LLVMIRGeneration.stopTimer();
138}
139
140bool BackendConsumer::HandleTopLevelDecl(DeclGroupRef D) {
141 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
142 Context->getSourceManager(),
143 "LLVM IR generation of declaration");
144
145 // Recurse.
146 if (TimerIsEnabled && !LLVMIRGenerationRefCount++)
147 CI.getFrontendTimer().yieldTo(LLVMIRGeneration);
148
149 Gen->HandleTopLevelDecl(D);
150
151 if (TimerIsEnabled && !--LLVMIRGenerationRefCount)
152 LLVMIRGeneration.yieldTo(CI.getFrontendTimer());
153
154 return true;
155}
156
157void BackendConsumer::HandleInlineFunctionDefinition(FunctionDecl *D) {
158 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
159 Context->getSourceManager(),
160 "LLVM IR generation of inline function");
161 if (TimerIsEnabled)
162 CI.getFrontendTimer().yieldTo(LLVMIRGeneration);
163
164 Gen->HandleInlineFunctionDefinition(D);
165
166 if (TimerIsEnabled)
167 LLVMIRGeneration.yieldTo(CI.getFrontendTimer());
168}
169
170void BackendConsumer::HandleInterestingDecl(DeclGroupRef D) {
171 HandleTopLevelDecl(D);
172}
173
174// Links each entry in LinkModules into our module. Returns true on error.
175bool BackendConsumer::LinkInModules(llvm::Module *M) {
176 // Builtin bitcode is internalized into the module that links it, so each
177 // PTU of an incremental session needs its own copy. Plain bitcode files are
178 // still linked once.
179 if (LangOpts.IncrementalExtensions && LinkModules.empty() &&
180 loadLinkModules(CI, Ctx&: M->getContext(), LinkModules,
181 /*OnlyInternalized=*/true))
182 return true;
183
184 return linkInModules(M&: *M, LinkModules, CodeGenOpts, LangOpts, TargetOpts,
185 DiagConsumer);
186}
187
188void BackendConsumer::HandleTranslationUnit(ASTContext &C) {
189 {
190 llvm::TimeTraceScope TimeScope("Frontend");
191 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
192 if (TimerIsEnabled && !LLVMIRGenerationRefCount++)
193 CI.getFrontendTimer().yieldTo(LLVMIRGeneration);
194
195 Gen->HandleTranslationUnit(Ctx&: C);
196
197 if (TimerIsEnabled && !--LLVMIRGenerationRefCount)
198 LLVMIRGeneration.yieldTo(CI.getFrontendTimer());
199 }
200
201 // Silently ignore if we weren't initialized for some reason.
202 if (!getModule())
203 return;
204
205 LLVMContext &Ctx = getModule()->getContext();
206 std::unique_ptr<DiagnosticHandler> OldDiagnosticHandler =
207 Ctx.getDiagnosticHandler();
208 llvm::scope_exit RestoreDiagnosticHandler(
209 [&]() { Ctx.setDiagnosticHandler(DH: std::move(OldDiagnosticHandler)); });
210 Ctx.setDiagnosticHandler(DH: createDiagnosticHandler());
211
212 Ctx.setDefaultTargetCPU(TargetOpts.CPU);
213 Ctx.setDefaultTargetFeatures(llvm::join(R: TargetOpts.Features, Separator: ","));
214 Ctx.setVirtualFileSystem(CI.getVirtualFileSystemPtr());
215
216 Expected<LLVMRemarkFileHandle> OptRecordFileOrErr =
217 setupLLVMOptimizationRemarks(
218 Context&: Ctx, RemarksFilename: CodeGenOpts.OptRecordFile, RemarksPasses: CodeGenOpts.OptRecordPasses,
219 RemarksFormat: CodeGenOpts.OptRecordFormat, RemarksWithHotness: CodeGenOpts.DiagnosticsWithHotness,
220 RemarksHotnessThreshold: CodeGenOpts.DiagnosticsHotnessThreshold);
221
222 if (Error E = OptRecordFileOrErr.takeError()) {
223 reportOptRecordError(E: std::move(E), Diags, CodeGenOpts);
224 return;
225 }
226
227 LLVMRemarkFileHandle OptRecordFile = std::move(*OptRecordFileOrErr);
228
229 if (OptRecordFile && CodeGenOpts.getProfileUse() !=
230 llvm::driver::ProfileInstrKind::ProfileNone)
231 Ctx.setDiagnosticsHotnessRequested(true);
232
233 if (CodeGenOpts.MisExpect) {
234 Ctx.setMisExpectWarningRequested(true);
235 }
236
237 if (CodeGenOpts.DiagnosticsMisExpectTolerance) {
238 Ctx.setDiagnosticsMisExpectTolerance(
239 CodeGenOpts.DiagnosticsMisExpectTolerance);
240 }
241
242 // Link each LinkModule into our module.
243 if (!CodeGenOpts.LinkBitcodePostopt && LinkInModules(M: getModule()))
244 return;
245
246 for (auto &F : getModule()->functions()) {
247 if (const Decl *FD = Gen->GetDeclForMangledName(MangledName: F.getName())) {
248 auto Loc = FD->getASTContext().getFullLoc(Loc: FD->getLocation());
249 DiagConsumer.addFunctionSourceLocation(MangledName: F.getName(), Loc);
250 }
251 }
252 if (CodeGen::CGDebugInfo *DI = Gen->CGM().getModuleDebugInfo())
253 DiagConsumer.setDIFileSources(DI->getDIFileSources());
254
255 if (CodeGenOpts.ClearASTBeforeBackend) {
256 LLVM_DEBUG(llvm::dbgs() << "Clearing AST...\n");
257 // Access to the AST is no longer available after this.
258 // Other things that the ASTContext manages are still available, e.g.
259 // the SourceManager. It'd be nice if we could separate out all the
260 // things in ASTContext used after this point and null out the
261 // ASTContext, but too many various parts of the ASTContext are still
262 // used in various parts.
263 C.cleanup();
264 C.getAllocator().Reset();
265 }
266
267 EmbedBitcode(M: getModule(), CGOpts: CodeGenOpts, Buf: llvm::MemoryBufferRef());
268
269 emitBackendOutput(CI, CGOpts&: CI.getCodeGenOpts(), M: getModule(), Action, VFS: FS,
270 OS: std::move(AsmOutStream), BC: this);
271
272 if (OptRecordFile)
273 OptRecordFile->keep();
274}
275
276void BackendConsumer::HandleTagDeclDefinition(TagDecl *D) {
277 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
278 Context->getSourceManager(),
279 "LLVM IR generation of declaration");
280 Gen->HandleTagDeclDefinition(D);
281}
282
283void BackendConsumer::HandleTagDeclRequiredDefinition(const TagDecl *D) {
284 Gen->HandleTagDeclRequiredDefinition(D);
285}
286
287void BackendConsumer::CompleteTentativeDefinition(VarDecl *D) {
288 Gen->CompleteTentativeDefinition(D);
289}
290
291void BackendConsumer::CompleteExternalDeclaration(DeclaratorDecl *D) {
292 Gen->CompleteExternalDeclaration(D);
293}
294
295void BackendConsumer::AssignInheritanceModel(CXXRecordDecl *RD) {
296 Gen->AssignInheritanceModel(RD);
297}
298
299void BackendConsumer::HandleVTable(CXXRecordDecl *RD) {
300 Gen->HandleVTable(RD);
301}
302
303void BackendConsumer::anchor() { }
304
305} // namespace clang
306
307std::unique_ptr<llvm::DiagnosticHandler>
308BackendConsumer::createDiagnosticHandler() {
309 return DiagConsumer.createDiagnosticHandler();
310}
311
312CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
313 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
314 OwnsVMContext(!_VMContext) {}
315
316CodeGenAction::~CodeGenAction() {
317 TheModule.reset();
318 if (OwnsVMContext)
319 delete VMContext;
320}
321
322bool CodeGenAction::hasIRSupport() const { return true; }
323
324void CodeGenAction::EndSourceFileAction() {
325 ASTFrontendAction::EndSourceFileAction();
326
327 // If the consumer creation failed, do nothing.
328 if (!getCompilerInstance().hasASTConsumer())
329 return;
330
331 // Steal the module from the consumer.
332 TheModule = BEConsumer->takeModule();
333}
334
335std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
336 return std::move(TheModule);
337}
338
339llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
340 OwnsVMContext = false;
341 return VMContext;
342}
343
344CodeGenerator *CodeGenAction::getCodeGenerator() const {
345 return BEConsumer->getCodeGenerator();
346}
347
348bool CodeGenAction::BeginSourceFileAction(CompilerInstance &CI) {
349 VMContext->getLibraryOptions().assign(Other: CI.getLibraryOptions());
350 if (CI.getFrontendOpts().GenReducedBMI)
351 CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleInterface);
352 return ASTFrontendAction::BeginSourceFileAction(CI);
353}
354
355static std::unique_ptr<raw_pwrite_stream>
356GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
357 switch (Action) {
358 case Backend_EmitAssembly:
359 return CI.createDefaultOutputFile(Binary: false, BaseInput: InFile, Extension: "s");
360 case Backend_EmitLL:
361 return CI.createDefaultOutputFile(Binary: false, BaseInput: InFile, Extension: "ll");
362 case Backend_EmitBC:
363 return CI.createDefaultOutputFile(Binary: true, BaseInput: InFile, Extension: "bc");
364 case Backend_EmitNothing:
365 return nullptr;
366 case Backend_EmitMCNull:
367 return CI.createNullOutputFile();
368 case Backend_EmitObj:
369 return CI.createDefaultOutputFile(Binary: true, BaseInput: InFile, Extension: "o");
370 }
371
372 llvm_unreachable("Invalid action!");
373}
374
375std::unique_ptr<ASTConsumer>
376CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
377 BackendAction BA = static_cast<BackendAction>(Act);
378 std::unique_ptr<raw_pwrite_stream> OS = CI.takeOutputStream();
379 if (!OS)
380 OS = GetOutputStream(CI, InFile, Action: BA);
381
382 if (BA != Backend_EmitNothing && !OS)
383 return nullptr;
384
385 // Load bitcode modules to link with, if we need to.
386 if (clang::loadLinkModules(CI, Ctx&: *VMContext, LinkModules,
387 /*OnlyInternalized=*/false))
388 return nullptr;
389
390 CoverageSourceInfo *CoverageInfo = nullptr;
391 // Add the preprocessor callback only when the coverage mapping is generated.
392 if (CI.getCodeGenOpts().CoverageMapping)
393 CoverageInfo = CodeGen::CoverageMappingModuleGen::setUpCoverageCallbacks(
394 CI.getPreprocessor());
395
396 std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
397 CI, BA, CI.getVirtualFileSystemPtr(), *VMContext, std::move(LinkModules),
398 InFile, std::move(OS), CoverageInfo));
399 BEConsumer = Result.get();
400
401 // Enable generating macro debug info only when debug info is not disabled and
402 // also macro debug info is enabled.
403 if (CI.getCodeGenOpts().getDebugInfo() != codegenoptions::NoDebugInfo &&
404 CI.getCodeGenOpts().MacroDebugInfo) {
405 std::unique_ptr<PPCallbacks> Callbacks =
406 std::make_unique<MacroPPCallbacks>(args: BEConsumer->getCodeGenerator(),
407 args&: CI.getPreprocessor());
408 CI.getPreprocessor().addPPCallbacks(C: std::move(Callbacks));
409 }
410
411 if (CI.getFrontendOpts().GenReducedBMI &&
412 !CI.getFrontendOpts().ModuleOutputPath.empty()) {
413 std::vector<std::unique_ptr<ASTConsumer>> Consumers(2);
414 Consumers[0] = std::make_unique<ReducedBMIGenerator>(
415 args&: CI.getPreprocessor(), args&: CI.getModuleCache(),
416 args&: CI.getFrontendOpts().ModuleOutputPath, args&: CI.getCodeGenOpts());
417 Consumers[1] = std::move(Result);
418 return std::make_unique<MultiplexConsumer>(args: std::move(Consumers));
419 }
420
421 return std::move(Result);
422}
423
424std::unique_ptr<llvm::Module>
425CodeGenAction::loadModule(MemoryBufferRef MBRef) {
426 CompilerInstance &CI = getCompilerInstance();
427 SourceManager &SM = CI.getSourceManager();
428
429 auto DiagErrors = [&](Error E) -> std::unique_ptr<llvm::Module> {
430 unsigned DiagID =
431 CI.getDiagnostics().getCustomDiagID(L: DiagnosticsEngine::Error, FormatString: "%0");
432 handleAllErrors(E: std::move(E), Handlers: [&](ErrorInfoBase &EIB) {
433 CI.getDiagnostics().Report(DiagID) << EIB.message();
434 });
435 return {};
436 };
437
438 // For ThinLTO backend invocations, ensure that the context
439 // merges types based on ODR identifiers. We also need to read
440 // the correct module out of a multi-module bitcode file.
441 if (!CI.getCodeGenOpts().ThinLTOIndexFile.empty()) {
442 VMContext->enableDebugTypeODRUniquing();
443
444 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(Buffer: MBRef);
445 if (!BMsOrErr)
446 return DiagErrors(BMsOrErr.takeError());
447 BitcodeModule *Bm = llvm::lto::findThinLTOModule(BMs: *BMsOrErr);
448 // We have nothing to do if the file contains no ThinLTO module. This is
449 // possible if ThinLTO compilation was not able to split module. Content of
450 // the file was already processed by indexing and will be passed to the
451 // linker using merged object file.
452 if (!Bm) {
453 auto M = std::make_unique<llvm::Module>(args: "empty", args&: *VMContext);
454 M->setTargetTriple(Triple(CI.getTargetOpts().Triple));
455 return M;
456 }
457 Expected<std::unique_ptr<llvm::Module>> MOrErr =
458 Bm->parseModule(Context&: *VMContext);
459 if (!MOrErr)
460 return DiagErrors(MOrErr.takeError());
461 return std::move(*MOrErr);
462 }
463
464 // Load bitcode modules to link with, if we need to.
465 if (clang::loadLinkModules(CI, Ctx&: *VMContext, LinkModules,
466 /*OnlyInternalized=*/false))
467 return nullptr;
468
469 // Handle textual IR and bitcode file with one single module.
470 llvm::SMDiagnostic Err;
471 if (std::unique_ptr<llvm::Module> M = parseIR(Buffer: MBRef, Err, Context&: *VMContext)) {
472 // For LLVM IR files, always verify the input and report the error in a way
473 // that does not ask people to report an issue for it.
474 std::string VerifierErr;
475 raw_string_ostream VerifierErrStream(VerifierErr);
476 if (llvm::verifyModule(M: *M, OS: &VerifierErrStream)) {
477 CI.getDiagnostics().Report(DiagID: diag::err_invalid_llvm_ir) << VerifierErr;
478 return {};
479 }
480 return M;
481 }
482
483 // If MBRef is a bitcode with multiple modules (e.g., -fsplit-lto-unit
484 // output), place the extra modules (actually only one, a regular LTO module)
485 // into LinkModules as if we are using -mlink-bitcode-file.
486 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(Buffer: MBRef);
487 if (BMsOrErr && BMsOrErr->size()) {
488 std::unique_ptr<llvm::Module> FirstM;
489 for (auto &BM : *BMsOrErr) {
490 Expected<std::unique_ptr<llvm::Module>> MOrErr =
491 BM.parseModule(Context&: *VMContext);
492 if (!MOrErr)
493 return DiagErrors(MOrErr.takeError());
494 if (FirstM)
495 LinkModules.push_back(Elt: {.Module: std::move(*MOrErr), /*PropagateAttrs=*/false,
496 /*Internalize=*/false, /*LinkFlags=*/{}});
497 else
498 FirstM = std::move(*MOrErr);
499 }
500 if (FirstM)
501 return FirstM;
502 }
503 // If BMsOrErr fails, consume the error and use the error message from
504 // parseIR.
505 consumeError(Err: BMsOrErr.takeError());
506
507 // Translate from the diagnostic info to the SourceManager location if
508 // available.
509 // TODO: Unify this with ConvertBackendLocation()
510 SourceLocation Loc;
511 if (Err.getLineNo() > 0) {
512 assert(Err.getColumnNo() >= 0);
513 Loc = SM.translateFileLineCol(SourceFile: SM.getFileEntryForID(FID: SM.getMainFileID()),
514 Line: Err.getLineNo(), Col: Err.getColumnNo() + 1);
515 }
516
517 // Strip off a leading diagnostic code if there is one.
518 StringRef Msg = Err.getMessage();
519 Msg.consume_front(Prefix: "error: ");
520
521 unsigned DiagID =
522 CI.getDiagnostics().getCustomDiagID(L: DiagnosticsEngine::Error, FormatString: "%0");
523
524 CI.getDiagnostics().Report(Loc, DiagID) << Msg;
525 return {};
526}
527
528void CodeGenAction::ExecuteAction() {
529 if (getCurrentFileKind().getLanguage() != Language::LLVM_IR) {
530 this->ASTFrontendAction::ExecuteAction();
531 return;
532 }
533
534 // If this is an IR file, we have to treat it specially.
535 BackendAction BA = static_cast<BackendAction>(Act);
536 CompilerInstance &CI = getCompilerInstance();
537 auto &CodeGenOpts = CI.getCodeGenOpts();
538 auto &Diagnostics = CI.getDiagnostics();
539 std::unique_ptr<raw_pwrite_stream> OS =
540 GetOutputStream(CI, InFile: getCurrentFileOrBufferName(), Action: BA);
541 if (BA != Backend_EmitNothing && !OS)
542 return;
543
544 SourceManager &SM = CI.getSourceManager();
545 FileID FID = SM.getMainFileID();
546 std::optional<MemoryBufferRef> MainFile = SM.getBufferOrNone(FID);
547 if (!MainFile)
548 return;
549
550 TheModule = loadModule(MBRef: *MainFile);
551 if (!TheModule)
552 return;
553
554 const TargetOptions &TargetOpts = CI.getTargetOpts();
555 if (TheModule->getTargetTriple().str() != TargetOpts.Triple) {
556 Diagnostics.Report(Loc: SourceLocation(), DiagID: diag::warn_fe_override_module)
557 << TargetOpts.Triple;
558 TheModule->setTargetTriple(Triple(TargetOpts.Triple));
559 }
560
561 llvm::ExceptionHandling ExceptionModel =
562 CodeGenOptions::toExceptionHandling(Kind: CodeGenOpts.getExceptionHandling());
563 if (ExceptionModel != llvm::ExceptionHandling::Default) {
564 StringRef ModelName = llvm::getExceptionModelName(EH: ExceptionModel);
565 if (auto *Existing = cast_or_null<llvm::MDString>(
566 Val: TheModule->getModuleFlag(Key: "exception-model"))) {
567 if (Existing->getString() != ModelName) {
568 Diagnostics.Report(DiagID: diag::err_fe_exception_model_mismatch)
569 << ModelName << Existing->getString();
570 return;
571 }
572 } else {
573 TheModule->addModuleFlag(
574 Behavior: llvm::Module::Error, Key: "exception-model",
575 Val: llvm::MDString::get(Context&: TheModule->getContext(), Str: ModelName));
576 }
577 }
578
579 EmbedObject(M: TheModule.get(), CGOpts: CodeGenOpts, VFS&: CI.getVirtualFileSystem(),
580 Diags&: Diagnostics);
581 EmbedBitcode(M: TheModule.get(), CGOpts: CodeGenOpts, Buf: *MainFile);
582
583 LLVMContext &Ctx = TheModule->getContext();
584
585 // Restore any diagnostic handler previously set before returning from this
586 // function.
587 struct RAII {
588 LLVMContext &Ctx;
589 std::unique_ptr<DiagnosticHandler> PrevHandler = Ctx.getDiagnosticHandler();
590 ~RAII() { Ctx.setDiagnosticHandler(DH: std::move(PrevHandler)); }
591 } _{.Ctx: Ctx};
592
593 // Set clang diagnostic handler. To do this we need to create a fake
594 // BackendConsumer.
595 BackendConsumer Result(CI, BA, CI.getVirtualFileSystemPtr(), *VMContext,
596 std::move(LinkModules), "", nullptr, nullptr,
597 TheModule.get());
598
599 // Link in each pending link module.
600 if (!CodeGenOpts.LinkBitcodePostopt && Result.LinkInModules(M: &*TheModule))
601 return;
602
603 // Textual IR needs value names while parsing; discard new names afterwards.
604 Ctx.setDiscardValueNames(CodeGenOpts.DiscardValueNames);
605 Ctx.setDiagnosticHandler(DH: Result.createDiagnosticHandler());
606
607 Ctx.setDefaultTargetCPU(TargetOpts.CPU);
608 Ctx.setDefaultTargetFeatures(llvm::join(R: TargetOpts.Features, Separator: ","));
609 Ctx.setVirtualFileSystem(CI.getVirtualFileSystemPtr());
610
611 Expected<LLVMRemarkFileHandle> OptRecordFileOrErr =
612 setupLLVMOptimizationRemarks(
613 Context&: Ctx, RemarksFilename: CodeGenOpts.OptRecordFile, RemarksPasses: CodeGenOpts.OptRecordPasses,
614 RemarksFormat: CodeGenOpts.OptRecordFormat, RemarksWithHotness: CodeGenOpts.DiagnosticsWithHotness,
615 RemarksHotnessThreshold: CodeGenOpts.DiagnosticsHotnessThreshold);
616
617 if (Error E = OptRecordFileOrErr.takeError()) {
618 reportOptRecordError(E: std::move(E), Diags&: Diagnostics, CodeGenOpts);
619 return;
620 }
621 LLVMRemarkFileHandle OptRecordFile = std::move(*OptRecordFileOrErr);
622
623 emitBackendOutput(CI, CGOpts&: CI.getCodeGenOpts(), M: TheModule.get(), Action: BA,
624 VFS: CI.getFileManager().getVirtualFileSystemPtr(),
625 OS: std::move(OS));
626 if (OptRecordFile)
627 OptRecordFile->keep();
628}
629
630//
631
632void EmitAssemblyAction::anchor() { }
633EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
634 : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
635
636void EmitBCAction::anchor() { }
637EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
638 : CodeGenAction(Backend_EmitBC, _VMContext) {}
639
640void EmitLLVMAction::anchor() { }
641EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
642 : CodeGenAction(Backend_EmitLL, _VMContext) {}
643
644void EmitLLVMOnlyAction::anchor() { }
645EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
646 : CodeGenAction(Backend_EmitNothing, _VMContext) {}
647
648void EmitCodeGenOnlyAction::anchor() { }
649EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
650 : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
651
652void EmitObjAction::anchor() { }
653EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
654 : CodeGenAction(Backend_EmitObj, _VMContext) {}
655