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 return linkInModules(*M, LinkModules, CodeGenOpts, LangOpts, TargetOpts,
176 DiagConsumer);
177}
178
180 {
181 llvm::TimeTraceScope TimeScope("Frontend");
182 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
183 if (TimerIsEnabled && !LLVMIRGenerationRefCount++)
184 CI.getFrontendTimer().yieldTo(LLVMIRGeneration);
185
186 Gen->HandleTranslationUnit(C);
187
188 if (TimerIsEnabled && !--LLVMIRGenerationRefCount)
189 LLVMIRGeneration.yieldTo(CI.getFrontendTimer());
190 }
191
192 // Silently ignore if we weren't initialized for some reason.
193 if (!getModule())
194 return;
195
196 LLVMContext &Ctx = getModule()->getContext();
197 std::unique_ptr<DiagnosticHandler> OldDiagnosticHandler =
198 Ctx.getDiagnosticHandler();
199 llvm::scope_exit RestoreDiagnosticHandler(
200 [&]() { Ctx.setDiagnosticHandler(std::move(OldDiagnosticHandler)); });
201 Ctx.setDiagnosticHandler(createDiagnosticHandler());
202
203 Ctx.setDefaultTargetCPU(TargetOpts.CPU);
204 Ctx.setDefaultTargetFeatures(llvm::join(TargetOpts.Features, ","));
205
206 Expected<LLVMRemarkFileHandle> OptRecordFileOrErr =
207 setupLLVMOptimizationRemarks(
208 Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,
209 CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,
210 CodeGenOpts.DiagnosticsHotnessThreshold);
211
212 if (Error E = OptRecordFileOrErr.takeError()) {
213 reportOptRecordError(std::move(E), Diags, CodeGenOpts);
214 return;
215 }
216
217 LLVMRemarkFileHandle OptRecordFile = std::move(*OptRecordFileOrErr);
218
219 if (OptRecordFile && CodeGenOpts.getProfileUse() !=
220 llvm::driver::ProfileInstrKind::ProfileNone)
221 Ctx.setDiagnosticsHotnessRequested(true);
222
223 if (CodeGenOpts.MisExpect) {
224 Ctx.setMisExpectWarningRequested(true);
225 }
226
227 if (CodeGenOpts.DiagnosticsMisExpectTolerance) {
228 Ctx.setDiagnosticsMisExpectTolerance(
229 CodeGenOpts.DiagnosticsMisExpectTolerance);
230 }
231
232 // Link each LinkModule into our module.
233 if (!CodeGenOpts.LinkBitcodePostopt && LinkInModules(getModule()))
234 return;
235
236 for (auto &F : getModule()->functions()) {
237 if (const Decl *FD = Gen->GetDeclForMangledName(F.getName())) {
238 auto Loc = FD->getASTContext().getFullLoc(FD->getLocation());
239 DiagConsumer.addFunctionSourceLocation(F.getName(), Loc);
240 }
241 }
242
243 if (CodeGenOpts.ClearASTBeforeBackend) {
244 LLVM_DEBUG(llvm::dbgs() << "Clearing AST...\n");
245 // Access to the AST is no longer available after this.
246 // Other things that the ASTContext manages are still available, e.g.
247 // the SourceManager. It'd be nice if we could separate out all the
248 // things in ASTContext used after this point and null out the
249 // ASTContext, but too many various parts of the ASTContext are still
250 // used in various parts.
251 C.cleanup();
252 C.getAllocator().Reset();
253 }
254
255 EmbedBitcode(getModule(), CodeGenOpts, llvm::MemoryBufferRef());
256
257 emitBackendOutput(CI, CI.getCodeGenOpts(), getModule(), Action, FS,
258 std::move(AsmOutStream), this);
259
260 if (OptRecordFile)
261 OptRecordFile->keep();
262}
263
266 Context->getSourceManager(),
267 "LLVM IR generation of declaration");
268 Gen->HandleTagDeclDefinition(D);
269}
270
272 Gen->HandleTagDeclRequiredDefinition(D);
273}
274
276 Gen->CompleteTentativeDefinition(D);
277}
278
280 Gen->CompleteExternalDeclaration(D);
281}
282
284 Gen->AssignInheritanceModel(RD);
285}
286
288 Gen->HandleVTable(RD);
289}
290
291void BackendConsumer::anchor() { }
292
293} // namespace clang
294
295std::unique_ptr<llvm::DiagnosticHandler>
297 return DiagConsumer.createDiagnosticHandler();
298}
299
300CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
301 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
302 OwnsVMContext(!_VMContext) {}
303
305 TheModule.reset();
306 if (OwnsVMContext)
307 delete VMContext;
308}
309
310bool CodeGenAction::hasIRSupport() const { return true; }
311
314
315 // If the consumer creation failed, do nothing.
316 if (!getCompilerInstance().hasASTConsumer())
317 return;
318
319 // Steal the module from the consumer.
320 TheModule = BEConsumer->takeModule();
321}
322
323std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
324 return std::move(TheModule);
325}
326
327llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
328 OwnsVMContext = false;
329 return VMContext;
330}
331
333 return BEConsumer->getCodeGenerator();
334}
335
337 VMContext->getLibraryOptions().assign(CI.getLibraryOptions());
339 CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleInterface);
341}
342
343static std::unique_ptr<raw_pwrite_stream>
344GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
345 switch (Action) {
347 return CI.createDefaultOutputFile(false, InFile, "s");
348 case Backend_EmitLL:
349 return CI.createDefaultOutputFile(false, InFile, "ll");
350 case Backend_EmitBC:
351 return CI.createDefaultOutputFile(true, InFile, "bc");
353 return nullptr;
355 return CI.createNullOutputFile();
356 case Backend_EmitObj:
357 return CI.createDefaultOutputFile(true, InFile, "o");
358 }
359
360 llvm_unreachable("Invalid action!");
361}
362
363std::unique_ptr<ASTConsumer>
365 BackendAction BA = static_cast<BackendAction>(Act);
366 std::unique_ptr<raw_pwrite_stream> OS = CI.takeOutputStream();
367 if (!OS)
368 OS = GetOutputStream(CI, InFile, BA);
369
370 if (BA != Backend_EmitNothing && !OS)
371 return nullptr;
372
373 // Load bitcode modules to link with, if we need to.
374 if (clang::loadLinkModules(CI, *VMContext, LinkModules))
375 return nullptr;
376
377 CoverageSourceInfo *CoverageInfo = nullptr;
378 // Add the preprocessor callback only when the coverage mapping is generated.
379 if (CI.getCodeGenOpts().CoverageMapping)
381 CI.getPreprocessor());
382
383 std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
384 CI, BA, CI.getVirtualFileSystemPtr(), *VMContext, std::move(LinkModules),
385 InFile, std::move(OS), CoverageInfo));
386 BEConsumer = Result.get();
387
388 // Enable generating macro debug info only when debug info is not disabled and
389 // also macro debug info is enabled.
390 if (CI.getCodeGenOpts().getDebugInfo() != codegenoptions::NoDebugInfo &&
391 CI.getCodeGenOpts().MacroDebugInfo) {
392 std::unique_ptr<PPCallbacks> Callbacks =
393 std::make_unique<MacroPPCallbacks>(BEConsumer->getCodeGenerator(),
394 CI.getPreprocessor());
395 CI.getPreprocessor().addPPCallbacks(std::move(Callbacks));
396 }
397
399 !CI.getFrontendOpts().ModuleOutputPath.empty()) {
400 std::vector<std::unique_ptr<ASTConsumer>> Consumers(2);
401 Consumers[0] = std::make_unique<ReducedBMIGenerator>(
404 Consumers[1] = std::move(Result);
405 return std::make_unique<MultiplexConsumer>(std::move(Consumers));
406 }
407
408 return std::move(Result);
409}
410
411std::unique_ptr<llvm::Module>
412CodeGenAction::loadModule(MemoryBufferRef MBRef) {
415
416 auto DiagErrors = [&](Error E) -> std::unique_ptr<llvm::Module> {
417 unsigned DiagID =
419 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
420 CI.getDiagnostics().Report(DiagID) << EIB.message();
421 });
422 return {};
423 };
424
425 // For ThinLTO backend invocations, ensure that the context
426 // merges types based on ODR identifiers. We also need to read
427 // the correct module out of a multi-module bitcode file.
428 if (!CI.getCodeGenOpts().ThinLTOIndexFile.empty()) {
429 VMContext->enableDebugTypeODRUniquing();
430
431 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
432 if (!BMsOrErr)
433 return DiagErrors(BMsOrErr.takeError());
434 BitcodeModule *Bm = llvm::lto::findThinLTOModule(*BMsOrErr);
435 // We have nothing to do if the file contains no ThinLTO module. This is
436 // possible if ThinLTO compilation was not able to split module. Content of
437 // the file was already processed by indexing and will be passed to the
438 // linker using merged object file.
439 if (!Bm) {
440 auto M = std::make_unique<llvm::Module>("empty", *VMContext);
441 M->setTargetTriple(Triple(CI.getTargetOpts().Triple));
442 return M;
443 }
444 Expected<std::unique_ptr<llvm::Module>> MOrErr =
445 Bm->parseModule(*VMContext);
446 if (!MOrErr)
447 return DiagErrors(MOrErr.takeError());
448 return std::move(*MOrErr);
449 }
450
451 // Load bitcode modules to link with, if we need to.
452 if (clang::loadLinkModules(CI, *VMContext, LinkModules))
453 return nullptr;
454
455 // Handle textual IR and bitcode file with one single module.
456 llvm::SMDiagnostic Err;
457 if (std::unique_ptr<llvm::Module> M = parseIR(MBRef, Err, *VMContext)) {
458 // For LLVM IR files, always verify the input and report the error in a way
459 // that does not ask people to report an issue for it.
460 std::string VerifierErr;
461 raw_string_ostream VerifierErrStream(VerifierErr);
462 if (llvm::verifyModule(*M, &VerifierErrStream)) {
463 CI.getDiagnostics().Report(diag::err_invalid_llvm_ir) << VerifierErr;
464 return {};
465 }
466 return M;
467 }
468
469 // If MBRef is a bitcode with multiple modules (e.g., -fsplit-lto-unit
470 // output), place the extra modules (actually only one, a regular LTO module)
471 // into LinkModules as if we are using -mlink-bitcode-file.
472 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
473 if (BMsOrErr && BMsOrErr->size()) {
474 std::unique_ptr<llvm::Module> FirstM;
475 for (auto &BM : *BMsOrErr) {
476 Expected<std::unique_ptr<llvm::Module>> MOrErr =
477 BM.parseModule(*VMContext);
478 if (!MOrErr)
479 return DiagErrors(MOrErr.takeError());
480 if (FirstM)
481 LinkModules.push_back({std::move(*MOrErr), /*PropagateAttrs=*/false,
482 /*Internalize=*/false, /*LinkFlags=*/{}});
483 else
484 FirstM = std::move(*MOrErr);
485 }
486 if (FirstM)
487 return FirstM;
488 }
489 // If BMsOrErr fails, consume the error and use the error message from
490 // parseIR.
491 consumeError(BMsOrErr.takeError());
492
493 // Translate from the diagnostic info to the SourceManager location if
494 // available.
495 // TODO: Unify this with ConvertBackendLocation()
496 SourceLocation Loc;
497 if (Err.getLineNo() > 0) {
498 assert(Err.getColumnNo() >= 0);
500 Err.getLineNo(), Err.getColumnNo() + 1);
501 }
502
503 // Strip off a leading diagnostic code if there is one.
504 StringRef Msg = Err.getMessage();
505 Msg.consume_front("error: ");
506
507 unsigned DiagID =
509
510 CI.getDiagnostics().Report(Loc, DiagID) << Msg;
511 return {};
512}
513
515 if (getCurrentFileKind().getLanguage() != Language::LLVM_IR) {
517 return;
518 }
519
520 // If this is an IR file, we have to treat it specially.
521 BackendAction BA = static_cast<BackendAction>(Act);
523 auto &CodeGenOpts = CI.getCodeGenOpts();
524 auto &Diagnostics = CI.getDiagnostics();
525 std::unique_ptr<raw_pwrite_stream> OS =
527 if (BA != Backend_EmitNothing && !OS)
528 return;
529
531 FileID FID = SM.getMainFileID();
532 std::optional<MemoryBufferRef> MainFile = SM.getBufferOrNone(FID);
533 if (!MainFile)
534 return;
535
536 TheModule = loadModule(*MainFile);
537 if (!TheModule)
538 return;
539
540 const TargetOptions &TargetOpts = CI.getTargetOpts();
541 if (TheModule->getTargetTriple().str() != TargetOpts.Triple) {
542 Diagnostics.Report(SourceLocation(), diag::warn_fe_override_module)
543 << TargetOpts.Triple;
544 TheModule->setTargetTriple(Triple(TargetOpts.Triple));
545 }
546
547 llvm::ExceptionHandling ExceptionModel =
548 CodeGenOptions::toExceptionHandling(CodeGenOpts.getExceptionHandling());
549 if (ExceptionModel != llvm::ExceptionHandling::Default) {
550 StringRef ModelName = llvm::getExceptionModelName(ExceptionModel);
551 if (auto *Existing = cast_or_null<llvm::MDString>(
552 TheModule->getModuleFlag("exception-model"))) {
553 if (Existing->getString() != ModelName) {
554 Diagnostics.Report(diag::err_fe_exception_model_mismatch)
555 << ModelName << Existing->getString();
556 return;
557 }
558 } else {
559 TheModule->addModuleFlag(
560 llvm::Module::Error, "exception-model",
561 llvm::MDString::get(TheModule->getContext(), ModelName));
562 }
563 }
564
565 EmbedObject(TheModule.get(), CodeGenOpts, CI.getVirtualFileSystem(),
566 Diagnostics);
567 EmbedBitcode(TheModule.get(), CodeGenOpts, *MainFile);
568
569 LLVMContext &Ctx = TheModule->getContext();
570
571 // Restore any diagnostic handler previously set before returning from this
572 // function.
573 struct RAII {
574 LLVMContext &Ctx;
575 std::unique_ptr<DiagnosticHandler> PrevHandler = Ctx.getDiagnosticHandler();
576 ~RAII() { Ctx.setDiagnosticHandler(std::move(PrevHandler)); }
577 } _{Ctx};
578
579 // Set clang diagnostic handler. To do this we need to create a fake
580 // BackendConsumer.
581 BackendConsumer Result(CI, BA, CI.getVirtualFileSystemPtr(), *VMContext,
582 std::move(LinkModules), "", nullptr, nullptr,
583 TheModule.get());
584
585 // Link in each pending link module.
586 if (!CodeGenOpts.LinkBitcodePostopt && Result.LinkInModules(&*TheModule))
587 return;
588
589 // Textual IR needs value names while parsing; discard new names afterwards.
590 Ctx.setDiscardValueNames(CodeGenOpts.DiscardValueNames);
591 Ctx.setDiagnosticHandler(Result.createDiagnosticHandler());
592
593 Ctx.setDefaultTargetCPU(TargetOpts.CPU);
594 Ctx.setDefaultTargetFeatures(llvm::join(TargetOpts.Features, ","));
595
596 Expected<LLVMRemarkFileHandle> OptRecordFileOrErr =
597 setupLLVMOptimizationRemarks(
598 Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,
599 CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,
600 CodeGenOpts.DiagnosticsHotnessThreshold);
601
602 if (Error E = OptRecordFileOrErr.takeError()) {
603 reportOptRecordError(std::move(E), Diagnostics, CodeGenOpts);
604 return;
605 }
606 LLVMRemarkFileHandle OptRecordFile = std::move(*OptRecordFileOrErr);
607
608 emitBackendOutput(CI, CI.getCodeGenOpts(), TheModule.get(), BA,
610 std::move(OS));
611 if (OptRecordFile)
612 OptRecordFile->keep();
613}
614
615//
616
617void EmitAssemblyAction::anchor() { }
618EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
619 : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
620
621void EmitBCAction::anchor() { }
622EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
623 : CodeGenAction(Backend_EmitBC, _VMContext) {}
624
625void EmitLLVMAction::anchor() { }
626EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
627 : CodeGenAction(Backend_EmitLL, _VMContext) {}
628
629void EmitLLVMOnlyAction::anchor() { }
630EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
631 : CodeGenAction(Backend_EmitNothing, _VMContext) {}
632
633void EmitCodeGenOnlyAction::anchor() { }
635 : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
636
637void EmitObjAction::anchor() { }
638EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
639 : 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:917
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:781
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:2059
@ 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:1317
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:3856
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:933
Defines the clang::TargetInfo interface.
Top level wrappers for InstallAPI frontend operations.
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.
bool loadLinkModules(CompilerInstance &CI, llvm::LLVMContext &Ctx, llvm::SmallVectorImpl< LinkModule > &LinkModules)
Load every bitcode file listed in CodeGenOpts.LinkBitcodeFiles into LinkModules.
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30