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