28#include "llvm/ADT/Hashing.h"
29#include "llvm/Bitcode/BitcodeReader.h"
30#include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
31#include "llvm/Demangle/Demangle.h"
32#include "llvm/IR/DebugInfo.h"
33#include "llvm/IR/DiagnosticInfo.h"
34#include "llvm/IR/DiagnosticPrinter.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/IRReader/IRReader.h"
40#include "llvm/LTO/LTOBackend.h"
41#include "llvm/Linker/Linker.h"
43#include "llvm/Support/MemoryBuffer.h"
44#include "llvm/Support/SourceMgr.h"
45#include "llvm/Support/TimeProfiler.h"
46#include "llvm/Support/Timer.h"
47#include "llvm/Support/ToolOutputFile.h"
48#include "llvm/Support/YAMLTraits.h"
49#include "llvm/Transforms/IPO/Internalize.h"
56#define DEBUG_TYPE "codegenaction"
63 : CodeGenOpts(CGOpts), BackendCon(BCon) {}
92 [&](
const LLVMRemarkSetupFileError &E) {
93 Diags.
Report(diag::err_cannot_open_file)
96 [&](
const LLVMRemarkSetupPatternError &E) {
97 Diags.
Report(diag::err_drv_optimization_remark_pattern)
100 [&](
const LLVMRemarkSetupFormatError &E) {
101 Diags.
Report(diag::err_drv_optimization_remark_format)
107 using LinkModule = CodeGenAction::LinkModule;
109 virtual void anchor();
116 std::unique_ptr<raw_pwrite_stream> AsmOutStream;
120 Timer LLVMIRGeneration;
121 unsigned LLVMIRGenerationRefCount;
126 bool IRGenFinished =
false;
128 bool TimerIsEnabled =
false;
130 std::unique_ptr<CodeGenerator> Gen;
142 std::vector<std::pair<llvm::hash_code, FullSourceLoc>>
143 ManglingFullSourceLocs;
147 llvm::Module *CurLinkModule =
nullptr;
156 const LangOptions &LangOpts,
const std::string &InFile,
158 std::unique_ptr<raw_pwrite_stream> OS, LLVMContext &
C,
160 : Diags(Diags), Action(Action), HeaderSearchOpts(HeaderSearchOpts),
161 CodeGenOpts(CodeGenOpts), TargetOpts(TargetOpts), LangOpts(LangOpts),
162 AsmOutStream(
std::move(OS)), Context(nullptr), FS(VFS),
163 LLVMIRGeneration(
"irgen",
"LLVM IR Generation Time"),
164 LLVMIRGenerationRefCount(0),
166 PPOpts, CodeGenOpts,
C, CoverageInfo)),
167 LinkModules(
std::move(LinkModules)) {
168 TimerIsEnabled = CodeGenOpts.TimePasses;
169 llvm::TimePassesIsEnabled = CodeGenOpts.TimePasses;
170 llvm::TimePassesPerRun = CodeGenOpts.TimePassesPerRun;
185 : Diags(Diags), Action(Action), HeaderSearchOpts(HeaderSearchOpts),
186 CodeGenOpts(CodeGenOpts), TargetOpts(TargetOpts), LangOpts(LangOpts),
187 Context(nullptr), FS(VFS),
188 LLVMIRGeneration(
"irgen",
"LLVM IR Generation Time"),
189 LLVMIRGenerationRefCount(0),
191 PPOpts, CodeGenOpts,
C, CoverageInfo)),
192 LinkModules(
std::move(LinkModules)), CurLinkModule(
Module) {
193 TimerIsEnabled = CodeGenOpts.TimePasses;
194 llvm::TimePassesIsEnabled = CodeGenOpts.TimePasses;
195 llvm::TimePassesPerRun = CodeGenOpts.TimePassesPerRun;
197 llvm::Module *
getModule()
const {
return Gen->GetModule(); }
199 return std::unique_ptr<llvm::Module>(Gen->ReleaseModule());
205 Gen->HandleCXXStaticMemberVarInstantiation(VD);
209 assert(!Context &&
"initialized multiple times");
214 LLVMIRGeneration.startTimer();
216 Gen->Initialize(Ctx);
219 LLVMIRGeneration.stopTimer();
225 "LLVM IR generation of declaration");
228 if (TimerIsEnabled) {
229 LLVMIRGenerationRefCount += 1;
230 if (LLVMIRGenerationRefCount == 1)
231 LLVMIRGeneration.startTimer();
234 Gen->HandleTopLevelDecl(D);
236 if (TimerIsEnabled) {
237 LLVMIRGenerationRefCount -= 1;
238 if (LLVMIRGenerationRefCount == 0)
239 LLVMIRGeneration.stopTimer();
248 "LLVM IR generation of inline function");
250 LLVMIRGeneration.startTimer();
252 Gen->HandleInlineFunctionDefinition(D);
255 LLVMIRGeneration.stopTimer();
266 for (
auto &LM : LinkModules) {
267 if (LM.PropagateAttrs)
268 for (Function &F : *LM.Module) {
273 Gen->CGM().addDefaultFunctionDefinitionAttributes(F);
276 CurLinkModule = LM.Module.get();
279 if (LM.Internalize) {
280 Err = Linker::linkModules(
281 *
getModule(), std::move(LM.Module), LM.LinkFlags,
282 [](llvm::Module &M,
const llvm::StringSet<> &GVS) {
283 internalizeModule(M, [&GVS](const llvm::GlobalValue &GV) {
284 return !GV.hasName() || (GVS.count(GV.getName()) == 0);
288 Err = Linker::linkModules(*
getModule(), std::move(LM.Module),
300 llvm::TimeTraceScope TimeScope(
"Frontend");
301 PrettyStackTraceString CrashInfo(
"Per-file LLVM IR generation");
302 if (TimerIsEnabled) {
303 LLVMIRGenerationRefCount += 1;
304 if (LLVMIRGenerationRefCount == 1)
305 LLVMIRGeneration.startTimer();
308 Gen->HandleTranslationUnit(
C);
310 if (TimerIsEnabled) {
311 LLVMIRGenerationRefCount -= 1;
312 if (LLVMIRGenerationRefCount == 0)
313 LLVMIRGeneration.stopTimer();
316 IRGenFinished =
true;
323 LLVMContext &Ctx = getModule()->getContext();
324 std::unique_ptr<DiagnosticHandler> OldDiagnosticHandler =
325 Ctx.getDiagnosticHandler();
326 Ctx.setDiagnosticHandler(std::make_unique<ClangDiagnosticHandler>(
330 setupLLVMOptimizationRemarks(
331 Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,
332 CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,
333 CodeGenOpts.DiagnosticsHotnessThreshold);
335 if (
Error E = OptRecordFileOrErr.takeError()) {
340 std::unique_ptr<llvm::ToolOutputFile> OptRecordFile =
341 std::move(*OptRecordFileOrErr);
345 Ctx.setDiagnosticsHotnessRequested(
true);
347 if (CodeGenOpts.MisExpect) {
348 Ctx.setMisExpectWarningRequested(
true);
351 if (CodeGenOpts.DiagnosticsMisExpectTolerance) {
352 Ctx.setDiagnosticsMisExpectTolerance(
353 CodeGenOpts.DiagnosticsMisExpectTolerance);
360 for (
auto &F : getModule()->functions()) {
361 if (
const Decl *FD = Gen->GetDeclForMangledName(F.getName())) {
362 auto Loc = FD->getASTContext().getFullLoc(FD->getLocation());
364 auto NameHash = llvm::hash_value(F.getName());
365 ManglingFullSourceLocs.push_back(std::make_pair(NameHash, Loc));
369 if (CodeGenOpts.ClearASTBeforeBackend) {
370 LLVM_DEBUG(llvm::dbgs() <<
"Clearing AST...\n");
378 C.getAllocator().Reset();
381 EmbedBitcode(getModule(), CodeGenOpts, llvm::MemoryBufferRef());
384 LangOpts,
C.getTargetInfo().getDataLayoutString(),
385 getModule(), Action, FS, std::move(AsmOutStream));
387 Ctx.setDiagnosticHandler(std::move(OldDiagnosticHandler));
390 OptRecordFile->keep();
396 "LLVM IR generation of declaration");
397 Gen->HandleTagDeclDefinition(D);
401 Gen->HandleTagDeclRequiredDefinition(D);
405 Gen->CompleteTentativeDefinition(D);
409 Gen->CompleteExternalDeclaration(D);
413 Gen->AssignInheritanceModel(RD);
417 Gen->HandleVTable(RD);
423 getBestLocationFromDebugLoc(
const llvm::DiagnosticInfoWithLocationBase &D,
424 bool &BadDebugInfo, StringRef &
Filename,
425 unsigned &Line,
unsigned &Column)
const;
427 std::optional<FullSourceLoc>
428 getFunctionSourceLocation(
const Function &F)
const;
430 void DiagnosticHandlerImpl(
const llvm::DiagnosticInfo &DI);
434 bool InlineAsmDiagHandler(
const llvm::DiagnosticInfoInlineAsm &D);
436 void SrcMgrDiagHandler(
const llvm::DiagnosticInfoSrcMgr &D);
440 bool StackSizeDiagHandler(
const llvm::DiagnosticInfoStackSize &D);
444 bool ResourceLimitDiagHandler(
const llvm::DiagnosticInfoResourceLimit &D);
447 void UnsupportedDiagHandler(
const llvm::DiagnosticInfoUnsupported &D);
451 void EmitOptimizationMessage(
const llvm::DiagnosticInfoOptimizationBase &D,
454 OptimizationRemarkHandler(
const llvm::DiagnosticInfoOptimizationBase &D);
455 void OptimizationRemarkHandler(
456 const llvm::OptimizationRemarkAnalysisFPCommute &D);
457 void OptimizationRemarkHandler(
458 const llvm::OptimizationRemarkAnalysisAliasing &D);
459 void OptimizationFailureHandler(
460 const llvm::DiagnosticInfoOptimizationFailure &D);
461 void DontCallDiagHandler(
const DiagnosticInfoDontCall &D);
464 void MisExpectDiagHandler(
const llvm::DiagnosticInfoMisExpect &D);
467 void BackendConsumer::anchor() {}
482 const llvm::SourceMgr &LSM = *D.getSourceMgr();
486 const MemoryBuffer *LBuf =
487 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
491 std::unique_ptr<llvm::MemoryBuffer> CBuf =
492 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
493 LBuf->getBufferIdentifier());
498 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
504#define ComputeDiagID(Severity, GroupName, DiagID) \
506 switch (Severity) { \
507 case llvm::DS_Error: \
508 DiagID = diag::err_fe_##GroupName; \
510 case llvm::DS_Warning: \
511 DiagID = diag::warn_fe_##GroupName; \
513 case llvm::DS_Remark: \
514 llvm_unreachable("'remark' severity not expected"); \
516 case llvm::DS_Note: \
517 DiagID = diag::note_fe_##GroupName; \
522#define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
524 switch (Severity) { \
525 case llvm::DS_Error: \
526 DiagID = diag::err_fe_##GroupName; \
528 case llvm::DS_Warning: \
529 DiagID = diag::warn_fe_##GroupName; \
531 case llvm::DS_Remark: \
532 DiagID = diag::remark_fe_##GroupName; \
534 case llvm::DS_Note: \
535 DiagID = diag::note_fe_##GroupName; \
541 const llvm::SMDiagnostic &D = DI.getSMDiag();
544 if (DI.isInlineAsmDiag())
552 D.print(
nullptr, llvm::errs());
561 StringRef Message = D.getMessage();
562 (void)Message.consume_front(
"error: ");
566 if (D.getLoc() != SMLoc())
572 if (DI.isInlineAsmDiag()) {
578 if (D.getLoc().isValid()) {
582 for (
const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
583 unsigned Column = D.getColumnNo();
602 std::string Message = D.getMsgStr().str();
625 if (D.getSeverity() != llvm::DS_Warning)
634 Diags.
Report(*Loc, diag::warn_fe_frame_larger_than)
637 << llvm::demangle(D.getFunction().getName().str());
642 const llvm::DiagnosticInfoResourceLimit &D) {
646 unsigned DiagID = diag::err_fe_backend_resource_limit;
647 ComputeDiagID(D.getSeverity(), backend_resource_limit, DiagID);
649 Diags.
Report(*Loc, DiagID)
650 << D.getResourceName() << D.getResourceSize() << D.getResourceLimit()
651 << llvm::demangle(D.getFunction().getName().str());
656 const llvm::DiagnosticInfoWithLocationBase &D,
bool &BadDebugInfo,
657 StringRef &
Filename,
unsigned &Line,
unsigned &Column)
const {
662 if (D.isLocationAvailable()) {
663 D.getLocation(
Filename, Line, Column);
667 FE = FileMgr.
getFile(D.getAbsolutePath());
686 if (DILoc.
isInvalid() && D.isLocationAvailable())
691 Diags.
Report(Loc, diag::note_fe_backend_invalid_loc)
697std::optional<FullSourceLoc>
699 auto Hash = llvm::hash_value(F.getName());
700 for (
const auto &Pair : ManglingFullSourceLocs) {
701 if (Pair.first == Hash)
708 const llvm::DiagnosticInfoUnsupported &D) {
710 assert(D.getSeverity() == llvm::DS_Error ||
711 D.getSeverity() == llvm::DS_Warning);
714 unsigned Line, Column;
715 bool BadDebugInfo =
false;
718 raw_string_ostream MsgStream(Msg);
722 if (Context !=
nullptr) {
724 MsgStream << D.getMessage();
726 DiagnosticPrinterRawOStream DP(MsgStream);
730 auto DiagType = D.getSeverity() == llvm::DS_Error
731 ? diag::err_fe_backend_unsupported
732 : diag::warn_fe_backend_unsupported;
733 Diags.
Report(Loc, DiagType) << MsgStream.str();
740 Diags.
Report(Loc, diag::note_fe_backend_invalid_loc)
745 const llvm::DiagnosticInfoOptimizationBase &D,
unsigned DiagID) {
747 assert(D.getSeverity() == llvm::DS_Remark ||
748 D.getSeverity() == llvm::DS_Warning);
751 unsigned Line, Column;
752 bool BadDebugInfo =
false;
755 raw_string_ostream MsgStream(Msg);
759 if (Context !=
nullptr) {
761 MsgStream << D.getMsg();
763 DiagnosticPrinterRawOStream DP(MsgStream);
768 MsgStream <<
" (hotness: " << *D.getHotness() <<
")";
779 Diags.
Report(Loc, diag::note_fe_backend_invalid_loc)
784 const llvm::DiagnosticInfoOptimizationBase &D) {
786 if (D.isVerbose() && !D.getHotness())
794 }
else if (D.isMissed()) {
800 D, diag::remark_fe_backend_optimization_remark_missed);
802 assert(D.isAnalysis() &&
"Unknown remark type");
804 bool ShouldAlwaysPrint =
false;
805 if (
auto *ORA = dyn_cast<llvm::OptimizationRemarkAnalysis>(&D))
806 ShouldAlwaysPrint = ORA->shouldAlwaysPrint();
808 if (ShouldAlwaysPrint ||
811 D, diag::remark_fe_backend_optimization_remark_analysis);
816 const llvm::OptimizationRemarkAnalysisFPCommute &D) {
821 if (D.shouldAlwaysPrint() ||
824 D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
828 const llvm::OptimizationRemarkAnalysisAliasing &D) {
833 if (D.shouldAlwaysPrint() ||
836 D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
840 const llvm::DiagnosticInfoOptimizationFailure &D) {
853 Diags.
Report(LocCookie, D.getSeverity() == DiagnosticSeverity::DS_Error
854 ? diag::err_fe_backend_error_attr
855 : diag::warn_fe_backend_warning_attr)
856 << llvm::demangle(D.getFunctionName().str()) << D.getNote();
860 const llvm::DiagnosticInfoMisExpect &D) {
862 unsigned Line, Column;
863 bool BadDebugInfo =
false;
867 Diags.
Report(Loc, diag::warn_profile_data_misexpect) << D.getMsg().str();
874 Diags.
Report(Loc, diag::note_fe_backend_invalid_loc)
881 unsigned DiagID = diag::err_fe_inline_asm;
882 llvm::DiagnosticSeverity Severity = DI.getSeverity();
884 switch (DI.getKind()) {
885 case llvm::DK_InlineAsm:
890 case llvm::DK_SrcMgr:
893 case llvm::DK_StackSize:
898 case llvm::DK_ResourceLimit:
906 case llvm::DK_OptimizationRemark:
911 case llvm::DK_OptimizationRemarkMissed:
916 case llvm::DK_OptimizationRemarkAnalysis:
921 case llvm::DK_OptimizationRemarkAnalysisFPCommute:
926 case llvm::DK_OptimizationRemarkAnalysisAliasing:
931 case llvm::DK_MachineOptimizationRemark:
936 case llvm::DK_MachineOptimizationRemarkMissed:
941 case llvm::DK_MachineOptimizationRemarkAnalysis:
946 case llvm::DK_OptimizationFailure:
951 case llvm::DK_Unsupported:
954 case llvm::DK_DontCall:
957 case llvm::DK_MisExpect:
965 std::string MsgStorage;
967 raw_string_ostream Stream(MsgStorage);
968 DiagnosticPrinterRawOStream DP(Stream);
972 if (DI.getKind() == DK_Linker) {
973 assert(CurLinkModule &&
"CurLinkModule must be set for linker diagnostics");
974 Diags.
Report(DiagID) << CurLinkModule->getModuleIdentifier() << MsgStorage;
985 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
986 OwnsVMContext(!_VMContext) {}
1006 return std::move(TheModule);
1010 OwnsVMContext =
false;
1018static std::unique_ptr<raw_pwrite_stream>
1035 llvm_unreachable(
"Invalid action!");
1038std::unique_ptr<ASTConsumer>
1048 VMContext->setOpaquePointers(CI.
getCodeGenOpts().OpaquePointers);
1051 if (LinkModules.empty())
1057 << F.Filename << BCBuf.getError().message();
1058 LinkModules.clear();
1063 getOwningLazyBitcodeModule(std::move(*BCBuf), *VMContext);
1065 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
1066 CI.getDiagnostics().Report(diag::err_cannot_open_file)
1067 << F.Filename << EIB.message();
1069 LinkModules.clear();
1072 LinkModules.push_back({std::move(ModuleOrErr.get()), F.PropagateAttrs,
1073 F.Internalize, F.LinkFlags});
1086 std::move(LinkModules), std::move(OS), *VMContext, CoverageInfo));
1093 std::unique_ptr<PPCallbacks> Callbacks =
1099 return std::move(
Result);
1102std::unique_ptr<llvm::Module>
1103CodeGenAction::loadModule(MemoryBufferRef MBRef) {
1107 VMContext->setOpaquePointers(CI.
getCodeGenOpts().OpaquePointers);
1113 VMContext->enableDebugTypeODRUniquing();
1115 auto DiagErrors = [&](
Error E) -> std::unique_ptr<llvm::Module> {
1118 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1126 return DiagErrors(BMsOrErr.takeError());
1127 BitcodeModule *Bm = llvm::lto::findThinLTOModule(*BMsOrErr);
1133 auto M = std::make_unique<llvm::Module>(
"empty", *VMContext);
1138 Bm->parseModule(*VMContext);
1140 return DiagErrors(MOrErr.takeError());
1141 return std::move(*MOrErr);
1144 llvm::SMDiagnostic Err;
1145 if (std::unique_ptr<llvm::Module> M = parseIR(MBRef, Err, *VMContext))
1152 if (Err.getLineNo() > 0) {
1153 assert(Err.getColumnNo() >= 0);
1154 Loc =
SM.translateFileLineCol(
SM.getFileEntryForID(
SM.getMainFileID()),
1155 Err.getLineNo(), Err.getColumnNo() + 1);
1159 StringRef Msg = Err.getMessage();
1160 if (Msg.startswith(
"error: "))
1161 Msg = Msg.substr(7);
1181 std::unique_ptr<raw_pwrite_stream> OS =
1188 std::optional<MemoryBufferRef> MainFile =
SM.getBufferOrNone(FID);
1192 TheModule = loadModule(*MainFile);
1197 if (TheModule->getTargetTriple() != TargetOpts.
Triple) {
1198 Diagnostics.Report(
SourceLocation(), diag::warn_fe_override_module)
1200 TheModule->setTargetTriple(TargetOpts.
Triple);
1203 EmbedObject(TheModule.get(), CodeGenOpts, Diagnostics);
1206 LLVMContext &Ctx = TheModule->getContext();
1212 std::unique_ptr<DiagnosticHandler> PrevHandler = Ctx.getDiagnosticHandler();
1213 ~RAII() { Ctx.setDiagnosticHandler(std::move(PrevHandler)); }
1222 std::move(LinkModules), *VMContext,
nullptr);
1225 Ctx.setDiscardValueNames(
false);
1226 Ctx.setDiagnosticHandler(
1227 std::make_unique<ClangDiagnosticHandler>(CodeGenOpts, &
Result));
1230 setupLLVMOptimizationRemarks(
1231 Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,
1232 CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,
1233 CodeGenOpts.DiagnosticsHotnessThreshold);
1235 if (
Error E = OptRecordFileOrErr.takeError()) {
1239 std::unique_ptr<llvm::ToolOutputFile> OptRecordFile =
1240 std::move(*OptRecordFileOrErr);
1247 OptRecordFile->keep();
1252void EmitAssemblyAction::anchor() { }
1256void EmitBCAction::anchor() { }
1260void EmitLLVMAction::anchor() { }
1264void EmitLLVMOnlyAction::anchor() { }
1268void EmitCodeGenOnlyAction::anchor() { }
1272void EmitObjAction::anchor() { }
Defines the clang::ASTContext interface.
#define ComputeDiagID(Severity, GroupName, DiagID)
static std::unique_ptr< raw_pwrite_stream > GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action)
#define ComputeDiagRemarkID(Severity, GroupName, DiagID)
static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D, SourceManager &CSM)
ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr buffer to be a valid FullS...
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.
ASTConsumer - This is an abstract interface that should be implemented by clients that read ASTs.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
SourceManager & getSourceManager()
void ExecuteAction() override
Implement the ExecuteAction interface by running Sema on the already-initialized AST consumer.
llvm::Module * getModule() const
void OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationBase &D)
bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D)
Specialized handler for StackSize diagnostic.
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 OptimizationFailureHandler(const llvm::DiagnosticInfoOptimizationFailure &D)
void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI)
This function is invoked when the backend needs to report something to the user.
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.
BackendConsumer(BackendAction Action, DiagnosticsEngine &Diags, IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS, const HeaderSearchOptions &HeaderSearchOpts, const PreprocessorOptions &PPOpts, const CodeGenOptions &CodeGenOpts, const TargetOptions &TargetOpts, const LangOptions &LangOpts, llvm::Module *Module, SmallVector< LinkModule, 4 > LinkModules, LLVMContext &C, CoverageSourceInfo *CoverageInfo=nullptr)
void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override
HandleCXXStaticMemberVarInstantiation - Tell the consumer that this.
bool ResourceLimitDiagHandler(const llvm::DiagnosticInfoResourceLimit &D)
Specialized handler for ResourceLimit diagnostic.
std::unique_ptr< llvm::Module > takeModule()
void AssignInheritanceModel(CXXRecordDecl *RD) override
Callback invoked when an MSInheritanceAttr has been attached to a CXXRecordDecl.
std::optional< FullSourceLoc > getFunctionSourceLocation(const Function &F) const
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...
void CompleteExternalDeclaration(VarDecl *D) override
CompleteExternalDeclaration - Callback invoked at the end of a translation unit to notify the consume...
void UnsupportedDiagHandler(const llvm::DiagnosticInfoUnsupported &D)
Specialized handler for unsupported backend feature diagnostic.
bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D)
Specialized handler for InlineAsm diagnostic.
BackendConsumer(BackendAction Action, DiagnosticsEngine &Diags, IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS, const HeaderSearchOptions &HeaderSearchOpts, const PreprocessorOptions &PPOpts, const CodeGenOptions &CodeGenOpts, const TargetOptions &TargetOpts, const LangOptions &LangOpts, const std::string &InFile, SmallVector< LinkModule, 4 > LinkModules, std::unique_ptr< raw_pwrite_stream > OS, LLVMContext &C, CoverageSourceInfo *CoverageInfo=nullptr)
void DontCallDiagHandler(const DiagnosticInfoDontCall &D)
const FullSourceLoc getBestLocationFromDebugLoc(const llvm::DiagnosticInfoWithLocationBase &D, bool &BadDebugInfo, StringRef &Filename, unsigned &Line, unsigned &Column) const
Get the best possible source location to represent a diagnostic that may have associated debug info.
void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID)
Specialized handlers for optimization remarks.
void MisExpectDiagHandler(const llvm::DiagnosticInfoMisExpect &D)
Specialized handler for misexpect warnings.
CodeGenerator * getCodeGenerator()
void SrcMgrDiagHandler(const llvm::DiagnosticInfoSrcMgr &D)
Specialized handler for diagnostics reported using SMDiagnostic.
Represents a C++ struct/union/class.
bool isMissedOptRemarkEnabled(StringRef PassName) const override
bool handleDiagnostics(const DiagnosticInfo &DI) override
ClangDiagnosticHandler(const CodeGenOptions &CGOpts, BackendConsumer *BCon)
bool isPassedOptRemarkEnabled(StringRef PassName) const override
bool isAnyRemarkEnabled() const override
bool isAnalysisRemarkEnabled(StringRef PassName) const override
std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
Create the AST consumer object for this action, if supported.
CodeGenerator * getCodeGenerator() const
friend class BackendConsumer
void EndSourceFileAction() override
Callback at the end of processing a single input.
~CodeGenAction() override
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
Callback to run the program action, using the initialized compiler instance.
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.
std::vector< BitcodeFileToLink > LinkBitcodeFiles
The files specified here are linked in to the module before optimizations.
std::string OptRecordPasses
The regex that filters the passes that should be saved to the optimization records.
OptRemark OptimizationRemark
Selected optimizations for which we should enable optimization remarks.
std::string ThinLTOIndexFile
Name of the function summary index file to use for ThinLTO function importing.
OptRemark OptimizationRemarkAnalysis
Selected optimizations for which we should enable optimization analyses.
std::string OptRecordFormat
The format used for serializing remarks (default: YAML)
OptRemark OptimizationRemarkMissed
Selected optimizations for which we should enable missed optimization remarks.
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.
DiagnosticsEngine & getDiagnostics() const
Get the current diagnostics engine.
std::unique_ptr< raw_pwrite_stream > createDefaultOutputFile(bool Binary=true, StringRef BaseInput="", StringRef Extension="", bool RemoveFileOnSignal=true, bool CreateMissingDirectories=false, bool ForceUseTemporary=false)
Create the default output file (from the invocation's options) and add it to the list of tracked outp...
FileManager & getFileManager() const
Return the current file manager to the caller.
Preprocessor & getPreprocessor() const
Return the current preprocessor.
TargetOptions & getTargetOpts()
std::unique_ptr< llvm::raw_pwrite_stream > takeOutputStream()
HeaderSearchOptions & getHeaderSearchOpts()
PreprocessorOptions & getPreprocessorOpts()
TargetInfo & getTarget() const
llvm::vfs::FileSystem & getVirtualFileSystem() const
LangOptions & getLangOpts()
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...
Decl - This represents one declaration (or definition), e.g.
A little helper class used to produce diagnostics.
Concrete class used by the front-end to report problems and issues.
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.
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...
Implements support for file system lookup, file system caching, and directory search management.
llvm::ErrorOr< std::unique_ptr< llvm::MemoryBuffer > > getBufferForFile(const FileEntry *Entry, bool isVolatile=false, bool RequiresNullTerminator=true)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > getVirtualFileSystemPtr() const
llvm::ErrorOr< const FileEntry * > getFile(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Lookup, cache, and verify the specified file (real or virtual).
InputKind getCurrentFileKind() const
CompilerInstance & getCompilerInstance() const
StringRef getCurrentFileOrBufferName() const
A SourceLocation and its associated SourceManager.
Represents a function declaration or definition.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Describes a module or submodule.
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
void addPPCallbacks(std::unique_ptr< PPCallbacks > C)
PrettyStackTraceDecl - If a crash occurs, indicate that it happened when doing something to a specifi...
Encodes a location in the source.
static SourceLocation getFromRawEncoding(UIntTy Encoding)
Turn a raw encoding of a SourceLocation object into a real SourceLocation.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
This class handles loading and caching of source files into memory.
FileManager & getFileManager() const
FileID createFileID(const FileEntry *SourceFile, SourceLocation IncludePos, SrcMgr::CharacteristicKind FileCharacter, int LoadedID=0, SourceLocation::UIntTy LoadedOffset=0)
Create a new FileID that represents the specified file being #included from the specified IncludePosi...
SourceLocation translateFileLineCol(const FileEntry *SourceFile, unsigned Line, unsigned Col) const
Get the source location for the given file:line:col triplet.
SourceLocation getLocForStartOfFile(FileID FID) const
Return the source location corresponding to the first byte of the specified file.
A trivial tuple used to represent a source range.
void AddString(StringRef V) const
Represents the declaration of a struct/union/class/enum.
const char * getDataLayoutString() const
Options for controlling the target.
std::string Triple
The name of the target triple to compile for.
Represents a variable declaration or definition.
Defines the clang::TargetInfo interface.
@ NoDebugInfo
Don't generate debug info.
static void reportOptRecordError(Error E, DiagnosticsEngine &Diags, const CodeGenOptions CodeGenOpts)
void EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts, DiagnosticsEngine &Diags)
CodeGenerator * CreateLLVMCodeGen(DiagnosticsEngine &Diags, llvm::StringRef ModuleName, IntrusiveRefCntPtr< llvm::vfs::FileSystem > FS, const HeaderSearchOptions &HeaderSearchOpts, const PreprocessorOptions &PreprocessorOpts, const CodeGenOptions &CGO, llvm::LLVMContext &C, CoverageSourceInfo *CoverageInfo=nullptr)
CreateLLVMCodeGen - Create a CodeGenerator instance.
@ C
Languages that the frontend can parse and compile.
@ LLVM_IR
LLVM IR: we accept this so that we can run the optimizer on it, and compile it to assembly or object ...
@ Result
The result type of a method or function.
void EmitBackendOutput(DiagnosticsEngine &Diags, const HeaderSearchOptions &, const CodeGenOptions &CGOpts, const TargetOptions &TOpts, const LangOptions &LOpts, StringRef TDesc, llvm::Module *M, BackendAction Action, llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS, std::unique_ptr< raw_pwrite_stream > OS)
void EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts, llvm::MemoryBufferRef Buf)
@ Backend_EmitAssembly
Emit native assembly files.
@ Backend_EmitLL
Emit human-readable LLVM assembly.
@ Backend_EmitBC
Emit LLVM bitcode files.
@ Backend_EmitObj
Emit native object files.
@ Backend_EmitMCNull
Run CodeGen, but don't emit anything.
@ Backend_EmitNothing
Don't emit anything (benchmarking mode)
YAML serialization mapping.