clang 24.0.0git
CodeGenAction.cpp
Go to the documentation of this file.
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
10#include "BackendConsumer.h"
11#include "CGCall.h"
12#include "CGDebugInfo.h"
13#include "CodeGenCLOptions.h"
14#include "CodeGenModule.h"
15#include "CoverageMappingGen.h"
16#include "MacroPPCallbacks.h"
19#include "clang/AST/DeclCXX.h"
20#include "clang/AST/DeclGroup.h"
33#include "llvm/ADT/ScopeExit.h"
34#include "llvm/Bitcode/BitcodeReader.h"
35#include "llvm/IR/DebugInfo.h"
36#include "llvm/IR/DiagnosticInfo.h"
37#include "llvm/IR/GlobalValue.h"
38#include "llvm/IR/LLVMContext.h"
39#include "llvm/IR/LLVMRemarkStreamer.h"
40#include "llvm/IR/Module.h"
41#include "llvm/IR/PassTimingInfo.h"
42#include "llvm/IR/Verifier.h"
43#include "llvm/IRReader/IRReader.h"
44#include "llvm/LTO/LTOBackend.h"
45#include "llvm/Pass.h"
46#include "llvm/Support/LibraryOptionsContext.h"
47#include "llvm/Support/ManagedStatic.h"
48#include "llvm/Support/MemoryBuffer.h"
49#include "llvm/Support/Mutex.h"
50#include "llvm/Support/SourceMgr.h"
51#include "llvm/Support/TimeProfiler.h"
52#include "llvm/Support/Timer.h"
53#include "llvm/Support/ToolOutputFile.h"
54#include "llvm/Transforms/Utils/Cloning.h"
55
56#include <optional>
57using namespace clang;
58using namespace llvm;
59
60#define DEBUG_TYPE "codegenaction"
61
62namespace {
63llvm::ManagedStatic<llvm::sys::SmartMutex<true>> TimePassesMutex;
64}
65
66namespace clang {
67
69 const CodeGenOptions &CodeGenOpts) {
70 handleAllErrors(
71 std::move(E),
72 [&](const LLVMRemarkSetupFileError &E) {
73 Diags.Report(diag::err_cannot_open_file)
74 << CodeGenOpts.OptRecordFile << E.message();
75 },
76 [&](const LLVMRemarkSetupPatternError &E) {
77 Diags.Report(diag::err_drv_optimization_remark_pattern)
78 << E.message() << CodeGenOpts.OptRecordPasses;
79 },
80 [&](const LLVMRemarkSetupFormatError &E) {
81 Diags.Report(diag::err_drv_optimization_remark_format)
82 << CodeGenOpts.OptRecordFormat;
83 });
84}
85
88 LLVMContext &C,
90 StringRef InFile,
91 std::unique_ptr<raw_pwrite_stream> OS,
92 CoverageSourceInfo *CoverageInfo,
93 llvm::Module *CurLinkModule)
94 : CI(CI), Diags(CI.getDiagnostics()), CodeGenOpts(CI.getCodeGenOpts()),
95 TargetOpts(CI.getTargetOpts()), LangOpts(CI.getLangOpts()),
96 AsmOutStream(std::move(OS)), FS(VFS), Action(Action),
97 Gen(CreateLLVMCodeGen(CI, InFile, C, CoverageInfo)),
98 LinkModules(std::move(LinkModules)), DiagConsumer(Diags, CodeGenOpts) {
99 DiagConsumer.setCurLinkModule(CurLinkModule);
100 TimerIsEnabled = CodeGenOpts.TimePasses;
101 {
102 llvm::sys::SmartScopedLock<true> Lock(*TimePassesMutex);
103 llvm::TimePassesIsEnabled = CodeGenOpts.TimePasses;
104 llvm::TimePassesPerRun = CodeGenOpts.TimePassesPerRun;
105 }
106 if (CodeGenOpts.TimePasses)
107 LLVMIRGeneration.init("irgen", "LLVM IR generation", CI.getTimerGroup());
108}
109
110llvm::Module* BackendConsumer::getModule() const {
111 return Gen->GetModule();
112}
113
114std::unique_ptr<llvm::Module> BackendConsumer::takeModule() {
115 return std::unique_ptr<llvm::Module>(Gen->ReleaseModule());
116}
117
119 return Gen.get();
120}
121
125
127 assert(!Context && "initialized multiple times");
128
129 Context = &Ctx;
130 DiagConsumer.setSourceManager(&Ctx.getSourceManager());
131
132 if (TimerIsEnabled)
133 LLVMIRGeneration.startTimer();
134
135 Gen->Initialize(Ctx);
136
137 if (TimerIsEnabled)
138 LLVMIRGeneration.stopTimer();
139}
140
142 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
143 Context->getSourceManager(),
144 "LLVM IR generation of declaration");
145
146 // Recurse.
147 if (TimerIsEnabled && !LLVMIRGenerationRefCount++)
148 CI.getFrontendTimer().yieldTo(LLVMIRGeneration);
149
150 Gen->HandleTopLevelDecl(D);
151
152 if (TimerIsEnabled && !--LLVMIRGenerationRefCount)
153 LLVMIRGeneration.yieldTo(CI.getFrontendTimer());
154
155 return true;
156}
157
160 Context->getSourceManager(),
161 "LLVM IR generation of inline function");
162 if (TimerIsEnabled)
163 CI.getFrontendTimer().yieldTo(LLVMIRGeneration);
164
165 Gen->HandleInlineFunctionDefinition(D);
166
167 if (TimerIsEnabled)
168 LLVMIRGeneration.yieldTo(CI.getFrontendTimer());
169}
170
174
175// Links each entry in LinkModules into our module. Returns true on error.
176bool BackendConsumer::LinkInModules(llvm::Module *M) {
177 // Builtin bitcode is internalized into the module that links it, so each
178 // PTU of an incremental session needs its own copy. Plain bitcode files are
179 // still linked once.
180 if (LangOpts.IncrementalExtensions && LinkModules.empty() &&
181 loadLinkModules(CI, M->getContext(), LinkModules,
182 /*OnlyInternalized=*/true))
183 return true;
184
185 return linkInModules(*M, LinkModules, CodeGenOpts, LangOpts, TargetOpts,
186 DiagConsumer);
187}
188
190 {
191 llvm::TimeTraceScope TimeScope("Frontend");
192 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
193 if (TimerIsEnabled && !LLVMIRGenerationRefCount++)
194 CI.getFrontendTimer().yieldTo(LLVMIRGeneration);
195
196 Gen->HandleTranslationUnit(C);
197
198 if (TimerIsEnabled && !--LLVMIRGenerationRefCount)
199 LLVMIRGeneration.yieldTo(CI.getFrontendTimer());
200 }
201
202 // Silently ignore if we weren't initialized for some reason.
203 if (!getModule())
204 return;
205
206 LLVMContext &Ctx = getModule()->getContext();
207 std::unique_ptr<DiagnosticHandler> OldDiagnosticHandler =
208 Ctx.getDiagnosticHandler();
209 llvm::scope_exit RestoreDiagnosticHandler(
210 [&]() { Ctx.setDiagnosticHandler(std::move(OldDiagnosticHandler)); });
211 Ctx.setDiagnosticHandler(createDiagnosticHandler());
212
213 Ctx.setDefaultTargetCPU(TargetOpts.CPU);
214 Ctx.setDefaultTargetFeatures(llvm::join(TargetOpts.Features, ","));
215 Ctx.setVirtualFileSystem(CI.getVirtualFileSystemPtr());
216
217 Expected<LLVMRemarkFileHandle> OptRecordFileOrErr =
218 setupLLVMOptimizationRemarks(
219 Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,
220 CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,
221 CodeGenOpts.DiagnosticsHotnessThreshold);
222
223 if (Error E = OptRecordFileOrErr.takeError()) {
224 reportOptRecordError(std::move(E), Diags, CodeGenOpts);
225 return;
226 }
227
228 LLVMRemarkFileHandle OptRecordFile = std::move(*OptRecordFileOrErr);
229
230 if (OptRecordFile && CodeGenOpts.getProfileUse() !=
231 llvm::driver::ProfileInstrKind::ProfileNone)
232 Ctx.setDiagnosticsHotnessRequested(true);
233
234 if (CodeGenOpts.MisExpect) {
235 Ctx.setMisExpectWarningRequested(true);
236 }
237
238 if (CodeGenOpts.DiagnosticsMisExpectTolerance) {
239 Ctx.setDiagnosticsMisExpectTolerance(
240 CodeGenOpts.DiagnosticsMisExpectTolerance);
241 }
242
243 // Link each LinkModule into our module.
244 if (!CodeGenOpts.LinkBitcodePostopt && LinkInModules(getModule()))
245 return;
246
247 for (auto &F : getModule()->functions()) {
248 if (const Decl *FD = Gen->GetDeclForMangledName(F.getName())) {
249 auto Loc = FD->getASTContext().getFullLoc(FD->getLocation());
250 DiagConsumer.addFunctionSourceLocation(F.getName(), Loc);
251 }
252 }
253 if (CodeGen::CGDebugInfo *DI = Gen->CGM().getModuleDebugInfo())
254 DiagConsumer.setDIFileSources(DI->getDIFileSources());
255
256 if (CodeGenOpts.ClearASTBeforeBackend) {
257 LLVM_DEBUG(llvm::dbgs() << "Clearing AST...\n");
258 // Access to the AST is no longer available after this.
259 // Other things that the ASTContext manages are still available, e.g.
260 // the SourceManager. It'd be nice if we could separate out all the
261 // things in ASTContext used after this point and null out the
262 // ASTContext, but too many various parts of the ASTContext are still
263 // used in various parts.
264 C.cleanup();
265 C.getAllocator().Reset();
266 }
267
268 EmbedBitcode(getModule(), CodeGenOpts, llvm::MemoryBufferRef());
269
270 emitBackendOutput(CI, CI.getCodeGenOpts(), getModule(), Action, FS,
271 std::move(AsmOutStream), this);
272
273 if (OptRecordFile)
274 OptRecordFile->keep();
275}
276
279 Context->getSourceManager(),
280 "LLVM IR generation of declaration");
281 Gen->HandleTagDeclDefinition(D);
282}
283
285 Gen->HandleTagDeclRequiredDefinition(D);
286}
287
289 Gen->CompleteTentativeDefinition(D);
290}
291
293 Gen->CompleteExternalDeclaration(D);
294}
295
297 Gen->AssignInheritanceModel(RD);
298}
299
301 Gen->HandleVTable(RD);
302}
303
304void BackendConsumer::anchor() { }
305
306} // namespace clang
307
308std::unique_ptr<llvm::DiagnosticHandler>
310 return DiagConsumer.createDiagnosticHandler();
311}
312
313CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
314 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
315 OwnsVMContext(!_VMContext) {}
316
318 TheModule.reset();
319 if (OwnsVMContext)
320 delete VMContext;
321}
322
323bool CodeGenAction::hasIRSupport() const { return true; }
324
327
328 // If the consumer creation failed, do nothing.
329 if (!getCompilerInstance().hasASTConsumer())
330 return;
331
332 // Steal the module from the consumer.
333 TheModule = BEConsumer->takeModule();
334}
335
336std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
337 return std::move(TheModule);
338}
339
340llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
341 OwnsVMContext = false;
342 return VMContext;
343}
344
346 return BEConsumer->getCodeGenerator();
347}
348
350 VMContext->getLibraryOptions().assign(CI.getLibraryOptions());
352 CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleInterface);
354}
355
356static std::unique_ptr<raw_pwrite_stream>
357GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
358 switch (Action) {
360 return CI.createDefaultOutputFile(false, InFile, "s");
361 case Backend_EmitLL:
362 return CI.createDefaultOutputFile(false, InFile, "ll");
363 case Backend_EmitBC:
364 return CI.createDefaultOutputFile(true, InFile, "bc");
366 return nullptr;
368 return CI.createNullOutputFile();
369 case Backend_EmitObj:
370 return CI.createDefaultOutputFile(true, InFile, "o");
371 }
372
373 llvm_unreachable("Invalid action!");
374}
375
376std::unique_ptr<ASTConsumer>
378 BackendAction BA = static_cast<BackendAction>(Act);
379 std::unique_ptr<raw_pwrite_stream> OS = CI.takeOutputStream();
380 if (!OS)
381 OS = GetOutputStream(CI, InFile, BA);
382
383 if (BA != Backend_EmitNothing && !OS)
384 return nullptr;
385
386 // Load bitcode modules to link with, if we need to.
387 if (clang::loadLinkModules(CI, *VMContext, LinkModules,
388 /*OnlyInternalized=*/false))
389 return nullptr;
390
391 CoverageSourceInfo *CoverageInfo = nullptr;
392 // Add the preprocessor callback only when the coverage mapping is generated.
393 if (CI.getCodeGenOpts().CoverageMapping)
396
397 std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
398 CI, BA, CI.getVirtualFileSystemPtr(), *VMContext, std::move(LinkModules),
399 InFile, std::move(OS), CoverageInfo));
400 BEConsumer = Result.get();
401
402 // Enable generating macro debug info only when debug info is not disabled and
403 // also macro debug info is enabled.
404 if (CI.getCodeGenOpts().getDebugInfo() != codegenoptions::NoDebugInfo &&
405 CI.getCodeGenOpts().MacroDebugInfo) {
406 std::unique_ptr<PPCallbacks> Callbacks =
407 std::make_unique<MacroPPCallbacks>(BEConsumer->getCodeGenerator(),
408 CI.getPreprocessor());
409 CI.getPreprocessor().addPPCallbacks(std::move(Callbacks));
410 }
411
413 !CI.getFrontendOpts().ModuleOutputPath.empty()) {
414 std::vector<std::unique_ptr<ASTConsumer>> Consumers(2);
415 Consumers[0] = std::make_unique<ReducedBMIGenerator>(
418 Consumers[1] = std::move(Result);
419 return std::make_unique<MultiplexConsumer>(std::move(Consumers));
420 }
421
422 return std::move(Result);
423}
424
425std::unique_ptr<llvm::Module>
426CodeGenAction::loadModule(MemoryBufferRef MBRef) {
429
430 auto DiagErrors = [&](Error E) -> std::unique_ptr<llvm::Module> {
431 unsigned DiagID =
433 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
434 CI.getDiagnostics().Report(DiagID) << EIB.message();
435 });
436 return {};
437 };
438
439 // For ThinLTO backend invocations, ensure that the context
440 // merges types based on ODR identifiers. We also need to read
441 // the correct module out of a multi-module bitcode file.
442 if (!CI.getCodeGenOpts().ThinLTOIndexFile.empty()) {
443 VMContext->enableDebugTypeODRUniquing();
444
445 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
446 if (!BMsOrErr)
447 return DiagErrors(BMsOrErr.takeError());
448 BitcodeModule *Bm = llvm::lto::findThinLTOModule(*BMsOrErr);
449 // We have nothing to do if the file contains no ThinLTO module. This is
450 // possible if ThinLTO compilation was not able to split module. Content of
451 // the file was already processed by indexing and will be passed to the
452 // linker using merged object file.
453 if (!Bm) {
454 auto M = std::make_unique<llvm::Module>("empty", *VMContext);
455 M->setTargetTriple(Triple(CI.getTargetOpts().Triple));
456 return M;
457 }
458 Expected<std::unique_ptr<llvm::Module>> MOrErr =
459 Bm->parseModule(*VMContext);
460 if (!MOrErr)
461 return DiagErrors(MOrErr.takeError());
462 return std::move(*MOrErr);
463 }
464
465 // Load bitcode modules to link with, if we need to.
466 if (clang::loadLinkModules(CI, *VMContext, LinkModules,
467 /*OnlyInternalized=*/false))
468 return nullptr;
469
470 // Handle textual IR and bitcode file with one single module.
471 llvm::SMDiagnostic Err;
472 if (std::unique_ptr<llvm::Module> M = parseIR(MBRef, Err, *VMContext)) {
473 // For LLVM IR files, always verify the input and report the error in a way
474 // that does not ask people to report an issue for it.
475 std::string VerifierErr;
476 raw_string_ostream VerifierErrStream(VerifierErr);
477 if (llvm::verifyModule(*M, &VerifierErrStream)) {
478 CI.getDiagnostics().Report(diag::err_invalid_llvm_ir) << VerifierErr;
479 return {};
480 }
481 return M;
482 }
483
484 // If MBRef is a bitcode with multiple modules (e.g., -fsplit-lto-unit
485 // output), place the extra modules (actually only one, a regular LTO module)
486 // into LinkModules as if we are using -mlink-bitcode-file.
487 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
488 if (BMsOrErr && BMsOrErr->size()) {
489 std::unique_ptr<llvm::Module> FirstM;
490 for (auto &BM : *BMsOrErr) {
491 Expected<std::unique_ptr<llvm::Module>> MOrErr =
492 BM.parseModule(*VMContext);
493 if (!MOrErr)
494 return DiagErrors(MOrErr.takeError());
495 if (FirstM)
496 LinkModules.push_back({std::move(*MOrErr), /*PropagateAttrs=*/false,
497 /*Internalize=*/false, /*LinkFlags=*/{}});
498 else
499 FirstM = std::move(*MOrErr);
500 }
501 if (FirstM)
502 return FirstM;
503 }
504 // If BMsOrErr fails, consume the error and use the error message from
505 // parseIR.
506 consumeError(BMsOrErr.takeError());
507
508 // Translate from the diagnostic info to the SourceManager location if
509 // available.
510 // TODO: Unify this with ConvertBackendLocation()
511 SourceLocation Loc;
512 if (Err.getLineNo() > 0) {
513 assert(Err.getColumnNo() >= 0);
515 Err.getLineNo(), Err.getColumnNo() + 1);
516 }
517
518 // Strip off a leading diagnostic code if there is one.
519 StringRef Msg = Err.getMessage();
520 Msg.consume_front("error: ");
521
522 unsigned DiagID =
524
525 CI.getDiagnostics().Report(Loc, DiagID) << Msg;
526 return {};
527}
528
530 if (getCurrentFileKind().getLanguage() != Language::LLVM_IR) {
532 return;
533 }
534
535 // If this is an IR file, we have to treat it specially.
536 BackendAction BA = static_cast<BackendAction>(Act);
538 auto &CodeGenOpts = CI.getCodeGenOpts();
539 auto &Diagnostics = CI.getDiagnostics();
540 std::unique_ptr<raw_pwrite_stream> OS =
542 if (BA != Backend_EmitNothing && !OS)
543 return;
544
546 FileID FID = SM.getMainFileID();
547 std::optional<MemoryBufferRef> MainFile = SM.getBufferOrNone(FID);
548 if (!MainFile)
549 return;
550
551 TheModule = loadModule(*MainFile);
552 if (!TheModule)
553 return;
554
555 const TargetOptions &TargetOpts = CI.getTargetOpts();
556 if (TheModule->getTargetTriple().str() != TargetOpts.Triple) {
557 Diagnostics.Report(SourceLocation(), diag::warn_fe_override_module)
558 << TargetOpts.Triple;
559 TheModule->setTargetTriple(Triple(TargetOpts.Triple));
560 }
561
562 llvm::ExceptionHandling ExceptionModel =
563 CodeGenOptions::toExceptionHandling(CodeGenOpts.getExceptionHandling());
564 if (ExceptionModel != llvm::ExceptionHandling::Default) {
565 StringRef ModelName = llvm::getExceptionModelName(ExceptionModel);
566 if (auto *Existing = cast_or_null<llvm::MDString>(
567 TheModule->getModuleFlag("exception-model"))) {
568 if (Existing->getString() != ModelName) {
569 Diagnostics.Report(diag::err_fe_exception_model_mismatch)
570 << ModelName << Existing->getString();
571 return;
572 }
573 } else {
574 TheModule->addModuleFlag(
575 llvm::Module::Error, "exception-model",
576 llvm::MDString::get(TheModule->getContext(), ModelName));
577 }
578 }
579
580 EmbedObject(TheModule.get(), CodeGenOpts, CI.getVirtualFileSystem(),
581 Diagnostics);
582 EmbedBitcode(TheModule.get(), CodeGenOpts, *MainFile);
583
584 LLVMContext &Ctx = TheModule->getContext();
585
586 // Restore any diagnostic handler previously set before returning from this
587 // function.
588 struct RAII {
589 LLVMContext &Ctx;
590 std::unique_ptr<DiagnosticHandler> PrevHandler = Ctx.getDiagnosticHandler();
591 ~RAII() { Ctx.setDiagnosticHandler(std::move(PrevHandler)); }
592 } _{Ctx};
593
594 // Set clang diagnostic handler. To do this we need to create a fake
595 // BackendConsumer.
596 BackendConsumer Result(CI, BA, CI.getVirtualFileSystemPtr(), *VMContext,
597 std::move(LinkModules), "", nullptr, nullptr,
598 TheModule.get());
599
600 // Link in each pending link module.
601 if (!CodeGenOpts.LinkBitcodePostopt && Result.LinkInModules(&*TheModule))
602 return;
603
604 // Textual IR needs value names while parsing; discard new names afterwards.
605 Ctx.setDiscardValueNames(CodeGenOpts.DiscardValueNames);
606 Ctx.setDiagnosticHandler(Result.createDiagnosticHandler());
607
608 Ctx.setDefaultTargetCPU(TargetOpts.CPU);
609 Ctx.setDefaultTargetFeatures(llvm::join(TargetOpts.Features, ","));
610 Ctx.setVirtualFileSystem(CI.getVirtualFileSystemPtr());
611
612 Expected<LLVMRemarkFileHandle> OptRecordFileOrErr =
613 setupLLVMOptimizationRemarks(
614 Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,
615 CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,
616 CodeGenOpts.DiagnosticsHotnessThreshold);
617
618 if (Error E = OptRecordFileOrErr.takeError()) {
619 reportOptRecordError(std::move(E), Diagnostics, CodeGenOpts);
620 return;
621 }
622 LLVMRemarkFileHandle OptRecordFile = std::move(*OptRecordFileOrErr);
623
624 emitBackendOutput(CI, CI.getCodeGenOpts(), TheModule.get(), BA,
626 std::move(OS));
627 if (OptRecordFile)
628 OptRecordFile->keep();
629}
630
631//
632
633void EmitAssemblyAction::anchor() { }
634EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
635 : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
636
637void EmitBCAction::anchor() { }
638EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
639 : CodeGenAction(Backend_EmitBC, _VMContext) {}
640
641void EmitLLVMAction::anchor() { }
642EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
643 : CodeGenAction(Backend_EmitLL, _VMContext) {}
644
645void EmitLLVMOnlyAction::anchor() { }
646EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
647 : CodeGenAction(Backend_EmitNothing, _VMContext) {}
648
649void EmitCodeGenOnlyAction::anchor() { }
651 : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
652
653void EmitObjAction::anchor() { }
654EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
655 : CodeGenAction(Backend_EmitObj, _VMContext) {}
Defines the clang::ASTContext interface.
static std::unique_ptr< raw_pwrite_stream > GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::FileManager interface and associated types.
Defines the clang::Preprocessor interface.
Defines the SourceManager interface.
virtual void HandleCXXStaticMemberVarInstantiation(VarDecl *D)
HandleCXXStaticMemberVarInstantiation - Tell the consumer that this.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
SourceManager & getSourceManager()
Definition ASTContext.h:916
void ExecuteAction() override
Implement the ExecuteAction interface by running Sema on the already-initialized AST consumer.
llvm::Module * getModule() const
void CompleteExternalDeclaration(DeclaratorDecl *D) override
CompleteExternalDeclaration - Callback invoked at the end of a translation unit to notify the consume...
void HandleVTable(CXXRecordDecl *RD) override
Callback involved at the end of a translation unit to notify the consumer that a vtable for the given...
void HandleTagDeclDefinition(TagDecl *D) override
HandleTagDeclDefinition - This callback is invoked each time a TagDecl (e.g.
bool HandleTopLevelDecl(DeclGroupRef D) override
HandleTopLevelDecl - Handle the specified top-level declaration.
void Initialize(ASTContext &Ctx) override
Initialize - This is called to initialize the consumer, providing the ASTContext.
void HandleInlineFunctionDefinition(FunctionDecl *D) override
This callback is invoked each time an inline (method or friend) function definition in a class is com...
void HandleTagDeclRequiredDefinition(const TagDecl *D) override
This callback is invoked the first time each TagDecl is required to be complete.
void HandleInterestingDecl(DeclGroupRef D) override
HandleInterestingDecl - Handle the specified interesting declaration.
void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override
HandleCXXStaticMemberVarInstantiation - Tell the consumer that this.
std::unique_ptr< llvm::DiagnosticHandler > createDiagnosticHandler()
Create an llvm::DiagnosticHandler that routes LLVM backend diagnostics through this consumer's clang ...
std::unique_ptr< llvm::Module > takeModule()
void AssignInheritanceModel(CXXRecordDecl *RD) override
Callback invoked when an MSInheritanceAttr has been attached to a CXXRecordDecl.
void HandleTranslationUnit(ASTContext &C) override
HandleTranslationUnit - This method is called when the ASTs for entire translation unit have been par...
void CompleteTentativeDefinition(VarDecl *D) override
CompleteTentativeDefinition - Callback invoked at the end of a translation unit to notify the consume...
bool LinkInModules(llvm::Module *M)
CodeGenerator * getCodeGenerator()
BackendConsumer(CompilerInstance &CI, BackendAction Action, IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS, llvm::LLVMContext &C, SmallVector< LinkModule, 4 > LinkModules, StringRef InFile, std::unique_ptr< raw_pwrite_stream > OS, CoverageSourceInfo *CoverageInfo, llvm::Module *CurLinkModule=nullptr)
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
Create the AST consumer object for this action, if supported.
CodeGenerator * getCodeGenerator() const
void EndSourceFileAction() override
Callback at the end of processing a single input.
bool BeginSourceFileAction(CompilerInstance &CI) override
Callback at the start of processing a single input.
CodeGenAction(unsigned _Act, llvm::LLVMContext *_VMContext=nullptr)
Create a new code generation action.
llvm::LLVMContext * takeLLVMContext()
Take the LLVM context used by this action.
BackendConsumer * BEConsumer
bool hasIRSupport() const override
Does this action support use with IR files?
void ExecuteAction() override
Implement the ExecuteAction interface by running Sema on the already-initialized AST consumer.
std::unique_ptr< llvm::Module > takeModule()
Take the generated LLVM module, for use after the action has been run.
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
std::string OptRecordFile
The name of the file to which the backend should save YAML optimization records.
static llvm::ExceptionHandling toExceptionHandling(ExceptionHandlingKind Kind)
Translate a clang ExceptionHandlingKind into the corresponding LLVM ExceptionHandling model.
std::string OptRecordPasses
The regex that filters the passes that should be saved to the optimization records.
std::string ThinLTOIndexFile
Name of the function summary index file to use for ThinLTO function importing.
std::string OptRecordFormat
The format used for serializing remarks (default: YAML)
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
Definition CGDebugInfo.h:60
static CoverageSourceInfo * setUpCoverageCallbacks(const CodeGenCLOptions &CLOpts, Preprocessor &PP)
The primary public interface to the Clang code generator.
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
std::unique_ptr< raw_pwrite_stream > createDefaultOutputFile(bool Binary=true, StringRef BaseInput="", StringRef Extension="", bool RemoveFileOnSignal=true, bool CreateMissingDirectories=false, bool ForceUseTemporary=false, bool SetOnlyIfDifferent=false)
Create the default output file (from the invocation's options) and add it to the list of tracked outp...
DiagnosticsEngine & getDiagnostics() const
Get the current diagnostics engine.
FileManager & getFileManager() const
Return the current file manager to the caller.
ModuleCache & getModuleCache() const
Preprocessor & getPreprocessor() const
Return the current preprocessor.
const llvm::cl::LibraryOptionsContext & getLibraryOptions() const
IntrusiveRefCntPtr< llvm::vfs::FileSystem > getVirtualFileSystemPtr() const
TargetOptions & getTargetOpts()
std::unique_ptr< llvm::raw_pwrite_stream > takeOutputStream()
FrontendOptions & getFrontendOpts()
llvm::vfs::FileSystem & getVirtualFileSystem() const
CodeGenOptions & getCodeGenOpts()
SourceManager & getSourceManager() const
Return the current source manager.
std::unique_ptr< raw_pwrite_stream > createNullOutputFile()
Stores additional source code information like skipped ranges which is required by the coverage mappi...
iterator begin()
Definition DeclGroup.h:95
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
Represents a ValueDecl that came out of a declarator.
Definition Decl.h:782
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:240
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
Definition Diagnostic.h:956
EmitAssemblyAction(llvm::LLVMContext *_VMContext=nullptr)
EmitBCAction(llvm::LLVMContext *_VMContext=nullptr)
EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext=nullptr)
EmitLLVMAction(llvm::LLVMContext *_VMContext=nullptr)
EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext=nullptr)
EmitObjAction(llvm::LLVMContext *_VMContext=nullptr)
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > getVirtualFileSystemPtr() const
InputKind getCurrentFileKind() const
virtual bool BeginSourceFileAction(CompilerInstance &CI)
Callback at the start of processing a single input.
CompilerInstance & getCompilerInstance() const
virtual void EndSourceFileAction()
Callback at the end of processing a single input.
StringRef getCurrentFileOrBufferName() const
unsigned GenReducedBMI
Whether to generate reduced BMI for C++20 named modules.
std::string ModuleOutputPath
Output Path for module output file.
Represents a function declaration or definition.
Definition Decl.h:2082
@ CMK_ModuleInterface
Compiling a C++ modules interface unit.
void addPPCallbacks(std::unique_ptr< PPCallbacks > C)
PrettyStackTraceDecl - If a crash occurs, indicate that it happened when doing something to a specifi...
Definition DeclBase.h:1318
Encodes a location in the source.
This class handles loading and caching of source files into memory.
FileID getMainFileID() const
Returns the FileID of the main source file.
SourceLocation translateFileLineCol(const FileEntry *SourceFile, unsigned Line, unsigned Col) const
Get the source location for the given file:line:col triplet.
const FileEntry * getFileEntryForID(FileID FID) const
Returns the FileEntry record for the provided FileID.
std::optional< llvm::MemoryBufferRef > getBufferOrNone(FileID FID, SourceLocation Loc=SourceLocation()) const
Return the buffer for the specified FileID.
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3898
Options for controlling the target.
std::string Triple
The name of the target triple to compile for.
std::vector< std::string > Features
The list of target specific features to enable or disable – this should be a list of strings starting...
std::string CPU
If given, the name of the target CPU to generate code for.
Represents a variable declaration or definition.
Definition Decl.h:934
Defines the clang::TargetInfo interface.
const CodeGenCLOptions & getCodeGenCLOptions(const llvm::LLVMContext &Ctx)
Top level wrappers for InstallAPI frontend operations.
bool loadLinkModules(CompilerInstance &CI, llvm::LLVMContext &Ctx, llvm::SmallVectorImpl< LinkModule > &LinkModules, bool OnlyInternalized)
Load every bitcode file listed in CodeGenOpts.LinkBitcodeFiles into LinkModules.
static void reportOptRecordError(Error E, DiagnosticsEngine &Diags, const CodeGenOptions &CodeGenOpts)
@ Result
The result type of a method or function.
Definition TypeBase.h:906
bool linkInModules(llvm::Module &M, llvm::SmallVectorImpl< LinkModule > &LinkModules, const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts, const TargetOptions &TargetOpts, BackendDiagnosticConsumer &DiagConsumer)
Link every module in LinkModules into M, propagating default function attributes and internalizing as...
void EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts, llvm::vfs::FileSystem &VFS, DiagnosticsEngine &Diags)
void emitBackendOutput(CompilerInstance &CI, CodeGenOptions &CGOpts, llvm::Module *M, BackendAction Action, llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS, std::unique_ptr< raw_pwrite_stream > OS, BackendConsumer *BC=nullptr)
void EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts, llvm::MemoryBufferRef Buf)
BackendAction
Definition BackendUtil.h:31
@ Backend_EmitAssembly
Emit native assembly files.
Definition BackendUtil.h:32
@ Backend_EmitLL
Emit human-readable LLVM assembly.
Definition BackendUtil.h:34
@ Backend_EmitBC
Emit LLVM bitcode files.
Definition BackendUtil.h:33
@ Backend_EmitObj
Emit native object files.
Definition BackendUtil.h:37
@ Backend_EmitMCNull
Run CodeGen, but don't emit anything.
Definition BackendUtil.h:36
@ Backend_EmitNothing
Don't emit anything (benchmarking mode)
Definition BackendUtil.h:35
std::unique_ptr< CodeGenerator > CreateLLVMCodeGen(const CompilerInstance &CI, llvm::StringRef ModuleName, llvm::LLVMContext &C, CoverageSourceInfo *CoverageInfo=nullptr)
CreateLLVMCodeGen - Create a CodeGenerator instance.
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30