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